Call it like this:
foo(*ob);
Note that there is no casting going on here, as suggested in your question title. All we have done is de-referenced the pointer to the object which we then pass to the function.
To avoid confusion (as there seems to be some in the comments). Assuming you are on Jupyter:
%matplotlib inline
> displays the plots INSIDE the notebook
sns.plt.show()
> displays the plots OUTSIDE of the notebook
%matplotlib inline
will OVERRIDE sns.plt.show()
in the sense that plots will be shown IN the notebook even when sns.plt.show()
is called.
And yes, it is easy to include the line in to your config:
Automatically run %matplotlib inline in IPython Notebook
But it seems a better convention to keep it together with imports in the actual code.
BLOB is for binary data (videos, images, documents, other)
CLOB is for large text data (text)
Maximum size on MySQL 2GB
Maximum size on Oracle 128TB
let str = "abcdef"
str[1 ..< 3] // returns "bc"
str[5] // returns "f"
str[80] // returns ""
str.substring(fromIndex: 3) // returns "def"
str.substring(toIndex: str.length - 2) // returns "abcd"
You will need to add this String extension to your project (it's fully tested):
extension String {
var length: Int {
return count
}
subscript (i: Int) -> String {
return self[i ..< i + 1]
}
func substring(fromIndex: Int) -> String {
return self[min(fromIndex, length) ..< length]
}
func substring(toIndex: Int) -> String {
return self[0 ..< max(0, toIndex)]
}
subscript (r: Range<Int>) -> String {
let range = Range(uncheckedBounds: (lower: max(0, min(length, r.lowerBound)),
upper: min(length, max(0, r.upperBound))))
let start = index(startIndex, offsetBy: range.lowerBound)
let end = index(start, offsetBy: range.upperBound - range.lowerBound)
return String(self[start ..< end])
}
}
Even though Swift always had out of the box solution to this problem (without String extension, which I provided below), I still would strongly recommend using the extension. Why? Because it saved me tens of hours of painful migration from early versions of Swift, where String's syntax was changing almost every release, but all I needed to do was to update the extension's implementation as opposed to refactoring the entire project. Make your choice.
let str = "Hello, world!"
let index = str.index(str.startIndex, offsetBy: 4)
str[index] // returns Character 'o'
let endIndex = str.index(str.endIndex, offsetBy:-2)
str[index ..< endIndex] // returns String "o, worl"
String(str.suffix(from: index)) // returns String "o, world!"
String(str.prefix(upTo: index)) // returns String "Hell"
Assuming MySQL (EDIT: posted before the SQL variant was supplied):
ALTER TABLE myTable ADD myNewColumn VARCHAR(255) AFTER myOtherColumn
The AFTER keyword tells MySQL where to place the new column. You can also use FIRST to flag the new column as the first column in the table.
Modify the definition of the function check_me as::
function check_me(ev) {
Now you can access the methods and parameters of the event, in your case:
ev.preventDefault();
Then, you have to pass the parameter on the onclick in the inline call::
<button type="button" onclick="check_me(event);">Click Me!</button>
A useful link to understand this.
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
function check_me(ev) {
ev.preventDefault();
alert("Hello World!")
}
</script>
</head>
<body>
<button type="button" onclick="check_me(event);">Click Me!</button>
</body>
</html>
Although the above is the direct answer to the question (passing an event object to an inline event), there are other ways of handling events that keep the logic separated from the presentation
addEventListener
:<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<button id='my_button' type="button">Click Me!</button>
<!-- put the javascript at the end to guarantee that the DOM is ready to use-->
<script type="text/javascript">
function check_me(ev) {
ev.preventDefault();
alert("Hello World!")
}
<!-- add the event to the button identified #my_button -->
document.getElementById("my_button").addEventListener("click", check_me);
</script>
</body>
</html>
Both of the above solutions are fine for a small project, or a hackish quick and dirty solution, but for bigger projects, it is better to keep the HTML separated from the Javascript.
Just put this two files in the same folder:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<button id='my_button' type="button">Click Me!</button>
<!-- put the javascript at the end to guarantee that the DOM is ready to use-->
<script type="text/javascript" src="example.js"></script>
</body>
</html>
function check_me(ev) {
ev.preventDefault();
alert("Hello World!")
}
document.getElementById("my_button").addEventListener("click", check_me);
Another way to do this is to use the Ruby on Rails debugger. There's a Ruby on Rails guide about debugging at http://guides.rubyonrails.org/debugging_rails_applications.html
Basically, start the server with the -u option:
./script/server -u
And then insert a breakpoint into your script where you would like to have access to the controllers, helpers, etc.
class EventsController < ApplicationController
def index
debugger
end
end
And when you make a request and hit that part in the code, the server console will return a prompt where you can then make requests, view objects, etc. from a command prompt. When finished, just type 'cont' to continue execution. There are also options for extended debugging, but this should at least get you started.
I hope your problem is with path & php binary as well. If you have fixed the path as per older answers, please use php-cli instead of php command while running cron job.
It may be possible php_sapi_name()
is not returning cli
. Its returning something else like cgi-fcgi
etc.
/usr/bin/php-cli -q /home/username/public_html/cron/cron.php >/dev/null
I hope it will help.
You have to set LANG as well, look for files named 'sp1*.msb', and set for instance export LANG=us if you find a file name sp1us.msb. The error message could sure be better :)
In some contexts, you can leverage margin settings to effectively specify "100% width minus N pixels". See the accepted answer to this question.
Although the question is tagged Unix, people also get to visit it when their target platform is Windows, and the answer for Windows is the GetCurrentDirectory()
function:
DWORD WINAPI GetCurrentDirectory(
_In_ DWORD nBufferLength,
_Out_ LPTSTR lpBuffer
);
These answers apply to both C and C++ code.
Link suggested by user4581301 in a comment to another question, and verified as the current top choice with a Google search 'site:microsoft.com getcurrentdirectory'.
Dim x as date
x = dr("appdate")
appdate = x.tostring("dd/MM/yyyy")
dr is the variable of datareader
angualr uses the lighter version of jquery called as jqlite which means it doesnt have all the features of jQuery. here is a reference in angularjs docs about what you can use from jquery. Angular Element docs
In your case you need to find a div with ID or class name. for class name you can use
var elems =$element.find('div') //returns all the div's in the $elements
angular.forEach(elems,function(v,k)){
if(angular.element(v).hasClass('class-name')){
console.log(angular.element(v));
}}
or you can use much simpler way by query selector
angular.element(document.querySelector('#id'))
angular.element(elem.querySelector('.classname'))
it is not as flexible as jQuery but what
You could take a look at date-and-time api for easily date manipulation.
let now = date.format(new Date(), 'YYYY-MM-DD HH:mm:ss', true);_x000D_
console.log(now);
_x000D_
<script src="https://cdn.jsdelivr.net/npm/date-and-time/date-and-time.min.js"></script>
_x000D_
I have approximately these problem. I need debug AngularJs application from Visual Studio 2013.
By default IIS Express restricted access to local files (like json).
But, first: JSON have JavaScript syntax.
Second: javascript files is allowed.
So:
rename JSON to JS (data.json->data.js
).
correct load command ($http.get('App/data.js').success(function (data) {...
load script data.js to page (<script src="App/data.js"></script>
)
Next use loaded data an usual manner. It is just workaround, of course.
You are binding properties to nothing. :required
in
<select class="form-control" v-model="selected" :required @change="changeLocation">
and :selected
in
<option :selected>Choose Province</option>
If you set the code like so, your errors should be gone:
<template>
<select class="form-control" v-model="selected" :required @change="changeLocation">
<option>Choose Province</option>
<option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>
</select>
</template>
you would now need to have a data
property called selected
so that v-model works. So,
{
data () {
return {
selected: "Choose Province"
}
}
}
If that seems like too much work, you can also do it like:
<template>
<select class="form-control" :required="true" @change="changeLocation">
<option :selected="true">Choose Province</option>
<option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>
</select>
</template>
You can use the v-model
approach if your default value depends on some data property.
You can go for the second method if your default selected value happens to be the first option
.
You can also handle it programmatically by doing so:
<select class="form-control" :required="true">
<option
v-for="option in options"
v-bind:value="option.id"
:selected="option == '<the default value you want>'"
>{{ option }}</option>
</select>
jdk.tools:jdk.tools
(or com.sun:tools
, or whatever you name it) is a JAR file that is distributed with JDK. Usually you add it to maven projects like this:
<dependency>
<groupId>jdk.tools</groupId>
<artifactId>jdk.tools</artifactId>
<scope>system</scope>
<systemPath>${java.home}/../lib/tools.jar</systemPath>
</dependency>
See, the Maven FAQ for adding dependencies to tools.jar
Or, you can manually install tools.jar
in the local repository using:
mvn install:install-file -DgroupId=jdk.tools -DartifactId=jdk.tools -Dpackaging=jar -Dversion=1.6 -Dfile=tools.jar -DgeneratePom=true
and then reference it like Cloudera did, using:
<dependency>
<groupId>jdk.tools</groupId>
<artifactId>jdk.tools</artifactId>
<version>1.6</version>
</dependency>
You could also expose the directive's controller to the parent scope, like ngForm
with name
attribute does: http://docs.angularjs.org/api/ng.directive:ngForm
Here you could find a very basic example how it could be achieved http://plnkr.co/edit/Ps8OXrfpnePFvvdFgYJf?p=preview
In this example I have myDirective
with dedicated controller with $clear
method (sort of very simple public API for the directive). I can publish this controller to the parent scope and use call this method outside the directive.
Here's a simplest example from ASP.NET Community, this gave me a clear understanding on the concept....
what difference does this make?
For an example of this, here is a way to put focus on a text box on a page when the page is loaded into the browser—with Visual Basic using the RegisterStartupScript
method:
Page.ClientScript.RegisterStartupScript(Me.GetType(), "Testing", _
"document.forms[0]['TextBox1'].focus();", True)
This works well because the textbox on the page is generated and placed on the page by the time the browser gets down to the bottom of the page and gets to this little bit of JavaScript.
But, if instead it was written like this (using the RegisterClientScriptBlock
method):
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "Testing", _
"document.forms[0]['TextBox1'].focus();", True)
Focus will not get to the textbox control and a JavaScript error will be generated on the page
The reason for this is that the browser will encounter the JavaScript before the text box is on the page. Therefore, the JavaScript will not be able to find a TextBox1.
This is the answer that was required but everybody answered only part one of many.
UTF-8
documentadvanced editors don't make it simple for you... go low level...
use notepad to save the document as meName.html & change the encoding
type to UTF-8
Step 2 - Mention in your html page that you are going to use such characters by
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
Step 3 - When you put in some characters make sure your container tags have the following 2 properties set
dir='rtl'
lang='ar'
example
<p dir="rtl" lang="ar" style="color:#e0e0e0;font-size:20px;">????? ??????? ??????</p>
NOTE: font type, font family, font face setting will have no effect on special characters
I have a buch of 0-tabIndexes, which I wanted to navigate by keyboard.
Since in that case, only the ORDER of the elements mattered, I did it using document.createTreeWalker
So first you create the filter (you only want [visible] elements, which have an attribute "tabIndex" with a NUMERICAL value.
Then you set the root node, beyond which you don't want to search.
In my case, this.m_tree
is a ul-element containing a toggable tree.
If you want the entire document instead, just replace this.m_tree
with document.documentElement
.
Then you set the current node to the current active element:
ni.currentNode = el; // el = document.activeElement
Then you return ni.nextNode()
or ni.previousNode()
.
Note:
this will NOT return the tabs in the correct order if you have tabIndices != 0 and the element order is NOT the tabIndex order. In case of tabIndex = 0, the tabOrder is always the element order, which is why this works (in that case).
protected createFilter(fn?: (node: Node) => number): NodeFilter
{
// Accept all currently filtered elements.
function acceptNode(node: Node): number
{
return NodeFilter.FILTER_ACCEPT;
}
if (fn == null)
fn = acceptNode;
// Work around Internet Explorer wanting a function instead of an object.
// IE also *requires* this argument where other browsers don't.
const safeFilter: NodeFilter = <NodeFilter><any>fn;
(<any>safeFilter).acceptNode = fn;
return safeFilter;
}
protected createTabbingFilter(): NodeFilter
{
// Accept all currently filtered elements.
function acceptNode(node: Node): number
{
if (!node)
return NodeFilter.FILTER_REJECT;
if (node.nodeType !== Node.ELEMENT_NODE)
return NodeFilter.FILTER_REJECT;
if (window.getComputedStyle(<Element>node).display === "none")
return NodeFilter.FILTER_REJECT;
// "tabIndex": "0"
if (!(<Element>node).hasAttribute("tabIndex"))
return NodeFilter.FILTER_SKIP;
let tabIndex = parseInt((<Element>node).getAttribute("tabIndex"), 10);
if (!tabIndex || isNaN(tabIndex) || !isFinite(tabIndex))
return NodeFilter.FILTER_SKIP;
// if ((<Element>node).tagName !== "LI") return NodeFilter.FILTER_SKIP;
return NodeFilter.FILTER_ACCEPT;
}
return this.createFilter(acceptNode);
}
protected getNextTab(el: HTMLElement): HTMLElement
{
let currentNode: Node;
// https://developer.mozilla.org/en-US/docs/Web/API/Document/createNodeIterator
// https://developer.mozilla.org/en-US/docs/Web/API/Document/createTreeWalker
// let ni = document.createNodeIterator(el, NodeFilter.SHOW_ELEMENT);
// let ni = document.createTreeWalker(this.m_tree, NodeFilter.SHOW_ELEMENT);
let ni = document.createTreeWalker(this.m_tree, NodeFilter.SHOW_ELEMENT, this.createTabbingFilter(), false);
ni.currentNode = el;
while (currentNode = ni.nextNode())
{
return <HTMLElement>currentNode;
}
return el;
}
protected getPreviousTab(el: HTMLElement): HTMLElement
{
let currentNode: Node;
let ni = document.createTreeWalker(this.m_tree, NodeFilter.SHOW_ELEMENT, this.createTabbingFilter(), false);
ni.currentNode = el;
while (currentNode = ni.previousNode())
{
return <HTMLElement>currentNode;
}
return el;
}
Note that the while-loop
while (currentNode = ni.nextNode())
{
// Additional checks here
// if(condition) return currentNode;
// else the loop continues;
return <HTMLElement>currentNode; // everything is already filtered down to what we need here
}
is only there if you want if you have additional criterias which you cannot filter in the filter passed to createTreeWalker.
Note this is TypeScript, you need to remove all tokens behind colons (:), and between angle-brackets (<>), e.g. <Element>
or :(node: Node) => number
to get valid JavaScript.
Here as a service, the transpiled JS:
"use strict";
function createFilter(fn) {
// Accept all currently filtered elements.
function acceptNode(node) {
return NodeFilter.FILTER_ACCEPT;
}
if (fn == null)
fn = acceptNode;
// Work around Internet Explorer wanting a function instead of an object.
// IE also *requires* this argument where other browsers don't.
const safeFilter = fn;
safeFilter.acceptNode = fn;
return safeFilter;
}
function createTabbingFilter() {
// Accept all currently filtered elements.
function acceptNode(node) {
if (!node)
return NodeFilter.FILTER_REJECT;
if (node.nodeType !== Node.ELEMENT_NODE)
return NodeFilter.FILTER_REJECT;
if (window.getComputedStyle(node).display === "none")
return NodeFilter.FILTER_REJECT;
// "tabIndex": "0"
if (!node.hasAttribute("tabIndex"))
return NodeFilter.FILTER_SKIP;
let tabIndex = parseInt(node.getAttribute("tabIndex"), 10);
if (!tabIndex || isNaN(tabIndex) || !isFinite(tabIndex))
return NodeFilter.FILTER_SKIP;
// if ((<Element>node).tagName !== "LI") return NodeFilter.FILTER_SKIP;
return NodeFilter.FILTER_ACCEPT;
}
return createFilter(acceptNode);
}
function getNextTab(el) {
let currentNode;
// https://developer.mozilla.org/en-US/docs/Web/API/Document/createNodeIterator
// https://developer.mozilla.org/en-US/docs/Web/API/Document/createTreeWalker
// let ni = document.createNodeIterator(el, NodeFilter.SHOW_ELEMENT);
// let ni = document.createTreeWalker(this.m_tree, NodeFilter.SHOW_ELEMENT);
let ni = document.createTreeWalker(document.documentElement, NodeFilter.SHOW_ELEMENT, createTabbingFilter(), false);
ni.currentNode = el;
while (currentNode = ni.nextNode()) {
return currentNode;
}
return el;
}
function getPreviousTab(el) {
let currentNode;
let ni = document.createTreeWalker(document.documentElement, NodeFilter.SHOW_ELEMENT, createTabbingFilter(), false);
ni.currentNode = el;
while (currentNode = ni.previousNode()) {
return currentNode;
}
return el;
}
WIth the Help of @excray's comment, I manage to figure it out the answer, What we need to do is actually write a simple for loop to iterate over the two arrays that represent the train data and test data.
First implement a simple lambda function to hold formula for the cosine calculation:
cosine_function = lambda a, b : round(np.inner(a, b)/(LA.norm(a)*LA.norm(b)), 3)
And then just write a simple for loop to iterate over the to vector, logic is for every "For each vector in trainVectorizerArray, you have to find the cosine similarity with the vector in testVectorizerArray."
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from nltk.corpus import stopwords
import numpy as np
import numpy.linalg as LA
train_set = ["The sky is blue.", "The sun is bright."] #Documents
test_set = ["The sun in the sky is bright."] #Query
stopWords = stopwords.words('english')
vectorizer = CountVectorizer(stop_words = stopWords)
#print vectorizer
transformer = TfidfTransformer()
#print transformer
trainVectorizerArray = vectorizer.fit_transform(train_set).toarray()
testVectorizerArray = vectorizer.transform(test_set).toarray()
print 'Fit Vectorizer to train set', trainVectorizerArray
print 'Transform Vectorizer to test set', testVectorizerArray
cx = lambda a, b : round(np.inner(a, b)/(LA.norm(a)*LA.norm(b)), 3)
for vector in trainVectorizerArray:
print vector
for testV in testVectorizerArray:
print testV
cosine = cx(vector, testV)
print cosine
transformer.fit(trainVectorizerArray)
print
print transformer.transform(trainVectorizerArray).toarray()
transformer.fit(testVectorizerArray)
print
tfidf = transformer.transform(testVectorizerArray)
print tfidf.todense()
Here is the output:
Fit Vectorizer to train set [[1 0 1 0]
[0 1 0 1]]
Transform Vectorizer to test set [[0 1 1 1]]
[1 0 1 0]
[0 1 1 1]
0.408
[0 1 0 1]
[0 1 1 1]
0.816
[[ 0.70710678 0. 0.70710678 0. ]
[ 0. 0.70710678 0. 0.70710678]]
[[ 0. 0.57735027 0.57735027 0.57735027]]
Use grep
$ grep --help | grep -i context
Context control:
-B, --before-context=NUM print NUM lines of leading context
-A, --after-context=NUM print NUM lines of trailing context
-C, --context=NUM print NUM lines of output context
-NUM same as --context=NUM
The jQuery way to click a link is
$('#LinkID').click();
For mailTo link, you have to write the following code
$('#LinkID')[0].click();
Try this CSS code for cross-browser compatibility.
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
user-select: none;
http://en.wikibooks.org/wiki/LaTeX/Formatting
use \alltt
environment instead. Then set size using the same commands as outside verbatim environment.
Be sure to check out verilog-mode and especially verilog-auto. http://www.veripool.org/wiki/verilog-mode/ It is a verilog mode for emacs, but plugins exist for vi(m?) for example.
An instantiation can be automated with AUTOINST. The comment is expanded with M-x verilog-auto
and can afterwards be manually edited.
subcomponent subcomponent_instance_name(/*AUTOINST*/);
Expanded
subcomponent subcomponent_instance_name (/*AUTOINST*/
//Inputs
.clk, (clk)
.rst_n, (rst_n)
.data_rx (data_rx_1[9:0]),
//Outputs
.data_tx (data_tx[9:0])
);
Implicit wires can be automated with /*AUTOWIRE*/
. Check the link for further information.
I had the same problem, and just found a handling not mentioned here. Though I'd contribute to the community:
npm install -g myapp
was not copying the bin
directory. I found this to be because I did not include it in the files
in my package.json
"files": [
"lib",
"bin" // this was missing
]
To grant a permission:
grant select on schema_name.sequence_name to user_or_role_name;
To check which permissions have been granted
select * from all_tab_privs where TABLE_NAME = 'sequence_name'
Both solutions below use javascript (I had no idea the solution was language agnostic!). Both solutions will need to be extended if capturing durations > 1 month
.
var date = new Date(536643021);
var str = '';
str += date.getUTCDate()-1 + " days, ";
str += date.getUTCHours() + " hours, ";
str += date.getUTCMinutes() + " minutes, ";
str += date.getUTCSeconds() + " seconds, ";
str += date.getUTCMilliseconds() + " millis";
console.log(str);
Gives:
"6 days, 5 hours, 4 minutes, 3 seconds, 21 millis"
Libraries are helpful, but why use a library when you can re-invent the wheel! :)
var getDuration = function(millis){
var dur = {};
var units = [
{label:"millis", mod:1000},
{label:"seconds", mod:60},
{label:"minutes", mod:60},
{label:"hours", mod:24},
{label:"days", mod:31}
];
// calculate the individual unit values...
units.forEach(function(u){
millis = (millis - (dur[u.label] = (millis % u.mod))) / u.mod;
});
// convert object to a string representation...
var nonZero = function(u){ return dur[u.label]; };
dur.toString = function(){
return units
.reverse()
.filter(nonZero)
.map(function(u){
return dur[u.label] + " " + (dur[u.label]==1?u.label.slice(0,-1):u.label);
})
.join(', ');
};
return dur;
};
Creates a "duration" object, with whatever fields you require. Formatting a timestamp then becomes simple...
console.log(getDuration(536643021).toString());
Gives:
"6 days, 5 hours, 4 minutes, 3 seconds, 21 millis"
Use a semaphore with a count that is equal to the number of readers. Let each reader take one count of the semaphore in order to read, that way they can all read at the same time. Then let the writer take ALL the semaphore counts prior to writing. This causes the writer to wait for all reads to finish and then block out reads while writing.
This can not be done purely with css. This is a behaviour, which affects the styling of the page.
With jquery you can quickly implement the behavior from your question:
$(function() {
$('#a').hover(function() {
$('#b').css('background-color', 'yellow');
}, function() {
// on mouseout, reset the background colour
$('#b').css('background-color', '');
});
});
The other answers were incorrect, at least in my case. request.path
does not provide the full url, only the relative url, e.g. /paper/53
. I did not find any proper solution, so I ended up hardcoding the constant part of the url in the View before concatenating it with request.path
.
Now, You can use below code (by google)
<div class="g-recaptcha" data-sitekey="<yours>" data-size="compact"></div>
I had this error as well. I triple checked that names were correct.
However I got this error simply because I was not terminating the script tag.
<template>
<div>
<p>My Form</p>
<PageA></PageA>
</div>
</template>
<script>
import PageA from "./PageA.vue"
export default {
name: "MyForm",
components: {
PageA
}
}
Notice there is no </script> at the end.
So be sure to double check this.
for unhashable lists. It is faster as it does not iterate about already checked entries.
def purge_dublicates(X):
unique_X = []
for i, row in enumerate(X):
if row not in X[i + 1:]:
unique_X.append(row)
return unique_X
This is an reality example when customize folder structure:
Folder structure, and initialize class HibernateUtil
with:
return new Configuration().configure("/config/hibernate.cfg.xml").buildSessionFactory();
with customize entities mapping files:
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping class="com.vy.entities.Users"/>
<mapping class="com.vy.entities.Post"/>
<mapping resource="config/Users.hbm.xml"/>
<mapping resource="config/Post.hbm.xml"/>
</session-factory>
</hibernate-configuration>
(Note: Simplest way, if you follow default way, it means put all xml config files inside src
folder, when build sessionFactory, only:
return new Configuration().configure().buildSessionFactory();
)
Use this method and pass your array in parameter
Collections.shuffle(arrayList);
This method return void so it will not give you a new list but as we know that array is passed as a reference type in Java so it will shuffle your array and save shuffled values in it. That's why you don't need any return type.
You can now use arraylist which is shuffled.
Ctrl + Alt + Shift + N allows you to search for symbols, including methods.
The primary advantage of this more complicated keybinding is that is searches in all files, not just the current file as Ctrl + F12 does.
(And as always, for Mac you substitute Cmd for Ctrl for these keybindings.)
Based off of @Mike Sherrill Cat Recall's answer, this is what worked for me:
ALTER TABLE "Children"
DROP CONSTRAINT "Children_parentId_fkey",
ADD CONSTRAINT "Children_parentId_fkey"
FOREIGN KEY ("parentId")
REFERENCES "Parent"(id)
ON DELETE CASCADE;
As answered by Magus :
the full path must me specified
Abstract states can be used to add a prefix to all child state urls. But note that abstract still needs a ui-view for its children to populate. To do so you can simply add it inline.
.state('app', {
url: "/app",
abstract: true,
template: '<ui-view/>'
})
For more information see documentation : https://github.com/angular-ui/ui-router/wiki/Nested-States-%26-Nested-Views
You're looking for keydown/press/up
$("#inputID").keydown(function(event) {
alert(event.keyCode);
});
or using bind $("#inputID").bind('onkeydown', ...
I may guess, the old instance of your program is still running. Windows does not allow to change the files which are currently "in use" and your linker cannot write the new .exe on the top of the running one. Try stopping/killing your program.
Have you seen this Coding Horror blog entry?
The Sad Tragedy of Micro-Optimization Theater
I am not shure whether or not it is "neater", but from a performance-standpoint it probably won't matter much.
Old question but I have a much better way of doing this. Rather than using rect()
use polygon
. This allows you to keep everything in plot
without using points
. Also you don't have to mess with par
at all. If you want to keep things automated make the coordinates of polygon
a function of your data.
plot.new()
polygon(c(-min(df[,1])^2,-min(df[,1])^2,max(df[,1])^2,max(df[,1])^2),c(-min(df[,2])^2,max(df[,2])^2,max(df[,2])^2,-min(df[,2])^2), col="grey")
par(new=T)
plot(df)
The browser is complaining because you're using JavaScript to close a window that wasn't opened with JavaScript, i.e. window.open('foo.html');
.
You could use this pretty simple solution:
Array.from(document.querySelectorAll('div'))
.find(el => el.textContent === 'SomeText, text continues.');
The Array.from
will convert the NodeList to an array (there are multiple methods to do this like the spread operator or slice)
The result now being an array allows for using the Array.find
method, you can then put in any predicate. You could also check the textContent with a regex or whatever you like.
Note that Array.from
and Array.find
are ES2015 features. Te be compatible with older browsers like IE10 without a transpiler:
Array.prototype.slice.call(document.querySelectorAll('div'))
.filter(function (el) {
return el.textContent === 'SomeText, text continues.'
})[0];
Just to add Python 3 f-string solution
prob = 1.0/3.0
print(f"{prob:.0%}")
I found that mounting a local volume over /tmp can cause permission issues when the "apt-get update" runs, which prevents the package cache from being populated. Hopefully, this isn't something most people do, but it's something else to look for if you see this issue.
Basically unmanaged code is code which does not run under the .NET CLR (aka not VB.NET, C#, etc.). My guess is that NUnit has a runner/wrapper which is not .NET code (aka C++).
SELECT REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(19), CONVERT(DATETIME, getdate(), 112), 126), '-', ''), 'T', ''), ':', '')
On Python 3.4, the pathlib
module was added, and the following code will reliably open a file in the same directory as the current script:
from pathlib import Path
p = Path(__file__).with_name('file.txt')
with p.open('r') as f:
print(f.read())
You can also use parent.absolute()
to get directory value as a string if needed:
p = Path(__file__)
dir_abs = p.parent.absolute() # Will return the executable directory absolute path
Did you maybe use some <tab>
instead of spaces?
Try remove all the spaces before the code and readd them using <space>
characters, just to be sure it's not a <tab>
.
check your branch on your repo. maybe someone delete it.
Another way to do this
while true; do (echo -e 'HTTP/1.1 200 OK\r\n'; echo -e "\n\tMy website has date function" ; echo -e "\t$(date)\n") | nc -lp 8080; done
Let's test it with 2 HTTP request using curl
In this example, 172.16.2.6 is the server IP Address.
Server Side
admin@server:~$ while true; do (echo -e 'HTTP/1.1 200 OK\r\n'; echo -e "\n\tMy website has date function" ; echo -e "\t$(date)\n") | nc -lp 8080; done
GET / HTTP/1.1 Host: 172.16.2.6:8080 User-Agent: curl/7.48.0 Accept:
*/*
GET / HTTP/1.1 Host: 172.16.2.6:8080 User-Agent: curl/7.48.0 Accept:
*/*
Client Side
user@client:~$ curl 172.16.2.6:8080
My website has date function
Tue Jun 13 18:00:19 UTC 2017
user@client:~$ curl 172.16.2.6:8080
My website has date function
Tue Jun 13 18:00:24 UTC 2017
user@client:~$
If you want to execute another command, feel free to replace $(date).
If you know the viewport angle of the camera, you can use the height in pixels to determine the angle from the top to bottom of the object. Then, using the distance and arctangent calculate the height:
height = arctan(angle) * distance
To find the viewport angle, point the camera at something which is of known height, and make it exactly fill the screen. For example, point it at a ruler, and make it just far enough away that you can only barely see the ends of the ruler. Measure the distance from the camera, and then your total viewport angle is
viewportAngle = tan(ruler_length / distance)
Then, suppose your camera is 480px tall (cheap webcam), and the view angle is 20°. If you have an object onscreen which is 240px tall, then its angle is 10°. If you know it's 2 feet away, you would say 2 feet * arctan(10°) = ~4.1 inches
tall. (I think... it's 2am so this may be a little off)
If I remember correctly (from a couple of years ago), one of the senior developers was talking about a fast way to bzero() on PowerPC (specs said we needed to zero almost all the memory on power up). It might not translate well (if at all) to x86, but it could be worth exploring.
The idea was to load a data cache line, clear that data cache line, and then write the cleared data cache line back to memory.
For what it is worth, I hope it helps.
I found that when my fragment was defined in the navigation graph with a <fragment>
tag (for a full screen dialogfragment), the dialogfragment would not dismiss with the dismiss()
command. Instead, I had to pop the back stack:
findNavController(getActivity(), R.id.nav_host_fragment).popBackStack();
However, if the same dialogfragment was defined in the navigation graph with a <dialog>
tag, dismiss()
works fine.
When floating elements exist on the page, non-floating elements wrap around the floating elements, similar to how text goes around a picture in a newspaper. From a document perspective (the original purpose of HTML), this is how floats work.
float
vs display:inline
Before the invention of display:inline-block
, websites use float
to set elements beside each other. float
is preferred over display:inline
since with the latter, you can't set the element's dimensions (width and height) as well as vertical paddings (top and bottom) - which floated elements can do since they're treated as block elements.
The main problem is that we're using float
against its intended purpose.
Another is that while float
allows side-by-side block-level elements, floats do not impart shape to its container. It's like position:absolute
, where the element is "taken out of the layout". For instance, when an empty container contains a floating 100px x 100px <div>
, the <div>
will not impart 100px in height to the container.
Unlike position:absolute
, it affects the content that surrounds it. Content after the floated element will "wrap" around the element. It starts by rendering beside it and then below it, like how newspaper text would flow around an image.
What clearfix does is to force content after the floats or the container containing the floats to render below it. There are a lot of versions for clear-fix, but it got its name from the version that's commonly being used - the one that uses the CSS property clear
.
Here are several ways to do clearfix , depending on the browser and use case. One only needs to know how to use the clear
property in CSS and how floats render in each browser in order to achieve a perfect cross-browser clear-fix.
Your provided style is a form of clearfix with backwards compatibility. I found an article about this clearfix. It turns out, it's an OLD clearfix - still catering the old browsers. There is a newer, cleaner version of it in the article also. Here's the breakdown:
The first clearfix you have appends an invisible pseudo-element, which is styled clear:both
, between the target element and the next element. This forces the pseudo-element to render below the target, and the next element below the pseudo-element.
The second one appends the style display:inline-block
which is not supported by earlier browsers. inline-block is like inline but gives you some properties that block elements, like width, height as well as vertical padding. This was targeted for IE-MAC.
This was the reapplication of display:block
due to IE-MAC rule above. This rule was "hidden" from IE-MAC.
All in all, these 3 rules keep the .clearfix
working cross-browser, with old browsers in mind.
Not perfect but I think it must be safest. Add nl2br:
$skuList = explode('<br />', nl2br($_POST['skuList']));
Check the service name of a database by
sql> show parameter service;
I know I'm late to the party, but here's a more solid answer.
All you need to do is use min-height: 100%;
rather than height: 100%;
and your gradient background will extend the entire height of the viewport without repeating, even if the content is scrollable.
Like this:
html {
min-height: 100%;
}
body {
background: linear-gradient(#ff7241, #ff4a1f);
}
I have given simple JavaScript date format examples please check the bellow code
var data = new Date($.now()); // without jquery remove this $.now()
console.log(data)// Thu Jun 23 2016 15:48:24 GMT+0530 (IST)
var d = new Date,
dformat = [d.getFullYear() ,d.getMonth()+1,
d.getDate()
].join('-')+' '+
[d.getHours(),
d.getMinutes(),
d.getSeconds()].join(':');
console.log(dformat) //2016-6-23 15:54:16
Using momentjs
var date = moment().format('YYYY-MM-DD H:mm:ss');
console.log(date) // 2016-06-23 15:59:08
Example please check https://jsfiddle.net/sjy3vjwm/2/
It can easily be done if u had declared a class that extends from Application
This class will be like a singleton, so when u need a context u can get it just like this:
I think this is the better answer and the cleaner
Here is my code from Utilities package:
public static String getAppNAme(){
return MyOwnApplication.getInstance().getString(R.string.app_name);
}
In recent versions of Git you can add multiple pushurl
s for a given remote. Use the following to add two pushurl
s to your origin
:
git remote set-url --add --push origin git://original/repo.git
git remote set-url --add --push origin git://another/repo.git
So when you push to origin
, it will push to both repositories.
UPDATE 1: Git 1.8.0.1 and 1.8.1 (and possibly other versions) seem to have a bug that causes --add
to replace the original URL the first time you use it, so you need to re-add the original URL using the same command. Doing git remote -v
should reveal the current URLs for each remote.
UPDATE 2: Junio C. Hamano, the Git maintainer, explained it's how it was designed. Doing git remote set-url --add --push <remote_name> <url>
adds a pushurl
for a given remote, which overrides the default URL for pushes. However, you may add multiple pushurl
s for a given remote, which then allows you to push to multiple remotes using a single git push
. You can verify this behavior below:
$ git clone git://original/repo.git
$ git remote -v
origin git://original/repo.git (fetch)
origin git://original/repo.git (push)
$ git config -l | grep '^remote\.'
remote.origin.url=git://original/repo.git
remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
Now, if you want to push to two or more repositories using a single command, you may create a new remote named all
(as suggested by @Adam Nelson in comments), or keep using the origin
, though the latter name is less descriptive for this purpose. If you still want to use origin
, skip the following step, and use origin
instead of all
in all other steps.
So let's add a new remote called all
that we'll reference later when pushing to multiple repositories:
$ git remote add all git://original/repo.git
$ git remote -v
all git://original/repo.git (fetch) <-- ADDED
all git://original/repo.git (push) <-- ADDED
origin git://original/repo.git (fetch)
origin git://original/repo.git (push)
$ git config -l | grep '^remote\.all'
remote.all.url=git://original/repo.git <-- ADDED
remote.all.fetch=+refs/heads/*:refs/remotes/all/* <-- ADDED
Then let's add a pushurl
to the all
remote, pointing to another repository:
$ git remote set-url --add --push all git://another/repo.git
$ git remote -v
all git://original/repo.git (fetch)
all git://another/repo.git (push) <-- CHANGED
origin git://original/repo.git (fetch)
origin git://original/repo.git (push)
$ git config -l | grep '^remote\.all'
remote.all.url=git://original/repo.git
remote.all.fetch=+refs/heads/*:refs/remotes/all/*
remote.all.pushurl=git://another/repo.git <-- ADDED
Here git remote -v
shows the new pushurl
for push, so if you do git push all master
, it will push the master
branch to git://another/repo.git
only. This shows how pushurl
overrides the default url (remote.all.url).
Now let's add another pushurl
pointing to the original repository:
$ git remote set-url --add --push all git://original/repo.git
$ git remote -v
all git://original/repo.git (fetch)
all git://another/repo.git (push)
all git://original/repo.git (push) <-- ADDED
origin git://original/repo.git (fetch)
origin git://original/repo.git (push)
$ git config -l | grep '^remote\.all'
remote.all.url=git://original/repo.git
remote.all.fetch=+refs/heads/*:refs/remotes/all/*
remote.all.pushurl=git://another/repo.git
remote.all.pushurl=git://original/repo.git <-- ADDED
You see both pushurl
s we added are kept. Now a single git push all master
will push the master
branch to both git://another/repo.git
and git://original/repo.git
.
I had the same problem and it was due to me not declaring the blank object first at the top of my controller:
$scope.model = {}
<input ng-model="model.firstProperty">
Hope this will works for you!
Yes - different
chmod a+x
will add the exec bits to the file but will not touch other bits. For example file might be still unreadable to others
and group
.
chmod 755
will always make the file with perms 755
no matter what initial permissions were.
This may or may not matter for your script.
On Mac OS X El Capitan I had to run these two commands to fix this error:
xcode-select --install
pip install lxml
Which ended up installing lxml-3.5.0
When you run the xcode-select command you may have to sign a EULA (so have an X-Term handy for the UI if you're doing this on a headless machine).
The same error appears if you do not use the correct (numeric) format of your data in your data.frame column using mean()
function. Therefore, check your data using str(data.frame&column)
function to see what data type you have, and convert it to numeric format if necessary.
For example, if your data is Character convert it with as.numeric(data.frame$column)
, or as a factor with as.numeric(as.character(data.frame$column))
. The mean function does not work with types other than numeric.
You can call sortable
on a <tbody>
instead of on the individual rows.
<table>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
</tr>
</tbody>
</table>?
<script>
$('tbody').sortable();
</script>
$(function() {_x000D_
$( "tbody" ).sortable();_x000D_
});
_x000D_
_x000D_
table {_x000D_
border-spacing: collapse;_x000D_
border-spacing: 0;_x000D_
}_x000D_
td {_x000D_
width: 50px;_x000D_
height: 25px;_x000D_
border: 1px solid black;_x000D_
}
_x000D_
_x000D_
_x000D_
<link href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" rel="stylesheet">_x000D_
<script src="//code.jquery.com/jquery-1.11.1.js"></script>_x000D_
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>_x000D_
_x000D_
<table>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>1</td>_x000D_
<td>2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>3</td>_x000D_
<td>4</td>_x000D_
</tr>_x000D_
<tr> _x000D_
<td>5</td>_x000D_
<td>6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>7</td>_x000D_
<td>8</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>9</td> _x000D_
<td>10</td>_x000D_
</tr> _x000D_
</tbody> _x000D_
</table>
_x000D_
Try this:
<div onselectstart="return false">some stuff</div>
Simple, but effective... works in current versions of all major browsers.
If anyone like me likes chainable data manipulation using the pandas dot notation (like piping), then the following may be useful:
df3 = df3.query('~index.duplicated()')
This enables chaining statements like this:
df3.assign(C=2).query('~index.duplicated()').mean()
Given Enum1 value = ...
, then if you mean by name:
Enum2 value2 = (Enum2) Enum.Parse(typeof(Enum2), value.ToString());
If you mean by numeric value, you can usually just cast:
Enum2 value2 = (Enum2)value;
(with the cast, you might want to use Enum.IsDefined
to check for valid values, though)
If you just have the xml
file of the color scheme you can:
Go to Preferences
-> Editor
-> Color and Fonts
and use the Import
button.
You should never store values with format. Formatting should be done in the view depending on user preferences.
Searching for phone nunbers with mixed formatting is near impossible.
For this case I would split into fields and store as integer. Numbers are faster than texts and splitting them and putting index on them makes all kind of queries ran fast.
Leading 0 could be a problem but probably not. In Sweden all area codes start with 0 and that is removed if also a country code is dialed. But the 0 isn't really a part of the number, it's a indicator used to tell that I'm adding an area code. Same for country code, you add 00 to say that you use a county code.
Leading 0 shouldn't be stored, they should be added when needed. Say you store 00 in the database and you use a server that only works with + they you have to replace 00 with + for that application.
So, store numbers as numbers.
You can also use SortedList and its Generic counterpart. These two classes and in Andrew Peters answer mentioned OrderedDictionary are dictionary classes in which items can be accessed by index (position) as well as by key. How to use these classes you can find: SortedList Class , SortedList Generic Class .
This tutorial displays splash screen for 2 seconds. You can easily change it to suit your needs.
- (void)showSplash {
UIViewController *modalViewController = [[UIViewController alloc] init];
modalViewController.view = modelView;
[self presentModalViewController:modalViewController animated:NO];
[self performSelector:@selector(hideSplash) withObject:nil afterDelay:yourDelay];
}
When you set a percentage height on an element who's parent elements don't have heights set, the parent elements have a default
height: auto;
You are asking the browser to calculate a height from an undefined value. Since that would equal a null-value, the result is that the browser does nothing with the height of child elements.
Besides using a JavaScript solution you could use this deadly easy table method:
#parent3 {
display: table;
width: 100%;
}
#parent3 .between {
display: table-row;
}
#parent3 .child {
display: table-cell;
}
Preview on http://jsbin.com/IkEqAfi/1
But: Bare in mind, that the table method only works properly in all modern Browsers and the Internet Explorer 8 and higher. As Fallback you could use JavaScript.
Extending on what @vabhatia said, this is what you want in native JavaScript (without JQuery).
ParentNode.insertBefore(<your element>, ParentNode.firstChild);
In one reusable piece of code I use the directive <%@include file="reuse.html"%>
and in the second I use the standard action <jsp:include page="reuse.html" />
.
Let the code in the reusable file be:
<html>
<head>
<title>reusable</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<img src="candle.gif" height="100" width="50"/> <br />
<p><b>As the candle burns,so do I</b></p>
</body>
After running both the JSP files you see the same output and think if there was any difference between the directive and the action tag. But if you look at the generated servlet
of the two JSP files, you will see the difference.
Here is what you will see when you use the directive:
out.write("<html>\r\n");
out.write(" <head>\r\n");
out.write(" <title>reusable</title>\r\n");
out.write(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\r\n");
out.write(" </head>\r\n");
out.write(" <body>\r\n");
out.write(" <img src=\"candle.gif\" height=\"100\" width=\"50\"/> <br />\r\n");
out.write(" <p><b>As the candle burns,so do I</b></p>\r\n");
out.write(" </body>\r\n");
out.write("</html>\r\n");
And this is what you will see for the used standard action in the second JSP file :
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "reusable.html", out, false);
So now you know that the include directive inserts the source of reuse.html
at translation time, but the action tag inserts the response of reuse.html
at runtime.
If you think about it, there is an extra performance hit with every action tag (<jsp:include>
). It means you can guarantee you will always have the latest content, but it increases performance cost.
In case you happen to be using Spring framework along with java, there is an easy way around.
Import the following.
import org.springframework.util.Base64Utils;
Convert like this.
byte[] bytearr ={0,1,2,3,4}; String encodedText = Base64Utils.encodeToString(bytearr);
To decode you can use the decodeToString method of the Base64Utils class.
Try this statement:
exit 1
Replace 1
with appropriate error codes. See also Exit Codes With Special Meanings.
1)Please add multiDexEnabled true 2)if you get compilation error then check your app level build.gradle weather same dependencies are implemented with different versions. 3)Remove one if you find same dependencies.
android { compileSdkVersion 28 defaultConfig {
minSdkVersion 17
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
hope it works fine :) Happy Coding
string k = "This is my\r\nugly string. I want\r\nto change this. Please \r\n help!";
k = System.Text.RegularExpressions.Regex.Replace(k, @"\r\n+", " ");
When you implement Comparable
interface, you need to implement method compareTo()
. You need it to compare objects, in order to use, for example, sorting method of ArrayList
class. You need a way to compare your objects to be able to sort them. So you need a custom compareTo()
method in your class so you can use it with the ArrayList
sort method. The compareTo()
method returns -1,0,1.
I have just read an according chapter in Java Head 2.0, I'm still learning.
Element which fired event we have in event property
event.currentTarget
We get DOM node object on which was set event handler.
Most nested node which started bubbling process we have in
event.target
Event object is always first attribute of event handler, example:
document.querySelector("someSelector").addEventListener(function(event){
console.log(event.target);
console.log(event.currentTarget);
});
More about event delegation You can read in http://maciejsikora.com/standard-events-vs-event-delegation/
The simplest way is to convert your unsigned long
s into unsigned long long
s, do your multiplication, and compare the result to 0x100000000LL.
You'll probably find that this is more efficient than doing the division as you've done in your example.
Oh, and it'll work in both C and C++ (as you've tagged the question with both).
Just been taking a look at the glibc manual. There's a mention of an integer overflow trap (FPE_INTOVF_TRAP
) as part of SIGFPE
. That would be ideal, apart from the nasty bits in the manual:
FPE_INTOVF_TRAP
Integer overflow (impossible in a C program unless you enable overflow trapping in a hardware-specific fashion).
A bit of a shame really.
getline is storing the entire line at once, which is not what you want. A simple fix is to have three variables and use cin to get them all. C++ will parse automatically at the spaces.
#include <iostream>
using namespace std;
int main() {
string a, b, c;
cin >> a >> b >> c;
//now you have your three words
return 0;
}
I don't know what particular "operation" you're talking about, so I can't help you there, but if it's changing characters, read up on string and indices. The C++ documentation is great. As for using namespace std; versus std:: and other libraries, there's already been a lot said. Try these questions on StackOverflow to start.
I'm not sure about older versions, but from NEON onward, you can just right click on workspace and select Remove from launcher selection option.
of course this won't remove the original files. It simply removes it from the list of suggested workspaces.
I ended up combining urlTree
with location.go
const urlTree = this.router.createUrlTree([], {
relativeTo: this.route,
queryParams: {
newParam: myNewParam,
},
queryParamsHandling: 'merge',
});
this.location.go(urlTree.toString());
Not sure if toString
can cause problems, but unfortunately location.go
, seems to be string based.
reloadRowsAtIndexPaths:
is fine, but still will force UITableViewDelegate
methods to fire.
The simplest approach I can imagine is:
UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:indexPath];
[self configureCell:cell forIndexPath:indexPath];
It's important to invoke your configureCell:
implementation on main thread, as it wont work on non-UI thread (the same story with reloadData
/reloadRowsAtIndexPaths:
). Sometimes it might be helpful to add:
dispatch_async(dispatch_get_main_queue(), ^
{
[self configureCell:cell forIndexPath:indexPath];
});
It's also worth to avoid work that would be done outside of the currently visible view:
BOOL cellIsVisible = [[self.tableView indexPathsForVisibleRows] indexOfObject:indexPath] != NSNotFound;
if (cellIsVisible)
{
....
}
If the project is a GUI project, no console will appear. In order to change the project into a console one you need to go to the project properties panel and set:
This solution works only if you had the classic "int main()" entry point.
But if you are like in my case (an openGL project), you don't need to edit the properties, as this works better:
AllocConsole();
freopen("CONIN$", "r",stdin);
freopen("CONOUT$", "w",stdout);
freopen("CONOUT$", "w",stderr);
printf and cout will work as usual.
If you call AllocConsole before the creation of a window, the console will appear behind the window, if you call it after, it will appear ahead.
Update
freopen
is deprecated and may be unsafe. Use freopen_s
instead:
FILE* fp;
AllocConsole();
freopen_s(&fp, "CONIN$", "r", stdin);
freopen_s(&fp, "CONOUT$", "w", stdout);
freopen_s(&fp, "CONOUT$", "w", stderr);
All the answers above are helpful but none solved my issue. In my production file, my STATIC_URL was https://<URL>/static
and I used the same STATIC_URL in my dev settings.py file.
This causes a silent failure in django/conf/urls/static.py.
The test elif not settings.DEBUG or '://' in prefix:
picks up the '//' in the URL and does not add the static URL pattern, causing no static files to be found.
It would be thoughtful if Django spit out an error message stating you can't use a http(s)://
with DEBUG = True
I had to change STATIC_URL to be '/static/'
If you give your table a unique id, its easier:
<div id="ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a"
onmouseup="checkMultipleSelection(this,event);">
<table id="ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a_table"
cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
<td style="width:50px; text-align:left;">09:15 AM</td>
<td style="width:50px; text-align:left;">Item001</td>
<td style="width:50px; text-align:left;">10</td>
<td style="width:50px; text-align:left;">Address1</td>
<td style="width:50px; text-align:left;">46545465</td>
<td style="width:50px; text-align:left;">ref1</td>
</tr>
</table>
</div>
var multiselect =
document.getElementById(
'ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a_table'
).rows[0].cells,
timeXaddr = [multiselect[0].innerHTML, multiselect[2].innerHTML];
//=> timeXaddr now an array containing ['09:15 AM', 'Address1'];
The format for HTTP headers is defined in the HTTP specification. I'm going to talk about HTTP 1.1, for which the specification is RFC 2616. In section 4.2, 'Message Headers', the general structure of a header is defined:
message-header = field-name ":" [ field-value ]
field-name = token
field-value = *( field-content | LWS )
field-content = <the OCTETs making up the field-value
and consisting of either *TEXT or combinations
of token, separators, and quoted-string>
This definition rests on two main pillars, token and TEXT. Both are defined in section 2.2, 'Basic Rules'. Token is:
token = 1*<any CHAR except CTLs or separators>
In turn resting on CHAR, CTL and separators:
CHAR = <any US-ASCII character (octets 0 - 127)>
CTL = <any US-ASCII control character
(octets 0 - 31) and DEL (127)>
separators = "(" | ")" | "<" | ">" | "@"
| "," | ";" | ":" | "\" | <">
| "/" | "[" | "]" | "?" | "="
| "{" | "}" | SP | HT
TEXT is:
TEXT = <any OCTET except CTLs,
but including LWS>
Where LWS is linear white space, whose definition i won't reproduce, and OCTET is:
OCTET = <any 8-bit sequence of data>
There is a note accompanying the definition:
The TEXT rule is only used for descriptive field contents and values
that are not intended to be interpreted by the message parser. Words
of *TEXT MAY contain characters from character sets other than ISO-
8859-1 [22] only when encoded according to the rules of RFC 2047
[14].
So, two conclusions. Firstly, it's clear that the header name must be composed from a subset of ASCII characters - alphanumerics, some punctuation, not a lot else. Secondly, there is nothing in the definition of a header value that restricts it to ASCII or excludes 8-bit characters: it's explicitly composed of octets, with only control characters barred (note that CR and LF are considered controls). Furthermore, the comment on the TEXT production implies that the octets are to be interpreted as being in ISO-8859-1, and that there is an encoding mechanism (which is horrible, incidentally) for representing characters outside that encoding.
So, to respond to @BalusC in particular, it's quite clear that according to the specification, header values are in ISO-8859-1. I've sent high-8859-1 characters (specifically, some accented vowels as used in French) in a header out of Tomcat, and had them interpreted correctly by Firefox, so to some extent, this works in practice as well as in theory (although this was a Location header, which contains a URL, and these characters are not legal in URLs, so this was actually illegal, but under a different rule!).
That said, i wouldn't rely on ISO-8859-1 working across all servers, proxies, and clients, so i would stick to ASCII as a matter of defensive programming.
Just fix the height of the image & provide width = auto
img{
height: 95vh;
width: auto;
}
When you insert the pair (10, 17)
and then (10, 20)
, there is technically no collision involved. You are just replacing the old value with the new value for a given key 10
(since in both cases, 10 is equal to 10 and also the hash code for 10 is always 10).
Collision happens when multiple keys hash to the same bucket. In that case, you need to make sure that you can distinguish between those keys. Chaining collision resolution is one of those techniques which is used for this.
As an example, let's suppose that two strings "abra ka dabra"
and "wave my wand"
yield hash codes 100
and 200
respectively. Assuming the total array size is 10, both of them end up in the same bucket (100 % 10
and 200 % 10
). Chaining ensures that whenever you do map.get( "abra ka dabra" );
, you end up with the correct value associated with the key. In the case of hash map in Java, this is done by using the equals
method.
I am getting this issue when using owl carousal and scrolling the images.
So get solved just adding below CSS in your page.
.owl-carousel {
-ms-touch-action: pan-y;
touch-action: pan-y;
}
or
.owl-carousel {
-ms-touch-action: none;
touch-action: none;
}
This can happen on foreachs when using:
foreach( $array as $key = $value )
instead of
foreach( $array as $key => $value )
Use the %02X
format parameter:
printf("%02X",word[i]);
More info can be found here: http://www.cplusplus.com/reference/cstdio/printf/
Assembly is the fundamental part of programming with .NET Framework. It contain code that CLR executes MSIL(Microsoft Intermediate Language) code in a portable executable file will not be executed if it does not have an associated assembly manifest.
Binary releases contain computer readable version of the application, meaning it is compiled. Source releases contain human readable version of the application, meaning it has to be compiled before it can be used.
It is a generic type constraint. In this case it means that the generic type T
has to be a reference type (class, interface, delegate, or array type).
var l = document.getElementsByClassName("chatMessages").length;
document.getElementsByClassName("chatMessages")[l-1].scrollIntoView();
this should work
Pandas DataFrames have the to_pickle
function which is useful for saving a DataFrame:
import pandas as pd
a = pd.DataFrame({'A':[0,1,0,1,0],'B':[True, True, False, False, False]})
print a
# A B
# 0 0 True
# 1 1 True
# 2 0 False
# 3 1 False
# 4 0 False
a.to_pickle('my_file.pkl')
b = pd.read_pickle('my_file.pkl')
print b
# A B
# 0 0 True
# 1 1 True
# 2 0 False
# 3 1 False
# 4 0 False
You can use .gitignore in the top level to ignore all directories in the project with the same name. For example:
Debug/
Release/
This should update immediately so it's visible when you do git status. Ensure that these directories are not already added to git, as that will override the ignores.
In new APIs don't forget about TAG:
notify(String tag, int id, Notification notification)
and correspondingly
cancel(String tag, int id)
instead of:
cancel(int id)
https://developer.android.com/reference/android/app/NotificationManager
A variation on the here-doc trick in the accepted answer by sunny256 is to use the Perl keywords for comments. If your comments are actually some sort of documentation, you can then start using the Perl syntax inside the commented block, which allows you to print it out nicely formatted, convert it to a man-page, etc.
As far as the shell is concerned, you only need to replace 'END'
with '=cut'
.
echo "before comment"
: <<'=cut'
=pod
=head1 NAME
podtest.sh - Example shell script with embedded POD documentation
etc.
=cut
echo "after comment"
(Found on "Embedding documentation in shell script")
Get the system time in milliseconds at the beginning, and again at the end, and subtract.
To get the number of milliseconds since 1970 in POSIX you would write:
struct timeval tv;
gettimeofday(&tv, NULL);
return ((((unsigned long long)tv.tv_sec) * 1000) +
(((unsigned long long)tv.tv_usec) / 1000));
To get the number of milliseconds since 1601 on Windows you would write:
SYSTEMTIME systime;
FILETIME filetime;
GetSystemTime(&systime);
if (!SystemTimeToFileTime(&systime, &filetime))
return 0;
unsigned long long ns_since_1601;
ULARGE_INTEGER* ptr = (ULARGE_INTEGER*)&ns_since_1601;
// copy the result into the ULARGE_INTEGER; this is actually
// copying the result into the ns_since_1601 unsigned long long.
ptr->u.LowPart = filetime.dwLowDateTime;
ptr->u.HighPart = filetime.dwHighDateTime;
// Compute the number of milliseconds since 1601; we have to
// divide by 10,000, since the current value is the number of 100ns
// intervals since 1601, not ms.
return (ns_since_1601 / 10000);
If you cared to normalize the Windows answer so that it also returned the number of milliseconds since 1970, then you would have to adjust your answer by 11644473600000 milliseconds. But that isn't necessary if all you care about is the elapsed time.
I'd use RestSharp - https://github.com/restsharp/RestSharp
Create class to deserialize to:
public class MyObject {
public string Id { get; set; }
public string Text { get; set; }
...
}
And the code to get that object:
RestClient client = new RestClient("http://whatever.com");
RestRequest request = new RestRequest("path/to/object");
request.AddParameter("id", "123");
// The above code will make a request URL of
// "http://whatever.com/path/to/object?id=123"
// You can pick and choose what you need
var response = client.Execute<MyObject>(request);
MyObject obj = response.Data;
Check out http://restsharp.org/ to get started.
The whole Distributed thing of Git is really really great. it gives a few features Shelvesets don't have (in the current product) such as local rollback and commit options (such as Eclipse's localhistory feature). You could alleviate this using developer branches, but lets be honest, many developers don't like branching and merging one bit. I've been asked to turn on the old style "exclusive checkout" feature in TFS a few times too often (and denied it each and every time).
I think many large enterprises are quite scared to allow a dev to just bring the whole history into a local workspace and take it with them (to a new employer for example)... Stealing a snapshot is bad, but taking away a whole history is even more troublesome. (Not that you couldn't get a full history from TFS of you wanted it)...
It's mentioned that it's a great way to backup, which is great for open source again where the original maintainer might stop to care and removes his version, but for a enterprise plan this again falls short for many enterprises as there is no clear assignment of responsibility to keep backups. And it would be hard to figure out which version to use if the main 'project' vanishes somehow. Which would tend to appoint one repository as leading/central.
What I like most about Git is the Push/Pull option, where you can easily contribute code to a project without the need to have commit rights. I guess you could use very limited users and shelvesets in TFS to mimic this, but it isn't as powerful as the Git option. Branching across team projects might work as well, but from an administrative perspective it's not really feasible for many organisations as adding team projects adds a lot of administartive overhead.
I'd also like to add to the things mentioned in the non source control area. Features such as Work Item Tracking, Reporting and Build Automation (including lab management) greatly benefit from a central leading repository. These become a lot harder when you use a pure distributed model, unless you make one of the nodes leading (and thus go back to a less distributed model).
With TFS Basic coming with TFS 11, it might not be far off to expect a distributed TFS which allows you to sync your local TFS basic to a central TFS in the TFS 12+ era. I'll put my vote for that down in the uservoice!
Another example is, you have class like :
@obc class Album: NSObject {
let name:String
let singer:Singer
let artwork:URL
let playingSong:Song
// ...
class func getCurrentlyPlayingSongLyric(duration: Int = 0) -> String {
// ...
return playingSong.lyric
}
}
you will also get the same type of error like :
instance member x cannot be used on type x.
It's because you assign your method with "class" keyword (which makes your method a type method) and using like :
Album.getCurrentlyPlayingSongLyric(duration: 5)
but who set the playingSong variable before? Ok. You shouldn't use class keyword for that case :
// ...
func getCurrentlyPlayingSongLyric(duration: Int = 0) -> String {
// ...
return playingSong.lyric
}
// ...
Now you're free to go.
_.each(['Hello', 'World!'], function(word){_x000D_
console.log(word);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
_x000D_
Here's simple example that could use _.each
:
function basket() {_x000D_
this.items = [];_x000D_
this.addItem = function(item) {_x000D_
this.items.push(item);_x000D_
};_x000D_
this.show = function() {_x000D_
console.log('items: ', this.items);_x000D_
}_x000D_
}_x000D_
_x000D_
var x = new basket();_x000D_
x.addItem('banana');_x000D_
x.addItem('apple');_x000D_
x.addItem('kiwi');_x000D_
x.show();
_x000D_
Output:
items: [ 'banana', 'apple', 'kiwi' ]
Instead of calling addItem
multiple times you could use underscore this way:
_.each(['banana', 'apple', 'kiwi'], function(item) { x.addItem(item); });
which is identical to calling addItem
three times sequentially with these items. Basically it iterates your array and for each item calls your anonymous callback function that calls x.addItem(item)
. The anonymous callback function is similar to addItem
member function (e.g. it takes an item) and is kind of pointless. So, instead of going through anonymous function it's better that _.each
avoids this indirection and calls addItem
directly:
_.each(['banana', 'apple', 'kiwi'], x.addItem);
but this won't work, as inside basket's addItem
member function this
won't refer to your x
basket that you created. That's why you have an option to pass your basket x
to be used as [context]
:
_.each(['banana', 'apple', 'kiwi'], x.addItem, x);
function basket() {_x000D_
this.items = [];_x000D_
this.addItem = function(item) {_x000D_
this.items.push(item);_x000D_
};_x000D_
this.show = function() {_x000D_
console.log('items: ', this.items);_x000D_
}_x000D_
}_x000D_
var x = new basket();_x000D_
_.each(['banana', 'apple', 'kiwi'], x.addItem, x);_x000D_
x.show();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
_x000D_
In short, if callback function that you pass to _.each
in any way uses this
then you need to specify what this
should be referring to inside your callback function. It may seem like x
is redundant in my example, but x.addItem
is just a function and could be totally unrelated to x
or basket
or any other object, for example:
function basket() {_x000D_
this.items = [];_x000D_
this.show = function() {_x000D_
console.log('items: ', this.items);_x000D_
}_x000D_
}_x000D_
function addItem(item) {_x000D_
this.items.push(item);_x000D_
};_x000D_
_x000D_
var x = new basket();_x000D_
_.each(['banana', 'apple', 'kiwi'], addItem, x);_x000D_
x.show();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
_x000D_
In other words, you bind some value to this
inside your callback, or you may as well use bind directly like this:
_.each(['banana', 'apple', 'kiwi'], addItem.bind(x));
how this feature can be useful with some different underscore methods?
In general, if some underscorejs
method takes a callback function and if you want that callback be called on some member function of some object (e.g. a function that uses this
) then you may bind that function to some object or pass that object as the [context]
parameter and that's the primary intention. And at the top of underscorejs documentation, that's exactly what they state: The iteratee is bound to the context object, if one is passed
Try one of these other mime-types (from here: http://filext.com/file-extension/CSV )
Also, the mime-type might be case sensitive...
This is copied from above, but condensed slightly and re-written in semantic terms. Note: #Container
has display: flex;
and flex-direction: column;
, while the columns have flex: 3;
and flex: 2;
(where "One value, unitless number" determines the flex-grow
property) per MDN flex
docs.
#Container {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
height: 600px;_x000D_
width: 580px;_x000D_
}_x000D_
_x000D_
.Content {_x000D_
display: flex;_x000D_
flex: 1;_x000D_
}_x000D_
_x000D_
#Detail {_x000D_
flex: 3;_x000D_
background-color: lime;_x000D_
}_x000D_
_x000D_
#ThumbnailContainer {_x000D_
flex: 2;_x000D_
background-color: black;_x000D_
}
_x000D_
<div id="Container">_x000D_
<div class="Content">_x000D_
<div id="Detail"></div>_x000D_
<div id="ThumbnailContainer"></div>_x000D_
</div>_x000D_
</div>
_x000D_
If you are using custom adapters than android:focusable="false"
and android:focusableInTouchMode="false"
are nessesury to make list items clickable while using checkbox.
<CheckBox
android:id="@+id/checkbox_fav"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/checkbox_layout"/>
In drawable>checkbox_layout.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="@drawable/uncked_checkbox"
android:state_checked="false"/>
<item android:drawable="@drawable/selected_checkbox"
android:state_checked="true"/>
<item android:drawable="@drawable/uncked_checkbox"/>
</selector>
There could be many reasons for Index not being used. Even after you specify hints, there are chances Oracle optimizer thinks otherwise and decide not to use Index. You need to go through the EXPLAIN PLAN part and see what is the cost of the statement with INDEX and without INDEX.
Assuming the Oracle uses CBO. Most often, if the optimizer thinks the cost is high with INDEX, even though you specify it in hints, the optimizer will ignore and continue for full table scan. Your first action should be checking DBA_INDEXES to know when the statistics are LAST_ANALYZED. If not analyzed, you can set table, index for analyze.
begin
DBMS_STATS.GATHER_INDEX_STATS ( OWNNAME=>user
, INDNAME=>IndexName);
end;
For table.
begin
DBMS_STATS.GATHER_TABLE_STATS ( OWNNAME=>user
, TABNAME=>TableName);
end;
In extreme cases, you can try setting up the statistics on your own.
If you declare your callback as mentioned by @lex82 like
callback = "callback(item.id, arg2)"
You can call the callback method in the directive scope with object map and it would do the binding correctly. Like
scope.callback({arg2:"some value"});
without requiring for $parse. See my fiddle(console log) http://jsfiddle.net/k7czc/2/
Update: There is a small example of this in the documentation:
& or &attr - provides a way to execute an expression in the context of the parent scope. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given and widget definition of scope: { localFn:'&myAttr' }, then isolate scope property localFn will point to a function wrapper for the count = count + value expression. Often it's desirable to pass data from the isolated scope via an expression and to the parent scope, this can be done by passing a map of local variable names and values into the expression wrapper fn. For example, if the expression is increment(amount) then we can specify the amount value by calling the localFn as localFn({amount: 22}).
I'm able to exclude multiple directories using the below config (comma separated folder paths):
sonar.exclusions=system/**, test/**, application/third_party/**, application/logs/**
And while running the sonar runner I got the following in the log:
Excluded sources:
system/**
test/**
application/third_party/**
application/logs/**
First, set your key field. Then include your other fields:
var results =
persons
.GroupBy(n => n.PersonId)
.Select(r => new Result {PersonID = r.Key, Cars = r.ToList() })
.ToList()
There are also DRM behaviors that incorporate multiple steps to the process. One of the most well known examples is one of Adobe's methods for verifying an installation of their Creative Suite. The traditional CD Key method discussed here is used, then Adobe's support line is called. The CD key is given to the Adobe representative and they give back an activation number to be used by the user.
However, despite being broken up into steps, this falls prey to the same methods of cracking used for the normal process. The process used to create an activation key that is checked against the original CD key was quickly discovered, and generators that incorporate both of the keys were made.
However, this method still exists as a way for users with no internet connection to verify the product. Going forward, it's easy to see how these methods would be eliminated as internet access becomes ubiquitous.
You don not need to create a $(document).mousemove( function(e) {})
to handle mouse x,y. Get the event in the $.hover
function and from there it is possible to get x and y positions of the mouse. See the code below:
$('foo').hover(function(e){
var pos = [e.pageX-150,e.pageY];
$('foo1').dialog( "option", "position", pos );
$('foo1').dialog('open');
},function(){
$('foo1').dialog('close');
});
I use the following format and works well.
robocopy \\SourceServer\Path \\TargetServer\Path filename.txt
to copy everything you can replace filename.txt
with *.*
and there are plenty of other switches to copy subfolders etc... see here: http://ss64.com/nt/robocopy.html
Declare in model:
class ModelName extends Model
{
protected $casts = [
'created_at' => 'datetime:d/m/Y', // Change your format
'updated_at' => 'datetime:d/m/Y',
];
While the git fetch
command will fetch down all the changes on the server that you don’t have yet, it will not modify your working directory at all. It will simply get the data for you and let you merge it yourself. However, there is a command called git pull
which is essentially a git fetch
immediately followed by a git merge
in most cases.
Read more: https://git-scm.com/book/en/v2/Git-Branching-Remote-Branches#Pulling
One other way, using the splat operator:
*a, last = [1, 3, 4, 5]
STDOUT:
a: [1, 3, 4]
last: 5
I second Shobhit Verma, and I have a little note to add : in his post he told that in Chrome (Opera for myself) the players need to be muted in order for the autoplay to succeed... And ironically, if you elevate the volume after load, it will still play... It's like all those anti-pop-ups mechanic that ignore invisible frame slid into your code... php-echoed html and javascript is : 10-second setTimeout onLoad of body tag that rises volume to maximum, video with autoplay and muted='muted' (yeah that $muted_code part is = "muted='muted")
echo "<body style='margin-bottom:0pt; margin-top:0pt; margin-left:0pt; margin-right:0pt' onLoad=\"setTimeout(function() {var vid = document.getElementById('hourglass_video'); vid.volume = 1.0;},10000);\">";
echo "<div id='hourglass_container' width='100%' height='100%' align='center' style='text-align:right; vertical-align:bottom'>";
echo "<video autoplay {$muted_code}title=\"!!! Pausing this video will immediately end your turn!!!\" oncontextmenu=\"dont_stop_hourglass(event);\" onPause=\"{$action}\" id='hourglass_video' frameborder='0' style='width:95%; margin-top:28%'>";
What is row?
Either of these could be correct.
1) I assume that you capture your ajax response in a javascript variable 'row'. If that is the case, this would hold true.
var result=row.split('|');
alert(result[2]);
otherwise
2) Use this where $(row)
is a jQuery
object.
var result=$(row).val().split('|');
alert(result[2]);
[As mentioned in the other answer, you may have to use $(row).val()
or $(row).text()
or $(row).html()
etc. depending on what $(row) is.]
Here is an example where pointer to data members could be useful:
#include <iostream>
#include <list>
#include <string>
template <typename Container, typename T, typename DataPtr>
typename Container::value_type searchByDataMember (const Container& container, const T& t, DataPtr ptr) {
for (const typename Container::value_type& x : container) {
if (x->*ptr == t)
return x;
}
return typename Container::value_type{};
}
struct Object {
int ID, value;
std::string name;
Object (int i, int v, const std::string& n) : ID(i), value(v), name(n) {}
};
std::list<Object*> objects { new Object(5,6,"Sam"), new Object(11,7,"Mark"), new Object(9,12,"Rob"),
new Object(2,11,"Tom"), new Object(15,16,"John") };
int main() {
const Object* object = searchByDataMember (objects, 11, &Object::value);
std::cout << object->name << '\n'; // Tom
}
For LinearLayout
with horizontal orientation, give layout_weight
to other child view except for the view that you want to align right. This works perfectly.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Specialization"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Right"
android:textColor="#ff0000" />
</LinearLayout>
Have you tried using the "auto-fill" in Excel?
If you have an entire column of items you put the formula in the first cell, make sure you get the result you desire and then you can do the copy/paste, or use auto fill which is an option that sits on the bottom right corner of the cell.
You go to that corner in the cell and once your cursor changes to a "+", you can double-click on it and it should populate all the way down to the last entry (as long as there are no populated cells, that is).
One way:
import os
os.listdir("/home/username/www/")
glob.glob("/home/username/www/*")
The glob.glob
method above will not list hidden files.
Since I originally answered this question years ago, pathlib has been added to Python. My preferred way to list a directory now usually involves the iterdir
method on Path
objects:
from pathlib import Path
print(*Path("/home/username/www/").iterdir(), sep="\n")
You are POSTing the json incorrectly -- but even if it were correct, you would not be able to test using print_r($_POST)
(read why here). Instead, on your second page, you can nab the incoming request using file_get_contents("php://input")
, which will contain the POSTed json. To view the received data in a more readable format, try this:
echo '<pre>'.print_r(json_decode(file_get_contents("php://input")),1).'</pre>';
In your code, you are indicating Content-Type:application/json
, but you are not json-encoding all of the POST data -- only the value of the "customer" POST field. Instead, do something like this:
$ch = curl_init( $url );
# Setup request to send json via POST.
$payload = json_encode( array( "customer"=> $data ) );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
# Return response instead of printing.
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
# Send request.
$result = curl_exec($ch);
curl_close($ch);
# Print response.
echo "<pre>$result</pre>";
Sidenote: You might benefit from using a third-party library instead of interfacing with the Shopify API directly yourself.
What about
this.f = window["instance:" + a] = function(){};
The only drawback is that the function in its toSource method wouldn't indicate a name. That's usually only a problem for debuggers.
I would start with upgrade of CMAKE version.
You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries
INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)
note that lib1
is expanded to liblib1.so
(on Linux), so use ln to create appropriate links in case you do not have them
Try replacing %H (Hour on a 24-hour clock) with %I (Hour on a 12-hour clock) ?
You have mostly the right idea, it's just the sending of the form that is wrong. The form belongs in the body of the request.
req, err := http.NewRequest("POST", url, strings.NewReader(form.Encode()))
Another option is to use the case-insensitive flag i, then there's no need for the extra character range A-Z.
var reg = /^[a-z]+$/i;
console.log( reg.test("somethingELSE") ); //true
console.log( "somethingELSE".match(reg)[0] ); //"somethingELSE"
Here's a DEMO on how this regex works with test() and match().
I Know this is a old question, and Pawel has given the correct answer, I just wanted to show a code example of how to do some string processing, and avoid an extra class for the list of a primitive type.
public class Test
{
public Test()
{
_strings = new List<string>
{
"test",
"test2",
"test3",
"test4"
};
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
private List<String> _strings { get; set; }
public List<string> Strings
{
get { return _strings; }
set { _strings = value; }
}
[Required]
public string StringsAsString
{
get { return String.Join(',', _strings); }
set { _strings = value.Split(',').ToList(); }
}
}
In my case, changin screen resolution from WVGA720 to WSVGA works for me.
Restarted worked! I found the same error to add new table to my database diagram on sql server 2016, restarted sql server management studio, finally solved.
I did an upgraded version of jezzipin's answer (and I'm animating padding top instead of height but you still get the point.
/**
* ResizeHeaderOnScroll
*
* @constructor
*/
var ResizeHeaderOnScroll = function()
{
this.protocol = window.location.protocol;
this.domain = window.location.host;
};
ResizeHeaderOnScroll.prototype.init = function()
{
if($(document).scrollTop() > 0)
{
$('header').data('size','big');
} else {
$('header').data('size','small');
}
ResizeHeaderOnScroll.prototype.checkScrolling();
$(window).scroll(function(){
ResizeHeaderOnScroll.prototype.checkScrolling();
});
};
ResizeHeaderOnScroll.prototype.checkScrolling = function()
{
if($(document).scrollTop() > 0)
{
if($('header').data('size') == 'big')
{
$('header').data('size','small');
$('header').stop().animate({
paddingTop:'1em',
paddingBottom:'1em'
},200);
}
}
else
{
if($('header').data('size') == 'small')
{
$('header').data('size','big');
$('header').stop().animate({
paddingTop:'3em'
},200);
}
}
}
$(document).ready(function(){
var resizeHeaderOnScroll = new ResizeHeaderOnScroll();
resizeHeaderOnScroll.init()
})
Recent versions of git run gc automatically when required, so you shouldn't have to do anything. See the Options section of man git-gc(1): "Some git commands run git gc --auto after performing operations that could create many loose objects."
I spent a lot of time on this issue and none of above solutions work for me. The names and number of build types were also exactly equal in both app and library project.
The only mistake I was making was - In library project's build.gradle, I was using line
apply plugin: 'com.android.application'
While this line should be -
apply plugin: 'com.android.library'
After making this change, this error got resolved.
Just another version of zipping without writing any file.
string fileName = "export_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xlsx";
byte[] fileBytes = here is your file in bytes
byte[] compressedBytes;
string fileNameZip = "Export_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".zip";
using (var outStream = new MemoryStream())
{
using (var archive = new ZipArchive(outStream, ZipArchiveMode.Create, true))
{
var fileInArchive = archive.CreateEntry(fileName, CompressionLevel.Optimal);
using (var entryStream = fileInArchive.Open())
using (var fileToCompressStream = new MemoryStream(fileBytes))
{
fileToCompressStream.CopyTo(entryStream);
}
}
compressedBytes = outStream.ToArray();
}
You don't have a Date
, you have a String
representation of a date. You should convert the String
into a Date
and then obtain the milliseconds. To convert a String
into a Date
and vice versa you should use SimpleDateFormat
class.
Here's an example of what you want/need to do (assuming time zone is not involved here):
String myDate = "2014/10/29 18:10:45";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = sdf.parse(myDate);
long millis = date.getTime();
Still, be careful because in Java the milliseconds obtained are the milliseconds between the desired epoch and 1970-01-01 00:00:00.
Using the new Date/Time API available since Java 8:
String myDate = "2014/10/29 18:10:45";
LocalDateTime localDateTime = LocalDateTime.parse(myDate,
DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss") );
/*
With this new Date/Time API, when using a date, you need to
specify the Zone where the date/time will be used. For your case,
seems that you want/need to use the default zone of your system.
Check which zone you need to use for specific behaviour e.g.
CET or America/Lima
*/
long millis = localDateTime
.atZone(ZoneId.systemDefault())
.toInstant().toEpochMilli();
Here is the code snippet I found:
var audio = new Audio();
audio.src ='http://translate.google.com/translate_tts?ie=utf-8&tl=en&q=Hello%20World.';
audio.play();
In this case, using WebView#loadDataWithBaseUrl()
is better than WebView#loadUrl()
!
webView.loadDataWithBaseURL(url,
data,
"text/html",
"utf-8",
null);
url: url/path String pointing to the directory all your JavaScript files and html links have their origin. If null, it's about:blank. data: String containing your hmtl file, read with BufferedReader for example
We use the following:
Canada
([A-Z]{1}[0-9]{1}){3} //We raise to upper first
America
[0-9]{5} //-or-
[0-9]{5}-[0-9]{4} //10 digit zip
Other
Accept as is
You can' just add a class to each of your DIVs and apply the rule to the class in this way:
HTML:
<div class="myclass" id="s1">...</div>
<div class="myclass" id="s2">...</div>
CSS:
//css
.myclass
{
...
}
For me, only the following worked with Oracle 11g and Glassfish 2.1 (Toplink):
Query query = entityManager.createNativeQuery("BEGIN PROCEDURE_NAME(); END;");
query.executeUpdate();
The variant with curly braces resulted in ORA-00900.
Alternatively you can edit the source and create your own incrementations
FontAwesome 5
https://github.com/FortAwesome/Font-Awesome/blob/master/web-fonts-with-css/less/_larger.less
// Icon Sizes
// -------------------------
.larger(@factor) when (@factor > 0) {
.larger((@factor - 1));
.@{fa-css-prefix}-@{factor}x {
font-size: (@factor * 1em);
}
}
/* makes the font 33% larger relative to the icon container */
.@{fa-css-prefix}-lg {
font-size: (4em / 3);
line-height: (3em / 4);
vertical-align: -.0667em;
}
.@{fa-css-prefix}-xs {
font-size: .75em;
}
.@{fa-css-prefix}-sm {
font-size: .875em;
}
// Change the number below to create your own incrementations
// This currently creates classes .fa-1x - .fa-10x
.larger(10);
FontAwesome 4
https://github.com/FortAwesome/Font-Awesome/blob/v4.7.0/less/larger.less
// Icon Sizes
// -------------------------
/* makes the font 33% larger relative to the icon container */
.@{fa-css-prefix}-lg {
font-size: (4em / 3);
line-height: (3em / 4);
vertical-align: -15%;
}
.@{fa-css-prefix}-2x { font-size: 2em; }
.@{fa-css-prefix}-3x { font-size: 3em; }
.@{fa-css-prefix}-4x { font-size: 4em; }
.@{fa-css-prefix}-5x { font-size: 5em; }
// Your custom sizes
.@{fa-css-prefix}-6x { font-size: 6em; }
.@{fa-css-prefix}-7x { font-size: 7em; }
.@{fa-css-prefix}-8x { font-size: 8em; }
Either use window.onload
this way
<script>
window.onload = function() {
// ...
}
</script>
or alternatively
<script>
window.onload = functionName;
</script>
(yes, without the parentheses)
Or just put the script at the very bottom of page, right before </body>
. At that point, all HTML DOM elements are ready to be accessed by document
functions.
<body>
...
<script>
functionName();
</script>
</body>
Use dot notation and/or bracket notation to access object properties and for
loops to iterate arrays:
var d, i;
for (i = 0; i < dictionary.data.length; i++) {
d = dictionary.data[i];
alert(d.id + ' ' + d.name);
}
You can also iterate arrays using for
..in
loops; however, properties added to Array.prototype
may show through, and you may not necessarily get array elements in their correct order, or even in any consistent order.
If your in a situation where you need to pass parameters to the function you want to execute after timeout, you can wrap the "named" function in an anonymous function.
i.e. works
setTimeout(function(){ startTimer(p1, p2); }, 1000);
i.e. won't work because it will call the function right away
setTimeout( startTimer(p1, p2), 1000);
The solution of Rohan will fix the problem as the error message will not be shown but the emulator will not use the hardware acceleration and thus be again very slow.
I recommend instead to install the Intel Hardware Accelerated Execution Manager as described here:
Ensure jre is installed.
cd /path/to/jre/bin/folder
As keytool file is present in the bin folder of jre, give path till bin as in the command above.
Then you can do:
keytool -genkey -alias aliaskeyname -keyalg RSA -keystore C:\mykeystore
The additional option -keystore will help you to specify the path where you want the generated self signed certificate.
Just set Label AutoSize property to False. Then the text will be wrapped and you can re-size the control manually to show the text.
You can use guava's Sets.newSetFromMap(map)
to get one. Java 6 also has that method in java.util.Collections
A clean way that allow dynamically setting title or meta description. In example I use ui-router but you can use ngRoute in same way.
var myApp = angular.module('myApp', ['ui.router'])
myApp.config(
['$stateProvider', function($stateProvider) {
$stateProvider.state('product', {
url: '/product/{id}',
templateUrl: 'views/product.html',
resolve: {
meta: ['$rootScope', '$stateParams', function ($rootScope, $stateParams) {
var title = "Product " + $stateParams.id,
description = "Product " + $stateParams.id;
$rootScope.meta = {title: title, description: description};
}]
// Or using server side title and description
meta: ['$rootScope', '$stateParams', '$http', function ($rootScope, $stateParams, $http) {
return $http({method: 'GET', url: 'api/product/ + $stateParams.id'})
.then (function (product) {
$rootScope.meta = {title: product.title, description: product.description};
});
}]
}
controller: 'ProductController'
});
}]);
HTML:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title ng-bind="meta.title + ' | My App'">myApp</title>
...
If you want the logo to take space, you are probably better of floating it left and then moving down the content using margin, sort of like this:
#logo { float: left; margin: 0 10px 10px 20px; } #content { margin: 10px 0 0 10px; }
or whatever margin you want.
Login into the machine as oracle login user id( where oracle is installed)..
Add ORACLE_HOME = <Oracle installation Directory>
in Environment variable
Open a command prompt
Change the directory to %ORACLE_HOME%\bin
type the command sqlplus /nolog
SQL> connect /as sysdba
SQL> alter user SYS identified by "newpassword";
One more check, while oracle installation and database confiuration assistant setup, if you configure any database then you might have given password and checked the same password for all other accounts.. If so, then you try with the password which you have given in your database configuration assistant setup.
Hope this will work for you..
You need to simple use following function.
function GetQueryStringByParameter(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
--- How to Use ---
var QueryString= GetQueryStringByParameter('QueryString');
You get SyntaxError
error exception because Python has no &&
operator. It has and
and &
where the latter one is the correct choice to create boolean expressions on Column
(|
for a logical disjunction and ~
for logical negation).
Condition you created is also invalid because it doesn't consider operator precedence. &
in Python has a higher precedence than ==
so expression has to be parenthesized.
(col("Age") == "") & (col("Survived") == "0")
## Column<b'((Age = ) AND (Survived = 0))'>
On a side note when
function is equivalent to case
expression not WHEN
clause. Still the same rules apply. Conjunction:
df.where((col("foo") > 0) & (col("bar") < 0))
Disjunction:
df.where((col("foo") > 0) | (col("bar") < 0))
You can of course define conditions separately to avoid brackets:
cond1 = col("Age") == ""
cond2 = col("Survived") == "0"
cond1 & cond2
You can continue chaining them like you've done.
results = results.Where (o => o.OrderStatus == OrderStatus.Open);
results = results.Where (o => o.InvoicePaid);
This represents an AND.
You could create a dict comprehension of just the elements whose values are None, and then update back into the original:
tmp = dict((k,"") for k,v in mydict.iteritems() if v is None)
mydict.update(tmp)
Update - did some performance tests
Well, after trying dicts of from 100 to 10,000 items, with varying percentage of None values, the performance of Alex's solution is across-the-board about twice as fast as this solution.
There is a simpler way to get the application data directory with min API 4+. From any Context (e.g. Activity, Application):
getApplicationInfo().dataDir
http://developer.android.com/reference/android/content/Context.html#getApplicationInfo()
This is how i solve it.:
items: [
{ title: 'Dashboard', icon: require('@/assets/icons/sidebar/dashboard.svg') },
{ title: 'Projects', icon: require('@/assets/icons/sidebar/projects.svg') },
{ title: 'Clients', icon: require('@/assets/icons/sidebar/clients.svg') },
],
And on the template part:
<img :src="item.icon" />
Laravel Collection
implements the PHP ArrayAccess
interface (which is why using foreach
is possible in the first place).
If you have the key already you can just use PHP unset
.
I prefer this, because it clearly modifies the collection in place, and is easy to remember.
foreach ($collection as $key => $value) {
unset($collection[$key]);
}
You want to use if statements:
if (liCount === 0) {
setLayoutState('start');
} else if (liCount <= 5) {
setLayoutState('upload1Row');
} else if (liCount <= 10) {
setLayoutState('upload2Rows');
}
$('#UploadList').data('jsp').reinitialise();
Difference between a Spy and a Mock
When Mockito creates a mock – it does so from the Class of a Type, not from an actual instance. The mock simply creates a bare-bones shell instance of the Class, entirely instrumented to track interactions with it. On the other hand, the spy will wrap an existing instance. It will still behave in the same way as the normal instance – the only difference is that it will also be instrumented to track all the interactions with it.
In the following example – we create a mock of the ArrayList class:
@Test
public void whenCreateMock_thenCreated() {
List mockedList = Mockito.mock(ArrayList.class);
mockedList.add("one");
Mockito.verify(mockedList).add("one");
assertEquals(0, mockedList.size());
}
As you can see – adding an element into the mocked list doesn’t actually add anything – it just calls the method with no other side-effect. A spy on the other hand will behave differently – it will actually call the real implementation of the add method and add the element to the underlying list:
@Test
public void whenCreateSpy_thenCreate() {
List spyList = Mockito.spy(new ArrayList());
spyList.add("one");
Mockito.verify(spyList).add("one");
assertEquals(1, spyList.size());
}
Here we can surely say that the real internal method of the object was called because when you call the size() method you get the size as 1, but this size() method isn’t been mocked! So where does 1 come from? The internal real size() method is called as size() isn’t mocked (or stubbed) and hence we can say that the entry was added to the real object.
Source: http://www.baeldung.com/mockito-spy + self notes.
Simply put, the transient java keyword protect fields from the been Serialize as their non-transient fields counter parts.
In this code snippet our abstract class BaseJob implement Serializable interface, we extends from BaseJob but we need not serialize the remote and local data sources; serialize only organizationName and isSynced fields.
public abstract class BaseJob implements Serializable{
public void ShouldRetryRun(){}
}
public class SyncOrganizationJob extends BaseJob {
public String organizationName;
public Boolean isSynced
@Inject transient RemoteDataSource remoteDataSource;
@Inject transient LocalDaoSource localDataSource;
public SyncOrganizationJob(String organizationName) {
super(new
Params(BACKGROUND).groupBy(GROUP).requireNetwork().persist());
this.organizationName = organizationName;
this.isSynced=isSynced;
}
}
You can use setTableId((short)100)
. I think this was changed in Java 5 so that numeric literals assigned to byte or short and within range for the target are automatically assumed to be the target type. That latest J2ME JVMs are derived from Java 4 though.
The RxJS functions need to be specifically imported. An easy way to do this is to import all of its features with import * as Rx from "rxjs/Rx"
Then make sure to access the Observable
class as Rx.Observable
.
you can pass a string representation of the list to json:
import json
str_list = raw_input("Enter in a list: ")
my_list = json.loads(str_list)
user enters in the list as you would in python: [2, 34, 5.6, 90]
Java does not provide a way to manually suggest that a method should be inlined. As @notnoop says in the comments, the inlining is typically done by the JVM at execution time.
try this one
<asp:DropDownList ID="ddList" runat="server">
<asp:ListItem Value="">--Select Month--</asp:ListItem>
<asp:ListItem Value="1">January</asp:ListItem>
<asp:ListItem Value="2">Feburary</asp:ListItem>
...
<asp:ListItem Value="12">December</asp:ListItem>
</asp:DropDownList>
Value should be empty for the default selected listitem, then it works fine
remove href
attribute:
<a id="" onclick="f1()">jhhghj</a>
if link styles are important then:
<a href="javascript:void(f1())">jhhghj</a>
In the .NET world there are two types of CLRs, "full" CLRs and Core CLRs, and these are quite different things.
There are two "full" CLR implementations, the Microsoft native .NET CLR (for Windows) and the Mono CLR (which itself has implementations for Windows, linux and unix (Mac OS X and FreeBSD)). A full CLR is exactly that - everything, pretty much, that you need. As such, "full" CLRs tend to be large in size.
Core CLRs are on the other hand are cut down, and much smaller. Because they are only a core implementation, they are unlikely to have everything you need in them, so with Core CLRs you add feature sets to the CLR that your specific software product uses, using NuGet. There are Core CLR implementations for Windows, linux (various) and unix (Mac OS X and FreeBSD) in the mix. Microsoft have or are refactoring the .NET framework libraries for Core CLR too, to make them more portable for the core context. Given mono's presence on *nix OSs it would be a surprise if the Core CLRs for *nix did not include some mono code base, but only the Mono community and Microsoft could tell us that for sure.
Also, I'd concur with Nico in that Core CLRs are new -- it's at RC2 at the moment I think. I wouldn't depend on it for production code yet.
To answer your question you could delivery your site on linux using Core CLR or Mono, and these are two different ways of doing it. If you want a safe bet right now I'd go with mono on linux, then port if you want to later, to Core.
//The simple version for 10 Characters from the beginning of the string
$string = substr($string,0,10).'...';
Update:
Based on suggestion for checking length (and also ensuring similar lengths on trimmed and untrimmed strings):
$string = (strlen($string) > 13) ? substr($string,0,10).'...' : $string;
So you will get a string of max 13 characters; either 13 (or less) normal characters or 10 characters followed by '...'
Update 2:
Or as function:
function truncate($string, $length, $dots = "...") {
return (strlen($string) > $length) ? substr($string, 0, $length - strlen($dots)) . $dots : $string;
}
Update 3:
It's been a while since I wrote this answer and I don't actually use this code any more. I prefer this function which prevents breaking the string in the middle of a word using the wordwrap
function:
function truncate($string,$length=100,$append="…") {
$string = trim($string);
if(strlen($string) > $length) {
$string = wordwrap($string, $length);
$string = explode("\n", $string, 2);
$string = $string[0] . $append;
}
return $string;
}
For iOS 9 beta 3,4 users. Since the option to view profiles is not viewable do the following from Xcode.
On iOS 9.1+ n iOS 9.2+ go to Settings -> General -> Device Management -> press the Profile -> Press Trust.
You just need to set selector
of button
in your layout file.
<Button
android:id="@+id/button1"
android:background="@drawable/selector_xml_name"
android:layout_width="200dp"
android:layout_height="126dp"
android:text="Hello" />
and done.
Edit
Following is button_effect.xml
file in drawable
directory
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/numpad_button_bg_selected" android:state_selected="true"></item>
<item android:drawable="@drawable/numpad_button_bg_pressed" android:state_pressed="true"></item>
<item android:drawable="@drawable/numpad_button_bg_normal"></item>
</selector>
In this, you can see that there are 3 drawables, you just need to place this button_effect
style to your button
, as i wrote above. You just need to replace selector_xml_name
with button_effect
.
You can actually send it as JSON the following way:
// Build the JSON object to pass parameters
JSONObject jsonObj = new JSONObject();
jsonObj.put("username", username);
jsonObj.put("apikey", apikey);
// Create the POST object and add the parameters
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);
While I don't have a complex comparison as most of these answers do, I would like to share my method for handling this situation. By extending IEnumerable<T>
, you can allow your Team
class to support Linq query extensions, without publicly exposing all the methods and properties of List<T>
.
class Team : IEnumerable<Player>
{
private readonly List<Player> playerList;
public Team()
{
playerList = new List<Player>();
}
public Enumerator GetEnumerator()
{
return playerList.GetEnumerator();
}
...
}
class Player
{
...
}
for people using laravel
<form method="post" ...>
@csrf
@method('put')
...
</form>
-eq
is used to compare integers. Use =
instead.
String name = modelOrderList.get(position).getName(); //get name from List
String text = "<font color='#000000'>" + name + "</font>"; //set Black color of name
/* check API version, according to version call method of Html class */
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.N) {
Log.d(TAG, "onBindViewHolder: if");
holder.textViewName.setText(context.getString(R.string._5687982) + " ");
holder.textViewName.append(Html.fromHtml(text));
} else {
Log.d(TAG, "onBindViewHolder: else");
holder.textViewName.setText("123456" + " "); //set text
holder.textViewName.append(Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY)); //append text into textView
}
Also I think if_exists was used like:
Hi ${userName?if_exists}, How are you?
which will not break if userName is null, the result if null would be:
Hi , How are you?
if_exists is now deprecated and has been replaced with the default operator ! as in
Hi ${userName!}, How are you?
the default operator also supports a default value, such as:
Hi ${userName!"John Doe"}, How are you?
The limitation of execl is that when executing a shell command or any other script that is not in the current working directory, then we have to pass the full path of the command or the script. Example:
execl("/bin/ls", "ls", "-la", NULL);
The workaround to passing the full path of the executable is to use the function execlp, that searches for the file (1st argument of execlp) in those directories pointed by PATH:
execlp("ls", "ls", "-la", NULL);
Java uses managed memory, so the only way you can allocate memory is by using the new
operator, and the only way you can deallocate memory is by relying on the garbage collector.
This memory management whitepaper (PDF) may help explain what's going on.
You can also call System.gc()
to suggest that the garbage collector run immediately. However, the Java Runtime makes the final decision, not your code.
According to the Java documentation,
Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.
A one liner:
perl -pi.back -e 's/<PREF>/ABCD/g;' inputfile
I use a very simple but efficient technique in my app.js ( my entry point ) I define a variable like
let authUser = {};
Then I assign to it from my route page ( like after successful login )
authUser = matchedUser
It May be not the best approach but it fits my needs.
For most styles do this:
var obj = document.createElement('select');
obj.style.width= "100px";
For styles that have hyphens in the name do this instead:
var obj = document.createElement('select');
obj.style["-webkit-background-size"] = "100px"
I'm not sure about HQL, but in JPA you just call the query's setParameter
with the parameter and collection.
Query q = entityManager.createQuery("SELECT p FROM Peron p WHERE name IN (:names)");
q.setParameter("names", names);
where names
is the collection of names you're searching for
Collection<String> names = new ArrayList<String();
names.add("Joe");
names.add("Jane");
names.add("Bob");
Another approach when you have many updates would be to use COALESCE:
UPDATE [DATABASE].[dbo].[TABLE_NAME]
SET
[ABC] = COALESCE(@ABC, [ABC]),
[ABCD] = COALESCE(@ABCD, [ABCD])
I found this question looking to change the timezone in my Django project's settings.py
file to the United Kingdom.
Using the tz database in jfs' solution I found the answer:
TIME_ZONE = 'Europe/London'
You can't add an icon and text because you can't apply a different font to part of a placeholder, however, if you are satisfied with just an icon then it can work. The FontAwesome icons are just characters with a custom font (you can look at the FontAwesome Cheatsheet for the escaped Unicode character in the content
rule. In the less source code it's found in variables.less The challenge would be to swap the fonts when the input is not empty. Combine it with jQuery like this.
<form role="form">
<div class="form-group">
<input type="text" class="form-control empty" id="iconified" placeholder=""/>
</div>
</form>
With this CSS:
input.empty {
font-family: FontAwesome;
font-style: normal;
font-weight: normal;
text-decoration: inherit;
}
And this (simple) jQuery
$('#iconified').on('keyup', function() {
var input = $(this);
if(input.val().length === 0) {
input.addClass('empty');
} else {
input.removeClass('empty');
}
});
The transition between fonts will not be smooth, however.
In the Nuget Package manager search for AspNet.ScriptManager.jQuery instead of jquery. THat way you will not have to set the mappings yourself and the project will work with the click of a simple install.
Or disable the Unobtrusive Validation by adding this line to the Configuration tag of the web.config file in the project.
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
Just move the extra condition into the JOIN ON criteria, this way the existence of b is not required to return a result
SELECT a.* FROM a
LEFT JOIN b ON a.group_id=b.group_id AND b.user_id!=$_SESSION{['user_id']}
WHERE a.keyword LIKE '%".$keyword."%'
GROUP BY group_id