const person = {
name: "Lokamn",
dob: 12,
print: function (value,value2) {
console.log(this.dob+value+value2)
}
}
const anotherPerson= {
name: "Pappu",
dob: 12,
}
person.print.call(anotherPerson,1,2)
name: "Lokamn",
dob: 12,
print: function (value,value2) {
console.log(this.dob+value+value2)
}
}
const anotherPerson= {
name: "Pappu",
dob: 12,
}
person.print.apply(anotherPerson,[1,2])
**call and apply function are difference call take separate argument but apply take array like:[1,2,3] **
name: "Lokamn",
dob: 12,
anotherPerson: {
name: "Pappu",
dob: 12,
print2: function () {
console.log(this)
}
}
}
var bindFunction = person.anotherPerson.print2.bind(person)
bindFunction()
For anyone learning this stuff, comments are more important, so drawing on Xak Tacit's idea
(from User500099's link) for Single Property comments, add this to the top of the XAML code block:
<!--Comments Allowed With Markup Compatibility (mc) In XAML!
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ØignoreØ="http://www.galasoft.ch/ignore"
mc:Ignorable="ØignoreØ"
Usage in property:
ØignoreØ:AttributeToIgnore="Text Of AttributeToIgnore"-->
Then in the code block
<Application FooApp:Class="Foo.App"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ØignoreØ="http://www.galasoft.ch/ignore"
mc:Ignorable="ØignoreØ"
...
AttributeNotToIgnore="TextNotToIgnore"
...
...
ØignoreØ:IgnoreThisAttribute="IgnoreThatText"
...
>
</Application>
Just use Array.from()
method to convert it to an Array
:
myMap : Map<string, boolean>;
for(let key of Array.from( myMap.keys()) ) {
console.log(key);
}
I suggest you do it through the GET request: for example, index.html:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form action="result.php" method="post">
Answer 1 <input type="radio" name="ans" value="ans1" /><br />
Answer 2 <input type="radio" name="ans" value="ans2" /><br />
Answer 3 <input type="radio" name="ans" value="ans3" /><br />
Answer 4 <input type="radio" name="ans" value="ans4" /><br />
<input type="button" value="submit" onclick="sendPost()" />
</form>
<script type="text/javascript">
function sendPost(){
var value = $('input[name="ans"]:checked').val();
window.location.href = "sendpost.php?ans="+value;
};
</script>
this is sendpost.php:
<?php
if(isset($_GET["ans"]) AND !empty($_GET["ans"])){
echo $_GET["ans"];
}
?>
To see local changes compare to your current branch
git diff .
To see local changed compare to any other existing branch
git diff <branch-name> .
To see changes of a particular file
git diff <branch-name> -- <file-path>
Make sure you run git fetch
at the beginning.
If you're using Ubuntu and have "Upstart" (http://upstart.ubuntu.com/) you can try this:
Create /var/init/yourservice.conf
with the following content
description "Your Java Service"
author "You"
start on runlevel [3]
stop on shutdown
expect fork
script
cd /web
java -jar server.jar >/var/log/yourservice.log 2>&1
emit yourservice_running
end script
Now you can issue the service yourservice start
and service yourservice stop
commands. You can tail /var/log/yourservice.log
to verify that it's working.
If you just want to run your jar from the console without it hogging the console window, you can just do:
java -jar /web/server.jar > /var/log/yourservice.log 2>&1
Have you tried to use CTRL-F5 to update the page?
Go to the appropriate subdirectory of the EDQP Tomcat installation directory. The default directories are:
On Linux: /opt/server/tomcat/bin
On Windows: c:\server\tomcat\bin
Run the startup command:
On Linux: ./startup.sh
On Windows: % startup.bat
Run the shutdown command:
On Linux: ./shutdown.sh
On Windows: % shutdown.bat
Although Chang's answer explains how to plot multiple times on the same figure, in this case you might be better off in this case using a groupby
and unstack
ing:
(Assuming you have this in dataframe, with datetime index already)
In [1]: df
Out[1]:
value
datetime
2010-01-01 1
2010-02-01 1
2009-01-01 1
# create additional month and year columns for convenience
df['Month'] = map(lambda x: x.month, df.index)
df['Year'] = map(lambda x: x.year, df.index)
In [5]: df.groupby(['Month','Year']).mean().unstack()
Out[5]:
value
Year 2009 2010
Month
1 1 1
2 NaN 1
Now it's easy to plot (each year as a separate line):
df.groupby(['Month','Year']).mean().unstack().plot()
Giving width to Label is not a proper way. you should take one div or table structure to manage this. but still if you don't want to change your whole code then you can use following code.
label {
width:200px;
float: left;
}
//add BOM to fix UTF-8 in Excel
fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
I got this line from Cool
At the present time, Intel graphics chips do not support CUDA. It is possible that, in the nearest future, these chips will support OpenCL (which is a standard that is very similar to CUDA), but this is not guaranteed and their current drivers do not support OpenCL either. (There is an Intel OpenCL SDK available, but, at the present time, it does not give you access to the GPU.)
Newest Intel processors (Sandy Bridge) have a GPU integrated into the CPU core. Your processor may be a previous-generation version, in which case "Intel(HD) graphics" is an independent chip.
Its a very late answer, but you can also use the Collections.singleton
:
List<String> list = new ArrayList<String>(Arrays.asList("", "Hi", null, "How"));
list.removeAll(Collections.singleton(null));
list.removeAll(Collections.singleton(""));
If really you can't use Defense Option 1: Prepared Statements (Parameterized Queries) or Defense Option 2: Stored Procedures, don't build your own tool, use the OWASP Enterprise Security API. From the OWASP ESAPI hosted on Google Code:
Don’t write your own security controls! Reinventing the wheel when it comes to developing security controls for every web application or web service leads to wasted time and massive security holes. The OWASP Enterprise Security API (ESAPI) Toolkits help software developers guard against security-related design and implementation flaws.
For more details, see Preventing SQL Injection in Java and SQL Injection Prevention Cheat Sheet.
Pay a special attention to Defense Option 3: Escaping All User Supplied Input that introduces the OWASP ESAPI project).
My solotion for responsive/dropdown navbar with angular-ui bootstrap (when update to angular 1.5 and, ui-bootrap 1.2.1)
index.html
...
<link rel="stylesheet" href="/css/app.css">
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<input type="checkbox" id="navbar-toggle-cbox">
<div class="navbar-header">
<label for="navbar-toggle-cbox" class="navbar-toggle"
ng-init="navCollapsed = true"
ng-click="navCollapsed = !navCollapsed"
aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</label>
<a class="navbar-brand" href="#">Project name</a>
<div id="navbar" class="collapse navbar-collapse" ng-class="{'in':!navCollapsed}">
<ul class="nav navbar-nav">
<li class="active"><a href="/view1">Home</a></li>
<li><a href="/view2">About</a></li>
<li><a href="#">Contact</a></li>
<li uib-dropdown>
<a href="#" uib-dropdown-toggle>Dropdown <b class="caret"></b></a>
<ul uib-dropdown-menu role="menu" aria-labelledby="split-button">
<li role="menuitem"><a href="#">Action</a></li>
<li role="menuitem"><a href="#">Another action</a></li>
</ul>
</li>
</ul>
</div>
</div>
</div>
</nav>
app.css
/* show the collapse when navbar toggle is checked */
#navbar-toggle-cbox:checked ~ .collapse {
display: block;
}
/* the checkbox used only internally; don't display it */
#navbar-toggle-cbox {
display:none
}
I use the ffmpeg-python
binding. You can find more information here.
import ffmpeg
(
ffmpeg
.input('/path/to/jpegs/*.jpg', pattern_type='glob', framerate=25)
.output('movie.mp4')
.run()
)
You can use parameters like that
<jsp:include page='about.jsp'>
<jsp:param name="articleId" value=""/>
</jsp:include>
and
in about.jsp you can take the paramter
<%String leftAds = request.getParameter("articleId");%>
I answered this question in another post:
How to get list of changed files since last build in Jenkins/Hudson
#!/bin/bash
set -e
job_name="whatever"
JOB_URL="http://myserver:8080/job/${job_name}/"
FILTER_PATH="path/to/folder/to/monitor"
python_func="import json, sys
obj = json.loads(sys.stdin.read())
ch_list = obj['changeSet']['items']
_list = [ j['affectedPaths'] for j in ch_list ]
for outer in _list:
for inner in outer:
print inner
"
_affected_files=`curl --silent ${JOB_URL}${BUILD_NUMBER}'/api/json' | python -c "$python_func"`
if [ -z "`echo \"$_affected_files\" | grep \"${FILTER_PATH}\"`" ]; then
echo "[INFO] no changes detected in ${FILTER_PATH}"
exit 0
else
echo "[INFO] changed files detected: "
for a_file in `echo "$_affected_files" | grep "${FILTER_PATH}"`; do
echo " $a_file"
done;
fi;
You can add the check directly to the top of the job's exec shell, and it will exit 0
if no changes are detected... Hence, you can always poll the top level for check-in's to trigger a build.
I know this is old but I just ran into this problem and none of the answers are suitable. nickf's solution works but it requires javascript. The best way is to disable the field and still pass the value is to use a hidden input field to pass the value to the form. For example,
<input type="text" value="22.2222" disabled="disabled" />
<input type="hidden" name="lat" value="22.2222" />
This way the value is passed but the user sees the greyed out field. The readonly attribute does not gray it out.
The linefeed character \n
is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n
instead, then it'll both see the line-break with only \n
and \r\n
, I've never had any problems using it.
Also, you should look into using a StringBuilder
instead of concatenating the String
in the while-loop at BookCatalog.toString()
, it is a lot more effective. For instance:
public String toString() {
BookNode current = front;
StringBuilder sb = new StringBuilder();
while (current!=null){
sb.append(current.getData().toString()+"\r\n ");
current = current.getNext();
}
return sb.toString();
}
the easiest hack is to set a min-height
to your page container at 400px assuming your footer come at the end. you dont even have to put css for the footer or just a width:100%
assuming your footer is direct child of your <body>
Just use
composer require {package/packagename}
like
composer require phpmailer/phpmailer
if the package is not in the vendor folder.. composer installs it and if the package exists, composer update package to the latest version.
1. Installing OpenCV 2.4.3
First, get OpenCV 2.4.3 from sourceforge.net. Its a self-extracting so just double click to start the installation. Install it in a directory, say C:\
.
Wait until all files get extracted. It will create a new directory C:\opencv
which
contains OpenCV header files, libraries, code samples, etc.
Now you need to add the directory C:\opencv\build\x86\vc10\bin
to your system PATH. This directory contains OpenCV DLLs required for running your code.
Open Control Panel → System → Advanced system settings → Advanced Tab → Environment variables...
On the System Variables section, select Path (1), Edit (2), and type C:\opencv\build\x86\vc10\bin;
(3), then click Ok.
On some computers, you may need to restart your computer for the system to recognize the environment path variables.
This will completes the OpenCV 2.4.3 installation on your computer.
2. Create a new project and set up Visual C++
Open Visual C++ and select File → New → Project... → Visual C++ → Empty Project. Give a name for your project (e.g: cvtest
) and set the project location (e.g: c:\projects
).
Click Ok. Visual C++ will create an empty project.
Make sure that "Debug" is selected in the solution configuration combobox. Right-click cvtest
and select Properties → VC++ Directories.
Select Include Directories to add a new entry and type C:\opencv\build\include
.
Click Ok to close the dialog.
Back to the Property dialog, select Library Directories to add a new entry and type C:\opencv\build\x86\vc10\lib
.
Click Ok to close the dialog.
Back to the property dialog, select Linker → Input → Additional Dependencies to add new entries. On the popup dialog, type the files below:
opencv_calib3d243d.lib
opencv_contrib243d.lib
opencv_core243d.lib
opencv_features2d243d.lib
opencv_flann243d.lib
opencv_gpu243d.lib
opencv_haartraining_engined.lib
opencv_highgui243d.lib
opencv_imgproc243d.lib
opencv_legacy243d.lib
opencv_ml243d.lib
opencv_nonfree243d.lib
opencv_objdetect243d.lib
opencv_photo243d.lib
opencv_stitching243d.lib
opencv_ts243d.lib
opencv_video243d.lib
opencv_videostab243d.lib
Note that the filenames end with "d" (for "debug"). Also note that if you have installed another version of OpenCV (say 2.4.9) these filenames will end with 249d instead of 243d (opencv_core249d.lib..etc).
Click Ok to close the dialog. Click Ok on the project properties dialog to save all settings.
NOTE:
These steps will configure Visual C++ for the "Debug" solution. For "Release" solution (optional), you need to repeat adding the OpenCV directories and in Additional Dependencies section, use:
opencv_core243.lib
opencv_imgproc243.lib
...
instead of:
opencv_core243d.lib
opencv_imgproc243d.lib
...
You've done setting up Visual C++, now is the time to write the real code. Right click your project and select Add → New Item... → Visual C++ → C++ File.
Name your file (e.g: loadimg.cpp
) and click Ok. Type the code below in the editor:
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
Mat im = imread("c:/full/path/to/lena.jpg");
if (im.empty())
{
cout << "Cannot load image!" << endl;
return -1;
}
imshow("Image", im);
waitKey(0);
}
The code above will load c:\full\path\to\lena.jpg
and display the image. You can
use any image you like, just make sure the path to the image is correct.
Type F5 to compile the code, and it will display the image in a nice window.
And that is your first OpenCV program!
3. Where to go from here?
Now that your OpenCV environment is ready, what's next?
c:\opencv\samples\cpp
.(Re)installing the latest JDK (e.g. Oracle's) fixed it for me.
Prior to installing the latest JDK, when I executed the following command in Terminal.app:
keytool -list -keystore $(/usr/libexec/java_home)/jre/lib/security/cacerts -v
It resulted in:
keytool error: java.io.IOException: Invalid keystore format
java.io.IOException: Invalid keystore format
at sun.security.provider.JavaKeyStore.engineLoad(JavaKeyStore.java:650)
at sun.security.provider.JavaKeyStore$JKS.engineLoad(JavaKeyStore.java:55)
at java.security.KeyStore.load(KeyStore.java:1445)
at sun.security.tools.keytool.Main.doCommands(Main.java:792)
at sun.security.tools.keytool.Main.run(Main.java:340)
at sun.security.tools.keytool.Main.main(Main.java:333)
But, after installing the latest Oracle JDK and restarting Terminal, executing the following command:
keytool -list -keystore $(/usr/libexec/java_home)/jre/lib/security/cacerts -v
Results in:
Enter keystore password:
Which indicates that the keytool on path can access the keystore.
Say you want to Zip all the folders(sub directories) in the current directory.
for root, dirs, files in os.walk("."):
for sub_dir in dirs:
zip_you_want = sub_dir+".zip"
zip_process = zipfile.ZipFile(zip_you_want, "w", zipfile.ZIP_DEFLATED)
zip_process.write(file_you_want_to_include)
zip_process.close()
print("Successfully zipped directory: {sub_dir}".format(sub_dir=sub_dir))
It really depends what you would like to clone. Is this a truly JSON object or just any object in JavaScript? If you would like to do any clone, it might get you into some trouble. Which trouble? I will explain it below, but first, a code example which clones object literals, any primitives, arrays and DOM nodes.
function clone(item) {
if (!item) { return item; } // null, undefined values check
var types = [ Number, String, Boolean ],
result;
// normalizing primitives if someone did new String('aaa'), or new Number('444');
types.forEach(function(type) {
if (item instanceof type) {
result = type( item );
}
});
if (typeof result == "undefined") {
if (Object.prototype.toString.call( item ) === "[object Array]") {
result = [];
item.forEach(function(child, index, array) {
result[index] = clone( child );
});
} else if (typeof item == "object") {
// testing that this is DOM
if (item.nodeType && typeof item.cloneNode == "function") {
result = item.cloneNode( true );
} else if (!item.prototype) { // check that this is a literal
if (item instanceof Date) {
result = new Date(item);
} else {
// it is an object literal
result = {};
for (var i in item) {
result[i] = clone( item[i] );
}
}
} else {
// depending what you would like here,
// just keep the reference, or create new object
if (false && item.constructor) {
// would not advice to do that, reason? Read below
result = new item.constructor();
} else {
result = item;
}
}
} else {
result = item;
}
}
return result;
}
var copy = clone({
one : {
'one-one' : new String("hello"),
'one-two' : [
"one", "two", true, "four"
]
},
two : document.createElement("div"),
three : [
{
name : "three-one",
number : new Number("100"),
obj : new function() {
this.name = "Object test";
}
}
]
})
And now, let's talk about problems you might get when start cloning REAL objects. I'm talking now, about objects which you create by doing something like
var User = function(){}
var newuser = new User();
Of course you can clone them, it's not a problem, every object expose constructor property, and you can use it to clone objects, but it will not always work. You also can do simple for in
on this objects, but it goes to the same direction - trouble. I have also included clone functionality inside the code, but it's excluded by if( false )
statement.
So, why cloning can be a pain? Well, first of all, every object/instance might have some state. You never can be sure that your objects doesn't have for example an private variables, and if this is the case, by cloning object, you just break the state.
Imagine there is no state, that's fine. Then we still have another problem. Cloning via "constructor" method will give us another obstacle. It's an arguments dependency. You never can be sure, that someone who created this object, did not did, some kind of
new User({
bike : someBikeInstance
});
If this is the case, you are out of luck, someBikeInstance was probably created in some context and that context is unkown for clone method.
So what to do? You still can do for in
solution, and treat such objects like normal object literals, but maybe it's an idea not to clone such objects at all, and just pass the reference of this object?
Another solution is - you could set a convention that all objects which must be cloned should implement this part by themselves and provide appropriate API method ( like cloneObject ). Something what cloneNode
is doing for DOM.
You decide.
I try to explain the Bayes rule with an example.
What is the chance that a random person selected from the society is a smoker?
You may reply 10%, and let's assume that's right.
Now, what if I say that the random person is a man and is 15 years old?
You may say 15 or 20%, but why?.
In fact, we try to update our initial guess with new pieces of evidence ( P(smoker) vs. P(smoker | evidence)
). The Bayes rule is a way to relate these two probabilities.
P(smoker | evidence) = P(smoker)* p(evidence | smoker)/P(evidence)
Each evidence may increase or decrease this chance. For example, this fact that he is a man may increase the chance provided that this percentage (being a man) among non-smokers is lower.
In the other words, being a man must be an indicator of being a smoker rather than a non-smoker. Therefore, if an evidence is an indicator of something, it increases the chance.
But how do we know that this is an indicator?
For each feature, you can compare the commonness (probability) of that feature under the given conditions with its commonness alone. (P(f | x) vs. P(f))
.
P(smoker | evidence) / P(smoker) = P(evidence | smoker)/P(evidence)
For example, if we know that 90% of smokers are men, it's not still enough to say whether being a man is an indicator of being smoker or not. For example if the probability of being a man in the society is also 90%, then knowing that someone is a man doesn't help us ((90% / 90%) = 1
. But if men contribute to 40% of the society, but 90% of the smokers, then knowing that someone is a man increases the chance of being a smoker (90% / 40%) = 2.25
, so it increases the initial guess (10%) by 2.25 resulting 22.5%.
However, if the probability of being a man was 95% in the society, then regardless of the fact that the percentage of men among smokers is high (90%)! the evidence that someone is a man decreases the chance of him being a smoker! (90% / 95%) = 0.95)
.
So we have:
P(smoker | f1, f2, f3,... ) = P(smoker) * contribution of f1* contribution of f2 *...
=
P(smoker)*
(P(being a man | smoker)/P(being a man))*
(P(under 20 | smoker)/ P(under 20))
Note that in this formula we assumed that being a man and being under 20 are independent features so we multiplied them, it means that knowing that someone is under 20 has no effect on guessing that he is man or woman. But it may not be true, for example maybe most adolescence in a society are men...
To use this formula in a classifier
The classifier is given with some features (being a man and being under 20) and it must decide if he is an smoker or not (these are two classes). It uses the above formula to calculate the probability of each class under the evidence (features), and it assigns the class with the highest probability to the input. To provide the required probabilities (90%, 10%, 80%...) it uses the training set. For example, it counts the people in the training set that are smokers and find they contribute 10% of the sample. Then for smokers checks how many of them are men or women .... how many are above 20 or under 20....In the other words, it tries to build the probability distribution of the features for each class based on the training data.
You can set it as a no title bar theme in the activity's xml in the AndroidManifest
<activity
android:name=".AnActivity"
android:label="@string/a_string"
android:theme="@android:style/Theme.NoTitleBar">
</activity>
There are now 8-digit hex codes in CSS4 (CSS Color Module Level 4), the last two digit (or in case of the abbreviation, the last of the 4 digits) represents alpha, 00
meaning fully transparent and ff
meaning fully opaque, 7f
representing an opacity of 0.5 etc.
The format is '#rrggbbaa'
or the shorthand, '#rgba'
.
Support is lacking for MS browsers, they might be less cooperative or just slower than the other developers, either or both of which actually sealed IE's fate: https://caniuse.com/#feat=css-rrggbbaa
$ sudo apt-get install libpq-dev
Year, this solve my problem. After execute this, do: pip install psycopg2
As long as you're not doing any INSERT or UPDATE statements in your stored procedure, you will probably want to make it a function.
Stored procedures are for executing by an outside program, or on a timed interval.
The answers here will explain it better than I can:
Can't be done natively with VBA. VBA is built in a single-threaded apartment. The only way to get multiple threads is to build a DLL in something other than VBA that has a COM interface and call it from VBA.
Besides grep
, you can also use other utilities such as awk
or sed
Here is a few examples. Let say you want to search for a string is
in the file named GPL
.
Your sample file
user@linux:~$ cat -n GPL
1 The GNU General Public License is a free, copyleft license for
2 The licenses for most software and other practical works are designed
3 the GNU General Public License is intended to guarantee your freedom to
4 GNU General Public License for most of our software;
user@linux:~$
1. grep
user@linux:~$ grep is GPL
The GNU General Public License is a free, copyleft license for
the GNU General Public License is intended to guarantee your freedom to
user@linux:~$
2. awk
user@linux:~$ awk /is/ GPL
The GNU General Public License is a free, copyleft license for
the GNU General Public License is intended to guarantee your freedom to
user@linux:~$
3. sed
user@linux:~$ sed -n '/is/p' GPL
The GNU General Public License is a free, copyleft license for
the GNU General Public License is intended to guarantee your freedom to
user@linux:~$
Hope this helps
I faced the same problem but it resolved with some changes in setting.xml(.*\apache-maven-3.3.3\apache-maven-3.3.3\conf)
.
<proxies>
<proxy>
<id>proxy</id>
<active>true</active>
<protocol>http</protocol>
<host>HOSTNAME</host>
<port>PORT</port>
</proxy>
</proxies>
Just check the hostname and port from the IE setting -> connections -> LAN Setting -> Proxy server
Hope this will resolve your problem also :)
Short answer...yes. You can use an anonymous class when you initialize a variable. Take a look at this question: Anonymous vs named inner classes? - best practices?
In my case, I needed to close just one excel window and not the entire application, so, I needed to tell which exact window to close, without saving it.
The following lines work just fine:
Sub test_t()
Windows("yourfilename.xlsx").Activate
ActiveWorkbook.Close SaveChanges:=False
End Sub
well the only thing that will work is
python -m pip install pip==
you can and should run it under IDE terminal (mine was pycharm)
Taken from the docs here:
Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules. For example, to subtract 5 days from the current time of the calendar, you can achieve it by calling:
Calendar calendar = Calendar.getInstance(); // this would default to now calendar.add(Calendar.DAY_OF_MONTH, -5).
I would use:
awk 'FNR <= 1' file_*.txt
As @Kusalananda points out there are many ways to capture the first line in command line but using the head -n 1
may not be the best option when using wildcards since it will print additional info. Changing 'FNR == i'
to 'FNR <= i'
allows to obtain the first i lines.
For example, if you have n files named file_1.txt, ... file_n.txt:
awk 'FNR <= 1' file_*.txt
hello
...
bye
But with head
wildcards print the name of the file:
head -1 file_*.txt
==> file_1.csv <==
hello
...
==> file_n.csv <==
bye
[UPDATE]
As per March 7, 2017, Visual Studio 2017
was released for general availability.
You can refer to Mehdi Dehghani answer for the direct download links
or the old-fashioned ways using the website, vibs2006 answer
And you can also combine it with ray pixar answer to make it a complete full standalone offline installer.
Note:
I don't condone any illegal use of the offline installer.
Please stop piracy and follow the EULA.The community edition is free even for commercial use, under some condition.
You can see the EULA in this link below.
https://www.visualstudio.com/support/legal/mt171547
Thank you.
Instruction for official offline installer:
Open this link
Scroll Down (DO NOT FORGET!)
These menu should be available in that panel:
- Community 2015
- Enterprise 2015
- Professional 2015
- Enterprise 2015
- Visual Studio 2015 Update
- Visual Studio 2015 Language Pack
- Visual Studio Test Professional 2015 Language Pack
- Test Professional 2015
- Express 2015 for Desktop
- Express 2015 for Windows 10
The language drop-down menu should be like this:
- English for English
- Deutsch for German
- Español for Spanish
- Français for French
- Italiano for Italian
- ??????? for Russian
- ??? for Japanese
- ???? for Chinese (Simplified)
- ???? for Chinese (Traditional)
- ??? for Korean
Check on "ISO" in radio-button menu (on the left side of the Download button)
The radio-button menu should be like this:
- Web installer
- ISO
Click the Download button
I had the same problem but with an other cause. The solution was to deactivate Avira Browser Protection (in german Browser-Schutz). I took the solusion from m2e cannot transfer metadata from nexus, but maven command line can. It can be activated again ones maven has the needed plugin.
Update your working copy to the selected revision. Useful if you want to have your working copy reflect a time in the past, or if there have been further commits to the repository and you want to update your working copy one step at a time. It is best to update a whole directory in your working copy, not just one file, otherwise your working copy could be inconsistent. This is used to test a specific rev purpose, if your test has done, you can use this command to test another rev or use SVN Update to get HEAD
If you want to undo an earlier change permanently, use Revert to this revision instead.
-- from TSVN help doc
If you Update your working copy to an earlier rev, this is only affect your own working copy, after you do some change, and want to commit, you will fail,TSVN will alert you to update your WC to latest revision first If you Revert to a rev, you can commit to repository.everyone will back to the rev after they do an update.
As others have said, it's an initialisation list. You can use it for two things:
For case #1, I assume you understand inheritance (if that's not the case, let me know in the comments). So you are simply calling the constructor of your base class.
For case #2, the question may be asked: "Why not just initialise it in the body of the constructor?" The importance of the initialisation lists is particularly evident for const
members. For instance, take a look at this situation, where I want to initialise m_val
based on the constructor parameter:
class Demo
{
Demo(int& val)
{
m_val = val;
}
private:
const int& m_val;
};
By the C++ specification, this is illegal. We cannot change the value of a const
variable in the constructor, because it is marked as const. So you can use the initialisation list:
class Demo
{
Demo(int& val) : m_val(val)
{
}
private:
const int& m_val;
};
That is the only time that you can change a const member variable. And as Michael noted in the comments section, it is also the only way to initialise a reference that is a class member.
Outside of using it to initialise const
member variables, it seems to have been generally accepted as "the way" of initialising variables, so it's clear to other programmers reading your code.
A write-up of jme's suggestion, using pathlib, in Python 3.
from pathlib import Path
parent = Path(r'/a/b')
son = Path(r'/a/b/c/d')
?
if parent in son.parents or parent==son:
print(son.relative_to(parent)) # returns Path object equivalent to 'c/d'
In PHP an array is an array; there is no primitive vs. object consideration, so there is no comparable optimization to be had.
The account that sql server is running under does not have access to the location where you have the backup file or are trying to restore the database to. You can use SQL Server Configuration Manager to find which account is used to run the SQL Server instance, and then make sure that account has full control over the .BAK file and the folder where the MDF will be restored to.
Click 'Run'->choose your JUnit->in 'Test Runner' select the JUnit version you want to run with.
These are the conversions for setting the text color opacity levels.
DE000000
8A000000
61000000
1F000000
FFFFFFFF
B3FFFFFF
80FFFFFF
1FFFFFFF
If you are looking for a custom code instead of plugin, then this might help you. Facebook graph has under gone some changes since it has evolved. These steps are for the latest Graph API which I tried recently and worked well.
There are two main steps involved - 1. Getting Facebook Access Token, 2. Calling the Graph API passing the access token.
1. Getting the access token - Here is the step by step process to get the access token for your Facebook page. - Embed Facebook page feed on my website. As per this you need to create an app in Facebook developers page which would give you an App Id and an App Secret. Use these two and get the Access Token.
2. Calling the Graph API - This would be pretty simple once you get the access token. You just need to form a URL to Graph API with all the fields/properties you want to retrieve and make a GET request to this URL. Here is one example on how to do it in asp.net MVC. Embedding facebook feeds using asp.net mvc. This should be pretty similar in any other technology as it would be just a HTTP GET request.
Sample FQL Query: https://graph.facebook.com/FBPageName/posts?fields=full_picture,picture,link,message,created_time&limit=5&access_token=YOUR_ACCESS_TOKEN_HERE
A much shorter version for getting a list of all subclasses:
from itertools import chain
def subclasses(cls):
return list(
chain.from_iterable(
[list(chain.from_iterable([[x], subclasses(x)])) for x in cls.__subclasses__()]
)
)
You need to check your project settings, under C++, check include directories and make sure it points to where GameEngine.h
resides, the other issue could be that GameEngine.h
is not in your source file folder or in any include directory and resides in a different folder relative to your project folder. For instance you have 2 projects ProjectA
and ProjectB
, if you are including GameEngine.h
in some source/header file in ProjectA
then to include it properly, assuming that ProjectB
is in the same parent folder do this:
include "../ProjectB/GameEngine.h"
This is if you have a structure like this:
Root\ProjectA
Root\ProjectB <- GameEngine.h actually lives here
Issue happens because Microsoft Security Update MS11-100 limits number of keys in Forms collection during HTTP POST request. To alleviate this problem you need to increase that number.
This can be done in your application Web.Config in the
<appSettings>
section (create the section directly under<configuration>
if it doesn’t exist). Add 2 lines similar to the lines below to the section:<add key="aspnet:MaxHttpCollectionKeys" value="2000" /> <add key="aspnet:MaxJsonDeserializerMembers" value="2000" />
The above example set the limit to 2000 keys. This will lift the limitation and the error should go away.
I'd say the closest thing to "IF" in CSS are media queries, such as those you can use for responsive design. With media queries, you're saying things like, "If the screen is between 440px and 660px wide, do this". Read more about media queries here: http://www.w3schools.com/cssref/css3_pr_mediaquery.asp, and here's an example of how they look:
@media screen and (max-width: 300px) {
body {
background-color: lightblue;
}
}
That's pretty much the extent of "IF" within CSS, except to move over to SASS/SCSS (as mentioned above).
I think your best bet is to change your classes / IDs within the scripting language, and then treat each of the class/ID options in your CSS. For instance, in PHP, it might be something like:
<?php
if( A > B ){
echo '<div class="option-a">';
}
else{
echo '<div class="option-b">';
}
?>
Then your CSS can be like
.option-a {
background-color:red;
}
.option-b {
background-color:blue;
}
Html.Raw()
returns IHtmlString
, not the ordinary string
. So, you cannot write them in opposite sides of :
operator. Remove that .ToString()
calling
@{int count = 0;}
@foreach (var item in Model.Resources)
{
@(count <= 3 ? Html.Raw("<div class=\"resource-row\">"): Html.Raw(""))
// some code
@(count <= 3 ? Html.Raw("</div>") : Html.Raw(""))
@(count++)
}
By the way, returning IHtmlString
is the way MVC recognizes html content and does not encode it. Even if it hasn't caused compiler errors, calling ToString()
would destroy meaning of Html.Raw()
Your error is happening because Object
is a module, not a class. So your inheritance is screwy.
Change your import statement to:
from Object import ClassName
and your class definition to:
class Visitor(ClassName):
or
change your class definition to:
class Visitor(Object.ClassName):
etc
For IE8 support, the "content" property cannot be empty.
To get around this I've done the following :
.ul li:after {
content:"icon";
text-indent:-999em;
display:block;
width:32px;
height:32px;
background:url(../img/icons/spritesheet.png) 0 -620px no-repeat;
margin:5% 0 0 45%;
}
Note : This works with image sprites too
The history limit is a pane attribute that is fixed at the time of pane creation and cannot be changed for existing panes. The value is taken from the history-limit
session option (the default value is 2000).
To create a pane with a different value you will need to set the appropriate history-limit
option before creating the pane.
To establish a different default, you can put a line like the following in your .tmux.conf
file:
set-option -g history-limit 3000
Note: Be careful setting a very large default value, it can easily consume lots of RAM if you create many panes.
For a new pane (or the initial pane in a new window) in an existing session, you can set that session’s history-limit
. You might use a command like this (from a shell):
tmux set-option history-limit 5000 \; new-window
For (the initial pane of the initial window in) a new session you will need to set the “global” history-limit
before creating the session:
tmux set-option -g history-limit 5000 \; new-session
Note: If you do not re-set the history-limit
value, then the new value will be also used for other panes/windows/sessions created in the future; there is currently no direct way to create a single new pane/window/session with its own specific limit without (at least temporarily) changing history-limit
(though show-option
(especially in 1.7 and later) can help with retrieving the current value so that you restore it later).
For completeness, in python 3.6 f-string are introduced in PEP-498. These strings make it possible to
embed expressions inside string literals, using a minimal syntax.
That would mean that for your example you could also use:
f'{self.author} in {self.publication}'
Try like this:
$.ajax({
type: 'POST',
// make sure you respect the same origin policy with this url:
// http://en.wikipedia.org/wiki/Same_origin_policy
url: 'http://nakolesah.ru/',
data: {
'foo': 'bar',
'ca$libri': 'no$libri' // <-- the $ sign in the parameter name seems unusual, I would avoid it
},
success: function(msg){
alert('wow' + msg);
}
});
Simple as this: <input type="text" name="email" value="e-mail..." onFocus="this.value=''">
The steel is far from hot, but I combined @abatishchev's solution with the answer from this post and got to this result. Hope it's useful:
public static class GlobalVars
{
private const string GlobalKey = "AllMyVars";
static GlobalVars()
{
Hashtable table = HttpContext.Current.Application[GlobalKey] as Hashtable;
if (table == null)
{
table = new Hashtable();
HttpContext.Current.Application[GlobalKey] = table;
}
}
public static Hashtable Vars
{
get { return HttpContext.Current.Application[GlobalKey] as Hashtable; }
}
public static IEnumerable<SomeClass> SomeCollection
{
get { return GetVar("SomeCollection") as IEnumerable<SomeClass>; }
set { WriteVar("SomeCollection", value); }
}
internal static DateTime SomeDate
{
get { return (DateTime)GetVar("SomeDate"); }
set { WriteVar("SomeDate", value); }
}
private static object GetVar(string varName)
{
if (Vars.ContainsKey(varName))
{
return Vars[varName];
}
return null;
}
private static void WriteVar(string varName, object value)
{
if (value == null)
{
if (Vars.ContainsKey(varName))
{
Vars.Remove(varName);
}
return;
}
if (Vars[varName] == null)
{
Vars.Add(varName, value);
}
else
{
Vars[varName] = value;
}
}
}
I've written this Codesandbox for a roundtrip from UTC to local time and from local time to UTC. You can change the timezone and the format. Enjoy!
Full Example on Codesandbox (DEMO):
https://codesandbox.io/s/momentjs-utc-to-local-roundtrip-foj57?file=/src/App.js
For Picrofo EDY
It depends, if you use the ShowDialog()
as a way of showing your form and to close it you use the close button instead of this.Close()
. The form will not be disposed or destroyed, it will only be hidden and changes can be made after is gone. In order to properly close it you will need the Dispose()
or Close()
method. In the other hand, if you use the Show()
method and you close it, the form will be disposed and can not be modified after.
Are there any performance benefits to using one over the other?
The current answer is no, because none of the current browser engines implements import/export
from the ES6 standard.
Some comparison charts http://kangax.github.io/compat-table/es6/ don't take this into account, so when you see almost all greens for Chrome, just be careful. import
keyword from ES6 hasn't been taken into account.
In other words, current browser engines including V8 cannot import new JavaScript file from the main JavaScript file via any JavaScript directive.
( We may be still just a few bugs away or years away until V8 implements that according to the ES6 specification. )
This document is what we need, and this document is what we must obey.
And the ES6 standard said that the module dependencies should be there before we read the module like in the programming language C, where we had (headers) .h
files.
This is a good and well-tested structure, and I am sure the experts that created the ES6 standard had that in mind.
This is what enables Webpack or other package bundlers to optimize the bundle in some special cases, and reduce some dependencies from the bundle that are not needed. But in cases we have perfect dependencies this will never happen.
It will need some time until import/export
native support goes live, and the require
keyword will not go anywhere for a long time.
What is require
?
This is node.js
way to load modules. ( https://github.com/nodejs/node )
Node uses system-level methods to read files. You basically rely on that when using require
. require
will end in some system call like uv_fs_open
(depends on the end system, Linux, Mac, Windows) to load JavaScript file/module.
To check that this is true, try to use Babel.js, and you will see that the import
keyword will be converted into require
.
Readify made a very complete answer. Yet, I wanted to add the End
statement, you can use:
Find the last used cell, before a blank in a Column:
Sub LastCellBeforeBlankInColumn()
Range("A1").End(xldown).Select
End Sub
Find the very last used cell in a Column:
Sub LastCellInColumn()
Range("A" & Rows.Count).End(xlup).Select
End Sub
Find the last cell, before a blank in a Row:
Sub LastCellBeforeBlankInRow()
Range("A1").End(xlToRight).Select
End Sub
Find the very last used cell in a Row:
Sub LastCellInRow()
Range("IV1").End(xlToLeft).Select
End Sub
See here for more information (and the explanation why xlCellTypeLastCell
is not very reliable).
C:\Program Files (x86)\LG Electronics\LG PC Suite\adb>adb install com.lge.filemanager-15052-v3.1.15052.apk
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
2683 KB/s (3159508 bytes in 1.150s)
pkg: /data/local/tmp/com.lge.filemanager-15052-v3.1.15052.apk
Success
C:\Program Files (x86)\LG Electronics\LG PC Suite\adb>
We can use the adb.exe which is there in PC suit, it worked for me. Thanks Chethan
You need to give the user table an alias the second time you join to it
e.g.
SELECT article . * , section.title, category.title, user.name, u2.name
FROM article
INNER JOIN section ON article.section_id = section.id
INNER JOIN category ON article.category_id = category.id
INNER JOIN user ON article.author_id = user.id
LEFT JOIN user u2 ON article.modified_by = u2.id
WHERE article.id = '1'
You can use reference type in generic arguments, not primitive type. So here you should use
Map<String, Integer> myMap = new HashMap<String, Integer>();
and store value as
myMap.put("abc", 5);
You should be able to add the Java Development Tools by selecting 'Help' -> 'Install New Software', there you select the 'Juno' update site, then 'Programming Languages' -> 'Eclipse Java Development Tools'.
After that, you will be able to run your JUnit tests with 'Right Click' -> 'Run as' -> 'JUnit test'.
For me this error was due to the command prompt, which was not running under administrator privileges. You need to right click on the command prompt and say "Run as administrator".
You need administrator role to install or uninstall a service.
I used this following code in my C++ project and it worked fine:
static HANDLE self;
static int numProcessors;
SYSTEM_INFO sysInfo;
double percent;
numProcessors = sysInfo.dwNumberOfProcessors;
//Getting system times information
FILETIME SysidleTime;
FILETIME SyskernelTime;
FILETIME SysuserTime;
ULARGE_INTEGER SyskernelTimeInt, SysuserTimeInt;
GetSystemTimes(&SysidleTime, &SyskernelTime, &SysuserTime);
memcpy(&SyskernelTimeInt, &SyskernelTime, sizeof(FILETIME));
memcpy(&SysuserTimeInt, &SysuserTime, sizeof(FILETIME));
__int64 denomenator = SysuserTimeInt.QuadPart + SyskernelTimeInt.QuadPart;
//Getting process times information
FILETIME ProccreationTime, ProcexitTime, ProcKernelTime, ProcUserTime;
ULARGE_INTEGER ProccreationTimeInt, ProcexitTimeInt, ProcKernelTimeInt, ProcUserTimeInt;
GetProcessTimes(self, &ProccreationTime, &ProcexitTime, &ProcKernelTime, &ProcUserTime);
memcpy(&ProcKernelTimeInt, &ProcKernelTime, sizeof(FILETIME));
memcpy(&ProcUserTimeInt, &ProcUserTime, sizeof(FILETIME));
__int64 numerator = ProcUserTimeInt.QuadPart + ProcKernelTimeInt.QuadPart;
//QuadPart represents a 64-bit signed integer (ULARGE_INTEGER)
percent = 100*(numerator/denomenator);
Your first problem is that there are at least four definitions for "file size":
The "end of file" offset, which is the number of bytes you have to skip to go from the beginning to the end of the file.
In other words, it is the number of bytes logically in the file (from a usage perspective).
The "valid data length", which is equal to the offset of the first byte which is not actually stored.
This is always less than or equal to the "end of file", and is a multiple of the cluster size.
For example, a 1 GB file can have a valid data length of 1 MB. If you ask Windows to read the first 8 MB, it will read the first 1 MB and pretend the rest of the data was there, returning it as zeros.
The "allocated size" of a file. This is always greater than or equal to the "end of file".
This is the number of clusters that the OS has allocated for the file, multiplied by the cluster size.
Unlike the case where the "end of file" is greater than the "valid data length", The excess bytes are not considered to be part of the file's data, so the OS will not fill a buffer with zeros if you try to read in the allocated region beyond the end of the file.
The "compressed size" of a file, which is only valid for compressed (and sparse?) files.
It is equal to the size of a cluster, multiplied by the number of clusters on the volume that are actually allocated to this file.
For non-compressed and non-sparse files, there is no notion of "compressed size"; you would use the "allocated size" instead.
Your second problem is that a "file" like C:\Foo
can actually have multiple streams of data.
This name just refers to the default stream. A file might have alternate streams, like C:\Foo:Bar
, whose size is not even shown in Explorer!
Your third problem is that a "file" can have multiple names ("hard links").
For example, C:\Windows\notepad.exe
and C:\Windows\System32\notepad.exe
are two names for the same file. Any name can be used to open any stream of the file.
Your fourth problem is that a "file" (or directory) might in fact not even be a file (or directory):
It might be a soft link (a "symbolic link" or a "reparse point") to some other file (or directory).
That other file might not even be on the same drive. It might even point to something on the network, or it might even be recursive! Should the size be infinity if it's recursive?
Your fifth is that there are "filter" drivers that make certain files or directories look like actual files or directories, even though they aren't. For example, Microsoft's WIM image files (which are compressed) can be "mounted" on a folder using a tool called ImageX, and those do not look like reparse points or links. They look just like directories -- except that the're not actually directories, and the notion of "size" doesn't really make sense for them.
Your sixth problem is that every file requires metadata.
For example, having 10 names for the same file requires more metadata, which requires space. If the file names are short, having 10 names might be as cheap as having 1 name -- and if they're long, then having multiple names can use more disk space for the metadata. (Same story with multiple streams, etc.)
Do you count these, too?
You have to append it. Create the element with:
var $div = $("<div>my div</div>");
$div.click(function(){alert("clicked")})
return $div;
Then if you append it will work.
Lockheed Martin uses a 3-prefix naming scheme which was wonderful to work with, especially when reading others' code.
Scope Reference Type(*Case-by-Case) Type
member m pointer p integer n
argument a reference r short n
local l float f
double f
boolean b
So...
int A::methodCall(float af_Argument1, int* apn_Arg2)
{
lpn_Temp = apn_Arg2;
mpf_Oops = lpn_Temp; // Here I can see I made a mistake, I should not assign an int* to a float*
}
Take it for what's it worth.
You can try this with Color.FromArgb
:
Random rnd = new Random();
lbl.ForeColor = Color.FromArgb(rnd.Next(255), rnd.Next(255), rnd.Next(255));
You can use <LinearLayout>
to group elements horizontaly. Also you should use style to set margins, background and other properties. This will allow you not to repeat code for every label you use.
Here is an example:
<LinearLayout
style="@style/FormItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
style="@style/FormLabel"
android:layout_width="wrap_content"
android:layout_height="@dimen/default_element_height"
android:text="@string/name_label"
/>
<EditText
style="@style/FormText.Editable"
android:id="@+id/cardholderName"
android:layout_width="wrap_content"
android:layout_height="@dimen/default_element_height"
android:layout_weight="1"
android:gravity="right|center_vertical"
android:hint="@string/card_name_hint"
android:imeOptions="actionNext"
android:singleLine="true"
/>
</LinearLayout>
Also you can create a custom view base on the layout above. Have you looked at Creating custom view ?
Just simply add or die(mysqli_error($db));
at the end of your query, this will print the mysqli error.
mysqli_query($db,"INSERT INTO stockdetails (`itemdescription`,`itemnumber`,`sellerid`,`purchasedate`,`otherinfo`,`numberofitems`,`isitdelivered`,`price`) VALUES ('$itemdescription','$itemnumber','$sellerid','$purchasedate','$otherinfo','$numberofitems','$numberofitemsused','$isitdelivered','$price')") or die(mysqli_error($db));
As a side note I'd say you are at risk of mysql injection
, check here How can I prevent SQL injection in PHP?. You should really use prepared statements to avoid any risk.
When you say
(a['x']==1) and (a['y']==10)
You are implicitly asking Python to convert (a['x']==1)
and (a['y']==10)
to boolean values.
NumPy arrays (of length greater than 1) and Pandas objects such as Series do not have a boolean value -- in other words, they raise
ValueError: The truth value of an array is ambiguous. Use a.empty, a.any() or a.all().
when used as a boolean value. That's because its unclear when it should be True or False. Some users might assume they are True if they have non-zero length, like a Python list. Others might desire for it to be True only if all its elements are True. Others might want it to be True if any of its elements are True.
Because there are so many conflicting expectations, the designers of NumPy and Pandas refuse to guess, and instead raise a ValueError.
Instead, you must be explicit, by calling the empty()
, all()
or any()
method to indicate which behavior you desire.
In this case, however, it looks like you do not want boolean evaluation, you want element-wise logical-and. That is what the &
binary operator performs:
(a['x']==1) & (a['y']==10)
returns a boolean array.
By the way, as alexpmil notes,
the parentheses are mandatory since &
has a higher operator precedence than ==
.
Without the parentheses, a['x']==1 & a['y']==10
would be evaluated as a['x'] == (1 & a['y']) == 10
which would in turn be equivalent to the chained comparison (a['x'] == (1 & a['y'])) and ((1 & a['y']) == 10)
. That is an expression of the form Series and Series
.
The use of and
with two Series would again trigger the same ValueError
as above. That's why the parentheses are mandatory.
To comment block with nested comments: substitute inner (block) comments from "--" to "++"
<!-- *********************************************************************
* IMPORTANT: To uncomment section
* sub inner comments "++" -> "--" & remove this comment
*********************************************************************
<head>
<title>My document's title</title> <++! My document's title ++>
<link rel=stylesheet href="mydoc.css" type="text/css">
</head>
<body>
<++! My document's important HTML stuff ++>
...
...
...
</body>
*********************************************************************
* IMPORTANT: To uncomment section
* sub inner comments "++" -> "--" & remove this comment
*********************************************************************
-->
Thus, the outer most comment ignores all "invalid" inner (block) comments.
If the two
controller is nested in One
controller.
Then you can simply call:
$scope.parentmethod();
Angular will search for parentmethod
function starting with current scope and up until it will reach the rootScope
.
in IE, you can use
event.returnValue = false;
to achieve the same result.
And in order not to get an error, you can test for the existence of preventDefault:
if(event.preventDefault) event.preventDefault();
You can combine the two with:
event.preventDefault ? event.preventDefault() : (event.returnValue = false);
Use position: fixed
instead of position: absolute
.
See here.
Use Google Sheets and import the CSV file.
Then you can export that to use in Excel
In order to load local images to your React.js application, you need to add require
parameter in media sections like or Image tags, as below:
image={require('./../uploads/temp.jpg')}
Another approach is to make port redirection:
sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 900 -j REDIRECT --to-port 3000
And run your server on >1024 port:
require('http').createServer().listen(3000);
ps the same could be done for https(443) port by the way.
public List<Student> findStudentByReports(Date startDate, Date endDate) {
System.out.println("call findStudentMethd******************with this pattern"
+ startDate
+ endDate
+ "*********************************************");
return em
.createQuery(
"' select attendence from Attendence attendence where attendence.admissionDate BETWEEN : startDate '' AND endDate ''"
+ "'")
.setParameter("startDate", startDate, TemporalType.DATE)
.setParameter("endDate", endDate, TemporalType.DATE)
.getResultList();
}
The recommended way to install setuptools on Windows is to download ez_setup.py and run it. The script will download the appropriate .egg file and install it for you.
For best results, uninstall previous versions FIRST (see Uninstalling).
Once installation is complete, you will find an easy_install.exe program in your Python Scripts subdirectory. For simple invocation and best results, add this directory to your PATH environment variable, if it is not already present.
more details : https://pypi.python.org/pypi/setuptools
The best plugin so far is Bootstrap Multiselect
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery Multi Select Dropdown with Checkboxes</title>
<link rel="stylesheet" href="css/bootstrap-3.1.1.min.css" type="text/css" />
<link rel="stylesheet" href="css/bootstrap-multiselect.css" type="text/css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="js/bootstrap-3.1.1.min.js"></script>
<script type="text/javascript" src="js/bootstrap-multiselect.js"></script>
</head>
<body>
<form id="form1">
<div style="padding:20px">
<select id="chkveg" multiple="multiple">
<option value="cheese">Cheese</option>
<option value="tomatoes">Tomatoes</option>
<option value="mozarella">Mozzarella</option>
<option value="mushrooms">Mushrooms</option>
<option value="pepperoni">Pepperoni</option>
<option value="onions">Onions</option>
</select>
<br /><br />
<input type="button" id="btnget" value="Get Selected Values" />
<script type="text/javascript">
$(function() {
$('#chkveg').multiselect({
includeSelectAllOption: true
});
$('#btnget').click(function(){
alert($('#chkveg').val());
});
});
</script>
</div>
</form>
</body>
</html>
Here's the DEMO
$(function() {_x000D_
_x000D_
$('#chkveg').multiselect({_x000D_
includeSelectAllOption: true_x000D_
});_x000D_
_x000D_
$('#btnget').click(function() {_x000D_
alert($('#chkveg').val());_x000D_
});_x000D_
});
_x000D_
.multiselect-container>li>a>label {_x000D_
padding: 4px 20px 3px 20px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://davidstutz.de/bootstrap-multiselect/dist/js/bootstrap-multiselect.js"></script>_x000D_
<link href="https://davidstutz.de/bootstrap-multiselect/docs/css/bootstrap-3.3.2.min.css" rel="stylesheet"/>_x000D_
<link href="https://davidstutz.de/bootstrap-multiselect/dist/css/bootstrap-multiselect.css" rel="stylesheet"/>_x000D_
<script src="https://davidstutz.de/bootstrap-multiselect/docs/js/bootstrap-3.3.2.min.js"></script>_x000D_
_x000D_
<form id="form1">_x000D_
<div style="padding:20px">_x000D_
_x000D_
<select id="chkveg" multiple="multiple">_x000D_
<option value="cheese">Cheese</option>_x000D_
<option value="tomatoes">Tomatoes</option>_x000D_
<option value="mozarella">Mozzarella</option>_x000D_
<option value="mushrooms">Mushrooms</option>_x000D_
<option value="pepperoni">Pepperoni</option>_x000D_
<option value="onions">Onions</option>_x000D_
</select>_x000D_
_x000D_
<br /><br />_x000D_
_x000D_
<input type="button" id="btnget" value="Get Selected Values" />_x000D_
</div>_x000D_
</form>
_x000D_
The Resource
class also has a method getDimensionPixelSize() which I think will fit your needs.
Since Vagrant 1.1
customize
option is getting VirtualBox-specific.
The modern way to do it is:
config.vm.provider :virtualbox do |vb|
vb.customize ["modifyvm", :id, "--memory", "256"]
end
Not really sure what you meant by "the caption in the middle", but here's one solution to get your images appear side by side, using the excellent display:inline-block
:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title></title>
<style>
div.container {
display:inline-block;
}
p {
text-align:center;
}
</style>
</head>
<body>
<div class="container">
<img src="http://placehold.it/350x150" height="200" width="200" />
<p>This is image 1</p>
</div>
<div class="container">
<img class="middle-img" src="http://placehold.it/350x150"/ height="200" width="200" />
<p>This is image 2</p>
</div>
<div class="container">
<img src="http://placehold.it/350x150" height="200" width="200" />
<p>This is image 3</p>
</div>
</div>
</body>
</html>
Well, I made a simple two liner script for this, Its small and does what u want.
Check it http://jsfiddle.net/9RxLM/
Its a jquery solution :D
The shortest way is indeed just
String fileContents = new File('/path/to/file').text
but in this case you have no control on how the bytes in the file are interpreted as characters. AFAIK groovy tries to guess the encoding here by looking at the file content.
If you want a specific character encoding you can specify a charset name with
String fileContents = new File('/path/to/file').getText('UTF-8')
See API docs on File.getText(String)
for further reference.
Just press Alt+Shift+Q,c for quick access.(In windows)
There can be one more reason for such behavior - you delete current working directory.
For example:
# in terminal #1
cd /home/user/myJavaApp
# in terminal #2
rm -rf /home/user/myJavaApp
# in terminal #1
java -jar myJar.jar
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
Yes, generally the best way to store a file in a database is to save the byte array in a BLOB column. You will probably want a couple of columns to additionally store the file's metadata such as name, extension, and so on.
It is not always a good idea to store files in the database - for instance, the database size will grow fast if you store files in it. But that all depends on your usage scenario.
I had the same issue. In my case I was using digitalocean and nginx.
I have first setup a domain example.app and a subdomain dev.exemple.app in digitalocean.
Second,I purchased two ssl certificat from godaddy.
And finaly, I configured two domain in nginx to use those two ssl certificat with the following snipet
My example.app domain config
server {
listen 7000 default_server;
listen [::]:7000 default_server;
listen 443 ssl default_server;
listen [::]:443 ssl default_server;
root /srv/nodejs/echantillonnage1;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name echantillonnage.app;
ssl_certificate /srv/nodejs/certificatSsl/widcardcertificate/echantillonnage.app.chained.crt;
ssl_certificate_key /srv/nodejs/certificatSsl/widcardcertificate/echantillonnage.app.key;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
proxy_pass http://127.0.0.1:8090;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
#try_files $uri $uri/ =404;
}
}
My dev.example.app
server {
listen 7000 default_server;
listen [::]:7000 default_server;
listen 444 ssl default_server;
listen [::]:444 ssl default_server;
root /srv/nodejs/echantillonnage1;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name dev.echantillonnage.app;
ssl_certificate /srv/nodejs/certificatSsl/dev/dev.echantillonnage.app.chained.crt;
ssl_certificate_key /srv/nodejs/certificatSsl/dev/dev.echantillonnage.app.key;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
proxy_pass http://127.0.0.1:8091;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
#try_files $uri $uri/ =404;
}
}
When I was launching https://dev.echantillonnage.app , I was getting
Fix CURL (51) SSL error: no alternative certificate subject name matches
My mistake was the two lines bellow
listen 444 ssl default_server;
listen [::]:444 ssl default_server;
I had to change this to:
listen 443 ssl;
listen [::]:443 ssl;
What it mentions as you type adb?
step1. >adb shell
step2. >cd data/data
step3. >ls -l|grep "your app package here"
step4. >cd "your app package here"
step5. >sqlite3 xx.db
You can use the following command :
$ grep "phpmyadmin" $path_to_access.log | grep -Po "^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" | sort | uniq | xargs -I% sudo iptables -A INPUT -s % -j DROP
Explanation:
Make sure your IP isn't listed before piping through iptables drop!!
This will first find all lines in $path_to_access.log that have phpmyadmin in them,
then grep out the ip address from the start of the line,
then sort and unique them,
then add a rule to drop them in iptables
Again, just edit in echo %
at the end instead of the iptables command to make sure your IP isn't in there. Don't inadvertently ban your access to the server!
Limitations
You may need to change the grep part of the command if you're on mac or any system that doesn't have grep -P. I'm not sure if all systems start with xargs, so that might need to be installed too. It's super useful anyway if you do a lot of bash.
We had exactly the same challenge some time ago. We wanted to go with CEF3 open source library which is WPF-based and supports .NET 3.5.
Firstly, the author of CEF himself listed binding for different languages here.
Secondly, we went ahead with open source .NET CEF3 binding which is called Xilium.CefGlue and had a good success with it. In cases where something is not working as you'd expect, author usually very responsive to the issues opened in build-in bitbucket tracker
So far it has served us well. Author updates his library to support latest CEF3 releases and bug fixes on regular bases.
In T-SQL you can:
SELECT [Date]
FROM [FRIIB].[dbo].[ArchiveAnalog]
GROUP BY [Date], DATEPART(hh, [Date])
or
by minute use DATEPART(mi, [Date])
or
by 10 minutes use DATEPART(mi, [Date]) / 10
(like Timothy suggested)
I like using pandas.apply() with python format().
import pandas as pd
s = pd.Series([1.357, 1.489, 2.333333])
make_float = lambda x: "${:,.2f}".format(x)
s.apply(make_float)
Also, it can be easily used with multiple columns...
df = pd.concat([s, s * 2], axis=1)
make_floats = lambda row: "${:,.2f}, ${:,.3f}".format(row[0], row[1])
df.apply(make_floats, axis=1)
For Mac OS X, I replaced the utilities that come with the operating system and replaced them with a newer version of coreutils. This allows you to access tools like readlink -f
(for absolute path to files) and realpath
(absolute path to directories) on your Mac.
The Homebrew version appends a 'G' (for GNU Tools) in front of the command name -- so the equivalents become greadlink -f FILE
and grealpath DIRECTORY
.
Instructions for how to install the coreutils/GNU Tools on Mac OS X through Homebrew can be found in this StackExchange arcticle.
NB: The readlink -f
and realpath
commands should work out of the box for non-Mac Unix users.
Was facing the same issue multiple times and I have 2 solutions:
Solution 1: Add surefire plugin reference to pom.xml. Watch that you have all nodes! In my IDEs auto import version was missing!!!
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M3</version>
</plugin>
</plugins>
Solution 2: My IDE added wrong import to the start of the file.
IDE added
import org.junit.Test;
I had to replace it with
import org.junit.jupiter.api.Test;
Answer below the dotted line below is the original that's now outdated.
Here is the latest information ( Thank you @deadfish ):
add &hl=<language>
like &hl=pl
or &hl=en
example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl
All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en
......................................................................
To change the actual local market:
Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html
To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720
I search the source code inside of Github Repositories with the free Sourcegraph Chrome Extension ... But I Downloaded Chrome First, I knew other browsers support it though, such as - and maybe just only - Firefox.
I skimmed through SourceForge's Chrome Extension Docs and then also I looked at just what I needed for searching for directory names with Github's Search Engine itself, by reading some of Github's Codebase Searching Doc
Just for the fun, I'm offering an alternative solution using jOOQ and Java 8. Instead of using jOOQ, you could be using any other API that maps JDBC ResultSet
to List
, such as Spring JDBC or Apache DbUtils, or write your own ResultSetIterator
:
List<Object> list =
DSL.using(connection)
.fetch("SELECT col1, col2, col3, ...")
.stream()
.flatMap(r -> Arrays.stream(r.intoArray()))
.collect(Collectors.toList());
List<Object> list =
DSL.using(connection)
.fetch("SELECT col1, col2, col3, ...")
.stream()
.flatMap(Record::intoStream)
.collect(Collectors.toList());
(Disclaimer, I work for the company behind jOOQ)
I tried Ninh Pham's solution but it didn't work for me until I tweaked it - see below. Remove contentType and don't encode your json data
$.fn.postJSON = function(url, data) {
return $.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json'
});
There isn't a magic bullet solution for what you're looking for, unfortunately. Here's what you can do:
create an Interface class using this command in the Visual Studio Command Prompt window:
wsdl.exe yourFile.wsdl /l:CS /serverInterface
Use VB or CS for your language of choice. This will create a new .cs
or .vb
file.
Create a new .NET Web Service project. Import Existing File into your project - the file that was created in the step above.
In your .asmx.cs
file in Code-View, modify your class as such:
public class MyWebService : System.Web.Services.WebService, IMyWsdlInterface
{
[WebMethod]
public string GetSomeString()
{
//you'll have to write your own business logic
return "Hello SOAP World";
}
}
It is permission issue in my case the task scheduler has a user which doesn't have permission on the server in which the database is present.
Adding
--protocol=tcp
to the list of pramaters in your connection worked for me.
MacOS 10.15: Android Studio 3.5.1:
The solution that works for me was to use the Java Environment tool jenv
(installed via homebrew). This tool changes the $JAVA_HOME when one switches between java versions.
In my case I have multiple Java versions installed and the current global version in use was the default. I also found it necessary to comment out the $JAVA_HOME environment variable in my .bash_profile
when using this tool.
In Terminal, I entered jenv global 1.8
to get java 1.8 running instead of a later version (I have multiple versions installed).
After that:
flutter doctor --android-licenses
OR
sdkmanager --licenses
both work fine.
Note: You may need to exit and reopen your Terminal shell if you have to redefine the $JAVA_HOME environment variable.
I hope this will help you
Create table :
create table users (id int,first_name varchar(10),last_name varchar(10));
Insert values into the table :
insert into users (id,first_name,last_name) values(1,'Abhishek','Anand');
What about -mmin
?
find /var/www/html/audio -daystart -maxdepth 1 -mmin +59 -type f -name "*.mp3" \
-exec rm -f {} \;
From man find:
-mmin n File's data was last modified n minutes ago.
Also, make sure to test this first!
... -exec echo rm -f '{}' \; ^^^^ Add the 'echo' so you just see the commands that are going to get run instead of actual trying them first.
VS 2017
Tools>NuGet Package Manager>Package Manager Settings>General Click on "Clear All NuGet Cache(s)"
let imageDataDict:[String: UIImage] = ["image": image]
// post a notification
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict)
// `default` is now a property, not a method call
// Register to receive notification in your class
NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)
// handle notification
func showSpinningWheel(_ notification: NSNotification) {
print(notification.userInfo ?? "")
if let dict = notification.userInfo as NSDictionary? {
if let id = dict["image"] as? UIImage{
// do something with your image
}
}
}
let imageDataDict:[String: UIImage] = ["image": image]
// post a notification
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict)
// `default` is now a property, not a method call
// Register to receive notification in your class
NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)
// handle notification
@objc func showSpinningWheel(_ notification: NSNotification) {
print(notification.userInfo ?? "")
if let dict = notification.userInfo as NSDictionary? {
if let id = dict["image"] as? UIImage{
// do something with your image
}
}
}
Are you trying to echo out a style or an inline style? An inline style would be like
echo "<p style=\"font-color: #ff0000;\">text here</p>";
$epoch = 1483228800;
$dt = new DateTime("@$epoch"); // convert UNIX timestamp to PHP DateTime
echo $dt->format('Y-m-d H:i:s'); // output = 2017-01-01 00:00:00
In the examples above "r" and "Y-m-d H:i:s" are PHP date formats, other examples:
r ----- Wed, 15 Mar 2017 12:00:00 +0100 (RFC 2822 date)
c ----- 2017-03-15T12:00:00+01:00 (ISO 8601 date)
M/d/Y ----- Mar/15/2017
d-m-Y ----- 15-03-2017
Y-m-d H:i:s ----- 2017-03-15 12:00:00
If the value stored in PropertyLoader.RET_SECONDARY_V_ARRAY
is not "V_ARRAY"
, then you are using different types; even if they are declared identically (e.g. both are table of number
) this will not work.
You're hitting this data type compatibility restriction:
You can assign a collection to a collection variable only if they have the same data type. Having the same element type is not enough.
You're trying to call the procedure with a parameter that is a different type to the one it's expecting, which is what the error message is telling you.
java.version
is a system property that exists in every JVM. There are two possible formats for it:
1.6.0_23
, 1.7.0
, 1.7.0_80
, 1.8.0_211
9.0.1
, 11.0.4
, 12
, 12.0.1
Here is a trick to extract the major version: If it is a 1.x.y_z
version string, extract the character at index 2 of the string. If it is a x.y.z
version string, cut the string to its first dot character, if one exists.
private static int getVersion() {
String version = System.getProperty("java.version");
if(version.startsWith("1.")) {
version = version.substring(2, 3);
} else {
int dot = version.indexOf(".");
if(dot != -1) { version = version.substring(0, dot); }
} return Integer.parseInt(version);
}
Now you can check the version much more comfortably:
if(getVersion() < 6) {
// ...
}
No.. It is not proper way. Refer the steps,
For Classpath reference:
Right click on project in Eclipse -> Buildpath -> Configure Build path -> Java Build Path (left Pane) -> Libraries(Tab) -> Add External Jars -> Select your jar and select OK.
For Deployment Assembly:
Right click on WAR in eclipse-> Buildpath -> Configure Build path -> Deployment Assembly (left Pane) -> Add -> External file system -> Add -> Select your jar -> Add -> Finish.
This is the proper way! Don't forget to remove environment variable. It is not required now.
Try this. Surely it will work. Try to use Maven, it will simplify you task.
Had a similar issue. But it is important to understand the root cause and it may vary for different use cases.
Scenario 1
You are trying to decrypt a value which was not encoded correctly in the first place.
byte[] encryptedBytes = Base64.decodeBase64(encryptedBase64String);
If the String is misconfigured for certain reason or has not been encoded correctly, you would see the error " Input length must be multiple of 16 when decrypting with padded cipher"
Scenario 2
Now if by any chance you are using this encoded string in url (trying to pass in the base64Encoded value in url, it will fail.
You should do URLEncoding and then pass in the token, it will work.
Scenario 3
When integrating with one of the vendors, we found that we had to do encryption of Base64 using URLEncoder but then we need not decode it because it was done internally by the Vendor
This is a particularly involved problem on Windows, where it's not enough to just chmod the files correctly. You have to set up your environment.
On Windows, this worked for me:
Install cygwin.
Replace the msysgit ssh.exe with cygwin's ssh.exe.
Using cygwin bash, chmod 600 the private key file, which was "id_rsa" for me.
If it still doesn't work, go to Control Panel -> System Properties -> Advanced -> Environment Variables and add the following environment variable. Then repeat step 3.
Variable Value
CYGWIN sbmntsec
Corrected the Fiddle - updated shows the Image duplicated into the Canvas...
And right click can be saved as a .PNG
<div style="text-align:center">
<img src="http://imgon.net/di-M7Z9.jpg" id="picture" style="display:none;" />
<br />
<div id="for_jcrop">here the image should apear</div>
<canvas id="rotate" style="border:5px double black; margin-top:5px; "></canvas>
</div>
Plus the JS on the fiddle page...
Cheers Si
Currently looking at saving this to File on the server --- ASP.net C# (.aspx web form page) Any advice would be cool....
You should possibly make data
a keyword parameter with a default value of empty dictionary:
class DHT:
def __init__(self, data=dict()):
self.data['one'] = '1'
self.data['two'] = '2'
self.data['three'] = '3'
def showData(self):
print(self.data)
if __name__ == '__main__':
DHT().showData()
This happens because $cOTLdata
is not null but the index 'char_data'
does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.
To check whether the index exists or not you can use isset():
isset($cOTLdata['char_data'])
Which means the line should look something like this:
$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;
Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).
"Dino TW" has provided the link to the comment Hibernate Mapping Exception : Repeated column in mapping for entity which has the vital information.
The link hints to provide "inverse=true" in the set mapping, I tried it and it actually works. It is such a rare situation wherein a Set and Composite key come together. Make inverse=true, we leave the insert & update of the table with Composite key to be taken care by itself.
Below can be the required mapping,
<class name="com.example.CompanyEntity" table="COMPANY">
<id name="id" column="COMPANY_ID"/>
<set name="names" inverse="true" table="COMPANY_NAME" cascade="all-delete-orphan" fetch="join" batch-size="1" lazy="false">
<key column="COMPANY_ID" not-null="true"/>
<one-to-many entity-name="vendorName"/>
</set>
</class>
Use following one line of code .UseUrls("http://*:80")
in Program.cs
Thus changing .UseStartup<Startup>()
to.UseStartup<Startup>()
.UseUrls("http://*:80")
You can use Named Sections.
_Layout.cshtml
<head>
<script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
@RenderSection("JavaScript", required: false)
</head>
_SomeView.cshtml
@section JavaScript
{
<script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
<script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}
I had the same problem and found out that I had forgotten to include the script in the file which I want to include in the live site.
Also, you should try this:
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
You can use django's filter
with datetime.date
objects:
import datetime
samples = Sample.objects.filter(sampledate__gte=datetime.date(2011, 1, 1),
sampledate__lte=datetime.date(2011, 1, 31))
Bit of a late response but I noticed that this information can be hard to find and haven't found the answer on SO, so here it is.
Try a differnt parameter #view=FitH to force it to fit in the horzontal space and also you need to start the querystring off with a # rather than an & making it:
filename.pdf#view=FitH
What I've noticed it is that this will work if adobe reader is embedded in the browser but chrome will use it's own version of the reader and won't respond in the same way. In my own case, the chrome browser zoomed to fit width by default, so no problem , but Internet Explorer needed the above parameters to ensure the link always opened the pdf page with the correct view setting.
For a full list of available parameters see this doc
EDIT: (lazy mode on)
When you're using iOS >= 4
dispatch_async(dispatch_get_main_queue(), ^{
//Your main thread code goes in here
NSLog(@"Im on the main thread");
});
You might also find it useful to know generally what these data types are used for:
:string
- is for small data types such as a title. (Should you choose string or text?):text
- is for longer pieces of textual data, such as a paragraph of information:binary
- is for storing data such as images, audio, or movies.:boolean
- is for storing true or false values.:date
- store only the date:datetime
- store the date and time into a column. :time
- is for time only:timestamp
- for storing date and time into a column.(What's the difference between datetime and timestamp?):decimal
- is for decimals (example of how to use decimals).:float
- is for decimals. (What's the difference between decimal and float?):integer
- is for whole numbers.:primary_key
- unique key that can uniquely identify each row in a tableThere's also references used to create associations. But, I'm not sure this is an actual data type.
New Rails 4 datatypes available in PostgreSQL:
:hstore
- storing key/value pairs within a single value (learn more about this new data type):array
- an arrangement of numbers or strings in a particular row (learn more about it and see examples):cidr_address
- used for IPv4 or IPv6 host addresses:inet_address
- used for IPv4 or IPv6 host addresses, same as cidr_address but it also accepts values with nonzero bits to the right of the netmask:mac_address
- used for MAC host addressesLearn more about the address datatypes here and here.
Also, here's the official guide on migrations: http://edgeguides.rubyonrails.org/migrations.html
Option #1: Use Clear() function to empty the List<T>
and retain it's capacity.
Count is set to 0, and references to other objects from elements of the collection are also released.
Capacity remains unchanged.
Option #2 - Use Clear() and TrimExcess() functions to set List<T>
to initial state.
Count is set to 0, and references to other objects from elements of the collection are also released.
Trimming an empty
List<T>
sets the capacity of the List to the default capacity.
Definitions
Count = number of elements that are actually in the List<T>
Capacity = total number of elements the internal data structure can hold without resizing.
Clear() Only
List<string> dinosaurs = new List<string>();
dinosaurs.Add("Compsognathus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Deinonychus");
Console.WriteLine("Count: {0}", dinosaurs.Count);
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
dinosaurs.Clear();
Console.WriteLine("\nClear()");
Console.WriteLine("\nCount: {0}", dinosaurs.Count);
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
Clear() and TrimExcess()
List<string> dinosaurs = new List<string>();
dinosaurs.Add("Triceratops");
dinosaurs.Add("Stegosaurus");
Console.WriteLine("Count: {0}", dinosaurs.Count);
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
dinosaurs.Clear();
dinosaurs.TrimExcess();
Console.WriteLine("\nClear() and TrimExcess()");
Console.WriteLine("\nCount: {0}", dinosaurs.Count);
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
The difference is that raw_input()
does not exist in Python 3.x, while input()
does. Actually, the old raw_input()
has been renamed to input()
, and the old input()
is gone, but can easily be simulated by using eval(input())
. (Remember that eval()
is evil. Try to use safer ways of parsing your input if possible.)
You probably want to have LI rather than the UL have the background-color:
.selected li {
background-color: red;
}
Then you want to have a dynamic class for the UL:
<ul ng-repeat="vote in votes" ng-click="setSelected()" class="{{selected}}">
Now you need to update the $scope.selected when clicking the row:
$scope.setSelected = function() {
console.log("show", arguments, this);
this.selected = 'selected';
}
and then un-select the previously highlighted row:
$scope.setSelected = function() {
// console.log("show", arguments, this);
if ($scope.lastSelected) {
$scope.lastSelected.selected = '';
}
this.selected = 'selected';
$scope.lastSelected = this;
}
Working solution:
SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table. But you can alter table column datatype or other property by the following steps.
For more detail you can refer the link.
typeof(IMyInterface).IsAssignableFrom(someclass.GetType());
or
typeof(IMyInterface).IsAssignableFrom(typeof(MyType));
You can use the StringUtils.join()
method of Apache Commons Lang:
String join = StringUtils.join(joinList, "+");
It could be something like
var myvar = from a in context.MyEntity
join b in context.MyEntity2 on a.key equals b.key
select new { prop1 = a.prop1, prop2= b.prop1};
allow_url_fopen
is generally set to On.
If it is not On, then you can try two things.
Create an .htaccess
file and keep it in root folder ( sometimes it may need to place it one step back folder of the root) and paste this code there.
php_value allow_url_fopen On
Create a php.ini
file (for update server php5.ini
) and keep it in root folder (sometimes it may need to place it one step back folder of the root) and paste the following code there:
allow_url_fopen = On;
I have personally tested the above solutions; they worked for me.
Just restating what Tomasz said.
There are many examples of FOO__in=...
style filters in the many-to-many and many-to-one tests. Here is syntax for your specific problem:
users_in_1zone = User.objects.filter(zones__id=<id1>)
# same thing but using in
users_in_1zone = User.objects.filter(zones__in=[<id1>])
# filtering on a few zones, by id
users_in_zones = User.objects.filter(zones__in=[<id1>, <id2>, <id3>])
# and by zone object (object gets converted to pk under the covers)
users_in_zones = User.objects.filter(zones__in=[zone1, zone2, zone3])
The double underscore (__) syntax is used all over the place when working with querysets.
The only real difference between RPC and RMI is that there is objects involved in RMI: instead of invoking functions through a proxy function, we invoke methods through a proxy.
you can do top level await since typescript 3.8
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html#-top-level-await
From the post:
This is because previously in JavaScript (along with most other languages with a similar feature), await was only allowed within the body of an async function. However, with top-level await, we can use await at the top level of a module.
const response = await fetch("...");
const greeting = await response.text();
console.log(greeting);
// Make sure we're a module
export {};
Note there’s a subtlety: top-level await only works at the top level of a module, and files are only considered modules when TypeScript finds an import or an export. In some basic cases, you might need to write out export {} as some boilerplate to make sure of this.
Top level await may not work in all environments where you might expect at this point. Currently, you can only use top level await when the target compiler option is es2017 or above, and module is esnext or system. Support within several environments and bundlers may be limited or may require enabling experimental support.
As mentioned, you should use jsPDF and html2canvas. I've also found a function inside issues of jsPDF which splits automatically your pdf into multiple pages (sources)
function makePDF() {
var quotes = document.getElementById('container-fluid');
html2canvas(quotes, {
onrendered: function(canvas) {
//! MAKE YOUR PDF
var pdf = new jsPDF('p', 'pt', 'letter');
for (var i = 0; i <= quotes.clientHeight/980; i++) {
//! This is all just html2canvas stuff
var srcImg = canvas;
var sX = 0;
var sY = 980*i; // start 980 pixels down for every new page
var sWidth = 900;
var sHeight = 980;
var dX = 0;
var dY = 0;
var dWidth = 900;
var dHeight = 980;
window.onePageCanvas = document.createElement("canvas");
onePageCanvas.setAttribute('width', 900);
onePageCanvas.setAttribute('height', 980);
var ctx = onePageCanvas.getContext('2d');
// details on this usage of this function:
// https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images#Slicing
ctx.drawImage(srcImg,sX,sY,sWidth,sHeight,dX,dY,dWidth,dHeight);
// document.body.appendChild(canvas);
var canvasDataURL = onePageCanvas.toDataURL("image/png", 1.0);
var width = onePageCanvas.width;
var height = onePageCanvas.clientHeight;
//! If we're on anything other than the first page,
// add another page
if (i > 0) {
pdf.addPage(612, 791); //8.5" x 11" in pts (in*72)
}
//! now we declare that we're working on that page
pdf.setPage(i+1);
//! now we add content to that page!
pdf.addImage(canvasDataURL, 'PNG', 20, 40, (width*.62), (height*.62));
}
//! after the for loop is finished running, we save the pdf.
pdf.save('test.pdf');
}
});
}
Here is my solution, based on previous answers by Paul Grimshaw and Anthony VO. I've submitted the code in a C# project on Github.
My main contribution is to eliminate explicitly creating and manipulating a StringBuilder
and instead working only with IEnumerable
. This avoids the allocation of a big buffer in memory.
public static class Util
{
public static string EscapeQuotes(this string self) {
return self?.Replace("\"", "\"\"") ?? "";
}
public static string Surround(this string self, string before, string after) {
return $"{before}{self}{after}";
}
public static string Quoted(this string self, string quotes = "\"") {
return self.Surround(quotes, quotes);
}
public static string QuotedCSVFieldIfNecessary(this string self) {
return (self == null) ? "" : self.Contains('"') ? self.Quoted() : self;
}
public static string ToCsvField(this string self) {
return self.EscapeQuotes().QuotedCSVFieldIfNecessary();
}
public static string ToCsvRow(this IEnumerable<string> self){
return string.Join(",", self.Select(ToCsvField));
}
public static IEnumerable<string> ToCsvRows(this DataTable self) {
yield return self.Columns.OfType<object>().Select(c => c.ToString()).ToCsvRow();
foreach (var dr in self.Rows.OfType<DataRow>())
yield return dr.ItemArray.Select(item => item.ToString()).ToCsvRow();
}
public static void ToCsvFile(this DataTable self, string path) {
File.WriteAllLines(path, self.ToCsvRows());
}
}
This approach combines nicely with converting IEnumerable
to DataTable as asked here.
Update in 2020. For React devs who care performance seriously.
Above solutions do work BUT will re-render your components whenever the window size changes by a single pixel.
This often causes performance issues so I wrote useWindowDimension
hook that debounces the resize
event for a short period of time. e.g 100ms
import React, { useState, useEffect } from 'react';
export function useWindowDimension() {
const [dimension, setDimension] = useState([
window.innerWidth,
window.innerHeight,
]);
useEffect(() => {
const debouncedResizeHandler = debounce(() => {
console.log('***** debounced resize'); // See the cool difference in console
setDimension([window.innerWidth, window.innerHeight]);
}, 100); // 100ms
window.addEventListener('resize', debouncedResizeHandler);
return () => window.removeEventListener('resize', debouncedResizeHandler);
}, []); // Note this empty array. this effect should run only on mount and unmount
return dimension;
}
function debounce(fn, ms) {
let timer;
return _ => {
clearTimeout(timer);
timer = setTimeout(_ => {
timer = null;
fn.apply(this, arguments);
}, ms);
};
}
Use it like this.
function YourComponent() {
const [width, height] = useWindowDimension();
return <>Window width: {width}, Window height: {height}</>;
}
Testing for user agent is complex, messy and invariably fails. I also didn't find that the media match for "handheld" worked for me. The simplest solution was to detect if the mouse was available. And that can be done like this:
var result = window.matchMedia("(any-pointer:coarse)").matches;
That will tell you if you need to show hover items or not and anything else that requires a physical pointer. The sizing can then be done on further media queries based on width.
The following little library is a belt braces version of the query above, should cover most "are you a tablet or a phone with no mouse" scenarios.
https://patrickhlauke.github.io/touch/touchscreen-detection/
Media matches have been supported since 2015 and you can check the compatibility here: https://caniuse.com/#search=matchMedia
In short you should maintain variables relating to whether the screen is touch screen and also what size the screen is. In theory I could have a tiny screen on a mouse operated desktop.
There is not a system call to do it for you, unfortunately. I'm guessing that's because there isn't a way to have really well-defined semantics for what should happen in error cases. Should it leave the directories that have already been created? Delete them? What if the deletions fail? And so on...
It is pretty easy to roll your own, however, and a quick google for 'recursive mkdir' turned up a number of solutions. Here's one that was near the top:
http://nion.modprobe.de/blog/archives/357-Recursive-directory-creation.html
static void _mkdir(const char *dir) {
char tmp[256];
char *p = NULL;
size_t len;
snprintf(tmp, sizeof(tmp),"%s",dir);
len = strlen(tmp);
if(tmp[len - 1] == '/')
tmp[len - 1] = 0;
for(p = tmp + 1; *p; p++)
if(*p == '/') {
*p = 0;
mkdir(tmp, S_IRWXU);
*p = '/';
}
mkdir(tmp, S_IRWXU);
}
Agree with Subir Kumar Sao and Faiz.
element_enter.findElement(By.xpath("//html/body/div[1]/div[3]/div[1]/form/div/div/input")).sendKeys(barcode);
Hear it from the Horse's Mouth : APUE (Richard Stevens).
To the kernel, all open files are referred to by File Descriptors. A file descriptor is a non-negative number.
When we open an existing file or create a new file, the kernel returns a file descriptor to the process. The kernel maintains a table of all open file descriptors, which are in use. The allotment of file descriptors is generally sequential and they are allotted to the file as the next free file descriptor from the pool of free file descriptors. When we closes the file, the file descriptor gets freed and is available for further allotment.
See this image for more details :
When we want to read or write a file, we identify the file with the file descriptor that was returned by open() or create() function call, and use it as an argument to either read() or write().
It is by convention that, UNIX System shells associates the file descriptor 0 with Standard Input of a process, file descriptor 1 with Standard Output, and file descriptor 2 with Standard Error.
File descriptor ranges from 0 to OPEN_MAX. File descriptor max value can be obtained with ulimit -n
. For more information, go through 3rd chapter of APUE Book.
Nice solution by leocaseiro
<input class="ng-hide" id="input-file-id" multiple type="file" />
<label for="input-file-id" class="md-button md-raised md-primary">Choose Files</label>
View in codepen
I also met this problem when I've made ListView for android app:
Map<String, Object> m;
for(int i=0; i < dates.length; i++){
m = new HashMap<String, Object>();
m.put(ATTR_DATES, dates[i]);
m.put(ATTR_SQUATS, squats[i]);
m.put(ATTR_BP, benchpress[i]);
m.put(ATTR_ROW, row[i]);
data.add(m);
}
The problem was that I've forgotten to use the [i]
index inside the loop
Remove any capital letters or other not allowed symbols in resource file name.
Example: activity_parkingList --> activity_parking_list
Use fileOrBlob.text()
as follows:
<input type="file" onchange="this.files[0].text().then(t => console.log(t))">
When user uploads a text file via that input, it will be logged to the console. Here's a working jsbin demo.
Here's a more verbose version:
<input type="file" onchange="loadFile(this.files[0])">
<script>
async function loadFile(file) {
let text = await file.text();
console.log(text);
}
</script>
Currently (January 2020) this only works in Chrome and Firefox, check here for compatibility if you're reading this in the future: https://developer.mozilla.org/en-US/docs/Web/API/Blob/text
On older browsers, this should work:
<input type="file" onchange="loadFile(this.files[0])">
<script>
async function loadFile(file) {
let text = await (new Response(file)).text();
console.log(text);
}
</script>
Related: As of September 2020 the new Native File System API available in Chrome and Edge in case you want permanent read-access (and even write access) to the user-selected file.
I've found different compilers return different results on true. I've also found that one is almost always better off comparing a bool to a bool instead of an int. Those ints tend to change value over time as your program evolves and if you assume true as 1, you can get bitten by an unrelated change elsewhere in your code.
I have a similar case: wanting my *.jar
file to access a file in a directory next to said *.jar
file. Refer to THIS ANSWER as well.
My file structure is:
./ - the root of your program
|__ *.jar
|__ dir-next-to-jar/some.txt
I'm able to load a file (say, some.txt
) to an InputStream inside the *.jar
file with the following:
InputStream stream = null;
try{
stream = ThisClassName.class.getClass().getResourceAsStream("/dir-next-to-jar/some.txt");
}
catch(Exception e) {
System.out.print("error file to stream: ");
System.out.println(e.getMessage());
}
Then do whatever you will with the stream
For people who are using only Doctrine DBAL and not the Doctrine ORM, they will not be able to access the getQuery()
method because it doesn't exists. They need to do something like the following.
$qb = new QueryBuilder($conn);
$count = $qb->select("count(id)")->from($tableName)->execute()->fetchColumn(0);
Here's a groovy version based on Morten Christiansen's answer.
void waitForAjaxCallsToComplete() {
repeatUntil(
{ return getJavaScriptFunction(driver, "return (window.jQuery || {active : false}).active") },
"Ajax calls did not complete before timeout."
)
}
static void repeatUntil(Closure runUntilTrue, String errorMessage, int pollFrequencyMS = 250, int timeOutSeconds = 10) {
def today = new Date()
def end = today.time + timeOutSeconds
def complete = false;
while (today.time < end) {
if (runUntilTrue()) {
complete = true;
break;
}
sleep(pollFrequencyMS);
}
if (!complete)
throw new TimeoutException(errorMessage);
}
static String getJavaScriptFunction(WebDriver driver, String jsFunction) {
def jsDriver = driver as JavascriptExecutor
jsDriver.executeScript(jsFunction)
}
You must use the name of the subform control, not the name of the subform, though these are often the same:
Forms![MainForm]![subform control name Name].Form.Requery
Or, if you are on the main form:
Me.[subform control name Name].Form.Requery
More Info: http://www.mvps.org/access/forms/frm0031.htm
Joe Edel's answer to himself is actually the right approach to resolve the pivot problem.
Basically the idea is to list out the columns in the base table firstly, and then any number of options.value
from the joint option table. Just left join
the same option table multiple times in order to get all the options.
What needs to be done by the programming language is to build this query dynamically according to a list of options needs to be queried.
For me, it came down to the proxy_pass
location setting. I needed to change over to using the HTTPS protocol, and have a valid SSL certificate set up on the node server side of things. That way when I introduce an external node server, I only have to change the IP and everything else remains the same config.
I hope this helps someone along the way... I was staring at the problem the whole time... sigh...
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
upstream nodeserver {
server 127.0.0.1:8080;
}
server {
listen 443 default_server ssl http2;
listen [::]:443 default_server ssl http2 ipv6only=on;
server_name mysite.com;
ssl_certificate ssl/site.crt;
ssl_certificate_key ssl/site.key;
location /websocket { #replace /websocket with the path required by your application
proxy_pass https://nodeserver;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_http_version 1.1;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_intercept_errors on;
proxy_redirect off;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-NginX-Proxy true;
proxy_ssl_session_reuse off;
}
}
From what I understand of the scikit-image docs (http://scikit-image.org/docs/dev/index.html), imshow() takes a ndarray as an argument, and not a dictionary:
http://scikit-image.org/docs/dev/api/skimage.io.html?highlight=imshow#skimage.io.imshow
Maybe if you post the whole stack trace, we could see that the TypeError comes somewhere deep from imshow().
JSP is s presentation framework, and is generally not supposed to contain any program logic in it. As skaffman suggested, use pure servlets, or any MVC web framework in order to achieve what you want.
You don't need to convert your dates to timestamp before the sorting, but it's a good idea though because it will take more time to sort without it.
$data = array(
array(
"title" => "Another title",
"date" => "Fri, 17 Jun 2011 08:55:57 +0200"
),
array(
"title" => "My title",
"date" => "Mon, 16 Jun 2010 06:55:57 +0200"
)
);
function sortFunction( $a, $b ) {
return strtotime($a["date"]) - strtotime($b["date"]);
}
usort($data, "sortFunction");
var_dump($data);
Linq to sql has no support for Count(Distinct ...). You therefore have to map a .NET method in code onto a Sql server function (thus Count(distinct.. )) and use that.
btw, it doesn't help if you post pseudo code copied from a toolkit in a format that's neither VB.NET nor C#.
String.Trim()
returns a string which equals the input string with all white-spaces trimmed from start and end:
" A String ".Trim() -> "A String"
String.TrimStart()
returns a string with white-spaces trimmed from the start:
" A String ".TrimStart() -> "A String "
String.TrimEnd()
returns a string with white-spaces trimmed from the end:
" A String ".TrimEnd() -> " A String"
None of the methods modify the original string object.
(In some implementations at least, if there are no white-spaces to be trimmed, you get back the same string object you started with:
csharp> string a = "a";
csharp> string trimmed = a.Trim();
csharp> (object) a == (object) trimmed;
returns true
I don't know whether this is guaranteed by the language.)
If you don't want to assign identifier to the hidden field; you can use name or class with selector like:
$('input[name=hiddenfieldname]').val();
or with assigned class:
$('input.hiddenfieldclass').val();
Final working solution using @Arrigo response and @Samitha Chathuranga comment, I'll put all together to build a full response for this question:
Open Git CMD console and type command 1 from second picture(go to your project folder on your PC)
Type command git init
Type command git add --all
Type command 2 from second picture (git remote add origin YOUR_LINK_TO_REPO
)
Type command git commit -m "my first commit"
Type command git push -u origin master
Note: if you get error unable to detect email or name, just type following commands after 5th step:
git config --global user.email "yourEmail" #your email at Bitbucket
git config --global user.name "yourName" #your name at Bitbucket
Hope I've understood you correctly, take a look at this: http://jsfiddle.net/EAEKc/
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
<meta charset="UTF-8" />_x000D_
<title>Content with Menu</title>_x000D_
<style>_x000D_
.content .left {_x000D_
float: left;_x000D_
width: 100px;_x000D_
background-color: green;_x000D_
}_x000D_
_x000D_
.content .right {_x000D_
margin-left: 100px;_x000D_
background-color: red;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div class="content">_x000D_
<div class="left">_x000D_
<p>Hi, Flo!</p>_x000D_
</div>_x000D_
<div class="right">_x000D_
<p>is</p>_x000D_
<p>this</p>_x000D_
<p>what</p>_x000D_
<p>you are looking for?</p>_x000D_
</div>_x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
You could use a variable to make the calculation and use toFixed
when you set the #diskamountUnit
element value:
var amount = $("#disk").slider("value") * 1.60;
$("#diskamountUnit").val('$' + amount.toFixed(2));
You can also do that in one step, in the val
method call but IMO the first way is more readable:
$("#diskamountUnit").val('$' + ($("#disk").slider("value") * 1.60).toFixed(2));
I am not much of a coder nor an expert in CSS, but I am still using your idea in my web designs. I have tried different resolutions too:
#wrapper {_x000D_
margin: 0 auto;_x000D_
width: 901px;_x000D_
height: 100%;_x000D_
background-color: #f7f7f7;_x000D_
background-image: url(images/wrapperback.gif);_x000D_
color: #000;_x000D_
}_x000D_
#header {_x000D_
float: left;_x000D_
width: 100.00%;_x000D_
height: 122px;_x000D_
background-color: #00314e;_x000D_
background-image: url(images/header.jpg);_x000D_
color: #fff;_x000D_
}_x000D_
#menu {_x000D_
float: left;_x000D_
padding-top: 20px;_x000D_
margin-left: 495px;_x000D_
width: 390px;_x000D_
color: #f1f1f1;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
<div id="header">_x000D_
<div id="menu">_x000D_
menu will go here_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Of course there will be a wrapper around both of them. You can control the location of the menu div which will be displayed within the header div with left margins and top positions. You can also set the div menu to float right if you like.
I am adding this solution for completeness and showing how to work with section headers.
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var tableView: UITableView!
var headerButtons: [UIButton]!
var sections = [true, true, true]
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
let section0Button = UIButton(type: .detailDisclosure)
section0Button.setTitle("Section 0", for: .normal)
section0Button.addTarget(self, action: #selector(section0Tapped), for: .touchUpInside)
let section1Button = UIButton(type: .detailDisclosure)
section1Button.setTitle("Section 1", for: .normal)
section1Button.addTarget(self, action: #selector(section1Tapped), for: .touchUpInside)
let section2Button = UIButton(type: .detailDisclosure)
section2Button.setTitle("Section 2", for: .normal)
section2Button.addTarget(self, action: #selector(section2Tapped), for: .touchUpInside)
headerButtons = [UIButton]()
headerButtons.append(section0Button)
headerButtons.append(section1Button)
headerButtons.append(section2Button)
}
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section] ? 3 : 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellReuseId = "cellReuseId"
let cell = UITableViewCell(style: .default, reuseIdentifier: cellReuseId)
cell.textLabel?.text = "\(indexPath.section): \(indexPath.row)"
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return headerButtons[section]
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 44
}
@objc func section0Tapped() {
sections[0] = !sections[0]
tableView.reloadSections([0], with: .fade)
}
@objc func section1Tapped() {
sections[1] = !sections[1]
tableView.reloadSections([1], with: .fade)
}
@objc func section2Tapped() {
sections[2] = !sections[2]
tableView.reloadSections([2], with: .fade)
}
}
Link to gist: https://gist.github.com/pawelkijowskizimperium/fe1e8511a7932a0d40486a2669316d2c
If you don't need VML and IE8 support then use Canvas (PaperJS for example). Look at latest IE10 demos for Windows 7. They have amazing animations in Canvas. SVG is not capable to do anything close to them. Overall Canvas is available at all mobile browsers. SVG is not working at early versions of Android 2.0- 2.3 (as I know)
Yes, Canvas is not scalable, but it so fast that you can redraw the whole canvas faster then browser capable to scroll view port.
From my perspective Microsoft's optimizations provides means to use Canvas as regular GDI engine and implement graphics applications like we do them for Windows now.
First you to add a class then remove id
<script type="text/javascript">
$(document).ready(function(){
$("#page_navigation1").addClass("page_navigation");
$("#add").click(function(){
$(".page_navigation").attr("id","page_navigation1");
});
$("#remove").click(function(){
$(".page_navigation").removeAttr("id");
});
});
</script>
Events can be tested using the async
/fakeAsync
functions provided by '@angular/core/testing'
, since any event in the browser is asynchronous and pushed to the event loop/queue.
Below is a very basic example to test the click event using fakeAsync
.
The fakeAsync
function enables a linear coding style by running the test body in a special fakeAsync
test zone.
Here I am testing a method that is invoked by the click event.
it('should', fakeAsync( () => {
fixture.detectChanges();
spyOn(componentInstance, 'method name'); //method attached to the click.
let btn = fixture.debugElement.query(By.css('button'));
btn.triggerEventHandler('click', null);
tick(); // simulates the passage of time until all pending asynchronous activities finish
fixture.detectChanges();
expect(componentInstance.methodName).toHaveBeenCalled();
}));
Below is what Angular docs have to say:
The principle advantage of fakeAsync over async is that the test appears to be synchronous. There is no
then(...)
to disrupt the visible flow of control. The promise-returningfixture.whenStable
is gone, replaced bytick()
There are limitations. For example, you cannot make an XHR call from within a
fakeAsync
Often when people are looking for "timezones", what will suffice is just "UTC offset". e.g., their server is in UTC+5 and they want to know that their client is running in UTC-8.
In plain old javascript (new Date()).getTimezoneOffset()/60
will return the current number of hours offset from UTC.
It's worth noting a possible "gotcha" in the sign of the getTimezoneOffset()
return value (from MDN docs):
The time-zone offset is the difference, in minutes, between UTC and local time. Note that this means that the offset is positive if the local timezone is behind UTC and negative if it is ahead. For example, for time zone UTC+10:00 (Australian Eastern Standard Time, Vladivostok Time, Chamorro Standard Time), -600 will be returned.
However, I recommend you use the day.js for time/date related Javascript code. In which case you can get an ISO 8601 formatted UTC offset by running:
> dayjs().format("Z")
"-08:00"
It probably bears mentioning that the client can easily falsify this information.
(Note: this answer originally recommended https://momentjs.com/, but dayjs is a more modern, smaller alternative.)
Basically a variant on Matthew Marshall's answer (with struct from the std.library):
import struct
print struct.calcsize("P") * 8
You can use this:
bankHoliday= [1, 0, 1, 1, 2, 0, 0, 1, 0, 0, 0, 2] #gives the list of bank holidays in each month
def bank_holiday(month):
month -= 1#Takes away the numbers from the months, as months start at 1 (January) not at 0. There is no 0 month.
print(bankHoliday[month])
bank_holiday(int(input("Which month would you like to check out: ")))
Your question 1 has been already extensively discussed in several excellent answers here.
I thought to share with you a few lines of code that allow you to compute the autocorrelation of a signal based only on the mathematical properties of the autocorrelation. That is, the autocorrelation may be computed in the following way:
subtract the mean from the signal and obtain an unbiased signal
compute the Fourier transform of the unbiased signal
compute the power spectral density of the signal, by taking the square norm of each value of the Fourier transform of the unbiased signal
compute the inverse Fourier transform of the power spectral density
normalize the inverse Fourier transform of the power spectral density by the sum of the squares of the unbiased signal, and take only half of the resulting vector
The code to do this is the following:
def autocorrelation (x) :
"""
Compute the autocorrelation of the signal, based on the properties of the
power spectral density of the signal.
"""
xp = x-np.mean(x)
f = np.fft.fft(xp)
p = np.array([np.real(v)**2+np.imag(v)**2 for v in f])
pi = np.fft.ifft(p)
return np.real(pi)[:x.size/2]/np.sum(xp**2)
Have done a number of comparisons between left outer and inner joins and have not been able to find a consisten difference. There are many variables. Am working on a reporting database with thousands of tables many with a large number of fields, many changes over time (vendor versions and local workflow) . It is not possible to create all of the combinations of covering indexes to meet the needs of such a wide variety of queries and handle historical data. Have seen inner queries kill server performance because two large (millions to tens of millions of rows) tables are inner joined both pulling a large number of fields and no covering index exists.
The biggest issue though, doesn't seem to appeaer in the discussions above. Maybe your database is well designed with triggers and well designed transaction processing to ensure good data. Mine frequently has NULL values where they aren't expected. Yes the table definitions could enforce no-Nulls but that isn't an option in my environment.
So the question is... do you design your query only for speed, a higher priority for transaction processing that runs the same code thousands of times a minute. Or do you go for accuracy that a left outer join will provide. Remember that inner joins must find matches on both sides, so an unexpected NULL will not only remove data from the two tables but possibly entire rows of information. And it happens so nicely, no error messages.
You can be very fast as getting 90% of the needed data and not discover the inner joins have silently removed information. Sometimes inner joins can be faster, but I don't believe anyone making that assumption unless they have reviewed the execution plan. Speed is important, but accuracy is more important.
As of today (2015, Aug., 1st), Apache2
in Debian Jessie
, you need to edit:
root@host:/etc/apache2/mods-enabled$ vi dir.conf
And change the order of that line, bringing index.php to the first position:
DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm
$("#closeLink").click(closeIt);
Let's say you want to call your function passing some args to it i.e., closeIt(1, false)
. Then, you should build an anonymous function and call closeIt
from it.
$("#closeLink").click(function() {
closeIt(1, false);
});
I wanted a solution that did not create any extra objects (ie listeners) that would have to be garbage collected later, and did not require nesting a view holder inside an adapter class.
In the ViewHolder
class
private static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private final TextView ....// declare the fields in your view
private ClickHandler ClickHandler;
public MyHolder(final View itemView) {
super(itemView);
nameField = (TextView) itemView.findViewById(R.id.name);
//find other fields here...
Button myButton = (Button) itemView.findViewById(R.id.my_button);
myButton.setOnClickListener(this);
}
...
@Override
public void onClick(final View view) {
if (clickHandler != null) {
clickHandler.onMyButtonClicked(getAdapterPosition());
}
}
Points to note: the ClickHandler
interface is defined, but not initialized here, so there is no assumption in the onClick
method that it was ever initialized.
The ClickHandler
interface looks like this:
private interface ClickHandler {
void onMyButtonClicked(final int position);
}
In the adapter, set an instance of 'ClickHandler' in the constructor, and override onBindViewHolder
, to initialize `clickHandler' on the view holder:
private class MyAdapter extends ...{
private final ClickHandler clickHandler;
public MyAdapter(final ClickHandler clickHandler) {
super(...);
this.clickHandler = clickHandler;
}
@Override
public void onBindViewHolder(final MyViewHolder viewHolder, final int position) {
super.onBindViewHolder(viewHolder, position);
viewHolder.clickHandler = this.clickHandler;
}
Note: I know that viewHolder.clickHandler is potentially getting set multiple times with the exact same value, but this is cheaper than checking for null and branching, and there is no memory cost, just an extra instruction.
Finally, when you create the adapter, you are forced to pass a ClickHandler
instance to the constructor, as so:
adapter = new MyAdapter(new ClickHandler() {
@Override
public void onMyButtonClicked(final int position) {
final MyModel model = adapter.getItem(position);
//do something with the model where the button was clicked
}
});
Note that adapter
is a member variable here, not a local variable
One way is to use ANSI escape sequences:
import sys
import time
for i in range(10):
print("Loading" + "." * i)
sys.stdout.write("\033[F") # Cursor up one line
time.sleep(1)
Also sometimes useful (for example if you print something shorter than before):
sys.stdout.write("\033[K") # Clear to the end of line
Wikipedia explains both reasonably well: UTF-8 vs Latin-1 (ISO-8859-1). Former is a variable-length encoding, latter single-byte fixed length encoding. Latin-1 encodes just the first 256 code points of the Unicode character set, whereas UTF-8 can be used to encode all code points. At physical encoding level, only codepoints 0 - 127 get encoded identically; code points 128 - 255 differ by becoming 2-byte sequence with UTF-8 whereas they are single bytes with Latin-1.
If you are in API level 21 or above you can use these XML attributes:
<!-- For indeterminate progress bar -->
android:indeterminateTint="@color/white"
<!-- For normal progress bar -->
android:progressTint="@color/white"
The readr package will fix this issue.
install.packages('readr')
library(readr)
readr::read_csv('yourfile.csv')
Some x86 instructions are designed to leave the content of the operands (registers) as they are and just set/unset specific internal CPU flags like the zero-flag (ZF). You can think at the ZF as a true/false boolean flag that resides inside the CPU.
in this particular case, TEST instruction performs a bitwise logical AND, discards the actual result and sets/unsets the ZF according to the result of the logical and: if the result is zero it sets ZF = 1, otherwise it sets ZF = 0.
Conditional jump instructions like JE are designed to look at the ZF for jumping/notjumping so using TEST and JE together is equivalent to perform a conditional jump based on the value of a specific register:
example:
TEST EAX,EAX
JE some_address
the CPU will jump to "some_address" if and only if ZF = 1, in other words if and only if AND(EAX,EAX) = 0 which in turn it can occur if and only if EAX == 0
the equivalent C code is:
if(eax == 0)
{
goto some_address
}
See Getting BLOB data from XHR request which points out that BlobBuilder doesn't work in Chrome so you need to use:
xhr.responseType = 'arraybuffer';
Mini John's answer totally worked for me! Awesome... had to add
--region eu-west-1
from Europe though
React Router v4
There's a couple of things that I needed to get this working smoothly.
The doc page on auth workflow has quite a lot of what is required.
However I had three issues
props.history
come from?Route
componentprops
?I ended up using:
<Route render>
which gets you props.history
which can then be passed down to the children.render={routeProps => <MyComponent {...props} {routeProps} />}
to combine other props
from this answer on 'react-router - pass props to handler component'N.B. With the render
method you have to pass through the props from the Route
component explicitly. You also want to use render
and not component
for performance reasons (component
forces a reload every time).
const App = (props) => (
<Route
path="/home"
render={routeProps => <MyComponent {...props} {...routeProps}>}
/>
)
const MyComponent = (props) => (
/**
* @link https://reacttraining.com/react-router/web/example/auth-workflow
* N.B. I use `props.history` instead of `history`
*/
<button onClick={() => {
fakeAuth.signout(() => props.history.push('/foo'))
}}>Sign out</button>
)
One of the confusing things I found is that in quite a few of the React Router v4 docs they use MyComponent = ({ match })
i.e. Object destructuring, which meant initially I didn't realise that Route
passes down three props, match
, location
and history
I think some of the other answers here are assuming that everything is done via JavaScript classes.
Here's an example, plus if you don't need to pass any props
through you can just use component
class App extends React.Component {
render () {
<Route
path="/home"
component={MyComponent}
/>
}
}
class MyComponent extends React.Component {
render () {
/**
* @link https://reacttraining.com/react-router/web/example/auth-workflow
* N.B. I use `props.history` instead of `history`
*/
<button onClick={() => {
this.fakeAuth.signout(() => this.props.history.push('/foo'))
}}>Sign out</button>
}
}
roenving is correct BUT you need to change the test to:
if(element.nodeType == 1) { //code }
because nodeType of 3 is actually a text node and nodeType of 1 is an HTML element. See http://www.w3schools.com/Dom/dom_nodetype.asp
According to comments: netcfg was removed in Android 6
Try
adb shell netcfg
Or
adb shell <device here or leave out if one device>
shell@android:/ $netcfg