It depends which version of Visual Studio:
Newer versions of Visual Studio support many versions of the .Net framework; check your project type and properties.
Those are just version designations (just like windows xp, vista or windows 7) which they are using to name their major releases, instead of using version numbers. so you'll want to use the newest eclipse version available, which is helios (or 3.6 which is the corresponding version number).
This way works for me.
# java -version 2>&1|awk '/version/ {gsub("\"","") ; print $NF}'
1.8.0_171
Try apachectl -V:
$ apachectl -V
Server version: Apache/2.2.9 (Unix)
Server built: Sep 18 2008 21:54:05
Server's Module Magic Number: 20051115:15
Server loaded: APR 1.2.7, APR-Util 1.2.7
Compiled using: APR 1.2.7, APR-Util 1.2.7
... etc ...
If it does not work for you, run the command with sudo
.
Use This method:
public static String getAndroidVersion() {
String versionName = "";
try {
versionName = String.valueOf(Build.VERSION.RELEASE);
} catch (Exception e) {
e.printStackTrace();
}
return versionName;
}
I just found another reason why to get this error. I cleaned my GAC from all versions of a specific library and built my project with reference to specific version deployed together with the executable. When I run the project I got this exception searching for a newer version of the library.
The reason was publisher policy. When I uninstalled library's versions from GAC I forgot to uninstall publisher policy assemblies as well so instead of using my locally deployed assembly the assembly loader found publisher policy in GAC which told it to search for a newer version.
This worked for me
PHP 7.2
AddHandler application/x-httpd-ea-php72 .php .php7 .phtml
PHP 7.3
AddHandler application/x-httpd-ea-php73 .php
For Linux, try following:
find . -name "YOUR_JAR_FILE.jar" -exec zipgrep "Implementation-Version:" '{}' \;|awk -F ': ' '{print $2}'
Although the question is "which version am I using?", this may not actually be everything you need to know. You may have other versions installed and this can cause problems, particularly when installing additional modules. This is my rough-and-ready approach to finding out what versions are installed:
updatedb # Be in root for this
locate site.py # All installations I've ever seen have this
The output for a single Python installation should look something like this:
/usr/lib64/python2.7/site.py
/usr/lib64/python2.7/site.pyc
/usr/lib64/python2.7/site.pyo
Multiple installations will have output something like this:
/root/Python-2.7.6/Lib/site.py
/root/Python-2.7.6/Lib/site.pyc
/root/Python-2.7.6/Lib/site.pyo
/root/Python-2.7.6/Lib/test/test_site.py
/usr/lib/python2.6/site-packages/site.py
/usr/lib/python2.6/site-packages/site.pyc
/usr/lib/python2.6/site-packages/site.pyo
/usr/lib64/python2.6/site.py
/usr/lib64/python2.6/site.pyc
/usr/lib64/python2.6/site.pyo
/usr/local/lib/python2.7/site.py
/usr/local/lib/python2.7/site.pyc
/usr/local/lib/python2.7/site.pyo
/usr/local/lib/python2.7/test/test_site.py
/usr/local/lib/python2.7/test/test_site.pyc
/usr/local/lib/python2.7/test/test_site.pyo
This is a helpful website listing the mapping for the latest releases of Chrome -
Wikipedia (or rather, the community on Wikipedia) keeps a pretty good up-to-date list here.
Based on Neeme Praks' answer, the below code should give you the version of eclipse ide you're running within.
In my case, I was running in an eclipse-derived product, so Neeme's answer just gave me the version of that product. The OP asked how to find the Eclipse version, whih is what I was after. Therefore I needed to make a couple of changes, leading me to this:
/**
* Attempts to get the version of the eclipse ide we're running in.
* @return the version, or null if it couldn't be detected.
*/
static Version getEclipseVersion() {
String product = "org.eclipse.platform.ide";
IExtensionRegistry registry = Platform.getExtensionRegistry();
IExtensionPoint point = registry.getExtensionPoint("org.eclipse.core.runtime.products");
if (point != null) {
IExtension[] extensions = point.getExtensions();
for (IExtension ext : extensions) {
if (product.equals(ext.getUniqueIdentifier())) {
IContributor contributor = ext.getContributor();
if (contributor != null) {
Bundle bundle = Platform.getBundle(contributor.getName());
if (bundle != null) {
return bundle.getVersion();
}
}
}
}
}
return null;
}
This will return you a convenient Version
, which can be compared thus:
private static final Version DESIRED_MINIMUM_VERSION = new Version("4.9"); //other constructors are available
boolean haveAtLeastMinimumDesiredVersion()
Version thisVersion = getEclipseVersion();
if (thisVersion == null) {
//we might have a problem
}
//returns a positive number if thisVersion is greater than the given parameter (desiredVersion)
return thisVersion.compareTo(DESIRED_MINIMUM_VERSION) >= 0;
}
After installing tomcat, you can choose "configure tomcat" by search in "search programs and files". After clicking on "configure Tomcat", you should give admin permissions and the window opens. Then click on "java" tab. There you can see the JVM and JAVA classpath.
While this isn't answering your question directly, I'm putting this here as google brought this page up first in my searches when I was looking for this info.
If you're using Visual Studio, you can right click on your project -> Properties -> Build -> Advanced This should list available versions as well as the one your proj is using.
You can try something like this:
package_version(R.version)
getRversion()
import numpy
print numpy.__version__
For Firefox, Chrome, Opera, Internet Explorer and Safari
var ua="Mozilla/1.22 (compatible; MSIE 10.0; Windows 3.1)";
//ua = navigator.userAgent;
var b;
var browser;
if(ua.indexOf("Opera")!=-1) {
b=browser="Opera";
}
if(ua.indexOf("Firefox")!=-1 && ua.indexOf("Opera")==-1) {
b=browser="Firefox";
// Opera may also contains Firefox
}
if(ua.indexOf("Chrome")!=-1) {
b=browser="Chrome";
}
if(ua.indexOf("Safari")!=-1 && ua.indexOf("Chrome")==-1) {
b=browser="Safari";
// Chrome always contains Safari
}
if(ua.indexOf("MSIE")!=-1 && (ua.indexOf("Opera")==-1 && ua.indexOf("Trident")==-1)) {
b="MSIE";
browser="Internet Explorer";
//user agent with MSIE and Opera or MSIE and Trident may exist.
}
if(ua.indexOf("Trident")!=-1) {
b="Trident";
browser="Internet Explorer";
}
// now for version
var version=ua.match(b+"[ /]+[0-9]+(.[0-9]+)*")[0];
console.log("broswer",browser);
console.log("version",version);
Image shown below. I'm only typing this because of a 30 character minimum imposed by Stackoverflow.
For me it was picking the default JVM v6 set in env vars.
Needed to explicitly add below in eclipse.ini to use v8 which is req by photon.
-vm
C:\Program Files\Java\jdk1.8.0_75\bin\javaw.exe
--launcher.appendVmargs
-vmargs
-Dosgi.requiredJavaVersion=1.8
NOTE : Add the entry of vm above the vm args else it will not work!
Just adding an answer because I came to this question to see the best way to include the version from package.json in my web application.
I know this question is targetted for Node.js however, if you are using Webpack to bundle your app just a reminder the recommended way is to use the DefinePlugin to declare a global version in the config and reference that. So you could do in your webpack.config.json
const pkg = require('../../package.json');
...
plugins : [
new webpack.DefinePlugin({
AppVersion: JSON.stringify(pkg.version),
...
And then AppVersion
is now a global that is available for you to use. Also make sure in your .eslintrc
you ignore this via the globals prop
The even simpler simplest way:
In Spyder, start a new "IPython Console", then run any of your existing scripts.
Now the version can be seen in the first output printed in the console window:
"Python 3.7.3 (default, Apr 24 2019, 15:29:51)..."
1)From OS level(UNIX):-
dataserver -v
2)From Syabse isql:-
select @@version
go
sp_version
go
This work fine for all Linux environment.
#!/bin/sh
cat /etc/*-release
In Ubuntu:
$ cat /etc/*-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=10.04
DISTRIB_CODENAME=lucid
DISTRIB_DESCRIPTION="Ubuntu 10.04.4 LTS"
or 12.04:
$ cat /etc/*-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=12.04
DISTRIB_CODENAME=precise
DISTRIB_DESCRIPTION="Ubuntu 12.04.4 LTS"
NAME="Ubuntu"
VERSION="12.04.4 LTS, Precise Pangolin"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu precise (12.04.4 LTS)"
VERSION_ID="12.04"
In RHEL:
$ cat /etc/*-release
Red Hat Enterprise Linux Server release 6.5 (Santiago)
Red Hat Enterprise Linux Server release 6.5 (Santiago)
Or Use this Script:
#!/bin/sh
# Detects which OS and if it is Linux then it will detect which Linux
# Distribution.
OS=`uname -s`
REV=`uname -r`
MACH=`uname -m`
GetVersionFromFile()
{
VERSION=`cat $1 | tr "\n" ' ' | sed s/.*VERSION.*=\ // `
}
if [ "${OS}" = "SunOS" ] ; then
OS=Solaris
ARCH=`uname -p`
OSSTR="${OS} ${REV}(${ARCH} `uname -v`)"
elif [ "${OS}" = "AIX" ] ; then
OSSTR="${OS} `oslevel` (`oslevel -r`)"
elif [ "${OS}" = "Linux" ] ; then
KERNEL=`uname -r`
if [ -f /etc/redhat-release ] ; then
DIST='RedHat'
PSUEDONAME=`cat /etc/redhat-release | sed s/.*\(// | sed s/\)//`
REV=`cat /etc/redhat-release | sed s/.*release\ // | sed s/\ .*//`
elif [ -f /etc/SuSE-release ] ; then
DIST=`cat /etc/SuSE-release | tr "\n" ' '| sed s/VERSION.*//`
REV=`cat /etc/SuSE-release | tr "\n" ' ' | sed s/.*=\ //`
elif [ -f /etc/mandrake-release ] ; then
DIST='Mandrake'
PSUEDONAME=`cat /etc/mandrake-release | sed s/.*\(// | sed s/\)//`
REV=`cat /etc/mandrake-release | sed s/.*release\ // | sed s/\ .*//`
elif [ -f /etc/debian_version ] ; then
DIST="Debian `cat /etc/debian_version`"
REV=""
fi
if [ -f /etc/UnitedLinux-release ] ; then
DIST="${DIST}[`cat /etc/UnitedLinux-release | tr "\n" ' ' | sed s/VERSION.*//`]"
fi
OSSTR="${OS} ${DIST} ${REV}(${PSUEDONAME} ${KERNEL} ${MACH})"
fi
echo ${OSSTR}
TL;DR) See this table: https://www.tensorflow.org/install/source#gpu
Check the CUDA version:
cat /usr/local/cuda/version.txt
and cuDNN version:
grep CUDNN_MAJOR -A 2 /usr/local/cuda/include/cudnn.h
and install a combination as given below in the images or here.
The following images and the link provide an overview of the officially supported/tested combinations of CUDA and TensorFlow on Linux, macOS and Windows:
Since the given specifications below in some cases might be too broad, here is one specific configuration that works:
tensorflow-gpu==1.12.0
cuda==9.0
cuDNN==7.1.4
The corresponding cudnn can be downloaded here.
Please refer to https://www.tensorflow.org/install/source#gpu for a up-to-date compatibility chart (for official TF wheels).
(figures updated May 20, 2020)
Updated as of Dec 5 2020: For the updated information please refer Link for Linux and Link for Windows.
In Mvc You can do it by opening Web.config file it comes under bottom of your project file
Probably the best way to do do this version comparison is to use the sys.hexversion
. This is important because comparing version tuples will not give you the desired result in all python versions.
import sys
if sys.hexversion < 0x02060000:
print "yep!"
else:
print "oops!"
If you are using Linux and you have different versions of Java installed, use the following command:
sudo update-alternatives --config java
This will give a quick way of switching between the Java versions installed on the system. By choosing Java 8 I will solve your problem.
def versiontuple(v):
return tuple(map(int, (v.split("."))))
>>> versiontuple("2.3.1") > versiontuple("10.1.1")
False
declare @sqlVers numeric(4,2)
select @sqlVers = left(cast(serverproperty('productversion') as varchar), 4)
Gives 8.00, 9.00, 10.00 and 10.50 for SQL 2000, 2005, 2008 and 2008R2 respectively.
Also, Try the system extended procedure xp_msver
. You can call this stored procedure like
exec master..xp_msver
All the data Git uses for information is stored in .git/
, so removing it should work just fine. Of course, make sure that your working copy is in the exact state that you want it, because everything else will be lost. .git
folder is hidden so make sure you turn on the Show hidden files, folders and disks
option.
From there, you can run git init
to create a fresh repository.
THE ANSWER IS : NMAP PROGRAM
THANKS FOR YOUR ATTENTIONS ...
another way is getting HTTP Headers by this site (http://web-sniffer.net/) or firefox add-on for getting HTTP Headers...
Best Regards
Have you tried doing a full "clean" and then rebuild in Eclipse (Project->Clean...)?
Are you able to compile and run with "javac" and "java" straight from the command line? Does that work properly?
If you right click on your project, go to "Properties" and then go to "Java Build Path", are there any suspicious entries under any of the tabs? This is essentially your CLASSPATH.
In the Eclipse preferences, you may also want to double check the "Installed JREs" section in the "Java" section and make sure it matches what you think it should.
You definitely have either a stale .class file laying around somewhere or you're getting a compile-time/run-time mismatch in the versions of Java you're using.
Eclipse uses the default Java on the system to run itself. This can also be changed in the eclipse.ini file in your eclipse install folder.
To find out the version of java that your eclipse project is using, see Project->properties->build path->Libraries tab and see the JRE system library thats being used. You can also check it out at Window->Preferences->Java->Installed JREs. This is a list of all JREs that eclipse knows about
To find out using code, use the System.getProperty(...) method. See http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html#getProperties() for supported properties.
use
import tensorflow as tf
print(tf.VERSION)
A succinct way to obtain a version string in X.Y.Z format is:
[NSBundle mainBundle].infoDictionary[@"CFBundleVersion"]
Or, for just X.Y:
[NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"]
Both of these snippets returns strings that you would assign to your label object's text property, e.g.
myLabel.text = [NSBundle mainBundle].infoDictionary[@"CFBundleVersion"];
In my case I was running nodejs
instead of node
. Due to nodejs
being installed by the package manager:
# which node
/home/user/.nvm/versions/node/v11.6.0/bin/node
# which nodejs
/usr/bin/nodejs
You have to upgrade your subversion client to at least 1.7.
With the command line client, you have to manually upgrade your working copy format by issuing the command svn upgrade
:
Upgrading the Working Copy
Subversion 1.7 introduces substantial changes to the working copy format. In previous releases of Subversion, Subversion would automatically update the working copy to the new format when a write operation was performed. Subversion 1.7, however, will make this a manual step. Before using Subversion 1.7 with their working copies, users will be required to run a new command,
svn upgrade
to update the metadata to the new format. This command may take a while, and for some users, it may be more practical to simply checkout a new working copy.
— Subversion 1.7 Release Notes
TortoiseSVN will perform the working copy upgrade with the next write operation:
Upgrading the Working Copy
Subversion 1.7 introduces substantial changes to the working copy format. In previous releases, Subversion would automatically update the working copy to the new format when a write operation was performed. Subversion 1.7, however, will make this a manual step.
Before you can use an existing working copy with TortoiseSVN 1.7, you have to upgrade the format first. If you right-click on an old working copy, TortoiseSVN only shows you one command in the context menu: Upgrade working copy.
— TortoiseSVN 1.7 Release notes
Here's the general idea:
Get child items in the .NET Framework directory that are containers whose names match the pattern v number dot number. Sort them by descending name, take the first object, and return its name property.
Here's the script:
(Get-ChildItem -Path $Env:windir\Microsoft.NET\Framework | Where-Object {$_.PSIsContainer -eq $true } | Where-Object {$_.Name -match 'v\d\.\d'} | Sort-Object -Property Name -Descending | Select-Object -First 1).Name
This page seems to have a pretty nice snippet which only uses the appString and appVersion property as a last resort as it claims them to be unreliable with certain browsers. The code on the page is as follows:
var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browserName = navigator.appName;
var fullVersion = ''+parseFloat(navigator.appVersion);
var majorVersion = parseInt(navigator.appVersion,10);
var nameOffset,verOffset,ix;
// In Opera 15+, the true version is after "OPR/"
if ((verOffset=nAgt.indexOf("OPR/"))!=-1) {
browserName = "Opera";
fullVersion = nAgt.substring(verOffset+4);
}
// In older Opera, the true version is after "Opera" or after "Version"
else if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
browserName = "Opera";
fullVersion = nAgt.substring(verOffset+6);
if ((verOffset=nAgt.indexOf("Version"))!=-1)
fullVersion = nAgt.substring(verOffset+8);
}
// In MSIE, the true version is after "MSIE" in userAgent
else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
browserName = "Microsoft Internet Explorer";
fullVersion = nAgt.substring(verOffset+5);
}
// In Chrome, the true version is after "Chrome"
else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
browserName = "Chrome";
fullVersion = nAgt.substring(verOffset+7);
}
// In Safari, the true version is after "Safari" or after "Version"
else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
browserName = "Safari";
fullVersion = nAgt.substring(verOffset+7);
if ((verOffset=nAgt.indexOf("Version"))!=-1)
fullVersion = nAgt.substring(verOffset+8);
}
// In Firefox, the true version is after "Firefox"
else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
browserName = "Firefox";
fullVersion = nAgt.substring(verOffset+8);
}
// In most other browsers, "name/version" is at the end of userAgent
else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) <
(verOffset=nAgt.lastIndexOf('/')) )
{
browserName = nAgt.substring(nameOffset,verOffset);
fullVersion = nAgt.substring(verOffset+1);
if (browserName.toLowerCase()==browserName.toUpperCase()) {
browserName = navigator.appName;
}
}
// trim the fullVersion string at semicolon/space if present
if ((ix=fullVersion.indexOf(";"))!=-1)
fullVersion=fullVersion.substring(0,ix);
if ((ix=fullVersion.indexOf(" "))!=-1)
fullVersion=fullVersion.substring(0,ix);
majorVersion = parseInt(''+fullVersion,10);
if (isNaN(majorVersion)) {
fullVersion = ''+parseFloat(navigator.appVersion);
majorVersion = parseInt(navigator.appVersion,10);
}
document.write(''
+'Browser name = '+browserName+'<br>'
+'Full version = '+fullVersion+'<br>'
+'Major version = '+majorVersion+'<br>'
+'navigator.appName = '+navigator.appName+'<br>'
+'navigator.userAgent = '+navigator.userAgent+'<br>'
)
(nvm maintainer here)
nvm alias default 6.11.5
if you want it pegged to that specific version.
You can also do nvm alias default 6
.
Either way, you'll want to upgrade to the latest version of nvm
(v0.33.11 as of this writing)
Open your terminal and run
curl -sSL https://raw.githubusercontent.com/rvm/rvm/master/binscripts/rvm-installer | bash -s stable
When this is complete, you need to restart your terminal for the rvm
command to work.
Now, run rvm list known
This shows the list of versions of the ruby.
Now, run rvm install ruby@latest
to get the latest ruby version.
If you type ruby -v
in the terminal, you should see ruby X.X.X
.
If it still shows you ruby 2.0.
, run rvm use ruby-X.X.X --default
.
Prerequisites for windows 10:
make
command available otherwise it will complain that "bash: make: command not found". You can install it by running mingw-get install msys-make
Might be already answered, but you can try this simple program to determine if and what installation of boost you have :
#include<boost/version.hpp>
#include<iostream>
using namespace std;
int main()
{
cout<<BOOST_VERSION<<endl;
return 0;
}
Add the following to package.json
:
"engines": {
"node": ">=10.0.0",
"npm": ">=6.0.0"
},
Add the following to .npmrc
(same directory as package.json
):
engine-strict=true
If you're having some problem about "error compiler of class file", it's possible to resolve this by changing the project's JRE to its correspondent through Eclipse.
I did that and it worked.
To complement what @kieste has posted, which I think is the best way to have Maven build informations available in your code if you're using Spring-boot: the documentation at http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#production-ready-application-info is very useful.
You just need to activate actuators, and add the properties you need in your application.properties
or application.yml
Automatic property expansion using Maven
You can automatically expand info properties from the Maven project using resource filtering. If you use the spring-boot-starter-parent you can then refer to your Maven ‘project properties’ via @..@ placeholders, e.g.
project.artifactId=myproject
project.name=Demo
project.version=X.X.X.X
project.description=Demo project for info endpoint
[email protected]@
[email protected]@
[email protected]@
[email protected]@
Actually you have a code compiled targeting a higher JDK (JDK 1.8 in your case) but at runtime you are supplying a lower JRE(JRE 7 or below).
you can fix this problem by adding target parameter while compilation
e.g. if your runtime target is 1.7, you should use 1.7 or below
javac -target 1.7 *.java
if you are using eclipse, you can sent this parameter at Window -> Preferences -> Java -> Compiler -> set "Compiler compliance level" = choose your runtime jre version or lower.
The following might work well enough:
aptitude versions ^hylafax+
See more in aptitude(8)
My guess is it's not in your path.
in bash, try:
echo $PATH
and
sudo which nginx
And see if the folder containing nginx is also in your $PATH variable.
If not, either add the folder to your path environment variable, or create an alias (and put it in your .bashrc) ooor your could create a link i guess.
or sudo nginx -v
if you just want that...
compgen -c python | grep -P '^python\d'
This lists some other python things too, But hey, You can identify all python versions among them.
I just want to clarify, because some of the answers refer to venv
and others refer to virtualenv
.
Use of the -p
or --python
flag is supported on virtualenv
, but not on venv
. If you have more than one Python version and you want to specify which one to create the venv
with, do it on the command line, like this:
malikarumi@Tetuoan2:~/Projects$ python3.6 -m venv {path to pre-existing dir you want venv in}
You can of course upgrade with venv
as others have pointed out, but that assumes you have already upgraded the Python that was used to create that venv
in the first place. You can't upgrade to a Python version you don't already have on your system somewhere, so make sure to get the version you want, first, then make all the venvs you want from it.
It is indeed based on versionCode and not on versionName. However, I noticed that changing the versionCode in AndroidManifest.xml wasn't enough with Android Studio - Gradle build system. I needed to change it in the build.gradle.
Use this:
((AssemblyFileVersionAttribute)Attribute.GetCustomAttribute(
Assembly.GetExecutingAssembly(),
typeof(AssemblyFileVersionAttribute), false)
).Version;
Or this:
new Version(System.Windows.Forms.Application.ProductVersion);
You can figure out version of Cocoapods by using below command :
pod —-version
o/p : 1.2.1
Now if you want detailed version of Gems and Cocoapods then use below command :
gem which cocoapods
(without sudo)
o/p : /Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.1/lib/cocoapods.rb
sudo gem which cocoapods
(with sudo)
o/p : /Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.1/lib/cocoapods.rb
Now if you want to get specific version of Pod present in Podfile then simply use command pod install
in terminal. This will show list of pod being used in project along with version.
With a Maven version of 3.5 or higher, you should be able to use a placeholder (e.g. ${revision}) in the parent section and inside the rest of the pom, you can use ${project.version}
.
Actually, you can also omit project properties outside of parent
which are the same, as they will be inherited. The result would look something like this:
<project>
<parent>
<artifactId>build.parent</artifactId>
<groupId>company</groupId>
<relativePath>../build.parent/pom.xml</relativePath>
<version>${revision}</version> <!-- use placeholder -->
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>artifact</artifactId>
<!-- no 'version', no 'groupId'; inherited from parent -->
<packaging>eclipse-plugin</packaging>
...
</project>
For more information, especially on how to resolve the placeholder during publishing, see Maven CI Friendly Versions | Multi Module Setup.
For me, the PHP path traversed from php5.6.25 (or php7) installation folder, through wamp folder, bin and php...
C:\wamp64\bin\php\php5.6.25>
Instead of having the whole migration script added, you could simply add the following (extracted from the migration script)
$.uaMatch = function( ua ) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
and then use it like so
$.uaMatch(navigator.userAgent)
While the OP may be working on a nix platform this answer could help non-nix platforms. I have not experienced the shebang approach work in Microsoft Windows.
Rephrased: The shebang line answers your question of "within my script" but I believe only for Unix-like platforms. Even though it is the Unix shell, outside the script, that actually interprets the shebang line to determine which version of Python interpreter to call. I am not sure, but I believe that solution does not solve the problem for Microsoft Windows platform users.
In the Microsoft Windows world, the simplify the way to run a specific Python version, without environment variables setup specifically for each specific version of Python installed, is just by prefixing the python.exe with the path you want to run it from, such as C:\Python25\python.exe mymodule.py or D:\Python27\python.exe mymodule.py
However you'd need to consider the PYTHONPATH and other PYTHON... environment variables that would point to the wrong version of Python libraries.
For example, you might run: C:\Python2.5.2\python.exe mymodule
Yet, the environment variables may point to the wrong version as such:
PYTHONPATH = D:\Python27
PYTHONLIB = D:\Python27\lib
Loads of horrible fun!
So a non-virtualenv way, in Windows, would be to use a batch file that sets up the environment and calls a specific Python executable via prefixing the python.exe with the path it resides in. This way has additional details you'll have to manage though; such as using command line arguments for either of the "start" or "cmd.exe" command to "save and replace the "console" environment" if you want the console to stick around after the application exits.
Your question leads me to believe you have several Python modules, each expecting a certain version of Python. This might be solvable "within" the script by having a launching module which uses the subprocess module. Instead of calling mymodule.py you would call a module that calls your module; perhaps launch_mymodule.py
import sys
import subprocess
if sys.argv[2] == '272':
env272 = {
'PYTHONPATH': 'blabla',
'PYTHONLIB': 'blabla', }
launch272 = subprocess.Popen('D:\\Python272\\python.exe mymodule.py', env=env272)
if sys.argv[1] == '252'
env252 = {
'PYTHONPATH': 'blabla',
'PYTHONLIB': 'blabla', }
launch252 = subprocess.Popen('C:\\Python252\\python.exe mymodule.py', env=env252)
I have not tested this.
You just need to get the value of the texbox and see if it has anything in it:
if (!$(`#textareaid`).val().length)
{
//do stuff
}
Specifically, to install the pdf.js plugin for firefox, you do not use the app store. Instead, go to addons.mozilla.org from inside mozilla and install it from there. Also, to see if it's installed properly, go to the menu Tools:Add-ons (not the "about:plugins" url as you might think from the desktop version).
(New account, otherwise I'd put this as a comment on the answer above)
In short:
<textarea>
should be closed immediately on the same line where it started.
General Practice: this will add-up line-breaks and spaces used for indentation in the code.
<textarea id="sitelink" name="sitelink">
</textarea>
Correct Practice
<textarea id="sitelink" name="sitelink"></textarea>
SELECT DATEADD(m,DATEDIFF(m,0,GETDATE())-1,0) AS PreviousMonthStart
SELECT DATEADD(ms,-2,DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)) AS PreviousMonthEnd
The dispatch_async(dispatch_get_main_queue())
method above is not guaranteed to work. I'm seeing non-deterministic behavior with it, in which sometimes the system has completed the layoutSubviews and the cell rendering before the completion block, and sometimes after.
Here's a solution that works 100% for me, on iOS 10. It requires the ability to instantiate the UITableView or UICollectionView as a custom subclass. Here's the UICollectionView solution, but it's exactly the same for UITableView:
CustomCollectionView.h:
#import <UIKit/UIKit.h>
@interface CustomCollectionView: UICollectionView
- (void)reloadDataWithCompletion:(void (^)(void))completionBlock;
@end
CustomCollectionView.m:
#import "CustomCollectionView.h"
@interface CustomCollectionView ()
@property (nonatomic, copy) void (^reloadDataCompletionBlock)(void);
@end
@implementation CustomCollectionView
- (void)reloadDataWithCompletion:(void (^)(void))completionBlock
{
self.reloadDataCompletionBlock = completionBlock;
[self reloadData];
}
- (void)layoutSubviews
{
[super layoutSubviews];
if (self.reloadDataCompletionBlock) {
self.reloadDataCompletionBlock();
self.reloadDataCompletionBlock = nil;
}
}
@end
Example usage:
[self.collectionView reloadDataWithCompletion:^{
// reloadData is guaranteed to have completed
}];
See here for a Swift version of this answer
Taken from the ReactKonvaCore.d.ts file:
onClick?(evt: Konva.KonvaEventObject<MouseEvent>): void;
So, I'd say your event type is Konva.KonvaEventObject<MouseEvent>
Session State may be broken if you have the following in Web.Config:
<httpModules>
<clear/>
</httpModules>
If this is the case, you may want to comment out such section, and you won't need any other changes to fix this issue.
In your case, you should simply use
$firstapiOutput->document_number
as the input for the second api.
From man 1 pkill
-f The pattern is normally only matched against the process name.
When -f is set, the full command line is used.
Which means, for example, if we see these lines in ps aux
:
apache 24268 0.0 2.6 388152 27116 ? S Jun13 0:10 /usr/sbin/httpd
apache 24272 0.0 2.6 387944 27104 ? S Jun13 0:09 /usr/sbin/httpd
apache 24319 0.0 2.6 387884 27316 ? S Jun15 0:04 /usr/sbin/httpd
We can kill them all using the pkill -f
option:
pkill -f httpd
It is stretching because align-self default value is stretch. there is two solution for this case : 1. set img align-self : center OR 2. set parent align-items : center
img { align-self: center }
OR
.parent { align-items: center }
Another way-too-complicated workaround, with the benefit of not having to re-install the application as the previous workaround required. This requires that you have access to the msi (or a setup.exe with the msi embedded).
If you have Visual Studio 2012 (or possibly other editions) and install the free "InstallShield LE", then you can create a new setup project using InstallShield.
One of the configuration options in the "Organize your Setup" step is called "Upgrade Paths". Open the properties for Upgrade Paths, and in the left pane right click "Upgrade Paths" and select "New Upgrade Path" ... now browse to the msi (or setup.exe containing the msi) and click "open". The upgrade code will be populated for you in the settings page in the right pane which you should now see.
element::after {
display: block;
content: " ";
}
This worked for me.
Steps to solve this problem
note: This problem mainly occurs due to which we haven't assigned our user name and email id in git so what we gonna do is assigning it in git
Open git that you have installed
Now we have to assign our user name and email id
Just type git config --user.name <your_name>
and click enter
(you can mention or type any name you want)
Similarly type git config --user.email <[email protected]>
and
click enter (you have to type your primary mail id)
And that's it.
Have a Good Day!!!.
switch ($value)
{
case 1:
case 2:
echo "the value is either 1 or 2.";
break;
}
This is called "falling through" the case block. The term exists in most languages implementing a switch statement.
You can use the update()
method to build a new dictionary containing all the items:
dall = {}
dall.update(d1)
dall.update(d2)
dall.update(d3)
Or, in a loop:
dall = {}
for d in [d1, d2, d3]:
dall.update(d)
Here is an extension of Roberto14's answer that does the following:
THIS WILL ONLY ALLOW IMAGES
Checks if FileReader is available and falls back to extension checking if it is not available.
Gives an error alert if not an image
If it is an image it loads a preview
** You should still do server side validation, this is more a convenience for the end user than anything else. But it is handy!
<form id="myform">
<input type="file" id="myimage" onchange="readURL(this)" />
<img id="preview" src="#" alt="Image Preview" />
</form>
<script>
function readURL(input) {
if (window.FileReader && window.Blob) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
var img = new Image();
img.onload = function() {
var preview = document.getElementById('preview');
preview.src = e.target.result;
};
img.onerror = function() {
alert('error');
input.value = '';
};
img.src = e.target.result;
}
reader.readAsDataURL(input.files[0]);
}
}
else {
var ext = input.value.split('.');
ext = ext[ext.length-1].toLowerCase();
var arrayExtensions = ['jpg' , 'jpeg', 'png', 'bmp', 'gif'];
if (arrayExtensions.lastIndexOf(ext) == -1) {
alert('error');
input.value = '';
}
else {
var preview = document.getElementById('preview');
preview.setAttribute('alt', 'Browser does not support preview.');
}
}
}
</script>
The default MidpointRounding.ToEven
, or Bankers' rounding (2.5 become 2, 4.5 becomes 4 and so on) has stung me before with writing reports for accounting, so I'll write a few words of what I found out, previously and from looking into it for this post.
From wikipedia
The origin of the term bankers' rounding remains more obscure. If this rounding method was ever a standard in banking, the evidence has proved extremely difficult to find. To the contrary, section 2 of the European Commission report The Introduction of the Euro and the Rounding of Currency Amounts suggests that there had previously been no standard approach to rounding in banking; and it specifies that "half-way" amounts should be rounded up.
It seems a very strange way of rounding particularly for banking, unless of course banks use to receive lots of deposits of even amounts. Deposit £2.4m, but we'll call it £2m sir.
The IEEE Standard 754 dates back to 1985 and gives both ways of rounding, but with banker's as the recommended by the standard. This wikipedia article has a long list of how languages implement rounding (correct me if any of the below are wrong) and most don't use Bankers' but the rounding you're taught at school:
If you are simply checking for the existence of an ID, there is no need to go into jQuery, you could simply:
if(document.getElementById("yourid") !== null)
{
}
getElementById
returns null
if it can't be found.
If however you plan to use the jQuery object later i'd suggest:
$(document).ready(function() {
var $myDiv = $('#DivID');
if ( $myDiv.length){
//you can now reuse $myDiv here, without having to select it again.
}
});
A selector always returns a jQuery object, so there shouldn't be a need to check against null
(I'd be interested if there is an edge case where you need to check for null
- but I don't think there is).
If the selector doesn't find anything then length === 0
which is "falsy" (when converted to bool its false). So if it finds something then it should be "truthy" - so you don't need to check for > 0. Just for it's "truthyness"
The easiest solution is to dispense with "like" altogether:
Select *
from table
where charindex(search_criteria, name) > 0
I prefer charindex over like. Historically, it had better performance, but I'm not sure if it makes much of difference now.
Many algorithms will specify that duplicates are excluded. For example, the example algorithms in the MIT Algorithms book usually present examples without duplicates. It is fairly trivial to implement duplicates (either as a list at the node, or in one particular direction.)
Most (that I've seen) specify left children as <= and right children as >. Practically speaking, a BST which allows either of the right or left children to be equal to the root node, will require extra computational steps to finish a search where duplicate nodes are allowed.
It is best to utilize a list at the node to store duplicates, as inserting an '=' value to one side of a node requires rewriting the tree on that side to place the node as the child, or the node is placed as a grand-child, at some point below, which eliminates some of the search efficiency.
You have to remember, most of the classroom examples are simplified to portray and deliver the concept. They aren't worth squat in many real-world situations. But the statement, "every element has a key and no two elements have the same key", is not violated by the use of a list at the element node.
So go with what your data structures book said!
Edit:
Universal Definition of a Binary Search Tree involves storing and search for a key based on traversing a data structure in one of two directions. In the pragmatic sense, that means if the value is <>, you traverse the data structure in one of two 'directions'. So, in that sense, duplicate values don't make any sense at all.
This is different from BSP, or binary search partition, but not all that different. The algorithm to search has one of two directions for 'travel', or it is done (successfully or not.) So I apologize that my original answer didn't address the concept of a 'universal definition', as duplicates are really a distinct topic (something you deal with after a successful search, not as part of the binary search.)
string firstdayofyear = new DateTime(DateTime.Now.Year, 1, 1).ToString("MM-dd-yyyy");
string lastdayofyear = new DateTime(DateTime.Now.Year, 12, 31).ToString("MM-dd-yyyy");
string firstdayofmonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToString("MM-dd-yyyy");
string lastdayofmonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).AddDays(-1).ToString("MM-dd-yyyy");
You need to add a return to the index.html file.
app.use(express.static(path.join(__dirname, 'build')));
app.get('*', function(req, res) {res.sendFile(path.join(__dirname + '/build/index.html')); });
To build uri with get parameters, Uri.Builder provides a more effective way.
Uri uri = new Uri.Builder()
.scheme("http")
.authority("foo.com")
.path("someservlet")
.appendQueryParameter("param1", foo)
.appendQueryParameter("param2", bar)
.build();
Your syntax would create an alias for a as b, but it wouldn't have scope beyond the results of the statement. It sounds like you may want to create a VIEW
If you want to insert object, use this:
currentLogs = [
{ socket_id: 'Server', message: 'Socketio online', data: 'Port 3333', logged: '2014-05-14 14:41:11' },
{ socket_id: 'Server', message: 'Waiting for Pi to connect...', data: 'Port: 8082', logged: '2014-05-14 14:41:11' }
];
console.warn(currentLogs.map(logs=>[ logs.socket_id , logs.message , logs.data , logs.logged ]));
The output will be:
[
[ 'Server', 'Socketio online', 'Port 3333', '2014-05-14 14:41:11' ],
[
'Server',
'Waiting for Pi to connect...',
'Port: 8082',
'2014-05-14 14:41:11'
]
]
Also, please check the documentation to know more about the map function.
Comments work fine in any of the usual Java/Groovy forms, but you can't currently use groovydoc
to process your Jenkinsfile
(s).
First, groovydoc
chokes on files without extensions with the wonderful error
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.codehaus.groovy.tools.GroovyStarter.rootLoader(GroovyStarter.java:109)
at org.codehaus.groovy.tools.GroovyStarter.main(GroovyStarter.java:131)
Caused by: java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1967)
at org.codehaus.groovy.tools.groovydoc.SimpleGroovyClassDocAssembler.<init>(SimpleGroovyClassDocAssembler.java:67)
at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.parseGroovy(GroovyRootDocBuilder.java:131)
at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.getClassDocsFromSingleSource(GroovyRootDocBuilder.java:83)
at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.processFile(GroovyRootDocBuilder.java:213)
at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.buildTree(GroovyRootDocBuilder.java:168)
at org.codehaus.groovy.tools.groovydoc.GroovyDocTool.add(GroovyDocTool.java:82)
at org.codehaus.groovy.tools.groovydoc.GroovyDocTool$add.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
at org.codehaus.groovy.tools.groovydoc.Main.execute(Main.groovy:214)
at org.codehaus.groovy.tools.groovydoc.Main.main(Main.groovy:180)
... 6 more
... and second, as far as I can tell Javadoc-style commments at the start of a groovy
script are ignored. So even if you copy/rename your Jenkinsfile
to Jenkinsfile.groovy
, you won't get much useful output.
I want to be able to use a
/**
* Document my Jenkinsfile's overall purpose here
*/
comment at the start of my Jenkinsfile. No such luck (yet).
groovydoc
will process classes and methods defined in your Jenkinsfile
if you pass -private
to the command, though.
That's your jQuery API problem, not your script. There is not much to worry about.
Try this:
git config --global alias.all '!f() { find . -d -name ".git" | sed s/\\/\.git//g | xargs -P10 -I{} git --git-dir={}/.git --work-tree={} $1; }; f'
It runs ten threads in parallel and does what ever git command you want to all repos in the folder structure. No matter if the repo is one or n levels deep.
E.g: git all pull
When you need to accept a function as argument which takes no arguments and returns no result (void), in my opinion it is still best to have something like
public interface Thunk { void apply(); }
somewhere in your code. In my functional programming courses the word 'thunk' was used to describe such functions. Why it isn't in java.util.function is beyond my comprehension.
In other cases I find that even when java.util.function does have something that matches the signature I want - it still doesn't always feel right when the naming of the interface doesn't match the use of the function in my code. I guess it's a similar point that is made elsewhere here regarding 'Runnable' - which is a term associated with the Thread class - so while it may have he signature I need, it is still likely to confuse the reader.
How To Fix The Broken Icon Links (blank.gif, text.gif, etc.)
Unfortunately as previously mentioned, simply adding a virtual host to your project doesn't fix the broken icon links.
The Problem:
WAMP/Apache does not change the directory reference for the icons to your respective installation directory. It is statically set to "c:/Apache24/icons" and 99.9% of users Apache installation does not reside here. Especially with WAMP.
The Fix:
Find your Apache icons directory! Typically it will be located here: "c:/wamp/bin/apache/apache2.4.9/icons". However your mileage may vary depending on your installation and if your Apache version is different, then your path will be different as well.\
Open up httpd-autoindex.conf in your favorite editor. This file can usually be found here: "C:\wamp\bin\apache\apache2.4.9\conf\extra\httpd-autoindex.conf". Again, if your Apache version is different, then so will this path.
Find this definition (usually located near the top of the file):
Alias /icons/ "c:/Apache24/icons/"
<Directory "c:/Apache24/icons">
Options Indexes MultiViews
AllowOverride None
Require all granted
</Directory>
Replace the "c:/Apache24/icons/" directories with your own. IMPORTANT You MUST have a trailing forward slash in the first directory reference. The second directory reference must have no trailing slash. Your results should look similar to this. Again, your directory may differ:
Alias /icons/ "c:/wamp/bin/apache/apache2.4.9/icons/"
<Directory "c:/wamp/bin/apache/apache2.4.9/icons">
Options Indexes MultiViews
AllowOverride None
Require all granted
</Directory>
Restart your Apache server and enjoy your cool icons!
Manoj answer above is correct, but another option is to use MESSAGE.encode() or encode('utf-8') to convert to bytes. bytes and encode are mostly the same, encode is compatible with python 2. see here for more
full code:
import socket
UDP_IP = "127.0.0.1"
UDP_PORT = 5005
MESSAGE = "Hello, World!"
print("UDP target IP: %s" % UDP_IP)
print("UDP target port: %s" % UDP_PORT)
print("message: %s" % MESSAGE)
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE.encode(), (UDP_IP, UDP_PORT))
If you want to extend the amount of time permitted for an ASP.NET script to execute then increase the Server.ScriptTimeout
value. The default is 90 seconds for .NET 1.x and 110 seconds for .NET 2.0 and later.
For example:
// Increase script timeout for current page to five minutes
Server.ScriptTimeout = 300;
This value can also be configured in your web.config
file in the httpRuntime
configuration element:
<!-- Increase script timeout to five minutes -->
<httpRuntime executionTimeout="300"
... other configuration attributes ...
/>
Please note according to the MSDN documentation:
"This time-out applies only if the debug attribute in the compilation element is False. Therefore, if the debug attribute is True, you do not have to set this attribute to a large value in order to avoid application shutdown while you are debugging."
If you've already done this but are finding that your session is expiring then increase the
ASP.NET HttpSessionState.Timeout
value:
For example:
// Increase session timeout to thirty minutes
Session.Timeout = 30;
This value can also be configured in your web.config
file in the sessionState
configuration element:
<configuration>
<system.web>
<sessionState
mode="InProc"
cookieless="true"
timeout="30" />
</system.web>
</configuration>
If your script is taking several minutes to execute and there are many concurrent users then consider changing the page to an Asynchronous Page. This will increase the scalability of your application.
The other alternative, if you have administrator access to the server, is to consider this long running operation as a candidate for implementing as a scheduled task or a windows service.
This should solve your problem for the time being but I must remind you it isn't a good approach :
WHERE
CASE LEN('TestPerson')
WHEN 0 THEN
CASE WHEN co.personentered = co.personentered THEN 1 ELSE 0 END
ELSE
CASE WHEN co.personentered LIKE '%TestPerson' THEN 1 ELSE 0 END
END = 1
AND cc.ccnum = CASE LEN('TestFFNum')
WHEN 0 THEN cc.ccnum
ELSE 'TestFFNum'
END
AND CASE LEN('2011-01-09 11:56:29.327')
WHEN 0 THEN CASE WHEN co.DTEntered = co.DTEntered THEN 1 ELSE 0 END
ELSE
CASE LEN('2012-01-09 11:56:29.327')
WHEN 0 THEN
CASE WHEN co.DTEntered >= '2011-01-09 11:56:29.327' THEN 1 ELSE 0 END
ELSE
CASE WHEN co.DTEntered BETWEEN '2011-01-09 11:56:29.327'
AND '2012-01-09 11:56:29.327'
THEN 1 ELSE 0 END
END
END = 1
AND tl.storenum < 699
This is how I've been doing it:
$arr = array(1,2,3,4,5,6,7,8,9);
$string = rtrim(implode(',', $arr), ',');
echo $string;
Output:
1,2,3,4,5,6,7,8,9
Live Demo: http://ideone.com/EWK1XR
EDIT: Per @joseantgv's comment, you should be able to remove rtrim()
from the above example. I.e:
$string = implode(',', $arr);
Try
df.loc[df.my_channel > 20000, 'my_channel'] = 0
Note: Since v0.20.0, ix
has been deprecated in favour of loc
/ iloc
.
I highly recommend you use the tobytes
function of the Image
object. After some timing checks this is much more efficient.
def jpg_image_to_array(image_path):
"""
Loads JPEG image into 3D Numpy array of shape
(width, height, channels)
"""
with Image.open(image_path) as image:
im_arr = np.fromstring(image.tobytes(), dtype=np.uint8)
im_arr = im_arr.reshape((image.size[1], image.size[0], 3))
return im_arr
The timings I ran on my laptop show
In [76]: %timeit np.fromstring(im.tobytes(), dtype=np.uint8)
1000 loops, best of 3: 230 µs per loop
In [77]: %timeit np.array(im.getdata(), dtype=np.uint8)
10 loops, best of 3: 114 ms per loop
```
If you need it prefix than you might like this
for ((i=7;i<=12;i++)); do echo `printf "%2.0d\n" $i |sed "s/ /0/"`;done
that will yield
07
08
09
10
11
12
The CURL extension ext/curl
is not installed or enabled in your PHP installation. Check the manual for information on how to install or enable CURL on your system.
Most likely persistent connections that are kept alive by the connection manager become stale. That is, the target server shuts down the connection on its end without HttpClient being able to react to that event, while the connection is being idle, thus rendering the connection half-closed or 'stale'. Usually this is not a problem. HttpClient employs several techniques to verify connection validity upon its lease from the pool. Even if the stale connection check is disabled and a stale connection is used to transmit a request message the request execution usually fails in the write operation with SocketException and gets automatically retried. However under some circumstances the write operation can terminate without an exception and the subsequent read operation returns -1 (end of stream). In this case HttpClient has no other choice but to assume the request succeeded but the server failed to respond most likely due to an unexpected error on the server side.
The simplest way to remedy the situation is to evict expired connections and connections that have been idle longer than, say, 1 minute from the pool after a period of inactivity. For details please see this section of the HttpClient tutorial.
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame, new MySchedule()).commit();
MySchedule is the name of my java class.
I had the same problem and the dll was a dynamically loaded reference. To solve the problem I have added an "using" with the namespace of the dll. Now the dll is copied in the output folder.
Replace hidden
with none
. See MDN reference.
In case you do need to define dataSource()
, for example when you have multiple data sources, you can use:
@Autowired Environment env;
@Primary
@Bean
public DataSource customDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("custom.datasource.driver-class-name"));
dataSource.setUrl(env.getProperty("custom.datasource.url"));
dataSource.setUsername(env.getProperty("custom.datasource.username"));
dataSource.setPassword(env.getProperty("custom.datasource.password"));
return dataSource;
}
By setting up the dataSource
yourself (instead of using DataSourceBuilder
), it fixed my problem which you also had.
The always knowledgeable Baeldung has a tutorial which explains in depth.
If you've got an image in the Icons folder of your project and its build action is "Resource", you can refer to it like this:
<Image Source="/Icons/play_small.png" />
That's the simplest way to do it. This is the only way I could figure doing it purely from the resource standpoint and no project files:
var resourceManager = new ResourceManager(typeof (Resources));
var bitmap = resourceManager.GetObject("Search") as System.Drawing.Bitmap;
var memoryStream = new MemoryStream();
bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
memoryStream.Position = 0;
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memoryStream;
bitmapImage.EndInit();
this.image1.Source = bitmapImage;
Try this:
<a href="pdf_server_with_path.php?file=pdffilename&path=http://myurl.com/mypath/">Download my eBook</a>
The code inside pdf_server_with_path.php is:
header("Content-Type: application/octet-stream");
$file = $_GET["file"] .".pdf";
$path = $_GET["path"];
$fullfile = $path.$file;
header("Content-Disposition: attachment; filename=" . Urlencode($file));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . Filesize($fullfile));
flush(); // this doesn't really matter.
$fp = fopen($fullfile, "r");
while (!feof($fp))
{
echo fread($fp, 65536);
flush(); // this is essential for large downloads
}
fclose($fp);
Use the spool:
spool myoutputfile.txt
select * from users;
spool off;
Note that this will create myoutputfile.txt in the directory from which you ran SQL*Plus.
If you need to run this from a SQL file (e.g., "tmp.sql") when SQLPlus starts up and output to a file named "output.txt":
tmp.sql:
select * from users;
Command:
sqlplus -s username/password@sid @tmp.sql > output.txt
Mind you, I don't have an Oracle instance in front of me right now, so you might need to do some of your own work to debug what I've written from memory.
In Kotlin you can use deleteRecursively()
extension from kotlin.io
package
val someDir = File("/path/to/dir")
someDir.deleteRecursively()
For PHP 8:
sudo apt update
sudo apt-get install php8.0-soap
Just for reference.
The joys of Maven.
Putting the relative path of the modules to ../pom.xml solved it.
The parent
element has a relativePath
element that you need to point to the directory of the parent. It defaults to ..
You are running Composer with SSL/TLS protection disabled.
composer config --global disable-tls true
composer config --global disable-tls false
Not sure if this is what you are looking for, but try putting:
android:debuggable="true"
in the application tag in the AndroidManifest.xml
Warning
If you run PowerShell from a cmd.exe window created by Powershell, the 2nd instance no longer waits for jobs to complete.
cmd> PowerShell
PS> Start-Process cmd.exe -Wait
Now from the new cmd window, run PowerShell again and within it start a 2nd cmd window: cmd2> PowerShell
PS> Start-Process cmd.exe -Wait
PS>
The 2nd instance of PowerShell no longer honors the -Wait request and ALL background process/jobs return 'Completed' status even thou they are still running !
I discovered this when my C# Explorer program is used to open a cmd.exe window and PS is run from that window, it also ignores the -Wait request. It appears that any PowerShell which is a 'win32 job' of cmd.exe fails to honor the wait request.
I ran into this with PowerShell version 3.0 on windows 7/x64
If by configure release/build, you mean you only need one config per makefile, then it is simply a matter and decoupling CC and CFLAGS:
CFLAGS=-DDEBUG
#CFLAGS=-O2 -DNDEBUG
CC=g++ -g3 -gdwarf2 $(CFLAGS)
Depending on whether you can use gnu makefile, you can use conditional to make this a bit fancier, and control it from the command line:
DEBUG ?= 1
ifeq ($(DEBUG), 1)
CFLAGS =-DDEBUG
else
CFLAGS=-DNDEBUG
endif
.o: .c
$(CC) -c $< -o $@ $(CFLAGS)
and then use:
make DEBUG=0
make DEBUG=1
If you need to control both configurations at the same time, I think it is better to have build directories, and one build directory / config.
This solution is using the official Microsoft.VisualBasic assembly to parse CSV.
Advantages:
Code:
using Microsoft.VisualBasic.FileIO;
public static List<List<string>> ParseCSV (string csv)
{
List<List<string>> result = new List<List<string>>();
// To use the TextFieldParser a reference to the Microsoft.VisualBasic assembly has to be added to the project.
using (TextFieldParser parser = new TextFieldParser(new StringReader(csv)))
{
parser.CommentTokens = new string[] { "#" };
parser.SetDelimiters(new string[] { ";" });
parser.HasFieldsEnclosedInQuotes = true;
// Skip over header line.
//parser.ReadLine();
while (!parser.EndOfData)
{
var values = new List<string>();
var readFields = parser.ReadFields();
if (readFields != null)
values.AddRange(readFields);
result.Add(values);
}
}
return result;
}
So you're trying to grab numeric values that are preceded by the token "%download%#"?
Try this pattern:
(?<=%download%#)\d+
That should work. I don't think #
or %
are special characters in .NET Regex, but you'll have to either escape the backslash like \\
or use a verbatim string for the whole pattern:
var regex = new Regex(@"(?<=%download%#)\d+");
return regex.Matches(strInput);
Tested here: http://rextester.com/BLYCC16700
NOTE: The lookbehind assertion (?<=...)
is important because you don't want to include %download%#
in your results, only the numbers after it. However, your example appears to require it before each string you want to capture. The lookbehind group will make sure it's there in the input string, but won't include it in the returned results. More on lookaround assertions here.
(ls $source).LastWriteTime
("ls", "dir", or "gci" are the default aliases for Get-ChildItem.)
Check if this solves the problem:
<div class="container-fluid no-padding">
<div class="row">
<div class="col-md-12">
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=1300%C3%97400&w=1300&h=400" alt="placeholder 960" class="img-responsive" />
</div>
</div>
</div>
CSS
.no-padding {
padding-left: 0;
padding-right: 0;
}
Css class no-padding
will override default bootstrap container padding.
Full example here.
@Update If you use bootstrap 4 it could be done even simpler
<div class="container-fluid px-0">
<div class="row">
<div class="col-md-12">
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=1300%C3%97400&w=1300&h=400" alt="placeholder 960" class="img-responsive" />
</div>
</div>
</div>
Updated example here.
You may not pass str
to fit this kind of classifier.
For example, if you have a feature column named 'grade' which has 3 different grades:
A,B and C.
you have to transfer those str
"A","B","C" to matrix by encoder like the following:
A = [1,0,0]
B = [0,1,0]
C = [0,0,1]
because the str
does not have numerical meaning for the classifier.
In scikit-learn, OneHotEncoder
and LabelEncoder
are available in inpreprocessing
module.
However OneHotEncoder
does not support to fit_transform()
of string.
"ValueError: could not convert string to float" may happen during transform.
You may use LabelEncoder
to transfer from str
to continuous numerical values. Then you are able to transfer by OneHotEncoder
as you wish.
In the Pandas dataframe, I have to encode all the data which are categorized to dtype:object
. The following code works for me and I hope this will help you.
from sklearn import preprocessing
le = preprocessing.LabelEncoder()
for column_name in train_data.columns:
if train_data[column_name].dtype == object:
train_data[column_name] = le.fit_transform(train_data[column_name])
else:
pass
Good question... I find that coders typically use the declaration to declare defaults. I've been held to one way (or warned) or the other too based on the compiler
void testFunct(int nVal1, int nVal2=500);
void testFunct(int nVal1, int nVal2)
{
using namespace std;
cout << nVal1 << << nVal2 << endl;
}
For http/https proxy with or without authentication:
Run one of the following commands in cmd.exe
set http_proxy=http://your_proxy:your_port
set http_proxy=http://username:password@your_proxy:your_port
set https_proxy=https://your_proxy:your_port
set https_proxy=https://username:password@your_proxy:your_port
In html;
<input type="file" accept="image/*">
This will accept all image formats but no other file like pdf or video.
But if you are using django, in django forms.py;
image_field = forms.ImageField(Here_are_the_parameters)
You may try this way. just use a function to get your object
def get_object(self, id):
try:
return UniversityDetails.objects.get(email__exact=email)
except UniversityDetails.DoesNotExist:
return False
When you declare a variable, you need to declare its type - in this case: int
. Also you've put a random comma in the while
loop. It probably worth looking up the syntax for Java and consider using a IDE that picks up on these kind of mistakes. You probably want something like this:
int [] numbers = { 1, 2, 3, 4, 5 ,6, 7, 8, 9 , 10 };
int sum = 0;
for(int i = 0; i < numbers.length; i++){
sum += numbers[i];
}
System.out.println("The sum is: " + sum);
Have you looked at this page?
http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Distinct
That might save you some time?
eg db.addresses.distinct("zip-code");
As a side note, you can include the separators while splitting the string in Go. To do so, use strings.SplitAfter
as in the example below.
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Printf("%q\n", strings.SplitAfter("z,o,r,r,o", ","))
}
In an .htaccess
file you need to use
Deny from all
Put this in site/includes/.htaccess
to make it specific to the includes
directory
If you just wish to disallow a listing of directory files you can use
Options -Indexes
That's not the way to concat in MYSQL. Use the CONCAT function Have a look here: http://dev.mysql.com/doc/refman/4.1/en/string-functions.html#function_concat
I know it's late but I use this command for Oracle:
select column_name,data_type,data_length from all_tab_columns where TABLE_NAME = 'xxxx' AND OWNER ='xxxxxxxxxx'
iCalendar was based on a vCalendar and Outlook 2007 handles both formats well so it doesn't really matters which one you choose.
I'm not sure if this stands for Outlook 2003. I guess you should give it a try.
Outlook's default calendar format is iCalendar (*.ics
)
I really like the BigDump to do it. It's a very simple PHP file that you edit and send with your huge file through SSH or FTP. Run and wait! It's very easy to configure character encoding, comes UTF-8 by default.
The answers above will work for changing the values.
If you want to change the number of cells in your list (e.g. I have a list called 'revisions' which has 4 items, I now need 7 items) you will find that you can't simply select your list and amend it on the sheet, So:
go to your 'Formulas' tab
choose "Name Manager"
a pop up box will show what is available for editing. Your list should be in it. Select your list and edit the range.
Simple answer NO.
However you can achieve something similar by running the following version using bind variables:
SELECT * FROM Employees WHERE EmployeeID = :EmpIDVar
Once you run the query above in SQL Developer you will be prompted to enter value for the bind variable EmployeeID.
An answer taken from ChristopheD here: https://stackoverflow.com/a/2500023/1225603
r = "456results string789"
s = ''.join(x for x in r if x.isdigit())
print int(s)
456789
Try checking his post. It shows how to implement transitions between web pages using AngularJS's ngRoute and ngAnimate: How to Make iPhone-Style Web Page Transitions Using AngularJS & CSS
Just wanted to add that the options to cron seem to have changed. Need to pass -n rather than -D.
cygrunsrv -I cron -p /usr/sbin/cron -a -n
As @ocean800 stated I updated node. The below solution is for Ubuntu 16.04 that worked for me, but something similar on OSX may fix this issue.
On Ubuntu 16.04, what worked for me was upgrading node
updating nodejs on ubuntu 16.04
I am replicating solution from the above link below
To update, you can install n
sudo npm install -g n
Then just :
sudo n latest
or a specific version
sudo n 8.9.0
Then try and install
sudo npm install <package>
I've never come across point 2? Can you explain why you think this affects deployment in any way. If anything maven allows you to structure your projects in a modularised way that actually allows hot fixes for bugs in a particular tier, and allows independent development of an API from the remainder of the project for example.
It is possible that you are trying to cram everything into a single module, in which case the problem isn't really maven at all, but the way you are using it.
I had a similar problem, just verify the port where your Mysql server is running, that will solve the problem
For example, my code was:
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:8080/bddventas","root","");
i change the string to
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bddventas","root","");
and voila!!, this workd because my server was running on that port
Hope this help
I don't know the MOST efficient method, but I'd do the following:
Should work \o/
If you need, I can code something up tomorrow in C to demonstrate.
I modified @MyKuLLSKI 's answer and added plurlization support. I took out seconds because I didn't need them, though feel free to re-add it if you need it.
public static String intervalToHumanReadableTime(int intervalMins) {
if(intervalMins <= 0) {
return "0";
} else {
long intervalMs = intervalMins * 60 * 1000;
long days = TimeUnit.MILLISECONDS.toDays(intervalMs);
intervalMs -= TimeUnit.DAYS.toMillis(days);
long hours = TimeUnit.MILLISECONDS.toHours(intervalMs);
intervalMs -= TimeUnit.HOURS.toMillis(hours);
long minutes = TimeUnit.MILLISECONDS.toMinutes(intervalMs);
StringBuilder sb = new StringBuilder(12);
if (days >= 1) {
sb.append(days).append(" day").append(pluralize(days)).append(", ");
}
if (hours >= 1) {
sb.append(hours).append(" hour").append(pluralize(hours)).append(", ");
}
if (minutes >= 1) {
sb.append(minutes).append(" minute").append(pluralize(minutes));
} else {
sb.delete(sb.length()-2, sb.length()-1);
}
return(sb.toString());
}
}
public static String pluralize(long val) {
return (Math.round(val) > 1 ? "s" : "");
}
Windows:
Use below cron:
39 20 * * * root [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -depth -mindepth 1 -maxdepth 1 -type f -cmin +$(/usr/lib/php5/maxlifetime) -print0 | xargs -r -0 rm
Go to File -> Settings -> Editor -> Auto Import -> Java and make the below things:
Select Insert imports on paste value to All
Do tick mark on Add unambigious imports on the fly option and "Optimize imports on the fly*
Functions are first class objects that can be:
To build on the example given by Kenny:
function a(x) {
var w = function b(y) {
return x + y;
}
return w;
};
var returnedFunction = a(3);
alert(returnedFunction(2));
Would alert you with 5.
I have used following command to connect MySQL Server 8.0 in Windows command prompt.
C:\Program Files\MySQL\MySQL Server 8.0\bin>mysql -u root -p my_db
Enter password: ****
or
C:\Program Files\MySQL\MySQL Server 8.0\bin>mysql -u root -p my_db -h localhost
Enter password: ****
Here my_db is schema name.
screen -x
^A
*
, select the one to disconnect, press d
Background: When I was looking for the solution with same problem description, I have always landed on this answer. I would like to provide more sensible solution. (For example: the other attached screen has a different size and a I cannot force resize it in my terminal.)
Note:
PREFIX
is usually^A
=ctrl+a
Note: the display may also be called:
- "user front-end" (in
at
command manual in screen)- "client" (tmux vocabulary where this functionality is
detach-client
)- "terminal" (as we call the window in our user interface) /depending on
1. Reattach a session: screen -x
-x
attach to a not detached screen session without detaching it
2. List displays of this session: PREFIX
*
It is the default key binding for: PREFIX
:displays
.
Performing it within the screen, identify the other display we want to disconnect (e.g. smaller size). (Your current display is displayed in brighter color/bold when not selected).
term-type size user interface window Perms
---------- ------- ---------- ----------------- ---------- -----
screen 240x60 you@/dev/pts/2 nb 0(zsh) rwx
screen 78x40 you@/dev/pts/0 nb 0(zsh) rwx
Using arrows ?
?
, select the targeted display, press d
If nothing happens, you tried to detach your own display and screen will not detach it. If it was another one, within a second or two, the entry will disappear.
Press ENTER
to quit the listing.
Optionally: in order to make the content fit your screen, reflow: PREFIX
F
(uppercase F)
Excerpt from man page of screen:
displays
Shows a tabular listing of all currently connected user front-ends (displays). This is most useful for multiuser sessions. The following keys can be used in displays list:
mouseclick
Move to the selected line. Available when "mousetrack" is set to on.space
Refresh the listd
Detach that displayD
Power detach that displayC-g
,enter
, orescape
Exit the list
If you want to send dates to C# from JS that is actually quite simple - if sending UTC dates is acceptable.
var date = new Date("Tue Jul 12 2011 16:00:00 GMT-0700");
var dateStrToSendToServer = date.toISOString();
... send to C# side ...
var success = DateTimeOffset.TryParse(jsISOStr, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var result);
C# DateTime
already understands ISO date formats and will parse it just fine.
To format from C# to JS just use DateTime.UtcNow.ToString("o")
.
Personally, I'm never comfortable relying on math and logic between different environments to get the milliseconds/ticks to show the EXACT same date and time a user may see on the client (especially where it matters). I would do the same when transferring currency as well (use strings instead to be safe, or separate dollars and cents between two different integers). Sending the date/time as separate values would be just a good (see accepted answer).
You may find your answer in the javadoc of Map#put(K, V) (which actually returns something):
public V put(K key, V value)
Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for this key, the old value is replaced by the specified value. (A map
m
is said to contain a mapping for a keyk
if and only ifm.containsKey(k)
would returntrue
.)Parameters:
key
- key with which the specified value is to be associated.
value
- value to be associated with the specified key.Returns:
previous value associated with specified key, ornull
if there was no mapping forkey
. (Anull
return can also indicate that the map previously associatednull
with the specifiedkey
, if the implementation supportsnull
values.)
So if you don't assign the returned value when calling mymap.put("1", "a string")
, it just becomes unreferenced and thus eligible for garbage collection.
With introduction of React hooks the state management (including forms state) became very simple and, in my opinion, way more understandable and predictable comparing with magic of other frameworks. For example:
const MyComponent = () => {
const [value, setValue] = React.useState('some initial value');
return <input value={value} onChange={e => setValue(e.target.value)} />;
}
This one-way flow makes it trivial to understand how the data is updated and when rendering happens. Simple but powerful to do any complex stuff in predictable and clear way. In this case, do "two-way" form state binding.
The example uses the primitive string value. Complex state management, eg. objects, arrays, nested data, can be managed this way too, but it is easier with help of libraries, like Hookstate (Disclaimer: I am the author of this library). Here is the example of complex state management.
When a form grows, there is an issue with rendering performance: form state is changed (so rerendering is needed) on every keystroke on any form field. This issue is also addressed by Hookstate. Here is the example of the form with 5000 fields: the state is updated on every keystore and there is no performance lag at all.
Works like a charm!
.imageClass {
-webkit-filter: drop-shadow(12px 12px 7px rgba(0,0,0,0.5));
}
Voila! That's it! Obviously this won't work in ie, but who cares...
Here is my one liner ES6 solution with an optional parameter on
.
if (typeof Array.prototype.move === "undefined") {
Array.prototype.move = function(from, to, on = 1) {
this.splice(to, 0, ...this.splice(from, on))
}
}
Adaptation of the first solution proposed by digiguru
The parameter on
is the number of element starting from from
you want to move.
env: django 2.1.7
view:
dict_objs[query_obj.id] = {'obj': query_obj, 'tag': str_tag}
return render(request, 'obj.html', {'dict_objs': dict_objs})
template:
{% for obj_id,dict_obj in dict_objs.items %}
<td>{{ dict_obj.obj.obj_name }}</td>
<td style="display:none">{{ obj_id }}</td>
<td>{{ forloop.counter }}</td>
<td>{{ dict_obj.obj.update_timestamp|date:"Y-m-d H:i:s"}}</td>
The commercial solution, SpreadsheetGear for .NET will do it.
You can see live ASP.NET (C# and VB) samples here and download an evaluation version here.
Disclaimer: I own SpreadsheetGear LLC
There are only two syntaxes at play here.
Plain old array initialisation:
int x[] = {0, 0}; // x[0] = 0, x[1] = 0
A designated initialiser. See the accepted answer to this question: How to initialize a struct in accordance with C programming language standards
The syntax is pretty self-explanatory though. You can initialise like this:
struct X {
int a;
int b;
}
struct X foo = { 0, 1 }; // a = 0, b = 1
or to use any ordering,
struct X foo = { .b = 0, .a = 1 }; // a = 1, b = 0
I believe that npm install
should not run in a production environment. There are several things that can go wrong - npm outage, download of newer dependencies (shrinkwrap seems to have solved this) are two of them.
On the other hand, folder node_modules should not be committed to Git. Apart from their big size, commits including them can become distracting.
The best solutions would be this: npm install
should run in a CI environment that is similar to the production environment. All tests will run and a zipped release file will be created that will include all dependencies.
As @TechSpellBound suggested remove the quotes around the ? signs. Then add a space character at the end of each row in your concatenated string. Otherwise the entire query will be sent as (using only part of it as an example) : .... WHERE bookings.booking_end < date ?OR bookings.booking_start > date ?GROUP BY ....
The ?
and the OR
needs to be seperated by a space character. Do it wherever needed in the query string.
You can also use df.icol(n)
to access a column by integer.
Update: icol
is deprecated and the same functionality can be achieved by:
df.iloc[:, n] # to access the column at the nth position
public String getIMEI(Context context){
TelephonyManager mngr = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
String imei = mngr.getDeviceId();
return imei;
}
git commit -a -m "message"
-a : Includes all currently changed/deleted files in this commit. Keep in mind, however, that untracked (new) files are not included.
-m : Sets the commit's message
Here I can't see even a single correct answer for this question (in WinForms tag) and it's strange for such frequent question.
Items of a ListBox
control may be DataRowView
, Complex Objects, Anonymous types, primary types and other types. Underlying value of an item should be calculated base on ValueMember
.
ListBox
control has a GetItemText
which helps you to get the item text regardless of the type of object you added as item. It really needs such GetItemValue
method.
GetItemValue Extension Method
We can create GetItemValue
Extension Method to get item value which works like GetItemText
:
using System;
using System.Windows.Forms;
using System.ComponentModel;
public static class ListControlExtensions
{
public static object GetItemValue(this ListControl list, object item)
{
if (item == null)
throw new ArgumentNullException("item");
if (string.IsNullOrEmpty(list.ValueMember))
return item;
var property = TypeDescriptor.GetProperties(item)[list.ValueMember];
if (property == null)
throw new ArgumentException(
string.Format("item doesn't contain '{0}' property or column.",
list.ValueMember));
return property.GetValue(item);
}
}
Using above method you don't need to worry about settings of ListBox
and it will return expected Value
for an item. It works with List<T>
, Array
, ArrayList
, DataTable
, List of Anonymous Types, list of primary types and all other lists which you can use as data source. Here is an example of usage:
//Gets underlying value at index 2 based on settings
this.listBox1.GetItemValue(this.listBox1.Items[2]);
Since we created the GetItemValue
method as an extension method, when you want to use the method, don't forget to include the namespace which you put the class in.
This method is applicable on ComboBox
and CheckedListBox
too.
If you need to re-use a string, then use StringBuffer:
String str = "hi";
StringBuffer sb = new StringBuffer(str);
while (...) {
sb.setCharAt(1, 'k');
}
EDIT:
Note that StringBuffer is thread-safe, while using StringBuilder is faster, but not thread-safe.
First, you should download the suitable version for your system from here: https://pecl.php.net/package/mcrypt/1.0.3/windows
Then, you should copy php_mcrypt.dll
to ../xampp/php/ext/
and enable the extension by adding extension=mcrypt
to your xampp/php/php.ini
file.
If you want to reinstall packages specified in a requirements.txt file, without upgrading, so just reinstall the specific versions specified in the requirements.txt file:
pip install -r requirements.txt --ignore-installed
Here is another short one-liner command which creates local branches for all remote branches:
(git branch -r | sed -n '/->/!s#^ origin/##p' && echo master) | xargs -L1 git checkout
It works also properly if tracking local branches are already created.
You can call it after the first git clone
or any time later.
If you do not need to have master
branch checked out after cloning, use
git branch -r | sed -n '/->/!s#^ origin/##p'| xargs -L1 git checkout
There's an outstanding issue to add this functionality to WebDriver, which can be tracked here: http://code.google.com/p/selenium/issues/detail?id=174
A workaround would be to use the JavascriptExector
as follows:
public void resizeTest() {
driver.Navigate().GoToUrl("http://www.example.com/");
((IJavaScriptExecutor)driver).ExecuteScript("window.resizeTo(1024, 768);");
}
Just to update the answer by parag and SpK to align with current SDK backward compatibility from deprecated methods:
int Measuredwidth = 0;
int Measuredheight = 0;
Point size = new Point();
WindowManager w = getWindowManager();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
w.getDefaultDisplay().getSize(size);
Measuredwidth = size.x;
Measuredheight = size.y;
}else{
Display d = w.getDefaultDisplay();
Measuredwidth = d.getWidth();
Measuredheight = d.getHeight();
}
The only way would be for you to consume the entire input stream yourself in the filter, take what you want from it, and then create a new InputStream for the content you read, and put that InputStream in to a ServletRequestWrapper (or HttpServletRequestWrapper).
The downside is you'll have to parse the payload yourself, the standard doesn't make that capability available to you.
Addenda --
As I said, you need to look at HttpServletRequestWrapper.
In a filter, you continue along by calling FilterChain.doFilter(request, response).
For trivial filters, the request and response are the same as the ones passed in to the filter. That doesn't have to be the case. You can replace those with your own requests and/or responses.
HttpServletRequestWrapper is specifically designed to facilitate this. You pass it the original request, and then you can intercept all of the calls. You create your own subclass of this, and replace the getInputStream method with one of your own. You can't change the input stream of the original request, so instead you have this wrapper and return your own input stream.
The simplest case is to consume the original requests input stream in to a byte buffer, do whatever magic you want on it, then create a new ByteArrayInputStream from that buffer. This is what is returned in your wrapper, which is passed to the FilterChain.doFilter method.
You'll need to subclass ServletInputStream and make another wrapper for your ByteArrayInputStream, but that's not a big deal either.
Use df[df.isnull().any(axis=1)]
for python 3.6 or above.
Best of both worlds:
using System.Runtime.InteropServices;
[DllImport("winmm.dll", EntryPoint = "timeBeginPeriod", SetLastError = true)]
private static extern uint TimeBeginPeriod(uint uMilliseconds);
[DllImport("winmm.dll", EntryPoint = "timeEndPeriod", SetLastError = true)]
private static extern uint TimeEndPeriod(uint uMilliseconds);
/**
* Extremely accurate sleep is needed here to maintain performance so system resolution time is increased
*/
private void accurateSleep(int milliseconds)
{
//Increase timer resolution from 20 miliseconds to 1 milisecond
TimeBeginPeriod(1);
Stopwatch stopwatch = new Stopwatch();//Makes use of QueryPerformanceCounter WIN32 API
stopwatch.Start();
while (stopwatch.ElapsedMilliseconds < milliseconds)
{
//So we don't burn cpu cycles
if ((milliseconds - stopwatch.ElapsedMilliseconds) > 20)
{
Thread.Sleep(5);
}
else
{
Thread.Sleep(1);
}
}
stopwatch.Stop();
//Set it back to normal.
TimeEndPeriod(1);
}
This was a interesting read i was looking for a quick copy paste. I knew i had done this before long ago with bitmath differently.
Here was my take on it.
// i had this as a extension method in a static class (this int inValue);
public static string ToBinaryString(int inValue)
{
string result = "";
for (int bitIndexToTest = 0; bitIndexToTest < 32; bitIndexToTest++)
result += ((inValue & (1 << (bitIndexToTest))) > 0) ? '1' : '0';
return result;
}
You could stick spacing in there with a bit of modulos in the loop.
// little bit of spacing
if (((bitIndexToTest + 1) % spaceEvery) == 0)
result += ' ';
You could probably use or pass in a stringbuilder and append or index directly to avoid deallocations and also get around the use of += this way;
This is basic code to find and play an audio file in Swift.
Add your audio file to your Xcode and add the code below.
import AVFoundation
class ViewController: UIViewController {
var audioPlayer = AVAudioPlayer() // declare globally
override func viewDidLoad() {
super.viewDidLoad()
guard let sound = Bundle.main.path(forResource: "audiofilename", ofType: "mp3") else {
print("Error getting the mp3 file from the main bundle.")
return
}
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: sound))
} catch {
print("Audio file error.")
}
audioPlayer.play()
}
@IBAction func notePressed(_ sender: UIButton) { // Button action
audioPlayer.stop()
}
}
I created my own Gem, but I did it in a directory that is not in my load path:
$ pwd
/Users/myuser/projects
$ gem build my_gem/my_gem.gemspec
Then I ran irb
and tried to load the Gem:
> require 'my_gem'
LoadError: cannot load such file -- my_gem
I used the global variable $: to inspect my load path and I realized I am using RVM. And rvm has specific directories in my load path $:
. None of those directories included my ~/projects directory where I created the custom gem.
So one solution is to modify the load path itself:
$: << "/Users/myuser/projects/my_gem/lib"
Note that the lib directory is in the path, which holds the my_gem.rb file which will be required in irb:
> require 'my_gem'
=> true
Now if you want to install the gem in RVM path, then you would need to run:
$ gem install my_gem
But it will need to be in a repository like rubygems.org.
$ gem push my_gem-0.0.0.gem
Pushing gem to RubyGems.org...
Successfully registered gem my_gem
public List<Student> findStudentByReports(Date startDate, Date endDate) {
System.out.println("call findStudentMethd******************with this pattern"
+ startDate
+ endDate
+ "*********************************************");
return em
.createQuery(
"' select attendence from Attendence attendence where attendence.admissionDate BETWEEN : startDate '' AND endDate ''"
+ "'")
.setParameter("startDate", startDate, TemporalType.DATE)
.setParameter("endDate", endDate, TemporalType.DATE)
.getResultList();
}
I always just use NOW():
INSERT INTO table (lastModifiedTime) VALUES (NOW())
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_now
Just to addon if someone is dealing with
, this would work if dealing with
.
Replace it with str_replace()
first and check it with empty()
empty(str_replace(" " ,"" , $YOUR_DATA)) ? $YOUR_DATA = '--' : $YOUR_DATA;
this happened again around last quarter of 2017 . greasemonkey firing too late . after domcontentloaded event already been fired.
what to do:
@run-at document-start
instead of document-endfrom : https://github.com/greasemonkey/greasemonkey/issues/2769
Even as a (private) script writer I'm confused why my script isn't working.
The most likely problem is that the 'DOMContentLoaded' event is fired before the script is run. Now before you come back and say @run-at document-start is set, that directive isn't fully supported at the moment. Due to the very asynchronous nature of WebExtensions there's little guarantee on when something will be executed. When FF59 rolls around we'll have #2663 which will help. It'll actually help a lot of things, debugging too.
Complete example below. I just love the copy/paste :)
HTML
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-body">
<form class="form-horizontal" method="" action="">
<div class="form-group">
<label class="col-md-4 control-label">Email</label>
<div class="col-md-6">
<input type="email" class="form-control" name="email" value="">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input id="password-field" type="password" class="form-control" name="password" value="secret">
<span toggle="#password-field" class="fa fa-lg fa-eye field-icon toggle-password"></span>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
CSS
.field-icon {
float: right;
margin-right: 8px;
margin-top: -23px;
position: relative;
z-index: 2;
cursor:pointer;
}
.container{
padding-top:50px;
margin: auto;
}
JS
$(".toggle-password").click(function() {
$(this).toggleClass("fa-eye fa-eye-slash");
var input = $($(this).attr("toggle"));
if (input.attr("type") == "password") {
input.attr("type", "text");
} else {
input.attr("type", "password");
}
});
Try it here: https://codepen.io/anon/pen/ZoMQZP
rows = a.shape[0] # 2
cols = a.shape[1] # 2
a.shape #(2,2)
a.size # rows * cols = 4
The most simple way is to use find_element_by_class_name('class_name')
You can convert the QString type to python string by just using the str
function. Assuming you are not using any Unicode characters you can get a python
string as below:
text = str(combobox1.currentText())
If you are using any unicode characters, you can do:
text = unicode(combobox1.currentText())
As of Ruby v1.9.3 you don't need to install any Gems in order to parse JSON, simply use require 'json'
:
require 'json'
json = JSON.parse '{"foo":"bar", "ping":"pong"}'
puts json['foo'] # prints "bar"
See JSON at Ruby-Doc.
As stated above to define a map as constant is not possible. But you can declare a global variable which is a struct that contains a map.
The Initialization would look like this:
var romanNumeralDict = struct {
m map[int]string
}{m: map[int]string {
1000: "M",
900: "CM",
//YOUR VALUES HERE
}}
func main() {
d := 1000
fmt.Printf("Value of Key (%d): %s", d, romanNumeralDict.m[1000])
}
I found how to run the query without error, but I hesitate to call it a "solution" without really understanding the underlying cause.
This more closely resembles the beginning of my actual query:
-- Comment
-- More comment
SELECT rf.flowrow, rf.stage, rf.process,
rf.instr instnum, rf.procedure_id, rtd_history.runtime, rtd_history.waittime
FROM
(
-- Comment at beginning of subquery
-- These two comment lines are the problem
SELECT sub2.flowrow, sub2.stage, sub2.process, sub2.instr, sub2.pid
FROM ( ...
The second set of comments above, at the beginning of the subquery, were the problem. When removed, the query executes. Other comments are fine. This is not a matter of some rogue or missing newline causing the following line to be commented, because the following line is a SELECT. A missing select would yield a different error than "not all variables bound."
I asked around and found one co-worker who has run into this -- comments causing query failures -- several times. Does anyone know how this can be the cause? It is my understanding that the very first thing a DBMS would do with comments is see if they contain hints, and if not, remove them during parsing. How can an ordinary comment containing no unusual characters (just letters and a period) cause an error? Bizarre.
You should re-assign the result of the replacement, like this:
sentence = sentence.replace("and", " ");
Be aware that the String
class is immutable, meaning that all of its methods return a new string and never modify the original string in-place, so the result of invoking a method in an instance of String
must be assigned to a variable or used immediately for the change to take effect.
Negatives are your friend here:
SELECT Col1
FROM TABLE
WHERE Col1 like '%[^a-Z0-9]%'
Which says that you want any rows where Col1
consists of any number of characters, then one character not in the set a-Z0-9, and then any number of characters.
If you have a case sensitive collation, it's important that you use a range that includes both upper and lower case A
, a
, Z
and z
, which is what I've given (originally I had it the wrong way around. a
comes before A
. Z
comes after z
)
Or, to put it another way, you could have written your original WHERE
as:
Col1 LIKE '[!@#$%]'
But, as you observed, you'd need to know all of the characters to include in the []
.
You should know that it is not possible to directly run a DDL statement like you do for DML from a PL/SQL block because PL/SQL does not support late binding directly it only support compile time binding which is fine for DML. hence to overcome this type of problem oracle has provided a dynamic SQL approach which can be used to execute the DDL statements.The dynamic sql approach is about parsing and binding of sql string at the runtime. Also you should rememder that DDL statements are by default auto commit hence you should be careful about any of the DDL statement using the dynamic SQL approach incase if you have some DML (which needs to be commited explicitly using TCL) before executing the DDL in the stored proc/function.
You can use any of the following dynamic sql approach to execute a DDL statement from a pl/sql block.
1) Execute immediate
2) DBMS_SQL package
3) DBMS_UTILITY.EXEC_DDL_STATEMENT (parse_string IN VARCHAR2);
Hope this answers your question with explanation.
You could use PHP's file_get_contents();
<?php
$script = file_get_contents('javascriptFile.js');
echo "<script>".$script."</script>";
?>
For more information on the function:
exec is for statement and does not return anything. eval is for expression and returns value of expression.
expression means "something" while statement means "do something".
In general when the user upload the file, the PHP server doen't catch any exception mistake or errors, it means that the file is uploaded successfully. https://www.php.net/manual/en/reserved.variables.files.php#109648
if ( boolval( $_FILES['image']['error'] === 0 ) ) {
// ...
}
Suppose you want to search "column" in "Table" and you want case insenstive search. The best and efficient way is as below;
//create empty JSON Object
mycolumn = {};
//check if column has valid value
if(column) {
mycolumn.column = {$regex: new RegExp(column), $options: "i"};
}
Table.find(mycolumn);
Above code just adds your search value as RegEx and searches in with insensitve criteria set with "i" as option.
All the best.
I'm using both AppCode and XCode.
So .idea/
should be ignored.
append this to Adam's .gitignore
####
# AppCode
.idea/
To stop repeated alert of Nick's answer
ScrollActivate();
function ScrollActivate() {
$(window).on("scroll", function () {
if ($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
$(window).off("scroll");
alert("near bottom!");
}
});
}
use open public proxy YQL, hosted by Yahoo. Handles XML and HTML
https://gist.github.com/rickdog/d66a03d1e1e5959aa9b68869807791d5
classic solution:
for f in $(find . -name "*dbg*"); do mv $f $(echo $f | sed 's/_dbg//'); done
You can use double quotes if ANSI SQL mode is enabled
CREATE TABLE IF NOT EXISTS misc_info
(
id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
"key" TEXT UNIQUE NOT NULL,
value TEXT NOT NULL
)
ENGINE=INNODB;
or the proprietary back tick escaping otherwise. (Where to find the `
character on various keyboard layouts is covered in this answer)
CREATE TABLE IF NOT EXISTS misc_info
(
id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
`key` TEXT UNIQUE NOT NULL,
value TEXT NOT NULL
)
ENGINE=INNODB;
Try this:
var value;
for (var key in dictionary) {
value = dictionary[key];
// your code here...
}
I have achieved this with following
Edit > Blank Operations > Remove Unnecessary Blank and EOL
All this git reset, hard, soft, and everything else mentioned here is probably working (it didn't for me) if you do the steps correctly and some sort of a genie.
If you are the average Joe smo, try this:
How to use git merge --squash?
Saved my life, and will be my go to squash, been using this 4 times since I found out about it. Simple, clean and basically 1 comamnd.
In short:
If you are on a branch lets call it "my_new_feature" off develop and your pull request has 35 commits (or however many) and you want it to be 1.
A. Make sure your branch is up to date, Go on develop, get latest and merge and resolve any conflicts with "my_new_feature"
(this step really you should take as soon as you can all the time anyway)
B. Get latest of develop and branch out to a new branch call it
"my_new_feature_squashed"
C. magic is here.
You want to take your work from "my_new_feature" to "my_new_feature_squashed"
So just do (while on your new branch we created off develop):
git merge --squash my_new_feature
All your changes will now be on your new branch, feel free to test it, then just do your 1 single commit, push, new PR of that branch - and wait for repeat the next day.
Don't you love coding? :)
using(StreamWriter writer = new StreamWriter("debug.txt", true))
{
writer.WriteLine("whatever you text is");
}
The second "true" parameter tells it to append.
Mysqli makes use of object oriented programming. Try using this approach instead:
function dbCon() {
if($mysqli = new mysqli('$hostname','$username','$password','$databasename')) return $mysqli; else return false;
}
if(!dbCon())
exit("<script language='javascript'>alert('Unable to connect to database')</script>");
else $con=dbCon();
if (isset($_GET['part'])){
$partid = $_GET['part'];
$sql = "SELECT *
FROM $usertable
WHERE PartNumber = $partid";
$result=$con->query($sql_query);
$row = $result->fetch_assoc();
$partnumber = $partid;
$nsn = $row["NSN"];
$description = $row["Description"];
$quantity = $row["Quantity"];
$condition = $row["Conditio"];
}
Let me know if you have any questions, I could not test this code so you might need to tripple check it!
Swapping two numbers using third variable be like this,
int temp;
int a=10;
int b=20;
temp = a;
a = b;
b = temp;
printf ("Value of a", %a);
printf ("Value of b", %b);
Swapping two numbers without using third variable
int a = 10;
int b = 20;
a = a+b;
b = a-b;
a = a-b;
printf ("value of a=", %a);
printf ("value of b=", %b);
Here is a thing I made for myself to clear out how things work. I guess others too can find this concrete example useful:
doit().then(function() { log('Now finally done!') });_x000D_
log('---- But notice where this ends up!');_x000D_
_x000D_
// For pedagogical reasons I originally wrote the following doit()-function so that _x000D_
// it was clear that it is a promise. That way wasn't really a normal way to do _x000D_
// it though, and therefore Slikts edited my answer. I therefore now want to remind _x000D_
// you here that the return value of the following function is a promise, because _x000D_
// it is an async function (every async function returns a promise). _x000D_
async function doit() {_x000D_
log('Calling someTimeConsumingThing');_x000D_
await someTimeConsumingThing();_x000D_
log('Ready with someTimeConsumingThing');_x000D_
}_x000D_
_x000D_
function someTimeConsumingThing() {_x000D_
return new Promise(function(resolve,reject) {_x000D_
setTimeout(resolve, 2000);_x000D_
})_x000D_
}_x000D_
_x000D_
function log(txt) {_x000D_
document.getElementById('msg').innerHTML += txt + '<br>'_x000D_
}
_x000D_
<div id='msg'></div>
_x000D_
An anonymous namespace makes the enclosed variables, functions, classes, etc. available only inside that file. In your example it's a way to avoid global variables. There is no runtime or compile time performance difference.
There isn't so much an advantage or disadvantage aside from "do I want this variable, function, class, etc. to be public or private?"
. "$PSScriptRoot\MyFunctions.ps1"
MyA1Func
Availalbe starting in v3, before that see How can I get the file system location of a PowerShell script?. It is VERY common.
P.S. I don't subscribe to the 'everything is a module' rule. My scripts are used by other developers out of GIT, so I don't like to put stuff in specific a place or modify system environment variables before my script will run. It's just a script (or two, or three).
Just create an element by parsing it with jQuery.
<div id="someElement"></div>
<script>
var code = "<script>alert(123);<\/script>";
$("#someElement").append($(code));
</script>
Working example: https://plnkr.co/edit/V2FE28Q2eBrJoJ6PUEBz
Windows 8 64bit runs both 32bit and 64bit applications. You want chromedriver 32bit for the 32bit version of chrome you're using.
The current release of chromedriver (v2.16) has been mentioned as running much smoother since it's older versions (there were a lot of issues before). This post mentions this and some of the slight differences between chromedriver and running the normal firefox driver:
http://seleniumsimplified.com/2015/07/recent-course-source-code-changes-for-webdriver-2-46-0/
What you mentioned about "doesn't call main method" is an odd remark. You may want to elaborate.
Dividing the app into blueprints is a great idea. However, if this isn't enough, and if you want to then divide the Blueprint itself into multiple py files, this is also possible using the regular Python module import system, and then looping through all the routes that get imported from the other files.
I created a Gist with the code for doing this:
https://gist.github.com/Jaza/61f879f577bc9d06029e
As far as I'm aware, this is the only feasible way to divide up a Blueprint at the moment. It's not possible to create "sub-blueprints" in Flask, although there's an issue open with a lot of discussion about this:
https://github.com/mitsuhiko/flask/issues/593
Also, even if it were possible (and it's probably do-able using some of the snippets from that issue thread), sub-blueprints may be too restrictive for your use case anyway - e.g. if you don't want all the routes in a sub-module to have the same URL sub-prefix.
If you have a form action and an input type="submit"
inside form tags, it's going to submit the old fashioned way and basically refresh the page. When doing AJAX type transactions this isn't the desired effect you are after.
Remove the action. Or remove the form altogether, though in cases it does come in handy to serialize to cut your workload. If the form tags remain, move the button outside the form tags, or alternatively make it a link with an onclick or click handler as opposed to an input button. Jquery UI Buttons works great in this case because you can mimic an input button with an a tag element.
Internally in SQL Server dates are stored as 2 integers. The first integer is the number of dates before or after the base date (1900/01/01). The second integer stores the number of clock ticks after midnight, each tick is 1/300 of a second.
Because of this, I often find the simplest way to compare dates is to simply substract them. This handles 90% of my use cases. E.g.,
select date1, date2, date2 - date1 as DifferenceInDays
from MyTable
...
When I need an answer in units other than days, I will use DateDiff.
C:\Program Files (x86)\Microsoft Visual Studio (Your Version Here)\Common7\IDE
A litle late perhaps but I would suggest
$(document).ready(function() {
var layout_select_html = $('#layout_select').html(); //save original dropdown list
$("#column_select").change(function () {
var cur_column_val = $(this).val(); //save the selected value of the first dropdown
$('#layout_select').html(layout_select_html); //set original dropdown list back
$('#layout_select').children('option').each(function(){ //loop through options
if($(this).val().indexOf(cur_column_val)== -1){ //do your conditional and if it should not be in the dropdown list
$(this).remove(); //remove option from list
}
});
});
If you use the following format in your request section while making sure the request url is of http://localhost:XXXX/OperationName/V#.
{
"address": "colombo",
"username": "hesh",
"password": "123",
"registetedDate": "2015-4-3",
"firstname": "hesh",
"contactNo": "07762",
"accountNo": "16161",
"lastName": "jay",
"listName":[
{
"elementOne":"valueOne"
},
{
"elementTwo":"valueTwo"
},
...]
}
You have several options to set up variables from outside your makefile:
From environment - each environment variable is transformed into a makefile variable with the same name and value.
You may also want to set -e
option (aka --environments-override
) on, and your environment variables will override assignments made into makefile (unless these assignments themselves use the override
directive . However, it's not recommended, and it's much better and flexible to use ?=
assignment (the conditional variable assignment operator, it only has an effect if the variable is not yet defined):
FOO?=default_value_if_not_set_in_environment
Note that certain variables are not inherited from environment:
MAKE
is gotten from name of the scriptSHELL
is either set within a makefile, or defaults to /bin/sh
(rationale: commands are specified within the makefile, and they're shell-specific).From command line - make
can take variable assignments as part of his command line, mingled with targets:
make target FOO=bar
But then all assignments to FOO
variable within the makefile will be ignored unless you use the override
directive in assignment. (The effect is the same as with -e
option for environment variables).
Exporting from the parent Make - if you call Make from a Makefile, you usually shouldn't explicitly write variable assignments like this:
# Don't do this!
target:
$(MAKE) -C target CC=$(CC) CFLAGS=$(CFLAGS)
Instead, better solution might be to export these variables. Exporting a variable makes it into the environment of every shell invocation, and Make calls from these commands pick these environment variable as specified above.
# Do like this
CFLAGS=-g
export CFLAGS
target:
$(MAKE) -C target
You can also export all variables by using export
without arguments.
The following test confirms that changing the type to string causes json_encode() to return a numeric as a JSON string (i.e., surrounded by double quotes). Use settype(arr["var"], "integer") or settype($arr["var"], "float") to fix it.
<?php
class testclass {
public $foo = 1;
public $bar = 2;
public $baz = "Hello, world";
}
$testarr = array( 'foo' => 1, 'bar' => 2, 'baz' => 'Hello, world');
$json_obj_txt = json_encode(new testclass());
$json_arr_txt = json_encode($testarr);
echo "<p>Object encoding:</p><pre>" . $json_obj_txt . "</pre>";
echo "<p>Array encoding:</p><pre>" . $json_arr_txt . "</pre>";
// Both above return ints as ints. Type the int to a string, though, and...
settype($testarr["foo"], "string");
$json_arr_cast_txt = json_encode($testarr);
echo "<p>Array encoding w/ cast:</p><pre>" . $json_arr_cast_txt . "</pre>";
?>
Why not use this
unbind()
before bind()
$('#myButton').unbind().bind('click', onButtonClicked);
I'm hesitant to offer this as it misuses ye olde html. It's not a GOOD solution but it is a solution: use a table.
CSS:
table.navigation {
width: 990px;
}
table.navigation td {
text-align: center;
}
HTML:
<table cellpadding="0" cellspacing="0" border="0" class="navigation">
<tr>
<td>HOME</td>
<td>ABOUT</td>
<td>BASIC SERVICES</td>
<td>SPECIALTY SERVICES</td>
<td>OUR STAFF</td>
<td>CONTACT US</td>
</tr>
</table>
This is not what tables were created to do but until we can reliably perform the same action in a better way I guess it is just about permissable.
To get the last element, simply use the size of the list as the second parameter. So for example, if you have 35 files, and you want the last five, you would do:
dataList.subList(30, 35);
A guaranteed safe way to do this is:
dataList.subList(Math.max(0, first), Math.min(dataList.size(), last) );
We can use drush command also to check logs
drush watchdog-show
it will show recent 10 messages.
or if we want to continue showing logs with more information we can user
drush watchdog-show --tail --full.
Maybe something like this
ps -eo pid,pcpu,comm
And if you like to parse and maybe only look at some processes.
#!/bin/sh
ps -eo pid,pcpu,comm | awk '{if ($2 > 4) print }' >> ~/ps_eo_test.txt
If you have a listview and turn it into a gridview you can easily make your gridview columns headers clickable by doing this.
<Style TargetType="GridViewColumnHeader">
<Setter Property="Command" Value="{Binding CommandOrderBy}"/>
<Setter Property="CommandParameter" Value="{Binding RelativeSource={RelativeSource Self},Path=Content}"/>
</Style>
Then just set a delegate command in your code.
public DelegateCommand CommandOrderBy { get { return new DelegateCommand(Delegated_CommandOrderBy); } }
private void Delegated_CommandOrderBy(object obj)
{
throw new NotImplementedException();
}
Im going to assume you all know how to make the ICommand DelegateCommand here. this allowed me to keep all my View clicking in the ViewModel.
I only added this so that there is multiple ways to accomplish the same thing. I did not write code for adding arrow buttons in the header, but that would be done in XAML style, you would need to redesign the entire header which JanDotNet has in their code.
You are not returning a response object from your view my_form_post
. The function ends with implicit return None
, which Flask does not like.
Make the function my_form_post
return an explicit response, for example
return 'OK'
at the end of the function.
Jean-François Corbett's answer is perfect. To be exhaustive I would just like to add that with some restrictons you could also use UsedRange.Columns.Count
or UsedRange.Rows.Count
.
The problem is that UsedRange is not always updated when deleting rows/columns (at least until you reopen the workbook).
The command setwd("~/")
should set your working directory to your home directory. You might be experiencing problems because the OS you are using does not recognise "~/"
as your home directory: this might be because of the OS, or it might be because of not having set that as your home directory elsewhere.
As you have tagged the post using RStudio:
You will now have set the folder as your working directory. Use the command getwd()
to get the working directory as it is now set, and save that as a variable string at the top of your script. Then use setwd
with that string as the argument, so that each time you run the script you use the same directory.
For example at the top of my script I would have:
work_dir <- "C:/Users/john.smith/Documents"
setwd(work_dir)
The problem with your query is that when using a GROUP BY clause (which you essentially do by using distinct) you can only use columns that you group by or aggregate functions. You cannot use the column id because there are potentially different values. In your case there is always only one value because of the HAVING clause, but most RDBMS are not smart enough to recognize that.
This should work however (and doesn't need a join):
UPDATE sales
SET status='ACTIVE'
WHERE id IN (
SELECT MIN(id) FROM sales
GROUP BY saleprice, saledate
HAVING COUNT(id) = 1
)
You could also use MAX or AVG instead of MIN, it is only important to use a function that returns the value of the column if there is only one matching row.
If you want to copy conditional formatting to another document you can use the "Copy to..." feature for the worksheet (click the tab with the name of the worksheet at the bottom) and copy the worksheet to the other document.
Then you can just copy what you want from that worksheet and right-click select "Paste special" -> "Paste conditional formatting only", as described earlier.
You can use CAST and CONVERT to switch between different types of encodings. See: http://dev.mysql.com/doc/refman/5.0/en/charset-convert.html
SELECT column1, CONVERT(column2 USING utf8)
FROM my_table
WHERE my_condition;
On compileSdkVersoin 25, you could do this:
styles.xml
<style name="AppTheme" parent="Theme.AppCompat.Light">
<item name="android:textColorSecondary">@color/your_color</item>
</style>
sql = "insert into Main (Firt Name, Last Name) values(textbox2.Text,textbox3.Text)";
(Firt Name) is not a valid field. It should be FirstName or First_Name. It may be your problem.
I would do:
((-1)+8) % 8
This adds the latter number to the first before doing the modulo giving 7 as desired. This should work for any number down to -8. For -9 add 2*8.
This should be more helpful for debug. Answer from @Juned Ahsan will not specify full URL and will not print multiple headers/parameters.
private String httpServletRequestToString(HttpServletRequest request) {
StringBuilder sb = new StringBuilder();
sb.append("Request Method = [" + request.getMethod() + "], ");
sb.append("Request URL Path = [" + request.getRequestURL() + "], ");
String headers =
Collections.list(request.getHeaderNames()).stream()
.map(headerName -> headerName + " : " + Collections.list(request.getHeaders(headerName)) )
.collect(Collectors.joining(", "));
if (headers.isEmpty()) {
sb.append("Request headers: NONE,");
} else {
sb.append("Request headers: ["+headers+"],");
}
String parameters =
Collections.list(request.getParameterNames()).stream()
.map(p -> p + " : " + Arrays.asList( request.getParameterValues(p)) )
.collect(Collectors.joining(", "));
if (parameters.isEmpty()) {
sb.append("Request parameters: NONE.");
} else {
sb.append("Request parameters: [" + parameters + "].");
}
return sb.toString();
}
private void batteryLevel() {
BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
context.unregisterReceiver(this);
int rawlevel = intent.getIntExtra("level", -1);
int scale = intent.getIntExtra("scale", -1);
int level = -1;
if (rawlevel >= 0 && scale > 0) {
level = (rawlevel * 100) / scale;
}
mBtn.setText("Battery Level Remaining: " + level + "%");
}
};
IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryLevelReceiver, batteryLevelFilter);
}
first of all;
a Fragment
must be inside a FragmentActivity
, that's the first rule,
a FragmentActivity
is quite similar to a standart Activity
that you already know, besides having some Fragment oriented methods
second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView
, where you inflate your layout, think of it as the setContentLayout
here is an example:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.fragment_layout, container, false); return mView; }
and continu your work based on that mView, so to find a View
by id, call mView.findViewById(..);
for the FragmentActivity
part:
the xml part "must" have a FrameLayout
in order to inflate a fragment in it
<FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" > </FrameLayout>
as for the inflation part
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();
begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site
You will have to override the OnPaint method, call the base implementation and the paint your own text.
You will need to create your own CustomProgressBar
and then override OnPaint
to draw what ever text you want.
Custom Progress Bar Class
namespace ProgressBarSample
{
public enum ProgressBarDisplayText
{
Percentage,
CustomText
}
class CustomProgressBar: ProgressBar
{
//Property to set to decide whether to print a % or Text
public ProgressBarDisplayText DisplayStyle { get; set; }
//Property to hold the custom text
public String CustomText { get; set; }
public CustomProgressBar()
{
// Modify the ControlStyles flags
//http://msdn.microsoft.com/en-us/library/system.windows.forms.controlstyles.aspx
SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);
}
protected override void OnPaint(PaintEventArgs e)
{
Rectangle rect = ClientRectangle;
Graphics g = e.Graphics;
ProgressBarRenderer.DrawHorizontalBar(g, rect);
rect.Inflate(-3, -3);
if (Value > 0)
{
// As we doing this ourselves we need to draw the chunks on the progress bar
Rectangle clip = new Rectangle(rect.X, rect.Y, (int)Math.Round(((float)Value / Maximum) * rect.Width), rect.Height);
ProgressBarRenderer.DrawHorizontalChunks(g, clip);
}
// Set the Display text (Either a % amount or our custom text
string text = DisplayStyle == ProgressBarDisplayText.Percentage ? Value.ToString() + '%' : CustomText;
using (Font f = new Font(FontFamily.GenericSerif, 10))
{
SizeF len = g.MeasureString(text, f);
// Calculate the location of the text (the middle of progress bar)
// Point location = new Point(Convert.ToInt32((rect.Width / 2) - (len.Width / 2)), Convert.ToInt32((rect.Height / 2) - (len.Height / 2)));
Point location = new Point(Convert.ToInt32((Width / 2) - len.Width / 2), Convert.ToInt32((Height / 2) - len.Height / 2));
// The commented-out code will centre the text into the highlighted area only. This will centre the text regardless of the highlighted area.
// Draw the custom text
g.DrawString(text, f, Brushes.Red, location);
}
}
}
}
Sample WinForms Application
using System;
using System.Linq;
using System.Windows.Forms;
using System.Collections.Generic;
namespace ProgressBarSample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// Set our custom Style (% or text)
customProgressBar1.DisplayStyle = ProgressBarDisplayText.CustomText;
customProgressBar1.CustomText = "Initialising";
}
private void btnReset_Click(object sender, EventArgs e)
{
customProgressBar1.Value = 0;
btnStart.Enabled = true;
}
private void btnStart_Click(object sender, EventArgs e)
{
btnReset.Enabled = false;
btnStart.Enabled = false;
for (int i = 0; i < 101; i++)
{
customProgressBar1.Value = i;
// Demo purposes only
System.Threading.Thread.Sleep(100);
// Set the custom text at different intervals for demo purposes
if (i > 30 && i < 50)
{
customProgressBar1.CustomText = "Registering Account";
}
if (i > 80)
{
customProgressBar1.CustomText = "Processing almost complete!";
}
if (i >= 99)
{
customProgressBar1.CustomText = "Complete";
}
}
btnReset.Enabled = true;
}
}
}
Do try this; easy one
#!/usr/bin/python
import os
# Creating an empty list that will contain the already traversed paths
donePaths = []
def direct(path):
for paths,dirs,files in os.walk(path):
if paths not in donePaths:
count = paths.count('/')
if files:
for ele1 in files:
print '---------' * (count), ele1
if dirs:
for ele2 in dirs:
print '---------' * (count), ele2
absPath = os.path.join(paths,ele2)
# recursively calling the direct function on each directory
direct(absPath)
# adding the paths to the list that got traversed
donePaths.append(absPath)
path = raw_input("Enter any path to get the following Dir Tree ...\n")
direct(path)
========OUTPUT below========
/home/test
------------------ b.txt
------------------ a.txt
------------------ a
--------------------------- a1.txt
------------------ b
--------------------------- b1.txt
--------------------------- b2.txt
--------------------------- cde
------------------------------------ cde.txt
------------------------------------ cdeDir
--------------------------------------------- cdeDir.txt
------------------ c
--------------------------- c.txt
--------------------------- c1
------------------------------------ c1.txt
------------------------------------ c2.txt
Search your local system's bash man page for ^INVOCATION for information on which file is going to be read at startup.
man bash
/^INVOCATION
Also in the FILES section,
~/.bash_profile
The personal initialization file, executed for login shells
~/.bashrc
The individual per-interactive-shell startup file
Add your script to the proper file. Make sure the script is in the $PATH, or use the absolute path to the script file.
Use a static AutoResetEvent in your spawned threads to call back to the main thread using the Set() method. This guy has a fairly good demo in SO on how to use it.
Whether you're running within the context of ASP.NET or not, you should be able to use HostingEnvironment.ApplicationPhysicalPath
Here is an example of concatenation operator:
architecture EXAMPLE of CONCATENATION is
signal Z_BUS : bit_vector (3 downto 0);
signal A_BIT, B_BIT, C_BIT, D_BIT : bit;
begin
Z_BUS <= A_BIT & B_BIT & C_BIT & D_BIT;
end EXAMPLE;
As a general rule use encodeURIComponent
. Don't be scared of the long name thinking it's more specific in it's use, to me it's the more commonly used method. Also don't be suckered into using encodeURI because you tested it and it appears to be encoding properly, it's probably not what you meant to use and even though your simple test using "Fred" in a first name field worked, you'll find later when you use more advanced text like adding an ampersand or a hashtag it will fail. You can look at the other answers for the reasons why this is.
In my own case I have the following error
Illegal mix of collations (utf8_general_ci,IMPLICIT) and (utf8_unicode_ci,IMPLICIT) for operation '='
$this->db->select("users.username as matric_no, CONCAT(users.surname, ' ', users.first_name, ' ', users.last_name) as fullname") ->join('users', 'users.username=classroom_students.matric_no', 'left') ->where('classroom_students.session_id', $session) ->where('classroom_students.level_id', $level) ->where('classroom_students.dept_id', $dept);
After weeks of google searching I noticed that the two fields I am comparing consists of different collation name. The first one i.e username is of utf8_general_ci while the second one is of utf8_unicode_ci so I went back to the structure of the second table and changed the second field (matric_no) to utf8_general_ci and it worked like a charm.
If forcing a push doesn't help ("git push --force origin
" or "git push --force origin master
" should be enough), it might mean that the remote server is refusing non fast-forward pushes either via receive.denyNonFastForwards config variable (see git config manpage for description), or via update / pre-receive hook.
With older Git you can work around that restriction by deleting "git push origin :master
" (see the ':' before branch name) and then re-creating "git push origin master
" given branch.
If you can't change this, then the only solution would be instead of rewriting history to create a commit reverting changes in D-E-F:
A-B-C-D-E-F-[(D-E-F)^-1] master A-B-C-D-E-F origin/master
Here are several benefits of IHttpActionResult
over HttpResponseMessage
mentioned in Microsoft ASP.Net Documentation:
- Simplifies unit testing your controllers.
- Moves common logic for creating HTTP responses into separate classes.
- Makes the intent of the controller action clearer, by hiding the low-level details of constructing the response.
But here are some other advantages of using IHttpActionResult
worth mentioning:
Ok
NotFound
Exception
Unauthorized
BadRequest
Conflict
Redirect
InvalidModelState
(link to full list)ExecuteAsync
method.ResponseMessageResult ResponseMessage(HttpResponseMessage response)
to convert HttpResponseMessage to IHttpActionResult.The code generates a compilation error because your instance type is an Animal:
Animal animal=new Animal();
Downcasting is not allowed in Java for several reasons. See here for details.
send email by smtp
public void EmailSend(string subject, string host, string from, string to, string body, int port, string username, string password, bool enableSsl)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient smtpServer = new SmtpClient(host);
mail.Subject = subject;
mail.From = new MailAddress(from);
mail.To.Add(to);
mail.Body = body;
smtpServer.Port = port;
smtpServer.Credentials = new NetworkCredential(username, password);
smtpServer.EnableSsl = enableSsl;
smtpServer.Send(mail);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
On client:
axios.get('/api', {
params: {
foo: 'bar'
}
});
On server:
function get(req, res, next) {
let param = req.query.foo
.....
}
Trying to work with spark-2.x.x, building Spark source code didn't work for me.
So, although I'm not going to use Hadoop, I downloaded the pre-built Spark with hadoop embeded : spark-2.0.0-bin-hadoop2.7.tar.gz
Point SPARK_HOME on the extracted directory, then add to PATH
: ;%SPARK_HOME%\bin;
Download the executable winutils from the Hortonworks repository, or from Amazon AWS platform winutils.
Create a directory where you place the executable winutils.exe. For example, C:\SparkDev\x64. Add the environment variable %HADOOP_HOME%
which points to this directory, then add %HADOOP_HOME%\bin
to PATH.
Using command line, create the directory:
mkdir C:\tmp\hive
Using the executable that you downloaded, add full permissions to the file directory you created but using the unixian formalism:
%HADOOP_HOME%\bin\winutils.exe chmod 777 /tmp/hive
Type the following command line:
%SPARK_HOME%\bin\spark-shell
Scala command line input should be shown automatically.
Remark : You don't need to configure Scala separately. It's built-in too.
I would use css tables to achieve a 100% sidebar height.
The basic idea is to wrap the sidebar and main divs in a container.
Give the container a display:table
And give the 2 child divs (sidebar and main) a display: table-cell
Like so..
#container {
display: table;
}
#main {
display: table-cell;
vertical-align: top;
}
#sidebar {
display: table-cell;
vertical-align: top;
}
Take a look at this LIVE DEMO where I have modified your initial markup using the above technique (I have used background colors for the different divs so that you can see which ones are which)
You should use the HasValue
property:
SomeProperty.HasValue
For example:
if (SomeProperty.HasValue)
{
// Do Something
}
else
{
// Do Something Else
}
FYI
public Nullable<System.Guid> SomeProperty { get; set; }
is equivalent to:
public System.Guid? SomeProperty { get; set; }
The MSDN Reference: http://msdn.microsoft.com/en-us/library/sksw8094.aspx
To get better results and robustness against differents types of matrices, you can do this in addition to the first answer, that copy the data :
cv::Mat source = getYourSource();
// Setup a rectangle to define your region of interest
cv::Rect myROI(10, 10, 100, 100);
// Crop the full image to that image contained by the rectangle myROI
// Note that this doesn't copy the data
cv::Mat croppedRef(source, myROI);
cv::Mat cropped;
// Copy the data into new matrix
croppedRef.copyTo(cropped);
RecordCount is what you want to use.
If Not temp_rst1.RecordCount > 0 ...
doesnt directly answer your question. But helpful for those who want to start something after some time.
Future.delayed(Duration(seconds: 1), () {
print('yo hey');
});
public String getUsername() {
AccountManager manager = AccountManager.get(this);
Account[] accounts = manager.getAccountsByType("com.google");
List<String> possibleEmails = new LinkedList<String>();
for (Account account : accounts) {
// TODO: Check possibleEmail against an email regex or treat
// account.name as an email address only for certain account.type values.
possibleEmails.add(account.name);
}
if (!possibleEmails.isEmpty() && possibleEmails.get(0) != null) {
String email = possibleEmails.get(0);
String[] parts = email.split("@");
if (parts.length > 1)
return parts[0];
}
return null;
}
send output to console, append to console log, delete output from current command
dir >> usb-create.1 && type usb-create.1 >> usb-create.log | type usb-create.1 && del usb-create.1
You can also set a max execution time in your .htaccess
file:
php_value max_execution_time 180
That's a bad practice to use the ==
equality operator instead of ===
.
undefined === undefined // true
null == undefined // true
null === undefined // false
The object.x === undefined
should return true
if x
is unknown property.
In chapter Bad Parts of JavaScript: The Good Parts, Crockford writes the following:
If you attempt to extract a value from an object, and if the object does not have a member with that name, it returns the undefined value instead.
In addition to undefined, JavaScript has a similar value called null. They are so similar that == thinks they are equal. That confuses some programmers into thinking that they are interchangeable, leading to code like
value = myObject[name]; if (value == null) { alert(name + ' not found.'); }
It is comparing the wrong value with the wrong operator. This code works because it contains two errors that cancel each other out. That is a crazy way to program. It is better written like this:
value = myObject[name]; if (value === undefined) { alert(name + ' not found.'); }
In fact, eclipse export will call
java -jar android-sdk-windows\tools\lib\sdklib.jar com.android.sdklib.build.ApkBuilderMain
and then call com.android.sdklib.internal.build.SignedJarBuilder.
[str(x) for x in EmployeeList]
would do a conversion, but it would fail if the unicode string characters do not lie in the ascii range.
>>> EmployeeList = [u'1001', u'Karick', u'14-12-2020', u'1$']
>>> [str(x) for x in EmployeeList]
['1001', 'Karick', '14-12-2020', '1$']
>>> EmployeeList = [u'1001', u'????', u'14-12-2020', u'1$']
>>> [str(x) for x in EmployeeList]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)
MS SQL Server 2008 introduces the MERGE statement, which I believe is part of the SQL:2003 standard. As many have shown it is not a big deal to handle one row cases, but when dealing with large datasets, one needs a cursor, with all the performance problems that come along. The MERGE statement will be much welcomed addition when dealing with large datasets.