Answering here because this is a popular thread. This is a clean solution in Kotlin that uses the recommended UrlQuerySanitizer
api. See the official documentation. I have added a string builder to concatenate and display the params.
var myURL: String? = null
if (intent.hasExtra("my_value")) {
myURL = intent.extras.getString("my_value")
} else {
myURL = intent.dataString
}
val sanitizer = UrlQuerySanitizer(myURL)
// We don't want to manually define every expected query *key*, so we set this to true
sanitizer.allowUnregisteredParamaters = true
val parameterNamesToValues: List<UrlQuerySanitizer.ParameterValuePair> = sanitizer.parameterList
val parameterIterator: Iterator<UrlQuerySanitizer.ParameterValuePair> = parameterNamesToValues.iterator()
// Helper simply so we can display all values on screen
val stringBuilder = StringBuilder()
while (parameterIterator.hasNext()) {
val parameterValuePair: UrlQuerySanitizer.ParameterValuePair = parameterIterator.next()
val parameterName: String = parameterValuePair.mParameter
val parameterValue: String = parameterValuePair.mValue
// Append string to display all key value pairs
stringBuilder.append("Key: $parameterName\nValue: $parameterValue\n\n")
}
// Set a textView's text to display the string
val paramListString = stringBuilder.toString()
val textView: TextView = findViewById(R.id.activity_title) as TextView
textView.text = "Paramlist is \n\n$paramListString"
// to check if the url has specific keys
if (sanitizer.hasParameter("type")) {
val type = sanitizer.getValue("type")
println("sanitizer has type param $type")
}
This could also be a solution without having to introduce a new method:
item = collection["item"] != null ? collection["item"].ToString() : null;
In dotnet core, Request.Headers["X-MyCustomHeader"]
returns StringValues
which will not be null. You can check the count though to make sure it found your header as follows:
var myHeaderValue = Request.Headers["X-MyCustomHeader"];
if(myHeaderValue.Count == 0) return Unauthorized();
string myHeader = myHeaderValue.ToString(); //For illustration purposes.
Here is how I would do it if working with a large number of "to remove" values that would take a long time to manually remove.
I had same problem and I solved using this code
HTML
<span id="current"></span><br>
<input type="number" id="n" value="5" step=".5" />
You can add just 3 first lines the others parts is optional.
$('#n').on('change paste', function () {
$("#current").html($(this).val())
});
// here when click on spinner to change value, call trigger change
$(".input-group-btn-vertical").click(function () {
$("#n").trigger("change");
});
// you can use this to block characters non numeric
$("#n").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 || (e.keyCode === 65 && e.ctrlKey === true) || (e.keyCode >= 35 && e.keyCode <= 40))
return;
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105))
e.preventDefault();
});
Example here : http://jsfiddle.net/XezmB/1303/
For iOS 7.0, I've found that the contentInset trick no longer works. This is the code I used to get rid of the margin/padding in iOS 7.
This brings the left edge of the text to the left edge of the container:
textView.textContainer.lineFragmentPadding = 0
This causes the top of the text to align with the top of the container
textView.textContainerInset = .zero
Both Lines are needed to completely remove the margin/padding.
z
means (un)z_ip.x
means ex_tract files from the archive.v
means print the filenames v_erbosely.f
means the following argument is a f_ilename.For more details, see tar
's man page.
you want to make sure that the user selects anything but "Choose an option" (which is the default one). So that it won't validate if you choose the first option. How can this be done?
You can do this by simple adding attribute required = "required" in the select tag. you can see it in below code
<select id="select" required="required">
<option value="">Choose an option</option>
<option value="option1">Option1</option>
<option value="option2">Option2</option>
<option value="option3">Option3</option>
</select>
It worked fine for me at chorme, firefox and internet explorer. Thanks
I just came across this, while looking for something else.
I would recommend to go with the methods in the os
package. This is because you can make it more general, compensating for any weird case.
You can do something like:
import os
the_file = 'aaaa/bbbb/ccc.ddd'
extensions_list = ['ddd', 'eee', 'fff']
if os.path.splitext(the_file)[-1] in extensions_list:
# Do your thing.
"The
==
operator checks to see if twoObjects
are exactly the sameObject
."
http://leepoint.net/notes-java/data/strings/12stringcomparison.html
String
is an Object
in java, so it falls into that category of comparison rules.
"2) Can we use Dijksra’s algorithm for shortest paths for graphs with negative weights – one idea can be, calculate the minimum weight value, add a positive value (equal to absolute value of minimum weight value) to all weights and run the Dijksra’s algorithm for the modified graph. Will this algorithm work?"
This absolutely doesn't work unless all shortest paths have same length. For example given a shortest path of length two edges, and after adding absolute value to each edge, then the total path cost is increased by 2 * |max negative weight|. On the other hand another path of length three edges, so the path cost is increased by 3 * |max negative weight|. Hence, all distinct paths are increased by different amounts.
@nobar's answer helpfully shows how to use tab completion to list a makefile's targets.
This works great for platforms that provide this functionality by default (e.g., Debian, Fedora).
On other platforms (e.g., Ubuntu) you must explicitly load this functionality, as implied by @hek2mgl's answer:
. /etc/bash_completion
installs several tab-completion functions, including the one for make
make
:
. /usr/share/bash-completion/completions/make
_complete_make() { COMPREPLY=($(compgen -W "$(make -pRrq : 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($1 !~ "^[#.]") {print $1}}' | egrep -v '^[^[:alnum:]]' | sort | xargs)" -- "${COMP_WORDS[$COMP_CWORD]}")); }
complete -F _complete_make make
-f <file>
.From the first link on google;
function call_func(_0x41dcx2) {
var _0x41dcx3 = eval('(' + _0x41dcx2 + ')');
var _0x41dcx4 = document['createElement']('div');
var _0x41dcx5 = _0x41dcx3['id'];
var _0x41dcx6 = _0x41dcx3['Student_name'];
var _0x41dcx7 = _0x41dcx3['student_dob'];
var _0x41dcx8 = '<b>ID:</b>';
_0x41dcx8 += '<a href="/learningyii/index.php?r=student/view& id=' + _0x41dcx5 + '">' + _0x41dcx5 + '</a>';
_0x41dcx8 += '<br/>';
_0x41dcx8 += '<b>Student Name:</b>';
_0x41dcx8 += _0x41dcx6;
_0x41dcx8 += '<br/>';
_0x41dcx8 += '<b>Student DOB:</b>';
_0x41dcx8 += _0x41dcx7;
_0x41dcx8 += '<br/>';
_0x41dcx4['innerHTML'] = _0x41dcx8;
_0x41dcx4['setAttribute']('class', 'view');
$('#StudentGridViewId')['find']('.items')['prepend'](_0x41dcx4);
};
It won't get you all the way back to source, and that's not really possible, but it'll get you out of a hole.
It is not elegant but possible to do it as one-liner <a>
element
<a href onclick="event.preventDefault(); location+='&like=like'">Like</a>
_x000D_
Here is a code snippet that works with Hibernate 4 based on Dominik's answer
Connection getConnection() {
Session session = entityManager.unwrap(Session.class);
MyWork myWork = new MyWork();
session.doWork(myWork);
return myWork.getConnection();
}
private static class MyWork implements Work {
Connection conn;
@Override
public void execute(Connection arg0) throws SQLException {
this.conn = arg0;
}
Connection getConnection() {
return conn;
}
}
In my case there was no change in projects, it just stopped to compile and with "type or namespace name XXX does not exist" and in the complaining class itself intellisense for that XXX namespace/class works fine. The problem was in references indeed!
Steps to reproduce:
Solution has ProjectA, ProjectB.
ProjectA references to third party log4net and it is marked Copy local: true
.
ProjectB references ProjectA and does not have reference to log4net.
Solution compiles fine.
Change in ProjectA: reference property for log4net to Copy local: false
.
This is because ProjectB
bin folder is missing third party library (log4net in my case)!
In this case solution would be -
Copy local: true
or you can also use OPEN Sql to find the number of rows using the COUNT Grouping clause and also there is system field SY-LINCT to count the lines(ROWS) of your table.
It depends on the context.
"undefined" means this value does not exist. typeof
returns "undefined"
"null" means this value exists with an empty value. When you use typeof
to test for "null", you will see that it's an object. Other case when you serialize "null" value to backend server like asp.net mvc, the server will receive "null", but when you serialize "undefined", the server is unlikely to receive a value.
the previous response is ASP.NET only
you need a reference to jquery (perhaps from a CDN): http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.js
and then a similar block of code but simpler...
$.ajax({ url: '/Controller/Action/Id',
success: function(data) { alert(data); },
statusCode : {
404: function(content) { alert('cannot find resource'); },
500: function(content) { alert('internal server error'); }
},
error: function(req, status, errorObj) {
// handle status === "timeout"
// handle other errors
}
});
I've added some necessary handlers, 404 and 500 happen all the time if you are debugging code. Also, a lot of other errors, such as timeout, will filter out through the error handler.
ASP.NET MVC Controllers handle requests, so you just need to request the correct URL and the controller will pick it up. This code sample with work in environments other than ASP.NET
I know this is a really old post, but I found it in searching for a solution to the same problem. I don't want a nested if-statement, and Switch is apparently newer than the version of Excel I'm using. I figured out what was going wrong with my code, so I figured I'd share here in case it helps someone else.
I remembered that VLOOKUP requires the source table to be sorted alphabetically/numerically for it to work. I was initially trying to do this...
=LOOKUP(LOWER(LEFT($T$3, 1)), {"s","l","m"}, {-1,1,0})
and it started working when I did this...
=LOOKUP(LOWER(LEFT($T$3, 1)), {"l","m","s"}, {1,0,-1})
I was initially thinking the last value might turn out to be a default, so I wanted the zero at the last place. That doesn't seem to be the behavior anyway, so I just put the possible matches in order, and it worked.
Edit: As a final note, I see that the example in the original post has letters in alphabetical order, but I imagine the real use case might have been different if the error was happening and the letters A, B, and C were just examples.
Assign something to your strings. This will definitely help.
Please try to fix this by setting the locale variables:
export LC_ALL="en_US.UTF-8"
export LC_CTYPE="en_US.UTF-8"
Yeah.
command >> file
to redirect just stdout of command
.
command >> file 2>&1
to redirect stdout and stderr to the file (works in bash, zsh)
And if you need to use sudo
, remember that just
sudo command >> /file/requiring/sudo/privileges
does not work, as privilege elevation applies to command
but not shell redirection part. However, simply using
tee
solves the problem:
command | sudo tee -a /file/requiring/sudo/privileges
You have a bad table design. You can't autoincrement a string, that doesn't make any sense. You have basically two options:
1.) change type of ID to int
instead of string
2.) not recommended!!! - handle autoincrement by yourself. You first need to get the latest value from the database, parse it to the integer, increment it and attach it to the entity as a string again. VERY BAD idea
First option requires to change every table that has a reference to this table, BUT it's worth it.
This tutorial gives a simple, yet elegant, solution, which i transcribe:
#include <sstream>
#include <string>
#include <stdexcept>
class BadConversion : public std::runtime_error {
public:
BadConversion(std::string const& s)
: std::runtime_error(s)
{ }
};
inline std::string stringify(double x)
{
std::ostringstream o;
if (!(o << x))
throw BadConversion("stringify(double)");
return o.str();
}
...
std::string my_val = stringify(val);
You can use the struct's pack:
In [11]: struct.pack(">I", 1)
Out[11]: '\x00\x00\x00\x01'
The ">" is the byte-order (big-endian) and the "I" is the format character. So you can be specific if you want to do something else:
In [12]: struct.pack("<H", 1)
Out[12]: '\x01\x00'
In [13]: struct.pack("B", 1)
Out[13]: '\x01'
This works the same on both python 2 and python 3.
Note: the inverse operation (bytes to int) can be done with unpack.
nvm use 8.11.4
Just go with nvm use node_version
Kotlin: (If anyone needs)
var mText = text.substring(0, text.length.coerceAtMost(20))
try this:
SELECT
t.*
FROM TestData t
INNER JOIN (SELECT
MIN(ID) as MinID
FROM TestData
WHERE SKU LIKE 'FOO-%'
) dt ON t.ID=dt.MinID
EDIT
once the OP corrected his samle output (previously had only ONE result row, now has all shown), this is the correct query:
declare @TestData table (ID int, sku char(6), product varchar(15))
insert into @TestData values (1 , 'FOO-23' ,'Orange')
insert into @TestData values (2 , 'BAR-23' ,'Orange')
insert into @TestData values (3 , 'FOO-24' ,'Apple')
insert into @TestData values (4 , 'FOO-25' ,'Orange')
--basically the same as @Aaron Alton's answer:
SELECT
dt.ID, dt.SKU, dt.Product
FROM (SELECT
ID, SKU, Product, ROW_NUMBER() OVER (PARTITION BY PRODUCT ORDER BY ID) AS RowID
FROM @TestData
WHERE SKU LIKE 'FOO-%'
) AS dt
WHERE dt.RowID=1
ORDER BY dt.ID
PARTITION BY Divides the result set into partitions. The window function is applied to each partition separately and computation restarts for each partition.
Found at this link: OVER Clause
You must use LEFT JOIN
instead of INNER JOIN
SELECT person.person_id, COUNT(appointment.person_id) AS "number_of_appointments"
FROM person
LEFT JOIN appointment ON person.person_id = appointment.person_id
GROUP BY person.person_id;
$htmlIngressCss='<style>';
$multiOptions = array("" => "All");
$resIn = $this->commonDB->getIngressTrunk();
while ($row = $resIn->fetch()) {
if($row['IsActive']==0){
$htmlIngressCss .= '.ingressClass select, option[value="'.$row['TrunkInfoID'].'"] {color:red;font-weight:bold;}';
}
$multiOptions[$row['TrunkInfoID']] = $row['IngressTrunkName'];
}
$htmlIngressCss.='</style>';
add $htmlIngressCss
in your html portion :)
One idea is to use String... args
public class Sample {
void demoMethod(String... args) {
for (String arg : args) {
System.out.println(arg);
}
}
public static void main(String args[] ) {
new Sample().demoMethod("ram", "rahim", "robert");
new Sample().demoMethod("krishna", "kasyap");
new Sample().demoMethod();
}
}
Output
ram
rahim
robert
krishna
kasyap
from https://www.tutorialspoint.com/Does-Java-support-default-parameter-values-for-a-method
Do a row div.
Like this:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">_x000D_
<div class="grid">_x000D_
<div class="row">_x000D_
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 bg-success">Under me should be a DIV</div>_x000D_
<div class="col-lg-6 col-md-6 col-sm-5 col-xs-12 bg-danger">Under me should be a DIV</div>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="col-lg-3 col-md-3 col-sm-4 col-xs-12 bg-warning">I am the last DIV</div>_x000D_
</div>_x000D_
</div>
_x000D_
All this are still up and working smoothly! (as of 23 Sep 2019)
Piece of advice: Do not direcly depend only on one of them; try to use one but have a contigency plan considering others! The more you use, the better!
Good luck!
I am not very good with this but KeyboardEvent
=> see KeyboardEvent
is initialized with initKeyEvent
.
Here is an example for emitting event on <input type="text" />
element
document.getElementById("txbox").addEventListener("keypress", function(e) {_x000D_
alert("Event " + e.type + " emitted!\nKey / Char Code: " + e.keyCode + " / " + e.charCode);_x000D_
}, false);_x000D_
_x000D_
document.getElementById("btn").addEventListener("click", function(e) {_x000D_
var doc = document.getElementById("txbox");_x000D_
var kEvent = document.createEvent("KeyboardEvent");_x000D_
kEvent.initKeyEvent("keypress", true, true, null, false, false, false, false, 74, 74);_x000D_
doc.dispatchEvent(kEvent);_x000D_
}, false);
_x000D_
<input id="txbox" type="text" value="" />_x000D_
<input id="btn" type="button" value="CLICK TO EMIT KEYPRESS ON TEXTBOX" />
_x000D_
If you've got the Java EE JDK with Glassfish, it's in glassfish3/glassfish/modules/javax.servlet-api.jar.
You need to close the connection before you can use the output parameters. Something like this
con.Close();
MessageBox.Show(cmd.Parameters["@code"].Value.ToString());
If you want to notify the user/take action whenever a network/connection change occur.
Use NLM API:
You can consider shapely:
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon
point = Point(0.5, 0.5)
polygon = Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])
print(polygon.contains(point))
From the methods you've mentioned I've only used the second, path.contains_points
, and it works fine. In any case depending on the precision you need for your test I would suggest creating a numpy bool grid with all nodes inside the polygon to be True (False if not). If you are going to make a test for a lot of points this might be faster (although notice this relies you are making a test within a "pixel" tolerance):
from matplotlib import path
import matplotlib.pyplot as plt
import numpy as np
first = -3
size = (3-first)/100
xv,yv = np.meshgrid(np.linspace(-3,3,100),np.linspace(-3,3,100))
p = path.Path([(0,0), (0, 1), (1, 1), (1, 0)]) # square with legs length 1 and bottom left corner at the origin
flags = p.contains_points(np.hstack((xv.flatten()[:,np.newaxis],yv.flatten()[:,np.newaxis])))
grid = np.zeros((101,101),dtype='bool')
grid[((xv.flatten()-first)/size).astype('int'),((yv.flatten()-first)/size).astype('int')] = flags
xi,yi = np.random.randint(-300,300,100)/100,np.random.randint(-300,300,100)/100
vflag = grid[((xi-first)/size).astype('int'),((yi-first)/size).astype('int')]
plt.imshow(grid.T,origin='lower',interpolation='nearest',cmap='binary')
plt.scatter(((xi-first)/size).astype('int'),((yi-first)/size).astype('int'),c=vflag,cmap='Greens',s=90)
plt.show()
, the results is this:
Assuming Python 3 (in Python 2, this difference is a little less well-defined) - a string is a sequence of characters, ie unicode codepoints; these are an abstract concept, and can't be directly stored on disk. A byte string is a sequence of, unsurprisingly, bytes - things that can be stored on disk. The mapping between them is an encoding - there are quite a lot of these (and infinitely many are possible) - and you need to know which applies in the particular case in order to do the conversion, since a different encoding may map the same bytes to a different string:
>>> b'\xcf\x84o\xcf\x81\xce\xbdo\xcf\x82'.decode('utf-16')
'?????'
>>> b'\xcf\x84o\xcf\x81\xce\xbdo\xcf\x82'.decode('utf-8')
'to??o?'
Once you know which one to use, you can use the .decode()
method of the byte string to get the right character string from it as above. For completeness, the .encode()
method of a character string goes the opposite way:
>>> 'to??o?'.encode('utf-8')
b'\xcf\x84o\xcf\x81\xce\xbdo\xcf\x82'
The free version of TightVnc viewer (I have TightVnc Viewer 1.5.4 8/3/2011) build does not support this. What you need is RealVNC but VNC Enterprise Edition 4.2 or the Personal Edition. Unfortunately this is not free and you have to pay for a license.
From the RealVNC website [releasenote] http://www.realvnc.com/products/enterprise/4.2/release-notes.html
VNC Viewer: Full-screen mode can span monitors on a multi-monitor system.
Quite late to this party, today I had the same problem.
The right answer on macOs I think is use jenv
brew install jenv openjdk@11
jenv add /usr/local/opt/openjdk@11
And then add into Intellij IDEA as new SDK the following path:
~/.jenv/versions/11/libexec/openjdk.jdk/Contents/Home/
In the first place consider the Small grid, see: http://getbootstrap.com/css/#grid-options. A max container width of 750 px will maybe to small for you (also read: Why does Bootstrap 3 force the container width to certain sizes?)
When using the Small grid use media queries to set the max-container width:
@media (min-width: 768px) { .container { max-width: 750px; } }
Second also read this question: Bootstrap 3 - 940px width grid?, possible duplicate?
12 x 60 = 720px for the columns and 11 x 20 = 220px
there will also a gutter of 20px on both sides of the grid so 220 + 720 + 40 makes 980px
there is 'no' @ColumnWidth
You colums width will be calculated dynamically based on your settings in variables.less.
you could set @grid-columns
and @grid-gutter-width
. The width of a column will be set as a percentage via grid.less in mixins.less:
.calc-grid(@index, @class, @type) when (@type = width) {
.col-@{class}-@{index} {
width: percentage((@index / @grid-columns));
}
}
update Set @grid-gutter-width to 20px;, @container-desktop: 940px;, @container-large-desktop: @container-desktop and recompile bootstrap.
First, get your tombstone stack trace, it will be printed every time your app crashes. Something like this:
*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
Build fingerprint: 'XXXXXXXXX'
pid: 1658, tid: 13086 >>> system_server <<<
signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 64696f7e
r0 00000000 r1 00000001 r2 ad12d1e8 r3 7373654d
r4 64696f72 r5 00000406 r6 00974130 r7 40d14008
r8 4b857b88 r9 4685adb4 10 00974130 fp 4b857ed8
ip 00000000 sp 4b857b50 lr afd11108 pc ad115ebc cpsr 20000030
d0 4040000040000000 d1 0000004200000003
d2 4e72cd924285e370 d3 00e81fe04b1b64d8
d4 3fbc71c7009b64d8 d5 3fe999999999999a
d6 4010000000000000 d7 4000000000000000
d8 4000000000000000 d9 0000000000000000
d10 0000000000000000 d11 0000000000000000
d12 0000000000000000 d13 0000000000000000
d14 0000000000000000 d15 0000000000000000
scr 80000012
#00 pc 000108d8 /system/lib/libc.so
#01 pc 0003724c /system/lib/libxvi020.so
#02 pc 0000ce02 /system/lib/libxvi020.so
#03 pc 0000d672 /system/lib/libxvi020.so
#04 pc 00010cce /system/lib/libxvi020.so
#05 pc 00004432 /system/lib/libwimax_jni.so
#06 pc 00011e74 /system/lib/libdvm.so
#07 pc 0004354a /system/lib/libdvm.so
#08 pc 00017088 /system/lib/libdvm.so
#09 pc 0001c210 /system/lib/libdvm.so
#10 pc 0001b0f8 /system/lib/libdvm.so
#11 pc 00059c24 /system/lib/libdvm.so
#12 pc 00059e3c /system/lib/libdvm.so
#13 pc 0004e19e /system/lib/libdvm.so
#14 pc 00011b94 /system/lib/libc.so
#15 pc 0001173c /system/lib/libc.so
code around pc:
ad115e9c 4620eddc bf00bd70 0001736e 0001734e
ad115eac 4605b570 447c4c0a f7f44620 e006edc8
ad115ebc 42ab68e3 68a0d103 f7f42122 6864edd2
ad115ecc d1f52c00 44784803 edbef7f4 bf00bd70
ad115edc 00017332 00017312 2100b51f 46682210
code around lr:
afd110e8 e2166903 1a000018 e5945000 e1a02004
afd110f8 e2055a02 e1a00005 e3851001 ebffed92
afd11108 e3500000 13856002 1a000001 ea000009
afd11118 ebfffe50 e1a01004 e1a00006 ebffed92
afd11128 e1a01005 e1550000 e1a02006 e3a03000
stack:
4b857b10 40e43be8
4b857b14 00857280
4b857b18 00000000
4b857b1c 034e8968
4b857b20 ad118ce9 /system/lib/libnativehelper.so
4b857b24 00000002
4b857b28 00000406
Then, use the addr2line
utility (find it in your NDK tool-chain) to find the function that crashes. In this sample, you do
addr2line -e -f libc.so 0001173c
And you will see where you got the problem. Of course this wont help you since it is in libc.
So you might combine the utilities of arm-eabi-objdump
to find the final target.
Believe me, it is a tough task.
Just for an update. I think I was doing Android native build from the whole-source-tree for quite a long time, until today I have myself carefully read the NDK documents. Ever since the release NDK-r6, it has provided a utility called ndk-stack
.
Following is the content from official NDK documents with the NDK-r9 tar ball.
Overview:
ndk-stack
is a simple tool that allows you to filter stack traces as they appear in the output of 'adb logcat' and replace any address inside a shared library with the corresponding : values.
In a nutshell, it will translate something like:
I/DEBUG ( 31): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
I/DEBUG ( 31): Build fingerprint: 'generic/google_sdk/generic/:2.2/FRF91/43546:eng/test-keys'
I/DEBUG ( 31): pid: 351, tid: 351 %gt;%gt;%gt; /data/local/ndk-tests/crasher <<<
I/DEBUG ( 31): signal 11 (SIGSEGV), fault addr 0d9f00d8
I/DEBUG ( 31): r0 0000af88 r1 0000a008 r2 baadf00d r3 0d9f00d8
I/DEBUG ( 31): r4 00000004 r5 0000a008 r6 0000af88 r7 00013c44
I/DEBUG ( 31): r8 00000000 r9 00000000 10 00000000 fp 00000000
I/DEBUG ( 31): ip 0000959c sp be956cc8 lr 00008403 pc 0000841e cpsr 60000030
I/DEBUG ( 31): #00 pc 0000841e /data/local/ndk-tests/crasher
I/DEBUG ( 31): #01 pc 000083fe /data/local/ndk-tests/crasher
I/DEBUG ( 31): #02 pc 000083f6 /data/local/ndk-tests/crasher
I/DEBUG ( 31): #03 pc 000191ac /system/lib/libc.so
I/DEBUG ( 31): #04 pc 000083ea /data/local/ndk-tests/crasher
I/DEBUG ( 31): #05 pc 00008458 /data/local/ndk-tests/crasher
I/DEBUG ( 31): #06 pc 0000d362 /system/lib/libc.so
I/DEBUG ( 31):
Into the more readable output:
********** Crash dump: **********
Build fingerprint: 'generic/google_sdk/generic/:2.2/FRF91/43546:eng/test-keys'
pid: 351, tid: 351 >>> /data/local/ndk-tests/crasher <<<
signal 11 (SIGSEGV), fault addr 0d9f00d8
Stack frame #00 pc 0000841e /data/local/ndk-tests/crasher : Routine zoo in /tmp/foo/crasher/jni/zoo.c:13
Stack frame #01 pc 000083fe /data/local/ndk-tests/crasher : Routine bar in /tmp/foo/crasher/jni/bar.c:5
Stack frame #02 pc 000083f6 /data/local/ndk-tests/crasher : Routine my_comparison in /tmp/foo/crasher/jni/foo.c:9
Stack frame #03 pc 000191ac /system/lib/libc.so
Stack frame #04 pc 000083ea /data/local/ndk-tests/crasher : Routine foo in /tmp/foo/crasher/jni/foo.c:14
Stack frame #05 pc 00008458 /data/local/ndk-tests/crasher : Routine main in /tmp/foo/crasher/jni/main.c:19
Stack frame #06 pc 0000d362 /system/lib/libc.so
Usage:
To do this, you will first need a directory containing symbolic versions of your application's shared libraries. If you use the NDK build system (i.e. ndk-build
), then these are always located under $PROJECT_PATH/obj/local/, where stands for your device's ABI (i.e. armeabi
by default).
You can feed the logcat
text either as direct input to the program, e.g.:
adb logcat | $NDK/ndk-stack -sym $PROJECT_PATH/obj/local/armeabi
Or you can use the -dump option to specify the logcat as an input file, e.g.:
adb logcat > /tmp/foo.txt
$NDK/ndk-stack -sym $PROJECT_PATH/obj/local/armeabi -dump foo.txt
IMPORTANT :
The tool looks for the initial line containing starts in the logcat
output, i.e. something that looks like:
*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
When copy/pasting traces, don't forget this line from the traces, or ndk-stack
won't work correctly.
TODO:
A future version of ndk-stack
will try to launch adb logcat
and select the library path automatically. For now, you'll have to do these steps manually.
As of now, ndk-stack
doesn't handle libraries that don't have debug information in them. It may be useful to try to detect the nearest function entry point to a given PC address (e.g. as in the libc.so example above).
in my case app want to use iCloud services, but in distr. provision profile wasn't set iCloud enabled. turn it on and refresh profile.
you should see this tutorial: https://scotch.io/@micwanyoike/how-to-add-fonts-to-a-react-project
import WebFont from 'webfontloader';
WebFont.load({
google: {
families: ['Titillium Web:300,400,700', 'sans-serif']
}
});
I just tried this method and I can say that it works very well ;)
This can be achieved purely with JavaScript.
I see the answer I wanted to write has been answered by lynx in comments to the question.
But I'm going to write answer anyway because just like me, people sometimes forget to read the comments.
So, if you just want to get an element's distance (in Pixels) from the top of your screen window, here is what you need to do:
// Fetch the element
var el = document.getElementById("someElement");
// Use the 'top' property of 'getBoundingClientRect()' to get the distance from top
var distanceFromTop = el.getBoundingClientRect().top;
Thats it!
Hope this helps someone :)
In addition to @Cristian's answer above, I had to do two more steps to get it working correctly. I will sum all of it here:
R.java
class and the press F6
(Refactor->Move...). It will allow you to move the class to another package, and all references to that class will be updated.build.gradle
file : android / defaultconfig / application ID [source].You can specify GLOBIGNORE
and use the pattern *
GLOBIGNORE='ignore1:ignore2' scp -r source/* remoteurl:remoteDir
You may wish to have general rules which you combine or override by using export GLOBIGNORE
, but for ad-hoc usage simply the above will do. The :
character is used as delimiter for multiple values.
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.js"></script>
<script type="text/javascript" src="jquery-2.1.0.js"></script>
<script type="text/javascript" >
function openOnImageClick()
{
//alert("Jai Sh Raam");
// document.getElementById("images").src = "fruits.jpg";
var img = document.createElement('img');
img.setAttribute('src', 'tiger.jpg');
img.setAttribute('width', '200');
img.setAttribute('height', '150');
document.getElementById("images").appendChild(img);
}
</script>
</head>
<body>
<h1>Screen Shot View</h1>
<p>Click the Tiger to display the Image</p>
<div id="images" >
</div>
<img src="tiger.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick()" />
<img src="Logo1.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick()" />
</body>
</html>
You might want to give a look at this simple Javascript method to be invoked when clicking on a link to make a panel/div expande or collapse.
<script language="javascript">
function toggle(elementId) {
var ele = document.getElementById(elementId);
if(ele.style.display == "block") {
ele.style.display = "none";
}
else {
ele.style.display = "block";
}
}
</script>
You can pass the div ID and it will toggle between display 'none' or 'block'.
Original source on snip2code - How to collapse a div in html
Here's the result I finally ended up using. It's a modified version of the classes by dgorissen above.
File: threadpool.py
from queue import Queue, Empty
import threading
from threading import Thread
class Worker(Thread):
_TIMEOUT = 2
""" Thread executing tasks from a given tasks queue. Thread is signalable,
to exit
"""
def __init__(self, tasks, th_num):
Thread.__init__(self)
self.tasks = tasks
self.daemon, self.th_num = True, th_num
self.done = threading.Event()
self.start()
def run(self):
while not self.done.is_set():
try:
func, args, kwargs = self.tasks.get(block=True,
timeout=self._TIMEOUT)
try:
func(*args, **kwargs)
except Exception as e:
print(e)
finally:
self.tasks.task_done()
except Empty as e:
pass
return
def signal_exit(self):
""" Signal to thread to exit """
self.done.set()
class ThreadPool:
"""Pool of threads consuming tasks from a queue"""
def __init__(self, num_threads, tasks=[]):
self.tasks = Queue(num_threads)
self.workers = []
self.done = False
self._init_workers(num_threads)
for task in tasks:
self.tasks.put(task)
def _init_workers(self, num_threads):
for i in range(num_threads):
self.workers.append(Worker(self.tasks, i))
def add_task(self, func, *args, **kwargs):
"""Add a task to the queue"""
self.tasks.put((func, args, kwargs))
def _close_all_threads(self):
""" Signal all threads to exit and lose the references to them """
for workr in self.workers:
workr.signal_exit()
self.workers = []
def wait_completion(self):
"""Wait for completion of all the tasks in the queue"""
self.tasks.join()
def __del__(self):
self._close_all_threads()
def create_task(func, *args, **kwargs):
return (func, args, kwargs)
To use the pool
from random import randrange
from time import sleep
delays = [randrange(1, 10) for i in range(30)]
def wait_delay(d):
print('sleeping for (%d)sec' % d)
sleep(d)
pool = ThreadPool(20)
for i, d in enumerate(delays):
pool.add_task(wait_delay, d)
pool.wait_completion()
If you want to use a function form a package or module in python you have to import and reference them. For example normally you do the following to draw 5 points( [1,5],[2,4],[3,3],[4,2],[5,1]) in the space:
import matplotlib.pyplot
matplotlib.pyplot.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
matplotlib.pyplot.show()
In your solution
from matplotlib import*
This imports the package matplotlib and "plot is not defined" means there is no plot function in matplotlib you can access directly, but instead if you import as
from matplotlib.pyplot import *
plot([1,2,3,4,5],[5,4,3,2,1],"bx")
show()
Now you can use any function in matplotlib.pyplot without referencing them with matplotlib.pyplot.
I would recommend you to name imports you have, in this case you can prevent disambiguation and future problems with the same function names. The last and clean version of above example looks like:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
plt.show()
I created JS performance test for it http://jsperf.com/split-and-join-vs-replace2
On the link put a hash:
<a href="otherpage.html#elementID">Jump</a>
And on other page, you can do:
$('html,body').animate({
scrollTop: $(window.location.hash).offset().top
});
On other page, you should have element with id set to elementID
to scroll to. Of course you can change the name of it.
Generating ssh keys on the client solved it for me
$ ssh-keygen -t rsa
Yes, bool
. It's not exactly the same -- '0'
is True
, but None
, False
, []
, 0
, 0.0
, and ""
are all False
.
bool
is used implicitly when you evaluate an object in a condition like an if
or while
statement, conditional expression, or with a boolean operator.
If you wanted to handle strings containing numbers as PHP does, you could do something like:
def empty(value):
try:
value = float(value)
except ValueError:
pass
return bool(value)
why dont you use export, then click 'Custom - display all possible options' radio button, then choose your database, then go to Output and choose 'View output as text' just scroll down and Go. Voila!
For people using jQuery, there is an excellent plugin for handling key events:
For capturing ?+S and Ctrl+S I'm using this:
$(window).bind('keydown.ctrl_s keydown.meta_s', function(event) {
event.preventDefault();
// Do something here
});
Even though, I have been using 400 to represent logical errors also, I have to say that returning 400 is wrong in this case because of the way the spec reads. Here is why i think so, the logical error could be that a relationship with another entity was failing or not satisfied and making changes to the other entity could cause the same exact to pass later. Like trying to (completely hypothetical) add an employee as a member of a department when that employee does not exist (logical error). Adding employee as member request could fail because employee does not exist. But the same exact request could pass after the employee has been added to the system.
Just my 2 cents ... We need lawyers & judges to interpret the language in the RFC these days :)
Thank You, Vish
I encountered the same problem, even though I did not make any dynamic memory allocation in my program, but I was accessing a vector's index without allocating memory for it.
So, if the same case, better allocate some memory using resize()
and then access vector elements.
I think if you overwrite a method and want to all the super-class version of it (like, say for equals
), then you virtually always want to call the direct superclass version first, which one will call its superclass version in turn if it wants.
I think it only makes rarely sense (if at all. i can't think of a case where it does) to call some arbitrary superclass' version of a method. I don't know if that is possible at all in Java. It can be done in C++:
this->ReallyTheBase::foo();
You can also try this.
consider today's date '28 Dec 2018'(for example)
this.date = new Date().toISOString().slice(0,10);
new Date() we get as: Fri Dec 28 2018 11:44:33 GMT+0530 (India Standard Time)
toISOString will convert to : 2018-12-28T06:15:27.479Z
slice(0,10) we get only first 10 characters as date which contains yyyy-mm-dd : 2018-12-28.
By default reference types have reference equality (i.e. two instances are only equal if they are the same object).
You need to override Object.Equals
(and Object.GetHashCode
to match) to implement your own equality. (And it is then good practice to implement an equality, ==
, operator.)
You can use nunique
in pandas:
df.hID.nunique()
# 5
I was running Eclipse Neon.2 and the Android SDK Build-tools + platform-tools version 26 on Mac OS 10.12.4 and none of the above answers (including the accepted answer) worked for me.
What did work was to
Quit Eclipse
Remove the folder <android-sdk>/build-tools/26.0.0
and to install the (older) version 25.0.3 of the build tools through the Android SDK manager.
Start Eclipse again
This is using ms-Dropdown : https://github.com/marghoobsuleman/ms-Dropdown
Data resource is json. But you dont need to use json. If you want you can use with css.
Css example : https://github.com/marghoobsuleman/ms-Dropdown/tree/master/examples
Json Example : http://jsfiddle.net/tcibikci/w3rdhj4s/6
HTML
<div id="byjson"></div>
Script
<script>
var jsonData = [
{description:'Choos your payment gateway', value:'', text:'Payment Gateway'},
{image:'https://via.placeholder.com/50', description:'My life. My card...', value:'amex', text:'Amex'},
{image:'https://via.placeholder.com/50', description:'It pays to Discover...', value:'Discover', text:'Discover'},
{image:'https://via.placeholder.com/50', title:'For everything else...', description:'For everything else...', value:'Mastercard', text:'Mastercard'},
{image:'https://via.placeholder.com/50', description:'Sorry not available...', value:'cash', text:'Cash on devlivery', disabled:true},
{image:'https://via.placeholder.com/50', description:'All you need...', value:'Visa', text:'Visa'},
{image:'https://via.placeholder.com/50', description:'Pay and get paid...', value:'Paypal', text:'Paypal'}
];
$("#byjson").msDropDown({byJson:{data:jsonData, name:'payments2'}}).data("dd");
}
</script>
There is also the Python termcolor module. Usage is pretty simple:
from termcolor import colored
print colored('hello', 'red'), colored('world', 'green')
Or in Python 3:
print(colored('hello', 'red'), colored('world', 'green'))
It may not be sophisticated enough, however, for game programming and the "colored blocks" that you want to do...
Well, i guess M represent the mantissa. Decimal can be used to save money, but it doesn't mean, decimal only used for money.
You can use VBScript regular expression features using OLE Automation. This is way better than the overhead of creating and maintaining an assembly. Please make sure you go through the comments section to get a better modified version of the main one.
http://blogs.msdn.com/b/khen1234/archive/2005/05/11/416392.aspx
DECLARE @obj INT, @res INT, @match BIT;
DECLARE @pattern varchar(255) = '<your regex pattern goes here>';
DECLARE @matchstring varchar(8000) = '<string to search goes here>';
SET @match = 0;
-- Create a VB script component object
EXEC @res = sp_OACreate 'VBScript.RegExp', @obj OUT;
-- Apply/set the pattern to the RegEx object
EXEC @res = sp_OASetProperty @obj, 'Pattern', @pattern;
-- Set any other settings/properties here
EXEC @res = sp_OASetProperty @obj, 'IgnoreCase', 1;
-- Call the method 'Test' to find a match
EXEC @res = sp_OAMethod @obj, 'Test', @match OUT, @matchstring;
-- Don't forget to clean-up
EXEC @res = sp_OADestroy @obj;
If you get SQL Server blocked access to procedure 'sys.sp_OACreate'...
error, use sp_reconfigure
to enable Ole Automation Procedures
. (Yes, unfortunately that is a server level change!)
More information about the Test
method is available here
Happy coding
Since you are asking about .NET, you should change the parameter from Long
to Integer
. .NET's Integer is 32-bit. (Classic VB's integer was only 16-bit.)
Declare Sub Sleep Lib "kernel32.dll" (ByVal Milliseconds As Integer)
Really though, the managed method isn't difficult...
System.Threading.Thread.CurrentThread.Sleep(5000)
Be careful when you do this. In a forms application, you block the message pump and what not, making your program to appear to have hanged. Rarely is sleep
a good idea.
string[] lines = File.ReadAllLines(txtProxyListPath.Text);
List<string> list_lines = new List<string>(lines);
Parallel.ForEach(list_lines, line =>
{
//Your stuff
});
Use:
System.Configuration.ConfigurationSettings.AppSettings["MyKey"];
AppSettings has been deprecated and is now considered obsolete (link).
In addition, the appSettings section of the app.config has been replaced by the applicationSettings section.
As someone else mentioned, you should be using System.Configuration.ConfigurationManager (link) which is new for .NET 2.0.
To switch the display-style between block
and none
you can do something like this:
function toggleDiv(id) {
var div = document.getElementById(id);
div.style.display = div.style.display == "none" ? "block" : "none";
}
working demo: http://jsfiddle.net/BQUyT/2/
This xsl:stylesheet
can use a specified list of column headers and will ensure that the rows will be ordered correctly.
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:csv="csv:csv">
<xsl:output method="text" encoding="utf-8" />
<xsl:strip-space elements="*" />
<xsl:variable name="delimiter" select="','" />
<csv:columns>
<column>name</column>
<column>sublease</column>
<column>addressBookID</column>
<column>boundAmount</column>
<column>rentalAmount</column>
<column>rentalPeriod</column>
<column>rentalBillingCycle</column>
<column>tenureIncome</column>
<column>tenureBalance</column>
<column>totalIncome</column>
<column>balance</column>
<column>available</column>
</csv:columns>
<xsl:template match="/property-manager/properties">
<!-- Output the CSV header -->
<xsl:for-each select="document('')/*/csv:columns/*">
<xsl:value-of select="."/>
<xsl:if test="position() != last()">
<xsl:value-of select="$delimiter"/>
</xsl:if>
</xsl:for-each>
<xsl:text>
</xsl:text>
<!-- Output rows for each matched property -->
<xsl:apply-templates select="property" />
</xsl:template>
<xsl:template match="property">
<xsl:variable name="property" select="." />
<!-- Loop through the columns in order -->
<xsl:for-each select="document('')/*/csv:columns/*">
<!-- Extract the column name and value -->
<xsl:variable name="column" select="." />
<xsl:variable name="value" select="$property/*[name() = $column]" />
<!-- Quote the value if required -->
<xsl:choose>
<xsl:when test="contains($value, '"')">
<xsl:variable name="x" select="replace($value, '"', '""')"/>
<xsl:value-of select="concat('"', $x, '"')"/>
</xsl:when>
<xsl:when test="contains($value, $delimiter)">
<xsl:value-of select="concat('"', $value, '"')"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$value"/>
</xsl:otherwise>
</xsl:choose>
<!-- Add the delimiter unless we are the last expression -->
<xsl:if test="position() != last()">
<xsl:value-of select="$delimiter"/>
</xsl:if>
</xsl:for-each>
<!-- Add a newline at the end of the record -->
<xsl:text>
</xsl:text>
</xsl:template>
</xsl:stylesheet>
I'm not sure that you want to send two SELECT statements in one request statement because you may not be able to access both ResultSet
s. The database may only return the last result set.
Multiple ResultSets
However, if you're calling a stored procedure that you know can return multiple resultsets something like this will work
CallableStatement stmt = con.prepareCall(...);
try {
...
boolean results = stmt.execute();
while (results) {
ResultSet rs = stmt.getResultSet();
try {
while (rs.next()) {
// read the data
}
} finally {
try { rs.close(); } catch (Throwable ignore) {}
}
// are there anymore result sets?
results = stmt.getMoreResults();
}
} finally {
try { stmt.close(); } catch (Throwable ignore) {}
}
Multiple SQL Statements
If you're talking about multiple SQL statements and only one SELECT then your database should be able to support the one String
of SQL. For example I have used something like this on Sybase
StringBuffer sql = new StringBuffer( "SET rowcount 100" );
sql.append( " SELECT * FROM tbl_books ..." );
sql.append( " SET rowcount 0" );
stmt = conn.prepareStatement( sql.toString() );
This will depend on the syntax supported by your database. In this example note the addtional spaces
padding the statements so that there is white space between the staments.
You can use cut with a delimiter like this:
with space delim:
cut -d " " -f1-100,1000-1005 infile.csv > outfile.csv
with tab delim:
cut -d$'\t' -f1-100,1000-1005 infile.csv > outfile.csv
I gave you the version of cut in which you can extract a list of intervals...
Hope it helps!
If you need minimal value for particular column
min(data[,2])
Note: R considers NA
both the minimum and maximum value so if you have NA's in your column, they return: NA
. To remedy, use:
min(data[,2], na.rm=T)
If this occurs IE intranet only, check compatibility settings and uncheck "Display intranet sites in Compatibility mode" .
IE-->settings-->compatibility
Refreshing gradle dependencies works for me: Right click over the project -> Gradle -> Refresh Gradle Project.
You could make the identifier a param for a query selector. For PHP and compatible languages use an associative array (in effect an objects) and then json_encode.
$temp=array('#id' =>array('href'=>'services.html')
,'img' =>array('src'=>"img/SolutionInnerbananer.jpg")
,'.html'=>'<h2 class="fg-white">AboutUs</h2><p class="fg-white">...</p>'
);
echo json_encode($temp);
But HTML don't do it for you without some JS.
{"#id":{"href":"services.html"},"img":{"src":"img\/SolutionInnerbananer.jpg"}
,".html":"<h2 class=\"fg-white\">AboutUs<\/h2><p class=\"fg-white\">...<\/p>"}
Add -fPIC
at the end of CMAKE_CXX_FLAGS
and CMAKE_C_FLAG
Example:
set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall --std=c++11 -O3 -fPIC" )
set( CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -O3 -fPIC" )
This solved my issue.
Seems to work fine.
If you have an empty BEGIN ... END block you might see
Msg 102, Level 15, State 1, Line 10 Incorrect syntax near 'END'.
For Word 2010 and 2013, go to File > Options > Customize Ribbon > Keyboard Shortcuts > All Commands (in left list) > Color: (in right list)
-- at this point, you type in the short cut (such as Alt+r) and select the color (such as red). (This actually goes back to 2003 but I don't have that installed to provide the pathway.)
You have extra spaces after END;
that cause the heredoc not terminated.
Do a reset of the configuration and set the root level to OFF
LogManager.getLogManager().reset();
Logger globalLogger = Logger.getLogger(java.util.logging.Logger.GLOBAL_LOGGER_NAME);
globalLogger.setLevel(java.util.logging.Level.OFF);
One other direction--just unpack the MSI file and get the goodies that way. Saves you from the eventual uninstall . . .
FYI this turned out to be an issue for me where I had two tables in a statement like the following:
SELECT * FROM table1
UNION ALL
SELECT * FROM table2
It worked, but then somewhere along the line the order of columns in one of the table definitions got changed. Changing the *
to SELECT column1, column2
fixed the issue. No idea how that happened, but lesson learned!
If a download fails for some reason Maven will not try to download it within a certain time frame (it leaves a file with a timestamp).
To fix this you can either
Use String.format:
String.format("%.2f", 4.52135);
As per docs:
The locale always used is the one returned by
Locale.getDefault()
.
this
this
(aka "the context") is a special keyword inside each function and its value only depends on how the function was called, not how/when/where it was defined. It is not affected by lexical scopes like other variables (except for arrow functions, see below). Here are some examples:
function foo() {
console.log(this);
}
// normal function call
foo(); // `this` will refer to `window`
// as object method
var obj = {bar: foo};
obj.bar(); // `this` will refer to `obj`
// as constructor function
new foo(); // `this` will refer to an object that inherits from `foo.prototype`
To learn more about this
, have a look at the MDN documentation.
this
ECMAScript 6 introduced arrow functions, which can be thought of as lambda functions. They don't have their own this
binding. Instead, this
is looked up in scope just like a normal variable. That means you don't have to call .bind
. That's not the only special behavior they have, please refer to the MDN documentation for more information.
function MyConstructor(data, transport) {
this.data = data;
transport.on('data', () => alert(this.data));
}
this
You actually don't want to access this
in particular, but the object it refers to. That's why an easy solution is to simply create a new variable that also refers to that object. The variable can have any name, but common ones are self
and that
.
function MyConstructor(data, transport) {
this.data = data;
var self = this;
transport.on('data', function() {
alert(self.data);
});
}
Since self
is a normal variable, it obeys lexical scope rules and is accessible inside the callback. This also has the advantage that you can access the this
value of the callback itself.
this
of the callback - part 1It might look like you have no control over the value of this
because its value is set automatically, but that is actually not the case.
Every function has the method .bind
[docs], which returns a new function with this
bound to a value. The function has exactly the same behavior as the one you called .bind
on, only that this
was set by you. No matter how or when that function is called, this
will always refer to the passed value.
function MyConstructor(data, transport) {
this.data = data;
var boundFunction = (function() { // parenthesis are not necessary
alert(this.data); // but might improve readability
}).bind(this); // <- here we are calling `.bind()`
transport.on('data', boundFunction);
}
In this case, we are binding the callback's this
to the value of MyConstructor
's this
.
Note: When a binding context for jQuery, use jQuery.proxy
[docs] instead. The reason to do this is so that you don't need to store the reference to the function when unbinding an event callback. jQuery handles that internally.
this
of the callback - part 2Some functions/methods which accept callbacks also accept a value to which the callback's this
should refer to. This is basically the same as binding it yourself, but the function/method does it for you. Array#map
[docs] is such a method. Its signature is:
array.map(callback[, thisArg])
The first argument is the callback and the second argument is the value this
should refer to. Here is a contrived example:
var arr = [1, 2, 3];
var obj = {multiplier: 42};
var new_arr = arr.map(function(v) {
return v * this.multiplier;
}, obj); // <- here we are passing `obj` as second argument
Note: Whether or not you can pass a value for this
is usually mentioned in the documentation of that function/method. For example, jQuery's $.ajax
method [docs] describes an option called context
:
This object will be made the context of all Ajax-related callbacks.
Another common manifestation of this problem is when an object method is used as callback/event handler. Functions are first-class citizens in JavaScript and the term "method" is just a colloquial term for a function that is a value of an object property. But that function doesn't have a specific link to its "containing" object.
Consider the following example:
function Foo() {
this.data = 42,
document.body.onclick = this.method;
}
Foo.prototype.method = function() {
console.log(this.data);
};
The function this.method
is assigned as click event handler, but if the document.body
is clicked, the value logged will be undefined
, because inside the event handler, this
refers to the document.body
, not the instance of Foo
.
As already mentioned at the beginning, what this
refers to depends on how the function is called, not how it is defined.
If the code was like the following, it might be more obvious that the function doesn't have an implicit reference to the object:
function method() {
console.log(this.data);
}
function Foo() {
this.data = 42,
document.body.onclick = this.method;
}
Foo.prototype.method = method;
The solution is the same as mentioned above: If available, use .bind
to explicitly bind this
to a specific value
document.body.onclick = this.method.bind(this);
or explicitly call the function as a "method" of the object, by using an anonymous function as callback / event handler and assign the object (this
) to another variable:
var self = this;
document.body.onclick = function() {
self.method();
};
or use an arrow function:
document.body.onclick = () => this.method();
This should work fine.
Workbook wb = new XSSFWorkbook("myWorkbook.xlsx");
Row row=sheet.getRow(0);
CellStyle style=null;
XSSFFont defaultFont= wb.createFont();
defaultFont.setFontHeightInPoints((short)10);
defaultFont.setFontName("Arial");
defaultFont.setColor(IndexedColors.BLACK.getIndex());
defaultFont.setBold(false);
defaultFont.setItalic(false);
XSSFFont font= wb.createFont();
font.setFontHeightInPoints((short)10);
font.setFontName("Arial");
font.setColor(IndexedColors.WHITE.getIndex());
font.setBold(true);
font.setItalic(false);
style=row.getRowStyle();
style.setFillBackgroundColor(IndexedColors.DARK_BLUE.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setFont(font);
If you do not create defaultFont
all your workbook will be using the other one as default.
in some cases where pywin32 is not the direct reference and other libraries require pywin32-ctypes to be installed; causes the "ImportError: No module named win32com" when application bundled with pyinstaller.
running following command solves on python 3.7 - pyinstaller 3.6
pip install pywin32==227
Create a new package And then move the classes of default package in new package and use those classes
For hexadecimal code try this
& 0x00FFFFFF
For RGB one
Red
, Green
, Blue
valuesImplementation
private static string HexConverter(Color c) {
return String.Format("#{0:X6}", c.ToArgb() & 0x00FFFFFF);
}
public static string RgbConverter(Color c) {
return String.Format("RGB({0},{1},{2})", c.R, c.G, c.B);
}
If there is an interface anywhere in the ThreadProvider hierarchy try putting the name of the Interface as the type of your service provider, eg. if you have say this structure:
public class ThreadProvider implements CustomInterface{
...
}
Then in your controller try this:
@Controller
public class ChiusuraController {
@Autowired
private CustomInterface chiusuraProvider;
}
The reason why this is happening is, in your first case when you DID NOT have ChiusuraProvider
extend ThreadProvider
Spring probably was underlying creating a CGLIB based proxy for you(to handle the @Transaction).
When you DID extend from ThreadProvider
assuming that ThreadProvider extends some interface, Spring in that case creates a Java Dynamic Proxy based Proxy, which would appear to be an implementation of that interface instead of being of ChisuraProvider
type.
If you absolutely need to use ChisuraProvider
you can try AspectJ as an alternative or force CGLIB based proxy in the case with ThreadProvider also this way:
<aop:aspectj-autoproxy proxy-target-class="true"/>
Here is some more reference on this from the Spring Reference site: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/classic-aop-spring.html#classic-aop-pfb
The is no API for adding a shortcut to the home screen in iOS, so no third-party browser is capable of providing that functionality.
The best solution is to install the different Python versions in multiple paths.
eg. C:\Python27 for 2.7, and C:\Python33 for 3.3.
Read this for more info: How to run multiple Python versions on Windows
Take a look at the Maven dependency plugin, specifically, the dependency:copy-dependencies goal. Take a look at the example under the heading The dependency:copy-dependencies mojo. Set the outputDirectory configuration property to ${basedir}/target/lib (I believe, you'll have to test).
Hope this helps.
In your form are you passing in any other attributes, via mass assignment that don't belong to your user model, or any of the nested models?
If so, I believe the ActiveRecord::UnknownAttributeError is triggered in this instance.
Otherwise, I think you can just create your own controller, by generating something like this:
# app/controllers/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
def new
super
end
def create
# add custom create logic here
end
def update
super
end
end
And then tell devise to use that controller instead of the default with:
# app/config/routes.rb
devise_for :users, :controllers => {:registrations => "registrations"}
One Additional point:
When you are converting from tsql
to plsql
you have to worry about no_data_found
exception
DECLARE
v_var NUMBER;
BEGIN
SELECT clmn INTO v_var FROM tbl;
Exception when no_data_found then v_var := null; --what ever handle the exception.
END;
In tsql
if no data found
then the variable will be null
but no exception
Add an id column to the csv file and leave it blank:
id,Name,Address
,name1,addr test 1
,name2,addr test 2
Remove KEEPIDENTITY keyword from query:
BULK INSERT Employee FROM 'path\tempFile.csv '
WITH (FIRSTROW = 2,FIELDTERMINATOR = ',' , ROWTERMINATOR = '\n');
The id identity field will be auto-incremented.
If you assign values to the id field in the csv, they'll be ignored unless you use the KEEPIDENTITY keyword, then they'll be used instead of auto-increment.
Just drop the option v
.
-v
is for verbose. If you don't use it then it won't display:
tar -zxf tmp.tar.gz -C ~/tmp1
Simple Solution:
JsonElement element = new JsonParser().parse(new InputStreamReader(inputStream));
JSONObject jsonObject = new JSONObject(element.getAsJsonObject().toString());
I have got the same error, but in my case I wrote class names for carousel item as .carousel-item the bootstrap.css is referring .item. SO ERROR solved. carosel-item is renamed to item
<div class="carousel-item active"></div>
RENAMED To the following:
<div class="item active"></div>
Comparaison of the different methods:
> CGI::escapeHTML("quote ' double quotes \"")
=> "quote ' double quotes ""
> Rack::Utils.escape_html("quote ' double quotes \"")
=> "quote ' double quotes ""
> ERB::Util.html_escape("quote ' double quotes \"")
=> "quote ' double quotes ""
I wrote my own to be compatible with Rails ActiveMailer escaping:
def escape_html(str)
CGI.escapeHTML(str).gsub("'", "'")
end
<div style="width: 200px; height: 150px; border: 1px solid black;position:relative">
<div style="width: 100%; height: 50px; border: 1px solid red;position:absolute;bottom:0">
</div>
</div>
After you parse it with Javascript, try this:
mandrill_events[0].event
In my experience, you usually want to do this, then 'protect' your files to do something fancy and then use the 'protected' files. If you have just one file you want to use like this, you can use the trick that's explained in the answer by Jeremy Thompson. However, if you attempt to do this on lots of files (say, for example when you're writing an installer), you're in for quite a bit of hurt.
A very elegant way this can be solved is by using the fact that your file system will not allow you to change a folder name if one of the files there it's being used. Keep the folder in the same file system and it'll work like a charm.
Do note that you should be aware of the obvious ways this can be exploited. After all, the files won't be locked. Also, be aware that there are other reasons that can result in your Move
operation to fail. Obviously proper error handling (MSDN) can help out here.
var originalFolder = @"c:\myHugeCollectionOfFiles"; // your folder name here
var someFolder = Path.Combine(originalFolder, "..", Guid.NewGuid().ToString("N"));
try
{
Directory.Move(originalFolder, someFolder);
// Use files
}
catch // TODO: proper exception handling
{
// Inform user, take action
}
finally
{
Directory.Move(someFolder, originalFolder);
}
For individual files I'd stick with the locking suggestion posted by Jeremy Thompson.
I am introducing Two custom library functions to be used in vba, which will serve the purpose of rounding the double value instead of using WorkSheetFunction.RoundDown and WorkSheetFunction.RoundUp
Function RDown(Amount As Double, digits As Integer) As Double
RDown = Int((Amount + (1 / (10 ^ (digits + 1)))) * (10 ^ digits)) / (10 ^ digits)
End Function
Function RUp(Amount As Double, digits As Integer) As Double
RUp = RDown(Amount + (5 / (10 ^ (digits + 1))), digits)
End Function
Thus function Rdown(2878.75 * 31.1,2) will return 899529.12 and function RUp(2878.75 * 31.1,2) will return 899529.13 Whereas The function Rdown(2878.75 * 31.1,-3) will return 89000 and function RUp(2878.75 * 31.1,-3) will return 90000
Check this blog by Martin Thoma. I tested the below code on MacOS Mojave and it worked as specified.
> def get_browser():
> """Get the browser (a "driver")."""
> # find the path with 'which chromedriver'
> path_to_chromedriver = ('/home/moose/GitHub/algorithms/scraping/'
> 'venv/bin/chromedriver')
> download_dir = "/home/moose/selenium-download/"
> print("Is directory: {}".format(os.path.isdir(download_dir)))
>
> from selenium.webdriver.chrome.options import Options
> chrome_options = Options()
> chrome_options.add_experimental_option('prefs', {
> "plugins.plugins_list": [{"enabled": False,
> "name": "Chrome PDF Viewer"}],
> "download": {
> "prompt_for_download": False,
> "default_directory": download_dir
> }
> })
>
> browser = webdriver.Chrome(path_to_chromedriver,
> chrome_options=chrome_options)
> return browser
Remove all the texts in android/settings.gradle and paste the below code
rootProject.name = '****Your Project Name****'
apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
include ':app'
This issue will usually happen when you migrate from react-native < 0.60 to react-native >0.60. If you create a new project in react-native >0.60 you will see the same settings as above mentioned
All the previous posts are correct. There's more than one way to skin a cat. Here is another way to do the same thing: (just replace "what_ever_you_want_to_convert" with your string and run it in Oracle:
set serveroutput on;
DECLARE
v_str VARCHAR2(1000);
BEGIN
--Create encoded value
v_str := utl_encode.text_encode
('what_ever_you_want_to_convert','WE8ISO8859P1', UTL_ENCODE.BASE64);
dbms_output.put_line(v_str);
--Decode the value..
v_str := utl_encode.text_decode
(v_str,'WE8ISO8859P1', UTL_ENCODE.BASE64);
dbms_output.put_line(v_str);
END;
/
Take a form-control
, and add is-valid
to its class. Notice how the control turns green, but more importantly, notice the checkmark icon on the right of the control? This is what we want!
Example:
.my-icon {_x000D_
padding-right: calc(1.5em + .75rem);_x000D_
background-image: url('https://use.fontawesome.com/releases/v5.8.2/svgs/regular/calendar-alt.svg');_x000D_
background-repeat: no-repeat;_x000D_
background-position: center right calc(.375em + .1875rem);_x000D_
background-size: calc(.75em + .375rem) calc(.75em + .375rem);_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>_x000D_
<div class="container">_x000D_
<div class="col-md-5">_x000D_
<input type="text" id="date" class="form-control my-icon" placeholder="Select...">_x000D_
</div>_x000D_
</div>
_x000D_
To make thepeer's answer work in IE 7 and forward, it needs a few tweaks.
IE will not honour z-index if the element is has no background-color, so the link will not overlap parts of the containig div that has content, only the blank parts. To fix this a background is added with opacity 0.
For some reason IE7 and various compatibility modes completely fail when using the span in a link approach. However if the link itself is given the style it works just fine.
.blockLink
{
position:absolute;
top:0;
left: 0;
width:100%;
height:100%;
z-index: 1;
background-color:#ffffff;
-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
filter: alpha(opacity=0);
opacity:0;
}
<div style="position:relative">
<some content>
<a href="somepage" class="blockLink" />
<div>
I suspect wpis.entry.lastChangeDate
has been somehow transformed into a string in the view, before arriving to the template.
In order to verify this hypothesis, you may just check in the view if it has some property/method that only strings have - like for instance wpis.entry.lastChangeDate.upper
, and then see if the template crashes.
You could also create your own custom filter, and use it for debugging purposes, letting it inspect the object, and writing the results of the inspection on the page, or simply on the console. It would be able to inspect the object, and check if it is really a DateTimeField.
On an unrelated notice, why don't you use models.DateTimeField(
auto_now_add
=True)
to set the datetime on creation?
args should be tuple.
eg:
args = ('A','B')
args = ('A',) # in case of single
For smaller files you could use this:
& C:\windows\system32\more +1 oldfile.csv > newfile.csv | out-null
... but it's not very effective at processing my example file of 16MB. It doesn't seem to terminate and release the lock on newfile.csv.
The identity
section goes under the system.web
section, not under authentication
:
<system.web>
<authentication mode="Windows"/>
<identity impersonate="true" userName="foo" password="bar"/>
</system.web>
DATE_ADD(FROM_DATE_HERE, INTERVAL INTERVAL_TIME_HERE DAY)
will give the Date after adjusting the INTERVAL
eg.
DATE_ADD(NOW(), INTERVAL -1 DAY) for deducting 1 DAY from current Day
DATE_ADD(NOW(), INTERVAL 2 DAY) for adding 2 Days
You can use like
UPDATE classes WHERE date=(DATE_ADD(date, INTERVAL 1 DAY)) WHERE id=161
You should have a default server for catch-all, you can return 404
or better to not respond at all (will save some bandwidth) by returning 444
which is nginx specific HTTP response that simply close the connection and return nothing
server {
listen 80 default_server;
server_name _; # some invalid name that won't match anything
return 444;
}
Swift version to get Bool?
NSUserDefaults.standardUserDefaults().objectForKey(DefaultsIsGiver) as? Bool
Something like this would work
/^\d{2}$/
Here is an example that you can use as function or also you can put the same logic in procedure. --SELECT * from [dbo].fn_SplitString ;
CREATE FUNCTION [dbo].[fn_SplitString]
(@CSV VARCHAR(MAX), @Delimeter VARCHAR(100) = ',')
RETURNS @retTable TABLE
(
[value] VARCHAR(MAX) NULL
)AS
BEGIN
DECLARE
@vCSV VARCHAR (MAX) = @CSV,
@vDelimeter VARCHAR (100) = @Delimeter;
IF @vDelimeter = ';'
BEGIN
SET @vCSV = REPLACE(@vCSV, ';', '~!~#~');
SET @vDelimeter = REPLACE(@vDelimeter, ';', '~!~#~');
END;
SET @vCSV = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@vCSV, '&', '&'), '<', '<'), '>', '>'), '''', '''), '"', '"');
DECLARE @xml XML;
SET @xml = '<i>' + REPLACE(@vCSV, @vDelimeter, '</i><i>') + '</i>';
INSERT INTO @retTable
SELECT
x.i.value('.', 'varchar(max)') AS COLUMNNAME
FROM @xml.nodes('//i')AS x(i);
RETURN;
END;
Dim DS As New DataSet
DS.Clear()
- DATASET clear works better than DataGridView.Rows.Clear()
for me :
Public Sub doQuery(sql As String)
Try
DS.Clear() '<-- here
' - CONNECT -
DBCon.Open()
' Cmd gets SQL Query
Cmd = New OleDbCommand(sql, DBCon)
DA = New OleDbDataAdapter(Cmd)
DA.Fill(DS)
' - DISCONNECT -
DBCon.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
In Visual Studio 2005 and 2008 you can try the Source Code Outliner Power Toy.
One point: you have to set NumberFormat property BEFORE loading the value into the cell. I had a nine digit number that still displayed as 9.14E+08 when the NumberFormat was set after the cell was loaded. Setting the property before loading the value made the number appear as I wanted, as straight text.
OR:
Could you try an autofit first:
Excel_Obj.Columns("A:V").EntireColumn.AutoFit
Naively type casting any string into an integer like so
SELECT ''::integer
Often results to the famous error:
Query failed: ERROR: invalid input syntax for integer: ""
PostgreSQL has no pre-defined function for safely type casting any string into an integer.
Create a user-defined function inspired by PHP's intval() function.
CREATE FUNCTION intval(character varying) RETURNS integer AS $$
SELECT
CASE
WHEN length(btrim(regexp_replace($1, '[^0-9]', '','g')))>0 THEN btrim(regexp_replace($1, '[^0-9]', '','g'))::integer
ELSE 0
END AS intval;
$$
LANGUAGE SQL
IMMUTABLE
RETURNS NULL ON NULL INPUT;
/* Example 1 */
SELECT intval('9000');
-- output: 9000
/* Example 2 */
SELECT intval('9gag');
-- output: 9
/* Example 3 */
SELECT intval('the quick brown fox jumps over the lazy dog');
-- output: 0
I don't know if you even need to wrap it. Won't this work?
SELECT COUNT(*), SUM(DATEDIFF(now(),availables.updated_at))
FROM availables
INNER JOIN rooms ON availables.room_id=rooms.id
WHERE availables.bookdate BETWEEN '2009-06-25'
AND date_add('2009-06-25', INTERVAL 4 DAY)
AND rooms.hostel_id = 5094
GROUP BY availables.bookdate);
If your goal is to return both result sets then you'll need to store it some place temporarily.
If you want to set Min 1 count and no Max length,
^.{1,}$
You have $headers .= '...';
followed by $headers = '...';
; the second line is overwriting the first.
Just put the $headers .= "Bcc: $emailList\r\n";
say after the Content-type
line and it should be fine.
On a side note, the To
is generally required; mail servers might mark your message as spam otherwise.
$headers = "From: [email protected]\r\n" .
"X-Mailer: php\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= "Bcc: $emailList\r\n";
make clean
removes any intermediate or output files from your source / build tree. However, it only affects the source / build tree; it does not touch the rest of the filesystem and so will not remove previously installed software.
If you're lucky, running make uninstall
will work. It's up to the library's authors to provide that, however; some authors provide an uninstall
target, others don't.
If you're not lucky, you'll have to manually uninstall it. Running make -n install
can be helpful, since it will show the steps that the software would take to install itself but won't actually do anything. You can then manually reverse those steps.
A nice solution that I've found is to do on UI something like:
<div *ngIf="isDataLoaded">
...Your page...
</div
Only when: isDataLoaded is true the page is rendered.
It's the default configuration for a Java web application; it's required.
WicketFilter
is applied to every HTTP request that's sent to this web app.
You could use the Export->Java->Runnable Jar to create a jar that includes its dependencies
Alternatively, you could use the fatjar eclipse plugin as well to bundle jars together
Well, reading it isn't hard, just use FileStream to read a byte[]. Converting it to text isn't really generally possible or meaningful unless you convert the 1's and 0's to hex. That's easy to do with the BitConverter.ToString(byte[]) overload. You'd generally want to dump 16 or 32 bytes in each line. You could use Encoding.ASCII.GetString() to try to convert the bytes to characters. A sample program that does this:
using System;
using System.IO;
using System.Text;
class Program {
static void Main(string[] args) {
// Read the file into <bits>
var fs = new FileStream(@"c:\temp\test.bin", FileMode.Open);
var len = (int)fs.Length;
var bits = new byte[len];
fs.Read(bits, 0, len);
// Dump 16 bytes per line
for (int ix = 0; ix < len; ix += 16) {
var cnt = Math.Min(16, len - ix);
var line = new byte[cnt];
Array.Copy(bits, ix, line, 0, cnt);
// Write address + hex + ascii
Console.Write("{0:X6} ", ix);
Console.Write(BitConverter.ToString(line));
Console.Write(" ");
// Convert non-ascii characters to .
for (int jx = 0; jx < cnt; ++jx)
if (line[jx] < 0x20 || line[jx] > 0x7f) line[jx] = (byte)'.';
Console.WriteLine(Encoding.ASCII.GetString(line));
}
Console.ReadLine();
}
}
SOLUTION OF Regsvr32: DllRegisterServer entry point was not found,
You can use the selectedIndex property to set it to the first option:
document.getElementById("select").selectedIndex = 0;
I use it to amend more than just the last commit.
Let's say I made a mistake in commit A and then made commit B. Now I can only amend B.
So I do git reset --soft HEAD^^
, I correct and re-commit A and then re-commit B.
Of course, it's not very convenient for large commits… but you shouldn't do large commits anyway ;-)
Ok, I am fairly experienced on the iPhone but new to android. I got this issue when I had:
Button infoButton = (Button)findViewById(R.id.InfoButton);
this line of code above:
@Override
public void onCreate (Bundle savedInstanceState) {
}
May be I am sleep deprived :P
There it is : ternary operator got added to angular parser in 1.1.5! see the changelog
Here is a fiddle showing new ternary operator used in ng-class directive.
ng-class="boolForTernary ? 'blue' : 'red'"
set a rule to check the file name (if the form is multipart)
$this->form_validation->set_rules('upload_file[name]', 'Upload file', 'required', 'No upload image :(');
overwrite the $_POST
array as follows:
$_POST['upload_file'] = $_FILES['upload_file']
and then do:
$this->form_validation->run()
For ISO8859_1 files, there is not an easy way to distinguish them from ASCII. For Unicode files however one can generally detect this based on the first few bytes of the file.
UTF-8 and UTF-16 files include a Byte Order Mark (BOM) at the very beginning of the file. The BOM is a zero-width non-breaking space.
Unfortunately, for historical reasons, Java does not detect this automatically. Programs like Notepad will check the BOM and use the appropriate encoding. Using unix or Cygwin, you can check the BOM with the file command. For example:
$ file sample2.sql
sample2.sql: Unicode text, UTF-16, big-endian
For Java, I suggest you check out this code, which will detect the common file formats and select the correct encoding: How to read a file and automatically specify the correct encoding
TypeError: Cannot read property 'then' of undefined when calling a Django service using AngularJS.
If you are calling a Python service, the code will look like below:
this.updateTalentSupplier=function(supplierObj){
var promise = $http({
method: 'POST',
url: bbConfig.BWS+'updateTalentSupplier/',
data:supplierObj,
withCredentials: false,
contentType:'application/json',
dataType:'json'
});
return promise; //Promise is returned
}
We are using MongoDB as the database(I know it doesn't matter. But if someone is searching with MongoDB + Python (Django) + AngularJS the result should come.
There are a few steps you need to take to properly store this information in your localStorage. Before we get down to the code however, please note that localStorage (at the current time) cannot hold any data type except for strings. You will need to serialize the array for storage and then parse it back out to make modifications to it.
Step 1:
The First code snippet below should only be run if you are not already storing a serialized array in your localStorage session
variable.
To ensure your localStorage is setup properly and storing an array, run the following code snippet first:
var a = [];
a.push(JSON.parse(localStorage.getItem('session')));
localStorage.setItem('session', JSON.stringify(a));
The above code should only be run once and only if you are not already storing an array in your localStorage session
variable. If you are already doing this skip to step 2.
Step 2:
Modify your function like so:
function SaveDataToLocalStorage(data)
{
var a = [];
// Parse the serialized data back into an aray of objects
a = JSON.parse(localStorage.getItem('session')) || [];
// Push the new data (whether it be an object or anything else) onto the array
a.push(data);
// Alert the array value
alert(a); // Should be something like [Object array]
// Re-serialize the array back into a string and store it in localStorage
localStorage.setItem('session', JSON.stringify(a));
}
This should take care of the rest for you. When you parse it out, it will become an array of objects.
Hope this helps.
One other way, using the splat operator:
*a, last = [1, 3, 4, 5]
STDOUT:
a: [1, 3, 4]
last: 5
MSalter's answer is a good idea.
If the integer calculation is required (for precision), but floating point is available, you could do something like:
uint64_t foo(uint64_t a, uint64_t b) {
double dc;
dc = pow(a, b);
if (dc < UINT_MAX) {
return (powu64(a, b));
}
else {
// Overflow
}
}
For a solution that is free of fiddly external dependencies*, there is now readxl
:
The readxl package makes it easy to get data out of Excel and into R. Compared to many of the existing packages (e.g. gdata, xlsx, xlsReadWrite) readxl has no external dependencies so it's easy to install and use on all operating systems. It is designed to work with tabular data stored in a single sheet.
Readxl supports both the legacy .xls format and the modern xml-based .xlsx format. .xls support is made possible the with libxls C library, which abstracts away many of the complexities of the underlying binary format. To parse .xlsx, we use the RapidXML C++ library.
It can be installed like so:
install.packages("readxl") # CRAN version
or
devtools::install_github("hadley/readxl") # development version
Usage
library(readxl)
# read_excel reads both xls and xlsx files
read_excel("my-old-spreadsheet.xls")
read_excel("my-new-spreadsheet.xlsx")
# Specify sheet with a number or name
read_excel("my-spreadsheet.xls", sheet = "data")
read_excel("my-spreadsheet.xls", sheet = 2)
# If NAs are represented by something other than blank cells,
# set the na argument
read_excel("my-spreadsheet.xls", na = "NA")
* not strictly true, it requires the Rcpp
package, which in turn requires Rtools (for Windows) or Xcode (for OSX), which are dependencies external to R. But they don't require any fiddling with paths, etc., so that's an advantage over Java and Perl dependencies.
Update There is now the rexcel package. This promises to get Excel formatting, functions and many other kinds of information from the Excel file and into R.
Try this
#import <QuartzCore/QuartzCore.h> // not necessary for 10 years now :)
...
view.layer.cornerRadius = 5;
view.layer.masksToBounds = true;
Note: If you are trying to apply rounded corners to a UIViewController
's view, it should not be applied in the view controller's constructor, but rather in -viewDidLoad
, after view
is actually instantiated.
public static void main(String[] args){
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1.equals(s2));
////
System.out.println(s1 == s2);
System.out.println("-----------------------------");
String s3 = "hello";
String s4 = "hello";
System.out.println(s3.equals(s4));
////
System.out.println(s3 == s4);
}
Here in this code u can campare the both '==' and '.equals'
here .equals is used to compare the reference objects and '==' is used to compare state of objects..
According to Swift 4.2 now it's easily to get random number like this
let randomDouble = Double.random(in: -7.9...12.8)
let randomIntFrom0To10 = Int.random(in: 0 ..< 10)
I noticed that you can also get errors if you don't specify the angles correctly, even when using glm::rotate(Model, angle_in_degrees, glm::vec3(x, y, z))
you still might run into problems. The fix I found for this was specifying the type as glm::rotate(Model, (glm::mediump_float)90, glm::vec3(x, y, z))
instead of just saying glm::rotate(Model, 90, glm::vec3(x, y, z))
Or just write the second argument, the angle in radians (previously in degrees), as a float with no cast needed such as in:
glm::mat4 rotationMatrix = glm::rotate(glm::mat4(1.0f), 3.14f, glm::vec3(1.0));
You can add glm::radians() if you want to keep using degrees. And add the includes:
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
Define two dates using new Date(). Calculate the time difference of two dates using date2. getTime() – date1. getTime(); Calculate the no. of days between two dates, divide the time difference of both the dates by no. of milliseconds in a day (10006060*24)
I think the following way is more clear and useful for nested ng-repeats. Check it out on Plunker.
<html ng-app="plunker">
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.min.js"></script>
</head>
<body ng-controller="MainCtrl">
<div ng-repeat="tab in mytabs">
<h1>{{tab.name}}</h1>
<div ng-repeat="val in tab.values">
<input type="checkbox" ng-change="checkValues()" ng-model="val.checked"/>
</div>
</div>
<br>
<pre> {{selected}} </pre>
<script>
var app = angular.module('plunker', []);
app.controller('MainCtrl', function ($scope,$filter) {
$scope.mytabs = [
{
name: "tab1",
values: [
{ value: "value1",checked:false },
{ value: "value2", checked: false },
{ value: "value3", checked: false },
{ value: "value4", checked: false }
]
},
{
name: "tab2",
values: [
{ value: "value1", checked: false },
{ value: "value2", checked: false },
{ value: "value3", checked: false },
{ value: "value4", checked: false }
]
}
]
$scope.selected = []
$scope.checkValues = function () {
angular.forEach($scope.mytabs, function (value, index) {
var selectedItems = $filter('filter')(value.values, { checked: true });
angular.forEach(selectedItems, function (value, index) {
$scope.selected.push(value);
});
});
console.log($scope.selected);
};
});
</script>
</body>
</html>
If this is for an intranet application and all of the clients use DHCP, you can query the DHCP server for the MAC address for a given IP address.
Your first problem was you weren't using your compare symbols correctly.
< less than
> greater than
<= less than or equal to
>= greater than or equal to
To answer your other questions; get the condition to work on every cell in the column and what about blanks?
What about blanks?
Add an extra IF
condition to check if the cell is blank or not, if it isn't blank perform the check. =IF(B2="","",B2<=TODAY())
Condition on every cell in column
Yes that is valid syntax but it may well not do what you want.
Execution will continue after your RAISERROR
except if you add a RETURN
. So you will need to add a block with BEGIN ... END
to hold the two statements.
Also I'm not sure why you plumped for severity 15. That usually indicates a syntax error.
Finally I'd simplify the conditions using IN
CREATE PROCEDURE [dbo].[AddApplicationUser] (@TenantId BIGINT,
@UserType TINYINT,
@UserName NVARCHAR(100),
@Password NVARCHAR(100))
AS
BEGIN
IF ( @TenantId IS NULL
AND @UserType IN ( 0, 1 ) )
BEGIN
RAISERROR('The value for @TenantID should not be null',15,1);
RETURN;
END
END
The :
is a bitfield. As for !!
, that is logical double negation and so returns 0
for false or 1
for true. And the -
is a minus sign, i.e. arithmetic negation.
It's all just a trick to get the compiler to barf on invalid inputs.
Consider BUILD_BUG_ON_ZERO
. When -!!(e)
evaluates to a negative value, that produces a compile error. Otherwise -!!(e)
evaluates to 0, and a 0 width bitfield has size of 0. And hence the macro evaluates to a size_t
with value 0.
The name is weak in my view because the build in fact fails when the input is not zero.
BUILD_BUG_ON_NULL
is very similar, but yields a pointer rather than an int
.
For a debug purpose:
/usr/sbin/nginx -g "daemon off;error_log /dev/stdout debug;"
For a classic purpose
/usr/sbin/nginx -g "daemon off;error_log /dev/stdout info;"
Require
Under the server bracket on the config file
access_log /dev/stdout;
There is a way that may be suitable if the items you want to delete are always at the "beginning" of the dict iteration
while mydict:
key, value = next(iter(mydict.items()))
if should_delete(key, value):
del mydict[key]
else:
break
The "beginning" is only guaranteed to be consistent for certain Python versions/implementations. For example from What’s New In Python 3.7
the insertion-order preservation nature of dict objects has been declared to be an official part of the Python language spec.
This way avoids a copy of the dict that a lot of the other answers suggest, at least in Python 3.
Try this...
<script type="text/javascript">
$("#form_oferta").submit(function(event)
{
var myData = $( form ).serialize();
$.ajax({
type: "POST",
contentType:attr( "enctype", "multipart/form-data" ),
url: " URL Goes Here ",
data: myData,
success: function( data )
{
alert( data );
}
});
return false;
});
</script>
Here the contentType
is specified as multipart/form-data
as we do in the form tag, this will work to upload simple file
On server side you just need to write simple file upload code to handle this request with echoing message you want to show to user as a response.
from within the directory of "my_script.py" you can simply do:
%run ./my_script.py
There is
between the two.
Semantical Difference:
FirstOrDefault
returns a first item of potentially multiple (or default if none exists).SingleOrDefault
assumes that there is a single item and returns it (or default if none exists). Multiple items are a violation of contract, an exception is thrown.Performance Difference
FirstOrDefault
is usually faster, it iterates until it finds the element and only has to iterate the whole enumerable when it doesn't find it. In many cases, there is a high probability to find an item.
SingleOrDefault
needs to check if there is only one element and therefore always iterates the whole enumerable. To be precise, it iterates until it finds a second element and throws an exception. But in most cases, there is no second element.
Conclusion
Use FirstOrDefault
if you don't care how many items there are or when you can't afford checking uniqueness (e.g. in a very large collection). When you check uniqueness on adding the items to the collection, it might be too expensive to check it again when searching for those items.
Use SingleOrDefault
if you don't have to care about performance too much and want to make sure that the assumption of a single item is clear to the reader and checked at runtime.
In practice, you use First
/ FirstOrDefault
often even in cases when you assume a single item, to improve performance. You should still remember that Single
/ SingleOrDefault
can improve readability (because it states the assumption of a single item) and stability (because it checks it) and use it appropriately.
Below is reference from https://android.googlesource.com/platform/tools/tradefederation/+/master/src/com/android/tradefed/util/FileUtil.java
/**
* Gets the base name, without extension, of given file name.
* <p/>
* e.g. getBaseName("file.txt") will return "file"
*
* @param fileName
* @return the base name
*/
public static String getBaseName(String fileName) {
int index = fileName.lastIndexOf('.');
if (index == -1) {
return fileName;
} else {
return fileName.substring(0, index);
}
}
You need to register the directory with Oracle. fopen takes the name of a directory object, not the path. For example:
(you may need to login as SYS to execute these)
CREATE DIRECTORY MY_DIR AS 'C:\';
GRANT READ ON DIRECTORY MY_DIR TO SCOTT;
Then, you can refer to it in the call to fopen:
execute sal_status('MY_DIR','vin1.txt');
installing Microsoft Visual C++ 2010 SP1 Redistributable Fixed it
Just be sure what timezone you want to use.
datetime="06/12/2012 07:21:22"
Most popular use takes machine timezone.
date -d "$datetime" +"%s" #depends on local timezone, my output = "1339456882"
But in case you intentionally want to pass UTC datetime and you want proper timezone you need to add -u
flag. Otherwise you convert it from your local timezone.
date -u -d "$datetime" +"%s" #general output = "1339485682"
Try to use jpg and png , also name your image in lowercase. Then drag and drop the image in res/drawable . then go to file and click save all . close eclipse then reopen it again . That is what worked for me .
Actually, The save command is only on instance of Document class. That have a lot of methods and attribute. So you can use lean() function to reduce work load. Refer here. https://hashnode.com/post/why-are-mongoose-mongodb-odm-lean-queries-faster-than-normal-queries-cillvawhq0062kj53asxoyn7j
Another problem with save function, that will make conflict data in with multi-save at a same time. Model.Update will make data consistently. So to update multi items in array of document. Use your familiar programming language and try something like this, I use mongoose in that:
User.findOne({'_id': '4d2d8deff4e6c1d71fc29a07'}).lean().exec()
.then(usr =>{
if(!usr) return
usr.events.forEach( e => {
if(e && e.profile==10 ) e.handled = 0
})
User.findOneAndUpdate(
{'_id': '4d2d8deff4e6c1d71fc29a07'},
{$set: {events: usr.events}},
{new: true}
).lean().exec().then(updatedUsr => console.log(updatedUsr))
})
I found this the most simple when toggling boolean values. Simply put if the value is already true then it sets it to false and vice versa. Beware of undefined errors, make sure your property was defined before executing
this.setState({
propertyName: this.propertyName = !this.propertyName
});
From Oracle 11gR2, the LISTAGG clause should do the trick:
SELECT question_id,
LISTAGG(element_id, ',') WITHIN GROUP (ORDER BY element_id)
FROM YOUR_TABLE
GROUP BY question_id;
Beware if the resulting string is too big (more than 4000 chars for a VARCHAR2, for instance): from version 12cR2, we can use ON OVERFLOW TRUNCATE/ERROR to deal with this issue.
The problem is that you are trying to access resources (in this case, strings) using getResources().getString(), which will try to get the resources from the Activity. See this source code of the Fragment class:
/**
* Return <code>getActivity().getResources()</code>.
*/
final public Resources getResources() {
if (mHost == null) {
throw new IllegalStateException("Fragment " + this + " not attached to Activity");
}
return mHost.getContext().getResources();
}
mHost
is the object that holds your Activity.
Because the Activity might not be attached, your getResources() call will throw an Exception.
The accepted solution IMHO is not the way to go as you are just hiding the problem. The correct way is just to get the resources from somewhere else that is always guaranteed to exist, like the application context:
youApplicationObject.getResources().getString(...)
As of C# 8 you can use the 'empty' property pattern (with pattern matching) to ensure an object is not null:
if (obj is { })
{
// 'obj' is not null here
}
This approach means "if the object references an instance of something" (i.e. it's not null).
You can think of this as the opposite of: if (obj is null)...
. which will return true when the object does not reference an instance of something.
For more info on patterns in C# 8.0 read here.
You must declare
int add(int a, int b);
(note to the semicolon)
in a header file and include the file into both files.
Including it into Main.c will tell compiler how the function should be called.
Including into the second file will allow you to check that declaration is valid (compiler would complain if declaration and implementation were not matched).
Then you must compile both *.c files into one project. Details are compiler-dependent.
You can refer to the proxy documentation here.
If you need to use a proxy, you can configure individual requests with the proxies argument to any request method:
import requests
proxies = {
"http": "http://10.10.1.10:3128",
"https": "https://10.10.1.10:1080",
}
requests.get("http://example.org", proxies=proxies)
To use HTTP Basic Auth with your proxy, use the http://user:[email protected]/ syntax:
proxies = {
"http": "http://user:[email protected]:3128/"
}
I got a solution working in the end using Redemption, have a look at these questions...
This is how I got it working with loading remote content that needs to be refreshed:
$(document).ready(function () {
var loadingContent = '<div class="modal-header"><h1>Processing...</h1></div><div class="modal-body"><div class="progress progress-striped active"><div class="bar" style="width: 100%;"></div></div></div>';
// This is need so the content gets replaced correctly.
$("#myModal").on("show.bs.modal", function (e) {
$(this).find(".modal-content").html(loadingContent);
var link = $(e.relatedTarget);
$(this).find(".modal-content").load(link.attr("href"));
});
$("#myModal2").on("hide.bs.modal", function (e) {
$(this).removeData('bs.modal');
});
});
Basically, just replace the modal content while it's loading with a loading message. The content will then be replaced once it's finished loading.
You can use substr
:
echo substr('a,b,c,d,e,', 0, -1);
# => 'a,b,c,d,e'
Here is a function (function genID() below) that recursively checks the DOM for uniqueness based on whatever id prefex/ID you want.
In your case you'd might use it as such
var seedNum = 1;
newSelectBox.setAttribute("id",genID('state-',seedNum));
function genID(myKey, seedNum){
var key = myKey + seedNum;
if (document.getElementById(key) != null){
return genID(myKey, ++seedNum);
}
else{
return key;
}
}
Extract the jar, and put it somewhere in your Java project (usually under a "lib" subdirectory).
Right click the project, open its preferences, go for Java build path, and then the Libraries tab. You can add the library there with "add a jar".
If your jar is not open source, you may want to store it elsewhere and connect to it as an external jar.
here's my refactored version which accepts multiline/single as an option
public string ShowDialog(string text, string caption, bool isMultiline = false, int formWidth = 300, int formHeight = 200)
{
var prompt = new Form
{
Width = formWidth,
Height = isMultiline ? formHeight : formHeight - 70,
FormBorderStyle = isMultiline ? FormBorderStyle.Sizable : FormBorderStyle.FixedSingle,
Text = caption,
StartPosition = FormStartPosition.CenterScreen,
MaximizeBox = isMultiline
};
var textLabel = new Label
{
Left = 10,
Padding = new Padding(0, 3, 0, 0),
Text = text,
Dock = DockStyle.Top
};
var textBox = new TextBox
{
Left = isMultiline ? 50 : 4,
Top = isMultiline ? 50 : textLabel.Height + 4,
Multiline = isMultiline,
Dock = isMultiline ? DockStyle.Fill : DockStyle.None,
Width = prompt.Width - 24,
Anchor = isMultiline ? AnchorStyles.Left | AnchorStyles.Top : AnchorStyles.Left | AnchorStyles.Right
};
var confirmationButton = new Button
{
Text = @"OK",
Cursor = Cursors.Hand,
DialogResult = DialogResult.OK,
Dock = DockStyle.Bottom,
};
confirmationButton.Click += (sender, e) =>
{
prompt.Close();
};
prompt.Controls.Add(textBox);
prompt.Controls.Add(confirmationButton);
prompt.Controls.Add(textLabel);
return prompt.ShowDialog() == DialogResult.OK ? textBox.Text : string.Empty;
}
if my_list is the list that you want to store your objects in it and my_object is your object wanted to be stored, use this structure:
my_list.append(my_object)
You should prefer Object Mapper instead. Here is the link for the same : Object Mapper - Spring MVC way of Obect to JSON
The reason is that the data doesn't match the datatype. I have come across the same issues that I forgot to make the fields match. Though my case is not same as yours, but it shows the similar error message.
The situation is that I copy a table, but accidently I misspell one field, so I change it using the ALTER
after creating the database. And the order of fields in both table is not identical. so when I use the INSERT INTO TableName SELECT * FROM TableName
, the result showed the similar errors: Operand type clash: datetime is incompatible with uniqueidentifier
This is a simiple example:
use example
go
create table Test1 (
id int primary key,
item uniqueidentifier,
inserted_at datetime
)
go
create table Test2 (
id int primary key,
inserted_at datetime
)
go
alter table Test2 add item uniqueidentifier;
go
--insert into Test1 (id, item, inserted_at) values (1, newid(), getdate()), (2, newid(), getdate());
insert into Test2 select * from Test1;
select * from Test1;
select * from Test2;
The error message is:
Msg 206, Level 16, State 2, Line 24
Operand type clash: uniqueidentifier is incompatible with datetime
I wasn't using Azure, but I got the same error locally. Using <customErrors mode="Off" />
seemed to have no effect, but checking the Application logs in Event Viewer revealed a warning from ASP.NET which contained all the detail I needed to resolve the issue.
Know it's an old post. But these issues still exist.
Here are some of my findings on the subject, grossly explained.
"Status" 0 means one of 3 things, as per the XMLHttpRequest spec:
dns name resolution failed (that's for instance when network plug is pulled out)
server did not answer (a.k.a. unreachable or unresponding)
request was aborted because of a CORS issue (abortion is performed by the user-agent and follows a failing OPTIONS pre-flight).
If you want to go further, dive deep into the inners of XMLHttpRequest. I suggest reading the ready-state update sequence ([0,1,2,3,4] is the normal sequence, [0,1,4] corresponds to status 0, [0,1,2,4] means no content sent which may be an error or not). You may also want to attach listeners to the xhr (onreadystatechange, onabort, onerror, ontimeout) to figure out details.
From the spec (XHR Living spec):
const unsigned short UNSENT = 0;
const unsigned short OPENED = 1;
const unsigned short HEADERS_RECEIVED = 2;
const unsigned short LOADING = 3;
const unsigned short DONE = 4;
if([[SDWebImageManager sharedManager] diskImageExistsForURL:[NSURL URLWithString:@"URL STRING1"]])
{
NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:[NSURL URLWithString:@"URL STRING1"]];
UIImage *tempImage=[self imageWithImage:[[SDImageCache sharedImageCache] imageFromDiskCacheForKey:key] scaledToWidth:cell.imgview.bounds.size.width];
cell.imgview.image=tempImage;
}
else
{
[cell.imgview sd_setImageWithURL:[NSURL URLWithString:@"URL STRING1"] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL)
{
UIImage *tempImage=[self imageWithImage:image scaledToWidth:cell.imgview.bounds.size.width];
cell.imgview.image=tempImage;
// [tableView beginUpdates];
// [tableView endUpdates];
}];
}
Note that the third highest salary may be the same the the first highest salary so your current approach wouldn't work.
I would do order the employees by salary and apply a LIMIT 3
at the end of the SQL query. You'll then have the top three of highest salaries and, thus, you also have the third highest salary (if there is one, a company may have two employees and then you wouldn't have a third highest salary).
The value of st
at st = datetime.strptime(st, '%A %d %B')
line something like 01 01 2013 02:05
and the strptime
can't parse this. Indeed, you get an hour in addition of the date... You need to add %H:%M
at your strptime.
Newtang's observation about the security rules aside, how are you going to know that anyone who views your page will have the correct images at c:\localfile.jpg
? You can't. Even if you think you can, you can't. It presupposes a windows environment, for one thing.
puts false or true
--> prints: false
puts false || true
--> prints: true
If you can't add to the BODY tag for some reason, you can add this AFTER the Form:
<SCRIPT type="text/javascript">
document.yourFormName.yourFieldName.focus();
</SCRIPT>
There is a simple way to do it. I tried it on my app and it worked pretty well.
Just type: $text = $row["text"]; echo nl2br($text);
It looks like jsbeautifier open sourced their tools and packaged them as Python and JS libs, and as CLI tools. It doesn't look like they call out to a web service, but I didn't check too closely. See the github repo with install instructions.
From their docs for Python CLI and library usage:
To beautify using python:
$ pip install jsbeautifier
$ js-beautify file.js
Beautified output goes to stdout
.
To use jsbeautifier
as a library is simple:
import jsbeautifier
res = jsbeautifier.beautify('your javascript string')
res = jsbeautifier.beautify_file('some_file.js')
...or, to specify some options:
opts = jsbeautifier.default_options()
opts.indent_size = 2
res = jsbeautifier.beautify('some javascript', opts)
If you want to pass a string instead of a filename, and you are using bash, then you can use process substitution like so:
$ js-beautify <(echo '{"some": "json"}')
Elizabeth Castro has an interesting article on this problem: Bye Bye Embed. Worth a read on how she attacked this problem, as well as handling QuickTime content.
If you use MAMP, you might have to set the socket: unix_socket: /Applications/MAMP/tmp/mysql/mysql.sock
Under Project->Properties->Debug, you should see a box for Command line arguments (This is in C# 2010, but it should basically be the same place)
$('#test').click(function() {_x000D_
var todayDate = moment("01.01.2019", "DD.MM.YYYY");_x000D_
var endDate = moment("08.02.2019", "DD.MM.YYYY");_x000D_
_x000D_
var result = 'Diff: ' + todayDate.diff(endDate, 'days');_x000D_
_x000D_
$('#result').html(result);_x000D_
});
_x000D_
#test {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background: #ffb;_x000D_
padding: 10px;_x000D_
border: 2px solid #999;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.js"></script>_x000D_
_x000D_
<div id='test'>Click Me!!!</div>_x000D_
<div id='result'></div>
_x000D_