A few steps you have to follow:
This works for me...
For my project, what solved the issue was that Chrome browser and chromedriver were not compatibles. I had a very old version of the driver that could not even open the browser. I just downloaded the latest version of both and problem solved. How did I discovered the issue? Because I ran my project using the Selenium native firefox driver with an old version of FF inculded with my application, I realized then that the problem was incompatibility of between browser and driver.
Hope this can help anyone with a similiar issue as mine, that generated this same Error Message.
Add the following dependency to your pom.xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.2</version>
</dependency>
This is the long form of the Java commands that can be run from a Windows command prompt:
"C:\Program Files\Java\jdk1.6.0_18\bin\javac.exe" -classpath "C:\Users\Scott\workspace\myproject" com\mycompany\myapp\HelloWorld.java
"C:\Program Files\Java\jdk1.6.0_18\bin\java.exe" -classpath "C:\Users\Scott\workspace\myproject" com.mycompany.myapp.HelloWorld
Notice the classpath has no slash at the end. The javac.exe commands expects the file to end with ".java". The java.exe command expects the full class name and does not end with ".class".
There are a few ways to simplify these commands:
You don't have to enter the entire classpath (ie, you can just use -classpath "."). Enter the directory you will be working in:
cd "C:\Users\Scott\workspace\myproject\"
You can use the default package (put the HelloWorld.java file directory in your working directory and don't use the Java package directive)
If you make these changes you would run something like this (and you might be able to leave out -classpath "."):
cd "C:\Users\Scott\workspace\myproject\"
javac -classpath "." HelloWorld.java
java -classpath "." HelloWorld
A ClassNotFoundException is thrown when the reported class is not found by the ClassLoader. This typically means that the class is missing from the CLASSPATH. It could also mean that the class in question is trying to be loaded from another class which was loaded in a parent classloader and hence the class from the child classloader is not visible. This is sometimes the case when working in more complex environments like an App Server (WebSphere is infamous for such classloader issues).
People often tend to confuse java.lang.NoClassDefFoundError
with java.lang.ClassNotFoundException
however there's an important distinction. For example an exception (an error really since java.lang.NoClassDefFoundError
is a subclass of java.lang.Error) like
java.lang.NoClassDefFoundError:
org/apache/activemq/ActiveMQConnectionFactory
does not mean that the ActiveMQConnectionFactory class is not in the CLASSPATH. Infact its quite the opposite. It means that the class ActiveMQConnectionFactory was found by the ClassLoader however when trying to load the class, it ran into an error reading the class definition. This typically happens when the class in question has static blocks or members which use a Class that's not found by the ClassLoader. So to find the culprit, view the source of the class in question (ActiveMQConnectionFactory in this case) and look for code using static blocks or static members. If you don't have access the the source, then simply decompile it using JAD.
On examining the code, say you find a line of code like below, make sure that the class SomeClass in in your CLASSPATH.
private static SomeClass foo = new SomeClass();
Tip : To find out which jar a class belongs to, you can use the web site jarFinder . This allows you to specify a class name using wildcards and it searches for the class in its database of jars. jarhoo allows you to do the same thing but its no longer free to use.
If you would like to locate the which jar a class belongs to in a local path, you can use a utility like jarscan ( http://www.inetfeedback.com/jarscan/ ). You just specify the class you'd like to locate and the root directory path where you'd like it to start searching for the class in jars and zip files.
Try going to Project -> Properties -> Java Build Path -> Order & Export
And Confirm Android Private Libraries are checked for your project and for all other library projects you are using in your Application.
In my case, I was trying to add a normal java class (from a normal java project) compiled with jre 1.7 to an android app project compiled with jre 1.7.
The solution was to recompile that normal java class with jre 1.6 and add references to the android app project (compiled with jre 1.6 also) as usual (in tab order and export be sure to check the class, project, etc).
The same process, when using an android library to reference external normal java classes.
Don't know what's wrong with jre 1.7, when compiling normal java classes from a normal java project and try to reference them in android app or android library projects.
If you don't use normal java classes (from a normal java project) you don't need to downgrade to jre 1.6.
I got the same problem and just Installed Play Services from SDK and all problems fly away.
You just download commons-logging-1.1.2.jar and then copy this file in to libs
finally, it works.
This error can be caused by unchecked Java version requirements.
In my case I was able to resolve this error, while building a high-profile open-source project, by switching from Java 9 to Java 8 using SDKMAN!.
sdk list java
sdk install java 8u152-zulu
sdk use java 8u152-zulu
Then doing a clean install as described below.
When using Maven as your build tool, it is sometimes helpful -- and usually gratifying, to do a clean 'install' build with testing disabled.
mvn clean install -DskipTests
Now that everything has been built and installed, you can go ahead and run the tests.
mvn test
Search here for centos jre install all users:
The easiest way to set an environment variable in CentOS is to use export as in
$> export JAVA_HOME=/usr/java/jdk.1.5.0_12
$> export PATH=$PATH:$JAVA_HOME
However, variables set in such a manner are transient i.e. they will disappear the moment you exit the shell. Obviously this is not helpful when setting environment variables that need to persist even when the system reboots.
In such cases, you need to set the variables within the system wide profile. In CentOS (I’m using v5.2), the folder /etc/profile.d/ is the recommended place to add customizations to the system profile.
For example, when installing the Sun JDK, you might need to set the JAVA_HOME and JRE_HOME environment variables. In this case:
Create a new file called java.sh
vim /etc/profile.d/java.sh
Within this file, initialize the necessary environment variables
export JRE_HOME=/usr/java/jdk1.5.0_12/jre
export PATH=$PATH:$JRE_HOME/bin
export JAVA_HOME=/usr/java/jdk1.5.0_12
export JAVA_PATH=$JAVA_HOME
export PATH=$PATH:$JAVA_HOME/bin
Now when you restart your machine, the environment variables within java.sh will be automatically initialized (checkout /etc/profile if you are curious how the files in /etc/profile.d/ are loaded).
PS: If you want to load the environment variables within java.sh
without having to restart the machine, you can use the source command as in:
$> source java.sh
As mentioned above, this could be a number of things. In my case I had a statically initialized variable which relied on a missing entry in my properties file. Added the missing entry to the properties file and the problem was solved.
If you have more than one version of java, it may interfere with your program.
I suggest you download JCreator.
When you do, click configure, options, and JDK Profiles. Delete the old versions of Java from the list. Then click the play button. Your program should appear.
If it doesn't, press ctrl+alt+O and then press the play button again.
Run from terminal
# google-chrome --no-sandbox --user-data-dir
or
Open the file opt/google/chrome/google-chrome and replace
exec -a "$0" "$HERE/chrome" "$@"
to
exec -a "$0" "$HERE/chrome" "$@" --user-data-dir --no-sandbox
It's working for chrome version 49 in CentOS 6. Chrome will give warning also.
Your list:
List<MyCustomObject> myCustomObjectList;
Your JSONArray:
// Don't need to loop through it. JSONArray constructor do it for you.
new JSONArray(myCustomObjectList)
Your response:
return new JSONObject().put("yourCustomKey", new JSONArray(myCustomObjectList));
Your post/put http body request would be like this:
{
"yourCustomKey: [
{
"myCustomObjectProperty": 1
},
{
"myCustomObjectProperty": 2
}
]
}
In my case, this was caused by custom manifest entries added by the maven-jar-plugin.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.6</version>
<configuration>
<archive>
<index>true</index>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
<manifestEntries>
<git>${buildNumber}</git>
<build-time>${timestamp}</build-time>
</manifestEntries>
</archive>
</configuration>
</plugin>
Removing the following entries fixed the problem
<index>true</index>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
Vue by default ships with the v-html directive to show it, you bind it onto the element itself rather than using the normal moustache binding for string variables.
So for your specific example you would need:
<div id="logapp">
<table>
<tbody>
<tr v-repeat="logs">
<td v-html="fail"></td>
<td v-html="type"></td>
<td v-html="description"></td>
<td v-html="stamp"></td>
<td v-html="id"></td>
</tr>
</tbody>
</table>
</div>
In special cases where you want to find whether a word is contained in a long text, you can iterate through the long text with a loop.
found=F
query_word=this
long_string="many many words in this text"
for w in $long_string; do
if [ "$w" = "$query_word" ]; then
found=T
break
fi
done
This is pure Bourne shell.
function isMobileDev(){
if(isset($_SERVER['HTTP_USER_AGENT']) and !empty($_SERVER['HTTP_USER_AGENT'])){
$user_ag = $_SERVER['HTTP_USER_AGENT'];
if(preg_match('/(Mobile|Android|Tablet|GoBrowser|[0-9]x[0-9]*|uZardWeb\/|Mini|Doris\/|Skyfire\/|iPhone|Fennec\/|Maemo|Iris\/|CLDC\-|Mobi\/)/uis',$user_ag)){
return true;
};
};
return false;
}
Each one is a different type execution.
ExecuteScalar is going to be the type of query which will be returning a single value.
An example would be returning a generated id after inserting.
INSERT INTO my_profile (Address) VALUES ('123 Fake St.');
SELECT CAST(scope_identity() AS int)
ExecuteReader gives you a data reader back which will allow you to read all of the columns of the results a row at a time.
An example would be pulling profile information for one or more users.
SELECT * FROM my_profile WHERE id = '123456'
ExecuteNonQuery is any SQL which isn't returning values, but is actually performing some form of work like inserting deleting or modifying something.
An example would be updating a user's profile in the database.
UPDATE my_profile SET Address = '123 Fake St.' WHERE id = '123456'
Sigh. Back in the 70s I was the "system programmer" (sysadmin) for an IBM 370 system, and my employer was a member of the IBM users group SHARE. It would sometimes happen thatsomebody submitted an APAR (bug report) on some unexpected behavior of some CMS command, and IBM would respond NOTABUG: the command does what it was designed to do (and what the documentation says).
SHARE came up with a counter to this: BAD -- Broken As Designed. I think this might apply to this implementation of equals for arrays.
There's nothing wrong with the implementation of Object.equals. Object has no data members, so there is nothing to compare. Two "Object"s are equal if and only if they are, in fact, the same Object (internally, the same address and length).
But that logic doesn't apply to arrays. Arrays have data, and you expect comparison (via equals) to compare the data. Ideally, the way Arrays.deepEquals does, but at least the way Arrays.equals does (shallow comparison of the elements).
So the problem is that array (as a built-in object) does not override Object.equals. String (as a named class) does override Object.equals and give the result you expect.
Other answers given are correct: [...].equals([....]) simply compares the pointers and not the contents. Maybe someday somebody will correct this. Or maybe not: how many existing programs would break if [...].equals actually compared the elements? Not many, I suspect, but more than zero.
you can make a jQuery onChange event to get the text from the combobox when the user select one of them:
<script>
$( "select" )
.change(function () {
var str = "";
$( "select option:selected" ).each(function() {
str += $( this ).text() + " ";
});
$('#EvaluationName').val(str);
})
.change();
</script>
When you select an option, it will save the text in an Input hidde
<input type="hidden" id="EvaluationName" name="EvaluationName" value="<?= $Evaluation ?>" />
After that, when you submit the form, just catch up the value of the input
$Evaluation = $_REQUEST['EvaluationName'];
Then you can do wathever you want with the text, for instance save it in a session variable and send it to other page. etc.
You could also stick something like this in the bottom of your SVG (right before the closing </svg>
tag):
<a xmlns="http://www.w3.org/2000/svg" id="anchor" xlink:href="/" xmlns:xlink="http://www.w3.org/1999/xlink" target="_top">
<rect x="0" y="0" width="100%" height="100%" fill-opacity="0"/>
</a>
Then just amend the link to suit. I have used 100% width and height to cover the SVG it sits in. Credit for the technique goes to the smart folks at Clearleft.com - that's where I first saw it used.
Make your object something like
public class MyObject : IComparable
{
public string a;
public string b;
virtual public int CompareTo(object obj)
{
if (obj is MyObject)
{
var compareObj = (MyObject)obj;
if (this.a.CompareTo(compareObj.a) == 0)
{
// compare second value
return this.b.CompareTo(compareObj.b);
}
return this.a.CompareTo(compareObj.b);
}
else
{
throw new ArgumentException("Object is not a MyObject ");
}
}
}
also note that the returns for CompareTo :
http://msdn.microsoft.com/en-us/library/system.icomparable.compareto.aspx
Then, if you have a List of MyObject, call .Sort() ie
var objList = new List<MyObject>();
objList.Sort();
Use jenv is an easy way.
1.Install jenv
curl -s get.jenv.io | bash
2.Config jenv
cd ~/.jenv/candidates/
mkdir java
cd java
mkdir 1.7
mkdir 1.8
3.Symlink the jdk path
ln -s /Library/Java/JavaVirtualMachines/jdk1.7.0_79.jdk/Contents/Home/bin ~/.jenv/candidates/java/1.7
ln -s /Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/bin ~/.jenv/candidates/java/1.8
4.You are all set
switch command:
jenv use java 1.8
set default:
jenv default java 1.7
At first glance your original attempt seems pretty close. I'm assuming that clockDate is a DateTime fields so try this:
IF (NOT EXISTS(SELECT * FROM Clock WHERE cast(clockDate as date) = '08/10/2012')
AND userName = 'test')
BEGIN
INSERT INTO Clock(clockDate, userName, breakOut)
VALUES(GetDate(), 'test', GetDate())
END
ELSE
BEGIN
UPDATE Clock
SET breakOut = GetDate()
WHERE Cast(clockDate AS Date) = '08/10/2012' AND userName = 'test'
END
Note that getdate gives you the current date. If you are trying to compare to a date (without the time) you need to cast or the time element will cause the compare to fail.
If clockDate is NOT datetime field (just date), then the SQL engine will do it for you - no need to cast on a set/insert statement.
IF (NOT EXISTS(SELECT * FROM Clock WHERE clockDate = '08/10/2012')
AND userName = 'test')
BEGIN
INSERT INTO Clock(clockDate, userName, breakOut)
VALUES(GetDate(), 'test', GetDate())
END
ELSE
BEGIN
UPDATE Clock
SET breakOut = GetDate()
WHERE clockDate = '08/10/2012' AND userName = 'test'
END
As others have pointed out, the merge statement is another way to tackle this same logic. However, in some cases, especially with large data sets, the merge statement can be prohibitively slow, causing a lot of tran log activity. So knowing how to logic it out as shown above is still a valid technique.
POCOs(Plain old CLR objects) are simply entities of your Domain. Normally when we use entity framework the entities are generated automatically for you. This is great but unfortunately these entities are interspersed with database access functionality which is clearly against the SOC (Separation of concern). POCOs are simple entities without any data access functionality but still gives the capabilities all EntityObject functionalities like
Here is a good start for this
You can also generate POCOs so easily from your existing Entity framework project using Code generators.
These messages are rather misleading and understandably a source of confusion. Older Ubuntu versions used Libav which is a fork of the FFmpeg project. FFmpeg returned in Ubuntu 15.04 "Vivid Vervet".
The fork was basically a non-amicable result of conflicting personalities and development styles within the FFmpeg community. It is worth noting that the maintainer for Debian/Ubuntu switched from FFmpeg to Libav on his own accord due to being involved with the Libav fork.
ffmpeg
vs the fake oneFor a while both Libav and FFmpeg separately developed their own version of ffmpeg
.
Libav then renamed their bizarro ffmpeg
to avconv
to distance themselves from the FFmpeg project. During the transition period the "not developed anymore" message was displayed to tell users to start using avconv
instead of their counterfeit version of ffmpeg
. This confused users into thinking that FFmpeg (the project) is dead, which is not true. A bad choice of words, but I can't imagine Libav not expecting such a response by general users.
This message was removed upstream when the fake "ffmpeg
" was finally removed from the Libav source, but, depending on your version, it can still show up in Ubuntu because the Libav source Ubuntu uses is from the ffmpeg-to-avconv transition period.
In June 2012, the message was re-worded for the package libav - 4:0.8.3-0ubuntu0.12.04.1
. Unfortunately the new "deprecated" message has caused additional user confusion.
Starting with Ubuntu 15.04 "Vivid Vervet", FFmpeg's ffmpeg
is back in the repositories again.
To further complicate matters, Libav chose a name that was historically used by FFmpeg to refer to its libraries (libavcodec, libavformat, etc). For example the libav-user mailing list, for questions and discussions about using the FFmpeg libraries, is unrelated to the Libav project.
If you are using avconv
then you are using Libav. If you are using ffmpeg
you could be using FFmpeg or Libav. Refer to the first line in the console output to tell the difference: the copyright notice will either mention FFmpeg or Libav.
Secondly, the version numbering schemes differ. Each of the FFmpeg or Libav libraries contains a version.h
header which shows a version number. FFmpeg will end in three digits, such as 57.67.100, and Libav will end in one digit such as 57.67.0. You can also view the library version numbers by running ffmpeg
or avconv
and viewing the console output.
ffmpeg
The real ffmpeg
is in the repository, so you can install it with:
apt-get install ffmpeg
Your options are:
ffmpeg
,ffmpeg
,These methods are non-intrusive, reversible, and will not interfere with the system or any repository packages.
Another possible option is to upgrade to Ubuntu 15.04 "Vivid Vervet" or newer and just use ffmpeg
from the repository.
For an interesting blog article on the situation, as well as a discussion about the main technical differences between the projects, see The FFmpeg/Libav situation.
You can use Simpsons rule or the Trapezium rule to calculate the area under a graph given a table of y-values at a regular interval.
Python script that calculates Simpsons rule:
def integrate(y_vals, h):
i = 1
total = y_vals[0] + y_vals[-1]
for y in y_vals[1:-1]:
if i % 2 == 0:
total += 2 * y
else:
total += 4 * y
i += 1
return total * (h / 3.0)
h
is the offset (or gap) between y values, and y_vals
is an array of well, y values.
Example (In same file as above function):
y_values = [13, 45.3, 12, 1, 476, 0]
interval = 1.2
area = integrate(y_values, interval)
print("The area is", area)
File
> Import
> General
> Existing Projects into workspace
.
Select the root folder that has your project(s). It lists all the projects available in the selected folder. Select the ones you would like to import and click Finish
. This should work just fine.
The key is already the ... ehm ... key
echo $array[20120504];
If you are unsure, if the key exists, test for it
$key = 20120504;
$result = isset($array[$key]) ? $array[$key] : null;
Minor addition:
$result = @$array[$key] ?: null;
One may argue, that @
is bad, but keep it serious: This is more readable and straight forward, isn't?
Update: With PHP7 my previous example is possible without the error-silencer
$result = $array[$key] ?? null;
Here are some more console logging "pro tips":
console.table
var animals = [
{ animal: 'Horse', name: 'Henry', age: 43 },
{ animal: 'Dog', name: 'Fred', age: 13 },
{ animal: 'Cat', name: 'Frodo', age: 18 }
];
console.table(animals);
console.trace
Shows you the call stack for leading up to the console.
You can even customise your consoles to make them stand out
console.todo = function(msg) {
console.log(‘ % c % s % s % s‘, ‘color: yellow; background - color: black;’, ‘–‘, msg, ‘–‘);
}
console.important = function(msg) {
console.log(‘ % c % s % s % s’, ‘color: brown; font - weight: bold; text - decoration: underline;’, ‘–‘, msg, ‘–‘);
}
console.todo(“This is something that’ s need to be fixed”);
console.important(‘This is an important message’);
If you really want to level up don't limit your self to the console statement.
Here is a great post on how you can integrate a chrome debugger right into your code editor!
https://hackernoon.com/debugging-react-like-a-champ-with-vscode-66281760037
Here's my version:
/* Convert a hex char digit to its integer value. */
int hexDigitToInt(char digit) {
digit = tolower(digit);
if ('0' <= digit && digit <= '9') //if it's decimal
return (int)(digit - '0');
else if ('a' <= digit && digit <= 'f') //if it's abcdef
return (int)(digit - ('a' - 10));
else
return -1; //value not in [0-9][a-f] range
}
/* Decode a hex string. */
char *decodeHexString(const char *hexStr) {
char* decoded = malloc(strlen(hexStr)/2+1);
char* hexStrPtr = (char *)hexStr;
char* decodedPtr = decoded;
while (*hexStrPtr != '\0') { /* Step through hexStr, two chars at a time. */
*decodedPtr = 16 * hexDigitToInt(*hexStrPtr) + hexDigitToInt(*(hexStrPtr+1));
hexStrPtr += 2;
decodedPtr++;
}
*decodedPtr = '\0'; /* final null char */
return decoded;
}
You can't do this without some browser specific code, since they implement text select ranged slightly differently. However, there are plugins that abstract this away. For exactly what you're after, there's the jQuery Caret (jCaret) plugin.
For your code to get the position you could do something like this:
$("#myTextInput").bind("keydown keypress mousemove", function() {
alert("Current position: " + $(this).caret().start);
});
If you don't want to use LINQ
// Get the files
DirectoryInfo info = new DirectoryInfo("path/to/files"));
FileInfo[] files = info.GetFiles();
// Sort by creation-time descending
Array.Sort(files, delegate(FileInfo f1, FileInfo f2)
{
return f2.CreationTime.CompareTo(f1.CreationTime);
});
No way to do that other than validate file extension with JavaScript when input path is populated by the file picker. To implement anything fancier you need to write your own component for whichever browser you want (activeX or XUL)
There's an "accept" attribute in HTML4.01 but I'm not aware of any browser supporting it - e.g. accept="image/gif,image/jpeg
- so it's a neat but impractical spec
Check out the "encoding/binary" package. Particularly the Read and Write functions:
binary.Write(a, binary.LittleEndian, myInt)
A simple solution but it gets the job done, assigns a known length and precision and avoids the chance of going exponential format (which is a risk when you use %g):
// Since we are only interested in 3 decimal places, this function
// can avoid any potential miniscule floating point differences
// which can return false when using "=="
int DoubleEquals(double i, double j)
{
return (fabs(i - j) < 0.000001);
}
void PrintMaxThreeDecimal(double d)
{
if (DoubleEquals(d, floor(d)))
printf("%.0f", d);
else if (DoubleEquals(d * 10, floor(d * 10)))
printf("%.1f", d);
else if (DoubleEquals(d * 100, floor(d* 100)))
printf("%.2f", d);
else
printf("%.3f", d);
}
Add or remove "elses" if you want a max of 2 decimals; 4 decimals; etc.
For example if you wanted 2 decimals:
void PrintMaxTwoDecimal(double d)
{
if (DoubleEquals(d, floor(d)))
printf("%.0f", d);
else if (DoubleEquals(d * 10, floor(d * 10)))
printf("%.1f", d);
else
printf("%.2f", d);
}
If you want to specify the minimum width to keep fields aligned, increment as necessary, for example:
void PrintAlignedMaxThreeDecimal(double d)
{
if (DoubleEquals(d, floor(d)))
printf("%7.0f", d);
else if (DoubleEquals(d * 10, floor(d * 10)))
printf("%9.1f", d);
else if (DoubleEquals(d * 100, floor(d* 100)))
printf("%10.2f", d);
else
printf("%11.3f", d);
}
You could also convert that to a function where you pass the desired width of the field:
void PrintAlignedWidthMaxThreeDecimal(int w, double d)
{
if (DoubleEquals(d, floor(d)))
printf("%*.0f", w-4, d);
else if (DoubleEquals(d * 10, floor(d * 10)))
printf("%*.1f", w-2, d);
else if (DoubleEquals(d * 100, floor(d* 100)))
printf("%*.2f", w-1, d);
else
printf("%*.3f", w, d);
}
You can also query by following code snippet as backward compatible;
int hasPermission = ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_CONTACTS);
if (hasPermission == PackageManager.PERMISSION_GRANTED) {
//Do smthng
}
Try Out with this:
firstMax = arr[0];
for (int i = 0; i<n; i++) {
if (firstMax < arr[i] ) {
secondMax = firstMax;
firstMax = arr[i];
}
}
In DB2, using single quotes instead of your double quotes will work. So that could translate the same in Oracle..
SELECT CustomerName AS Customer, '' AS Contact
FROM Customers;
To export a single component in ES6, you can use export default
as follows:
class MyClass extends Component {
...
}
export default MyClass;
And now you use the following syntax to import that module:
import MyClass from './MyClass.react'
If you are looking to export multiple components from a single file the declaration would look something like this:
export class MyClass1 extends Component {
...
}
export class MyClass2 extends Component {
...
}
And now you can use the following syntax to import those files:
import {MyClass1, MyClass2} from './MyClass.react'
using subprocess ping command to ping decode it because the response is binary:
import subprocess
ping_response = subprocess.Popen(["ping", "-a", "google.com"], stdout=subprocess.PIPE).stdout.read()
result = ping_response.decode('utf-8')
print(result)
Make sure launchPackage.command
are running in a terminal and try run again. It will build the bundle. It is kinda like webpack-dev-server.
Why should you abort the request?
If each request takes more than five seconds, what will happen?
You shouldn't abort the request if the parameter passing with the request is not changing. eg:- the request is for retrieving the notification data. In such situations, The nice approach is that set a new request only after completing the previous Ajax request.
$(document).ready(
var fn = function(){
$.ajax({
url: 'ajax/progress.ftl',
success: function(data) {
//do something
},
complete: function(){setTimeout(fn, 500);}
});
};
var interval = setTimeout(fn, 500);
);
If you write it as the following in SQL server then there would be no danger of wiping the database table unless all of the values in that table happen to actually be between those values:
DELETE FROM [dbo].[TableName] WHERE [TableName].[IdField] BETWEEN 79 AND 296
After searching a lot I find out that it is possible to create a new folder from the web interface, but it would require you to have at least one file within the folder when creating it.
When using the normal way of creating new files through the web interface, you can type in the folder into the file name to create the file within that new directory.
For example, if I would like to create the file filename.md
in a series of sub-folders, I can do this (taken from the GitHub blog):
A solution in c#
public class Queue<T> where T : class
{
private Stack<T> input = new Stack<T>();
private Stack<T> output = new Stack<T>();
public void Enqueue(T t)
{
input.Push(t);
}
public T Dequeue()
{
if (output.Count == 0)
{
while (input.Count != 0)
{
output.Push(input.Pop());
}
}
return output.Pop();
}
}
There's a function empty()
ready for you in std::string:
std::string a;
if(a.empty())
{
//do stuff. You will enter this block if the string is declared like this
}
or
std::string a;
if(!a.empty())
{
//You will not enter this block now
}
a = "42";
if(!a.empty())
{
//And now you will enter this block.
}
What is the difference between left join and left outer join?
Nothing. LEFT JOIN
and LEFT OUTER JOIN
are equivalent.
Given the following sample
myData <- data.frame(A=rep(1:2, 3), B=rep(1:3, 2), Pulse=20:25)
then
myData$A <-as.factor(myData$A)
myData$B <-as.factor(myData$B)
or you could select your columns altogether and wrap it up nicely:
# select columns
cols <- c("A", "B")
myData[,cols] <- data.frame(apply(myData[cols], 2, as.factor))
levels(myData$A) <- c("long", "short")
levels(myData$B) <- c("1kg", "2kg", "3kg")
To obtain
> myData
A B Pulse
1 long 1kg 20
2 short 2kg 21
3 long 3kg 22
4 short 1kg 23
5 long 2kg 24
6 short 3kg 25
This may be of help to you. It isn't the stock WPF datagrid however.
I used DevExpress with a custom ColorFormatter behaviour. I couldn't find anything on the market that did this out of the box. This took me a few days to develop. My code attaached below, hopefully this helps someone out there.
Edit: I used POCO view models and MVVM however you could change this to not use POCO if you desire.
Viewmodel.cs
namespace ViewModel
{
[POCOViewModel]
public class Table2DViewModel
{
public ITable2DView Table2DView { get; set; }
public DataTable ItemsTable { get; set; }
public Table2DViewModel()
{
}
public Table2DViewModel(MainViewModel mainViewModel, ITable2DView table2DView) : base(mainViewModel)
{
Table2DView = table2DView;
CreateTable();
}
private void CreateTable()
{
var dt = new DataTable();
var xAxisStrings = new string[]{"X1","X2","X3"};
var yAxisStrings = new string[]{"Y1","Y2","Y3"};
//TODO determine your min, max number for your colours
var minValue = 0;
var maxValue = 100;
Table2DView.SetColorFormatter(minValue,maxValue, null);
//Add the columns
dt.Columns.Add(" ", typeof(string));
foreach (var x in xAxisStrings) dt.Columns.Add(x, typeof(double));
//Add all the values
double z = 0;
for (var y = 0; y < yAxisStrings.Length; y++)
{
var dr = dt.NewRow();
dr[" "] = yAxisStrings[y];
for (var x = 0; x < xAxisStrings.Length; x++)
{
//TODO put your actual values here!
dr[xAxisStrings[x]] = z++; //Add a random values
}
dt.Rows.Add(dr);
}
ItemsTable = dt;
}
public static Table2DViewModel Create(MainViewModel mainViewModel, ITable2DView table2DView)
{
var factory = ViewModelSource.Factory((MainViewModel mainVm, ITable2DView view) => new Table2DViewModel(mainVm, view));
return factory(mainViewModel, table2DView);
}
}
}
IView.cs
namespace Interfaces
{
public interface ITable2DView
{
void SetColorFormatter(float minValue, float maxValue, ColorScaleFormat colorScaleFormat);
}
}
View.xaml.cs
namespace View
{
public partial class Table2DView : ITable2DView
{
public Table2DView()
{
InitializeComponent();
}
static ColorScaleFormat defaultColorScaleFormat = new ColorScaleFormat
{
ColorMin = (Color)ColorConverter.ConvertFromString("#FFF8696B"),
ColorMiddle = (Color)ColorConverter.ConvertFromString("#FFFFEB84"),
ColorMax = (Color)ColorConverter.ConvertFromString("#FF63BE7B")
};
public void SetColorFormatter(float minValue, float maxValue, ColorScaleFormat colorScaleFormat = null)
{
if (colorScaleFormat == null) colorScaleFormat = defaultColorScaleFormat;
ConditionBehavior.MinValue = minValue;
ConditionBehavior.MaxValue = maxValue;
ConditionBehavior.ColorScaleFormat = colorScaleFormat;
}
}
}
DynamicConditionBehavior.cs
namespace Behaviors
{
public class DynamicConditionBehavior : Behavior<GridControl>
{
GridControl Grid => AssociatedObject;
protected override void OnAttached()
{
base.OnAttached();
Grid.ItemsSourceChanged += OnItemsSourceChanged;
}
protected override void OnDetaching()
{
Grid.ItemsSourceChanged -= OnItemsSourceChanged;
base.OnDetaching();
}
public ColorScaleFormat ColorScaleFormat { get; set;}
public float MinValue { get; set; }
public float MaxValue { get; set; }
private void OnItemsSourceChanged(object sender, EventArgs e)
{
var view = Grid.View as TableView;
if (view == null) return;
view.FormatConditions.Clear();
foreach (var col in Grid.Columns)
{
view.FormatConditions.Add(new ColorScaleFormatCondition
{
MinValue = MinValue,
MaxValue = MaxValue,
FieldName = col.FieldName,
Format = ColorScaleFormat,
});
}
}
}
}
View.xaml
<UserControl x:Class="View"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:dxmvvm="http://schemas.devexpress.com/winfx/2008/xaml/mvvm"
xmlns:ViewModels="clr-namespace:ViewModel"
xmlns:dxg="http://schemas.devexpress.com/winfx/2008/xaml/grid"
xmlns:behaviors="clr-namespace:Behaviors"
xmlns:dxdo="http://schemas.devexpress.com/winfx/2008/xaml/docking"
DataContext="{dxmvvm:ViewModelSource Type={x:Type ViewModels:ViewModel}}"
mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="800">
<UserControl.Resources>
<Style TargetType="{x:Type dxg:GridColumn}">
<Setter Property="Width" Value="50"/>
<Setter Property="HorizontalHeaderContentAlignment" Value="Center"/>
</Style>
<Style TargetType="{x:Type dxg:HeaderItemsControl}">
<Setter Property="FontWeight" Value="DemiBold"/>
</Style>
</UserControl.Resources>
<!--<dxmvvm:Interaction.Behaviors>
<dxmvvm:EventToCommand EventName="" Command="{Binding OnLoadedCommand}"/>
</dxmvvm:Interaction.Behaviors>-->
<dxg:GridControl ItemsSource="{Binding ItemsTable}"
AutoGenerateColumns="AddNew"
EnableSmartColumnsGeneration="True">
<dxmvvm:Interaction.Behaviors >
<behaviors:DynamicConditionBehavior x:Name="ConditionBehavior" />
</dxmvvm:Interaction.Behaviors>
<dxg:GridControl.View>
<dxg:TableView ShowGroupPanel="False"
AllowPerPixelScrolling="True"/>
</dxg:GridControl.View>
</dxg:GridControl>
</UserControl>
If you're using 0
and an empty string ''
and null
to designate undefined you've got a data problem. Just update the columns and fix your schema.
UPDATE pt.incentive_channel
SET pt.incentive_marketing = NULL
WHERE pt.incentive_marketing = '';
UPDATE pt.incentive_channel
SET pt.incentive_advertising = NULL
WHERE pt.incentive_marketing = '';
UPDATE pt.incentive_channel
SET pt.incentive_channel = NULL
WHERE pt.incentive_marketing = '';
This will make joining and selecting substantially easier moving forward.
Perhaps you could use pandas.where(args)
like so:
data_frame = data_frame.where(data_frame < 0, 0)
I used @qwertyjones's answer to automate logging into Oracle Agile with a public password.
I saved the login page as index.html
, edited all the href=
and action=
fields to have the full URL to the Agile server.
The key <form>
line needed to change from
<form autocomplete="off" name="MainForm" method="POST"
action="j_security_check"
onsubmit="return false;" target="_top">
to
<form autocomplete="off" name="MainForm" method="POST"
action="http://my.company.com:7001/Agile/default/j_security_check"
onsubmit="return false;" target="_top">
I also added this snippet to the end of the <body>
<script>
function checkCookiesEnabled(){ return true; }
document.MainForm.j_username.value = "joeuser";
document.MainForm.j_password.value = "abcdef";
submitLoginForm();
</script>
I had to disable the cookie check by redefining the function that did the check, because I was hosting this from XAMPP and I didn't want to deal with it. The submitLoginForm()
call was inspired by inspecting the keyPressEvent()
function.
In my case I found that simply clearing the animation on the view before setting the visibility to GONE
works.
dp2.clearAnimation();
dp2.setVisibility(View.GONE);
I had a similar issue where I toggle between two views, one of which must always start off as GONE
- But when I displayed the views again, it was displaying over the first view even if setVisibility(GONE)
was called. Clearing the animation before setting the view to GONE
worked.
Slightly modified code for Swift 3.0
let calendar = NSCalendar.current as NSCalendar
// Replace the hour (time) of both dates with 00:00
let date1 = calendar.startOfDay(for: startDateTime)
let date2 = calendar.startOfDay(for: endDateTime)
let flags = NSCalendar.Unit.day
let components = calendar.components(flags, from: date1, to: date2, options: [])
return components.day!
Differences in SOAP versions
Both SOAP Version 1.1 and SOAP Version 1.2 are World Wide Web Consortium (W3C) standards. Web services can be deployed that support not only SOAP 1.1 but also support SOAP 1.2. Some changes from SOAP 1.1 that were made to the SOAP 1.2 specification are significant, while other changes are minor.
The SOAP 1.2 specification introduces several changes to SOAP 1.1. This information is not intended to be an in-depth description of all the new or changed features for SOAP 1.1 and SOAP 1.2. Instead, this information highlights some of the more important differences between the current versions of SOAP.
The changes to the SOAP 1.2 specification that are significant include the following updates: SOAP 1.1 is based on XML 1.0. SOAP 1.2 is based on XML Information Set (XML Infoset). The XML information set (infoset) provides a way to describe the XML document with XSD schema. However, the infoset does not necessarily serialize the document with XML 1.0 serialization on which SOAP 1.1 is based.. This new way to describe the XML document helps reveal other serialization formats, such as a binary protocol format. You can use the binary protocol format to compact the message into a compact format, where some of the verbose tagging information might not be required.
In SOAP 1.2 , you can use the specification of a binding to an underlying protocol to determine which XML serialization is used in the underlying protocol data units. The HTTP binding that is specified in SOAP 1.2 - Part 2 uses XML 1.0 as the serialization of the SOAP message infoset.
SOAP 1.2 provides the ability to officially define transport protocols, other than using HTTP, as long as the vendor conforms to the binding framework that is defined in SOAP 1.2. While HTTP is ubiquitous, it is not as reliable as other transports including TCP/IP and MQ. SOAP 1.2 provides a more specific definition of the SOAP processing model that removes many of the ambiguities that might lead to interoperability errors in the absence of the Web Services-Interoperability (WS-I) profiles. The goal is to significantly reduce the chances of interoperability issues between different vendors that use SOAP 1.2 implementations. SOAP with Attachments API for Java (SAAJ) can also stand alone as a simple mechanism to issue SOAP requests. A major change to the SAAJ specification is the ability to represent SOAP 1.1 messages and the additional SOAP 1.2 formatted messages. For example, SAAJ Version 1.3 introduces a new set of constants and methods that are more conducive to SOAP 1.2 (such as getRole(), getRelay()) on SOAP header elements. There are also additional methods on the factories for SAAJ to create appropriate SOAP 1.1 or SOAP 1.2 messages. The XML namespaces for the envelope and encoding schemas have changed for SOAP 1.2. These changes distinguish SOAP processors from SOAP 1.1 and SOAP 1.2 messages and supports changes in the SOAP schema, without affecting existing implementations. Java Architecture for XML Web Services (JAX-WS) introduces the ability to support both SOAP 1.1 and SOAP 1.2. Because JAX-RPC introduced a requirement to manipulate a SOAP message as it traversed through the run time, there became a need to represent this message in its appropriate SOAP context. In JAX-WS, a number of additional enhancements result from the support for SAAJ 1.3.
There is not difine POST AND GET method for particular android....but all here is differance
GET The GET method appends name/value pairs to the URL, allowing you to retrieve a resource representation. The big issue with this is that the length of a URL is limited (roughly 3000 char) resulting in data loss should you have to much stuff in the form on your page, so this method only works if there is a small number parameters.
What does this mean for me? Basically this renders the GET method worthless to most developers in most situations. Here is another way of looking at it: the URL could be truncated (and most likely will be give today's data-centric sites) if the form uses a large number of parameters, or if the parameters contain large amounts of data. Also, parameters passed on the URL are visible in the address field of the browser (YIKES!!!) not the best place for any kind of sensitive (or even non-sensitive) data to be shown because you are just begging the curious user to mess with it.
POST The alternative to the GET method is the POST method. This method packages the name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the forms output, basically its a no-brainer on which one to use. POST is also more secure but certainly not safe. Although HTTP fully supports CRUD, HTML 4 only supports issuing GET and POST requests through its various elements. This limitation has held Web applications back from making full use of HTTP, and to work around it, most applications overload POST to take care of everything but resource retrieval.
Life span of java Thread is over after completion of run()
method. Same thread can't be started again.
Looper transforms normal Thread
into a message loop. Key methods of Looper
are :
void prepare ()
Initialize the current thread as a looper. This gives you a chance to create handlers that then reference this looper, before actually starting the loop. Be sure to call loop() after calling this method, and end it by calling quit().
void loop ()
Run the message queue in this thread. Be sure to call quit() to end the loop.
void quit()
Quits the looper.
Causes the loop() method to terminate without processing any more messages in the message queue.
This mindorks article by Janishar explains the core concepts in nice way.
Looper
is associated with a Thread. If you need Looper
on UI thread, Looper.getMainLooper()
will return associated thread.
You need Looper
to be associated with a Handler.
Looper
, Handler
, and HandlerThread
are the Android’s way of solving the problems of asynchronous programming.
Once you have Handler
, you can call below APIs.
post (Runnable r)
Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached.
boolean sendMessage (Message msg)
Pushes a message onto the end of the message queue after all pending messages before the current time. It will be received in handleMessage(Message), in the thread attached to this handler.
HandlerThread is handy class for starting a new thread that has a looper. The looper can then be used to create handler classes
In some scenarios, you can't run Runnable
tasks on UI Thread.
e.g. Network operations : Send message on a socket, open an URL and get content by reading InputStream
In these cases, HandlerThread
is useful. You can get Looper
object from HandlerThread
and create a Handler
on HandlerThread
instead of main thread.
The HandlerThread code will be like this:
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
Refer to below post for example code:
To get or set the Password in a PasswordBox, use the Password property. Such as
string password = PasswordBox.Password;
This doesn't support Databinding as far as I know, so you'd have to set the value in the codebehind, and update it accordingly.
You have to use the FormulaEvaluator, as shown here. This will return a value that is either the value present in the cell or the result of the formula if the cell contains such a formula :
FileInputStream fis = new FileInputStream("/somepath/test.xls");
Workbook wb = new HSSFWorkbook(fis); //or new XSSFWorkbook("/somepath/test.xls")
Sheet sheet = wb.getSheetAt(0);
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
// suppose your formula is in B3
CellReference cellReference = new CellReference("B3");
Row row = sheet.getRow(cellReference.getRow());
Cell cell = row.getCell(cellReference.getCol());
if (cell!=null) {
switch (evaluator.evaluateFormulaCell(cell)) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.println(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
System.out.println(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BLANK:
break;
case Cell.CELL_TYPE_ERROR:
System.out.println(cell.getErrorCellValue());
break;
// CELL_TYPE_FORMULA will never occur
case Cell.CELL_TYPE_FORMULA:
break;
}
}
if you need the exact contant (ie the formla if the cell contains a formula), then this is shown here.
Edit : Added a few example to help you.
first you get the cell (just an example)
Row row = sheet.getRow(rowIndex+2);
Cell cell = row.getCell(1);
If you just want to set the value into the cell using the formula (without knowing the result) :
String formula ="ABS((1-E"+(rowIndex + 2)+"/D"+(rowIndex + 2)+")*100)";
cell.setCellFormula(formula);
cell.setCellStyle(this.valueRightAlignStyleLightBlueBackground);
if you want to change the message if there is an error in the cell, you have to change the formula to do so, something like
IF(ISERR(ABS((1-E3/D3)*100));"N/A"; ABS((1-E3/D3)*100))
(this formula check if the evaluation return an error and then display the string "N/A", or the evaluation if this is not an error).
if you want to get the value corresponding to the formula, then you have to use the evaluator.
Hope this help,
Guillaume
It means node is not able to listen on defined port. Change it to something like 1234 or 2000 or 3000 and restart your server.
Do not depend on ADB shell, just treat it (the adb logcat) a normal linux output and then pip it:
$ adb shell logcat | grep YouTag
# just like:
$ ps -ef | grep your_proc
In my humble opinion, this is just a matter of deciding if the arguments are optional or not. If an Person object shouldn't (logically) exist without Name and Age, they should be mandatory in the constructor. If they are optional, (i.e. their absence is not a threat to the good functioning of the object), use the setters.
Here's a quote from Symfony's docs on constructor injection:
There are several advantages to using constructor injection:
- If the dependency is a requirement and the class cannot work without it then injecting it via the constructor ensures it is present when the class is used as the class cannot be constructed without it.
- The constructor is only ever called once when the object is created, so you can be sure that the dependency will not change during the object's lifetime.
These advantages do mean that constructor injection is not suitable for working with optional dependencies. It is also more difficult to use in combination with class hierarchies: if a class uses constructor injection then extending it and overriding the constructor becomes problematic.
(Symfony is one of the most popular and respected php frameworks)
PowerShell is pretty common these days so I use it often as a quick way to invoke C# since that has functions for pretty much everything:
@echo off
set pathToResolve=%~dp0\..\SomeFile.txt
for /f "delims=" %%a in ('powershell -Command "[System.IO.Path]::GetFullPath( '%projectDirMc%' )"') do @set resolvedPath=%%a
echo Resolved path: %resolvedPath%
It's a bit slow, but the functionality gained is hard to beat unless without resorting to an actual scripting language.
I like this way.
.circle:before {
content: "";
width: 14px;
height: 14px;
border: 3px solid #fff;
background-color: #ced4da;
border-radius: 7px;
display: inline-block;
margin-bottom: -2px;
margin-right: 7px;
box-shadow: 0px 0px 0px 1px #ced4da;
}
It will create gray circle with wit border around it and again 1px around border!
It would be good to share, For DB2 use:
INSERT(someColumn, 1, 4, '')
Stuff
is not supported in DB2
>>> a = {'foo': 'bar', 'baz': 'quux', 'hello': 'world'}
>>> list(reduce(lambda x, y: x + y, a.items()))
['foo', 'bar', 'baz', 'quux', 'hello', 'world']
To explain: a.items() returns a list of tuples. Adding two tuples together makes one tuple containing all elements. Thus the reduction creates one tuple containing all keys and values and then the list(...) makes a list from that.
Really nice and easy solution, exactly what I wanted !
I bring some small modifications
public class TextBlockMoo : TextBlock
{
public String SelectedText = "";
public delegate void TextSelectedHandler(string SelectedText);
public event TextSelectedHandler OnTextSelected;
protected void RaiseEvent()
{
if (OnTextSelected != null){OnTextSelected(SelectedText);}
}
TextPointer StartSelectPosition;
TextPointer EndSelectPosition;
Brush _saveForeGroundBrush;
Brush _saveBackGroundBrush;
TextRange _ntr = null;
protected override void OnMouseDown(MouseButtonEventArgs e)
{
base.OnMouseDown(e);
if (_ntr!=null) {
_ntr.ApplyPropertyValue(TextElement.ForegroundProperty, _saveForeGroundBrush);
_ntr.ApplyPropertyValue(TextElement.BackgroundProperty, _saveBackGroundBrush);
}
Point mouseDownPoint = e.GetPosition(this);
StartSelectPosition = this.GetPositionFromPoint(mouseDownPoint, true);
}
protected override void OnMouseUp(MouseButtonEventArgs e)
{
base.OnMouseUp(e);
Point mouseUpPoint = e.GetPosition(this);
EndSelectPosition = this.GetPositionFromPoint(mouseUpPoint, true);
_ntr = new TextRange(StartSelectPosition, EndSelectPosition);
// keep saved
_saveForeGroundBrush = (Brush)_ntr.GetPropertyValue(TextElement.ForegroundProperty);
_saveBackGroundBrush = (Brush)_ntr.GetPropertyValue(TextElement.BackgroundProperty);
// change style
_ntr.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(Colors.Yellow));
_ntr.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.DarkBlue));
SelectedText = _ntr.Text;
}
}
In my case, I replaced the src taq using:
$('#gmap_canvas').attr('src', newSrc);
_x000D_
Step 1: Set the PATH variable JAVA_HOME to the path of the JDK present on the system. Step 2: in the Path variable add the path of the C:\Program Files\Java\jdk(version)\bin
This should solve the problem. Happy coding!!
Instead of doing
Reader in = new BufferedReader(
new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder= new StringBuilder();
char[] buf = new char[1000];
int l = 0;
while (l >= 0) {
builder.append(buf, 0, l);
l = in.read(buf);
}
JSONTokener tokener = new JSONTokener( builder.toString() );
You can do:
JSONTokener tokener = new JSONTokener(
IOUtils.toString(response.getEntity().getContent()) );
where IOUtils is from the commons IO library.
env.OrderByDescending(x => x.ReportDate)
i'd suggest shorter and faster approach:
printf("%.2f", ((signed long)(fVal * 100) * 0.01f));
this way you won't overflow int, plus multiplication by 100 shouldn't influence the significand/mantissa itself, because the only thing that really is changing is exponent.
believe there should be a way in accessing file system.
Include node.d.ts
using npm i @types/node
. And then create a new tsconfig.json
file (npx tsc --init
) and create a .ts
file as followed:
import fs from 'fs';
fs.readFileSync('foo.txt','utf8');
You can use other functions in fs
as well : https://nodejs.org/api/fs.html
Node quick start : https://basarat.gitbooks.io/typescript/content/docs/node/nodejs.html
A very simple plugin for counting actual lines of source code is step counter eclipse plugin. Please download and try.
Place the downloaded jar file under eclipse\plugin folder and restart eclipse.
Rightclick and select step counter
After ensuring the naming conventions are correct as described in other answers, and also trying to invalidate the cache and restart, deleting temp/cache folders the issue still persisted for me.
I got rid of it as follows: Add a new dummy XML resource. This will trigger bindings and its meta-data to re-create across the project. The annoying compile errors should no longer be visible anymore. You now delete the dummy XML you added.
For me as of August 2020, the Binding would automatically get corrupted repeatedly. It seems to be biting more than it can chew under the hood.
If your query has any JOINs, Mysql Workbench will not allow you to alter the table, even if your results are all from a single table.
For example, the following query
SELECT u.* FROM users u JOIN passwords p ON u.id=p.user_id WHERE p.password IS NULL;
will not allow you to edit the results or add rows, even though the results are limited to one table. You must specifically do something like:
SELECT * FROM users WHERE id=1012;
and then you can edit the row and add rows to the table.
You need to first find iframe
. You can do so using following statement.
WebElement iFrame= driver.findElement(By.tagName("iframe"));
Then, you can swith to it using switchTo
method on you WebDriver
object.
driver.switchTo().frame(iFrame);
And to move back to the parent frame, you can either use switchTo().parentFrame()
or if you want to get back to the main (or most parent) frame, you can use switchTo().defaultContent();
.
driver.switchTo().parentFrame(); // to move back to parent frame
driver.switchTo().defaultContent(); // to move back to most parent or main frame
Hope it helps.
double a = 100.3;
printf("%f %d\n", a, (int)(a* 10.0));
Output Cygwin 100.3 1003
Output MinGW: 100.3 1002
Using (int) to convert double to int seems not to be fail-safe
You can find more about that here: Convert double to int?
You dont have to
RUN mkdir -p /usr/src/app
This will be created automatically when you specifiy your WORKDIR
FROM node:latest
WORKDIR /usr/src/app
COPY package.json .
RUN npm install
COPY . ./
EXPOSE 3000
CMD [ “npm”, “start” ]
The following is a hybrid jQuery solution that formats each data "record" into an HTML element and uses the data's properties as HTML attribute values.
The jquery each
runs the inner loop; I needed the regular JavaScript for
on the outer loop to be able to grab the property name (instead of value) for display as the heading. According to taste it can be modified for slightly different behaviour.
This is only 5 main lines of code but wrapped onto multiple lines for display:
$.get("data.php", function(data){
for (var propTitle in data) {
$('<div></div>')
.addClass('heading')
.insertBefore('#contentHere')
.text(propTitle);
$(data[propTitle]).each(function(iRec, oRec) {
$('<div></div>')
.addClass(oRec.textType)
.attr('id', 'T'+oRec.textId)
.insertBefore('#contentHere')
.text(oRec.text);
});
}
});
Produces the output
(Note: I modified the JSON data text values by prepending a number to ensure I was displaying the proper records in the proper sequence - while "debugging")
<div class="heading">
justIn
</div>
<div id="T123" class="Greeting">
1Hello
</div>
<div id="T514" class="Question">
1What's up?
</div>
<div id="T122" class="Order">
1Come over here
</div>
<div class="heading">
recent
</div>
<div id="T1255" class="Greeting">
2Hello
</div>
<div id="T6564" class="Question">
2What's up?
</div>
<div id="T0192" class="Order">
2Come over here
</div>
<div class="heading">
old
</div>
<div id="T5213" class="Greeting">
3Hello
</div>
<div id="T9758" class="Question">
3What's up?
</div>
<div id="T7655" class="Order">
3Come over here
</div>
<div id="contentHere"></div>
Apply a style sheet
<style>
.heading { font-size: 24px; text-decoration:underline }
.Greeting { color: green; }
.Question { color: blue; }
.Order { color: red; }
</style>
to get a "beautiful" looking set of data
More Info
The JSON data was used in the following way:
for each category (key name the array is held under):
for each object held inside an array:
You can do that I believe. It needs root permission. If you want to know where your apk files are stored, open a emulator and then go to
DDMS>File Explorer-> you can see a directory by name "data" -> Click on it and you will see a "app" folder.
Your apks are stored there. In fact just copying a apk directly to the folder works for me with emulators.
Here you can find info on how to upgrade to v3: http://tosbourn.com/2013/08/javascript/upgrading-from-bootstraps-typeahead-to-typeahead-js/
Here are some examples too: http://twitter.github.io/typeahead.js/examples/
You must use an aggregate function on the columns against which you are not grouping. In this example, I arbitrarily picked the Min function. You are combining the rows with the same FruitType
value. If I have two rows with the same FruitType
value but different Fruit_Id
values for example, what should the system do?
Select Min(tblFruit_id) As tblFruit_id
, tblFruit_FruitType
From tblFruit
Group By tblFruit_FruitType
I already have answered here and it's working for me, please refer this link https://stackoverflow.com/a/40133225/3636561
String socailLink="https://www.facebook.com/kfc";
Intent intent = new Intent(Intent.ACTION_VIEW);
String facebookUrl = Utils.getFacebookUrl(getActivity(), socailLink);
if (facebookUrl == null || facebookUrl.length() == 0) {
Log.d("facebook Url", " is coming as " + facebookUrl);
return;
}
intent.setData(Uri.parse(facebookUrl));
startActivity(intent);
please refer link to get rest part.
I have created a library to batch delete or update records with a round trip on EF Core 5.
Sample code as follows:
await ctx.DeleteRangeAsync(b => b.Price > n || b.AuthorName == "zack yang");
await ctx.BatchUpdate()
.Set(b => b.Price, b => b.Price + 3)
.Set(b=>b.AuthorName,b=>b.Title.Substring(3,2)+b.AuthorName.ToUpper())
.Set(b => b.PubTime, b => DateTime.Now)
.Where(b => b.Id > n || b.AuthorName.StartsWith("Zack"))
.ExecuteAsync();
Github repository: https://github.com/yangzhongke/Zack.EFCore.Batch Report: https://www.reddit.com/r/dotnetcore/comments/k1esra/how_to_batch_delete_or_update_in_entity_framework/
EXISTS
will be faster because once the engine has found a hit, it will quit looking as the condition has proved true.
With IN
, it will collect all the results from the sub-query before further processing.
Easier Yet, you can operate directly on $@
;)
Here is how to do pass a a list of args directly from the prompt:
function echoarg { for stuff in "$@" ; do echo $stuff ; done ; }
echoarg Hey Ho Lets Go
Hey
Ho
Lets
Go
You can do like
HTML in PHP :
<?php
echo "<table>";
echo "<tr>";
echo "<td>Name</td>";
echo "<td>".$name."</td>";
echo "</tr>";
echo "</table>";
?>
Or You can write like.
PHP in HTML :
<?php /*Do some PHP calculation or something*/ ?>
<table>
<tr>
<td>Name</td>
<td><?php echo $name;?></td>
</tr>
</table>
<?php /*Do some PHP calculation or something*/ ?>
Means:
You can open a PHP tag with <?php
, now add your PHP code, then close the tag with ?>
and then write your html code. When needed to add more PHP, just open another PHP tag with <?php
.
There's no such thing as the "first" key in a hash (Javascript calls them objects). They are fundamentally unordered. Do you mean just choose any single key:
for (var k in ahash) {
break
}
// k is a key in ahash.
You can also use the Properties class
Here's the constants file called
# this will hold all of the constants
frameWidth = 1600
frameHeight = 900
Here is the code that uses the constants
public class SimpleGuiAnimation {
int frameWidth;
int frameHeight;
public SimpleGuiAnimation() {
Properties properties = new Properties();
try {
File file = new File("src/main/resources/dataDirectory/gui_constants.properties");
FileInputStream fileInputStream = new FileInputStream(file);
properties.load(fileInputStream);
}
catch (FileNotFoundException fileNotFoundException) {
System.out.println("Could not find the properties file" + fileNotFoundException);
}
catch (Exception exception) {
System.out.println("Could not load properties file" + exception.toString());
}
this.frameWidth = Integer.parseInt(properties.getProperty("frameWidth"));
this.frameHeight = Integer.parseInt(properties.getProperty("frameHeight"));
}
It looks like your syntax is slightly out. This has some good examples
DECLARE @TempCustomer TABLE
(
CustomerId uniqueidentifier,
FirstName nvarchar(100),
LastName nvarchar(100),
Email nvarchar(100)
);
INSERT @TempCustomer
SELECT
CustomerId,
FirstName,
LastName,
Email
FROM
Customer
WHERE
CustomerId = @CustomerId
Then later
SELECT CustomerId FROM @TempCustomer
Initially, the firebase database was pointing to 11.8.0 .after changing all the related jars to 11.0.4 this issue is resolved at changes the SDK level.
compile 'com.google.firebase:firebase-database:11.0.4'
compile 'com.google.firebase:firebase-messaging:11.0.4'
This works:
<script src="/clock.js" type="text/javascript"></script>
The leading slash means the root directory of your site. Strictly speaking, language="Javascript"
has been deprecated by type="text/javascript"
.
Capitalization of tags and attributes is also widely discouraged.
in jquery we have to use selector($) to declare variables
var test=$("<%=ddl.ClientId%>");
here we can get the id of drop down to j query variable
Some more pre-conditions are needed for the ones written by Bill K and dadinn
Object[] newArray = new Object[src.length - 1];
if (i > 0){
System.arraycopy(src, 0, newArray, 0, i);
}
if (newArray.length > i){
System.arraycopy(src, i + 1, newArray, i, newArray.length - i);
}
return newArray;
I suggest you to first try to understand Java 8 in the whole picture, most importantly in your case it will be streams, lambdas and method references.
You should never convert existing code to Java 8 code on a line-by-line basis, you should extract features and convert those.
What I identified in your first case is the following:
Let's see how we do that, we can do it with the following:
List<Player> playersOfTeam = players.stream()
.filter(player -> player.getTeam().equals(teamName))
.collect(Collectors.toList());
What you do here is:
Collection<Player>
, now you have a Stream<Player>
.Predicate<Player>
, mapping every player to the boolean true if it is wished to be kept.Collector
, here we can use one of the standard library collectors, which is Collectors.toList()
.This also incorporates two other points:
List<E>
over ArrayList<E>
.new ArrayList<>()
, you are using Java 8 after all.Now onto your second point:
You again want to convert something of legacy Java to Java 8 without looking at the bigger picture. This part has already been answered by @IanRoberts, though I think that you need to do players.stream().filter(...)...
over what he suggested.
Swift 3.0.1+ (Some of the other swift 3.0 answers are not up to date)
textField.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)),
for: UIControlEvents.editingChanged)
func textFieldDidChange(_ textField: UITextField) {
}
For pyautogui users:
import pyautogui
screenshot = pyautogui.screenshot()
Jeff Atwood has a recent blog post about this: The Great Newline Schism
Here is the essence from Wikipedia:
The sequence CR+LF was in common use on many early computer systems that had adopted teletype machines, typically an ASR33, as a console device, because this sequence was required to position those printers at the start of a new line. On these systems, text was often routinely composed to be compatible with these printers, since the concept of device drivers hiding such hardware details from the application was not yet well developed; applications had to talk directly to the teletype machine and follow its conventions. The separation of the two functions concealed the fact that the print head could not return from the far right to the beginning of the next line in one-character time. That is why the sequence was always sent with the CR first. In fact, it was often necessary to send extra characters (extraneous CRs or NULs, which are ignored) to give the print head time to move to the left margin. Even after teletypes were replaced by computer terminals with higher baud rates, many operating systems still supported automatic sending of these fill characters, for compatibility with cheaper terminals that required multiple character times to scroll the display.
nchar(YOURSTRING)
you may need to convert to a character vector first;
nchar(as.character(YOURSTRING))
Since data.table
1.12.4 (Oct 2019), data.table
gains two functions to facilitate this: nafill
and setnafill
.
nafill
operates on columns:
cols = c('a', 'b')
y[ , (cols) := lapply(.SD, nafill, fill=0), .SDcols = cols]
setnafill
operates on tables (the replacements happen by-reference/in-place)
setnafill(y, cols=cols, fill=0)
# print y to show the effect
y[]
This will also be more efficient than the other options; see ?nafill
for more, the last-observation-carried-forward (LOCF) and next-observation-carried-backward (NOCB) versions of NA
imputation for time series.
This will work for your data.table
version:
for (col in c("a", "b")) y[is.na(get(col)), (col) := 0]
Alternatively, as David Arenburg points out below, you can use set
(side benefit - you can use it either on data.frame
or data.table
):
for (col in 1:2) set(x, which(is.na(x[[col]])), col, 0)
Solution with .Where and .Contains has complexity of O(N square). Simple .Join should have a lot better performance (close to O(N) due to hashing). So the correct code is:
_dataContext.UserProfile.Join(idList, up => up.ID, id => id, (up, id) => up);
And now result of my measurement. I generated 100 000 UserProfiles and 100 000 ids. Join took 32ms and .Where with .Contains took 2 minutes and 19 seconds! I used pure IEnumerable for this testing to prove my statement. If you use List instead of IEnumerable, .Where and .Contains will be faster. Anyway the difference is significant. The fastest .Where .Contains is with Set<>. All it depends on complexity of underlying coletions for .Contains. Look at this post to learn about linq complexity.Look at my test sample below:
private static void Main(string[] args)
{
var userProfiles = GenerateUserProfiles();
var idList = GenerateIds();
var stopWatch = new Stopwatch();
stopWatch.Start();
userProfiles.Join(idList, up => up.ID, id => id, (up, id) => up).ToArray();
Console.WriteLine("Elapsed .Join time: {0}", stopWatch.Elapsed);
stopWatch.Restart();
userProfiles.Where(up => idList.Contains(up.ID)).ToArray();
Console.WriteLine("Elapsed .Where .Contains time: {0}", stopWatch.Elapsed);
Console.ReadLine();
}
private static IEnumerable<int> GenerateIds()
{
// var result = new List<int>();
for (int i = 100000; i > 0; i--)
{
yield return i;
}
}
private static IEnumerable<UserProfile> GenerateUserProfiles()
{
for (int i = 0; i < 100000; i++)
{
yield return new UserProfile {ID = i};
}
}
Console output:
Elapsed .Join time: 00:00:00.0322546
Elapsed .Where .Contains time: 00:02:19.4072107
updating ipykernel did it for me. it seems arch linux's ipykernel package had been outdated for some time
just do pip install --upgrade ipykernel
reference here: github solution
I had also faced the same issue, after few searches, I found a solution that worked for me.I hope it will help you.
As you have already created users, now try to do a FLUSH PRIVILEGES
on your Mysql console.
This issue is already in MySql bug post.You can also check this one.Now after flushing, you can create a new user.
follow below Steps:
Step-1: Open terminal Ctrl+Alt+T
Step-2: mysql -u root -p , it will ask for your MySQL password.
Now you can able to see Mysql console.
Step-3: CREATE USER 'username'@'host' IDENTIFIED by 'PASSWORD';
Instead of username you can put username you want. If you are running Mysql on your local machine, then type "localhost" instead of the host, otherwise give your server name you want to access.
Ex: CREATE USER smruti@localhost IDENTIFIED by 'hello';
Now new user is created. If you want to give all access then type
GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';
Now you can quit the MySQL by typing \q
.Now once again login through
mysql -u newusername -p
, then press Enter. You can see everything.
Hope this helps.
$.browser
was removed from jQuery starting with version 1.9. It is now available as a plugin. It's generally recommended to avoid browser detection, which is why it was removed.
use this command:
sudo sed -i "s/mirrorlist=https/mirrorlist=http/" /etc/yum.repos.d/epel.repo
or alternatively use command
vi /etc/yum.repos.d/epel.repo
go to line number 4 and change the url from
mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-6&arch=$basearch
to
mirrorlist=http://mirrors.fedoraproject.org/metalink?repo=epel-6&arch=$basearch
There is no "better" but the more common one is ||
. They have different precedence and ||
would work like one would expect normally.
See also: Logical operators (the following example is taken from there):
// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;
// The constant false is assigned to $f and then true is ignored
// Acts like: (($f = false) or true)
$f = false or true;
I had the same problem,
i solved it by:
1 - i uninstall virtual box
2 - i uninstall genymotion with all new folder that dependency
3 - download latest version of virtual box(from oracle site)
4 - download latest version of Genymotion(without virtual box version
size:about42M)
5 - first install virtual box
6 - install genymotion
7 - before run genymotion you should restart your windows os
8 - run genymotion as admin
Sorry for my english writing
I'm new to learn :D
From the source code:
// Instance of WebViewClient that is the client callback.
private volatile WebViewClient mWebViewClient;
// Instance of WebChromeClient for handling all chrome functions.
private volatile WebChromeClient mWebChromeClient;
// SOME OTHER SUTFFF.......
/**
* Set the WebViewClient.
* @param client An implementation of WebViewClient.
*/
public void setWebViewClient(WebViewClient client) {
mWebViewClient = client;
}
/**
* Set the WebChromeClient.
* @param client An implementation of WebChromeClient.
*/
public void setWebChromeClient(WebChromeClient client) {
mWebChromeClient = client;
}
Using WebChromeClient allows you to handle Javascript dialogs, favicons, titles, and the progress. Take a look of this example: Adding alert() support to a WebView
At first glance, there are too many differences WebViewClient & WebChromeClient. But, basically: if you are developing a WebView that won't require too many features but rendering HTML, you can just use a WebViewClient
. On the other hand, if you want to (for instance) load the favicon of the page you are rendering, you should use a WebChromeClient
object and override the onReceivedIcon(WebView view, Bitmap icon)
.
Most of the times, if you don't want to worry about those things... you can just do this:
webView= (WebView) findViewById(R.id.webview);
webView.setWebChromeClient(new WebChromeClient());
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
And your WebView will (in theory) have all features implemented (as the android native browser).
You could use a subselect combined with a UNION. Whenever you can return the same fields for more than one condition use OR with the parenthesis as in this example:
SELECT * FROM
(SELECT val1, val2 FROM table1 WHERE (condition1 is true)
OR (condition2 is true))
UNION
SELECT * FROM
(SELECT val5, val6 FROM table7 WHERE (condition9 is true)
OR (condition4 is true))
Player.cpp
require the definition of Ball
class. So simply add #include "Ball.h"
Player.cpp:
#include "Player.h"
#include "Ball.h"
void Player::doSomething(Ball& ball) {
ball.ballPosX += 10; // incomplete type error occurs here.
}
string ConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(ConnectionString))
{
//Create the SqlCommand object
SqlCommand cmd = new SqlCommand(“spAddEmployee”, con);
//Specify that the SqlCommand is a stored procedure
cmd.CommandType = System.Data.CommandType.StoredProcedure;
//Add the input parameters to the command object
cmd.Parameters.AddWithValue(“@Name”, txtEmployeeName.Text);
cmd.Parameters.AddWithValue(“@Gender”, ddlGender.SelectedValue);
cmd.Parameters.AddWithValue(“@Salary”, txtSalary.Text);
//Add the output parameter to the command object
SqlParameter outPutParameter = new SqlParameter();
outPutParameter.ParameterName = “@EmployeeId”;
outPutParameter.SqlDbType = System.Data.SqlDbType.Int;
outPutParameter.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(outPutParameter);
//Open the connection and execute the query
con.Open();
cmd.ExecuteNonQuery();
//Retrieve the value of the output parameter
string EmployeeId = outPutParameter.Value.ToString();
}
Font http://www.codeproject.com/Articles/748619/ADO-NET-How-to-call-a-stored-procedure-with-output
can you try if.else
> col2=ifelse(df1$col=="true",1,0)
> df1
$col
[1] "true" "false"
> cbind(df1$col)
[,1]
[1,] "true"
[2,] "false"
> cbind(df1$col,col2)
col2
[1,] "true" "1"
[2,] "false" "0"
You can do something like this to read your nodes.
Also you can find some explanation in this page http://www.compoc.com/tuts/
<script type="text/javascript">
var markers = null;
$(document).ready(function () {
$.get("File.xml", {}, function (xml){
$('marker',xml).each(function(i){
markers = $(this);
});
});
});
</script>
You need to subscribe to the KeyDown
event on the text box. Then something like this:
private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.' && e.KeyChar != '+' && e.KeyChar != '-'
&& e.KeyChar != '(' && e.KeyChar != ')' && e.KeyChar != '*'
&& e.KeyChar != '/')
{
e.Handled = true;
return;
}
e.Handled=false;
return;
}
The important thing to know is that if you changed the Handled
property to true
, it will not process the keystroke. Setting it to false
will.
Another approach suitable for overriding a few properties in your test, if you are using @SpringBootTest
annotation:
@SpringBootTest(properties = {"propA=valueA", "propB=valueB"})
You need to control the opening of sub forms from a main form.
In my case I'm opening a Login window first before I launch my form1. I control everything from Program.cs. Set up a validation flag in Program.cs. Open Login window from Program.cs. Control then goes to login window. Then if the validation is good, set the validation flag to true from the login window. Now you can safely close the login window. Control returns to Program.cs. If the validation flag is true, open form1. If the validation flag is false, your application will close.
In Program.cs:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
///
//Validation flag
public static bool ValidLogin = false;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Login());
if (ValidLogin)
{
Application.Run(new Form1());
}
}
}
In Login.cs:
private void btnOK_Click(object sender, EventArgs e)
{
if (txtUsername.Text == "x" && txtPassword.Text == "x")
{
Program.ValidLogin = true;
this.Close();
}
else
{
MessageBox.Show("Username or Password are incorrect.");
}
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
Interesting idea. Some searching on Google produced a few pages of interest, including:
Hope this helps.
There is now a great plugin for Firebug that clones this nice feature in chrome. Check out:
https://addons.mozilla.org/en-US/firefox/addon/firestorage-plus/
It's developed by Nick Belhomme and updated regularly
Pretty old question... but I had the same problem today and solved with script, a little bit slow and complex but worked. I did this:
Let's start from the source DB (SQL 2014) right click on the database you would like to backup -> Generate Scripts -> "Script entire database and all database objet" (or u can select only some table if u want) -> the most important step is in the "Set Scripting Options" tab, here you have to click on "Advanced" and look for the option "Script for Server version" and in my case I could select everything from SQL 2005, also pay attention to the option "Types of data to script" I advice "Schema and data" and also Script Triggers and Script Full-text Indexes (if you need, it's false by default) and finally click ok and next. Should look like this:
Now transfer your generated script into your SQL 2008, open it and last Important Step: You must change mdf and ldf location!!
That's all folks, happy F5!! :D
Here is a code sample which should pretty much sum this up for you... In addition to the below, showing how you can't access a default in another package there is one more thing.
Default is not accessible in a subclass if the class that subclasses it is in another package, but it is accessible if the subclass is in the same package.
package main;
public class ClassA {
private int privateVar;
public int publicVar;
int defaultVar;
}
package main;
public class ClassB {
public static void main(String[] args) {
ClassA a = new ClassA();
int v1 = a.publicVar; // Works
int v2 = a.defaultVar; // Works
int v3 = a.privateVar; // Doesn't work
}
}
package other;
public class ClassC {
public static void main(String[] args) {
ClassA a = new ClassA();
int v1 = a.publicVar; // Works
int v2 = a.defaultVar; // Doesn't work
int v3 = a.privateVar; // Doesn't work
}
}
While an old question, I've just dealt with a variant of it, but none of the solutions here were applicable, so I found another, and am adding it for posterity. Yes, I know the OP said they were aware of this option and it didn't suit them, but for anyone following afterwards it might prove useful.
In my case, I want to test for the availability of a local apt-cacher-ng
service from a docker
build. That means absolutely nothing can be installed prior to the test. No nc
, nmap
, expect
, telnet
or python
. perl
however is present, along with the core libraries, so I used this:
perl -MIO::Socket::INET -e 'exit(! defined( IO::Socket::INET->new("172.17.42.1:3142")))'
An example of fine-grained timing using mach_absolute_time()
in Swift 4:
let start = mach_absolute_time()
// do something
let elapsedMTU = mach_absolute_time() - start
var timebase = mach_timebase_info()
if mach_timebase_info(&timebase) == 0 {
let elapsed = Double(elapsedMTU) * Double(timebase.numer) / Double(timebase.denom)
print("render took \(elapsed)")
}
else {
print("timebase error")
}
Based on the solution of @Roman, you can set multiple values:
update users as u set -- postgres FTW
email = u2.email,
first_name = u2.first_name,
last_name = u2.last_name
from (values
(1, '[email protected]', 'Hollis', 'O\'Connell'),
(2, '[email protected]', 'Robert', 'Duncan')
) as u2(id, email, first_name, last_name)
where u2.id = u.id;
For @return
tag use {{field1: Number, field2: String}}
, see: http://wiki.servoy.com/display/public/DOCS/Annotating+JavaScript+using+JSDoc
Depending on what you are using this for, you may need to specify the data type (see 'dtype').
For example, to create a 2D array of 8-bit values (suitable for use as a monochrome image):
myarray = numpy.empty(shape=(H,W),dtype='u1')
For an RGB image, include the number of color channels in the shape: shape=(H,W,3)
You may also want to consider zero-initializing with numpy.zeros
instead of using numpy.empty
. See the note here.
The solution is:
Update-Database –TargetMigration 201609261919239_yourLastMigrationSucess
Many people will suggest you use MERGE
, but I caution you against it. By default, it doesn't protect you from concurrency and race conditions any more than multiple statements, but it does introduce other dangers:
http://www.mssqltips.com/sqlservertip/3074/use-caution-with-sql-servers-merge-statement/
Even with this "simpler" syntax available, I still prefer this approach (error handling omitted for brevity):
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
UPDATE dbo.table SET ... WHERE PK = @PK;
IF @@ROWCOUNT = 0
BEGIN
INSERT dbo.table(PK, ...) SELECT @PK, ...;
END
COMMIT TRANSACTION;
A lot of folks will suggest this way:
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
IF EXISTS (SELECT 1 FROM dbo.table WHERE PK = @PK)
BEGIN
UPDATE ...
END
ELSE
BEGIN
INSERT ...
END
COMMIT TRANSACTION;
But all this accomplishes is ensuring you may need to read the table twice to locate the row(s) to be updated. In the first sample, you will only ever need to locate the row(s) once. (In both cases, if no rows are found from the initial read, an insert occurs.)
Others will suggest this way:
BEGIN TRY
INSERT ...
END TRY
BEGIN CATCH
IF ERROR_NUMBER() = 2627
UPDATE ...
END CATCH
However, this is problematic if for no other reason than letting SQL Server catch exceptions that you could have prevented in the first place is much more expensive, except in the rare scenario where almost every insert fails. I prove as much here:
Not sure what you think you gain by having a single statement; I don't think you gain anything. MERGE
is a single statement but it still has to really perform multiple operations anyway - even though it makes you think it doesn't.
Use the pandas to_datetime
function to parse the column as DateTime. Also, by using infer_datetime_format=True
, it will automatically detect the format and convert the mentioned column to DateTime.
import pandas as pd
raw_data['Mycol'] = pd.to_datetime(raw_data['Mycol'], infer_datetime_format=True)
This is for windows environment:
I got the Initial Admin password under C:\Users\Deepak("MyUser").jenkins\secrets\initialAdminPassword
I was able to login with user "admin" and above password. Then under Jenkins> people I edited the password of the user and clicked on apply to reflect the changes.
I think these kinds of problems are solved if we think about real life.
Bad Practice:
Example 1:
Darling everything is FINE/OK (HTTP CODE 200) - (Success):
{
...but I don't want us to be together anymore!!!... (Error)
// Then everything isn't OK???
}
Example 2:
You are the best employee (HTTP CODE 200) - (Success):
{
...But we cannot continue your contract!!!... (Error)
// Then everything isn't OK???
}
Good Practices:
Darling I don't feel good (HTTP CODE 400) - (Error):
{
...I no longer feel anything for you, I think the best thing is to separate... (Error)
// In this case, you are alerting me from the beginning that something is wrong ...
}
This is only my personal opinion, each one can implement it as it is most comfortable or needs.
Note: The idea for this explanation was drawn from a great friend @diosney
3 ½ Years later...
For my own project I wanted to flatten JSON objects in mongoDB dot notation and came up with a simple solution:
/**
* Recursively flattens a JSON object using dot notation.
*
* NOTE: input must be an object as described by JSON spec. Arbitrary
* JS objects (e.g. {a: () => 42}) may result in unexpected output.
* MOREOVER, it removes keys with empty objects/arrays as value (see
* examples bellow).
*
* @example
* // returns {a:1, 'b.0.c': 2, 'b.0.d.e': 3, 'b.1': 4}
* flatten({a: 1, b: [{c: 2, d: {e: 3}}, 4]})
* // returns {a:1, 'b.0.c': 2, 'b.0.d.e.0': true, 'b.0.d.e.1': false, 'b.0.d.e.2.f': 1}
* flatten({a: 1, b: [{c: 2, d: {e: [true, false, {f: 1}]}}]})
* // return {a: 1}
* flatten({a: 1, b: [], c: {}})
*
* @param obj item to be flattened
* @param {Array.string} [prefix=[]] chain of prefix joined with a dot and prepended to key
* @param {Object} [current={}] result of flatten during the recursion
*
* @see https://docs.mongodb.com/manual/core/document/#dot-notation
*/
function flatten (obj, prefix, current) {
prefix = prefix || []
current = current || {}
// Remember kids, null is also an object!
if (typeof (obj) === 'object' && obj !== null) {
Object.keys(obj).forEach(key => {
this.flatten(obj[key], prefix.concat(key), current)
})
} else {
current[prefix.join('.')] = obj
}
return current
}
Features and/or caveats
{a: () => {}}
you might not get what you wanted!{a: {}, b: []}
is flattened to {}
.Easiest solution to force UTF-8 encoding in Spring MVC returning String:
In @RequestMapping
, use:
produces = MediaType.APPLICATION_JSON_VALUE + "; charset=utf-8"
Generally git pull
is enough, but I'm not sure what layout you have chosen (or has github chosen for you).
try,
str_list = " ".join([str(ele) for ele in numlist])
this statement will give you each element of your list in string
format
print("The list now looks like [{0}]".format(str_list))
and,
change print(numlist.pop(2)+" has been removed")
to
print("{0} has been removed".format(numlist.pop(2)))
as well.
To add a header just add the following code to the location block where you want to add the header:
location some-location {
add_header X-my-header my-header-content;
}
Obviously, replace the x-my-header and my-header-content with what you want to add. And that's all there is to it.
INNER JOIN: Returns all rows when there is at least one match in BOTH tables
LEFT JOIN: Return all rows from the left table, and the matched rows from the right table
RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table
FULL JOIN: Return all rows when there is a match in ONE of the tables
Leave visible columns before filling the GridView
. Fill the GridView
and then hide the columns.
No, it sets all members/elements that haven't been explicitly set to their default-initialisation value, which is zero for numeric types.
#pragma comment(lib,"ntdll.lib")
EXTERN_C NTSTATUS NTAPI NtSuspendProcess(IN HANDLE ProcessHandle);
void SuspendSelf(){
NtSuspendProcess(GetCurrentProcess());
}
ntdll contains the exported function NtSuspendProcess, pass the handle to a process to do the trick.
I had this issue as well. The solution is (if you are on Windows as I am) to change the path to C:\PROGRA~1\Android\android-sdk-windows\
.
Assuming Program Files
is the first directory with the word PROGRAM in it which it should be. This worked.
Using parameter binding is definitely the way to go here. Not only is it very quick to write (just add [Parameter(Mandatory=$true)]
above your mandatory parameters), but it's also the only option that you won't hate yourself for later.
More below:
[Console]::ReadLine
is explicitly forbidden by the FxCop rules for PowerShell. Why? Because it only works in PowerShell.exe, not PowerShell ISE, PowerGUI, etc.
Read-Host is, quite simply, bad form. Read-Host uncontrollably stops the script to prompt the user, which means that you can never have another script that includes the script that uses Read-Host.
You're trying to ask for parameters.
You should use the [Parameter(Mandatory=$true)]
attribute, and correct typing, to ask for the parameters.
If you use this on a [SecureString]
, it will prompt for a password field. If you use this on a Credential type, ([Management.Automation.PSCredential]
), the credentials dialog will pop up, if the parameter isn't there. A string will just become a plain old text box. If you add a HelpMessage to the parameter attribute (that is, [Parameter(Mandatory = $true, HelpMessage = 'New User Credentials')]
) then it will become help text for the prompt.
I realise this is an old post but this might benefit somebody who, like me, has come to this page from a google search and is at their wits end.
None of the other answers given here worked for me and I had already given up hope, but today I was searching for a solution to another similar problem with divs, which I found answered multiple times on SO. The accepted answer worked for my div, and I had the sudden notion to try it for my previous textbox issue - and it worked! The solution:
add box-sizing: border-box
to the style of the textbox.
To add this to all multi-line textboxes using CSS, add the following to your style sheet:
textarea
{
box-sizing: border-box;
}
Thanks to thirtydot for the solution at
and
Content of div is longer then div itself when width is set to 100%?
type MyProps = {
workoutType: string | null;
};
case_when
is now a pretty clean implementation of the SQL-style case when:
structure(list(a = c(1, 3, 4, 6, 3, 2, 5, 1), b = c(1, 3, 4,
2, 6, 7, 2, 6), c = c(6, 3, 6, 5, 3, 6, 5, 3), d = c(6, 2, 4,
5, 3, 7, 2, 6), e = c(1, 2, 4, 5, 6, 7, 6, 3), f = c(2, 3, 4,
2, 2, 7, 5, 2)), .Names = c("a", "b", "c", "d", "e", "f"), row.names = c(NA,
8L), class = "data.frame") -> df
df %>%
mutate( g = case_when(
a == 2 | a == 5 | a == 7 | (a == 1 & b == 4 ) ~ 2,
a == 0 | a == 1 | a == 4 | a == 3 | c == 4 ~ 3
))
Using dplyr 0.7.4
The manual: http://dplyr.tidyverse.org/reference/case_when.html
Here is another option.
os.scandir(path='.')
It returns an iterator of os.DirEntry objects corresponding to the entries (along with file attribute information) in the directory given by path.
Example:
with os.scandir(path) as it:
for entry in it:
if not entry.name.startswith('.'):
print(entry.name)
Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type or file attribute information, because os.DirEntry objects expose this information if the operating system provides it when scanning a directory. All os.DirEntry methods may perform a system call, but is_dir() and is_file() usually only require a system call for symbolic links; os.DirEntry.stat() always requires a system call on Unix but only requires one for symbolic links on Windows.
This is a common issue.
one of the easiest way to solve is to check if the special character is reaching inside the action layer and then modifying the special character in the java code.
If you are able to view this character in Action or any other java layer of your choice (Like business layer), just replace the character with corresponding HTML character using the StringEscapeUtils.html#escapeHtml
After doing the escape. use the new string to save to the DB.
Define a class like this :
public class myclass {
string id ;
string title ;
string content;
}
public class program {
public void Main () {
List<myclass> objlist = new List<myclass> () ;
foreach (var value in objlist) {
TextBox1.Text = value.id ;
TextBox2.Text= value.title;
TextBox3.Text= value.content ;
}
}
}
I tried to draw a sketch and you can improve it in many ways. Instead of defining class "myclass", you can define struct.
override
is a C++11 keyword which means that a method is an "override" from a method from a base class. Consider this example:
class Foo
{
public:
virtual void func1();
}
class Bar : public Foo
{
public:
void func1() override;
}
If B::func1()
signature doesn't equal A::func1()
signature a compilation error will be generated because B::func1()
does not override A::func1()
, it will define a new method called func1()
instead.
$("**:**input[type=text], :input[type='textarea']").css({width: '90%'});
You could use ng-init in an outer div:
<div ng-init="param='value';">
<div ng-controller="BasketController" >
<label>param: {{value}}</label>
</div>
</div>
The parameter will then be available in your controller's scope:
function BasketController($scope) {
console.log($scope.param);
}
ERR_CACHE_MISS
error solutionyou just need add one line code <uses-permission android:name="android.permission.INTERNET"/>
in your app/src/main/AndroidManifest.xml
file as below screenshots shows.
All of the other answers were either deprecated or didn't work for HttpClient 4.3.
Here is a way to allow all hostnames when building an http client.
CloseableHttpClient httpClient = HttpClients
.custom()
.setHostnameVerifier(new AllowAllHostnameVerifier())
.build();
Or if you are using version 4.4 or later, the updated call looks like this:
CloseableHttpClient httpClient = HttpClients
.custom()
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.build();
Give a class .border-lb
and give this CSS
.border-lb {border: 1px solid #ccc; border-width: 0 0 1px 1px;}
And the HTML
<table width="770">
<tr>
<td class="border-lb">picture (border only to the left and bottom ) </td>
<td>text</td>
</tr>
<tr>
<td>text</td>
<td class="border-lb">picture (border only to the left and bottom) </td>
</tr>
</table>
The only way I got this to work on my machine was to do it this way:
# Ignore all directories, and all sub-directories, and it's contents:
*/*
#Now ignore all files in the current directory
#(This fails to ignore files without a ".", for example
#'file.txt' works, but
#'file' doesn't):
/*.*
#Only Include these specific directories and subdirectories:
!wordpress/
!wordpress/*/
!wordpress/*/wp-content/
!wordpress/*/wp-content/themes/
Notice how you have to explicitly allow content for each level you want to include. So if I have subdirectories 5 deep under themes, I still need to spell that out.
This is from @Yarin's comment here: https://stackoverflow.com/a/5250314/1696153
These were useful topics:
I also tried
*
*/*
**/**
and **/wp-content/themes/**
or /wp-content/themes/**/*
None of that worked for me, either. Lots of trail and error!
Don't know why @Janos deleted his answer, but it's correct: your data frame Train
doesn't have a column named pre
. When you pass a formula and a data frame to a model-fitting function, the names in the formula have to refer to columns in the data frame. Your Train
has columns called residual.sugar
, total.sulfur
, alcohol
and quality
. You need to change either your formula or your data frame so they're consistent with each other.
And just to clarify: Pre
is an object containing a formula. That formula contains a reference to the variable pre
. It's the latter that has to be consistent with the data frame.
The other answers work well, but since you asked for a solution using just the bash shell, you can do this:
AirBoxOmega:~ d$ cat > file #First we'll create a basic CSV
a,b,c,d,e,f,g,h,i,k
1,2,3,4,5,6,7,8,9,10
a,b,c,d,e,f,g,h,i,k
1,2,3,4,5,6,7,8,9,10
a,b,c,d,e,f,g,h,i,k
1,2,3,4,5,6,7,8,9,10
a,b,c,d,e,f,g,h,i,k
1,2,3,4,5,6,7,8,9,10
a,b,c,d,e,f,g,h,i,k
1,2,3,4,5,6,7,8,9,10
a,b,c,d,e,f,g,h,i,k
1,2,3,4,5,6,7,8,9,10
And then you can pull out columns (the first in this example) like so:
AirBoxOmega:~ d$ while IFS=, read -a csv_line;do echo "${csv_line[0]}";done < file
a
1
a
1
a
1
a
1
a
1
a
1
So there's a couple of things going on here:
while IFS=,
- this is saying to use a comma as the IFS (Internal Field Separator), which is what the shell uses to know what separates fields (blocks of text). So saying IFS=, is like saying "a,b" is the same as "a b" would be if the IFS=" " (which is what it is by default.)
read -a csv_line;
- this is saying read in each line, one at a time and create an array where each element is called "csv_line" and send that to the "do" section of our while loop
do echo "${csv_line[0]}";done < file
- now we're in the "do" phase, and we're saying echo the 0th element of the array "csv_line". This action is repeated on every line of the file. The < file
part is just telling the while loop where to read from. NOTE: remember, in bash, arrays are 0 indexed, so the first column is the 0th element.
So there you have it, pulling out a column from a CSV in the shell. The other solutions are probably more practical, but this one is pure bash.
Using the OCI8 extension to access Oracle Database. So Download php_oci8.dll from 1https://pecl.php.net/package/oci8/2.0.8/windows. (5.6 Thread Safe (TS) x86 ) php_oci8.dll must be the same version with your php version.Then unzipped it and you will find
1.php_oci8.dll
2.php_oci8_11g.dll (as per your oralce version) these two file pasted into your
(xampp\php\ext) folder.
Open your php.ini file and add these extension=php_oci8.dll extension=php_oci8_11g.dll
Check your oracle version and service name using these commands
show parameter service_name; service_name is orcl (you should remember this service name)
After downloading instantclient_11_1 unzipped it and then pasted in your Local Disk. And copy the path C:\instantclient_11_1 and then set this path as your user variable & system variable. Note is that my code is working without setting path variable.
Open your cmd and enter into SQL, create your schema following these commands
grant connect,resource to dbname;
Create table user_info and insert data into your table and commit out. Note: you must commit your data either data is not inserted.
<html>_x000D_
<head><title>Oracle demo</title></head>_x000D_
<body>_x000D_
<?php_x000D_
_x000D_
// Create connection to Oracle_x000D_
$conn = oci_connect("dbname", "pass123", "//localhost/orcl"); // orcl is your service_name_x000D_
_x000D_
$query = 'select * from user_info';_x000D_
$stid = oci_parse($conn, $query);_x000D_
$r = oci_execute($stid);_x000D_
_x000D_
// Fetch each row in an associative array_x000D_
print '<table border="1">';_x000D_
while ($row = oci_fetch_array($stid, OCI_RETURN_NULLS+OCI_ASSOC)) {_x000D_
print '<tr>';_x000D_
foreach ($row as $item) {_x000D_
print '<td>'.($item !== null ? htmlentities($item, ENT_QUOTES) : ' ').'</td>';_x000D_
}_x000D_
print '</tr>';_x000D_
}_x000D_
print '</table>';
_x000D_
Just declare the variable at the starting of a class.
e.g. for string variable:
public partial class Login : System.Web.UI.Page
{
public string sError;
protected void Page_Load(object sender, EventArgs e)
{
//Page Load Code
}
According to the Microsoft documentation, the TimeSpan structure exposes Hours, Minutes, Seconds, and Milliseconds as integer members. Maybe you want something like:
dateDifference.Hours.ToString() + " hrs, " + dateDifference.Minutes.ToString() + " mins, " + dateDifference.Seconds.ToString() + " secs"
Postgres documentation describes the differences between UUID
s. A couple of them:
V3:
uuid_generate_v3(namespace uuid, name text)
- This function generates a version 3 UUID in the given namespace using the specified input name.
V4:
uuid_generate_v4
- This function generates a version 4 UUID, which is derived entirely from random numbers.
You can use disabled attribute to disable the textbox.
document.getElementById('color').disabled = true;
For those who can not figure out this in instructions from this answer there:
Try to set padding value more then 0, if child divs have margin-top or margin-bottom you can replace it with padding
For example if you have
#childRightCol
{
margin-top: 30px;
}
#childLeftCol
{
margin-bottom: 20px;
}
it'll be better to replace it with:
#parent
{
padding: 30px 0px 20px 0px;
}
This is for cases that you want to use interpolated strings. I'm actually posting this because I'm tired of trial and error and eventually scrolling through tons of docs every time I need to format some scalar.
$"{1234.5678:0.00}" "1234.57" 2 decimal places, notice that value is rounded
$"{1234.5678,10:0.00}" " 1234.57" right-aligned
$"{1234.5678,-10:0.00}" "1234.57 " left-aligned
$"{1234.5678:0.#####}" "1234.5678" 5 optional digits after the decimal point
$"{1234.5678:0.00000}" "1234.56780" 5 forced digits AFTER the decimal point, notice the trailing zero
$"{1234.5678:00000.00}" "01234.57" 5 forced digits BEFORE the decimal point, notice the leading zero
$"{1234.5612:0}" "1235" as integer, notice that value is rounded
$"{1234.5678:F2}" "1234.57" standard fixed-point
$"{1234.5678:F5}" "1234.56780" 5 digits after the decimal point, notice the trailing zero
$"{1234.5678:g2}" "1.2e+03" standard general with 2 meaningful digits, notice "e"
$"{1234.5678:G2}" "1.2E+03" standard general with 2 meaningful digits, notice "E"
$"{1234.5678:G3}" "1.23E+03" standard general with 3 meaningful digits
$"{1234.5678:G5}" "1234.6" standard general with 5 meaningful digits
$"{1234.5678:e2}" "1.23e+003" standard exponential with 2 digits after the decimal point, notice "e"
$"{1234.5678:E3}" "1.235E+003" standard exponential with 3 digits after the decimal point, notice "E"
$"{1234.5678:N2}" "1,234.57" standard numeric, notice the comma
$"{1234.5678:C2}" "$1,234.57" standard currency, notice the dollar sign
$"{1234.5678:P2}" "123,456.78 %" standard percent, notice that value is multiplied by 100
$"{1234.5678:2}" "2" :)
Performance Warning
Interpolated strings are slow. In my experience this is the order (fast to slow):
value.ToString(format)+" blah blah"
string.Format("{0:format} blah blah", value)
$"{value:format} blah blah"
You can use the counter and array length.
$array = array(1,2,3,4); $i = 0; $len = count($array); foreach ($array as $item) { if ($i === 0) { // first } else if ($i === $len - 1) { // last } // … $i++; }
If you want to make sure the HTML file doesn't contain any PHP code and will not be executed as PHP, do not use include
or require
. Simply do:
echo file_get_contents("/path/to/file.html");
If you want to keep the height of the DIV absolute, regardless of the amount of text inside use the following:
overflow: hidden;
Incase you want to mimic what php function htmlspecialchars_decode does use php function get_html_translation_table() to dump the table and then use the java code like,
static Map<String,String> html_specialchars_table = new Hashtable<String,String>();
static {
html_specialchars_table.put("<","<");
html_specialchars_table.put(">",">");
html_specialchars_table.put("&","&");
}
static String htmlspecialchars_decode_ENT_NOQUOTES(String s){
Enumeration en = html_specialchars_table.keys();
while(en.hasMoreElements()){
String key = en.nextElement();
String val = html_specialchars_table.get(key);
s = s.replaceAll(key, val);
}
return s;
}
As of 2018 there is a much shorter and elegant solution. Just use. Array.prototype.sort().
Example:
var items = [
{ name: 'Edward', value: 21 },
{ name: 'Sharpe', value: 37 },
{ name: 'And', value: 45 },
{ name: 'The', value: -12 },
{ name: 'Magnetic', value: 13 },
{ name: 'Zeros', value: 37 }
];
// sort by value
items.sort(function (a, b) {
return a.value - b.value;
});
if you give a 2D array to the plot function of matplotlib it will assume the columns to be lines:
If x and/or y is 2-dimensional, then the corresponding columns will be plotted.
In your case your shape is not accepted (100, 1, 1, 8000). As so you can using numpy squeeze to solve the problem quickly:
np.squeez doc: Remove single-dimensional entries from the shape of an array.
import numpy as np
import matplotlib.pyplot as plt
data = np.random.randint(3, 7, (10, 1, 1, 80))
newdata = np.squeeze(data) # Shape is now: (10, 80)
plt.plot(newdata) # plotting by columns
plt.show()
But notice that 100 sets of 80 000 points is a lot of data for matplotlib. I would recommend that you look for an alternative. The result of the code example (run in Jupyter) is:
You can use this in your MySQL WHERE clause to return records that were created within the last 7 days/week:
created >= DATE_SUB(CURDATE(),INTERVAL 7 day)
Also use NOW() in the subtraction to give hh:mm:ss resolution. So to return records created exactly (to the second) within the last 24hrs, you could do:
created >= DATE_SUB(NOW(),INTERVAL 1 day)
Note: Do not implement this in production code you are ever going to use on a network you do not entirely trust. Especially anything going over the public internet.
Your question is just what I want to know. After I did some searches, the conclusion is as follows.
In HttpClient way, you should create a custom class from org.apache.http.conn.ssl.SSLSocketFactory, not the one org.apache.http.conn.ssl.SSLSocketFactory itself. Some clues can be found in this post Custom SSL handling stopped working on Android 2.2 FroYo.
An example is like ...
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.conn.ssl.SSLSocketFactory;
public class MySSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");
public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(truststore);
TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sslContext.init(null, new TrustManager[] { tm }, null);
}
@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
}
@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
}
and use this class while creating instance of HttpClient.
public HttpClient getNewHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}
BTW, the link below is for someone who is looking for HttpURLConnection solution. Https Connection Android
I have tested the above two kinds of solutions on froyo, and they all work like a charm in my cases. Finally, using HttpURLConnection may face the redirect problems, but this is beyond the topic.
Note: Before you decide to trust all certificates, you probably should know the site full well and won't be harmful of it to end-user.
Indeed, the risk you take should be considered carefully, including the effect of hacker's mock site mentioned in the following comments that I deeply appreciated. In some situation, although it might be hard to take care of all certificates, you'd better know the implicit drawbacks to trust all of them.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/foobar/i$ index.php [NE,L]
@Lyle's answer is rather dangerous and I have seen it not work particularly if you make the enum a static inner class. Instead I have used something like this which will load the BootstrapSingleton maps before the enums.
Edit this should not be a problem any more with modern JVMs (JVM 1.6 or greater) but I do think there are still issues with JRebel but I haven't had a chance to retest it.
Load me first:
public final class BootstrapSingleton {
// Reverse-lookup map for getting a day from an abbreviation
public static final Map<String, Day> lookup = new HashMap<String, Day>();
}
Now load it in the enum constructor:
public enum Day {
MONDAY("M"), TUESDAY("T"), WEDNESDAY("W"),
THURSDAY("R"), FRIDAY("F"), SATURDAY("Sa"), SUNDAY("Su"), ;
private final String abbreviation;
private Day(String abbreviation) {
this.abbreviation = abbreviation;
BootstrapSingleton.lookup.put(abbreviation, this);
}
public String getAbbreviation() {
return abbreviation;
}
public static Day get(String abbreviation) {
return lookup.get(abbreviation);
}
}
If you have an inner enum you can just define the Map above the enum definition and that (in theory) should get loaded before.
I was about to ask the very same question. After searching a bit further and decyphering part of webpack's documentation I think that what you want is the output.library
and output.libraryTarget
in the webpack.config.js
file.
For example:
js/index.js:
var foo = 3;
var bar = true;
webpack.config.js
module.exports = {
...
entry: './js/index.js',
output: {
path: './www/js/',
filename: 'index.js',
library: 'myLibrary',
libraryTarget: 'var'
...
}
Now if you link the generated www/js/index.js
file in a html script tag you can access to myLibrary.foo
from anywhere in your other scripts.
Follow these steps if you're on openSuse or SUSE.
Install php7 if it's not already installed.
zypper in php7
If you have php7 installed, update it with:
zypper update php7
Install php7-sockets
zypper in php7-sockets
Most probably, AllowOverride is set to None. in Directory section of apache2.conf located in /etc/apache2 folder
Try setting it to AllowOverride All
If you are doing this in browser there are no character encoding libraries built-in, but you can get by with:
function pad(n) {
return n.length < 2 ? "0" + n : n;
}
var array = new Uint8Array(data);
var str = "";
for( var i = 0, len = array.length; i < len; ++i ) {
str += ( "%" + pad(array[i].toString(16)))
}
str = decodeURIComponent(str);
Here's a demo that decodes a 3-byte UTF-8 unit: http://jsfiddle.net/Z9pQE/
Don't expect sprintf (or any other function with varargs) to automatically cast anything. The compiler doesn't try to read the format string and do the cast for you; at runtime, sprintf has no meta-information available to determine what is on the stack; it just pops bytes and interprets them as given by the format string. sprintf(myvar, "%0", 0); immediately segfaults.
So: The format strings and the other arguments must match!
There is a special entry on the official training section of Android about this: http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html
The section is quite new, it was not there when the question was asked.
The suggested solution is to use a LruCache. That class was introduced on Honeycomb, but it is also included on the compatibility library.
You can initialize a LruCache by setting the maximum number or entries and it will automatically sort them your you and clean them less used ones when you go over the limit. Other than that it is used as a normal Map.
The sample code from the official page:
private LruCache mMemoryCache;
@Override
protected void onCreate(Bundle savedInstanceState) {
...
// Get memory class of this device, exceeding this amount will throw an
// OutOfMemory exception.
final int memClass = ((ActivityManager) context.getSystemService(
Context.ACTIVITY_SERVICE)).getMemoryClass();
// Use 1/8th of the available memory for this memory cache.
final int cacheSize = 1024 * 1024 * memClass / 8;
mMemoryCache = new LruCache(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
// The cache size will be measured in bytes rather than number of items.
return bitmap.getByteCount();
}
};
...
}
public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
if (getBitmapFromMemCache(key) == null) {
mMemoryCache.put(key, bitmap);
}
}
public Bitmap getBitmapFromMemCache(String key) {
return mMemoryCache.get(key);
}
Previously SoftReferences were a good alternative, but not anymore, quoting from the official page:
Note: In the past, a popular memory cache implementation was a SoftReference or WeakReference bitmap cache, however this is not recommended. Starting from Android 2.3 (API Level 9) the garbage collector is more aggressive with collecting soft/weak references which makes them fairly ineffective. In addition, prior to Android 3.0 (API Level 11), the backing data of a bitmap was stored in native memory which is not released in a predictable manner, potentially causing an application to briefly exceed its memory limits and crash.
I ended up making my own, I find that it works better the other solutions that were around.
call your (windows-)git with cygpath
as parameter, in order to convert the "calling path". I m confused why that should be a problem.
Another solution:
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.5.201505241946</version>
<executions>
<execution>
<id>default-prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>default-report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
<execution>
<id>default-check</id>
<goals>
<goal>check</goal>
</goals>
<configuration>
<rules>
<rule implementation="org.jacoco.maven.RuleConfiguration">
<excludes>
<exclude>com.mypackage1</exclude
<exclude>com.mypackage2</exclude>
</excludes>
<element>PACKAGE</element>
<limits>
<limit implementation="org.jacoco.report.check.Limit">
<counter>COMPLEXITY</counter>
<value>COVEREDRATIO</value>
<minimum>0.85</minimum>
</limit>
</limits>
</rule>
</rules>
</configuration>
</execution>
</executions>
</plugin>
Please note that, we are using "<element>PACKAGE</element>"
in the configuration which then helps us to exclude at package level.
You can always use the plot()
function like so:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
ys = [i+x+(i*x)**2 for i in range(10)]
plt.figure()
for y in ys:
plt.plot(x, y, 'o')
plt.show()
For Redmi and Mi devices turn off MIUI Optimization
Settings > Additional Settings > Developer Options > MIUI Optimization
In addition... I was playing around with various libs in my test and noticed their different handling of 4xx requests. In this case my test returns a json object with a 400 response. This is how 3 popular libs handle the response:
// request-promise-native
const body = request({ url: url, json: true })
const res = await t.throws(body);
console.log(res.error)
// node-fetch
const body = await fetch(url)
console.log(await body.json())
// Axios
const body = axios.get(url)
const res = await t.throws(body);
console.log(res.response.data)
Of interest is that request-promise-native
and axios
throw on 4xx response while node-fetch
doesn't. Also fetch
uses a promise for json parsing.
This function is using in yii framework for ajax call check.
public function isAjax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest';
}
It denotes an rvalue reference. Rvalue references will only bind to temporary objects, unless explicitly generated otherwise. They are used to make objects much more efficient under certain circumstances, and to provide a facility known as perfect forwarding, which greatly simplifies template code.
In C++03, you can't distinguish between a copy of a non-mutable lvalue and an rvalue.
std::string s;
std::string another(s); // calls std::string(const std::string&);
std::string more(std::string(s)); // calls std::string(const std::string&);
In C++0x, this is not the case.
std::string s;
std::string another(s); // calls std::string(const std::string&);
std::string more(std::string(s)); // calls std::string(std::string&&);
Consider the implementation behind these constructors. In the first case, the string has to perform a copy to retain value semantics, which involves a new heap allocation. However, in the second case, we know in advance that the object which was passed in to our constructor is immediately due for destruction, and it doesn't have to remain untouched. We can effectively just swap the internal pointers and not perform any copying at all in this scenario, which is substantially more efficient. Move semantics benefit any class which has expensive or prohibited copying of internally referenced resources. Consider the case of std::unique_ptr
- now that our class can distinguish between temporaries and non-temporaries, we can make the move semantics work correctly so that the unique_ptr
cannot be copied but can be moved, which means that std::unique_ptr
can be legally stored in Standard containers, sorted, etc, whereas C++03's std::auto_ptr
cannot.
Now we consider the other use of rvalue references- perfect forwarding. Consider the question of binding a reference to a reference.
std::string s;
std::string& ref = s;
(std::string&)& anotherref = ref; // usually expressed via template
Can't recall what C++03 says about this, but in C++0x, the resultant type when dealing with rvalue references is critical. An rvalue reference to a type T, where T is a reference type, becomes a reference of type T.
(std::string&)&& ref // ref is std::string&
(const std::string&)&& ref // ref is const std::string&
(std::string&&)&& ref // ref is std::string&&
(const std::string&&)&& ref // ref is const std::string&&
Consider the simplest template function- min and max. In C++03 you have to overload for all four combinations of const and non-const manually. In C++0x it's just one overload. Combined with variadic templates, this enables perfect forwarding.
template<typename A, typename B> auto min(A&& aref, B&& bref) {
// for example, if you pass a const std::string& as first argument,
// then A becomes const std::string& and by extension, aref becomes
// const std::string&, completely maintaining it's type information.
if (std::forward<A>(aref) < std::forward<B>(bref))
return std::forward<A>(aref);
else
return std::forward<B>(bref);
}
I left off the return type deduction, because I can't recall how it's done offhand, but that min can accept any combination of lvalues, rvalues, const lvalues.
Here is the code for get value of checked radio button and set radio button checked according to it's value in edit form:
Controller:
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
CommonServiceReference.tbl_user user = new CommonServiceReference.tbl_user();
user.user_gender = collection["rdbtnGender"];
return RedirectToAction("Index");
}
catch(Exception e)
{
throw e;
}
}
public ActionResult Edit(int id)
{
CommonServiceReference.ViewUserGroup user = clientObj.getUserById(id);
ViewBag.UserObj = user;
return View();
}
VIEW:
Create:
<input type="radio" id="rdbtnGender1" name="rdbtnGender" value="Male" required>
<label for="rdbtnGender1">MALE</label>
<input type="radio" id="rdbtnGender2" name="rdbtnGender" value="Female" required>
<label for="rdbtnGender2">FEMALE</label>
Edit:
<input type="radio" id="rdbtnGender1" name="rdbtnGender" value="Male" @(ViewBag.UserObj.user_gender == "Male" ? "checked='true'" : "") required>
<label for="rdbtnGender1">MALE</label>
<input type="radio" id="rdbtnGender2" name="rdbtnGender" value="Female" @(ViewBag.UserObj.user_gender == "Female" ? "checked='true'" : "") required>
<label for="rdbtnGender2">FEMALE</label>
I also had this problem. I had some Portuguese text with some special characters, but these characters where already in unicode format (ex.: \u00e3
).
So I want to convert S\u00e3o
to São
.
I did it using the apache commons StringEscapeUtils. As @sorin-sbarnea said. Can be downloaded here.
Use the method unescapeJava
, like this:
String text = "S\u00e3o"
text = StringEscapeUtils.unescapeJava(text);
System.out.println("text " + text);
(There is also the method escapeJava
, but this one puts the unicode characters in the string.)
If any one knows a solution on pure Java, please tell us.
this.Controls["name"];
This is the actual code that is ran:
public virtual Control this[string key]
{
get
{
if (!string.IsNullOrEmpty(key))
{
int index = this.IndexOfKey(key);
if (this.IsValidIndex(index))
{
return this[index];
}
}
return null;
}
}
vs:
public Control[] Find(string key, bool searchAllChildren)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException("key", SR.GetString("FindKeyMayNotBeEmptyOrNull"));
}
ArrayList list = this.FindInternal(key, searchAllChildren, this, new ArrayList());
Control[] array = new Control[list.Count];
list.CopyTo(array, 0);
return array;
}
private ArrayList FindInternal(string key, bool searchAllChildren, Control.ControlCollection controlsToLookIn, ArrayList foundControls)
{
if ((controlsToLookIn == null) || (foundControls == null))
{
return null;
}
try
{
for (int i = 0; i < controlsToLookIn.Count; i++)
{
if ((controlsToLookIn[i] != null) && WindowsFormsUtils.SafeCompareStrings(controlsToLookIn[i].Name, key, true))
{
foundControls.Add(controlsToLookIn[i]);
}
}
if (!searchAllChildren)
{
return foundControls;
}
for (int j = 0; j < controlsToLookIn.Count; j++)
{
if (((controlsToLookIn[j] != null) && (controlsToLookIn[j].Controls != null)) && (controlsToLookIn[j].Controls.Count > 0))
{
foundControls = this.FindInternal(key, searchAllChildren, controlsToLookIn[j].Controls, foundControls);
}
}
}
catch (Exception exception)
{
if (ClientUtils.IsSecurityOrCriticalException(exception))
{
throw;
}
}
return foundControls;
}
You're all doing too much work:
right(str(100+@x),2)
-- for a function, same idea:
--
create function zeroPad( @yourNum int, @wid int)
as
begin
return right( 1000000+@yourNum), @wid)
end
Using PostgreSQL 9.6.x with official Java driver 42.2.4
:
...myPreparedStatement.execute...
myPreparedStatement.toString()
Will show the SQL with the ?
already replaced, which is what I was looking for.
Just added this answer to cover the postgres case.
I would never have thought it could be so simple.
EDITED MARCH 2019 now with programmatic pin color,
PURE JAVASCRIPT, NO IMAGES, SUPPORTS LABELS
no longer relies on deprecated Charts API
var pinColor = "#FFFFFF";
var pinLabel = "A";
// Pick your pin (hole or no hole)
var pinSVGHole = "M12,11.5A2.5,2.5 0 0,1 9.5,9A2.5,2.5 0 0,1 12,6.5A2.5,2.5 0 0,1 14.5,9A2.5,2.5 0 0,1 12,11.5M12,2A7,7 0 0,0 5,9C5,14.25 12,22 12,22C12,22 19,14.25 19,9A7,7 0 0,0 12,2Z";
var labelOriginHole = new google.maps.Point(12,15);
var pinSVGFilled = "M 12,2 C 8.1340068,2 5,5.1340068 5,9 c 0,5.25 7,13 7,13 0,0 7,-7.75 7,-13 0,-3.8659932 -3.134007,-7 -7,-7 z";
var labelOriginFilled = new google.maps.Point(12,9);
var markerImage = { // https://developers.google.com/maps/documentation/javascript/reference/marker#MarkerLabel
path: pinSVGFilled,
anchor: new google.maps.Point(12,17),
fillOpacity: 1,
fillColor: pinColor,
strokeWeight: 2,
strokeColor: "white",
scale: 2,
labelOrigin: labelOriginFilled
};
var label = {
text: pinLabel,
color: "white",
fontSize: "12px",
}; // https://developers.google.com/maps/documentation/javascript/reference/marker#Symbol
this.marker = new google.maps.Marker({
map: map.MapObject,
//OPTIONAL: label: label,
position: this.geographicCoordinates,
icon: markerImage,
//OPTIONAL: animation: google.maps.Animation.DROP,
});
I used below layout and able to achieve custom layout in Navigation View.
<android.support.design.widget.NavigationView
android:id="@+id/navi_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start|top"
android:background="@color/navigation_view_bg_color"
app:theme="@style/NavDrawerTextStyle">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="@layout/drawer_header" />
<include layout="@layout/navigation_drawer_menu" />
</LinearLayout>
</android.support.design.widget.NavigationView>
Your approach is dependent on Java's ArrayList#toString() implementation.
While the implementation is documented in the Java API and very unlikely to change, there's a chance it could. It's far more reliable to implement this yourself (loops, StringBuilders, recursion whatever you like better).
Sure this approach may seem "neater" or more "too sweet" or "money" but it is, in my opinion, a worse approach.
This works for me:
ListBox x = new ListBox();
x.Items.Add(new ListItem("Hello", "1"));
x.Items.Add(new ListItem("Bye", "2"));
Console.Write(x.Items[0].Value);
You need to switch your values:
/* No greater than 900px, no less than 400px */
@media (max-width:900px) and (min-width:400px) {
.foo {
display:none;
}
}?
Demo: http://jsfiddle.net/xf6gA/ (using background color, so it's easier to confirm)
Try dashed...
<hr style="border-top: 2px dashed black;color:transparent;"/>
Another option is to use
#include <process.h>
system("pause");
Though this is not very portable because it will only work on Windows, but it will automatically print
Press any key to continue...
Chrome did change their menus since this question was asked. This solution was tested with Chrome 47.0.2526.73 to 72.0.3626.109.
If you are using Chrome right now, you can check your version with : chrome://version
OLDER VERSIONS:
Scroll down to the bottom of the page and click on "Show advanced settings..." to show more settings.
OLDER VERSIONS:
In the "Network" section, click on "Change proxy settings...".
That's it.
Don't use exceptions for flow control. Use DateTime.TryParse and DateTime.TryParseExact. Personally I prefer TryParseExact with a specific format, but I guess there are times when TryParse is better. Example use based on your original code:
DateTime value;
if (!DateTime.TryParse(startDateTextBox.Text, out value))
{
startDateTextox.Text = DateTime.Today.ToShortDateString();
}
Reasons for preferring this approach:
I used this to change the background for my button
button.setBackground(getResources().getDrawable(R.drawable.primary_button));
"button" is the variable holding my Button, and the image am setting in the background is primary_button
There's a note on the ahpi.imgload.js plugin at the moment saying that it is currently broken, and to try this gist instead: https://gist.github.com/797120/7176db676f1e0e20d7c23933f9fc655c2f120c58
For Bootstrap version 3.1.1 and above, the best class for centering the content is the .center-block
helper class.
I disagree that the sieve of Atkin is the way to go, because it could easily take longer to check every number in [1,n] for primality than it would to reduce the number by divisions.
Here's some code that, although slightly hackier, is generally much faster:
import operator
# A slightly efficient superset of primes.
def PrimesPlus():
yield 2
yield 3
i = 5
while True:
yield i
if i % 6 == 1:
i += 2
i += 2
# Returns a dict d with n = product p ^ d[p]
def GetPrimeDecomp(n):
d = {}
primes = PrimesPlus()
for p in primes:
while n % p == 0:
n /= p
d[p] = d.setdefault(p, 0) + 1
if n == 1:
return d
def NumberOfDivisors(n):
d = GetPrimeDecomp(n)
powers_plus = map(lambda x: x+1, d.values())
return reduce(operator.mul, powers_plus, 1)
ps That's working python code to solve this problem.
You can use (':hidden') method to find if your div is visible or not.. Also its a good practice to cache a element if you are using it multiple times in your code..
$(".subpanel a").click(function()
{
var chatterNickname = $(this).text();
var $chatPanel = $("#singlechatpanel-1");
if(!$chatPanel.is(':hidden'))
{
alert("Room 1 is filled.");
$chatPanel.show();
$("#singlechatpanel-1 #chatter_nickname").html("Chatting with: " + chatterNickname);
}
});
You can write in this way
<string name="you_me">You & Me<string>
Output: You & Me
This solution is based on MSDN with some modifications I made.
It finds exact or PART of string and sets it.
private int lastMatch = 0;
private void textBoxSearch_TextChanged(object sender, EventArgs e)
{
// Set our intial index variable to -1.
int x = 0;
string match = textBoxSearch.Text;
// If the search string is empty set to begining of textBox
if (textBoxSearch.Text.Length != 0)
{
bool found = true;
while (found)
{
if (comboBoxSelect.Items.Count == x)
{
comboBoxSelect.SelectedIndex = lastMatch;
found = false;
}
else
{
comboBoxSelect.SelectedIndex = x;
match = comboBoxSelect.SelectedValue.ToString();
if (match.Contains(textBoxSearch.Text))
{
lastMatch = x;
found = false;
}
x++;
}
}
}
else
comboBoxSelect.SelectedIndex = 0;
}
I hope I helped!