<div class="row" *ngIf="teamMembers?.length > 0">
This checks first if teamMembers
has a value and if teamMembers
doesn't have a value, it doesn't try to access length
of undefined
because the first part of the condition already fails.
From the Rails api on PartialRender:
Rendering the default case
If you're not going to be using any of the options like collections or layouts, you can also use the short-hand defaults of render to render partials.
Examples:
# Instead of <%= render partial: "account" %>
<%= render "account" %>
# Instead of <%= render partial: "account", locals: { account: @buyer } %>
<%= render "account", account: @buyer %>
# @account.to_partial_path returns 'accounts/account', so it can be used to replace:
# <%= render partial: "accounts/account", locals: { account: @account} %>
<%= render @account %>
# @posts is an array of Post instances, so every post record returns 'posts/post' on `to_partial_path`,
# that's why we can replace:
# <%= render partial: "posts/post", collection: @posts %>
<%= render @posts %>
So, you can use pass a local variable size
to render as follows:
<%= render @users, size: 50 %>
and then use it in the _user.html.erb
partial:
<li>
<%= gravatar_for user, size: size %>
<%= link_to user.name, user %>
</li>
Note that size: size
is equivalent to :size => size
.
This can happen if a comma is missing. I ran into it when I had a list of two-tuples, each of which consisted of a string in the first position, and a list in the second. I erroneously omitted the comma after the first component of a tuple in one case, and the interpreter thought I was trying to index the first component.
The PictureBox.Load(string url) method "sets the ImageLocation to the specified URL and displays the image indicated."
There's not a good way to convert it to foreach, because mysql_fetch_array()
just fetches the next result from $result_select
. If you really wanted to foreach, you could do pull all the results into an array first, doing something like the following:
$result_list = array();
while($row = mysql_fetch_array($result_select)) {
result_list[] = $row;
}
foreach($result_list as $row) {
...
}
But there's no good reason I can see to do that - and you still have to use the while loop, which is unavoidable due to how mysql_fetch_array()
works. Why is it so important to use a foreach()?
EDIT: If this is just for learning purposes: you can't convert this to a foreach
. You have to have a pre-existing array to use a foreach()
instead of a while()
, and mysql_fetch_array()
fetches one result per call - there's no pre-existing array for foreach()
to iterate through.
Click the Gradle icon on the right panel, then click on the (root).
Tasks > android > signingReport
Then the Gradle script will execute, and you will see your keys.
create an empty modal box on the current page and below is the ajax call you can see how to fetch the content in result from another html page.
$.ajax({url: "registration.html", success: function(result){
//alert("success"+result);
$("#contentBody").html(result);
$("#myModal").modal('show');
}});
once the call is done you will get the content of the page by the result to then you can insert the code in you modal's content id using.
You can call controller and get the page content and you can show that in your modal.
below is the example of Bootstrap 3 modal in that we are loading content from registration.html page...
index.html
------------------------------------------------
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript">
function loadme(){
//alert("loadig");
$.ajax({url: "registration.html", success: function(result){
//alert("success"+result);
$("#contentBody").html(result);
$("#myModal").modal('show');
}});
}
</script>
</head>
<body>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" onclick="loadme()">Load me</button>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content" >
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body" id="contentBody">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</body>
</html>
registration.html
--------------------
<!DOCTYPE html>
<html>
<style>
body {font-family: Arial, Helvetica, sans-serif;}
form {
border: 3px solid #f1f1f1;
font-family: Arial;
}
.container {
padding: 20px;
background-color: #f1f1f1;
width: 560px;
}
input[type=text], input[type=submit] {
width: 100%;
padding: 12px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}
input[type=checkbox] {
margin-top: 16px;
}
input[type=submit] {
background-color: #4CAF50;
color: white;
border: none;
}
input[type=submit]:hover {
opacity: 0.8;
}
</style>
<body>
<h2>CSS Newsletter</h2>
<form action="/action_page.php">
<div class="container">
<h2>Subscribe to our Newsletter</h2>
<p>Lorem ipsum text about why you should subscribe to our newsletter blabla. Lorem ipsum text about why you should subscribe to our newsletter blabla.</p>
</div>
<div class="container" style="background-color:white">
<input type="text" placeholder="Name" name="name" required>
<input type="text" placeholder="Email address" name="mail" required>
<label>
<input type="checkbox" checked="checked" name="subscribe"> Daily Newsletter
</label>
</div>
<div class="container">
<input type="submit" value="Subscribe">
</div>
</form>
</body>
</html>
In 2018:
var map = new google.maps.Map(...)
map.addListener('tilesloaded', function () { ... })
https://developers.google.com/maps/documentation/javascript/events
If you want to due this in component.ts
HTML:
<button class="class1 class2" (click)="clicked($event)">Click me</button>
Component:
clicked(event) {
event.target.classList.add('class3'); // To ADD
event.target.classList.remove('class1'); // To Remove
event.target.classList.contains('class2'); // To check
event.target.classList.toggle('class4'); // To toggle
}
For more options, examples and browser compatibility visit this link.
I too got same problem.
I was using span with in td like 03/21/2017, by doing this, datatable treated this as string and sorting did not work.
I removed span inside td, and it got fixed. like, 03/21/2017
// UITableViewCell set Identify "Cell"
// UITableView Name is tableReport
UIViewController,UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBOutlet weak var tableReport: UITableView!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableReport.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = "Report Name"
return cell;
}
}
Implementation:
// Promisify setTimeout
const pause = (ms, cb, ...args) =>
new Promise((resolve, reject) => {
setTimeout(async () => {
try {
resolve(await cb?.(...args))
} catch (error) {
reject(error)
}
}, ms)
})
Tests:
// Test 1
pause(1000).then(() => console.log('called'))
// Test 2
pause(1000, (a, b, c) => [a, b, c], 1, 2, 3).then(value => console.log(value))
// Test 3
pause(1000, () => {
throw Error('foo')
}).catch(error => console.error(error))
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat-ws
SELECT CONCAT_WS(" ", `first_name`, `last_name`) AS `whole_name` FROM `users`
{{ uppercase_expression | capitaliseFirst}}
should work
I want to previde another solution for this error, especially for who want to use 32-bit and 64-bit Eclipse in one system.
Eclipse will startup using the JRE/JDK in jre
sub-directory if it exists. (STS or other eclipse based IDE also support this feature...)
The solution is create directory junction using mklink.exe
command which exist in windows vista or newer version (junction.exe offer similar function for Windows 2000/XP)
Open the command line windows and exeute following command:
mklink /j "$ECLIPSE-HOME/jre" "$JDK_or_JRE_home"
Of course, if the Eclipse is for 64-bit Windows, the architecture of JDK/JRE
must be the same.
Assume:
Eclipse for windows x86_64
is installed in d:\devTool\eclipseJDK for windows x64
is installed in C:\Program Files\Java\jdk1.8.0The command for creating the jre
folder will be:
mklink /j "d:\devTool\eclipse\jre" "C:\Program Files\Java\jdk1.8.0"
BTW, delete directory junction will NOT delete any file. If you create a wrong link, you can delete it using file explorer or rmdir
command.
rmdir "d:\devTool\eclipse\jre"
Here's a solution in Python.
#!/usr/bin/env python
def brackets_match(brackets):
stack = []
for char in brackets:
if char == "{" or char == "(" or char == "[":
stack.append(char)
if char == "}":
if stack[-1] == "{":
stack.pop()
else:
return False
elif char == "]":
if stack[-1] == "[":
stack.pop()
else:
return False
elif char == ")":
if stack[-1] == "(":
stack.pop()
else:
return False
if len(stack) == 0:
return True
else:
return False
if __name__ == "__main__":
print(brackets_match("This is testing {([])} if brackets have match."))
Generally, I agree with @kgrittn's advice. Go for it.
But to address your basic question about concat()
: The new function concat()
is useful if you need to deal with null values - and null has neither been ruled out in your question nor in the one you refer to.
If you can rule out null values, the good old (SQL standard) concatenation operator ||
is still the best choice, and @luis' answer is just fine:
SELECT col_a || col_b;
If either of your columns can be null, the result would be null in that case. You could defend with COALESCE
:
SELECT COALESCE(col_a, '') || COALESCE(col_b, '');
But that get tedious quickly with more arguments. That's where concat()
comes in, which never returns null, not even if all arguments are null. Per documentation:
NULL arguments are ignored.
SELECT concat(col_a, col_b);
The remaining corner case for both alternatives is where all input columns are null in which case we still get an empty string ''
, but one might want null instead (at least I would). One possible way:
SELECT CASE
WHEN col_a IS NULL THEN col_b
WHEN col_b IS NULL THEN col_a
ELSE col_a || col_b
END;
This gets more complex with more columns quickly. Again, use concat()
but add a check for the special condition:
SELECT CASE WHEN (col_a, col_b) IS NULL THEN NULL
ELSE concat(col_a, col_b) END;
How does this work?
(col_a, col_b)
is shorthand notation for a row type expression ROW (col_a, col_b)
. And a row type is only null if all columns are null. Detailed explanation:
Also, use concat_ws()
to add separators between elements (ws
for "with separator").
An expression like the one in Kevin's answer:
SELECT $1.zipcode || ' - ' || $1.city || ', ' || $1.state;
is tedious to prepare for null values in PostgreSQL 8.3 (without concat()
). One way (of many):
SELECT COALESCE(
CASE
WHEN $1.zipcode IS NULL THEN $1.city
WHEN $1.city IS NULL THEN $1.zipcode
ELSE $1.zipcode || ' - ' || $1.city
END, '')
|| COALESCE(', ' || $1.state, '');
STABLE
concat()
and concat_ws()
are STABLE
functions, not IMMUTABLE
because they can invoke datatype output functions (like timestamptz_out
) that depend on locale settings.
Explanation by Tom Lane.
This prohibits their direct use in index expressions. If you know that the result is actually immutable in your case, you can work around this with an IMMUTABLE
function wrapper. Example here:
iterator
is a more general concept: any object whose class has a __next__
method (next
in Python 2) and an __iter__
method that does return self
.
Every generator is an iterator, but not vice versa. A generator is built by calling a function that has one or more yield
expressions (yield
statements, in Python 2.5 and earlier), and is an object that meets the previous paragraph's definition of an iterator
.
You may want to use a custom iterator, rather than a generator, when you need a class with somewhat complex state-maintaining behavior, or want to expose other methods besides __next__
(and __iter__
and __init__
). Most often, a generator (sometimes, for sufficiently simple needs, a generator expression) is sufficient, and it's simpler to code because state maintenance (within reasonable limits) is basically "done for you" by the frame getting suspended and resumed.
For example, a generator such as:
def squares(start, stop):
for i in range(start, stop):
yield i * i
generator = squares(a, b)
or the equivalent generator expression (genexp)
generator = (i*i for i in range(a, b))
would take more code to build as a custom iterator:
class Squares(object):
def __init__(self, start, stop):
self.start = start
self.stop = stop
def __iter__(self): return self
def __next__(self): # next in Python 2
if self.start >= self.stop:
raise StopIteration
current = self.start * self.start
self.start += 1
return current
iterator = Squares(a, b)
But, of course, with class Squares
you could easily offer extra methods, i.e.
def current(self):
return self.start
if you have any actual need for such extra functionality in your application.
The accepted answer doesn't cut it because if a user de-selects a row the list is not updated accordingly.
Here is what I suggest instead:
Private Sub CommandButton2_Click()
Dim lItem As Long
For lItem = 0 To ListBox1.ListCount - 1
If ListBox1.Selected(lItem) = True Then
MsgBox(ListBox1.List(lItem))
End If
Next
End Sub
Courtesy of http://www.ozgrid.com/VBA/multi-select-listbox.htm
To convert the private key from PKCS#1 to PKCS#8 with openssl:
# openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in pkcs1.key -out pkcs8.key
That will work as long as you have the PKCS#1 key in PEM (text format) as described in the question.
Here is a method adapted from Jquery 2.1.1 that take a dom element instead of a jquery object (so jquery is not needed). Includes type checks and regex expressions:
function addClass(element, value) {
// Regex terms
var rclass = /[\t\r\n\f]/g,
rnotwhite = (/\S+/g);
var classes,
cur,
curClass,
finalValue,
proceed = typeof value === "string" && value;
if (!proceed) return element;
classes = (value || "").match(rnotwhite) || [];
cur = element.nodeType === 1
&& (element.className
? (" " + element.className + " ").replace(rclass, " ")
: " "
);
if (!cur) return element;
var j = 0;
while ((curClass = classes[j++])) {
if (cur.indexOf(" " + curClass + " ") < 0) {
cur += curClass + " ";
}
}
// only assign if different to avoid unneeded rendering.
finalValue = cur.trim();
if (element.className !== finalValue) {
element.className = finalValue;
}
return element;
};
The reason is that your rule
%.o: %.cpp
...
expects the .cpp file to reside in the same directory as the .o your building. Since test.exe in your case depends on build/widgets/apple.o (etc), make is expecting apple.cpp to be build/widgets/apple.cpp.
You can use VPATH to resolve this:
VPATH = src/widgets
BUILDDIR = build/widgets
$(BUILDDIR)/%.o: %.cpp
...
When attempting to build "build/widgets/apple.o", make will search for apple.cpp in VPATH. Note that the build rule has to use special variables in order to access the actual filename make finds:
$(BUILDDIR)/%.o: %.cpp
$(CC) $< -o $@
Where "$<" expands to the path where make located the first dependency.
Also note that this will build all the .o files in build/widgets. If you want to build the binaries in different directories, you can do something like
build/widgets/%.o: %.cpp
....
build/ui/%.o: %.cpp
....
build/tests/%.o: %.cpp
....
I would recommend that you use "canned command sequences" in order to avoid repeating the actual compiler build rule:
define cc-command
$(CC) $(CFLAGS) $< -o $@
endef
You can then have multiple rules like this:
build1/foo.o build1/bar.o: %.o: %.cpp
$(cc-command)
build2/frotz.o build2/fie.o: %.o: %.cpp
$(cc-command)
Try this:
find . -name "*.pdf" -type f -exec cp {} ./pdfsfolder \;
See also a lot of general hints and useful links at the regex tag details page.
Online tutorials
Quantifiers
*
:greedy, *?
:reluctant, *+
:possessive+
:greedy, +?
:reluctant, ++
:possessive?
:optional (zero-or-one){n,m}
:between n & m, {n,}
:n-or-more, {n}
:exactly n{n}
and {n}?
Character Classes
[...]
: any one character, [^...]
: negated/any character but[^]
matches any one character including newlines javascript[\w-[\d]]
/ [a-z-[qz]]
: set subtraction .net, xml-schema, xpath, JGSoft[\w&&[^\d]]
: set intersection java, ruby 1.9+[[:alpha:]]
:POSIX character classes[^\\D2]
, [^[^0-9]2]
, [^2[^0-9]]
get different results in Java? java\d
:digit, \D
:non-digit\w
:word character, \W
:non-word character\s
:whitespace, \S
:non-whitespace\p{L}, \P{L}
, etc.)Escape Sequences
\h
:space-or-tab, \t
:tab\H
:Non horizontal whitespace character, \V
:Non vertical whitespace character, \N
:Non line feed character pcre php5 java-8\v
:vertical tab, \e
:the escape characterAnchors
^
:start of line/input, \b
:word boundary, and \B
:non-word boundary, $
:end of line/input\A
:start of input, \Z
:end of input php, perl, ruby\z
:the very end of input (\Z
in Python) .net, php, pcre, java, ruby, icu, swift, objective-c\G
:start of match php, perl, ruby(Also see "Flavor-Specific Information ? Java ? The functions in Matcher
")
Groups
(...)
:capture group, (?:)
:non-capture group
\1
:backreference and capture-group reference, $1
:capture group reference
(?i:regex)
mean?(?P<group_name>regexp)
mean?(?>)
:atomic group or independent group, (?|)
:branch reset
regular-expressions.info
(?<groupname>regex)
: Overview and naming rules (Non-Stack Overflow links)(?P<groupname>regex)
python, (?<groupname>regex)
.net, (?<groupname>regex)
perl, (?P<groupname>regex)
and (?<groupname>regex)
phpLookarounds
(?=...)
:positive, (?!...)
:negative(?<=...)
:positive, (?<!...)
:negative (not supported by javascript)Modifiers
flag | modifier | flavors |
---|---|---|
c |
current position | perl |
e |
expression | php perl |
g |
global | most |
i |
case-insensitive | most |
m |
multiline | php perl python javascript .net java |
m |
(non)multiline | ruby |
o |
once | perl ruby |
S |
study | php |
s |
single line | unsupported: javascript (workaround) | ruby |
U |
ungreedy | php r |
u |
unicode | most |
x |
whitespace-extended | most |
y |
sticky ? | javascript |
Other:
|
:alternation (OR) operator, .
:any character, [.]
:literal dot character(*PRUNE)
, (*SKIP)
, (*FAIL)
and (*F)
(*BSR_ANYCRLF)
(?R)
, (?0)
and (?1)
, (?-1)
, (?&groupname)
Common Tasks
{...}
Advanced Regex-Fu
(?!a)a
this
except in contexts A, B and CFlavor-Specific Information
(Except for those marked with *
, this section contains non-Stack Overflow links.)
java.util.regex.Matcher
:
matches()
): The match must be anchored to both input-start and -endfind()
): A match may be anywhere in the input string (substrings)lookingAt()
: The match must be anchored to input-start onlyjava.lang.String
functions that accept regular expressions: matches(s)
, replaceAll(s,s)
, replaceFirst(s,s)
, split(s)
, split(s,i)
java.util.regex
preg_match
search
vs match
, how-toregex
, struct regex::Regex
regexp
commandGeneral information
(Links marked with *
are non-Stack Overflow links.)
Examples of regex that can cause regex engine to fail
Tools: Testers and Explainers
(This section contains non-Stack Overflow links.)
If your variable is an argument, you can simply use %~dpn
(for paths) or %~n
(for names only) followed by the argument number, so you don't have to worry for varying extension lengths.
For instance %~dpn0
will return the path of the batch file without its extension, %~dpn1
will be %1
without extension, etc.
Whereas %~n0
will return the name of the batch file without its extension, %~n1
will be %1
without path and extension, etc.
I had the same issue in a Windows Service. All keys where in the right place in the registry. The build of the service was done for x86 and I still got the exception. I found out about CorFlags.exe
Run this on your service.exe
without flags to verify if you run under 32 bit. If not run it with the flag /32BIT+ /Force
(Force only for signed assemblies)
If you have UAC turned you can get the following error: corflags : error CF001 : Could not open file for writing
Give the user full control on the assemblies.
And if you wanna work with data object, this two implements very important:
public class User implements Parcelable
check more in here
The first part:
.Cells(.Rows.Count,"A")
Sends you to the bottom row of column A, which you knew already.
The End function starts at a cell and then, depending on the direction you tell it, goes that direction until it reaches the edge of a group of cells that have text. Meaning, if you have text in cells C4:E4 and you type:
Sheet1.Cells(4,"C").End(xlToRight).Select
The program will select E4, the rightmost cell with text in it.
In your case, the code is spitting out the row of the very last cell with text in it in column A. Does that help?
I tend to underscore fields with _ so don't really ever need to use this. Also R# tends to refactor them away anyway...
Try this instead:
$journalName = preg_replace('/\s+/', '_', $journalName);
Explanation: you are most likely seeing whitespace, not just plain spaces (there is a difference).
If I understand correctly, you want to know how to convert bytes encoded as a hex string to its form as an ASCII text, like "537461636B" would be converted to "Stack", in such case then the following code should solve your problem.
Have not run any benchmarks but I assume it is not the peak of efficiency.
static char ByteToAscii(const char *input) {
char singleChar, out;
memcpy(&singleChar, input, 2);
sprintf(&out, "%c", (int)strtol(&singleChar, NULL, 16));
return out;
}
int HexStringToAscii(const char *input, unsigned int length,
char **output) {
int mIndex, sIndex = 0;
char buffer[length];
for (mIndex = 0; mIndex < length; mIndex++) {
sIndex = mIndex * 2;
char b = ByteToAscii(&input[sIndex]);
memcpy(&buffer[mIndex], &b, 1);
}
*output = strdup(buffer);
return 0;
}
There is also a constructor overload for List that will work... But I guess this would required a strong typed array.
//public List(IEnumerable<T> collection)
var intArray = new[] { 1, 2, 3, 4, 5 };
var list = new List<int>(intArray);
... for Array class
var intArray = Array.CreateInstance(typeof(int), 5);
for (int i = 0; i < 5; i++)
intArray.SetValue(i, i);
var list = new List<int>((int[])intArray);
One simple trick we use is to just call git add --all
twice in a row.
For example, our Windows 7 commit script calls:
$ git add --all
$ git add --all
The first add treats the link as text and adds the folders for delete.
The second add traverses the link correctly and undoes the delete by restoring the files.
It's less elegant than some of the other proposed solutions but it is a simple fix to some of our legacy environments that got symlinks added.
Joe Kington's excellent answer is already 4 years old,
Matplotlib has incrementally changed (in particular, the introduction
of the cycler
module) and the new major release, Matplotlib 2.0.x,
has introduced stylistic differences that are important from the point
of view of the colors used by default.
The color of individual lines (as well as the color of different plot
elements, e.g., markers in scatter plots) is controlled by the color
keyword argument,
plt.plot(x, y, color=my_color)
my_color
is either
(0.,0.5,0.5)
),"#008080"
(RGB) or "#008080A0"
),"k"
for black, possible values in "bgrcmykw"
),"teal"
) --- aka HTML color name (in the docs also X11/CSS4 color name),'xkcd:'
(e.g., 'xkcd:barbie pink'
),'T10'
categorical palette, (e.g., 'tab:blue'
, 'tab:olive'
),"C3"
, i.e., the letter "C"
followed by a single digit in "0-9"
).By default, different lines are plotted using different colors, that are defined by default and are used in a cyclic manner (hence the name color cycle).
The color cycle is a property of the axes
object, and in older
releases was simply a sequence of valid color names (by default a
string of one character color names, "bgrcmyk"
) and you could set it
as in
my_ax.set_color_cycle(['kbkykrkg'])
(as noted in a comment this API has been deprecated, more on this later).
In Matplotlib 2.0 the default color cycle is ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"]
, the Vega category10 palette.
(the image is a screenshot from https://vega.github.io/vega/docs/schemes/)
The following code shows that the color cycle notion has been deprecated
In [1]: from matplotlib import rc_params
In [2]: rc_params()['axes.color_cycle']
/home/boffi/lib/miniconda3/lib/python3.6/site-packages/matplotlib/__init__.py:938: UserWarning: axes.color_cycle is deprecated and replaced with axes.prop_cycle; please use the latter.
warnings.warn(self.msg_depr % (key, alt_key))
Out[2]:
['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
'#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']
Now the relevant property is the 'axes.prop_cycle'
In [3]: rc_params()['axes.prop_cycle']
Out[3]: cycler('color', ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'])
Previously, the color_cycle
was a generic sequence of valid color
denominations, now by default it is a cycler
object containing a
label ('color'
) and a sequence of valid color denominations. The
step forward with respect to the previous interface is that it is
possible to cycle not only on the color of lines but also on other
line attributes, e.g.,
In [5]: from cycler import cycler
In [6]: new_prop_cycle = cycler('color', ['k', 'r']) * cycler('linewidth', [1., 1.5, 2.])
In [7]: for kwargs in new_prop_cycle: print(kwargs)
{'color': 'k', 'linewidth': 1.0}
{'color': 'k', 'linewidth': 1.5}
{'color': 'k', 'linewidth': 2.0}
{'color': 'r', 'linewidth': 1.0}
{'color': 'r', 'linewidth': 1.5}
{'color': 'r', 'linewidth': 2.0}
As you have seen, the cycler
objects are composable and when you iterate on a composed cycler
what you get, at each iteration, is a dictionary of keyword arguments for plt.plot
.
You can use the new defaults on a per axes
object ratio,
my_ax.set_prop_cycle(new_prop_cycle)
or you can install temporarily the new default
plt.rc('axes', prop_cycle=new_prop_cycle)
or change altogether the default editing your .matplotlibrc
file.
Last possibility, use a context manager
with plt.rc_context({'axes.prop_cycle': new_prop_cycle}):
...
to have the new cycler
used in a group of different plots, reverting to defaults at the end of the context.
The doc string of the cycler()
function is useful, but the (not so much) gory details about the cycler
module and the cycler()
function, as well as examples, can be found in the fine docs.
Here's a plain Javascript way of doing toggle:
<script>
var toggle = function() {
var mydiv = document.getElementById('newpost');
if (mydiv.style.display === 'block' || mydiv.style.display === '')
mydiv.style.display = 'none';
else
mydiv.style.display = 'block'
}
</script>
<div id="newpost">asdf</div>
<input type="button" value="btn" onclick="toggle();">
This is a basic example of how to get the creation date of a file in Java
, using BasicFileAttributes
class:
Path path = Paths.get("C:\\Users\\jorgesys\\workspaceJava\\myfile.txt");
BasicFileAttributes attr;
try {
attr = Files.readAttributes(path, BasicFileAttributes.class);
System.out.println("Creation date: " + attr.creationTime());
//System.out.println("Last access date: " + attr.lastAccessTime());
//System.out.println("Last modified date: " + attr.lastModifiedTime());
} catch (IOException e) {
System.out.println("oops error! " + e.getMessage());
}
To have code which looks like this:
List<Item> items;
...
for (Item item : In.reverse(items))
{
...
}
Put this code into a file called "In.java":
import java.util.*;
public enum In {;
public static final <T> Iterable<T> reverse(final List<T> list) {
return new ListReverseIterable<T>(list);
}
class ListReverseIterable<T> implements Iterable<T> {
private final List<T> mList;
public ListReverseIterable(final List<T> list) {
mList = list;
}
public Iterator<T> iterator() {
return new Iterator<T>() {
final ListIterator<T> it = mList.listIterator(mList.size());
public boolean hasNext() {
return it.hasPrevious();
}
public T next() {
return it.previous();
}
public void remove() {
it.remove();
}
};
}
}
}
In case you want to handle intent on opened activity, you can use PendintIntent (Complete steps below):
public class SMSReciver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
try {
if (senderNum.contains("MOB_NUMBER")) {
Toast.makeText(context,"",Toast.LENGTH_SHORT).show();
Intent intentCall = new Intent(context, MainActivity.class);
intentCall.putExtra("message", currentMessage.getMessageBody());
PendingIntent pendingIntent= PendingIntent.getActivity(context, 0, intentCall, PendingIntent.FLAG_UPDATE_CURRENT);
pendingIntent.send();
}
} catch (Exception e) {
}
}
}
} catch (Exception e) {
}
}
}
manifest:
<activity android:name=".MainActivity"
android:launchMode="singleTask"/>
<receiver android:name=".SMSReciver">
<intent-filter android:priority="1000">
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
onNewIntent:
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Toast.makeText(this, "onNewIntent", Toast.LENGTH_SHORT).show();
onSMSReceived(intent.getStringExtra("message"));
}
permissions:
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
You need also $sce.trustAsResourceUrl
or it won't open the website inside the iframe:
angular.module('myApp', [])_x000D_
.controller('dummy', ['$scope', '$sce', function ($scope, $sce) {_x000D_
_x000D_
$scope.url = $sce.trustAsResourceUrl('https://www.angularjs.org');_x000D_
_x000D_
$scope.changeIt = function () {_x000D_
$scope.url = $sce.trustAsResourceUrl('https://docs.angularjs.org/tutorial');_x000D_
}_x000D_
}]);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="dummy">_x000D_
<iframe ng-src="{{url}}" width="300" height="200"></iframe>_x000D_
<br>_x000D_
<button ng-click="changeIt()">Change it</button>_x000D_
</div>
_x000D_
You need to extract the number from the string, and pass it into the Date constructor
:
var x = [{
"id": 1,
"start": "\/Date(1238540400000)\/"
}, {
"id": 2,
"start": "\/Date(1238626800000)\/"
}];
var myDate = new Date(x[0].start.match(/\d+/)[0] * 1);
The parts are:
x[0].start - get the string from the JSON
x[0].start.match(/\d+/)[0] - extract the numeric part
x[0].start.match(/\d+/)[0] * 1 - convert it to a numeric type
new Date(x[0].start.match(/\d+/)[0] * 1)) - Create a date object
Just in case anyone still stumbles upon this old question:
The code was theoretically almost correct in a sense, the problem was the use of $('this') instead of $(this), therefore telling jQuery to look for a tag.
$(document).ready(function(){
$("#frame").click(function () {
$(this).load("http://www.google.com/");
});
});
The script itself woudln't work as it is right now though because the load() function itself is an AJAX function, and google does not seem to specifically allow the use of loading this page with AJAX, but this method should be easy to use in order to load pages from your own domain by using relative paths.
I found the simplest way is just to close the window and run a module/script to reopen the shell.
var string = string.split(",");
If you prefer simplicity and more control on SQL queries then I would suggest going with Spring Data/ Spring JDBC.
Its good amount of learning curve in JPA and sometimes difficult to debug issues. On the other hand, while you have full control over SQL, it becomes much easier to optimize query and improve performance. You can easily share your SQL with DBA or someone who has a better understanding of Database.
I think something like:
function ReplaceContentInContainer(klass,content) {
var elems = document.getElementsByTagName('*');
for (i in elems){
if(elems[i].getAttribute('class') == klass || elems[i].getAttribute('className') == klass){
elems[i].innerHTML = content;
}
}
}
would work
Have you gone through google's geocoding api. The following link shall help you get started: http://code.google.com/apis/maps/documentation/geocoding/#GeocodingRequests
No you can't set them as single one for example if you have div{ border-top: 2px solid red; border-right: 2px solid red; border-bottom: 2px solid red; border-left: 2px solid red; } same properties for all fours then you can set them in single line
div{border:2px solid red;}
First change the xml, mark your second activity as DEFAULT
<activity android:name=".AddNewActivity" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Now you can initiate this activity using StartActivity method.
2018 10 25. Update.
Notepad++ 7.5.8 does not have plugin manager by default. You have to download plugins manually.
Keep in mind, if you use 64 bit version of Notepad++, you should also use 64 bit version of plugin. I had a similar issue here.
My answer is just a conceptual one without any source code. It might be useful for some readers like myself to understand.
It depends on your initial approach on how you architecture your app. There are basically two approaches.
You create one activity (base activity) and all the other views and screens will be fragments. That base activity contains the implementation for Drawer and Coordinator Layouts. It is actually my preferred way of doing because having small self-contained fragments will make app development easier and smoother.
If you have started your app development with activities, one for each screen , then you will probably create base activity, and all other activity extends from it. The base activity will contain the code for drawer and coordinator implementation. Any activity that needs drawer implementation can extend from base activity.
I would personally prefer avoiding to use fragments and activities mixed without any organizing. That makes the development more difficult and get you stuck eventually. If you have done it, refactor your code.
Random r = new Random();
int i1 = r.nextInt(80 - 65) + 65;
This gives a random integer between 65 (inclusive) and 80 (exclusive), one of 65,66,...,78,79
.
require(TSDT)
c(1,3,11) %nin% 1:10
# [1] FALSE FALSE TRUE
For more information, you can refer to: https://cran.r-project.org/web/packages/TSDT/TSDT.pdf
If you want to show all the rows set like bellow
pd.options.display.max_rows = None
If you want to show all columns set like bellow
pd.options.display.max_columns = None
If the code should be simple, then you probably asking for C example based on traditional BSD sockets. Solutions like boost::asio
are imho quite complicated when it comes to short and simple "hello world" example.
To compile examples you mentioned you must make simple fixes, because you are compiling under C++ compiler. I'm referring to following files:
http://www.linuxhowtos.org/data/6/server.c
http://www.linuxhowtos.org/data/6/client.c
from: http://www.linuxhowtos.org/C_C++/socket.htm
Add following includes to both files:
#include <cstdlib>
#include <cstring>
#include <unistd.h>
In client.c, change the line:
if (connect(sockfd,&serv_addr,sizeof(serv_addr)) < 0)
{ ... }
to:
if (connect(sockfd,(const sockaddr*)&serv_addr,sizeof(serv_addr)) < 0)
{ ... }
As you can see in C++ an explicit cast is needed.
I use Spring Boot, my solution to the problem was
"src/main/resources/myfile.extension"
Hope it helps someone.
It works fine for my v. 5.4.5 of Notepad++. I just select multiple lines and press TAB.
If you want TAB to be replaced by SPACE than you need to go Settings > Preferences and select Edit Components tab. Next check Replace by spaces check box in Tab Setting section.
Update: In a newer version of Notepad++ this option is in Settings > Preferences > Languaage section.
The typical usage of shifting a variable and assigning back to the variable can be rewritten with shorthand operators <<=, >>=, or >>>=, also known in the spec as Compound Assignment Operators.
For example,
i >>= 2
produces the same result as
i = i >> 2
The choice of when to use a surrogate primary key as opposed to a natural key is tricky. Answers such as, always or never, are rarely useful. I find that it depends on the situation.
As an example, I have the following tables:
CREATE TABLE toll_booths (
id INTEGER NOT NULL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
...
UNIQUE(name)
)
CREATE TABLE cars (
vin VARCHAR(17) NOT NULL PRIMARY KEY,
license_plate VARCHAR(10) NOT NULL,
...
UNIQUE(license_plate)
)
CREATE TABLE drive_through (
id INTEGER NOT NULL PRIMARY KEY,
toll_booth_id INTEGER NOT NULL REFERENCES toll_booths(id),
vin VARCHAR(17) NOT NULL REFERENCES cars(vin),
at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
amount NUMERIC(10,4) NOT NULL,
...
UNIQUE(toll_booth_id, vin)
)
We have two entity tables (toll_booths
and cars
) and a transaction table (drive_through
). The toll_booth
table uses a surrogate key because it has no natural attribute that is not guaranteed to change (the name can easily be changed). The cars
table uses a natural primary key because it has a non-changing unique identifier (vin
). The drive_through
transaction table uses a surrogate key for easy identification, but also has a unique constraint on the attributes that are guaranteed to be unique at the time the record is inserted.
http://database-programmer.blogspot.com has some great articles on this particular subject.
I know its too longtime to reply but just as an information purpose for future readers:
WebRequest
System.Object
System.MarshalByRefObject
System.Net.WebRequest
The WebRequest
is an abstract base class. So you actually don't use it directly. You use it through it derived classes - HttpWebRequest
and FileWebRequest
.
You use Create method of WebRequest
to create an instance of WebRequest
. GetResponseStream
returns data stream
.
There are also FileWebRequest
and FtpWebRequest
classes that inherit
from WebRequest
. Normally, you would use WebRequest
to, well, make a request and convert the return to either HttpWebRequest
, FileWebRequest
or FtpWebRequest
, depend on your request. Below is an example:
Example:
var _request = (HttpWebRequest)WebRequest.Create("http://stackverflow.com");
var _response = (HttpWebResponse)_request.GetResponse();
WebClient
System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Net.WebClient
WebClient
provides common operations to sending
and receiving
data from a resource identified by a URI
. Simply, it’s a higher-level abstraction of HttpWebRequest
. This ‘common operations’ is what differentiate WebClient
from HttpWebRequest
, as also shown in the sample below:
Example:
var _client = new WebClient();
var _stackContent = _client.DownloadString("http://stackverflow.com");
There are also DownloadData
and DownloadFile
operations under WebClient
instance. These common operations also simplify code of what we would normally do with HttpWebRequest
. Using HttpWebRequest
, we have to get the response of our request, instantiate StreamReader
to read the response and finally, convert the result to whatever type we expect. With WebClient
, we just simply call DownloadData, DownloadFile or DownloadString
.
However, keep in mind that WebClient.DownloadString
doesn’t consider the encoding
of the resource you requesting. So, you would probably end up receiving weird characters if you don’t specify and encoding.
NOTE: Basically "WebClient takes few lines of code as compared to Webrequest"
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class ConcurrentHashSet<E> extends AbstractSet<E> implements Set<E>{
private final ConcurrentMap<E, Object> theMap;
private static final Object dummy = new Object();
public ConcurrentHashSet(){
theMap = new ConcurrentHashMap<E, Object>();
}
@Override
public int size() {
return theMap.size();
}
@Override
public Iterator<E> iterator(){
return theMap.keySet().iterator();
}
@Override
public boolean isEmpty(){
return theMap.isEmpty();
}
@Override
public boolean add(final E o){
return theMap.put(o, ConcurrentHashSet.dummy) == null;
}
@Override
public boolean contains(final Object o){
return theMap.containsKey(o);
}
@Override
public void clear(){
theMap.clear();
}
@Override
public boolean remove(final Object o){
return theMap.remove(o) == ConcurrentHashSet.dummy;
}
public boolean addIfAbsent(final E o){
Object obj = theMap.putIfAbsent(o, ConcurrentHashSet.dummy);
return obj == null;
}
}
LINUX
I always had issues while trying paths and the spec parameter.
Therefore I went for the online solution that will update automatically the JSON on Swagger without having to reimport.
If you use npm to start your swagger editor you should add a symbolic link of your json file.
cd /path/to/your/swaggerui
where index.html
is.
ln -s /path/to/your/generated/swagger.json
You may encounter cache problems. The quick way to solve this was to add a token at the end of my url...
window.onload = function() {
var noCache = Math.floor((Math.random() * 1000000) + 1);
// Build a system
const editor = SwaggerEditorBundle({
url: "http://localhost:3001/swagger.json?"+noCache,
dom_id: '#swagger-editor',
layout: 'StandaloneLayout',
presets: [
SwaggerEditorStandalonePreset
]
})
window.editor = editor
}
You can create a new MongoDB ObjectId
like this using mongoose:
var mongoose = require('mongoose');
var newId = new mongoose.mongo.ObjectId('56cb91bdc3464f14678934ca');
// or leave the id string blank to generate an id with a new hex identifier
var newId2 = new mongoose.mongo.ObjectId();
In visual studio 2012, When I published the solution mistakenly with 'debug' option I got this exception. With 'release' option it never occurred. Hope it helps.
It is possible to insert an image in a Google Spreadsheet using Google Apps Script. However, the image should have been hosted publicly over internet. At present, it is not possible to insert private images from Google Drive.
You can use following code to insert an image through script.
function insertImageOnSpreadsheet() {
var SPREADSHEET_URL = 'INSERT_SPREADSHEET_URL_HERE';
// Name of the specific sheet in the spreadsheet.
var SHEET_NAME = 'INSERT_SHEET_NAME_HERE';
var ss = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
var sheet = ss.getSheetByName(SHEET_NAME);
var response = UrlFetchApp.fetch(
'https://developers.google.com/adwords/scripts/images/reports.png');
var binaryData = response.getContent();
// Insert the image in cell A1.
var blob = Utilities.newBlob(binaryData, 'image/png', 'MyImageName');
sheet.insertImage(blob, 1, 1);
}
Above example has been copied from this link. Check noogui's reply for details.
In case you need to insert image from Google Drive, please check this link for current updates.
I don't think you can ever be sure on the next id, because someone might insert a new row just after you asked for the next id. You would at least need a transaction, and if I'm not mistaken you can only get the actual id used after inserting it, at least that is the common way of handling it -- see http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
I have tried all these solutions, a big margin will be added to <html>
element automatically when I use the code below:
.clearfix:after {
visibility: hidden;
display: block;
content: ".";
clear: both;
height: 0;
}
Finally, I solved the margin problem by adding font-size: 0;
to the above CSS.
From the firebug site http://getfirebug.com/logging/
Calling console.dir(object) will log an interactive listing of an object's properties, like > a miniature version of the DOM tab.
I have the same issue because I set the NODE_ENV=production
while building Docker. Then I add one more npm install --only=dev
. Everything works fine. I need the devDependencies for building TypeSciprt modules
RUN npm install
RUN npm install --only=dev
I guess if you are using WSL with GUI, then you could just try
sudo /etc/init.d/docker start
Summary
Floating point arithmetic is exact, unfortunately, it doesn't match up well with our usual base-10 number representation, so it turns out we are often giving it input that is slightly off from what we wrote.
Even simple numbers like 0.01, 0.02, 0.03, 0.04 ... 0.24 are not representable exactly as binary fractions. If you count up 0.01, .02, .03 ..., not until you get to 0.25 will you get the first fraction representable in base2. If you tried that using FP, your 0.01 would have been slightly off, so the only way to add 25 of them up to a nice exact 0.25 would have required a long chain of causality involving guard bits and rounding. It's hard to predict so we throw up our hands and say "FP is inexact", but that's not really true.
We constantly give the FP hardware something that seems simple in base 10 but is a repeating fraction in base 2.
How did this happen?
When we write in decimal, every fraction (specifically, every terminating decimal) is a rational number of the form
a / (2n x 5m)
In binary, we only get the 2n term, that is:
a / 2n
So in decimal, we can't represent 1/3. Because base 10 includes 2 as a prime factor, every number we can write as a binary fraction also can be written as a base 10 fraction. However, hardly anything we write as a base10 fraction is representable in binary. In the range from 0.01, 0.02, 0.03 ... 0.99, only three numbers can be represented in our FP format: 0.25, 0.50, and 0.75, because they are 1/4, 1/2, and 3/4, all numbers with a prime factor using only the 2n term.
In base10 we can't represent 1/3. But in binary, we can't do 1/10 or 1/3.
So while every binary fraction can be written in decimal, the reverse is not true. And in fact most decimal fractions repeat in binary.
Dealing with it
Developers are usually instructed to do < epsilon comparisons, better advice might be to round to integral values (in the C library: round() and roundf(), i.e., stay in the FP format) and then compare. Rounding to a specific decimal fraction length solves most problems with output.
Also, on real number-crunching problems (the problems that FP was invented for on early, frightfully expensive computers) the physical constants of the universe and all other measurements are only known to a relatively small number of significant figures, so the entire problem space was "inexact" anyway. FP "accuracy" isn't a problem in this kind of application.
The whole issue really arises when people try to use FP for bean counting. It does work for that, but only if you stick to integral values, which kind of defeats the point of using it. This is why we have all those decimal fraction software libraries.
I love the Pizza answer by Chris, because it describes the actual problem, not just the usual handwaving about "inaccuracy". If FP were simply "inaccurate", we could fix that and would have done it decades ago. The reason we haven't is because the FP format is compact and fast and it's the best way to crunch a lot of numbers. Also, it's a legacy from the space age and arms race and early attempts to solve big problems with very slow computers using small memory systems. (Sometimes, individual magnetic cores for 1-bit storage, but that's another story.)
Conclusion
If you are just counting beans at a bank, software solutions that use decimal string representations in the first place work perfectly well. But you can't do quantum chromodynamics or aerodynamics that way.
I found the following in the site.css generated by VS2013
/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
max-width: 280px;
}
To override this behavior in a specific element, add the following...
style="max-width: none;"
For example:
<div class="col-md-6">
<textarea style="max-width: none;"
class="form-control"
placeholder="a col-md-6 multiline input box" />
</div>
Your data class doesn't match the JSON object. Use this instead:
[DataContract]
public class GoogleSearchResults
{
[DataMember]
public ResponseData responseData { get; set; }
}
[DataContract]
public class ResponseData
{
[DataMember]
public IEnumerable<Results> results { get; set; }
}
[DataContract]
public class Results
{
[DataMember]
public string unescapedUrl { get; set; }
[DataMember]
public string url { get; set; }
[DataMember]
public string visibleUrl { get; set; }
[DataMember]
public string cacheUrl { get; set; }
[DataMember]
public string title { get; set; }
[DataMember]
public string titleNoFormatting { get; set; }
[DataMember]
public string content { get; set; }
}
Also, you don't have to instantiate the class to get its type for deserialization:
public static T Deserialise<T>(string json)
{
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
var serialiser = new DataContractJsonSerializer(typeof(T));
return (T)serialiser.ReadObject(ms);
}
}
There are quite a bit of answers to handle it client side, but you can change the output server side if you desired.
There are a few ways to approach this, I'll start with the basics. You'll have to subclass the JsonResult class and override the ExecuteResult method. From there you can take a few different approaches to change the serialization.
Approach 1: The default implementation uses the JsonScriptSerializer. If you take a look at the documentation, you can use the RegisterConverters method to add custom JavaScriptConverters. There are a few problems with this though: The JavaScriptConverter serializes to a dictionary, that is it takes an object and serializes to a Json dictionary. In order to make the object serialize to a string it requires a bit of hackery, see post. This particular hack will also escape the string.
public class CustomJsonResult : JsonResult
{
private const string _dateFormat = "yyyy-MM-dd HH:mm:ss";
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
HttpResponseBase response = context.HttpContext.Response;
if (!String.IsNullOrEmpty(ContentType))
{
response.ContentType = ContentType;
}
else
{
response.ContentType = "application/json";
}
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data != null)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
// Use your custom JavaScriptConverter subclass here.
serializer.RegisterConverters(new JavascriptConverter[] { new CustomConverter });
response.Write(serializer.Serialize(Data));
}
}
}
Approach 2 (recommended): The second approach is to start with the overridden JsonResult and go with another Json serializer, in my case the Json.NET serializer. This doesn't require the hackery of approach 1. Here is my implementation of the JsonResult subclass:
public class CustomJsonResult : JsonResult
{
private const string _dateFormat = "yyyy-MM-dd HH:mm:ss";
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
HttpResponseBase response = context.HttpContext.Response;
if (!String.IsNullOrEmpty(ContentType))
{
response.ContentType = ContentType;
}
else
{
response.ContentType = "application/json";
}
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data != null)
{
// Using Json.NET serializer
var isoConvert = new IsoDateTimeConverter();
isoConvert.DateTimeFormat = _dateFormat;
response.Write(JsonConvert.SerializeObject(Data, isoConvert));
}
}
}
Usage Example:
[HttpGet]
public ActionResult Index() {
return new CustomJsonResult { Data = new { users=db.Users.ToList(); } };
}
Additional credits: James Newton-King
You need to be aware that month is zero based so when you do the getMonth you will need to add 1. In the example below we have to add 1 to Januaray as 1 and not 0
Calendar c = Calendar.getInstance();
c.set(2011, 2, 1);
c.add(Calendar.MONTH, -1);
int month = c.get(Calendar.MONTH) + 1;
assertEquals(1, month);
If you have the IDs stored in a temp table (which can be done by some C# function or simple SQL) then the problem becomes easy and doable in SQL.
select "all exist"
where (select case when count(distinct t.id) = (select count(distinct id) from #products) then "true" else "false" end
from ProductTable t, #products p
where t.id = p.id) = "true"
This will return "all exists" when all the products in #products
exist in the target table (ProductTable
) and will not return a row if the above is not true.
If you are not willing to write to a temp table, then you need to feed in some parameter for the number of products you are attempting to find, and replace the temp table with an 'in'; clause so the subquery looks like this:
SELECT "All Exist"
WHERE(
SELECT case when count(distinct t.id) = @ProductCount then "true" else "false"
FROM ProductTable t
WHERE t.id in (1,100,10,20) -- example IDs
) = "true"
I was need to save the start position and the end position. this work to me:
$('.object').draggable({
stop: function(ev, ui){
var position = ui.position;
var originalPosition = ui.originalPosition;
}
});
You want to add libraries to your project and in doing so you have two options as you yourself identified:
Compile-time libraries are libraries which is needed to compile your application. They are not included when your application is assembled (e.g., into a war-file). Libraries of this kind must be provided by the container running your project.
This is useful in situation when you want to vary API and implementation, or when the library is supplied by the container (which is typically the case with javax.servlet which is required to compile but provided by the application server, e.g., Apache Tomcat).
Run-time libraries are libraries which is needed both for compilation and when running your project. This is probably what you want in most cases. If for instance your project is packaged into a war/ear, then these libraries will be included in the package.
As for the other alernatives you have either global libraries using Library Manager
or jdk libraries. The latter is simply your regular java libraries, while the former is just a way for your to store a set of libraries under a common name. For all your future projects, instead of manually assigning the libraries you can simply select to import them from your Library Manager
.
React-redux 'connect' function accepts two arguments first is mapStateToProps and second is mapDispatchToProps check below ex.
export default connect(mapStateToProps, mapDispatchToProps)(Index);
`
If we don't want retrieve state from redux then we set null instead of mapStateToProps.
export default connect(null, mapDispatchToProps)(Index);
To make sure it does not fail for string
, date
and timestamp
columns:
import pyspark.sql.functions as F
def count_missings(spark_df,sort=True):
"""
Counts number of nulls and nans in each column
"""
df = spark_df.select([F.count(F.when(F.isnan(c) | F.isnull(c), c)).alias(c) for (c,c_type) in spark_df.dtypes if c_type not in ('timestamp', 'string', 'date')]).toPandas()
if len(df) == 0:
print("There are no any missing values!")
return None
if sort:
return df.rename(index={0: 'count'}).T.sort_values("count",ascending=False)
return df
If you want to see the columns sorted based on the number of nans and nulls in descending:
count_missings(spark_df)
# | Col_A | 10 |
# | Col_C | 2 |
# | Col_B | 1 |
If you don't want ordering and see them as a single row:
count_missings(spark_df, False)
# | Col_A | Col_B | Col_C |
# | 10 | 1 | 2 |
I also encountered the same problem. I solve the problem by executing the following sql:
ALTER ${table} ROW_FORMAT=COMPRESSED;
But, I think u should know about the Row Storage.
There are two kinds of columns: variable-length column(such as VARCHAR, VARBINARY, and BLOB and TEXT types) and fixed-length column. They are stored in different types of pages.
Variable-length columns are an exception to this rule. Columns such as BLOB and VARCHAR that are too long to fit on a B-tree page are stored on separately allocated disk pages called overflow pages. We call such columns off-page columns. The values of these columns are stored in singly-linked lists of overflow pages, and each such column has its own list of one or more overflow pages. In some cases, all or a prefix of the long column value is stored in the B-tree, to avoid wasting storage and eliminating the need to read a separate page.
and when purpose of setting ROW_FORMAT is
When a table is created with ROW_FORMAT=DYNAMIC or ROW_FORMAT=COMPRESSED, InnoDB can store long variable-length column values (for VARCHAR, VARBINARY, and BLOB and TEXT types) fully off-page, with the clustered index record containing only a 20-byte pointer to the overflow page.
Wanna know more about DYNAMIC and COMPRESSED Row Formats
Based on quentinadam's answer
Swift 5.1
// size refers to the width/height of your tile images, by default is 256.0
// Seems to get better results using round()
// frame.width is the width of the MKMapView
let zoom = round(log2(360 * Double(frame.width) / size / region.span.longitudeDelta))
but it ONLY shows the index.html file and NOTHING attached to it, so no images, no effects or anything that the html file should display.
That's because in your program that's the only thing that you return to the browser regardless of what the request looks like.
You can take a look at a more complete example that will return the correct files for the most common web pages (HTML, JPG, CSS, JS) in here https://gist.github.com/hectorcorrea/2573391
Also, take a look at this blog post that I wrote on how to get started with node. I think it might clarify a few things for you: http://hectorcorrea.com/blog/introduction-to-node-js
I have reformatted your code.
The error was situated in this line :
printf("%d", (**c));
To fix it, change to :
printf("%d", (*c));
The * retrieves the value from an address. The ** retrieves the value (an address in this case) of an other value from an address.
In addition, the () was optional.
#include <stdio.h>
int main(void)
{
int b = 10;
int *a = NULL;
int *c = NULL;
a = &b;
c = &a;
printf("%d", *c);
return 0;
}
EDIT :
The line :
c = &a;
must be replaced by :
c = a;
It means that the value of the pointer 'c' equals the value of the pointer 'a'. So, 'c' and 'a' points to the same address ('b'). The output is :
10
EDIT 2:
If you want to use a double * :
#include <stdio.h>
int main(void)
{
int b = 10;
int *a = NULL;
int **c = NULL;
a = &b;
c = &a;
printf("%d", **c);
return 0;
}
Output:
10
Your mock is raising the exception just fine, but the error.resp.status
value is missing. Rather than use return_value
, just tell Mock
that status
is an attribute:
barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
Additional keyword arguments to Mock()
are set as attributes on the resulting object.
I put your foo
and bar
definitions in a my_tests
module, added in the HttpError
class so I could use it too, and your test then can be ran to success:
>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
... barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
... result = my_test.foo()
...
404 -
>>> result is None
True
You can even see the print '404 - %s' % error.message
line run, but I think you wanted to use error.content
there instead; that's the attribute HttpError()
sets from the second argument, at any rate.
None of the above helped for me.
I was able to install Mojave using this link here: http://dosdude1.com/mojave/ This patch worked beautifully and without a hitch
Proof: here's Mojave running on my (unsupported) 2011 Mac-mini
Here is a good tutorial with code. Let me know if it works for you! This is also a good tutorial.
EDIT
In This example, all you need to do is add this line:
gallery.setSelection(1);
after setting the adapter to gallery object, that is this line:
gallery.setAdapter(new ImageAdapter(this));
UPDATE1
Alright, I got your problem. This open source library is your solution. I also have used it for one of my projects. Hope this will solve your problem finally.
UPDATE2:
I would suggest you to go through this tutorial. You might get idea. I think I got your problem, you want the horizontal scrollview with snap. Try to search with that keyword on google or out here, you might get your solution.
ls -d */ | xargs -iA cp file.txt A
For simple cases like this, TimeUnit should be used. TimeUnit usage is a bit more explicit about what is being represented and is also much easier to read and write when compared to doing all of the arithmetic calculations explicitly. For example, to calculate the number days from milliseconds, the following statement would work:
long days = TimeUnit.MILLISECONDS.toDays(milliseconds);
For cases more advanced, where more finely grained durations need to be represented in the context of working with time, an all encompassing and modern date/time API should be used. For JDK8+, java.time is now included (here are the tutorials and javadocs). For earlier versions of Java joda-time is a solid alternative.
In my case, all other solutions didn't work, but this one did:
obj = {...arr}
my arr is in a form: [name: "the name", email: "[email protected]"]
if (maybeObject !== undefined)
alert("Got here!");
The best way is to store native JavaScript Date objects, which map onto BSON native Date objects.
> db.test.insert({date: ISODate()})
> db.test.insert({date: new Date()})
> db.test.find()
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:42.389Z") }
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:57.240Z") }
The native type supports a whole range of useful methods out of the box, which you can use in your map-reduce jobs, for example.
If you need to, you can easily convert Date
objects to and from Unix timestamps1), using the getTime()
method and Date(milliseconds)
constructor, respectively.
1) Strictly speaking, the Unix timestamp is measured in seconds. The JavaScript Date object measures in milliseconds since the Unix epoch.
I want to know how can I update some field(not all) like method 1 where id = 1
Use @Query
, as you did in Method 2.
is too long query in my case because I have many field in my entity
Then have smaller entities. Or, do not update fields individually, but instead have more coarse-grained interactions with the database.
IOW, there is nothing in Room itself that will do what you seek.
UPDATE 2020-09-15: Room now has partial entity support, which can help with this scenario. See this answer for more.
Simply use
$(document).height() // - $('body').offset().top
and / or
$(window).height()
instead of $('body').height();
This works too:
window.location.href = window.location.pathname + window.location.search
Swift 5+:
let globalPoint = aView.superview?.convert(aView.frame.origin, to: nil)
Quick fix for CGRectMake , CGPointMake, CGSizeMake in Swift3 & iOS10
Add these extensions :
extension CGRect{
init(_ x:CGFloat,_ y:CGFloat,_ width:CGFloat,_ height:CGFloat) {
self.init(x:x,y:y,width:width,height:height)
}
}
extension CGSize{
init(_ width:CGFloat,_ height:CGFloat) {
self.init(width:width,height:height)
}
}
extension CGPoint{
init(_ x:CGFloat,_ y:CGFloat) {
self.init(x:x,y:y)
}
}
Then go to "Find and Replace in Workspace" Find CGRectMake , CGPointMake, CGSizeMake and Replace them with CGRect , CGPoint, CGSize
These steps might save all the time as Xcode right now doesn't give us quick conversion from Swift 2+ to Swift 3
I notice that recent Oracle client installers change file permissions.
I had Oracle 12.0.1 32 bit client installed for a year. I recently installed Oracle 12.0.1 64 bit client. The Oracle install change ALL file permissions in the 32 bit folders.
My application suddenly failed to run.
I used PROCMON.EXE (https://docs.microsoft.com/en-us/sysinternals/downloads/) and noticed that permission was denied opening OCI.DLL
I changed the permissions for everything in the Oracle client folders and application works as expected.
Nowadays, people use DESC
instead of DESCRIPTION
. For example:-
DESC users;
MAMP takes only two highest versions of the PHP in the following folder /Application/MAMP/bin/php
As you can see here highest versions are 7.0.10 and 5.6.25
Now 7.0.10 version is removed and as you can see highest two versions are 5.6.25 and 5.5.38 as shown in preferences
In PL/SQL, A cursor is a pointer to this context area. It contains all the information needed for processing the statement.
Implicit Cursors: Implicit cursors are automatically created by Oracle whenever an SQL statement is executed, when there is no explicit cursor for the statement. Programmers cannot control the implicit cursors and the information in it.
Explicit Cursors: Explicit cursors are programmer-defined cursors for gaining more control over the context area. An explicit cursor should be defined in the declaration section of the PL/SQL Block. It is created on a SELECT Statement which returns more than one row.
The syntax for creating an explicit cursor is:
CURSOR cursor_name IS select_statement;
You basically need to set top
and left
to 50%
to center the left-top corner of the div. You also need to set the margin-top
and margin-left
to the negative half of the div's height and width to shift the center towards the middle of the div.
Thus, provided a <!DOCTYPE html>
(standards mode), this should do:
position: fixed;
width: 500px;
height: 200px;
top: 50%;
left: 50%;
margin-top: -100px; /* Negative half of height. */
margin-left: -250px; /* Negative half of width. */
Or, if you don't care about centering vertically and old browsers such as IE6/7, then you can instead also add left: 0
and right: 0
to the element having a margin-left
and margin-right
of auto
, so that the fixed positioned element having a fixed width knows where its left and right offsets start. In your case thus:
position: fixed;
width: 500px;
height: 200px;
margin: 5% auto; /* Will not center vertically and won't work in IE6/7. */
left: 0;
right: 0;
Again, this works only in IE8+ if you care about IE, and this centers only horizontally not vertically.
Just copy an image into your res/drawable
folder and use
imageView.setImageResource(R.drawable.my_image);
The variety of answers can cause a little confusion. We have
setBackgroundResource()
setBackgroundDrawable()
setBackground()
setImageResource()
setImageDrawable()
setImageBitmap()
The methods with Background
in their name all belong to the View
class, not to ImageView
specifically. But since ImageView
inherits from View
you can use them, too. The methods with Image
in their name belong specifically to ImageView
.
The View
methods all do the same thing as each other (though setBackgroundDrawable()
is deprecated), so we will just focus on setBackgroundResource()
. Similarly, the ImageView
methods all do the same thing, so we will just focus on setImageResource()
. The only difference between the methods is they type of parameter you pass in.
Here is a FrameLayout
that contains an ImageView
. The ImageView
initially doesn't have any image in it. (I only added the FrameLayout
so that I could put a border around it. That way you can see the edge of the ImageView
.)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/frameLayout"
android:layout_width="250dp"
android:layout_height="250dp"
android:background="@drawable/border"
android:layout_centerInParent="true">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
</RelativeLayout>
Below we will compare the different methods.
If you use ImageView's setImageResource()
, then the image keeps its aspect ratio and is resized to fit. Here are two different image examples.
imageView.setImageResource(R.drawable.sky);
imageView.setImageResource(R.drawable.balloons);
Using View's setBackgroundResource()
, on the other hand, causes the image resource to be stretched to fill the view.
imageView.setBackgroundResource(R.drawable.sky);
imageView.setBackgroundResource(R.drawable.balloons);
The View's background image and the ImageView's image are drawn separately, so you can set them both.
imageView.setBackgroundResource(R.drawable.sky);
imageView.setImageResource(R.drawable.balloons);
You can do this with pure CSS but you will need to hard code the offset scroll amounts, which may not be ideal should you be changing page content- or should dimensions of your content change on say window resize.
You're likely best placed to use e.g. jQuery, specifically:
$('html, body').stop().animate({
scrollTop: element.offset().top
}, 1000);
A complete implementation may be:
$('#up, #down').on('click', function(e){
e.preventDefault();
var target= $(this).get(0).id == 'up' ? $('#down') : $('#up');
$('html, body').stop().animate({
scrollTop: target.offset().top
}, 1000);
});
Where element
is the target element to scroll to and 1000
is the delay in ms before completion.
The benefit being, no matter what changes to your content dimensions, the function will not need to be altered.
If anyone still has problem, this is my code.
I have a custom view which is square (width = height) and I want to assign a character to it. onDraw()
shows how to get height of character, although I'm not using it. Character will be displayed in the middle of view.
public class SideBarPointer extends View {
private static final String TAG = "SideBarPointer";
private Context context;
private String label = "";
private int width;
private int height;
public SideBarPointer(Context context) {
super(context);
this.context = context;
init();
}
public SideBarPointer(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
init();
}
public SideBarPointer(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.context = context;
init();
}
private void init() {
// setBackgroundColor(0x64FF0000);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
height = this.getMeasuredHeight();
width = this.getMeasuredWidth();
setMeasuredDimension(width, width);
}
protected void onDraw(Canvas canvas) {
float mDensity = context.getResources().getDisplayMetrics().density;
float mScaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
Paint previewPaint = new Paint();
previewPaint.setColor(0x0C2727);
previewPaint.setAlpha(200);
previewPaint.setAntiAlias(true);
Paint previewTextPaint = new Paint();
previewTextPaint.setColor(Color.WHITE);
previewTextPaint.setAntiAlias(true);
previewTextPaint.setTextSize(90 * mScaledDensity);
previewTextPaint.setShadowLayer(5, 1, 2, Color.argb(255, 87, 87, 87));
float previewTextWidth = previewTextPaint.measureText(label);
// float previewTextHeight = previewTextPaint.descent() - previewTextPaint.ascent();
RectF previewRect = new RectF(0, 0, width, width);
canvas.drawRoundRect(previewRect, 5 * mDensity, 5 * mDensity, previewPaint);
canvas.drawText(label, (width - previewTextWidth)/2, previewRect.top - previewTextPaint.ascent(), previewTextPaint);
super.onDraw(canvas);
}
public void setLabel(String label) {
this.label = label;
Log.e(TAG, "Label: " + label);
this.invalidate();
}
}
In need of an extension method:
public static int DivideUp(this int dividend, int divisor)
{
return (dividend + (divisor - 1)) / divisor;
}
No checks here (overflow, DivideByZero
, etc), feel free to add if you like. By the way, for those worried about method invocation overhead, simple functions like this might be inlined by the compiler anyways, so I don't think that's where to be concerned. Cheers.
P.S. you might find it useful to be aware of this as well (it gets the remainder):
int remainder;
int result = Math.DivRem(dividend, divisor, out remainder);
Seaborn's barplot returns an axis-object (not a figure). This means you can do the following:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
ax = sns.barplot(x = 'val', y = 'cat',
data = fake,
color = 'black')
ax.set(xlabel='common xlabel', ylabel='common ylabel')
plt.show()
There are two directories that looks like JDK.
C:\Program Files\Java\jdk1.7.0_02
C:\Program Files (x86)\Java\jdk1.7.0_02\
This may be due to both 64 bit and 32 bit JDK installed? What ever may be the case, the java.exe
seen by ant.bat should from the JDK. If the JRE's java.exe
comes first in the path, that will be used to guess the JDK location.
Put 'C:\Program Files (x86)\Java\jdk1.7.0_02\bin' or 'C:\Program Files\Java\jdk1.7.0_02' as the first argument in the path.
Further steps:
You can take output of ant -diagnostics
and look for interesting keys. (assuming Sun/Oracle JDK).
java.class.path
java.library.path
sun.boot.library.path
(in my case tools.jar appears in java.class.path)
Right(A1, Len(A1)-Find("(asterisk)",Substitute(A1, "(space)","(asterisk)",Len(A1)-Len(Substitute(A1,"(space)", "(no space)")))))
Try this. Hope it works.
It is working. I just added square brackets to JSON data. The data is:
var data = [
{
"id": "1",
"msg": "hi",
"tid": "2013-05-05 23:35",
"fromWho": "[email protected]"
},
{
"id": "2",
"msg": "there",
"tid": "2013-05-05 23:45",
"fromWho": "[email protected]"
}
]
And the loop is:
for (var key in data) {
if (data.hasOwnProperty(key)) {
alert(data[key].id);
}
}
Some "front ends", with the "Use Booleans" option enabled, will treat all TINYINT(1) columns as Boolean, and vice versa.
This allows you to, in the application, use TRUE and FALSE rather than 1 and 0.
This doesn't affect the database at all, since it's implemented in the application.
There is not really a BOOLEAN
type in MySQL. BOOLEAN is just a synonym for TINYINT(1), and TRUE and FALSE are synonyms for 1 and 0.
If the conversion is done in the compiler, there will be no difference in performance in the application. Otherwise, the difference still won't be noticeable.
You should use whichever method allows you to code more efficiently, though not using the feature may reduce dependency on that particular "front end" vendor.
ReferenceError: Can't find variable: require.
You have installed "npm", you can run as normal the script to a "localhost" "127.0.0.1".
When you use the http.clientRequest() with "options" in a "npm" you need to install "RequireJS" inside of the module.
A module is any file or directory in the node_modules directory that can be loaded by the Node. Install "RequiereJS" for to make work the http.clientRequest(options).
When the accepted answer doesn't work (for example when dealing with Paint) you can use:
float spTextSize = 12;
float textSize = spTextSize * getResources().getDisplayMetrics().scaledDensity;
textPaint.setTextSize(textSize);
The first set of errors, for the missing vtable, are caused because you do not implement takeaway::textualGame()
; instead you implement a non-member function, textualGame()
. I think that adding the missing takeaway::
will fix that.
The cause of the last error is that you're calling a virtual function, initialData()
, from the constructor of gameCore
. At this stage, virtual functions are dispatched according to the type currently being constructed (gameCore
), not the most derived class (takeaway
). This particular function is pure virtual, and so calling it here gives undefined behaviour.
Two possible solutions:
gameCore
out of the constructor and into a separate initialisation function, which must be called after the object is fully constructed; orgameCore
into two classes: an abstract interface to be implemented by takeaway
, and a concrete class containing the state. Construct takeaway
first, and then pass it (via a reference to the interface class) to the constructor of the concrete class.I would recommend the second, as it is a move towards smaller classes and looser coupling, and it will be harder to use the classes incorrectly. The first is more error-prone, as there is no way be sure that the initialisation function is called correctly.
One final point: the destructor of a base class should usually either be virtual (to allow polymorphic deletion) or protected (to prevent invalid polymorphic deletion).
Fill the dataset with data from, say a stored proc command
DbDataAdapter adapter = DbProviderFactories.GetFactory(cmd.Connection).CreateDataAdapter();
adapter.SelectCommand = cmd;
DataSet ds = new DataSet();
adapter.Fill(ds);
Get The Schema,
string s = ds.GetXmlSchema();
save it to a file say: datasetSchema.xsd. Generate the C# classes for the Schema: (at the VS Command Prompt)
xsd datasetSchema.xsd /c
Now, when you need to convert the DataSet data to classes you can deserialize (the default name given to the generated root class is NewDataSet):
public static T Create<T>(string xml)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (StringReader reader = new StringReader(xml))
{
T t = (T)serializer.Deserialize(reader);
reader.Close();
return t;
}
}
var xml = ds.GetXml();
var dataSetObjects = Create<NewDataSet>(xml);
You may also need the following directive to be set before the first "sub_filter" for backend-servers with data compression:
proxy_set_header Accept-Encoding "";
Otherwise it may not work. For your example it will look like:
location /admin/ {
proxy_pass http://localhost:8080/;
proxy_set_header Accept-Encoding "";
sub_filter "http://your_server/" "http://your_server/admin/";
sub_filter_once off;
}
Take a look at this example.
$("#wizard li").click(function () {
alert($(this).index()); // alert index of li relative to ul parent
});
This worked for me!
App/build.gradle
//Add this....Keep both version same
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
The simplest Angular jqLite version.
JS:
.directive('cOnChange', function() {
'use strict';
return {
restrict: "A",
scope : {
cOnChange: '&'
},
link: function (scope, element) {
element.on('change', function () {
scope.cOnChange();
});
}
};
});
HTML:
<input type="file" data-c-on-change="your.functionName()">
Maybe for UWP C#
public static async Task<IStorageItem> AsIStorageItemAsync(this string iStorageItemPath)
{
if (string.IsNullOrEmpty(iStorageItemPath)) return null;
IStorageItem storageItem = null;
try
{
storageItem = await StorageFolder.GetFolderFromPathAsync(iStorageItemPath);
if (storageItem != null) return storageItem;
} catch { }
try
{
storageItem = await StorageFile.GetFileFromPathAsync(iStorageItemPath);
if (storageItem != null) return storageItem;
} catch { }
return storageItem;
}
If you installed mongodb with homebrew, there's an easier way:
List mongo job with launchctl:
launchctl list | grep mongo
Stop mongo job:
launchctl stop <job label>
(For me this is launchctl stop homebrew.mxcl.mongodb
)
Start mongo job:
launchctl start <job label>
If you just want to convert a relative path with optional parameters I created an extension method for IHttpContextAccessor
public static string AbsoluteUrl(this IHttpContextAccessor httpContextAccessor, string relativeUrl, object parameters = null)
{
var request = httpContextAccessor.HttpContext.Request;
var url = new Uri(new Uri($"{request.Scheme}://{request.Host.Value}"), relativeUrl).ToString();
if (parameters != null)
{
url = Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString(url, ToDictionary(parameters));
}
return url;
}
private static Dictionary<string, string> ToDictionary(object obj)
{
var json = JsonConvert.SerializeObject(obj);
return JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
}
You can then call the method from your service/view using the injected IHttpContextAccessor
var callbackUrl = _httpContextAccessor.AbsoluteUrl("/Identity/Account/ConfirmEmail", new { userId = applicationUser.Id, code });
String if the size is fixed and small and text if it is variable and big. This is kind of important because text is way bigger than strings. It contains a lot more kilobytes.
So for small fields always use string(varchar). Fields like. first_name, login, email, subject (of a article or post) and example of texts: content/body of a post or article. fields for paragraphs etc
String size 1 to 255 (default = 255)
Text size 1 to 4294967296 (default = 65536)2
Answer is really simple guys, in android if you want to convert hex color in to int, just use android Color class, example shown as below
this is for light gray color
Color.parseColor("#a8a8a8");
Thats it and you will get your result.
You are using aggregate
function which not getting the items to perform action , you must verify linq query is giving some result as below:
var maxOrderLevel =sdv.Any()? sdv.Max(s => s.nOrderLevel):0
I believe there is a difference. Let's rename them so that we can talk about them more easily:
const double PI1 = 3.141592653589793;
constexpr double PI2 = 3.141592653589793;
Both PI1
and PI2
are constant, meaning you can not modify them. However only PI2
is a compile-time constant. It shall be initialized at compile time. PI1
may be initialized at compile time or run time. Furthermore, only PI2
can be used in a context that requires a compile-time constant. For example:
constexpr double PI3 = PI1; // error
but:
constexpr double PI3 = PI2; // ok
and:
static_assert(PI1 == 3.141592653589793, ""); // error
but:
static_assert(PI2 == 3.141592653589793, ""); // ok
As to which you should use? Use whichever meets your needs. Do you want to ensure that you have a compile time constant that can be used in contexts where a compile-time constant is required? Do you want to be able to initialize it with a computation done at run time? Etc.
I have found that, at least for "passcode"-like fields, doing something like <input type="tel" />
ends up producing the most authentic number-oriented field and it also has the benefit of no autoformatting. For example, in a mobile application I developed for Hilton recently, I ended up going with this:
... and my client was very impressed.
<form>_x000D_
<input type="tel" />_x000D_
<button type="submit">Submit</button>_x000D_
</form>
_x000D_
Here is a full example where the parent widget controls the children widget. The parent widget updates the children widgets (Text and TextField) with a counter.
To update the Text widget, all you do is pass in the String parameter. To update the TextField widget, you need to pass in a controller, and set the text in the controller.
main.dart:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Demo',
home: Home(),
);
}
}
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Update Text and TextField demo'),
),
body: ParentWidget());
}
}
class ParentWidget extends StatefulWidget {
@override
_ParentWidgetState createState() => _ParentWidgetState();
}
class _ParentWidgetState extends State<ParentWidget> {
int _counter = 0;
String _text = 'no taps yet';
var _controller = TextEditingController(text: 'initial value');
void _handleTap() {
setState(() {
_counter = _counter + 1;
_text = 'number of taps: ' + _counter.toString();
_controller.text = 'number of taps: ' + _counter.toString();
});
}
@override
Widget build(BuildContext context) {
return Container(
child: Column(children: <Widget>[
RaisedButton(
onPressed: _handleTap,
child: const Text('Tap me', style: TextStyle(fontSize: 20)),
),
Text('$_text'),
TextField(controller: _controller,),
]),
);
}
}
Most updated way to achieve this is:
Add this to your EditText in XML:
android:imeOptions="actionSearch"
Then in your Activity/Fragment:
EditText.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
// Do what you want here
return@setOnEditorActionListener true
}
return@setOnEditorActionListener false
}
If you don't want to import calendar
and apply .isleap
method you can try this:
def isleapyear(year):
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
return True
return False
I had this problem too. I found setting the appearance to none helped.
.class {
appearance:none;
-moz-appearance:none;
-webkit-appearance:none;
background-color: red;
}
Update: since the answer from @r2evans, it is much easier to insert images into R Markdown and control the size of the image.
The bookdown book does a great job of explaining that the best way to include images is by using include_graphics()
. For example, a full width image can be printed with a caption below:
```{r pressure, echo=FALSE, fig.cap="A caption", out.width = '100%'}
knitr::include_graphics("temp.png")
```
The reason this method is better than the pandoc approach ![your image](path/to/image)
:
fig.width
), the output width in the report (out.width
), add captions (fig.cap
) etc.knitr::kable()
is the best way to include tables in an R Markdown report as explained fully here. Again, this function is intelligent in automatically selecting the correct formatting for the output selected.
```{r table}
knitr::kable(mtcars[1:5,, 1:5], caption = "A table caption")
```
If you want to make your own simple tables in R Markdown and are using R Studio, you can check out the insert_table
package. It provides a tidy graphical interface for making tables.
Achieving custom styling of the table column width is beyond the scope of knitr
, but the kableExtra
package has been written to help achieve this: https://cran.r-project.org/web/packages/kableExtra/index.html
The R Markdown cheat sheet is still the best place to learn about most the basic syntax you can use.
If you are looking for potential extensions to the formatting, the bookdown
package is also worth exploring. It provides the ability to cross-reference, create special headers and more: https://bookdown.org/yihui/bookdown/markdown-extensions-by-bookdown.html
WHERE
clause introduces a condition on individual rows; HAVING
clause introduces a condition on aggregations, i.e. results of selection where a single result, such as count, average, min, max, or sum, has been produced from multiple rows. Your query calls for a second kind of condition (i.e. a condition on an aggregation) hence HAVING
works correctly.
As a rule of thumb, use WHERE
before GROUP BY
and HAVING
after GROUP BY
. It is a rather primitive rule, but it is useful in more than 90% of the cases.
While you're at it, you may want to re-write your query using ANSI version of the join:
SELECT L.LectID, Fname, Lname
FROM Lecturers L
JOIN Lecturers_Specialization S ON L.LectID=S.LectID
GROUP BY L.LectID, Fname, Lname
HAVING COUNT(S.Expertise)>=ALL
(SELECT COUNT(Expertise) FROM Lecturers_Specialization GROUP BY LectID)
This would eliminate WHERE
that was used as a theta join condition.
Just recently I forked a current Github project called "RibbonMenu" and edited it to fit my needs:
https://github.com/jaredsburrows/RibbonMenu
ActionBar with Menu out
ActionBar with Menu out and search selected
You could simply use ^[\w.]+
to match A-Z, a-z, 0-9 and _
go to that path "C:\Program Files (x86)\JetBrains\IntelliJ IDEA 12.1.4\bin\idea.exe.vmoptions" and change size to -Xmx512m
-Xms128m
-Xmx512m
-XX:MaxPermSize=250m
-XX:ReservedCodeCacheSize=64m
-XX:+UseCodeCacheFlushing
-ea
-Dsun.io.useCanonCaches=false
-Djava.net.preferIPv4Stack=true
hope its will work
Everything that interacts with the UI must be called in the UI thread (unless it is a frozen object). To do that, you can use the dispatcher.
var disp = /* Get the UI dispatcher, each WPF object has a dispatcher which you can query*/
disp.BeginInvoke(DispatcherPriority.Normal,
(Action)(() => /*Do your UI Stuff here*/));
I use BeginInvoke here, usually a backgroundworker doesn't need to wait that the UI updates. If you want to wait, you can use Invoke
. But you should be careful not to call BeginInvoke to fast to often, this can get really nasty.
By the way, The BackgroundWorker class helps with this kind of taks. It allows Reporting changes, like a percentage and dispatches this automatically from the Background thread into the ui thread. For the most thread <> update ui tasks the BackgroundWorker is a great tool.
You could also use a core dump and then examine it with gdb. To get useful information you also need to compile with the -g
flag.
Whenever you get the message:
Segmentation fault (core dumped)
a core file is written into your current directory. And you can examine it with the command
gdb your_program core_file
The file contains the state of the memory when the program crashed. A core dump can be useful during the deployment of your software.
Make sure your system doesn't set the core dump file size to zero. You can set it to unlimited with:
ulimit -c unlimited
Careful though! that core dumps can become huge.
To check MySQL version of MAMP , use the following command in Terminal:
/Applications/MAMP/Library/bin/mysql --version
Assume you have started MAMP .
Example output:
./mysql Ver 14.14 Distrib 5.1.44, for apple-darwin8.11.1 (i386) using EditLine wrapper
UPDATE: Moreover, if you want to find where does mysql installed in system, use the following command:
type -a mysql
type -a
is an equivalent of tclsh built-in command where
in OS X bash shell. If MySQL is found, it will show :
mysql is /usr/bin/mysql
If not found, it will show:
-bash: type: mysql: not found
By default , MySQL is not installed in Mac OS X.
Sidenote: For XAMPP, the command should be:
/Applications/XAMPP/xamppfiles/bin/mysql --version
Fragment
can be thought of as non-root components in a composite tree of ui elements while activities sit at the top in the forest of composites(ui trees).
A rule of thumb on when not to use Fragment
is when as a child the fragment has a conflicting attribute, e.g., it may be immersive or may be using a different style all together or has some other architectural / logical difference and doesn't fit in the existing tree homogeneously.
A rule of thumb on when to prefer Activity
over Fragment
is when the task (or set of coherent task) is fully independent and reusable and does some heavy weight lifting and should not be burdened further to conform to another parent-child composite (SRP violation, second responsibility would be to conform to the composite). For e.g., a MediaCaptureActivity
that captures audio, video, photos etc and allows for edits, noise removal, annotations on photos etc and so on. This activity/module may have child fragments that do more granular work and conform to a common display theme.
It is an old post, but I came across this recently
Selecting a specific interval
As @aleroot already mentioned, by using
table.setRowSelectionInterval(index0, index1);
You can specify an interval, which should be selected.
Adding an interval to the existing selection
You can also keep the current selection, and simply add additional rows by using this here
table.getSelectionModel().addSelectionInterval(index0, index1);
This line of code additionally selects the specified interval. It doesn't matter if that interval already is selected, of parts of it are selected.
I have recently done this on my website using jQuery. The code calculates the height of the tallest div and sets the other divs to the same height. Here's the technique:
http://www.broken-links.com/2009/01/20/very-quick-equal-height-columns-in-jquery/
I don't believe height:100%
will work, so if you don't explicitly know the div heights I don't think there is a pure CSS solution.
I have found answers to my confusions.
There is a very important difference between the root
and the alias
directives. This difference exists in the way the path specified in the root
or the alias
is processed.
In case of the root
directive, full path is appended to the root including the location part, whereas in case of the alias
directive, only the portion of the path NOT including the location part is appended to the alias.
To illustrate:
Let's say we have the config
location /static/ {
root /var/www/app/static/;
autoindex off;
}
In this case the final path that Nginx will derive will be
/var/www/app/static/static
This is going to return 404
since there is no static/
within static/
This is because the location part is appended to the path specified in the root
. Hence, with root
, the correct way is
location /static/ {
root /var/www/app/;
autoindex off;
}
On the other hand, with alias
, the location part gets dropped. So for the config
location /static/ {
alias /var/www/app/static/;
autoindex off; ?
} |
pay attention to this trailing slash
the final path will correctly be formed as
/var/www/app/static
alias
directiveThere is no definitive guideline about whether a trailing slash is mandatory per Nginx documentation, but a common observation by people here and elsewhere seems to indicate that it is.
A few more places have discussed this, not conclusively though.
https://serverfault.com/questions/375602/why-is-my-nginx-alias-not-working
People have suggested many great solutions here, but I used this simple technique with my EditText (nothing in java and AnroidManifest.xml is required). Just set your focusable and focusableInTouchMode to false directly on EditText.
<EditText
android:id="@+id/text_pin"
android:layout_width="136dp"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textAlignment="center"
android:inputType="numberPassword"
android:password="true"
android:textSize="24dp"
android:focusable="false"
android:focusableInTouchMode="false"/>
My intent here is to use this edit box in App lock activity where I am asking user to input the PIN and I want to show my custom PIN pad. Tested with minSdk=8 and maxSdk=23 on Android Studio 2.1
$(document).ready(function() {
$('.headings').click(function () {$('#sub1').css("display",""); });
$('.headings').click(function () {return false;});
$('#sub1').click(function () {return false;});
$('body').click(function () {$('#sub1').css("display","none");
})});
When you try to handle multi languages like Japanese and Korean you might get in trouble. mb_convert_encoding with 'auto' parameter doesn't work well. Setting mb_detect_order('ASCII,UTF-8,JIS,EUC-JP,SJIS,EUC-KR,UHC') doesn't help since it will detect EUC-* wrongly.
I concluded that as long as input strings comes from HTML, it should use 'charset' in a meta element. I use Simple HTML DOM Parser because it supports invalid HTML.
The below snippet extracts title element from a web page. If you would like to convert entire page, then you may want to remove some lines.
<?php
require_once 'simple_html_dom.php';
echo convert_title_to_utf8(file_get_contents($argv[1])), PHP_EOL;
function convert_title_to_utf8($contents)
{
$dom = str_get_html($contents);
$title = $dom->find('title', 0);
if (empty($title)) {
return null;
}
$title = $title->plaintext;
$metas = $dom->find('meta');
$charset = 'auto';
foreach ($metas as $meta) {
if (!empty($meta->charset)) { // html5
$charset = $meta->charset;
} else if (preg_match('@charset=(.+)@', $meta->content, $match)) {
$charset = $match[1];
}
}
if (!in_array(strtolower($charset), array_map('strtolower', mb_list_encodings()))) {
$charset = 'auto';
}
return mb_convert_encoding($title, 'UTF-8', $charset);
}
Seems like kind of a homely way of doing things, but if you must... you could restructure it as such to fit your needs:
boolean found = false;
case 1:
for (Element arrayItem : array) {
if (arrayItem == whateverValue) {
found = true;
} // else if ...
}
if (found) {
break;
}
case 2:
This will do the trick
.gallery-item
{
opacity:1;
}
.gallery-item:hover
{
opacity:0;
transition: opacity .2s ease-out;
-moz-transition: opacity .2s ease-out;
-webkit-transition: opacity .2s ease-out;
-o-transition: opacity .2s ease-out;
}
to set unlimited number of rows use
None
i.e.,
pd.set_option('display.max_cols', None)
now the notebook will display all the rows in all datasets within the notebook ;)
Similarly you can set to show all columns as
pd.set_option('display.max_rows', None)
now if you use run the cell with only dataframe with out any head or tail tags as
df
then it will show all the rows and columns in the dataframe df
I have not used bundle exec
much, but am setting it up now.
I have had instances where the wrong rake was used and much time wasted tracking down the problem. This helps you avoid that.
Here's how to set up RVM so you can use bundle exec
by default within a specific project directory:
For me was because I put the animation name inside square brackets.
<div [@animation]></div>
But after I removed the bracket all worked fine (In Angular 9.0.1):
<div @animation></div>
I'm adding this answer because after researching the web, I ended up at this answer but still didn't know which subfolder of the IIS logs folder to look in.
If your server has multiple websites, you will need to know the IIS ID for the site. An easy way to get this in IIS is to simply click on the Sites folder in the left panel. The ID for each site is shown in the right panel.
Once you know the ID, let's call it n, the corresponding logs are in the W3SVCn subfolder of the IIS logs folder. So, if your website ID is 4, say, and the IIS logs are in the default location, then the logs are in this folder:
%SystemDrive%\inetpub\logs\LogFiles\W3SVC4
Acknowlegements:
You do not have permissions to access the file. Please be sure whether you can access the file in that drive.
string route= @"E:\Sample.text";
FileStream fs = new FileStream(route, FileMode.Create);
You have to provide the file name to create. Please try this, now you can create.
Javadoc comments can be automatically appended by using your IDE's autocomplete feature. Try typing /**
and hitting Enter to generate a sample Javadoc comment.
/**
*
* @param action The action to execute.
* @param args The exec() arguments.
* @param callbackContext The callback context used when calling back into JavaScript.
* @return
* @throws JSONException
*/
As far as your question goes: no, if activating from .ini
is not enough and you can't upgrade PHP, there's not much you can do. Some modules, but not all, can be added without recompilation (zypper install php5-soap
, yum install php-soap
). If it is not enough, try installing some PEAR class for interpreted SOAP support (NuSOAP, etc.).
In general, the double-dash --switches
are designed to be used when recompiling PHP from scratch.
You would download the PHP source package (as a compressed .tgz
tarball, say), expand it somewhere and then, e.g. under Linux, run the configure script
./configure --prefix ...
The configure
command used by your PHP may be shown with phpinfo()
. Repeating it identical should give you an exact copy of the PHP you now have installed. Adding --enable-soap
will then enable SOAP in addition to everything else.
That said, if you aren't familiar with PHP recompilation, don't do it. It also requires several ancillary libraries that you might, or might not, have available - freetype
, gd
, libjpeg
, XML
, expat
, and so on and so forth (it's not enough they are installed; they must be a developer version, i.e. with headers and so on; in most distributions, having libjpeg
installed might not be enough, and you might need libjpeg-dev
also).
I have to keep a separate virtual machine with everything installed for my recompilation purposes.
I tried with the following and it's worked:
release {
debuggable true
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
Pure Python 3
def print_table(data, cols, wide):
'''Prints formatted data on columns of given width.'''
n, r = divmod(len(data), cols)
pat = '{{:{}}}'.format(wide)
line = '\n'.join(pat * cols for _ in range(n))
last_line = pat * r
print(line.format(*data))
print(last_line.format(*data[n*cols:]))
data = [str(i) for i in range(27)]
print_table(data, 6, 12)
Will print
0 1 2 3 4 5
6 7 8 9 10 11
12 13 14 15 16 17
18 19 20 21 22 23
24 25 26
Running as admin didn't help me. (also got errors with syscall: rename)
Turns out this error can also occur if files are locked by Windows.
This can occur if :
Running as admin doesn't get around windows file locking.
I created a new project in VS2017 and then switched to VSCode to try to add more packages. After stopping the project from running and closing VS2017 it was able to complete without error
Disclaimer: I'm not exactly sure if this means running as admin isn't necessary, but try to avoid it if possible to avoid the possibility of some rogue package doing stuff it isn't meant to.
constructor(private activatedRoute: ActivatedRoute) {
this.activatedRoute.queryParams.subscribe(params => {
console.log(params['type'])
}); }
This works for me!
This happened to me multiple times and then went away, before I could figure out why. In my case it was:
Wrong system time in the dual boot setup!
Turns out, my dual boot with Ubuntu was the root cause!! I've been too lazy to fix up Ubuntu to stop messing with my hardware clock. When I log into Ubuntu, the time jumps 5 hours forward.
Out of bad luck, I built the project once, with the wrong system time, then corrected the time. As a result, all the build files had wrong timestamps, and VS would think they are all out of date and would rebuild the project.
sizeof(buffer) == sizeof(char*)
Use length instead.
Also, better to use fopen
with "wb
"....
From what I understand using,
::-webkit-input-placeholder::before
or ::-webkit-input-placeholder::after
,
to add more placeholder content doesn't work anymore. Think its a new Chrome update.
Really annoying as it was a great workaround, now im back to just adding lots of empty spaces between lines that I want in a placeholder. eg:
<input type="text" value="" id="email1" placeholder="I am on one line. I am on a second line etc etc..." />
NSURL *URL = [NSURL URLWithString:@"url"];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *params = @{@"prefix":@"param",@"prefix":@"param",@"prefix":@"param"};
[manager POST:URL.absoluteString parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
self.arrayFromPost = [responseObject objectForKey:@"data"];
// values in foreach loop
NSLog(@"POst send: %@",_arrayFromPost);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
Note that exact reason why your code is frozen is not because you set too high request.recv() buffer size. Here is explained What means buffer size in socket.recv(buffer_size)
This code will work until it'll receive an empty TCP message (if you'd print this empty message, it'd show b''
):
while True:
data = self.request.recv(1024)
if not data: break
And note, that there is no way to send empty TCP message. socket.send(b'')
simply won't work.
Why? Because empty message is sent only when you type socket.close()
, so your script will loop as long as you won't close your connection.
As Hans L pointed out here are some good methods to end message.
If the to-be-updated component is not inside the same NamingContainer
component (ui:repeat
, h:form
, h:dataTable
, etc), then you need to specify the "absolute" client ID. Prefix with :
(the default NamingContainer
separator character) to start from root.
<p:ajax process="@this" update="count :subTotal"/>
To be sure, check the client ID of the subTotal
component in the generated HTML for the actual value. If it's inside for example a h:form
as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.
<p:ajax process="@this" update="count :formId:subTotal"/>
Space separation of IDs is more recommended as <f:ajax>
doesn't support comma separation and starters would otherwise get confused.
My solution is to write a static method inside the fragment:
public TheFragment setData(TheData data) {
TheFragment tf = new TheFragment();
tf.data = data;
return tf;
}
This way I am sure that all the data I need is inside the Fragment before any other possible operation which could need to work with it. Also it looks cleaner in my opinion.
I developed a Tool - Code Analyzer, it runs in iPhone/iPad/Mac, to analyze Java/Android files, https://decompile.io
Motti is right about the order, but there are some other things to consider:
Compilers typically use a hidden flag variable to indicate if the local statics have already been initialized, and this flag is checked on every entry to the function. Obviously this is a small performance hit, but what's more of a concern is that this flag is not guaranteed to be thread-safe.
If you have a local static as above, and foo
is called from multiple threads, you may have race conditions causing plonk
to be initialized incorrectly or even multiple times. Also, in this case plonk
may get destructed by a different thread than the one which constructed it.
Despite what the standard says, I'd be very wary of the actual order of local static destruction, because it's possible that you may unwittingly rely on a static being still valid after it's been destructed, and this is really difficult to track down.
It will not work like this, put both images as background images:
.bg-img {
background:url(images/yourImg.jpg) no-repeat 0 0;
}
.bg-img:hover {
background:url(images/yourImg-1.jpg) no-repeat 0 0;
}
I hope this'll do . or else, may ask me directly
_x000D_
Sub RemoveBlankLines()
Application.ScreenUpdating = False
Dim rngCel As Range
Dim strOldVal As String
Dim strNewVal As String
For Each rngCel In Selection
If rngCel.HasFormula = False Then
strOldVal = rngCel.Value
strNewVal = strOldVal
Debug.Print rngCel.Address
Do
If Left(strNewVal, 1) = vbLf Then strNewVal = Right(strNewVal, Len(strNewVal) - 1)
If strNewVal = strOldVal Then Exit Do
strOldVal = strNewVal
Loop
Do
If Right(strNewVal, 1) = vbLf Then strNewVal = Left(strNewVal, Len(strNewVal) - 1)
If strNewVal = strOldVal Then Exit Do
strOldVal = strNewVal
Loop
Do
strNewVal = Replace(strNewVal, vbLf & vbLf, "^")
strNewVal = Replace(strNewVal, Replace(String(Len(strNewVal) - _
Len(Replace(strNewVal, "^", "")), "^"), "^", "^"), "^")
strNewVal = Replace(strNewVal, "^", vbLf)
If strNewVal = strOldVal Then Exit Do
strOldVal = strNewVal
Loop
If rngCel.Value <> strNewVal Then
rngCel = strNewVal
End If
rngCel.Value = Application.Trim(rngCel.Value)
End If
Next rngCel
Application.ScreenUpdating = True
End Sub
_x000D_
UITableView
has a property separatorInset
. You can use that to set the insets of the table view separators to zero to let them span the full width of the screen.
[tableView setSeparatorInset:UIEdgeInsetsZero];
Note: If your app is also targeting other iOS versions, you should check for the availability of this property before calling it by doing something like this:
if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
[tableView setSeparatorInset:UIEdgeInsetsZero];
}
Set the property of your DataGridView:
Anchor: Top,Left
AutoSizeColumn: Fill
Dock: Fill
If you use spyder and love GUI, you can simply click on the folder button on the upper right corner of your screen and navigate through folders/directories you want as current directory. After doing so you can go to the file explorer tab of the window in spyder IDE and you can see all the files/folders present there. to check your current working directory go to the console of spyder IDE and simply type
pwd
it will print the same path as you have selected before.
If you can make an approximation of the number of items that will be there at the end, use the overload of the List constuctor that takes count as a parameter. You will save some expensive List duplications. Otherwise you have to pay for it.
The right way to achieve what you are looking for is to use
title="Choose..."
for example:
<select class="form-contro selectpicker" name="example" title="Choose...">
<option value="all">All Affiliate</option>
</select>
check the documentation for more info about below ref
This is a simplified variation of Fernando's answer. This is for Linux and either Python 2 or 3. No external library is needed, and no external process is run.
import glob
def get_command_pid(command):
for path in glob.glob('/proc/*/comm'):
if open(path).read().rstrip() == command:
return path.split('/')[2]
Only the first matching process found will be returned, which works well for some purposes. To get the PIDs of multiple matching processes, you could just replace the return
with yield
, and then get a list with pids = list(get_command_pid(command))
.
Alternatively, as a single expression:
For one process:
next(path.split('/')[2] for path in glob.glob('/proc/*/comm') if open(path).read().rstrip() == command)
For multiple processes:
[path.split('/')[2] for path in glob.glob('/proc/*/comm') if open(path).read().rstrip() == command]
Answered by zerkms is the correct method. But, if someone looking to insert more extra column in the table then you can get it from the following:
INSERT INTO action_2_members (`campaign_id`, `mobile`, `email`, `vote`, `vote_date`, `current_time`)
SELECT `campaign_id`, `from_number`, '[email protected]', `received_msg`, `date_received`, 1502309889 FROM `received_txts` WHERE `campaign_id` = '8'
In the above query, there are 2 extra columns named email & current_time.
Right click on your Subversion working directory folder, and select TortoiseSVN->Clean Up from the Context Menu. This will recurse it's way through your working directory and cleanup any incomplete actions, remove the local locks (which is different from using Subversion locking of a file in the repository which lets everyone know about the lock).
If that doesn't work, see if you can find the names of the files that were changed, but not yet committed, save them, and redo the checkout.
Easy way to fix this issue
Solution:
to install "microsoft.entityframeworkcore.sqlserver" with NuGet
PS: make sure you have using EF on the content "using Microsoft.EntityFrameworkCore;"
There are a lot of answer above which will definitely help you but (after 2 days of afford and research on adb memory tools) I think i can help with my opinion too.
As Hackbod says : Thus if you were to take all of the physical RAM actually mapped in to each process, and add up all of the processes, you would probably end up with a number much greater than the actual total RAM. so there is no way you can get exact amount of memory per process.
But you can get close to it by some logic..and I will tell how..
There are some API like
android.os.Debug.MemoryInfo
andActivityManager.getMemoryInfo()
mentioned above which you already might have being read about and used but I will talk about other way
So firstly you need to be a root user to get it work. Get into console with root privilege by executing su
in process and get its output and input stream
. Then pass id\n
(enter) in ouputstream and write it to process output, If will get an inputstream containing uid=0
, you are root user.
Now here is the logic which you will use in above process
When you get ouputstream of process pass you command (procrank, dumpsys meminfo etc...) with \n
instead of id and get its inputstream
and read, store the stream in bytes[ ] ,char[ ] etc.. use raw data..and you are done!!!!!
permission :
<uses-permission android:name="android.permission.FACTORY_TEST"/>
Check if you are root user :
// su command to get root access
Process process = Runtime.getRuntime().exec("su");
DataOutputStream dataOutputStream =
new DataOutputStream(process.getOutputStream());
DataInputStream dataInputStream =
new DataInputStream(process.getInputStream());
if (dataInputStream != null && dataOutputStream != null) {
// write id to console with enter
dataOutputStream.writeBytes("id\n");
dataOutputStream.flush();
String Uid = dataInputStream.readLine();
// read output and check if uid is there
if (Uid.contains("uid=0")) {
// you are root user
}
}
Execute your command with su
Process process = Runtime.getRuntime().exec("su");
DataOutputStream dataOutputStream =
new DataOutputStream(process.getOutputStream());
if (dataOutputStream != null) {
// adb command
dataOutputStream.writeBytes("procrank\n");
dataOutputStream.flush();
BufferedInputStream bufferedInputStream =
new BufferedInputStream(process.getInputStream());
// this is important as it takes times to return to next line so wait
// else you with get empty bytes in buffered stream
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// read buffered stream into byte,char etc.
byte[] bff = new byte[bufferedInputStream.available()];
bufferedInputStream.read(bff);
bufferedInputStream.close();
}
}
You get a raw data in a single string from console instead of in some instance from any API,which is complex to store as you will need to separate it manually.
This is just a try, please suggest me if I missed something
It is possible to do (in the deployed repository):
git fetch
// git fetch will download all the recent changes, but it will not put it in your current checked out code (working area).
Followed by:
git checkout origin/master -- path/to/file
// git checkout <local repo name (default is origin)>/<branch name> -- path/to/file will checkout the particular file from the downloaded changes (origin/master).
Use (eventName)
for while binding event to DOM, basically ()
is used for event binding. Also use ngModel
to get two way binding for myModel
variable.
Markup
<input type="text" [(ngModel)]="myModel" (blur)="onBlurMethod()">
Code
export class AppComponent {
myModel: any;
constructor(){
this.myModel = '123';
}
onBlurMethod(){
alert(this.myModel)
}
}
Alternative(not preferable)
<input type="text" #input (blur)="onBlurMethod($event.target.value)">
For model driven form to fire validation on blur
, you could pass updateOn
parameter.
ctrl = new FormControl('', {
updateOn: 'blur', //default will be change
validators: [Validators.required]
});
Another application for XOR
is in circuits. It is used to sum bits.
When you look at a truth table:
x | y | x^y
---|---|-----
0 | 0 | 0 // 0 plus 0 = 0
0 | 1 | 1 // 0 plus 1 = 1
1 | 0 | 1 // 1 plus 0 = 1
1 | 1 | 0 // 1 plus 1 = 0 ; binary math with 1 bit
You can notice that the result of XOR
is x added with y, without keeping track of the carry bit, the carry bit is obtained from the AND
between x and y.
x^y // is actually ~xy + ~yx
// Which is the (negated x ANDed with y) OR ( negated y ANDed with x ).
2020 Simple way :
git reset <commit_hash>
(The commit hash of the last commit you want to keep).
If the commit was pushed, you can then do :
git push -f
You will keep the now uncommitted changes locally
It must be at least 64 bits. Other than that it's implementation defined.
Strictly speaking, unsigned long long
isn't standard in C++ until the C++0x standard. unsigned long long
is a 'simple-type-specifier' for the type unsigned long long int
(so they're synonyms).
The long long
set of types is also in C99 and was a common extension to C++ compilers even before being standardized.
You can use the built-in http
module to do an http.request()
.
However if you want to simplify the API you can use a module such as superagent
I got the question "say you were writing the built in function for casting an integer to a string in PHP, how would you write that function" in a programming interview. Here's a solution.
$nums = ["0","1","2","3","4","5","6","7","8","9"];
$int = 15939;
$string = "";
while ($int) {
$string .= $nums[$int % 10];
$int = (int)($int / 10);
}
$result = strrev($string);
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
It can clear google account in my webview
Use QString's number method (docs are here):
double valueAsDouble = 1.2;
QString valueAsString = QString::number(valueAsDouble);
In practical terms, Alnitak is correct and makes it easy to understand, but ultimately in JavaScript, everything is passed by value.
What is the "value" of an object? It is the object reference.
When you pass in an object, you get a copy of this value (hence the 'copy of a reference' that Alnitak described). If you change this value, you do not change the original object; you are changing your copy of that reference.
like this:
/\<word\>
\<
means beginning of a word, and \>
means the end of a word,
Adding @Roe's comment:
VIM provides a shortcut for this. If you already have word on screen and you want to find other instances of it, you can put the cursor on the word and press '*'
to search forward in the file or '#'
to search backwards.
Also when scripting, you can specify a name when creating the window with -n <window name>
. For example:
# variable to store the session name
SESSION="my_session"
# set up session
tmux -2 new-session -d -s $SESSION
# create window; split into panes
tmux new-window -t $SESSION:0 -n 'My Window with a Name'
Make sure the "m" in main() is lowercase this would also cause java not to see your main method, I've done that several times unfortunately.
In net .core you can use
var client = new HttpClient();
client.SetBasicAuthentication(userName, password);
or
var client = new HttpClient();
client.SetBearerToken(token);
CSS only with a delay of 3s
a few points to take here:
Code:
header {
animation: 3s ease-out 0s 1 wait, 0.21s ease-out 3s 1 slideInFromBottom;
}
@keyframes wait {
from { transform: translateY(20px); }
to { transform: translateY(20px); }
}
@keyframes slideInFromBottom {
from { transform: translateY(20px); opacity: 0; }
to { transform: translateY(0); opacity: 1; }
}
In addition to all the great answers here already, I've also used it to walk an item through a series of transformation steps.
If a transformation is implemented as a Func<T,T>
, you can add several transformations to a List<Func<T,T>>
and use Aggregate
to walk an instance of T
through each step.
You want to take a string
value, and walk it through a series of text transformations that could be built programatically.
var transformationPipeLine = new List<Func<string, string>>();
transformationPipeLine.Add((input) => input.Trim());
transformationPipeLine.Add((input) => input.Substring(1));
transformationPipeLine.Add((input) => input.Substring(0, input.Length - 1));
transformationPipeLine.Add((input) => input.ToUpper());
var text = " cat ";
var output = transformationPipeLine.Aggregate(text, (input, transform)=> transform(input));
Console.WriteLine(output);
This will create a chain of transformations: Remove leading and trailing spaces -> remove first character -> remove last character -> convert to upper-case. Steps in this chain can be added, removed, or reordered as needed, to create whatever kind of transformation pipeline is required.
The end result of this specific pipeline, is that " cat "
becomes "A"
.
This can become very powerful once you realize that T
can be anything. This could be used for image transformations, like filters, using BitMap
as an example;
You can use :+
to append element to array and +:
to prepend it:
0 +: array :+ 4
should produce:
res3: Array[Int] = Array(0, 1, 2, 3, 4)
It's the same as with any other implementation of Seq
.
The best example is this one, No hiding, No jQuery, It's completely pure CSS
http://css-tricks.com/snippets/css/custom-file-input-styling-webkitblink/
.custom-file-input::-webkit-file-upload-button {_x000D_
visibility: hidden;_x000D_
}_x000D_
_x000D_
.custom-file-input::before {_x000D_
content: 'Select some files';_x000D_
display: inline-block;_x000D_
background: -webkit-linear-gradient(top, #f9f9f9, #e3e3e3);_x000D_
border: 1px solid #999;_x000D_
border-radius: 3px;_x000D_
padding: 5px 8px;_x000D_
outline: none;_x000D_
white-space: nowrap;_x000D_
-webkit-user-select: none;_x000D_
cursor: pointer;_x000D_
text-shadow: 1px 1px #fff;_x000D_
font-weight: 700;_x000D_
font-size: 10pt;_x000D_
}_x000D_
_x000D_
.custom-file-input:hover::before {_x000D_
border-color: black;_x000D_
}_x000D_
_x000D_
.custom-file-input:active::before {_x000D_
background: -webkit-linear-gradient(top, #e3e3e3, #f9f9f9);_x000D_
}
_x000D_
<input type="file" class="custom-file-input">
_x000D_
Yes, it does. The way to enable this depends on your version of Notepad++. On newer versions you can use:
Menu View ? Show Symbol ? *Show All Characters`
or
Menu View ? Show Symbol ? Show White Space and TAB
(Thanks to bers' comment and bkaid's answers below for these updated locations.)
On older versions you can look for:
Menu View ? Show all characters
or
Menu View ? Show White Space and TAB
There is a new docker command for "secrets" management. But that only works for swarm clusters.
docker service create
--name my-iis
--publish target=8000,port=8000
--secret src=homepage,target="\inetpub\wwwroot\index.html"
microsoft/iis:nanoserver
Use Func<T>
rather than Action<T>
.
Action<T>
acts like a void method with parameter of type T, while Func<T>
works like a function with no parameters and which returns an object of type T.
If you wish to give parameters to your function, use Func<TParameter1, TParameter2, ..., TReturn>
.
Your suggestion would work, but using a Do loop might be a little more readable.
This is actually an idiom in C - instead of using a goto, you can have a do { } while (0) loop with a break statement if you want to bail out of the construct early.
Dim i
For i = 0 To 10
Do
If i = 4 Then Exit Do
WScript.Echo i
Loop While False
Next
As crush suggests, it looks a little better if you remove the extra indentation level.
Dim i
For i = 0 To 10: Do
If i = 4 Then Exit Do
WScript.Echo i
Loop While False: Next