The below 'd help you to add the cert to the Root Store-
certutil -enterprise -f -v -AddStore "Root" <Cert File path>
This worked for me perfectly.
You need to use the openssl pkcs12 -export -chain -in server.crt -CAfile ...
Your PFX file should contain the private key within it. Export the private key and certificate directly from your PFX file (e.g. using OpenSSL) and import them into your Java keystore.
Edit
Further information:
openssl pkcs12 -in filename.pfx -nocerts -out key.pem
openssl pkcs12 -in filename.pfx -clcerts -nokeys -out cert.pem
keytool
.Is there any equivalent for the truststore? How can I view the trusted certificates?
Yes there is.The exact same command since keystore and truststore differ only in what they store i.e. private key or signed public key (certificate)
No other difference
The SSL errors are often thrown by network management software such as Cyberroam.
To answer your question,
you will have to enter badidea into Chrome every time you visit a website.
You might at times have to enter it more than once, as the site may try to pull in various resources before load, hence causing multiple SSL errors
On Windows you can try these steps:
/lib/security
with JRE (you can use a comand System.out.println(System.getProperty("java.home");
to find the folder with the current JRE). Make a backup of the file.install certificate in java linux
/opt/jdk(version)/bin/keytool -import -alias aliasname -file certificate.cer -keystore cacerts -storepass password
These are the steps which solved my problem:
Search the path where my java was installed
find / -name jre
Move to java directory (where jre was installed on my server)
cd /path/to/jre/bin
Create SSL certificate with keytool command
./keytool -genkey -alias [mypassword] -keyalg [RSA]
May be this will help:
wget --no-check-certificate https://blah-blah.tld/path/filename
I had this problem couple of weeks ago. I first tried the troubleshooting on the Android developer site, but without luck. After that I reinstalled the Android SDK, which solved my problem.
You can move your proxy authentication and ssl staff to soap handler
port = new SomeService().getServicePort();
Binding binding = ((BindingProvider) port).getBinding();
binding.setHandlerChain(Collections.<Handler>singletonList(new ProxyHandler()));
This is my example, do all network ops
class ProxyHandler implements SOAPHandler<SOAPMessageContext> {
static class TrustAllHost implements HostnameVerifier {
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
}
static class TrustAllCert implements X509TrustManager {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
}
private SSLSocketFactory socketFactory;
public SSLSocketFactory getSocketFactory() throws Exception {
// just an example
if (socketFactory == null) {
SSLContext sc = SSLContext.getInstance("SSL");
TrustManager[] trustAllCerts = new TrustManager[] { new TrustAllCert() };
sc.init(null, trustAllCerts, new java.security.SecureRandom());
socketFactory = sc.getSocketFactory();
}
return socketFactory;
}
@Override public boolean handleMessage(SOAPMessageContext msgCtx) {
if (!Boolean.TRUE.equals(msgCtx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY)))
return true;
HttpURLConnection http = null;
try {
SOAPMessage outMessage = msgCtx.getMessage();
outMessage.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, "UTF-8");
// outMessage.setProperty(SOAPMessage.WRITE_XML_DECLARATION, true); // Not working. WTF?
ByteArrayOutputStream message = new ByteArrayOutputStream(2048);
message.write("<?xml version='1.0' encoding='UTF-8'?>".getBytes("UTF-8"));
outMessage.writeTo(message);
String endpoint = (String) msgCtx.get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY);
URL service = new URL(endpoint);
Proxy proxy = Proxy.NO_PROXY;
//Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("{proxy.url}", {proxy.port}));
http = (HttpURLConnection) service.openConnection(proxy);
http.setReadTimeout(60000); // set your timeout
http.setConnectTimeout(5000);
http.setUseCaches(false);
http.setDoInput(true);
http.setDoOutput(true);
http.setRequestMethod("POST");
http.setInstanceFollowRedirects(false);
if (http instanceof HttpsURLConnection) {
HttpsURLConnection https = (HttpsURLConnection) http;
https.setHostnameVerifier(new TrustAllHost());
https.setSSLSocketFactory(getSocketFactory());
}
http.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");
http.setRequestProperty("Content-Length", Integer.toString(message.size()));
http.setRequestProperty("SOAPAction", "");
http.setRequestProperty("Host", service.getHost());
//http.setRequestProperty("Proxy-Authorization", "Basic {proxy_auth}");
InputStream in = null;
OutputStream out = null;
try {
out = http.getOutputStream();
message.writeTo(out);
} finally {
if (out != null) {
out.flush();
out.close();
}
}
int responseCode = http.getResponseCode();
MimeHeaders responseHeaders = new MimeHeaders();
message.reset();
try {
in = http.getInputStream();
IOUtils.copy(in, message);
} catch (final IOException e) {
try {
in = http.getErrorStream();
IOUtils.copy(in, message);
} catch (IOException e1) {
throw new RuntimeException("Unable to read error body", e);
}
} finally {
if (in != null)
in.close();
}
for (Map.Entry<String, List<String>> header : http.getHeaderFields().entrySet()) {
String name = header.getKey();
if (name != null)
for (String value : header.getValue())
responseHeaders.addHeader(name, value);
}
SOAPMessage inMessage = MessageFactory.newInstance()
.createMessage(responseHeaders, new ByteArrayInputStream(message.toByteArray()));
if (inMessage == null)
throw new RuntimeException("Unable to read server response code " + responseCode);
msgCtx.setMessage(inMessage);
return false;
} catch (Exception e) {
throw new RuntimeException("Proxy error", e);
} finally {
if (http != null)
http.disconnect();
}
}
@Override public boolean handleFault(SOAPMessageContext context) {
return false;
}
@Override public void close(MessageContext context) {
}
@Override public Set<QName> getHeaders() {
return Collections.emptySet();
}
}
It use UrlConnection, you can use any library you want in handler. Have fun!
If you're working in PowerShell you can use something like the following, given a pfx file InputBundle.pfx, to produce a DER encoded (binary) certificate file OutputCert.der:
Get-PfxCertificate -FilePath InputBundle.pfx |
Export-Certificate -FilePath OutputCert.der -Type CERT
Newline added for clarity, but you can of course have this all on a single line.
If you need the certificate in ASCII/Base64 encoded PEM format, you can take extra steps to do so as documented elsewhere, such as here: https://superuser.com/questions/351548/windows-integrated-utility-to-convert-der-to-pem
If you need to export to a different format than DER encoded, you can change the -Type
parameter for Export-Certificate to use the types supported by .NET, as seen in help Export-Certificate -Detailed
:
-Type <CertType>
Specifies the type of output file for the certificate export as follows.
-- SST: A Microsoft serialized certificate store (.sst) file format which can contain one or more certificates. This is the default value for multiple certificates.
-- CERT: A .cer file format which contains a single DER-encoded certificate. This is the default value for one certificate.
-- P7B: A PKCS#7 file format which can contain one or more certificates.
I had the same probleme but the response made by Mike A helped me to figure it out: I had a my certificate, an intermediate certificate (Gandi) , an other intermediate (UserTrustRSA) and finally the RootCA certificate (AddTrust).
So first i made a chain file with Gandi+UserTrustRSA+AddTrust and specified it with SSLCertificateChainFile. But it didn't worked.
So i tried MikeA answer by just putting AddTruct cert in a file and specified it with SSLCACertificateFile and removing SSLCertificateChainFile.But it didn't worked.
So finnaly i made a chain file with only Gandi+UserTrustRSA specified by SSLCertificateChainFile and the other file with only the RootCA specified by SSLCACertificateFile and it worked.
# Server Certificate:
SSLCertificateFile /etc/ssl/apache/myserver.cer
# Server Private Key:
SSLCertificateKeyFile /etc/ssl/apache/myserver.key
# Server Certificate Chain:
SSLCertificateChainFile /etc/ssl/apache/Gandi+UserTrustRSA.pem
# Certificate Authority (CA):
SSLCACertificateFile /etc/ssl/apache/AddTrust.pem
Seems logical when you read but hope it helps.
I created .pfx file from .key and .pem files.
Like this openssl pkcs12 -inkey rootCA.key -in rootCA.pem -export -out rootCA.pfx
That's not the direct answer but still maybe it helps out someone else.
Yes -- the X509Store.Certificates
property returns a snapshot of the X.509 certificate store.
this happened to me when using JUnit + rest assured + hamcrest, in this case, dont add junit to build path, if you have the maven project, this resolved me, below is the pom.xml
<dependencies>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
You'll have to jailbreak your device.
Under
Provisioning -> Distribution -> Distribution Provisioning Profiles
I downloaded the desired certificate again and installed it. Now I don't see an empty file in Xcode. The build also works now (no code sign error).
What I also did: I downloaded the WWDR and installed it, but I don't know if that was the reason (because I think it's always the same)
If you use Windows, probably the location is like this:
C:\User\YourUser\.android\debug.keystore
You can do that in one command:
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365
You can also add -nodes
(short for no DES
) if you don't want to protect your private key with a passphrase. Otherwise it will prompt you for "at least a 4 character" password.
The days
parameter (365) you can replace with any number to affect the expiration date. It will then prompt you for things like "Country Name", but you can just hit Enter and accept the defaults.
Add -subj '/CN=localhost'
to suppress questions about the contents of the certificate (replace localhost
with your desired domain).
Self-signed certificates are not validated with any third party unless you import them to the browsers previously. If you need more security, you should use a certificate signed by a certificate authority (CA).
I solved the problem by cat'ing all the pems together:
cat cert.pem chain.pem fullchain.pem >all.pem
openssl pkcs12 -export -in all.pem -inkey privkey.pem -out cert_and_key.p12 -name tomcat -CAfile chain.pem -caname root -password MYPASSWORD
keytool -importkeystore -deststorepass MYPASSWORD -destkeypass MYPASSWORD -destkeystore MyDSKeyStore.jks -srckeystore cert_and_key.p12 -srcstoretype PKCS12 -srcstorepass MYPASSWORD -alias tomcat
keytool -import -trustcacerts -alias root -file chain.pem -keystore MyDSKeyStore.jks -storepass MYPASSWORD
(keytool didn't know what to do with a PKCS7 formatted key)
I got all the pems from letsencrypt
You can list down the entries (certificates details) with the keytool and even you don't need to mention the store type.
keytool -list -v -keystore cert.p12 -storepass <password>
Keystore type: PKCS12
Keystore provider: SunJSSE
Your keystore contains 1 entry
Alias name: 1
Creation date: Jul 11, 2020
Entry type: PrivateKeyEntry
Certificate chain length: 2
If you're using Linux, you can also follow this official wiki pages:
Basically:
Now, the following command will add the certificate (where YOUR_FILE is your exported file):
certutil -d sql:$HOME/.pki/nssdb -A -t "P,," -n YOUR_FILE -i YOUR_FILE
To list all your certificates, run the following command:
certutil -d sql:$HOME/.pki/nssdb -L
If it still doesn't work, you could be affected by this bug: Issue 55050: Ubuntu SSL error 8179
P.S. Please also make sure that you have libnss3-tools
, before you can use above commands.
If you don't have, please install it by:
sudo apt-get install libnss3-tools # on Ubuntu
sudo yum install nss-tools # on Fedora, Red Hat, etc.
As a bonus, you can use the following handy scripts:
$ cat add_cert.sh
certutil -d sql:$HOME/.pki/nssdb -A -t "P,," -n $1 -i $1
$ cat list_cert.sh
certutil -d sql:$HOME/.pki/nssdb -L # add '-h all' to see all built-in certs
$ cat download_cert.sh
echo QUIT | openssl s_client -connect $1:443 | sed -ne '/BEGIN CERT/,/END CERT/p'
Usage:
add_cert.sh [FILE]
list_cert.sh
download_cert.sh [DOMAIN]
Run Chrome with --auto-ssl-client-auth
parameter
google-chrome --auto-ssl-client-auth
The openssl
documentation says that file supplied as the -in
argument must be in PEM format.
Turns out that, contrary to the CA's manual, the certificate returned by the CA which I stored in myCert.cer
is not PEM format rather it is PKCS7.
In order to create my .p12
, I had to first convert the certificate to PEM:
openssl pkcs7 -in myCert.cer -print_certs -out certs.pem
and then execute
openssl pkcs12 -export -out keyStore.p12 -inkey myKey.pem -in certs.pem
Firefox now (since 58) uses a SQLite database cert9.db instead of legacy cert8.db. I have made a fix to a solution presented here to make it work with new versions of Firefox:
certificateFile="MyCa.cert.pem"
certificateName="MyCA Name"
for certDB in $(find ~/.mozilla* ~/.thunderbird -name "cert9.db")
do
certDir=$(dirname ${certDB});
#log "mozilla certificate" "install '${certificateName}' in ${certDir}"
certutil -A -n "${certificateName}" -t "TCu,Cuw,Tuw" -i ${certificateFile} -d sql:${certDir}
done
TLS client certificates are not sent in HTTP headers. They are transmitted by the client as part of the TLS handshake, and the server will typically check the validity of the certificate during the handshake as well.
If the certificate is accepted, most web servers can be configured to add headers for transmitting the certificate or information contained on the certificate to the application. Environment variables are populated with certificate information in Apache and Nginx which can be used in other directives for setting headers.
As an example of this approach, the following Nginx config snippet will validate a client certificate, and then set the SSL_CLIENT_CERT
header to pass the entire certificate to the application. This will only be set when then certificate was successfully validated, so the application can then parse the certificate and rely on the information it bears.
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /path/to/chainedcert.pem; # server certificate
ssl_certificate_key /path/to/key; # server key
ssl_client_certificate /path/to/ca.pem; # client CA
ssl_verify_client on;
proxy_set_header SSL_CLIENT_CERT $ssl_client_cert;
location / {
proxy_pass http://localhost:3000;
}
}
Just Go To *Startmenu >>Java >>Configure Java >> Security >> Edit site list >> copy and paste your Link with problem >> OK Problem fixed :)*
If you only want to verify that issuer of UserCert.pem
is actually Intermediate.pem
do the following (example uses: OpenSSL 1.1.1
):
openssl verify -no-CAfile -no-CApath -partial_chain -trusted Intermediate.pem UserCert.pem
and you will get:
UserCert.pem: OK
or
UserCert.pem: verification failed
Since this is caused by a misconfiguration of the network you are operating on just setup your smartphone to share its internet connection using USB tethering and use it to download the missing packages.
Just for anyone else who goes through this, the answers above are correct but it can still be a bit confusing especially if you have multiple certificates. These were the steps that I took:
First take note of the date in the actual distribution certificate that is missing its private key. Then go to the keychain application on the other computer and type iOS in the search bar. It will show all of your iOS Developer and Distribution keys so you have to find the right one.
Click the right arrow of each iOS Distribution entry to reveal the certificate and find the one with the correct date and export that one by right clicking and selection export.
Then just import it in the keychain of the new computer and at least with Xcode 9.3 it immediately recognizes it and corrects the error so you can now upload your achieve.
Here is what you can do:-
Exim SSL certificates
By default, the /etc/exim.conf will use the cert/key files:
/etc/exim.cert
/etc/exim.key
so if you're wondering where to set your files, that's where.
They're controlled by the exim.conf's options:
tls_certificate = /etc/exim.cert
tls_privatekey = /etc/exim.key
Intermediate Certificates
If you have a CA Root certificate (ca bundle, chain, etc.) you'll add the contents of your CA into the exim.cert, after your actual certificate.
Probably a good idea to make sure you have a copy of everything elsewhere in case you make an error.
Dovecot and ProFtpd should also read it correctly, so dovecot no longer needs the ssl_ca option. So for both cases, there is no need to make any changes to either the exim.conf or dovecot.conf(/etc/dovecot/conf/ssl.conf)
keytool
comes with the JDK installation (in the bin
folder):
keytool -importcert -file "your.cer" -keystore your.jks -alias "<anything>"
This will create a new keystore and add just your certificate to it.
So, you can't convert a certificate to a keystore: you add a certificate to a keystore.
You may not want to disable all ssl Verificatication and so you can just disable the hostName verification via this which is a bit less scary than the alternative:
HttpsURLConnection.setDefaultHostnameVerifier(
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
[EDIT]
As mentioned by conapart3 SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
is now deprecated, so it may be removed in a later version, so you may be forced in the future to roll your own, although I would still say I would steer away from any solutions where all verification is turned off.
If you are trying to load a cert from a .pfx file in IIS the solution may be as simple as enabling this option for the Application Pool
.
Right click on the App Pool and select Advanced Settings
.
Then enable Load User Profile
I ran into this same problem when I wanted to enable SSL to a project hosted on IIS 8. Finally the tool I used was OpenSSL, after many days fighting with makecert commands.The certificate is generated in Debian, but I could import it seamlessly into IIS 7 and 8.
Download the OpenSSL compatible with your OS and this configuration file. Set the configuration file as default configuration of OpenSSL.
First we will generate the private key and certificate of Certification Authority (CA). This certificate is to sign the certificate request (CSR).
You must complete all fields that are required in this process.
openssl req -new -x509 -days 3650 -extensions v3_ca -keyout root-cakey.pem -out root-cacert.pem -newkey rsa:4096
You can create a configuration file with default settings like this: Now we will generate the certificate request, which is the file that is sent to the Certification Authorities.
The Common Name must be set the domain of your site, for example: public.organization.com.
openssl req -new -nodes -out server-csr.pem -keyout server-key.pem -newkey rsa:4096
Now the certificate request is signed with the generated CA certificate.
openssl x509 -req -days 365 -CA root-cacert.pem -CAkey root-cakey.pem -CAcreateserial -in server-csr.pem -out server-cert.pem
The generated certificate must be exported to a .pfx file that can be imported into the IIS.
openssl pkcs12 -export -out server-cert.pfx -inkey server-key.pem -in server-cert.pem -certfile root-cacert.pem -name "Self Signed Server Certificate"
In this step we will import the certificate CA.
In your server must import the CA certificate to the Trusted Root Certification Authorities, for IIS can trust the certificate to be imported. Remember that the certificate to be imported into the IIS, has been signed with the certificate of the CA.
With this step, the IIS trust on the authenticity of our certificate.
In our last step we will import the certificate to IIS and add the binding site.
Now go to your site on IIS Manager and select Bindings... and Add a new binding.
Select https as the type of binding and you should be able to see the imported certificate.
The selected answer didn't work for me, but it's close. I found a tutorial that worked for me and the certificate I obtained from StartCom.
Change the leader and trailer so the file looks similar to this:
-----BEGIN PKCS7-----
[... certificate content here ...]
-----END PKCS7-----
For example, my StartCom certificate began with:
-----BEGIN CERTIFICATE-----
and ended with:
-----END CERTIFICATE-----
Run the following OpenSSL command (works on Ubuntu 14.04.4, as of this writing):
openssl pkcs7 -print_certs –in pkcs7.p7b -out pem.cer
The output is a .cer with the certificate chain.
Reference: http://www.freetutorialssubmit.com/extract-certificates-from-P7B/2206
If you have a rooted device, you can use a Magisk Module to move User Certs to System so it will be Trusted Certificate
Converting Using OpenSSL
These commands allow you to convert certificates and keys to different formats to make them compatible with specific types of servers or software.
Convert a DER file (.crt .cer .der) to PEM
openssl x509 -inform der -in certificate.cer -out certificate.pem
Convert a PEM file to DER
openssl x509 -outform der -in certificate.pem -out certificate.der
Convert a PKCS#12 file (.pfx .p12) containing a private key and certificates to PEM
openssl pkcs12 -in keyStore.pfx -out keyStore.pem -nodes
You can add -nocerts to only output the private key or add -nokeys to only output the certificates.
Convert a PEM certificate file and a private key to PKCS#12 (.pfx .p12)
openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.crt -certfile CACert.crt
Convert PEM to CRT (.CRT file)
openssl x509 -outform der -in certificate.pem -out certificate.crt
OpenSSL Convert PEM
Convert PEM to DER
openssl x509 -outform der -in certificate.pem -out certificate.der
Convert PEM to P7B
openssl crl2pkcs7 -nocrl -certfile certificate.cer -out certificate.p7b -certfile CACert.cer
Convert PEM to PFX
openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.crt -certfile CACert.crt
OpenSSL Convert DER
Convert DER to PEM
openssl x509 -inform der -in certificate.cer -out certificate.pem
OpenSSL Convert P7B
Convert P7B to PEM
openssl pkcs7 -print_certs -in certificate.p7b -out certificate.cer
Convert P7B to PFX
openssl pkcs7 -print_certs -in certificate.p7b -out certificate.cer
openssl pkcs12 -export -in certificate.cer -inkey privateKey.key -out certificate.pfx -certfile CACert.cer
OpenSSL Convert PFX
Convert PFX to PEM
openssl pkcs12 -in certificate.pfx -out certificate.cer -nodes
Generate rsa keys by OpenSSL
Using OpenSSL on the command line you’d first need to generate a public and private key, you should password protect this file using the -passout argument, there are many different forms that this argument can take so consult the OpenSSL documentation about that.
openssl genrsa -out private.pem 1024
This creates a key file called private.pem that uses 1024 bits. This file actually have both the private and public keys, so you should extract the public one from this file:
openssl rsa -in private.pem -out public.pem -outform PEM -pubout
or
openssl rsa -in private.pem -pubout > public.pem
or
openssl rsa -in private.pem -pubout -out public.pem
You’ll now have public.pem containing just your public key, you can freely share this with 3rd parties. You can test it all by just encrypting something yourself using your public key and then decrypting using your private key, first we need a bit of data to encrypt:
Example file :
echo 'too many secrets' > file.txt
You now have some data in file.txt, lets encrypt it using OpenSSL and the public key:
openssl rsautl -encrypt -inkey public.pem -pubin -in file.txt -out file.ssl
This creates an encrypted version of file.txt calling it file.ssl, if you look at this file it’s just binary junk, nothing very useful to anyone. Now you can unencrypt it using the private key:
openssl rsautl -decrypt -inkey private.pem -in file.ssl -out decrypted.txt
You will now have an unencrypted file in decrypted.txt:
cat decrypted.txt
|output -> too many secrets
RSA TOOLS Options in OpenSSL
NAME
rsa - RSA key processing tool
SYNOPSIS
openssl rsa [-help] [-inform PEM|NET|DER] [-outform PEM|NET|DER] [-in filename] [-passin arg] [-out filename] [-passout arg] [-aes128] [-aes192] [-aes256] [-camellia128] [-camellia192] [-camellia256] [-des] [-des3] [-idea] [-text] [-noout] [-modulus] [-check] [-pubin] [-pubout] [-RSAPublicKey_in] [-RSAPublicKey_out] [-engine id]
DESCRIPTION
The rsa command processes RSA keys. They can be converted between various forms and their components printed out. Note this command uses the traditional SSLeay compatible format for private key encryption: newer applications should use the more secure PKCS#8 format using the pkcs8 utility.
COMMAND OPTIONS
-help
Print out a usage message.
-inform DER|NET|PEM
This specifies the input format. The DER option uses an ASN1 DER encoded form compatible with the PKCS#1 RSAPrivateKey or SubjectPublicKeyInfo format. The PEM form is the default format: it consists of the DER format base64 encoded with additional header and footer lines. On input PKCS#8 format private keys are also accepted. The NET form is a format is described in the NOTES section.
-outform DER|NET|PEM
This specifies the output format, the options have the same meaning as the -inform option.
-in filename
This specifies the input filename to read a key from or standard input if this option is not specified. If the key is encrypted a pass phrase will be prompted for.
-passin arg
the input file password source. For more information about the format of arg see the PASS PHRASE ARGUMENTS section in openssl.
-out filename
This specifies the output filename to write a key to or standard output if this option is not specified. If any encryption options are set then a pass phrase will be prompted for. The output filename should not be the same as the input filename.
-passout password
the output file password source. For more information about the format of arg see the PASS PHRASE ARGUMENTS section in openssl.
-aes128|-aes192|-aes256|-camellia128|-camellia192|-camellia256|-des|-des3|-idea
These options encrypt the private key with the specified cipher before outputting it. A pass phrase is prompted for. If none of these options is specified the key is written in plain text. This means that using the rsa utility to read in an encrypted key with no encryption option can be used to remove the pass phrase from a key, or by setting the encryption options it can be use to add or change the pass phrase. These options can only be used with PEM format output files.
-text
prints out the various public or private key components in plain text in addition to the encoded version.
-noout
this option prevents output of the encoded version of the key.
-modulus
this option prints out the value of the modulus of the key.
-check
this option checks the consistency of an RSA private key.
-pubin
by default a private key is read from the input file: with this option a public key is read instead.
-pubout
by default a private key is output: with this option a public key will be output instead. This option is automatically set if the input is a public key.
-RSAPublicKey_in, -RSAPublicKey_out
like -pubin and -pubout except RSAPublicKey format is used instead.
-engine id
specifying an engine (by its unique id string) will cause rsa to attempt to obtain a functional reference to the specified engine, thus initialising it if needed. The engine will then be set as the default for all available algorithms.
NOTES
The PEM private key format uses the header and footer lines:
-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----
The PEM public key format uses the header and footer lines:
-----BEGIN PUBLIC KEY-----
-----END PUBLIC KEY-----
The PEM RSAPublicKey format uses the header and footer lines:
-----BEGIN RSA PUBLIC KEY-----
-----END RSA PUBLIC KEY-----
The NET form is a format compatible with older Netscape servers and Microsoft IIS .key files, this uses unsalted RC4 for its encryption. It is not very secure and so should only be used when necessary.
Some newer version of IIS have additional data in the exported .key files. To use these with the utility, view the file with a binary editor and look for the string "private-key", then trace back to the byte sequence 0x30, 0x82 (this is an ASN1 SEQUENCE). Copy all the data from this point onwards to another file and use that as the input to the rsa utility with the -inform NET option.
EXAMPLES
To remove the pass phrase on an RSA private key:
openssl rsa -in key.pem -out keyout.pem
To encrypt a private key using triple DES:
openssl rsa -in key.pem -des3 -out keyout.pem
To convert a private key from PEM to DER format:
openssl rsa -in key.pem -outform DER -out keyout.der
To print out the components of a private key to standard output:
openssl rsa -in key.pem -text -noout
To just output the public part of a private key:
openssl rsa -in key.pem -pubout -out pubkey.pem
Output the public part of a private key in RSAPublicKey format:
openssl rsa -in key.pem -RSAPublicKey_out -out pubkey.pem
Here's my bash command line to list multiple certificates in order of their expiration, most recently expiring first.
for pem in /etc/ssl/certs/*.pem; do
printf '%s: %s\n' \
"$(date --date="$(openssl x509 -enddate -noout -in "$pem"|cut -d= -f 2)" --iso-8601)" \
"$pem"
done | sort
Sample output:
2015-12-16: /etc/ssl/certs/Staat_der_Nederlanden_Root_CA.pem
2016-03-22: /etc/ssl/certs/CA_Disig.pem
2016-08-14: /etc/ssl/certs/EBG_Elektronik_Sertifika_Hizmet_S.pem
If you are using a git server inside a private network and are using a self-signed certificate or a certificate over an IP address ; you may also simply use the git global config to disable the ssl checks:
git config --global http.sslverify "false"
For me, I just wanted to test a website that had an automatic http->https redirect. I think I had some certs installed already, so this alone works for me on Ubuntu 16.04 running curl 7.47.0 (x86_64-pc-linux-gnu) libcurl/7.47.0 GnuTLS/3.4.10 zlib/1.2.8 libidn/1.32 librtmp/2.3
curl --proto-default https <target>
My typical expectation is than when "subject" is used a context like this, it means the target of the certificate. If you think of a certificate as a cryptographically secured description of a thing (person, device, communication channel, etc), then the subject is the stuff related to that thing.
It's not the thing itself. For example, no one would say "the subject takes his SmartCard and authenticates his PIN". That would be the "user".
But it usually relates to the various data items related to that that thing. For example:
Usually, it's used to distinguish between the other players in the PKI world. Namely the "issuer" and the "root". The issuer is the CA that issued the cert (to the subject), and the root is the CA that is end point of all the trust in the heirarchy. The typical relationship is root--->issuer--->subject.
You do NOT need openssl or makecert or any of that. You also don't need the personal key given to you by your CA. I can almost guarantee that the problem is that you expect to be able to use the key and cer files provided by your CA but they aren't based on "the IIS way". I'm so tired of seeing bad and difficult info out here that I decided to blog the subject and the solution. When you realize what's going on and see how easy it is, you will want to hug me :)
SSL Certs for IIS with PFX once and for all - SSL and IIS Explained - http://rainabba.blogspot.com/2014/03/ssl-certs-for-iis-with-pfx-once-and-for.html
Use IIS "Server Certificates" UI to "Generate Certificate Request" (the details of this request are out of the scope of this article but those details are critical). This will give you a CSR prepped for IIS. You then give that CSR to your CA and ask for a certificate. Then you take the CER/CRT file they give you, go back to IIS, "Complete Certificate Request" in the same place you generated the request. It may ask for a .CER and you might have a .CRT. They are the same thing. Just change the extension or use the . extension drop-down to select your .CRT. Now provide a proper "friendly name" (*.yourdomain.com, yourdomain.com, foo.yourdomain.com, etc..) THIS IS IMPORTANT! This MUST match what you setup the CSR for and what your CA provided you. If you asked for a wildcard, your CA must have approved and generated a wildcard and you must use the same. If your CSR was generated for foo.yourdomain.com, you MUST provide the same at this step.
I had trouble with a .pfx file with openconnect. Renaming didn't solve the problem. I used keytool to convert it to .p12 and it worked.
keytool -importkeystore -destkeystore new.p12 -deststoretype pkcs12 -srckeystore original.pfx
In my case the password for the new file (new.p12) had to be the same as the password for the .pfx file.
Adding to Sani's and blak3r's answers, I've added the following to the startup code for my application, but in VB:
'** Overriding the certificate validation check.
Net.ServicePointManager.ServerCertificateValidationCallback = Function(sender, certificate, chain, sslPolicyErrors) True
Seems to do the trick.
When I tried to select the development provisioning profile in Code Signing Identity is would say "profile doesn't match any valid certificate". So when I followed the two step process below it worked:
1) Under "Code Signing Identity" for Development change to "Don't Code Sign".
2) Then Under "Code Signing Identity" for Development you will be able to select your provisioning profile for Development.
Drove me nuts, but stumbled upon the solution.
When I had the problem recently it was a cross site issue where our dev server hosts our analytics software as well as the application. In the other environments the chrome console would show this error and the javascript file (tracker) on the dev server as the source. This was causing issues for QA personnel who were trying to view the analytics data for their environment (nothing was being captured because of this issue).
The solution to fix this in-house was to add the SSL certificate the DEV site was using to the Trusted People store on the QA people's machine.
If this was a problem in production I would most likely move the javascript into the actual web apps.
+1 to banging my head against the wall for a day or two...
Also check this setting:
Build Settings -> Code Signing -> Provisioning Profile
After following the above steps, "Automatic" setting worked for me. ~kjm~
Once you have established that they don't match, you still have a problem -- what to do about it. Often, the certificate may merely be assembled incorrectly. When a CA signs your certificate, they send you a block that looks something like
-----BEGIN CERTIFICATE-----
MIIAA-and-a-buncha-nonsense-that-is-your-certificate
-and-a-buncha-nonsense-that-is-your-certificate-and-
a-buncha-nonsense-that-is-your-certificate-and-a-bun
cha-nonsense-that-is-your-certificate-and-a-buncha-n
onsense-that-is-your-certificate-AA+
-----END CERTIFICATE-----
they'll also send you a bundle (often two certificates) that represent their authority to grant you a certificate. this will look something like
-----BEGIN CERTIFICATE-----
MIICC-this-is-the-certificate-that-signed-your-request
-this-is-the-certificate-that-signed-your-request-this
-is-the-certificate-that-signed-your-request-this-is-t
he-certificate-that-signed-your-request-this-is-the-ce
rtificate-that-signed-your-request-A
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIICC-this-is-the-certificate-that-signed-for-that-one
-this-is-the-certificate-that-signed-for-that-one-this
-is-the-certificate-that-signed-for-that-one-this-is-t
he-certificate-that-signed-for-that-one-this-is-the-ce
rtificate-that-signed-for-that-one-this-is-the-certifi
cate-that-signed-for-that-one-AA
-----END CERTIFICATE-----
except that unfortunately, they won't be so clearly labeled.
a common practice, then, is to bundle these all up into one file -- your certificate, then the signing certificates. But since they aren't easily distinguished, it sometimes happens that someone accidentally puts them in the other order -- signing certs, then the final cert -- without noticing. In that case, your cert will not match your key.
You can test to see what the cert thinks it represents by running
openssl x509 -noout -text -in yourcert.cert
Near the top, you should see "Subject:" and then stuff that looks like your data. If instead it lookslike your CA, your bundle is probably in the wrong order; you might try making a backup, and then moving the last cert to the beginning, hoping that is the one that is your cert.
If this doesn't work, you might just have to get the cert re-issued. When I make a CSR, I like to clearly label what server it's for (instead of just ssl.key or server.key) and make a copy of it with the date in the name, like mydomain.20150306.key etc. that way they private and public key pairs are unlikely to get mixed up with another set.
You've just published that private key, so now the whole world knows what it is. Hopefully that was just for testing.
EDIT: Others have noted that the openssl text header of the published key, -----BEGIN RSA PRIVATE KEY-----, indicates that it is PKCS#1. However, the actual Base64 contents of the key in question is PKCS#8. Evidently the OP copy and pasted the header and trailer of a PKCS#1 key onto the PKCS#8 key for some unknown reason. The sample code I've provided below works with PKCS#8 private keys.
Here is some code that will create the private key from that data. You'll have to replace the Base64 decoding with your IBM Base64 decoder.
public class RSAToy {
private static final String BEGIN_RSA_PRIVATE_KEY = "-----BEGIN RSA PRIVATE KEY-----\n"
+ "MIIEuwIBADAN ...skipped the rest\n"
// + ...
// + ... skipped the rest
// + ...
+ "-----END RSA PRIVATE KEY-----";
public static void main(String[] args) throws Exception {
// Remove the first and last lines
String privKeyPEM = BEGIN_RSA_PRIVATE_KEY.replace("-----BEGIN RSA PRIVATE KEY-----\n", "");
privKeyPEM = privKeyPEM.replace("-----END RSA PRIVATE KEY-----", "");
System.out.println(privKeyPEM);
// Base64 decode the data
byte [] encoded = Base64.decode(privKeyPEM);
// PKCS8 decode the encoded RSA private key
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey privKey = kf.generatePrivate(keySpec);
// Display the results
System.out.println(privKey);
}
}
To convert the private key from PKCS#1 to PKCS#8 with openssl:
# openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in pkcs1.key -out pkcs8.key
That will work as long as you have the PKCS#1 key in PEM (text format) as described in the question.
Since you installed a new OS you probably don't have any more of your private and public keys that you used to sign your app in to XCode before. You need to regenerate those keys on your machine by revoking your previous certificate and asking for a new one on the iOS development portal. As part of the process you will be asked to generate a Certificate Signing Request which is where you seem to have a problem.
You will find all you need there which consists of (from the official doc):
1.Open Keychain Access on your Mac (located in Applications/Utilities).
2.Open Preferences and click Certificates. Make sure both Online Certificate Status Protocol and Certificate Revocation List are set to Off.
3.Choose Keychain Access > Certificate Assistant > Request a Certificate From a Certificate Authority.
Note: If you have a private key selected when you do this, the CSR won’t be accepted. Make sure no private key is selected. Enter your user email address and common name. Use the same address and name as you used to register in the iOS Developer Program. No CA Email Address is required.
4.Select the options “Saved to disk” and “Let me specify key pair information” and click Continue.
5.Specify a filename and click Save. (make sure to replace .certSigningRequest with .csr)
For the Key Size choose 2048 bits and for Algorithm choose RSA. Click Continue and the Certificate Assistant creates a CSR and saves the file to your specified location.
Check your JAVA_HOME path. As systems looks for a java.policy file which is located in JAVA_HOME/jre/lib/security
. Your JAVA_HOME should always be ../JAVA/JDK
.
FWIW, on Ubuntu 10.04.2 LTS installing the ca-certificates-java and the ca-certificates packages fixed this problem for me.
My mistake was simply using the CSR file instead of the CERT file.
OpenSSH cannot use PKCS#12 files out of the box. As others suggested, you must extract the private key in PEM format which gets you from the land of OpenSSL to OpenSSH. Other solutions mentioned here don’t work for me. I use OS X 10.9 Mavericks (10.9.3 at the moment) with “prepackaged” utilities (OpenSSL 0.9.8y, OpenSSH 6.2p2).
First, extract a private key in PEM format which will be used directly by OpenSSH:
openssl pkcs12 -in filename.p12 -clcerts -nodes -nocerts | openssl rsa > ~/.ssh/id_rsa
I strongly suggest to encrypt the private key with password:
openssl pkcs12 -in filename.p12 -clcerts -nodes -nocerts | openssl rsa -passout 'pass:Passw0rd!' > ~/.ssh/id_rsa
Obviously, writing a plain-text password on command-line is not safe either, so you should delete the last command from history or just make sure it doesn’t get there. Different shells have different ways. You can prefix your command with space to prevent it from being saved to history in Bash and many other shells. Here is also how to delete the command from history in Bash:
history -d $(history | tail -n 2 | awk 'NR == 1 { print $1 }')
Alternatively, you can use different way to pass a private key password to OpenSSL - consult OpenSSL documentation for pass phrase arguments.
Then, create an OpenSSH public key which can be added to authorized_keys file:
ssh-keygen -y -f ~/.ssh/id_rsa > ~/.ssh/id_rsa.pub
public static void main(String[] args) {
try {
String keystorePass = "20174";
String keyPass = "rav@789";
String alias = "TyaGi!";
InputStream keystoreStream = new FileInputStream("D:/keyFile.jks");
KeyStore keystore = KeyStore.getInstance("JCEKS");
keystore.load(keystoreStream, keystorePass.toCharArray());
Key key = keystore.getKey(alias, keyPass.toCharArray());
byte[] bt = key.getEncoded();
String s = new String(bt);
System.out.println("------>"+s);
String str12 = Base64.encodeBase64String(bt);
System.out.println("Fetched Key From JKS : " + str12);
} catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException ex) {
System.out.println(ex);
}
}
For me, I had encountered this error when invoking a webservice call, make sure that the site has a valid ssl, i.e the logo on the side of the url is checked, otherwise need to add the certificate to trusted key store in your machine
The trick for me was discovering that even though I could see the developer cert under login, it was not under My Certificates. The fix was to export the cert from the keychain on the old mac, then import it into My Certificates/login on the new mac.
Check these links: http://www.orcsweb.com/blog/james/powershell-ing-on-windows-server-how-to-import-certificates-using-powershell/
Import-Certificate: http://poshcode.org/1937
You can do something like:
dir -Path C:\Certs -Filter *.cer | Import-Certificate -CertFile $_ -StoreNames AuthRoot, Root -LocalMachine -Verbose
Importing .cer
certificate file downloaded from browser (open the url and dig for details) into cacerts keystore in java_home\jre\lib\security
worked for me, as opposed to attemps to generate and use my own keystore.
java_home\jre\lib\security
cmd
and CTRL+SHIFT+ENTERyourAliasName
and path\to\certificate.cer
respectively) ..\..\bin\keytool -import -trustcacerts -keystore cacerts -storepass changeit -noprompt -alias yourAliasName -file path\to\certificate.cer
This way you don't have to specify any additional JVM options and the certificate should be recognized by the JRE.
File > Project Structure > Build Variants > Select release > Make sure 'Signing Config' is not empty > if it is select from the drop window the $signingConfigs.release
I did this with Android Studio 3.1.4 and it allowed me to create a release apk after following all the steps above of creating the release apk and release key and adding the info to the app gradle. Cheers!
To create a self signed certificate on Windows 7 with IIS 6...
Open IIS
Select your server (top level item or your computer's name)
Under the IIS section, open "Server Certificates"
Click "Create Self-Signed Certificate"
Name it "localhost" (or something like that that is not specific)
Click "OK"
You can then bind that certificate to your website...
Right click on your website and choose "Edit bindings..."
Click "Add"
Click "OK"
Click "Close"
It's worth noting that in addition to purchasing a certificate (as mentioned above), you can also create your own for free; this is referred to as a "self-signed certificate". The difference between a self-signed certificate and one that's purchased is simple: the purchased one has been signed by a Certificate Authority that your browser already knows about. In other words, your browser can easily validate the authenticity of a purchased certificate.
Unfortunately this has led to a common misconception that self-signed certificates are inherently less secure than those sold by commercial CA's like GoDaddy and Verisign, and that you have to live with browser warnings/exceptions if you use them; this is incorrect.
If you securely distribute a self-signed certificate (or CA cert, as bobince suggested) and install it in the browsers that will use your site, it's just as secure as one that's purchased and is not vulnerable to man-in-the-middle attacks and cert forgery. Obviously this means that it's only feasible if only a few people need secure access to your site (e.g., internal apps, personal blogs, etc.).
Put your domain name here: https://www.ssllabs.com/ssltest/analyze.html You should be able to see if there are any issues with your ssl certificate chain. I am guessing that you have SSL chain issues. A short description of the problem is that there's actually a list of certificates on your server (and not only one) and these need to be in the correct order. If they are there but not in the correct order, the website will be fine on desktop browsers (an iOs as well I think), but android is more strict about the order of certificates, and will give an error if the order is incorrect. To fix this you just need to re-order the certificates.
Use following link to sign .exe (setup/ installer)file (sign exe/setup file without using Microsoft setup signtool)
https://ebourg.github.io/jsign/#files
sample command java -jar jsign-2.0.jar --keystore keystore.jks" --alias alias --storepass password MyInstaller.exe
Worked for me :)
work with all https
httpClient = new DefaultHttpClient();
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { }
public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { }
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, ssf));
Just fixed a similar issue.
I realized I had an application pool that was running under an account that only had reading permission over the certificate that it was used.
The .NET application could correctly retrieve the certificate but that exception was thrown only when GetRequestStream() was called.
Certificates permissions can be managed via MMC console
You need to configure a raw HttpClient with SSL support, something like this:
@Test
public void givenAcceptingAllCertificatesUsing4_4_whenUsingRestTemplate_thenCorrect()
throws ClientProtocolException, IOException {
CloseableHttpClient httpClient
= HttpClients.custom()
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.build();
HttpComponentsClientHttpRequestFactory requestFactory
= new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
ResponseEntity<String> response
= new RestTemplate(requestFactory).exchange(
urlOverHttps, HttpMethod.GET, null, String.class);
assertThat(response.getStatusCode().value(), equalTo(200));
}
to print only the certificate chain and not the server's certificate:
# MYHOST=myhost.com
# MYPORT=443
# openssl s_client -connect ${MYHOST}:${MYPORT} -showcerts 2>/dev/null </dev/null | awk '/^.*'"${MYHOST}"'/,/-----END CERTIFICATE-----/{next;}/-----BEGIN/,/-----END CERTIFICATE-----/{print}'
to update CA trust on CentOS/RHEL 6/7 :
# update-ca-trust enable
# openssl s_client -connect ${MYHOST}:${MYPORT} -showcerts 2>/dev/null </dev/null | awk '/^.*'"${MYHOST}"'/,/-----END CERTIFICATE-----/{next;}/-----BEGIN/,/-----END CERTIFICATE-----/{print}' >/etc/pki/ca-trust/source/anchors/myca.cert
# update-ca-trust extract
on CentOS/RHEL 5:
# openssl s_client -connect ${MYHOST}:${MYPORT} -showcerts 2>/dev/null </dev/null | awk '/^.*'"${MYHOST}"'/,/-----END CERTIFICATE-----/{next;}/-----BEGIN/,/-----END CERTIFICATE-----/{print}' >>/etc/pki/tls/certs/ca-bundle.crt
The docker run
command has a --ulimit
flag you can use this flag to set the open file limit in your docker container.
Run the following command when spinning up your container to set the open file limit.
docker run --ulimit nofile=<softlimit>:<hardlimit>
the first value before the colon indicates the soft file limit and the value after the colon indicates the hard file limit. you can verify this by running your container in interactive mode and executing the following command in your containers shell ulimit -n
PS: check out this blog post for more clarity
It's better to use
$('#search-form').setAttribute('action', '/controllerName/actionName');
rather than
$('#search-form').attr('action', '/controllerName/actionName');
So, based on trante's answer we have:
$('#search-form').submit(function() {
var formAction = $("#selectsearch").val() == "people" ? "user" : "content";
$("#search-form").setAttribute("action", "/search/" + formAction);
});
Using setAttribute
can save you a lot of time potentially.
Another convoluted answer which should technically work and is ok for a small number of data points is to plot all your data points as 1 series in order to get your connecting line. Then plot each point as its own series. Then format data labels to display series name for each of the individual data points.
In short it works ok for a small data set or just key points from a data set.
You can use either the xml attribute android:cursorVisible="false"
or programatically:
view.setCursorVisible(false)
view.isCursorVisible = false
Order of magnitude: zero.
In other words, you won't see your throughput cut in half, or anything like it, when you add TLS. Answers to the "duplicate" question focus heavily on application performance, and how that compares to SSL overhead. This question specifically excludes application processing, and seeks to compare non-SSL to SSL only. While it makes sense to take a global view of performance when optimizing, that is not what this question is asking.
The main overhead of SSL is the handshake. That's where the expensive asymmetric cryptography happens. After negotiation, relatively efficient symmetric ciphers are used. That's why it can be very helpful to enable SSL sessions for your HTTPS service, where many connections are made. For a long-lived connection, this "end-effect" isn't as significant, and sessions aren't as useful.
Here's an interesting anecdote. When Google switched Gmail to use HTTPS, no additional resources were required; no network hardware, no new hosts. It only increased CPU load by about 1%.
If you want to do it in a tidyverse
manner, try add_column
from tibble
, which allows you to specifiy where to place the new column with .before
or .after
parameter:
library(tibble)
df <- data.frame(b = c(1, 1, 1), c = c(2, 2, 2), d = c(3, 3, 3))
add_column(df, a = 0, .before = 1)
# a b c d
# 1 0 1 2 3
# 2 0 1 2 3
# 3 0 1 2 3
I had this problem I iOS 12.4 when calling evaluateJavascript. I solved it by wrapping the call in DispatchQueue.main.async { }
Note however:
If you issue SET TRANSACTION ISOLATION LEVEL in a stored procedure or trigger, when the object returns control the isolation level is reset to the level in effect when the object was invoked. For example, if you set REPEATABLE READ in a batch, and the batch then calls a stored procedure that sets the isolation level to SERIALIZABLE, the isolation level setting reverts to REPEATABLE READ when the stored procedure returns control to the batch.
From SQL database get enum like:
SqlDataReader dr = selectCmd.ExecuteReader();
while (dr.Read()) {
EnumType et = (EnumType)Enum.Parse(typeof(EnumType), dr.GetString(0));
....
}
Yes, you can use jQuery's attribute selector for that.
var linksToGoogle = $('a[href="http://google.com"]');
Alternatively, if your interest is rather links starting with a certain URL, use the attribute-starts-with selector:
var allLinksToGoogle = $('a[href^="http://google.com"]');
Another option:
a = [2,4,6,3,8]
a -= [3]
which results in
=> [2, 4, 6, 8]
The following answer is not exactly optimal by any measure, but I needed something that maintains its position within the container whilst it stretches the inner div fully.
https://jsfiddle.net/fah5axm5/
$(function() {
$(window).on('load resize', ppaFullWidth);
function ppaFullWidth() {
var $elements = $('[data-ppa-full-width="true"]');
$.each( $elements, function( key, item ) {
var $el = $(this);
var $container = $el.closest('.container');
var margin = parseInt($container.css('margin-left'), 10);
var padding = parseInt($container.css('padding-left'), 10)
var offset = margin + padding;
$el.css({
position: "relative",
left: -offset,
"box-sizing": "border-box",
width: $(window).width(),
"padding-left": offset + "px",
"padding-right": offset + "px"
});
});
}
});
My pod kept crashing and I was unable to find the cause. Luckily there is a space where kubernetes saves all the events that occurred before my pod crashed.
(#List Events sorted by timestamp)
To see these events run the command:
kubectl get events --sort-by=.metadata.creationTimestamp
make sure to add a --namespace mynamespace
argument to the command if needed
The events shown in the output of the command showed my why my pod kept crashing.
Try This:
int positionOfJPG=url.IndexOf(".jpg");
string newString = url.Substring(18, url.Length - positionOfJPG);
<html>
<head>
<script>
function callme(field) {
alert("field:" + field.value);
}
</script>
</head>
<body>
<form name="f1">
<input type="text" onkeyup="callme(this);" name="text1">
</form>
</body>
</html>
It looks like you can use the onkeyup to get the new value of the HTML input control. Hope it helps.
I think it gives the error because of the underscore symbol.
Note : underscore symbol should not be written directly, you have to write like as \_
.
So fix these kind special symbol errors.
I fixed the issue without changing the python path as that did not seem like the right solution for me. The following solution worked for me, hopefully it works for you as well :))
Activate your virtualenv (using source activate / activate.bat / activate.ps1 if using power shell)
C:\Users\<myUserName>\Videos\myFolder>django-project\Scripts\activate.bat
(django-project) C:\Users\<myUserName>\Videos\myFolder>
Navigate to your project directory and open vscode there.
(django-project) C:\Users\prash\Videos\myFolder\projects>code .
in VS Code, goto File --> Preferences --> Settings (dont worry you dont need to open the json file)
In the setting search bar search for virtual / venv and hit enter. You should find the below in the search bar:
Python: Venv Folders Folders in your home directory to look into for virtual environments (supports pyenv, direnv and virtualenvwrapper by default).
Add item, and then enter the path of the scripts of your virtuanenv which has the activate file in it. For example in my system, it is:
C:\Users\<myUserName>\Videos\myFolder\django-project\Scripts\
Save it and restart VS Code.
To restart, open cmd again, navigate to your project path and open vs code. (Note that your venv should be activated in cmd before you open vs code from cmd)
Command to open vs code from cmd:
code .
Displaying an Image
in WPF is much easier than that. Try this:
<Image Source="{Binding DisplayedImagePath}" HorizontalAlignment="Left"
Margin="0,0,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Bottom"
Grid.Row="8" Width="200" Grid.ColumnSpan="2" />
And the property can just be a string
:
public string DisplayedImage
{
get { return @"C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg"; }
}
Although you really should add your images to a folder named Images
in the root of your project and set their Build Action to Resource in the Properties Window in Visual Studio... you could then access them using this format:
public string DisplayedImage
{
get { return "/AssemblyName;component/Images/ImageName.jpg"; }
}
UPDATE >>>
As a final tip... if you ever have a problem with a control not working as expected, simply type 'WPF', the name of that control and then the word 'class' into a search engine. In this case, you would have typed 'WPF Image Class'. The top result will always be MSDN and if you click on the link, you'll find out all about that control and most pages have code examples as well.
UPDATE 2 >>>
If you followed the examples from the link to MSDN and it's not working, then your problem is not the Image
control. Using the string
property that I suggested, try this:
<StackPanel>
<Image Source="{Binding DisplayedImagePath}" />
<TextBlock Text="{Binding DisplayedImagePath}" />
</StackPanel>
If you can't see the file path in the TextBlock
, then you probably haven't set your DataContext
to the instance of your view model. If you can see the text, then the problem is with your file path.
UPDATE 3 >>>
In .NET 4, the above Image.Source
values would work. However, Microsoft made some horrible changes in .NET 4.5 that broke many different things and so in .NET 4.5, you'd need to use the full pack
path like this:
<Image Source="pack://application:,,,/AssemblyName;component/Images/image_to_use.png">
For further information on pack URIs, please see the Pack URIs in WPF page on Microsoft Docs.
If you don't want to modify ansible.cfg
or the playbook.yml
then you can just set an environment variable:
export ANSIBLE_HOST_KEY_CHECKING=False
Selenium2 includes webdriver, which has python bindings and allows one to use the headless htmlUnit driver, or switch to firefox or chrome for graphical debugging.
do use the links above. If you run into error "This update is not applicable to your computer. " then make sure you are in fact using the right file for your os. for example i tried running windows 2012 server from that link on windows 7 service pack 1 and I got the above error so be sure to use the right zip. If you don't know which os you have then go to start and system and it should pop right up This should be self explanatory but
Add this into your header
<script>
//tooltip
$(function() {
var tooltips = $( "[title]" ).tooltip();
$(document)(function() {
tooltips.tooltip( "open" );
});
});
</script>
Then just add the attribute title="your tooltip"
to any element
You can always fall back to the good old WinAPI calls, although the amount of work involved is non-trivial. There is no requirement that .NET services be installed via a .NET-aware mechanism.
To install:
OpenSCManager
.CreateService
to register the service.ChangeServiceConfig2
to set a description.CloseServiceHandle
.To uninstall:
OpenSCManager
.OpenService
.DeleteService
on the handle returned by OpenService
.CloseServiceHandle
.The main reason I prefer this over using the ServiceInstaller
/ServiceProcessInstaller
is that you can register the service with your own custom command line arguments. For example, you might register it as "MyApp.exe -service"
, then if the user runs your app without any arguments you could offer them a UI to install/remove the service.
Running Reflector on ServiceInstaller
can fill in the details missing from this brief explanation.
P.S. Clearly this won't have "the same effect as calling: InstallUtil MyService.exe" - in particular, you won't be able to uninstall using InstallUtil. But it seems that perhaps this wasn't an actual stringent requirement for you.
Just looking at the message it sounds like one or more of the components that you reference, or one or more of their dependencies is not registered properly.
If you know which component it is you can use regsvr32.exe to register it, just open a command prompt, go to the directory where the component is and type regsvr32 filename.dll
(assuming it's a dll), if it works, try to run the code again otherwise come back here with the error.
If you don't know which component it is, try re-installing/repairing the GIS software (I assume you've installed some GIS software that includes the component you're trying to use).
Both the answers provided above work fine.
A slightly more robust method I needed to use recently:
- (void) dismissKeyboard {
NSArray *windows = [UIApplication sharedApplication].windows;
for(UIWindow *window in windows) [window endEditing:true];
// Or if you're only working with one UIWindow:
[[UIApplication sharedApplication].keyWindow endEditing:true];
}
I found some of the other "global" methods didn't work (for example, UIWebView
& WKWebView
refused to resign).
If you want to pass the cookie to the browser, you have to append to the headers to be sent back. If you're using wsgi:
import requests
...
def application(environ, start_response):
cookie = {'enwiki_session': '17ab96bd8ffbe8ca58a78657a918558'}
response_headers = [('Content-type', 'text/plain')]
response_headers.append(('Set-Cookie',cookie))
...
return [bytes(post_env),response_headers]
I'm successfully able to authenticate with Bugzilla and TWiki hosted on the same domain my python wsgi script is running by passing auth user/password to my python script and pass the cookies to the browser. This allows me to open the Bugzilla and TWiki pages in the same browser and be authenticated. I'm trying to do the same with SuiteCRM but i'm having trouble with SuiteCRM accepting the session cookies obtained from the python script even though it has successfully authenticated.
what version of sonar are you using? There is one option called "sonar.skippedModules=yourmodulename".
This will skip the whole module. So be aware of it.
I think that you need to step back and think about what a map, or associative array, really is. All it is is a way to store a value for a given key, and get that value back quickly and efficiently. You may also want to be able to iterate over the keys to retrieve every key value pair, or delete keys and their associated values.
Now, think about a data structure you use all the time in shell scripting, and even just in the shell without writing a script, that has these properties. Stumped? It's the filesystem.
Really, all you need to have an associative array in shell programming is a temp directory. mktemp -d
is your associative array constructor:
prefix=$(basename -- "$0")
map=$(mktemp -dt ${prefix})
echo >${map}/key somevalue
value=$(cat ${map}/key)
If you don't feel like using echo
and cat
, you can always write some little wrappers; these ones are modelled off of Irfan's, though they just output the value rather than setting arbitrary variables like $value
:
#!/bin/sh
prefix=$(basename -- "$0")
mapdir=$(mktemp -dt ${prefix})
trap 'rm -r ${mapdir}' EXIT
put() {
[ "$#" != 3 ] && exit 1
mapname=$1; key=$2; value=$3
[ -d "${mapdir}/${mapname}" ] || mkdir "${mapdir}/${mapname}"
echo $value >"${mapdir}/${mapname}/${key}"
}
get() {
[ "$#" != 2 ] && exit 1
mapname=$1; key=$2
cat "${mapdir}/${mapname}/${key}"
}
put "newMap" "name" "Irfan Zulfiqar"
put "newMap" "designation" "SSE"
put "newMap" "company" "My Own Company"
value=$(get "newMap" "company")
echo $value
value=$(get "newMap" "name")
echo $value
edit: This approach is actually quite a bit faster than the linear search using sed suggested by the questioner, as well as more robust (it allows keys and values to contain -, =, space, qnd ":SP:"). The fact that it uses the filesystem does not make it slow; these files are actually never guaranteed to be written to the disk unless you call sync
; for temporary files like this with a short lifetime, it's not unlikely that many of them will never be written to disk.
I did a few benchmarks of Irfan's code, Jerry's modification of Irfan's code, and my code, using the following driver program:
#!/bin/sh
mapimpl=$1
numkeys=$2
numvals=$3
. ./${mapimpl}.sh #/ <- fix broken stack overflow syntax highlighting
for (( i = 0 ; $i < $numkeys ; i += 1 ))
do
for (( j = 0 ; $j < $numvals ; j += 1 ))
do
put "newMap" "key$i" "value$j"
get "newMap" "key$i"
done
done
The results:
$ time ./driver.sh irfan 10 5 real 0m0.975s user 0m0.280s sys 0m0.691s $ time ./driver.sh brian 10 5 real 0m0.226s user 0m0.057s sys 0m0.123s $ time ./driver.sh jerry 10 5 real 0m0.706s user 0m0.228s sys 0m0.530s $ time ./driver.sh irfan 100 5 real 0m10.633s user 0m4.366s sys 0m7.127s $ time ./driver.sh brian 100 5 real 0m1.682s user 0m0.546s sys 0m1.082s $ time ./driver.sh jerry 100 5 real 0m9.315s user 0m4.565s sys 0m5.446s $ time ./driver.sh irfan 10 500 real 1m46.197s user 0m44.869s sys 1m12.282s $ time ./driver.sh brian 10 500 real 0m16.003s user 0m5.135s sys 0m10.396s $ time ./driver.sh jerry 10 500 real 1m24.414s user 0m39.696s sys 0m54.834s $ time ./driver.sh irfan 1000 5 real 4m25.145s user 3m17.286s sys 1m21.490s $ time ./driver.sh brian 1000 5 real 0m19.442s user 0m5.287s sys 0m10.751s $ time ./driver.sh jerry 1000 5 real 5m29.136s user 4m48.926s sys 0m59.336s
If you want to create a CORS service from PHP, you can use this code as the first step in your file that handles the requests:
// Allow from any origin
if(isset($_SERVER["HTTP_ORIGIN"]))
{
// You can decide if the origin in $_SERVER['HTTP_ORIGIN'] is something you want to allow, or as we do here, just allow all
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
}
else
{
//No HTTP_ORIGIN set, so we allow any. You can disallow if needed here
header("Access-Control-Allow-Origin: *");
}
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Max-Age: 600"); // cache for 10 minutes
if($_SERVER["REQUEST_METHOD"] == "OPTIONS")
{
if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_METHOD"]))
header("Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT"); //Make sure you remove those you do not want to support
if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_HEADERS"]))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
//Just exit with 200 OK with the above headers for OPTIONS method
exit(0);
}
//From here, handle the request as it is ok
Get Sum Of particular row value using PHP MYSQL
"SELECT SUM(filed_name) from table_name"
For ordinary table markup, here's a short solution that works on all devices/browsers on BrowserStack, except IE 7 and below:
table { border-collapse: collapse; }
td + td,
th + th { border-left: 1px solid; }
tr + tr { border-top: 1px solid; }
For IE 7 support, add this:
tr + tr > td,
tr + tr > th { border-top: 1px solid; }
A test case can be seen here: http://codepen.io/dalgard/pen/wmcdE
SET sql_mode = 'NO_ZERO_DATE';
UPDATE `news` SET `d_stop`='2038-01-01 00:00:00' WHERE `d_stop`='0000-00-00 00:00:00'
You can use localStorage and its "storage" eventListener to transfer sessionStorage data from one tab to another.
This code would need to exist on ALL tabs. It should execute before your other scripts.
// transfers sessionStorage from one tab to another
var sessionStorage_transfer = function(event) {
if(!event) { event = window.event; } // ie suq
if(!event.newValue) return; // do nothing if no value to work with
if (event.key == 'getSessionStorage') {
// another tab asked for the sessionStorage -> send it
localStorage.setItem('sessionStorage', JSON.stringify(sessionStorage));
// the other tab should now have it, so we're done with it.
localStorage.removeItem('sessionStorage'); // <- could do short timeout as well.
} else if (event.key == 'sessionStorage' && !sessionStorage.length) {
// another tab sent data <- get it
var data = JSON.parse(event.newValue);
for (var key in data) {
sessionStorage.setItem(key, data[key]);
}
}
};
// listen for changes to localStorage
if(window.addEventListener) {
window.addEventListener("storage", sessionStorage_transfer, false);
} else {
window.attachEvent("onstorage", sessionStorage_transfer);
};
// Ask other tabs for session storage (this is ONLY to trigger event)
if (!sessionStorage.length) {
localStorage.setItem('getSessionStorage', 'foobar');
localStorage.removeItem('getSessionStorage', 'foobar');
};
I tested this in chrome, ff, safari, ie 11, ie 10, ie9
This method "should work in IE8" but i could not test it as my IE was crashing every time i opened a tab.... any tab... on any website. (good ol IE) PS: you'll obviously need to include a JSON shim if you want IE8 support as well. :)
Credit goes to this full article: http://blog.guya.net/2015/06/12/sharing-sessionstorage-between-tabs-for-secure-multi-tab-authentication/
Merge byte arrays of multiple PDF files:
public static byte[] MergePDFs(List<byte[]> pdfFiles)
{
if (pdfFiles.Count > 1)
{
PdfReader finalPdf;
Document pdfContainer;
PdfWriter pdfCopy;
MemoryStream msFinalPdf = new MemoryStream();
finalPdf = new PdfReader(pdfFiles[0]);
pdfContainer = new Document();
pdfCopy = new PdfSmartCopy(pdfContainer, msFinalPdf);
pdfContainer.Open();
for (int k = 0; k < pdfFiles.Count; k++)
{
finalPdf = new PdfReader(pdfFiles[k]);
for (int i = 1; i < finalPdf.NumberOfPages + 1; i++)
{
((PdfSmartCopy)pdfCopy).AddPage(pdfCopy.GetImportedPage(finalPdf, i));
}
pdfCopy.FreeReader(finalPdf);
}
finalPdf.Close();
pdfCopy.Close();
pdfContainer.Close();
return msFinalPdf.ToArray();
}
else if (pdfFiles.Count == 1)
{
return pdfFiles[0];
}
return null;
}
Install
npm i core-js
Modular standard library for JavaScript. Includes polyfills for ECMAScript up to 2019: promises, symbols, collections, iterators, typed arrays, many other features, ECMAScript proposals, some cross-platform WHATWG / W3C features and proposals like URL. You can load only required features or use it without global namespace pollution.
Function declaration;
import os
def mkdir_p(filename):
try:
folder=os.path.dirname(filename)
if not os.path.exists(folder):
os.makedirs(folder)
return True
except:
return False
usage :
filename = "./download/80c16ee665c8/upload/backup/mysql/2014-12-22/adclient_sql_2014-12-22-13-38.sql.gz"
if (mkdir_p(filename):
print "Created dir :%s" % (os.path.dirname(filename))
The problem is quite simple. You checked if the version was less than 2.4, not less than or equal to. So if the Python version is 2.4, it's not less than 2.4. What you should have had was:
if sys.version_info **<=** (2, 4):
, not
if sys.version_info < (2, 4):
$shopOwner = ShopMeta::firstOrNew(array('shopId' => $theID,'metadataKey' => 2001));
Then make your changes and save. Note the firstOrNew doesn't do the insert if its not found, if you do need that then its firstOrCreate.
The two includes you mention in your comment are essential. 'does not name a type' just means there is no definition for that identifier visible to the compiler. If there are errors in the LCD library you mention, then those need to be addressed - omitting the #include will definitely not fix it!
Two notes from experience which might be helpful:
You need to add all #include's to the main sketch - irrespective of whether they are included via another #include.
If you add files to the library folder, the Arduino IDE must be restarted before those new files will be visible.
You could look at using Lattice. In this example I have defined a grid over which I want to plot z~x,y. It looks something like this. Note that most of the code is just building a 3D shape that I plot using the wireframe function.
The variables "b" and "s" could be x or y.
require(lattice)
# begin generating my 3D shape
b <- seq(from=0, to=20,by=0.5)
s <- seq(from=0, to=20,by=0.5)
payoff <- expand.grid(b=b,s=s)
payoff$payoff <- payoff$b - payoff$s
payoff$payoff[payoff$payoff < -1] <- -1
# end generating my 3D shape
wireframe(payoff ~ s * b, payoff, shade = TRUE, aspect = c(1, 1),
light.source = c(10,10,10), main = "Study 1",
scales = list(z.ticks=5,arrows=FALSE, col="black", font=10, tck=0.5),
screen = list(z = 40, x = -75, y = 0))
While both of the above answers work well if key,value are strings, I had a situation to append a string and integer (jq errors using the above expressions)
Requirement: To construct a url out below json
pradeep@seleniumframework>curl http://192.168.99.103:8500/v1/catalog/service/apache-443 | jq .[0]
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 251 100 251 0 0 155k 0 --:--:-- --:--:-- --:--:-- 245k
{
"Node": "myconsul",
"Address": "192.168.99.103",
"ServiceID": "4ce41e90ede4:compassionate_wozniak:443",
"ServiceName": "apache-443",
"ServiceTags": [],
"ServiceAddress": "",
"ServicePort": 1443,
"ServiceEnableTagOverride": false,
"CreateIndex": 45,
"ModifyIndex": 45
}
Solution:
curl http://192.168.99.103:8500/v1/catalog/service/apache-443 |
jq '.[0] | "http://" + .Address + ":" + "\(.ServicePort)"'
''.join([a, b]) is better solution than +.
Because Code should be written in a way that does not disadvantage other implementations of Python (PyPy, Jython, IronPython, Cython, Psyco, and such)
form a += b or a = a + b is fragile even in CPython and isn't present at all in implementations that don't use refcounting (reference counting is a technique of storing the number of references, pointers, or handles to a resource such as an object, block of memory, disk space or other resource)
https://www.python.org/dev/peps/pep-0008/#programming-recommendations
I had win10 SDK and I only had to do retarget and then I stopped getting this error. The idea was that the project needs to upgrade its target Windows SDK.
If you want a version that raises an error:
"string to search".index("needle")
If you want a version that returns -1:
"string to search".find("needle")
This is more efficient than the 'in' syntax
In the format you've provided, assuming the user is smart enough to give you valid dates, you don't need to convert to a date first, you can compare them as strings.
I fixed this by updating the Request
class that my Controller receives.
I removed the following class level annotation from my Request
class on my server side. After that my client didn't get 415 error.
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
have a look here for the full syntax: http://en.wikipedia.org/wiki/File_URI_scheme
for unix-like systems it will be as @Alex said file:///your/file/here
whereas for Windows systems would be file:///c|/path/to/file
This is the behaviour to adopt when the referenced object is deleted. It is not specific to Django; this is an SQL standard. Although Django has its own implementation on top of SQL. (1)
There are seven possible actions to take when such event occurs:
CASCADE
: When the referenced object is deleted, also delete the objects that have references to it (when you remove a blog post for instance, you might want to delete comments as well). SQL equivalent: CASCADE
.PROTECT
: Forbid the deletion of the referenced object. To delete it you will have to delete all objects that reference it manually. SQL equivalent: RESTRICT
.RESTRICT
: (introduced in Django 3.1) Similar behavior as PROTECT
that matches SQL's RESTRICT
more accurately. (See django documentation example)SET_NULL
: Set the reference to NULL (requires the field to be nullable). For instance, when you delete a User, you might want to keep the comments he posted on blog posts, but say it was posted by an anonymous (or deleted) user. SQL equivalent: SET NULL
.SET_DEFAULT
: Set the default value. SQL equivalent: SET DEFAULT
.SET(...)
: Set a given value. This one is not part of the SQL standard and is entirely handled by Django.DO_NOTHING
: Probably a very bad idea since this would create integrity issues in your database (referencing an object that actually doesn't exist). SQL equivalent: NO ACTION
. (2)Source: Django documentation
See also the documentation of PostgreSQL for instance.
In most cases, CASCADE
is the expected behaviour, but for every ForeignKey, you should always ask yourself what is the expected behaviour in this situation. PROTECT
and SET_NULL
are often useful. Setting CASCADE
where it should not, can potentially delete all of your database in cascade, by simply deleting a single user.
Additional note to clarify cascade direction
It's funny to notice that the direction of the CASCADE
action is not clear to many people. Actually, it's funny to notice that only the CASCADE
action is not clear. I understand the cascade behavior might be confusing, however you must think that it is the same direction as any other action. Thus, if you feel that CASCADE
direction is not clear to you, it actually means that on_delete
behavior is not clear to you.
In your database, a foreign key is basically represented by an integer field which value is the primary key of the foreign object. Let's say you have an entry comment_A, which has a foreign key to an entry article_B. If you delete the entry comment_A, everything is fine. article_B used to live without comment_A and don't bother if it's deleted. However, if you delete article_B, then comment_A panics! It never lived without article_B and needs it, and it's part of its attributes (article=article_B
, but what is article_B???). This is where on_delete
steps in, to determine how to resolve this integrity error, either by saying:
PROTECT
or RESTRICT
in Django/SQL)SET_NULL
)CASCADE
behavior).SET_DEFAULT
, or even SET(...)
).DO_NOTHING
)I hope it makes cascade direction clearer. :)
Footnotes
(1) Django has its own implementation on top of SQL. And, as mentioned by @JoeMjr2 in the comments below, Django will not create the SQL constraints. If you want the constraints to be ensured by your database (for instance, if your database is used by another application, or if you hang in the database console from time to time), you might want to set the related constraints manually yourself. There is an open ticket to add support for database-level on delete constrains in Django.
(2) Actually, there is one case where
DO_NOTHING
can be useful: If you want to skip Django's implementation and implement the constraint yourself at the database-level.
Try to change the rpc_address to point to the node's IP instead of 0.0.0.0 and specify the IP while connecting to the cqlsh, as if the IP is 10.0.2.64 and the rpc_port left to the default value 9160 then the following should work:
cqlsh 10.0.2.64 9160
OR
cqlsh 10.0.2.64
Also make sure that start_rpc is set to true in /etc/cassandra/cassandra.yaml configuration file.
In your example number
is a primitive, so will be stored as a value.
If you want to use a reference then you should use one of the wrapper types (e.g. Integer
)
This approach will not limit element's width when using margins in flexbox
top: 0; left: 0;
transform: translate(calc(50vw - 50%));
Also for centering it vertically
top: 0; left: 0;
transform: translate(calc(50vw - 50%), calc(50vh - 50%));
BufferedReader#read
reads single character[0 to 65535 (0x00-0xffff)] from the stream, so it is not possible to read single integer from stream.
String s= inp.readLine();
int[] m= new int[2];
String[] s1 = inp.readLine().split(" ");
m[0]=Integer.parseInt(s1[0]);
m[1]=Integer.parseInt(s1[1]);
// Checking whether I am taking the inputs correctly
System.out.println(s);
System.out.println(m[0]);
System.out.println(m[1]);
You can check also Scanner vs. BufferedReader.
Hibernate is implementation of "JPA" which is a specification for Java objects in Database.
I would recommend to use w.r.t JPA as you can switch between different ORMS.
When you use JDBC then you need to use SQL Queries, so if you are proficient in SQL then go for JDBC.
Assuming SQL Server:
e.g. if you class special characters as anything NOT alphanumeric:
DECLARE @MyString VARCHAR(100)
SET @MyString = 'adgkjb$'
IF (@MyString LIKE '%[^a-zA-Z0-9]%')
PRINT 'Contains "special" characters'
ELSE
PRINT 'Does not contain "special" characters'
Just add to other characters you don't class as special, inside the square brackets
I had the same problem for a GitHub repository. My account was missing SSH Key. The process is
Then, you can clone the repository with submodules (git clone --recursive YOUR-GIT-REPO-URL
)
or
Run git submodule init
and git submodule update
to fetch submodules in already cloned repository.
If you mean the row number after the last row that is used, you can find it with this:
Dim unusedRow As Long
unusedRow = Cells.SpecialCells(xlCellTypeLastCell).Offset(1, 0).Row
If you mean a row that happens to be blank with data after it... it gets more complicated.
Here's a function I wrote which will give you the actual row number of the first row that is blank for the provided worksheet.
Function firstBlankRow(ws As Worksheet) As Long
'returns the row # of the row after the last used row
'Or the first row with no data in it
Dim rw As Range
For Each rw In ws.UsedRange.Rows
If rw.Address = ws.Range(rw.Address).SpecialCells(xlCellTypeBlanks). _
Address Then
firstBlankRow = rw.Row
Exit For
End If
Next
If firstBlankRow = 0 Then
firstBlankRow = ws.Cells.SpecialCells(xlCellTypeLastCell). _
Offset(1, 0).Row
End If
End Function
Usage example: firstblankRow(thisworkbook.Sheets(1))
or pass any worksheet.
Edit: As ooo pointed out, this will error if there are no blank cells in your used range.
When I run maven test, java.lang.OutOfMemoryError happens. I google it for solutions and have tried to export MAVEN_OPTS=-Xmx1024m, but it did not work.
Setting the Xmx
options using MAVEN_OPTS
does work, it does configure the JVM used to start Maven. That being said, the maven-surefire-plugin forks a new JVM by default, and your MAVEN_OPTS
are thus not passed.
To configure the sizing of the JVM used by the maven-surefire-plugin, you would either have to:
forkMode
to never
(which is be a not so good idea because Maven won't be isolated from the test) ~or~ argLine
parameter (the right way):In the later case, something like this:
<configuration>
<argLine>-Xmx1024m</argLine>
</configuration>
But I have to say that I tend to agree with Stephen here, there is very likely something wrong with one of your test and I'm not sure that giving more memory is the right solution to "solve" (hide?) your problem.
if not exists (select dist_id from tbl_stock where dist_id= @cust_id and item_id=@item_id)
insert into tbl_stock(dist_id,item_id,qty)values(@cust_id, @item_id, @qty);
else
update tbl_stock set qty=(qty + @qty) where dist_id= @cust_id and item_id= @item_id;
If you happen to be using numpy (with import numpy as np
):
In [24]: x
Out[24]: array([1, 2, 3, 4, 5])
In [25]: np.dot(x, 10**np.arange(len(x)-1, -1, -1))
Out[25]: 12345
You can call the super class's constructor like this
class A(object):
def __init__(self, number):
print "parent", number
class B(A):
def __init__(self):
super(B, self).__init__(5)
b = B()
NOTE:
This will work only when the parent class inherits object
I created a docker container for doing exactly that https://github.com/qoomon/docker-host
You can then simply use container name dns to access host system e.g.
curl http://dockerhost:9200
I used to be irked by this problem; and I used to have a macro-cum-wrapper-function solution just like in Talonmies and Jared's answers, but, honestly? It makes using the CUDA Runtime API even more ugly and C-like.
So I've approached this in a different and more fundamental way. For a sample of the result, here's part of the CUDA vectorAdd
sample - with complete error checking of every runtime API call:
// (... prepare host-side buffers here ...)
auto current_device = cuda::device::current::get();
auto d_A = cuda::memory::device::make_unique<float[]>(current_device, numElements);
auto d_B = cuda::memory::device::make_unique<float[]>(current_device, numElements);
auto d_C = cuda::memory::device::make_unique<float[]>(current_device, numElements);
cuda::memory::copy(d_A.get(), h_A.get(), size);
cuda::memory::copy(d_B.get(), h_B.get(), size);
// (... prepare a launch configuration here... )
cuda::launch(vectorAdd, launch_config,
d_A.get(), d_B.get(), d_C.get(), numElements
);
cuda::memory::copy(h_C.get(), d_C.get(), size);
// (... verify results here...)
Again - all potential errors are checked , and an exception if an error occurred (caveat: If the kernel caused some error after launch, it will be caught after the attempt to copy the result, not before; to ensure the kernel was successful you would need to check for error between the launch and the copy with a cuda::outstanding_error::ensure_none()
command).
The code above uses my
Thin Modern-C++ wrappers for the CUDA Runtime API library (Github)
Note that the exceptions carry both a string explanation and the CUDA runtime API status code after the failing call.
A few links to how CUDA errors are automagically checked with these wrappers:
Section 6.16 Frame target names in the HTML 4.01 spec defines the meanings, but it is partly outdated. It refers to “windows”, whereas HTML5 drafts more realistically speak about “browsing contexts”, since modern browsers often use tabs instead of windows in this context.
Briefly, _self
is the default (current browsing context, i.e. current window or tab), so it is useful only to override a <base target=...>
setting. The value _parent
refers to the frameset that is the parent of the current frame, whereas _top
“breaks out of all frames” and opens the linked document in the entire browser window.
They are not different from the point of view of JVM. Immutable objects don't have methods that can change the instance variables. And the instance variables are private; therefore you can't change it after you create it. A famous example would be String. You don't have methods like setString, or setCharAt. And s1 = s1 + "w" will create a new string, with the original one abandoned. That's my understanding.
You can use this library to manipulate the image while uploading. http://www.verot.net/php_class_upload.htm
You need to add a dataType - http://api.jquery.com/jQuery.ajax/
$(document).ready(function() {
$("#lesen").click(function() {
$.ajax({
url : "helloworld.txt",
dataType: "text",
success : function (data) {
$(".text").html(data);
}
});
});
});
Add .*
to s
in your first line.
Try:
DELETE s.* FROM spawnlist s
INNER JOIN npc n ON s.npc_templateid = n.idTemplate
WHERE (n.type = "monster");
Fixed positioning is supposed to define everything in relation to the viewport, so position:fixed
is always going to do that. Try using position:relative
on the child div instead.
(I realize you might need the fixed positioning for other reasons, but if so - you can't really make the width match it's parent with out JS without inherit
)
svn move
— Move a file or directory.
The last-child
selector is used to select the last child element of a parent. It cannot be used to select the last child element with a specific class under a given parent element.
The other part of the compound selector (which is attached before the :last-child
) specifies extra conditions which the last child element must satisfy in-order for it to be selected. In the below snippet, you would see how the selected elements differ depending on the rest of the compound selector.
.parent :last-child{ /* this will select all elements which are last child of .parent */_x000D_
font-weight: bold;_x000D_
}_x000D_
_x000D_
.parent div:last-child{ /* this will select the last child of .parent only if it is a div*/_x000D_
background: crimson;_x000D_
}_x000D_
_x000D_
.parent div.child-2:last-child{ /* this will select the last child of .parent only if it is a div and has the class child-2*/_x000D_
color: beige;_x000D_
}
_x000D_
<div class='parent'>_x000D_
<div class='child'>Child</div>_x000D_
<div class='child'>Child</div>_x000D_
<div class='child'>Child</div>_x000D_
<div>Child w/o class</div>_x000D_
</div>_x000D_
<div class='parent'>_x000D_
<div class='child'>Child</div>_x000D_
<div class='child'>Child</div>_x000D_
<div class='child'>Child</div>_x000D_
<div class='child-2'>Child w/o class</div>_x000D_
</div>_x000D_
<div class='parent'>_x000D_
<div class='child'>Child</div>_x000D_
<div class='child'>Child</div>_x000D_
<div class='child'>Child</div>_x000D_
<p>Child w/o class</p>_x000D_
</div>
_x000D_
To answer your question, the below would style the last child li
element with background color as red.
li:last-child{
background-color: red;
}
But the following selector would not work for your markup because the last-child
does not have the class='complete'
even though it is an li
.
li.complete:last-child{
background-color: green;
}
It would have worked if (and only if) the last li
in your markup also had class='complete'
.
To address your query in the comments:
@Harry I find it rather odd that: .complete:last-of-type does not work, yet .complete:first-of-type does work, regardless of it's position it's parents element. Thanks for your help.
The selector .complete:first-of-type
works in the fiddle because it (that is, the element with class='complete'
) is still the first element of type li
within the parent. Try to add <li>0</li>
as the first element under the ul
and you will find that first-of-type
also flops. This is because the first-of-type
and last-of-type
selectors select the first/last element of each type under the parent.
Refer to the answer posted by BoltClock, in this thread for more details about how the selector works. That is as comprehensive as it gets :)
If you want to keep the row with the lowest id
value:
DELETE FROM NAMES
WHERE id NOT IN (SELECT *
FROM (SELECT MIN(n.id)
FROM NAMES n
GROUP BY n.name) x)
If you want the id
value that is the highest:
DELETE FROM NAMES
WHERE id NOT IN (SELECT *
FROM (SELECT MAX(n.id)
FROM NAMES n
GROUP BY n.name) x)
The subquery in a subquery is necessary for MySQL, or you'll get a 1093 error.
If the text contains \r\n that need to be converted into new lines use the 'Extended' or 'Regular expression' modes and escape the backslash character in 'Find what':
Find what: \\r\\n
Replace with: \r\n
In cpp, you need to pay special attention to string types when using execvp
:
#include <iostream>
#include <string>
#include <cstring>
#include <stdio.h>
#include <unistd.h>
using namespace std;
const size_t MAX_ARGC = 15; // 1 command + # of arguments
char* argv[MAX_ARGC + 1]; // Needs +1 because of the null terminator at the end
// c_str() converts string to const char*, strdup converts const char* to char*
argv[0] = strdup(command.c_str());
// start filling up the arguments after the first command
size_t arg_i = 1;
while (cin && arg_i < MAX_ARGC) {
string arg;
cin >> arg;
if (arg.empty()) {
argv[arg_i] = nullptr;
break;
} else {
argv[arg_i] = strdup(arg.c_str());
}
++arg_i;
}
// Run the command with arguments
if (execvp(command.c_str(), argv) == -1) {
// Print error if command not found
cerr << "command '" << command << "' not found\n";
}
Reference: execlp?execvp?????
An image may say more than a thousand words:
* Figure describing the complexity of a modern multi-processor, multi-core system.
Source:
They are used for different purposes and in fact have different operator precedences. The &&
and ||
operators are intended for Boolean conditions, whereas and
and or
are intended for control flow.
For example, the following is a Boolean condition:
if ($foo == $bar && $baz != $quxx) {
This differs from control flow:
doSomething() or die();
You can also use this approach in case you want to pass some http parameters and send a json request:
(note: I have added in some extra code just incase it helps any other future readers)
public void postJsonWithHttpParams() throws URISyntaxException, UnsupportedEncodingException, IOException {
//add the http parameters you wish to pass
List<NameValuePair> postParameters = new ArrayList<>();
postParameters.add(new BasicNameValuePair("param1", "param1_value"));
postParameters.add(new BasicNameValuePair("param2", "param2_value"));
//Build the server URI together with the parameters you wish to pass
URIBuilder uriBuilder = new URIBuilder("http://google.ug");
uriBuilder.addParameters(postParameters);
HttpPost postRequest = new HttpPost(uriBuilder.build());
postRequest.setHeader("Content-Type", "application/json");
//this is your JSON string you are sending as a request
String yourJsonString = "{\"str1\":\"a value\",\"str2\":\"another value\"} ";
//pass the json string request in the entity
HttpEntity entity = new ByteArrayEntity(yourJsonString.getBytes("UTF-8"));
postRequest.setEntity(entity);
//create a socketfactory in order to use an http connection manager
PlainConnectionSocketFactory plainSocketFactory = PlainConnectionSocketFactory.getSocketFactory();
Registry<ConnectionSocketFactory> connSocketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", plainSocketFactory)
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(connSocketFactoryRegistry);
connManager.setMaxTotal(20);
connManager.setDefaultMaxPerRoute(20);
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(HttpClientPool.connTimeout)
.setConnectTimeout(HttpClientPool.connTimeout)
.setConnectionRequestTimeout(HttpClientPool.readTimeout)
.build();
// Build the http client.
CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(connManager)
.setDefaultRequestConfig(defaultRequestConfig)
.build();
CloseableHttpResponse response = httpclient.execute(postRequest);
//Read the response
String responseString = "";
int statusCode = response.getStatusLine().getStatusCode();
String message = response.getStatusLine().getReasonPhrase();
HttpEntity responseHttpEntity = response.getEntity();
InputStream content = responseHttpEntity.getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = buffer.readLine()) != null) {
responseString += line;
}
//release all resources held by the responseHttpEntity
EntityUtils.consume(responseHttpEntity);
//close the stream
response.close();
// Close the connection manager.
connManager.close();
}
With Git 2.15 (Q4 2017), "git branch
" learned "-c/-C
" to create a new branch by copying an existing one.
See commit c8b2cec (18 Jun 2017) by Ævar Arnfjörð Bjarmason (avar
).
See commit 52d59cc, commit 5463caa (18 Jun 2017) by Sahil Dua (sahildua2305
).
(Merged by Junio C Hamano -- gitster
-- in commit 3b48045, 03 Oct 2017)
branch
: add a--copy
(-c
) option to go with--move
(-m
)Add the ability to
--copy
a branch and its reflog and configuration, this uses the same underlying machinery as the--move
(-m
) option except the reflog and configuration is copied instead of being moved.This is useful for e.g. copying a topic branch to a new version, e.g.
work
towork-2
after submitting thework
topic to the list, while preserving all the tracking info and other configuration that goes with the branch, and unlike--move
keeping the other already-submitted branch around for reference.
Note: when copying a branch, you remain on your current branch.
As Junio C Hamano explains, the initial implementation of this new feature was modifying HEAD, which was not good:
When creating a new branch
B
by copying the branchA
that happens to be the current branch, it also updatesHEAD
to point at the new branch.
It probably was made this way because "git branch -c A B
" piggybacked its implementation on "git branch -m A B
",This does not match the usual expectation.
If I were sitting on a blue chair, and somebody comes and repaints it to red, I would accept ending up sitting on a chair that is now red (I am also OK to stand, instead, as there no longer is my favourite blue chair).But if somebody creates a new red chair, modelling it after the blue chair I am sitting on, I do not expect to be booted off of the blue chair and ending up on sitting on the new red one.
The std::mbstowcs
function is what you are looking for:
char text[] = "something";
wchar_t wtext[20];
mbstowcs(wtext, text, strlen(text)+1);//Plus null
LPWSTR ptr = wtext;
for string
s,
string text = "something";
wchar_t wtext[20];
mbstowcs(wtext, text.c_str(), text.length());//includes null
LPWSTR ptr = wtext;
--> ED: The "L" prefix only works on string literals, not variables. <--
I would use the operator[].
map <char, int> m1;
m1['G'] ++; // If the element 'G' does not exist then it is created and
// initialized to zero. A reference to the internal value
// is returned. so that the ++ operator can be applied.
// If 'G' did not exist it now exist and is 1.
// If 'G' had a value of 'n' it now has a value of 'n+1'
So using this technique it becomes really easy to read all the character from a stream and count them:
map <char, int> m1;
std::ifstream file("Plop");
std::istreambuf_iterator<char> end;
for(std::istreambuf_iterator<char> loop(file); loop != end; ++loop)
{
++m1[*loop]; // prefer prefix increment out of habbit
}
All of drop down lists disappeared in Build Settings after running the Fix Issue in Xcode 5. Spent several days trying to figure out what was wrong with my provisioning profiles and code signing. Found a link Xcode 4 missing drop down lists in Build Settings and sure enough I needed to re-enabled "Show Values" under the Editor menu. Hopefully this helps anyone else in this predicament.
Also, I had to clear my derived data, clean the solution and quit and reopen Xcode into for the code signing identities to correctly appear. My distribution provisioning profiles where showing up as signed by my developer certificate which was incorrect.
With IntelliJ IDEA
you can create a Jar Application
runtime configuration, select the JAR
, the sources, the JRE
to run the Jar
with and start debugging. Here is the documentation.
If you are just opened a new java project then create a new folder src/ in the man project location.
Then cut and paste all your package in that folder.
Then Right click on src directory and select option Mark Directory As > Sources Root.
You can achieve it by code also, In you Global.asax file in Session_Start event write response.redirect to your start page like following.
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
Response.Redirect("~/Index.aspx");
}
You can get redirect page name from database or any other storage to change the application start page while application is running no need to edit web.config or change any IIS settings
I was facing the similar issue. My env details - Python 2.7.11 pip 9.0.1 CentOS release 5.11 (Final)
Error on python interpreter -
>>> import mysql.connector
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named mysql.connector
>>>
Use pip to search the available module -
$ pip search mysql-connector | grep --color mysql-connector-python
mysql-connector-python-rf (2.2.2) - MySQL driver written in Python
mysql-connector-python (2.0.4) - MySQL driver written in Python
Install the mysql-connector-python-rf -
$ pip install mysql-connector-python-rf
Verify
$ python
Python 2.7.11 (default, Apr 26 2016, 13:18:56)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-54)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mysql.connector
>>>
Thanks =)
For python3 and later use the next command: $ pip3 install mysql-connector-python-rf
The next step would be FisherFaces. Try it and check whether they work for you.
Here is a nice comparison.
Some action, very possibly not represented in the visible code, has closed the interactive screen device. It could be done either by a "click" on a close-button. (Could also be done by an extra dev.off() when plotting to a file-graphics device. This may happen if you paste in a mult-line plotting command that has a dev,off() at the end of it but errors out at the opening of the external device but then has hte dev.off() on a separate line so it accidentally closes the interactive device).
Some (most?) R implementations will start up a screen graphics device open automatically, but if you close it down, you then need to re-initialize it. On Windows that might be window()
; on a Mac, quartz()
; and on a linux box, x11()
. You also may need to issue a plot.new()
command. I just follow orders. When I get that error I issue plot.new()
and if I don't see a plot window, I issue quartz()
as well. I then start over from the beginning with a new plot(., ., ...)
command and any further additions to that plot screen image.
you could use this formular to do the job -> get the CellValue for the specific row by typing: = indirect("$A&Cell()) depending on which column you have to check, you have to change the $A
For Example -> You could use a customized VBA Function in the Background:
Public Function IstDatum(Zelle) As Boolean IstDatum = False If IsDate(Zelle) Then IstDatum = True End Function
I need it to check for a date-entry in column A:
=IstDatum(INDIREKT("$A"&ZEILE()))
string
does not name a type. The class in the string
header is called std::string
.
Please do not put using namespace std
in a header file, it pollutes the global namespace for all users of that header. See also "Why is 'using namespace std;' considered a bad practice in C++?"
Your class should look like this:
#include <string>
class Game
{
private:
std::string white;
std::string black;
std::string title;
public:
Game(std::istream&, std::ostream&);
void display(colour, short);
};
From IE7 onwards you can simply use
#footer {
position:fixed;
bottom:0;
}
See caniuse for support.
You may interest in using php's inbuilt function realpath(). and passing a constant DIR
for example: $TargetDirectory = realpath(__DIR__."/../.."); //Will take you 2 folder's back
String realpath() :: Returns canonicalized absolute pathname ..
Using @Pavel's answer as guide, here's a helper method if you don't have the points but have start x,y and height and width. Also can draw inverted/upside down - which is useful for me as it was used as end of vertical barchart.
private void drawTriangle(int x, int y, int width, int height, boolean inverted, Paint paint, Canvas canvas){
Point p1 = new Point(x,y);
int pointX = x + width/2;
int pointY = inverted? y + height : y - height;
Point p2 = new Point(pointX,pointY);
Point p3 = new Point(x+width,y);
Path path = new Path();
path.setFillType(Path.FillType.EVEN_ODD);
path.moveTo(p1.x,p1.y);
path.lineTo(p2.x,p2.y);
path.lineTo(p3.x,p3.y);
path.close();
canvas.drawPath(path, paint);
}
Let me introduce easy GUI/idiot proof approach that you can take in these situations.
myRepo_temp
myRepo_original
).myRepo_temp
and myRepo_original
)This is useful for example if you want partially reverse some changes as you can copy stuff from one to another folder.
You may face similar problem on Ubuntu:
Embedded error: tools.jar not found: /usr/lib/jvm/java-7-openjdk-amd64/jre/../lib/tools.jar
The problem is with JAVA_HOME that is not set properly.
So, on Ubuntu 14.04 x64 using Java8:
sudo apt-get install openjdk-8-jdk openjdk-8-jre
export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
OP's solution to his problem, as he says, has dubious output. That code still shows confusion about representations of time. To clear up this confusion, and make code that won't lead to wrong times, consider this extension of what he did:
public static void _testDateFormatting() {
SimpleDateFormat sdfGMT1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdfGMT1.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat sdfGMT2 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");
sdfGMT2.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat sdfLocal1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
SimpleDateFormat sdfLocal2 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");
try {
Date d = new Date();
String s1 = d.toString();
String s2 = sdfLocal1.format(d);
// Store s3 or s4 in database.
String s3 = sdfGMT1.format(d);
String s4 = sdfGMT2.format(d);
// Retrieve s3 or s4 from database, using LOCAL sdf.
String s5 = sdfLocal1.parse(s3).toString();
//EXCEPTION String s6 = sdfLocal2.parse(s3).toString();
String s7 = sdfLocal1.parse(s4).toString();
String s8 = sdfLocal2.parse(s4).toString();
// Retrieve s3 from database, using GMT sdf.
// Note that this is the SAME sdf that created s3.
Date d2 = sdfGMT1.parse(s3);
String s9 = d2.toString();
String s10 = sdfGMT1.format(d2);
String s11 = sdfLocal2.format(d2);
} catch (Exception e) {
e.printStackTrace();
}
}
examining values in a debugger:
s1 "Mon Sep 07 06:11:53 EDT 2015" (id=831698113128)
s2 "2015.09.07 06:11:53" (id=831698114048)
s3 "2015.09.07 10:11:53" (id=831698114968)
s4 "2015.09.07 10:11:53 GMT+00:00" (id=831698116112)
s5 "Mon Sep 07 10:11:53 EDT 2015" (id=831698116944)
s6 -- omitted, gave parse exception
s7 "Mon Sep 07 10:11:53 EDT 2015" (id=831698118680)
s8 "Mon Sep 07 06:11:53 EDT 2015" (id=831698119584)
s9 "Mon Sep 07 06:11:53 EDT 2015" (id=831698120392)
s10 "2015.09.07 10:11:53" (id=831698121312)
s11 "2015.09.07 06:11:53 EDT" (id=831698122256)
sdf2 and sdfLocal2 include time zone, so we can see what is really going on. s1 & s2 are at 06:11:53 in zone EDT. s3 & s4 are at 10:11:53 in zone GMT -- equivalent to the original EDT time. Imagine we save s3 or s4 in a data base, where we are using GMT for consistency, so we can have times from anywhere in the world, without storing different time zones.
s5 parses the GMT time, but treats it as a local time. So it says "10:11:53" -- the GMT time -- but thinks it is 10:11:53 in local time. Not good.
s7 parses the GMT time, but ignores the GMT in the string, so still treats it as a local time.
s8 works, because now we include GMT in the string, and the local zone parser uses it to convert from one time zone to another.
Now suppose you don't want to store the zone, you want to be able to parse s3, but display it as a local time. The answer is to parse using the same time zone it was stored in -- so use the same sdf as it was created in, sdfGMT1. s9, s10, & s11 are all representations of the original time. They are all "correct". That is, d2 == d1. Then it is only a question of how you want to DISPLAY it. If you want to display what is stored in DB -- GMT time -- then you need to format it using a GMT sdf. Ths is s10.
So here is the final solution, if you don't want to explicitly store with " GMT" in the string, and want to display in GMT format:
public static void _testDateFormatting() {
SimpleDateFormat sdfGMT1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdfGMT1.setTimeZone(TimeZone.getTimeZone("GMT"));
try {
Date d = new Date();
String s3 = sdfGMT1.format(d);
// Store s3 in DB.
// ...
// Retrieve s3 from database, using GMT sdf.
Date d2 = sdfGMT1.parse(s3);
String s10 = sdfGMT1.format(d2);
} catch (Exception e) {
e.printStackTrace();
}
}
You essentially do inherit the constuctors in the sense that you can simply call super if and when appropriate, it's just that it would be error prone for reasons others have mentioned if it happened by default. The compiler can't presume when it is appropriate and when it isn't.
The job of the compiler is to provide as much flexibility as possible while reducing complexity and risk of unintended side-effects.
I just tried a bare-bones implementation and it just works:
public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame("Hello");
frame.setPreferredSize(new Dimension(200, 200));
frame.add(new Board());
frame.pack();
frame.setVisible(true);
}
}
public class Board extends JPanel {
private Player player = new Player();
public Board(){
setBackground(Color.BLACK);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.red);
g.fillOval(player.getCenter().x, player.getCenter().y,
player.getRadius(), player.getRadius());
}
}
public class Player {
private Point center = new Point(50, 50);
public Point getCenter() {
return center;
}
private int radius = 10;
public int getRadius() {
return radius;
}
}
The amount of hacks you would need to go through to completely hide the fact your site is built by Meteor.js is absolutely ridiculous. You would have to strip essentially all core functionality and just serve straight up html, completely defeating the purpose of using the framework anyway.
That being said, I suggest looking at buildwith.com
You enter a url, and it reveals a ton of information about a site. If you only need to "fool" engines like this, there may be simple solutions.
If you have longer query and you like to use psql then put your query to a file and use the following command:
psql -d my_db_name -t -A -F";" -f input-file.sql -o output-file.csv
In Bootstrap 4 it was renamed to .rounded-circle
Usage :
<div class="col-xs-7">
<img src="img/gallery2.JPG" class="rounded-circle" alt="HelPic>
</div>
See migration docs from bootstrap.
select GROUP_CONCAT(stat SEPARATOR ' ') from (select concat('KILL ',id,';') as stat from information_schema.processlist) as stats;
Then copy and paste the result back into the terminal. Something like:
KILL 2871; KILL 2879; KILL 2874; KILL 2872; KILL 2866;
Rails 4:
def change
change_column_null(:users, :admin, false )
end
Suppose you have defined your route name like this:
https://localhost:3000/user/:userid
which will become:
https://localhost:3000/user/5896544
Here, if you will print: request.params
{
userId : 5896544
}
so
request.params.userId = 5896544
so request.params is an object containing properties to the named route
and request.query comes from query parameters in the URL eg:
https://localhost:3000/user?userId=5896544
request.query
{
userId: 5896544
}
so
request.query.userId = 5896544
I'm running BS3 on a dev site and the following produces the effect/layout you're requesting. Of course you'll need the glyphicons set up in BS3.
<div class="navbar navbar-inverse navbar-static-top" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" rel="home" href="/" title="Aahan Krish's Blog - Homepage">ITSMEEE</a>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav">
<li><a href="/topic/notes/">/notes</a></li>
<li><a href="/topic/dev/">/dev</a></li>
<li><a href="/topic/good-reads/">/good-reads</a></li>
<li><a href="/topic/art/">/art</a></li>
<li><a href="/topic/bookmarks/">/bookmarks</a></li>
<li><a href="/all-topics/">/all</a></li>
</ul>
<div class="col-sm-3 col-md-3 pull-right">
<form class="navbar-form" role="search">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search" name="srch-term" id="srch-term">
<div class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</form>
</div>
</div>
</div>
UPDATE: See JSFiddle
Here is a shorthand that webpack will use so you don't have to use require.context
.
HTML:
<div class="col-lg-2" v-for="pic in pics">
<img :src="getImgUrl(pic)" v-bind:alt="pic">
</div>
Vue Method:
getImgUrl(pic) {
return require('../assets/'+pic)
}
And I find that the first 2 paragraphs in here explain why this works? well.
Please note that it's a good idea to put your pet pictures inside a subdirectory, instead of lobbing it in with all your other image assets. Like so: ./assets/pets/
As an alternative to $dollarsign
notation, use a within
block:
breast <- within(breast, {
class <- as.numeric(as.character(class))
})
Note that you want to convert your vector to a character before converting it to a numeric. Simply calling as.numeric(class)
will not the ids corresponding to each factor level (1, 2) rather than the levels themselves.
You can use ax.figure.savefig()
:
import pandas as pd
s = pd.Series([0, 1])
ax = s.plot.hist()
ax.figure.savefig('demo-file.pdf')
This has no practical benefit over ax.get_figure().savefig()
as suggested in Philip Cloud's answer, so you can pick the option you find the most aesthetically pleasing. In fact, get_figure()
simply returns self.figure
:
# Source from snippet linked above
def get_figure(self):
"""Return the `.Figure` instance the artist belongs to."""
return self.figure
curl -d @request.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere
its python implementation be like
import requests
headers = {
'Content-Type': 'application/json',
}
params = (
('key', 'mykeyhere'),
)
data = open('request.json')
response = requests.post('https://www.googleapis.com/qpxExpress/v1/trips/search', headers=headers, params=params, data=data)
#NB. Original query string below. It seems impossible to parse and
#reproduce query strings 100% accurately so the one below is given
#in case the reproduced version is not "correct".
# response = requests.post('https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere', headers=headers, data=data)
check this link, it will help convert cURl command to python,php and nodejs
for example if the startTime it's 23:00 and endTime 1:00 to get a duration of 2:00.
Not possible. If you have only time-of-day, the clock stops at midnight. Without the context of dates, how do we know if you mean 1 AM on the next day, next week, or next decade?
So going from 11 PM to 1 AM means moving backwards in time 22 hours, running the hands of the clock counterclockwise. See the result below, a negative twenty-two hours.
Duration.between( // Represent a span of time a total number of seconds plus a fractional second in nanoseconds.
LocalTime.of( 23 , 0 ) , // A time-of-day without a date and without a time zone.
LocalTime.of( 1 , 0 ) // A time-of-day clock stops at midnight. So getting to 1 AM from 11 PM means going backwards 22 hours.
) // Return a `Duration` object.
.toString() // Generate a `String` representing this span of time using standard ISO 8601 format: PnYnMnDTnHnMnS
PT-22H
Crossing midnight requires the larger context of date in addition to time-of-day (see below).
How do I measure time elapsed in Java?
Instant.now()
.Duration.between
.Duration
object, extract a number of 24-hour days, hours, minutes, seconds, and fractional second in nanoseconds by calling the various to…Part
methods.toString
to generate a String
in standard ISO 8601 format of PnYnMnDTnHnMnS
.Example code, using pair of Instant
objects.
Duration.between( // Represent a span of time a total number of seconds plus a fractional second in nanoseconds.
then , // Some other `Instant` object, captured earlier with `Instant.now()`.
Instant.now() // Capture the current moment in UTC with a resolution as fine as nanoseconds, depending on the limits of your host computer hardware clock and operating system. Generally you will get current moment in microseconds (six decimal digits of fractional second) in Java 9, 10, and 11, but only milliseconds in Java 8.
) // Return a `Duration` object.
.toString() // Generate a `String` representing this span of time using standard ISO 8601 format: PnYnMnDTnHnMnS
PT3M27.602197S
We have new technology for this now built into Java 8 and later, the java.time framework.
The java.time framework is defined by JSR 310, inspired by the highly successful Joda-Time project, extended by the ThreeTen-Extra project, and described in the Oracle Tutorial.
The old date-time classes such as java.util.Date/.Calendar bundled with the earliest versions of Java have proven to be poorly designed, confusing, and troublesome. They are supplanted by the java.time classes.
Other answers discuss resolution.
The java.time classes have nanosecond resolution, up to nine digits of a decimal fraction of a second. For example, 2016-03-12T04:29:39.123456789Z
.
Both the old java.util.Date/.Calendar classes and the Joda-Time classes have millisecond resolution (3 digits of fraction). For example, 2016-03-12T04:29:39.123Z
.
In Java 8, the current moment is fetched with up to only millisecond resolution because of a legacy issue. In Java 9 and later, the current time can be determined up to nanosecond resolution provided your computer’s hardware clock runs so finely.
If you truly want to work with only the time-of-day lacking any date or time zone, use the LocalTime
class.
LocalTime sooner = LocalTime.of ( 17, 00 );
LocalTime later = LocalTime.of ( 19, 00 );
A Duration
represents a span of time it terms of a count of seconds plus nanoseconds.
Duration duration = Duration.between ( sooner, later );
Dump to console.
System.out.println ( "sooner: " + sooner + " | later: " + later + " | duration: " + duration );
sooner: 17:00 | later: 19:00 | duration: PT2H
Notice the default output of Duration::toString
is in standard ISO 8601 format. In this format, the P
marks the beginning (as in 'Period'), and the T
separates any years-months-days portion from the hours-minutes-seconds portion.
Unfortunately, working with time-of-day only gets tricky when you wrap around the clock crossing midnight. The LocalTime
class handles this by assuming you want to go backwards to an earlier point in the day.
Using the same code as above but going from 23:00
to 01:00
results in a negative twenty-two hours (PT-22H
).
LocalTime sooner = LocalTime.of ( 23, 0 );
LocalTime later = LocalTime.of ( 1, 0 );
sooner: 23:00 | later: 01:00 | duration: PT-22H
If you intend to cross midnight, it probably makes sense for you to be working with date-time values rather than time-of-day-only values.
Time zone is crucial to dates. So we specify three items: (1) the desired date, (2) desired time-of-day, and (3) the time zone as a context by which to interpret that date and time. Here we arbitrarily choose the time zone of the Montréal area.
If you define the date by only an offset-from-UTC, use a ZoneOffset
with a OffsetDateTime
. If you have a full time zone (offset plus rules for handling anomalies such as Daylight Saving Time), use a ZoneId
with a ZonedDateTime
.
LocalDate localDate = LocalDate.of ( 2016, 1, 23 );
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime sooner = ZonedDateTime.of ( localDate, LocalTime.of ( 23, 0 ), zoneId );
We specify the later time as next day at 1:00 AM.
ZonedDateTime later = ZonedDateTime.of ( localDate.plusDays ( 1 ), LocalTime.of ( 1, 0 ), zoneId );
We calculate the Duration
in the same manner as seen above. Now we get the two hours expected by this Question.
Duration duration = Duration.between ( sooner, later );
Dump to console.
System.out.println ( "sooner: " + sooner + " | later: " + later + " | duration: " + duration );
sooner: 2016-01-23T23:00-05:00[America/Montreal] | later: 2016-01-24T01:00-05:00[America/Montreal] | duration: PT2H
If the date-times at hand had involved Daylight Saving Time (DST) or other such anomaly, the java.time classes would adjust as needed. Read class doc for details.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
You're missing service name:
SQL> connect username/password@hostname:port/SERVICENAME
EDIT
If you can connect to the database from other computer try running there:
select sys_context('USERENV','SERVICE_NAME') from dual
and
select sys_context('USERENV','SID') from dual
Each jar version has a unique checksum. You can calculate the checksum for you jar (that had no version info) and compare it with the different versions of the jar. We can also search a jar using checksum.
Refer this Question to calculate checksum: What is the best way to calculate a checksum for a file that is on my machine?
In Access 2010, go to the Create tab on the ribbon. Click Macro. An "Action Catalog" panel should appear on the right side of the screen. Underneath, there's a section titled "In This Database." Clicking on one of the macro names should display its code.
I think one of the biggest confusions is the difference between what you can do with mongo
(or an interactive/hybrid shell) vs. mongo --eval
(or a pure JavaScript shell). I keep these helpful documents handy:
Here is an example of scripting what you might otherwise do with show
commands:
# List all databases and the collections in them
mongo --eval "
db.getMongo().getDBNames().forEach(
function(v, i){
print(
v + '\n\t' +
db.getSiblingDB(v).getCollectionNames().join('\n\t')
)
}
)
"
Note: That works really well as a one-liner. (But it looks terrible on Stack Overflow.)
mongo --eval "db.getMongo().getDBNames().forEach(function(v, i){print(v+'\n\t'+db.getSiblingDB(v).getCollectionNames().join('\n\t'))})"
So, the trick here is to use absolute positioning calc
like this:
top: calc(50% - XYpx);
left: calc(50% - XYpx);
where XYpx is half the size of your image, in my case, the image was a square. Of course, in this now obsolete case, the image must also change its size proportionally in response to window resize to be able to remain at the center without looking out of proportion.
That's the error you get when the DLL itself requires another COM server to be registered first or has a dependency on another DLL that's not available. The Regsvr32.exe tool does very little, it calls LoadLibrary() to load the DLL that's passed in the command line argument. Then GetProcAddress() to find the DllRegisterServer() entry point in the DLL. And calls it to leave it up to the COM server to register itself.
What that code does is fairly unguessable. The diagnostic you got is however pretty self-evident from the error code, for some reason this COM server needs another one to be registered first. The error message is crappy, it doesn't tell you what other server it needs. A sad side-effect of the way COM error handling works.
To troubleshoot this, use SysInternals' ProcMon tool. It shows you what registry keys Regsvr32.exe (actually: the COM server) is opening to find the server. Look for accesses to the CLSID key. That gives you a hint what {guid} it is looking for. That still doesn't quite tell you the server DLL, you should compare the trace with one you get from a machine that works. The InprocServer32 key has the DLL path.
You need to publish the exposed ports by using the following options:
-P (upper case) or --publish-all that will tell Docker to use random ports from your host and map them to the exposed container's ports.
-p (lower case) or --publish=[] that will tell Docker to use ports you manually set and map them to the exposed container's ports.
The second option is preferred because you already know which ports are mapped. If you use the first option then you will need to call docker inspect demo
and check which random ports are being used from your host at the Ports section.
Just run the following command:
docker run -it -p 8080:8080 demo
After that your url will work.
You can also solve this problem without changing code in server, changing header in $http.post
call and use $_POST
the regular way. Explained here: http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/
I don't think this solves the problem to the first questioner, but for googlers coming here for answers:
On update 51, java 1.8 prohibited[1] RC4 ciphers by default, as we can see on the Release Notes page:
Bug Fix: Prohibit RC4 cipher suites
RC4 is now considered as a compromised cipher.
RC4 cipher suites have been removed from both client and server default enabled cipher suite list in Oracle JSSE implementation. These cipher suites can still be enabled by
SSLEngine.setEnabledCipherSuites()
andSSLSocket.setEnabledCipherSuites()
methods. See JDK-8077109 (not public).
If your server has a strong preference for this cipher (or use only this cipher) this can trigger a handshake_failure
on java.
You can test connecting to the server enabling RC4 ciphers (first, try without enabled
argument to see if triggers a handshake_failure
, then set enabled
:
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.io.*;
import java.util.Arrays;
/** Establish a SSL connection to a host and port, writes a byte and
* prints the response. See
* http://confluence.atlassian.com/display/JIRA/Connecting+to+SSL+services
*/
public class SSLRC4Poke {
public static void main(String[] args) {
String[] cyphers;
if (args.length < 2) {
System.out.println("Usage: "+SSLRC4Poke.class.getName()+" <host> <port> enable");
System.exit(1);
}
try {
SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket(args[0], Integer.parseInt(args[1]));
cyphers = sslsocketfactory.getSupportedCipherSuites();
if (args.length ==3){
sslsocket.setEnabledCipherSuites(new String[]{
"SSL_DH_anon_EXPORT_WITH_RC4_40_MD5",
"SSL_DH_anon_WITH_RC4_128_MD5",
"SSL_RSA_EXPORT_WITH_RC4_40_MD5",
"SSL_RSA_WITH_RC4_128_MD5",
"SSL_RSA_WITH_RC4_128_SHA",
"TLS_ECDHE_ECDSA_WITH_RC4_128_SHA",
"TLS_ECDHE_RSA_WITH_RC4_128_SHA",
"TLS_ECDH_ECDSA_WITH_RC4_128_SHA",
"TLS_ECDH_RSA_WITH_RC4_128_SHA",
"TLS_ECDH_anon_WITH_RC4_128_SHA",
"TLS_KRB5_EXPORT_WITH_RC4_40_MD5",
"TLS_KRB5_EXPORT_WITH_RC4_40_SHA",
"TLS_KRB5_WITH_RC4_128_MD5",
"TLS_KRB5_WITH_RC4_128_SHA"
});
}
InputStream in = sslsocket.getInputStream();
OutputStream out = sslsocket.getOutputStream();
// Write a test byte to get a reaction :)
out.write(1);
while (in.available() > 0) {
System.out.print(in.read());
}
System.out.println("Successfully connected");
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
1 - https://www.java.com/en/download/faq/release_changes.xml
If you are using Java 1.5 or later then this is an iterative binary GCD algorithm which uses Integer.numberOfTrailingZeros()
to reduce the number of checks and iterations required.
public class Utils {
public static final int gcd( int a, int b ){
// Deal with the degenerate case where values are Integer.MIN_VALUE
// since -Integer.MIN_VALUE = Integer.MAX_VALUE+1
if ( a == Integer.MIN_VALUE )
{
if ( b == Integer.MIN_VALUE )
throw new IllegalArgumentException( "gcd() is greater than Integer.MAX_VALUE" );
return 1 << Integer.numberOfTrailingZeros( Math.abs(b) );
}
if ( b == Integer.MIN_VALUE )
return 1 << Integer.numberOfTrailingZeros( Math.abs(a) );
a = Math.abs(a);
b = Math.abs(b);
if ( a == 0 ) return b;
if ( b == 0 ) return a;
int factorsOfTwoInA = Integer.numberOfTrailingZeros(a),
factorsOfTwoInB = Integer.numberOfTrailingZeros(b),
commonFactorsOfTwo = Math.min(factorsOfTwoInA,factorsOfTwoInB);
a >>= factorsOfTwoInA;
b >>= factorsOfTwoInB;
while(a != b){
if ( a > b ) {
a = (a - b);
a >>= Integer.numberOfTrailingZeros( a );
} else {
b = (b - a);
b >>= Integer.numberOfTrailingZeros( b );
}
}
return a << commonFactorsOfTwo;
}
}
Unit test:
import java.math.BigInteger;
import org.junit.Test;
import static org.junit.Assert.*;
public class UtilsTest {
@Test
public void gcdUpToOneThousand(){
for ( int x = -1000; x <= 1000; ++x )
for ( int y = -1000; y <= 1000; ++y )
{
int gcd = Utils.gcd(x, y);
int expected = BigInteger.valueOf(x).gcd(BigInteger.valueOf(y)).intValue();
assertEquals( expected, gcd );
}
}
@Test
public void gcdMinValue(){
for ( int x = 0; x < Integer.SIZE-1; x++ ){
int gcd = Utils.gcd(Integer.MIN_VALUE,1<<x);
int expected = BigInteger.valueOf(Integer.MIN_VALUE).gcd(BigInteger.valueOf(1<<x)).intValue();
assertEquals( expected, gcd );
}
}
}
You must modify the query like this
CREATE TABLE #TMPGUARDIAN(
LAST_NAME NVARCHAR(30),
FRST_NAME NVARCHAR(30))
INSERT INTO #TMPGUARDIAN(FRST_NAME,LAST_NAME)
SELECT LAST_NAME,FRST_NAME FROM TBL_PEOPLE
-- Make a last session for clearing the all temporary tables. always drop at end. In your case, sometimes, there might be an error happen if the table is not exists, while you trying to delete.
DROP TABLE #TMPGUARDIAN
Avoid using insert into Because If you are using insert into then in future if you want to modify the temp table by adding a new column which can be filled after some process (not along with insert). At that time, you need to rework and design it in the same manner.
Use Table Variable http://odetocode.com/articles/365.aspx
declare @userData TABLE(
LAST_NAME NVARCHAR(30),
FRST_NAME NVARCHAR(30)
)
Advantages No need for Drop statements, since this will be similar to variables. Scope ends immediately after the execution.
Try this to move your table (tbl1) to tablespace (tblspc2).
alter table tb11 move tablespace tblspc2;
As you are looking for form object changes, the best watching approach is to use
$watchCollection
. Please have a look into official documentation for different performance characteristics.
You may try this. It solved my issue.
import matplotlib.image as mpimg
img = mpimg.imread("src.png")
mpimg.imsave("out.png", img, cmap=cmap)
Your regex seems a bit too complex in my opinion. Also, remember that the dot is a special character meaning "any character". The following regex should work (note the escaped dots):
^.*\.(jpg|JPG|gif|GIF|doc|DOC|pdf|PDF)$
You can use a tool like Expresso to test your regular expressions.
You cannot use a variable to access a property via dot notation, instead use the array notation.
var obj= {
'name' : 'jroi'
};
var a = 'name';
alert(obj.a); //will not work
alert(obj[a]); //should work and alert jroi'
That's not even valid syntax. And you're trying to compare to a string. For arrays you would have to walk the array yourself:
public class T {
public static void main( String args[] ) {
char[] list = {'m', 'e', 'y'};
int index = -1;
for (int i = 0; (i < list.length) && (index == -1); i++) {
if (list[i] == 'e') {
index = i;
}
}
System.out.println(index);
}
}
If you are using a collection, such as ArrayList<Character>
you can also use the indexOf()
method:
ArrayList<Character> list = new ArrayList<Character>();
list.add('m');
list.add('e');
list.add('y');
System.out.println(list.indexOf('e'));
There is also the Arrays
class which shortens above code:
List list = Arrays.asList(new Character[] { 'm', 'e', 'y' });
System.out.println(list.indexOf('e'));
You need not specify the classes folder. Intellij should be able to load it. You will get this error if "Project Compiler output" is blank.
Just make sure that below value is set: Project Settings -> Project -> Project Compiler output to your projectDir/out folder
Jenkins has a link to their REST API in the bottom right of each page. This link appears on every page of Jenkins and points you to an API output for the exact page you are browsing. That should provide some understanding into how to build the API URls.
You can additionally use some wrapper, like I do, in Python, using http://jenkinsapi.readthedocs.io/en/latest/
Here is their website: https://wiki.jenkins-ci.org/display/JENKINS/Remote+access+API
Just replace the form.submit function with your own implementation:
var form = document.getElementById('form');
var formSubmit = form.submit; //save reference to original submit function
form.onsubmit = function(e)
{
formHandler();
return false;
};
var formHandler = form.submit = function()
{
alert('hi there');
formSubmit(); //optionally submit the form
};
This is known as the Diamond Problem, the page has an entry on Python, but in short, Python will call the superclass's methods from left to right.
Both the regex and included files are good methods, and I frequently use those. But another alternative is to use a "named location", which is a useful approach in many situations — especially more complicated ones. The official "If is Evil" page shows essentially the following as a good way to do things:
error_page 418 = @common_location;
location /first/location/ {
return 418;
}
location /second/location/ {
return 418;
}
location @common_location {
# The common configuration...
}
There are advantages and disadvantages to these various approaches. One big advantage to a regex is that you can capture parts of the match and use them to modify the response. Of course, you can usually achieve similar results with the other approaches by either setting a variable in the original block or using map
. The downside of the regex approach is that it can get unwieldy if you want to match a variety of locations, plus the low precedence of a regex might just not fit with how you want to match locations — not to mention that there are apparently performance impacts from regexes in some cases.
The main advantage of including files (as far as I can tell) is that it is a little more flexible about exactly what you can include — it doesn't have to be a full location block, for example. But it's also just subjectively a bit clunkier than named locations.
Also note that there is a related solution that you may be able to use in similar situations: nested locations. The idea is that you would start with a very general location, apply some configuration common to several of the possible matches, and then have separate nested locations for the different types of paths that you want to match. For example, it might be useful to do something like this:
location /specialpages/ {
# some config
location /specialpages/static/ {
try_files $uri $uri/ =404;
}
location /specialpages/dynamic/ {
proxy_pass http://127.0.0.1;
}
}
There are several other ways, besides using the in
operator (easiest):
index()
>>> try:
... "xxxxABCDyyyy".index("test")
... except ValueError:
... print "not found"
... else:
... print "found"
...
not found
find()
>>> if "xxxxABCDyyyy".find("ABCD") != -1:
... print "found"
...
found
re
>>> import re
>>> if re.search("ABCD" , "xxxxABCDyyyy"):
... print "found"
...
found
You can also close the application:
Application.Exit();
It will end the processes.
It works using ajax. The jsp then display in iframe returned by controller in response to request.
function openPage() {
jQuery.ajax({
type : 'POST',
data : jQuery(this).serialize(),
url : '<%=request.getContextPath()%>/post_action',
success : function(data, textStatus) {
jQuery('#iframeId').contents().find('body').append(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
}
});
}
Add sudo to your command line, like:
$ sudo firebase init
This functions should help you...
bool isThereSpace(String s){
return s.Contains(" ");
}
You can concat the data in this way:
InfoDF = pd.DataFrame()
tempDF = pd.DataFrame(rows,columns=['id','min_date'])
InfoDF = pd.concat([InfoDF,tempDF])
Use NetworkMonitor to monitoring network state and internet connection.
Sample:
namespace AmRoNetworkMonitor.Demo
{
using System;
internal class Program
{
private static void Main()
{
NetworkMonitor.StateChanged += NetworkMonitor_StateChanged;
NetworkMonitor.StartMonitor();
Console.WriteLine("Press any key to stop monitoring.");
Console.ReadKey();
NetworkMonitor.StopMonitor();
Console.WriteLine("Press any key to close program.");
Console.ReadKey();
}
private static void NetworkMonitor_StateChanged(object sender, StateChangeEventArgs e)
{
Console.WriteLine(e.IsAvailable ? "Is Available" : "Is Not Available");
}
}
}
Exec the query in TOAD or SQL DEVELOPER
---select /*csv*/ username, user_id, created from all_users;
Save in .SQL format in "C" drive
--- x.sql
execute command
---- set serveroutput on
spool y.csv
@c:\x.sql
spool off;
Use Func<T>
rather than Action<T>
.
Action<T>
acts like a void method with parameter of type T, while Func<T>
works like a function with no parameters and which returns an object of type T.
If you wish to give parameters to your function, use Func<TParameter1, TParameter2, ..., TReturn>
.
make new style
.container {
position: relative;
}
.center-nav {
position: absolute;
left: 0;
right: 0;
margin: 0 auto;
width: auto;
max-width: 200px;
text-align: center;
}
.center-nav li{
text-align: center;
width:100%;
}
Replace website name UL with below
<ul class="nav navbar-nav center-nav">
<li class="nav-item"><a class="nav-link" href="#">Website Name</a></li>
</ul>
Hope this helps..
IntVar = int("".join(filter(str.isdigit, StringVar)))
You are not changing the object in the assignment statement, you replace one immutable object with another one. Object String("a")
does not change to String("ty")
, it gets discarded, and a reference to ty
gets written into a
in its stead.
In contrast, StringBuffer
represents a mutable object. You can do this:
StringBuffer b = new StringBuffer("Hello");
System.out.writeln(b);
b.append(", world!");
System.out.writeln(b);
Here, you did not re-assign b
: it still points to the same object, but the content of that object has changed.
i think that is what you want.
SELECT
A.SalesOrderID,
A.OrderDate,
FooFromB.*
FROM A,
(SELECT TOP 1 B.Foo
FROM B
WHERE A.SalesOrderID = B.SalesOrderID
) AS FooFromB
WHERE A.Date BETWEEN '2000-1-4' AND '2010-1-4'
My suggestion would be
$value = $_POST["myfield"];
$Query = Database::Prepare("SELECT * FROM TABLE WHERE MYFIELD LIKE ?");
$Query->Execute(array("%".$value."%"));
One of the values you pass on to Ancestors
becomes None
at some point, it says, so check if otu
, tree
, tree[otu]
or tree[otu][0]
are None
in the beginning of the function instead of only checking tree[otu][0][0] == None
. But perhaps you should reconsider your path of action and the datatype in question to see if you could improve the structure somewhat.
It's a really old topic but as it still comes up top in search results:
Nowadays you can add additional class fa-fw
to set it fixed width.
Example:
<i class="fa fa-pencil fa-fw" aria-hidden="true"></i>
By default the field delimiter is non-blank to blank transition so tab should work just fine.
However, the columns are indexed base 1 and base 0 so you probably want
sort -k4nr file.txt
to sort file.txt by column 4 numerically in reverse order. (Though the data in the question has even 5 fields so the last field would be index 5.)
You can use this to solve this issue:
Go to START > EXECUTE, and run CLICONFG.EXE.
The Named Pipes protocol will be first in the list.Demote it, and promote TCP/IP.
Test the application thoroughly.
I hope this help.
The argument is of length zero takes places when you get an output as an integer of length 0 and not a NULL output.i.e., integer(0).
You can further verify my point by finding the class of your output-
>class(output)
"integer"
Actually, you should use the translate directive for such stuff instead.
<h1 translate="{{pageTitle}}"></h1>
The directive takes care of asynchronous execution and is also clever enough to unwatch translation ids on the scope if the translation has no dynamic values.
However, if there's no way around and you really have to use $translate
service in the controller, you should wrap the call in a $translateChangeSuccess
event using $rootScope
in combination with $translate.instant()
like this:
.controller('foo', function ($rootScope, $scope, $translate) {
$rootScope.$on('$translateChangeSuccess', function () {
$scope.pageTitle = $translate.instant('PAGE.TITLE');
});
})
So why $rootScope
and not $scope
? The reason for that is, that in angular-translate's events are $emit
ed on $rootScope
rather than $broadcast
ed on $scope
because we don't need to broadcast through the entire scope hierarchy.
Why $translate.instant()
and not just async $translate()
? When $translateChangeSuccess
event is fired, it is sure that the needed translation data is there and no asynchronous execution is happening (for example asynchronous loader execution), therefore we can just use $translate.instant()
which is synchronous and just assumes that translations are available.
Since version 2.8.0 there is also $translate.onReady()
, which returns a promise that is resolved as soon as translations are ready. See the changelog.
For those who couldn't find this option. Install JDK Parameter Plugin
Wikipedia has this to say about the differences.
In general JScript is an ActiveX scripting language that is probably interpreted as JavaScript by non-IE browsers.
Most of the time you need this type of check for database usage, like checking if string valid userId. Bacause of that there can't be any strange symbols that can be parced as integer. Also integer should be in database range of integer. You just need normal int like 1,2,3 and so on.
const isStrNormPosInt = (str: string) => {
return /^([1-9]\d*)$/.test(str) && Number(str) <= 2147483647 // postgres max int
}
If check is passed, you can just convert it to number Number(str)
Which characters you must and which you mustn't escape indeed depends on the regex flavor you're working with.
For PCRE, and most other so-called Perl-compatible flavors, escape these outside character classes:
.^$*+?()[{\|
and these inside character classes:
^-]\
For POSIX extended regexes (ERE), escape these outside character classes (same as PCRE):
.^$*+?()[{\|
Escaping any other characters is an error with POSIX ERE.
Inside character classes, the backslash is a literal character in POSIX regular expressions. You cannot use it to escape anything. You have to use "clever placement" if you want to include character class metacharacters as literals. Put the ^ anywhere except at the start, the ] at the start, and the - at the start or the end of the character class to match these literally, e.g.:
[]^-]
In POSIX basic regular expressions (BRE), these are metacharacters that you need to escape to suppress their meaning:
.^$*[\
Escaping parentheses and curly brackets in BREs gives them the special meaning their unescaped versions have in EREs. Some implementations (e.g. GNU) also give special meaning to other characters when escaped, such as \? and +. Escaping a character other than .^$*(){} is normally an error with BREs.
Inside character classes, BREs follow the same rule as EREs.
If all this makes your head spin, grab a copy of RegexBuddy. On the Create tab, click Insert Token, and then Literal. RegexBuddy will add escapes as needed.
The simplest way is to create an iframe and set the source to the URL of the PDF.
(ducks mad HTML designers) Done it myself, works fine, cross browser (crawls into bunker).
This error raised up because you trying to update dict
object by using a wrong sequence (list
or tuple
) structure.
cash_id.create(cr, uid, lines,context=None)
trying to convert lines
into dict object:
(0, 0, {
'name': l.name,
'date': l.date,
'amount': l.amount,
'type': l.type,
'statement_id': exp.statement_id.id,
'account_id': l.account_id.id,
'account_analytic_id': l.analytic_account_id.id,
'ref': l.ref,
'note': l.note,
'company_id': l.company_id.id
})
Remove the second zero from this tuple to properly convert it into a dict object.
To test it your self, try this into python shell:
>>> l=[(0,0,{'h':88})]
>>> a={}
>>> a.update(l)
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
a.update(l)
ValueError: dictionary update sequence element #0 has length 3; 2 is required
>>> l=[(0,{'h':88})]
>>> a.update(l)
I realize you're looking for a "deep" copy of an array, but if you just have a single level array you can use this:
Copying a native JS Array is easy. Use the Array.slice() method which creates a copy of part/all of the array.
var foo = ['a','b','c','d','e'];
var bar = foo.slice();
now foo and bar are 5 member arrays of 'a','b','c','d','e'
of course bar is a copy, not a reference... so if you did this next...
bar.push('f');
alert('foo:' + foo.join(', '));
alert('bar:' + bar.join(', '));
you would now get:
foo:a, b, c, d, e
bar:a, b, c, d, e, f
int opcion = JOptionPane.showConfirmDialog(null, "Realmente deseas salir?", "Aviso", JOptionPane.YES_NO_OPTION);
if (opcion == 0) { //The ISSUE is here
System.out.print("si");
} else {
System.out.print("no");
}
public class JSONPage {
Logger log = Logger.getLogger("com.prodapt.autotest.gui.design.EditTestData");
public static final JFrame JSONFrame = new JFrame();
public final JPanel jPanel = new JPanel();
JLabel IdLabel = new JLabel("JSON ID*");
JLabel DataLabel = new JLabel("JSON Data*");
JFormattedTextField JId = new JFormattedTextField("Auto Generated");
JTextArea JData = new JTextArea();
JButton Cancel = new JButton("Cancel");
JButton Add = new JButton("Add");
public void JsonPage() {
JSONFrame.getContentPane().add(jPanel);
JSONFrame.add(jPanel);
JSONFrame.setSize(400, 250);
JSONFrame.setResizable(false);
JSONFrame.setVisible(false);
JSONFrame.setTitle("Add JSON Data");
JSONFrame.setLocationRelativeTo(null);
jPanel.setLayout(null);
JData.setWrapStyleWord(true);
JId.setEditable(false);
IdLabel.setBounds(20, 30, 120, 25);
JId.setBounds(100, 30, 120, 25);
DataLabel.setBounds(20, 60, 120, 25);
JData.setBounds(100, 60, 250, 75);
Cancel.setBounds(80, 170, 80, 30);
Add.setBounds(280, 170, 50, 30);
jPanel.add(IdLabel);
jPanel.add(JId);
jPanel.add(DataLabel);
jPanel.add(JData);
jPanel.add(Cancel);
jPanel.add(Add);
SwingUtilities.updateComponentTreeUI(JSONFrame);
Cancel.addActionListener(new ActionListener() {
@SuppressWarnings("deprecation")
@Override
public void actionPerformed(ActionEvent e) {
JData.setText("");
JSONFrame.hide();
TestCasePage.testCaseFrame.show();
}
});
Add.addActionListener(new ActionListener() {
@SuppressWarnings("deprecation")
@Override
public void actionPerformed(ActionEvent e) {
try {
PreparedStatement pStatement = DAOHelper.getInstance()
.createJSON(
ConnectionClass.getInstance()
.getConnection());
pStatement.setString(1, null);
if (JData.getText().toString().isEmpty()) {
JOptionPane.showMessageDialog(JSONFrame,
"Must Enter JSON Path");
} else {
// System.out.println(eleSelectBy);
pStatement.setString(2, JData.getText());
pStatement.executeUpdate();
JOptionPane.showMessageDialog(JSONFrame, "!! Added !!");
log.info("JSON Path Added"+JData);
JData.setText("");
JSONFrame.hide();
}
} catch (SQLException e1) {
JData.setText("");
log.info("Error in Adding JSON Path");
e1.printStackTrace();
}
}
});
}
}
To open the back camera:-
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(cameraIntent, REQUEST_CODE_CAMERA)
To open the front camera:-
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.O -> {
cameraIntent.putExtra("android.intent.extras.CAMERA_FACING", CameraCharacteristics.LENS_FACING_FRONT) // Tested on API 24 Android version 7.0(Samsung S6)
}
Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> {
cameraIntent.putExtra("android.intent.extras.CAMERA_FACING", CameraCharacteristics.LENS_FACING_FRONT) // Tested on API 27 Android version 8.0(Nexus 6P)
cameraIntent.putExtra("android.intent.extra.USE_FRONT_CAMERA", true)
}
else -> cameraIntent.putExtra("android.intent.extras.CAMERA_FACING", 1) // Tested API 21 Android version 5.0.1(Samsung S4)
}
startActivityForResult(cameraIntent, REQUEST_CODE_CAMERA)
I could not make it work for API 28 and above. Also, opening the front camera directly is not possible in some devices(depends on the manufacturer).
Get the latest version of MVC3 via NuGet. Open your project in Dev Studio. Open the Package Manager Console tab at the bottom of Dev Studio. Then use this command:
PM> Install-Package Microsoft.AspNet.Mvc -Version 3.0.50813.1
If you click the tab key after "-Version" you will get a list of all of the available versions.
If you have an old version of NuGet you may get an error indicating you have to upgrade it. If so, open Tools->Extension Manager to install the latest version of NuGet. Note, you will need to run Dev Studio as Administrator before you can install NuGet.
Installing MVC3 should update Web.config in your project.
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-3.0.0.1" newVersion="3.0.0.1" />
</dependentAssembly>
</assemblyBinding>
My answer is too late, but it can help others.
I had the same problem, even when I used a form tag.
I solved it by declaring Meta Charset in the header of the page:
<meta charset = "UTF-8" />
_x000D_
C# is a programming language, .NET is the framework that the language is built on.
Here is the refined version of the class which seems to work and lacks problems other solutions have:
package org.solovyev.android.views.llm;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
/**
* {@link android.support.v7.widget.LinearLayoutManager} which wraps its content. Note that this class will always
* wrap the content regardless of {@link android.support.v7.widget.RecyclerView} layout parameters.
*
* Now it's impossible to run add/remove animations with child views which have arbitrary dimensions (height for
* VERTICAL orientation and width for HORIZONTAL). However if child views have fixed dimensions
* {@link #setChildSize(int)} method might be used to let the layout manager know how big they are going to be.
* If animations are not used at all then a normal measuring procedure will run and child views will be measured during
* the measure pass.
*/
public class LinearLayoutManager extends android.support.v7.widget.LinearLayoutManager {
private static final int CHILD_WIDTH = 0;
private static final int CHILD_HEIGHT = 1;
private static final int DEFAULT_CHILD_SIZE = 100;
private final int[] childDimensions = new int[2];
private int childSize = DEFAULT_CHILD_SIZE;
private boolean hasChildSize;
@SuppressWarnings("UnusedDeclaration")
public LinearLayoutManager(Context context) {
super(context);
}
@SuppressWarnings("UnusedDeclaration")
public LinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
public static int makeUnspecifiedSpec() {
return View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
}
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
final int widthMode = View.MeasureSpec.getMode(widthSpec);
final int heightMode = View.MeasureSpec.getMode(heightSpec);
final int widthSize = View.MeasureSpec.getSize(widthSpec);
final int heightSize = View.MeasureSpec.getSize(heightSpec);
final boolean exactWidth = widthMode == View.MeasureSpec.EXACTLY;
final boolean exactHeight = heightMode == View.MeasureSpec.EXACTLY;
final int unspecified = makeUnspecifiedSpec();
if (exactWidth && exactHeight) {
// in case of exact calculations for both dimensions let's use default "onMeasure" implementation
super.onMeasure(recycler, state, widthSpec, heightSpec);
return;
}
final boolean vertical = getOrientation() == VERTICAL;
initChildDimensions(widthSize, heightSize, vertical);
int width = 0;
int height = 0;
// it's possible to get scrap views in recycler which are bound to old (invalid) adapter entities. This
// happens because their invalidation happens after "onMeasure" method. As a workaround let's clear the
// recycler now (it should not cause any performance issues while scrolling as "onMeasure" is never
// called whiles scrolling)
recycler.clear();
final int stateItemCount = state.getItemCount();
final int adapterItemCount = getItemCount();
// adapter always contains actual data while state might contain old data (f.e. data before the animation is
// done). As we want to measure the view with actual data we must use data from the adapter and not from the
// state
for (int i = 0; i < adapterItemCount; i++) {
if (vertical) {
if (!hasChildSize) {
if (i < stateItemCount) {
// we should not exceed state count, otherwise we'll get IndexOutOfBoundsException. For such items
// we will use previously calculated dimensions
measureChild(recycler, i, widthSpec, unspecified, childDimensions);
} else {
logMeasureWarning(i);
}
}
height += childDimensions[CHILD_HEIGHT];
if (i == 0) {
width = childDimensions[CHILD_WIDTH];
}
if (height >= heightSize) {
break;
}
} else {
if (!hasChildSize) {
if (i < stateItemCount) {
// we should not exceed state count, otherwise we'll get IndexOutOfBoundsException. For such items
// we will use previously calculated dimensions
measureChild(recycler, i, unspecified, heightSpec, childDimensions);
} else {
logMeasureWarning(i);
}
}
width += childDimensions[CHILD_WIDTH];
if (i == 0) {
height = childDimensions[CHILD_HEIGHT];
}
if (width >= widthSize) {
break;
}
}
}
if ((vertical && height < heightSize) || (!vertical && width < widthSize)) {
// we really should wrap the contents of the view, let's do it
if (exactWidth) {
width = widthSize;
} else {
width += getPaddingLeft() + getPaddingRight();
}
if (exactHeight) {
height = heightSize;
} else {
height += getPaddingTop() + getPaddingBottom();
}
setMeasuredDimension(width, height);
} else {
// if calculated height/width exceeds requested height/width let's use default "onMeasure" implementation
super.onMeasure(recycler, state, widthSpec, heightSpec);
}
}
private void logMeasureWarning(int child) {
if (BuildConfig.DEBUG) {
Log.w("LinearLayoutManager", "Can't measure child #" + child + ", previously used dimensions will be reused." +
"To remove this message either use #setChildSize() method or don't run RecyclerView animations");
}
}
private void initChildDimensions(int width, int height, boolean vertical) {
if (childDimensions[CHILD_WIDTH] != 0 || childDimensions[CHILD_HEIGHT] != 0) {
// already initialized, skipping
return;
}
if (vertical) {
childDimensions[CHILD_WIDTH] = width;
childDimensions[CHILD_HEIGHT] = childSize;
} else {
childDimensions[CHILD_WIDTH] = childSize;
childDimensions[CHILD_HEIGHT] = height;
}
}
@Override
public void setOrientation(int orientation) {
// might be called before the constructor of this class is called
//noinspection ConstantConditions
if (childDimensions != null) {
if (getOrientation() != orientation) {
childDimensions[CHILD_WIDTH] = 0;
childDimensions[CHILD_HEIGHT] = 0;
}
}
super.setOrientation(orientation);
}
public void clearChildSize() {
hasChildSize = false;
setChildSize(DEFAULT_CHILD_SIZE);
}
public void setChildSize(int childSize) {
hasChildSize = true;
if (this.childSize != childSize) {
this.childSize = childSize;
requestLayout();
}
}
private void measureChild(RecyclerView.Recycler recycler, int position, int widthSpec, int heightSpec, int[] dimensions) {
final View child = recycler.getViewForPosition(position);
final RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) child.getLayoutParams();
final int hPadding = getPaddingLeft() + getPaddingRight();
final int vPadding = getPaddingTop() + getPaddingBottom();
final int hMargin = p.leftMargin + p.rightMargin;
final int vMargin = p.topMargin + p.bottomMargin;
final int hDecoration = getRightDecorationWidth(child) + getLeftDecorationWidth(child);
final int vDecoration = getTopDecorationHeight(child) + getBottomDecorationHeight(child);
final int childWidthSpec = getChildMeasureSpec(widthSpec, hPadding + hMargin + hDecoration, p.width, canScrollHorizontally());
final int childHeightSpec = getChildMeasureSpec(heightSpec, vPadding + vMargin + vDecoration, p.height, canScrollVertically());
child.measure(childWidthSpec, childHeightSpec);
dimensions[CHILD_WIDTH] = getDecoratedMeasuredWidth(child) + p.leftMargin + p.rightMargin;
dimensions[CHILD_HEIGHT] = getDecoratedMeasuredHeight(child) + p.bottomMargin + p.topMargin;
recycler.recycleView(child);
}
}
This is also available as a library. Link to relevant class.
% notation is called a format specifier. For example, %d tells printf() to print an integer. %s to print a string (char *) etc. You should really look it up here: http://google.com/search?q=printf+format+specifiers
No, commas are not used for string concatenation. Commas are for separating arguments passed to a function.
This is not a spring boot tutorial. It's the updated answer to a question on how to run a Maven build within a Docker container.
Question originally posted 4 years ago.
Use the spring initializer to generate a demo app
Extract the zip archive locally
#
# Build stage
#
FROM maven:3.6.0-jdk-11-slim AS build
COPY src /home/app/src
COPY pom.xml /home/app
RUN mvn -f /home/app/pom.xml clean package
#
# Package stage
#
FROM openjdk:11-jre-slim
COPY --from=build /home/app/target/demo-0.0.1-SNAPSHOT.jar /usr/local/lib/demo.jar
EXPOSE 8080
ENTRYPOINT ["java","-jar","/usr/local/lib/demo.jar"]
Note
docker build -t demo .
$ docker run --rm -it demo:latest
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.3.RELEASE)
2019-02-22 17:18:57.835 INFO 1 --- [ main] com.example.demo.DemoApplication : Starting DemoApplication v0.0.1-SNAPSHOT on f4e67677c9a9 with PID 1 (/usr/local/bin/demo.jar started by root in /)
2019-02-22 17:18:57.837 INFO 1 --- [ main] com.example.demo.DemoApplication : No active profile set, falling back to default profiles: default
2019-02-22 17:18:58.294 INFO 1 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 0.711 seconds (JVM running for 1.035)
Read the Docker hub documentation on how the Maven build can be optimized to use a local repository to cache jars.
This question is now 4 years old and in that time it's fair to say building application using Docker has undergone significant change.
This new style enables you to create more light-weight images that don't encapsulate your build tools and source code.
The example here again uses the official maven base image to run first stage of the build using a desired version of Maven. The second part of the file defines how the built jar is assembled into the final output image.
FROM maven:3.5-jdk-8 AS build
COPY src /usr/src/app/src
COPY pom.xml /usr/src/app
RUN mvn -f /usr/src/app/pom.xml clean package
FROM gcr.io/distroless/java
COPY --from=build /usr/src/app/target/helloworld-1.0.0-SNAPSHOT.jar /usr/app/helloworld-1.0.0-SNAPSHOT.jar
EXPOSE 8080
ENTRYPOINT ["java","-jar","/usr/app/helloworld-1.0.0-SNAPSHOT.jar"]
Note:
I haven't used this approach but seems worthy of investigation as it enables you to build images without having to create nasty things like Dockerfiles :-)
https://github.com/GoogleContainerTools/jib
The project has a Maven plugin which integrates the packaging of your code directly into your Maven workflow.
Try using the new official images, there's one for Maven
https://registry.hub.docker.com/_/maven/
The image can be used to run Maven at build time to create a compiled application or, as in the following examples, to run a Maven build within a container.
The following command runs your Maven build inside a container:
docker run -it --rm \
-v "$(pwd)":/opt/maven \
-w /opt/maven \
maven:3.2-jdk-7 \
mvn clean install
Notes:
Run the Nexus container
docker run -d -p 8081:8081 --name nexus sonatype/nexus
Create a "settings.xml" file:
<settings>
<mirrors>
<mirror>
<id>nexus</id>
<mirrorOf>*</mirrorOf>
<url>http://nexus:8081/content/groups/public/</url>
</mirror>
</mirrors>
</settings>
Now run Maven linking to the nexus container, so that dependencies will be cached
docker run -it --rm \
-v "$(pwd)":/opt/maven \
-w /opt/maven \
--link nexus:nexus \
maven:3.2-jdk-7 \
mvn -s settings.xml clean install
Notes:
as the error says 'No installed build tools found' it means that
1 : It really really really did not found build tools
2 : To make him find build tools you need to define these paths correctly
PATH IS SAME FOR UBUNTU(.bashrc) AND MAC(.bash_profile)
export ANDROID_HOME=/Users/vijay/Software/android-sdk-macosx
export PATH=${PATH}:/Users/vijay/Software/android-sdk-macosx/tools
export PATH=${PATH}:/Users/vijay/Software/android-sdk-macosx/platform-tools
3 : IMPORTANT IMPORTANT as soon as you set environmental variables you need to reload evnironmental variables.
//For ubuntu
$source .bashrc
//For macos
$source .bash_profile
4 : Then check in terminal
$printenv ANDROID_HOME
$printenv PATH
Note : if you did not find your changes in printenv then restart the pc and try again printenv PATH, printenv ANDROID_HOME .There is also command to reload environmental variables .
4 : then open terminal and write HALF TEXT '$and' and hit tab. On hitting tab you should see full '$android' name.this verifys all paths are correct
5 : write $android in terminal and hit enter
If you are using a GROUP BY without any aggregate function then internally it will treated as DISTINCT, so in this case there is no difference between GROUP BY and DISTINCT.
But when you are provided with DISTINCT clause better to use it for finding your unique records because the objective of GROUP BY is to achieve aggregation.
Short answer: Both are needed.
I feel like the right answer was given but minimally. Yeah generally unset() is best for "speed", but if you want to reclaim memory immediately (at the cost of CPU) should want to use null.
Like others mentioned, setting to null doesn't mean everything is reclaimed, you can have shared memory (uncloned) objects that will prevent destruction of the object. Moreover, like others have said, you can't "destroy" the objects explicitly anyway so you shouldn't try to do it anyway.
You will need to figure out which is best for you. Also you can use __destruct() for an object which will be called on unset or null but it should be used carefully and like others said, never be called directly!
see:
http://www.stoimen.com/blog/2011/11/14/php-dont-call-the-destructor-explicitly/
I think you could do it by creating parameters in an object maybe?
var myObject = {}; for(var i=0;i<myArray.length;i++) { myObject[ myArray[i] ]; }
If you don't set them to anything, you'll just have an object with some parameters that are undefined. I'd have to write this myself to be sure though.
Awk approach:
awk '/pattern/{print; count++; if (count==10) exit}' file
You can find out the option for changing browser in Window menu
.
See image at below.
This image can be easy to understand.
Aggregated List of Libraries
There are couple of different solutions to achieve this:
1 - Native javascript for-in loop:
const result = {};
let key;
for (key in obj1) {
if(obj1.hasOwnProperty(key)){
result[key] = obj1[key];
}
}
for (key in obj2) {
if(obj2.hasOwnProperty(key)){
result[key] = obj2[key];
}
}
2 - Object.keys()
:
const result = {};
Object.keys(obj1)
.forEach(key => result[key] = obj1[key]);
Object.keys(obj2)
.forEach(key => result[key] = obj2[key]);
3 - Object.assign()
:
(Browser compatibility: Chrome: 45, Firefox (Gecko): 34, Internet Explorer: No support, Edge: (Yes), Opera: 32, Safari: 9)
const result = Object.assign({}, obj1, obj2);
4 - Spread Operator:
Standardised from ECMAScript 2015 (6th Edition, ECMA-262):
Defined in several sections of the specification: Array Initializer, Argument Lists
Using this new syntax you could join/merge different objects into one object like this:
const result = {
...obj1,
...obj2,
};
5 - jQuery.extend(target, obj1, obj2)
:
Merge the contents of two or more objects together into the first object.
const target = {};
$.extend(target, obj1, obj2);
6 - jQuery.extend(true, target, obj1, obj2)
:
Run a deep merge of the contents of two or more objects together into the target. Passing false
for the first argument is not supported.
const target = {};
$.extend(true, target, obj1, obj2);
7 - Lodash _.assignIn(object, [sources])
: also named as _.extend
:
const result = {};
_.assignIn(result, obj1, obj2);
8 - Lodash _.merge(object, [sources])
:
const result = _.merge(obj1, obj2);
There are a couple of important differences between lodash's merge function and Object.assign
:
1- Although they both receive any number of objects but lodash's merge apply a deep merge of those objects but Object.assign
only merges the first level. For instance:
_.isEqual(_.merge({
x: {
y: { key1: 'value1' },
},
}, {
x: {
y: { key2: 'value2' },
},
}), {
x: {
y: {
key1: 'value1',
key2: 'value2',
},
},
}); // true
BUT:
const result = Object.assign({
x: {
y: { key1: 'value1' },
},
}, {
x: {
y: { key2: 'value2' },
},
});
_.isEqual(result, {
x: {
y: {
key1: 'value1',
key2: 'value2',
},
},
}); // false
// AND
_.isEqual(result, {
x: {
y: {
key2: 'value2',
},
},
}); // true
2- Another difference has to do with how Object.assign
and _.merge
interpret the undefined
value:
_.isEqual(_.merge({x: 1}, {x: undefined}), { x: 1 }) // false
BUT:
_.isEqual(Object.assign({x: 1}, {x: undefined}), { x: undefined })// true
Update 1:
When using for in
loop in JavaScript, we should be aware of our environment specially the possible prototype changes in the JavaScript types. For instance some of the older JavaScript libraries add new stuff to Array.prototype
or even Object.prototype
.
To safeguard your iterations over from the added stuff we could use object.hasOwnProperty(key)
to mke sure the key is actually part of the object you are iterating over.
Update 2:
I updated my answer and added the solution number 4, which is a new JavaScript feature but not completely standardized yet. I am using it with Babeljs which is a compiler for writing next generation JavaScript.
Update 3:
I added the difference between Object.assign
and _.merge
.
Borrowing from @Khan's answer, I would do:
IF OBJECT_ID('dbo.test_abc_def', 'V') IS NOT NULL
DROP VIEW dbo.test_abc_def
GO
CREATE VIEW dbo.test_abc_def AS
SELECT
VCV.xxxx
,VCV.yyyy AS yyyy
,VCV.zzzz AS zzzz
FROM TABLE_A
UTC
is definitely a valid timezone. It is simply an abbreviation for Coordinated Universal Time. In addition, remember that date_default_timezone_set
accepts one of the following values:
$timezones=array(
"America/Adak",
"America/Argentina/Buenos_Aires",
"America/Argentina/La_Rioja",
"America/Argentina/San_Luis",
"America/Atikokan",
"America/Belem",
"America/Boise",
"America/Caracas",
"America/Chihuahua",
"America/Cuiaba",
"America/Denver",
"America/El_Salvador",
"America/Godthab",
"America/Guatemala",
"America/Hermosillo",
"America/Indiana/Tell_City",
"America/Inuvik",
"America/Kentucky/Louisville",
"America/Lima",
"America/Managua",
"America/Mazatlan",
"America/Mexico_City",
"America/Montreal",
"America/Nome",
"America/Ojinaga",
"America/Port-au-Prince",
"America/Rainy_River",
"America/Rio_Branco",
"America/Santo_Domingo",
"America/St_Barthelemy",
"America/St_Vincent",
"America/Tijuana",
"America/Whitehorse",
"America/Anchorage",
"America/Argentina/Catamarca",
"America/Argentina/Mendoza",
"America/Argentina/Tucuman",
"America/Atka",
"America/Belize",
"America/Buenos_Aires",
"America/Catamarca",
"America/Coral_Harbour",
"America/Curacao",
"America/Detroit",
"America/Ensenada",
"America/Goose_Bay",
"America/Guayaquil",
"America/Indiana/Indianapolis",
"America/Indiana/Vevay",
"America/Iqaluit",
"America/Kentucky/Monticello",
"America/Los_Angeles",
"America/Manaus",
"America/Mendoza",
"America/Miquelon",
"America/Montserrat",
"America/Noronha",
"America/Panama",
"America/Port_of_Spain",
"America/Rankin_Inlet",
"America/Rosario",
"America/Sao_Paulo",
"America/St_Johns",
"America/Swift_Current",
"America/Toronto",
"America/Winnipeg",
"America/Anguilla",
"America/Argentina/ComodRivadavia",
"America/Argentina/Rio_Gallegos",
"America/Argentina/Ushuaia",
"America/Bahia",
"America/Blanc-Sablon",
"America/Cambridge_Bay",
"America/Cayenne",
"America/Cordoba",
"America/Danmarkshavn",
"America/Dominica",
"America/Fort_Wayne",
"America/Grand_Turk",
"America/Guyana",
"America/Indiana/Knox",
"America/Indiana/Vincennes",
"America/Jamaica",
"America/Knox_IN",
"America/Louisville",
"America/Marigot",
"America/Menominee",
"America/Moncton",
"America/Nassau",
"America/North_Dakota/Beulah",
"America/Pangnirtung",
"America/Porto_Acre",
"America/Recife",
"America/Santa_Isabel",
"America/Scoresbysund",
"America/St_Kitts",
"America/Tegucigalpa",
"America/Tortola",
"America/Yakutat",
"America/Antigua",
"America/Argentina/Cordoba",
"America/Argentina/Salta",
"America/Aruba",
"America/Bahia_Banderas",
"America/Boa_Vista",
"America/Campo_Grande",
"America/Cayman",
"America/Costa_Rica",
"America/Dawson",
"America/Edmonton",
"America/Fortaleza",
"America/Grenada",
"America/Halifax",
"America/Indiana/Marengo",
"America/Indiana/Winamac",
"America/Jujuy",
"America/Kralendijk",
"America/Lower_Princes",
"America/Martinique",
"America/Merida",
"America/Monterrey",
"America/New_York",
"America/North_Dakota/Center",
"America/Paramaribo",
"America/Porto_Velho",
"America/Regina",
"America/Santarem",
"America/Shiprock",
"America/St_Lucia",
"America/Thule",
"America/Vancouver",
"America/Yellowknife",
"America/Araguaina",
"America/Argentina/Jujuy",
"America/Argentina/San_Juan",
"America/Asuncion",
"America/Barbados",
"America/Bogota",
"America/Cancun",
"America/Chicago",
"America/Creston",
"America/Dawson_Creek",
"America/Eirunepe",
"America/Glace_Bay",
"America/Guadeloupe",
"America/Havana",
"America/Indiana/Petersburg",
"America/Indianapolis",
"America/Juneau",
"America/La_Paz",
"America/Maceio",
"America/Matamoros",
"America/Metlakatla",
"America/Montevideo",
"America/Nipigon",
"America/North_Dakota/New_Salem",
"America/Phoenix",
"America/Puerto_Rico",
"America/Resolute",
"America/Santiago",
"America/Sitka",
"America/St_Thomas",
"America/Thunder_Bay",
"America/Virgin",
"Indian/Antananarivo",
"Indian/Kerguelen",
"Indian/Reunion",
"Australia/ACT",
"Australia/Currie",
"Australia/Lindeman",
"Australia/Perth",
"Australia/Victoria",
"Europe/Amsterdam",
"Europe/Berlin",
"Europe/Chisinau",
"Europe/Helsinki",
"Europe/Kiev",
"Europe/Madrid",
"Europe/Moscow",
"Europe/Prague",
"Europe/Sarajevo",
"Europe/Tallinn",
"Europe/Vatican",
"Europe/Zagreb",
"Pacific/Apia",
"Pacific/Efate",
"Pacific/Galapagos",
"Pacific/Johnston",
"Pacific/Marquesas",
"Pacific/Noumea",
"Pacific/Ponape",
"Pacific/Tahiti",
"Pacific/Wallis",
"Indian/Chagos",
"Indian/Mahe",
"Australia/Adelaide",
"Australia/Darwin",
"Australia/Lord_Howe",
"Australia/Queensland",
"Australia/West",
"Europe/Andorra",
"Europe/Bratislava",
"Europe/Copenhagen",
"Europe/Isle_of_Man",
"Europe/Lisbon",
"Europe/Malta",
"Europe/Nicosia",
"Europe/Riga",
"Europe/Simferopol",
"Europe/Tirane",
"Europe/Vienna",
"Europe/Zaporozhye",
"Pacific/Auckland",
"Pacific/Enderbury",
"Pacific/Gambier",
"Pacific/Kiritimati",
"Pacific/Midway",
"Pacific/Pago_Pago",
"Pacific/Port_Moresby",
"Pacific/Tarawa",
"Pacific/Yap",
"Africa/Abidjan",
"Africa/Asmera",
"Africa/Blantyre",
"Africa/Ceuta",
"Africa/Douala",
"Africa/Johannesburg",
"Africa/Kinshasa",
"Africa/Lubumbashi",
"Africa/Mbabane",
"Africa/Niamey",
"Africa/Timbuktu",
"Africa/Accra",
"Africa/Bamako",
"Africa/Brazzaville",
"Africa/Conakry",
"Africa/El_Aaiun",
"Africa/Juba",
"Africa/Lagos",
"Africa/Lusaka",
"Africa/Mogadishu",
"Africa/Nouakchott",
"Africa/Tripoli",
"Africa/Addis_Ababa",
"Africa/Bangui",
"Africa/Bujumbura",
"Africa/Dakar",
"Africa/Freetown",
"Africa/Kampala",
"Africa/Libreville",
"Africa/Malabo",
"Africa/Monrovia",
"Africa/Ouagadougou",
"Africa/Tunis",
"Africa/Algiers",
"Africa/Banjul",
"Africa/Cairo",
"Africa/Dar_es_Salaam",
"Africa/Gaborone",
"Africa/Khartoum",
"Africa/Lome",
"Africa/Maputo",
"Africa/Nairobi",
"Africa/Porto-Novo",
"Africa/Windhoek",
"Africa/Asmara",
"Africa/Bissau",
"Africa/Casablanca",
"Africa/Djibouti",
"Africa/Harare",
"Africa/Kigali",
"Africa/Luanda",
"Africa/Maseru",
"Africa/Ndjamena",
"Africa/Sao_Tome",
"Atlantic/Azores",
"Atlantic/Faroe",
"Atlantic/St_Helena",
"Atlantic/Bermuda",
"Atlantic/Jan_Mayen",
"Atlantic/Stanley",
"Atlantic/Canary",
"Atlantic/Madeira",
"Atlantic/Cape_Verde",
"Atlantic/Reykjavik",
"Atlantic/Faeroe",
"Atlantic/South_Georgia",
"Asia/Aden",
"Asia/Aqtobe",
"Asia/Baku",
"Asia/Calcutta",
"Asia/Dacca",
"Asia/Dushanbe",
"Asia/Hong_Kong",
"Asia/Jayapura",
"Asia/Kashgar",
"Asia/Kuala_Lumpur",
"Asia/Magadan",
"Asia/Novokuznetsk",
"Asia/Pontianak",
"Asia/Riyadh",
"Asia/Shanghai",
"Asia/Tehran",
"Asia/Ujung_Pandang",
"Asia/Vladivostok",
"Asia/Almaty",
"Asia/Ashgabat",
"Asia/Bangkok",
"Asia/Choibalsan",
"Asia/Damascus",
"Asia/Gaza",
"Asia/Hovd",
"Asia/Jerusalem",
"Asia/Kathmandu",
"Asia/Kuching",
"Asia/Makassar",
"Asia/Novosibirsk",
"Asia/Pyongyang",
"Asia/Saigon",
"Asia/Singapore",
"Asia/Tel_Aviv",
"Asia/Ulaanbaatar",
"Asia/Yakutsk",
"Asia/Amman",
"Asia/Ashkhabad",
"Asia/Beirut",
"Asia/Chongqing",
"Asia/Dhaka",
"Asia/Harbin",
"Asia/Irkutsk",
"Asia/Kabul",
"Asia/Katmandu",
"Asia/Kuwait",
"Asia/Manila",
"Asia/Omsk",
"Asia/Qatar",
"Asia/Sakhalin",
"Asia/Taipei",
"Asia/Thimbu",
"Asia/Ulan_Bator",
"Asia/Yekaterinburg",
"Asia/Anadyr",
"Asia/Baghdad",
"Asia/Bishkek",
"Asia/Chungking",
"Asia/Dili",
"Asia/Hebron",
"Asia/Istanbul",
"Asia/Kamchatka",
"Asia/Kolkata",
"Asia/Macao",
"Asia/Muscat",
"Asia/Oral",
"Asia/Qyzylorda",
"Asia/Samarkand",
"Asia/Tashkent",
"Asia/Thimphu",
"Asia/Urumqi",
"Asia/Yerevan",
"Asia/Aqtau",
"Asia/Bahrain",
"Asia/Brunei",
"Asia/Colombo",
"Asia/Dubai",
"Asia/Ho_Chi_Minh",
"Asia/Jakarta",
"Asia/Karachi",
"Asia/Krasnoyarsk",
"Asia/Macau",
"Asia/Nicosia",
"Asia/Phnom_Penh",
"Asia/Rangoon",
"Asia/Seoul",
"Asia/Tbilisi",
"Asia/Tokyo",
"Asia/Vientiane",
"Australia/Canberra",
"Australia/LHI",
"Australia/NSW",
"Australia/Tasmania",
"Australia/Broken_Hill",
"Australia/Hobart",
"Australia/North",
"Australia/Sydney",
"Pacific/Chuuk",
"Pacific/Fiji",
"Pacific/Guam",
"Pacific/Kwajalein",
"Pacific/Niue",
"Pacific/Pitcairn",
"Pacific/Saipan",
"Pacific/Truk",
"Pacific/Chatham",
"Pacific/Fakaofo",
"Pacific/Guadalcanal",
"Pacific/Kosrae",
"Pacific/Nauru",
"Pacific/Palau",
"Pacific/Rarotonga",
"Pacific/Tongatapu",
"Pacific/Easter",
"Pacific/Funafuti",
"Pacific/Honolulu",
"Pacific/Majuro",
"Pacific/Norfolk",
"Pacific/Pohnpei",
"Pacific/Samoa",
"Pacific/Wake",
"Antarctica/Casey",
"Antarctica/McMurdo",
"Antarctica/Vostok",
"Antarctica/Davis",
"Antarctica/Palmer",
"Antarctica/DumontDUrville",
"Antarctica/Rothera",
"Antarctica/Macquarie",
"Antarctica/South_Pole",
"Antarctica/Mawson",
"Antarctica/Syowa",
"Arctic/Longyearbyen",
"Europe/Athens",
"Europe/Brussels",
"Europe/Dublin",
"Europe/Istanbul",
"Europe/Ljubljana",
"Europe/Mariehamn",
"Europe/Oslo",
"Europe/Rome",
"Europe/Skopje",
"Europe/Tiraspol",
"Europe/Vilnius",
"Europe/Zurich",
"Europe/Belfast",
"Europe/Bucharest",
"Europe/Gibraltar",
"Europe/Jersey",
"Europe/London",
"Europe/Minsk",
"Europe/Paris",
"Europe/Samara",
"Europe/Sofia",
"Europe/Uzhgorod",
"Europe/Volgograd",
"Europe/Belgrade",
"Europe/Budapest",
"Europe/Guernsey",
"Europe/Kaliningrad",
"Europe/Luxembourg",
"Europe/Monaco",
"Europe/Podgorica",
"Europe/San_Marino",
"Europe/Stockholm",
"Europe/Vaduz",
"Europe/Warsaw",
"Indian/Cocos",
"Indian/Mauritius",
"Indian/Christmas",
"Indian/Maldives",
"Indian/Comoro",
"Indian/Mayotte",
"Australia/Brisbane",
"Australia/Eucla",
"Australia/Melbourne",
"Australia/South",
"Australia/Yancowinna",
);
Timezones in PHP at http://www.php.net/manual/en/timezones.php
You are looking for CHAR_LENGTH()
to get the number of characters in a string.
For multi-byte charsets LENGTH()
will give you the number of bytes the string occupies, while CHAR_LENGTH()
will return the number of characters.
Free "Export to KML" script for ArcGIS 9
Here is a list of available methods that someone found.
Also, it seems to me that the most efficient representation of a polygon layer is by using Google Maps API's polyline encoding, which significantly compresses lat-lng data. But getting into that format takes work: use ArcMap to export Shape as lat/lng coordinates, then convert into polylines using Google Maps API.
Now that we can use dataFor()
to check if the binding has been applied, I would prefer check the data binding, rather than cleanNode()
and applyBindings()
.
Like this:
var koNode = document.getElementById('formEdit');
var hasDataBinding = !!ko.dataFor(koNode);
console.log('has data binding', hasDataBinding);
if (!hasDataBinding) { ko.applyBindings(vm, koNode);}
A lot of answers already!
First, let's say it is fairly common that we need to do the binding multiple times in a page. Say, I have a form inside the Bootstrap modal, which will be loaded again and again. Many of the form input have two-way binding.
I usually take the easy route: clearing the binding every time before the the binding.
var koNode = document.getElementById('formEdit');
ko.cleanNode(koNode);
ko.applyBindings(vm, koNode);
Just make sure here koNode
is required, for, ko.cleanNode()
requires a node element, even though we can omit it in ko.applyBinding(vm)
.
The ?type=daily
argument (ending up in the $_GET
array) is only valid for web-accessed pages.
You'll need to call it like php myfile.php daily
and retrieve that argument from the $argv
array (which would be $argv[1]
, since $argv[0]
would be myfile.php
).
If the page is used as a webpage as well, there are two options you could consider. Either accessing it with a shell script and Wget, and call that from cron:
#!/bin/sh
wget http://location.to/myfile.php?type=daily
Or check in the PHP file whether it's called from the command line or not:
if (defined('STDIN')) {
$type = $argv[1];
} else {
$type = $_GET['type'];
}
(Note: You'll probably need/want to check if $argv
actually contains enough variables and such)
CSS rules are inherited by default - hence the "cascading" name. To get what you want you need to use !important:
form div
{
font-size: 12px;
font-weight: bold;
}
div.content
{
// any rule you want here, followed by !important
}
\S
matches anything but a whitespace, according to this reference.
Actually there is another (maybe better solution) where you can use the angular's native 'filter' filter and still pass arguments to your custom filter.
Consider the following code:
<div ng-repeat="group in groups">
<li ng-repeat="friend in friends | filter:weDontLike(group.enemy.name)">
<span>{{friend.name}}</span>
<li>
</div>
To make this work you just define your filter as the following:
$scope.weDontLike = function(name) {
return function(friend) {
return friend.name != name;
}
}
As you can see here, weDontLike actually returns another function which has your parameter in its scope as well as the original item coming from the filter.
It took me 2 days to realise you can do this, haven't seen this solution anywhere yet.
Checkout Reverse polarity of an angular.js filter to see how you can use this for other useful operations with filter.
yes, static block is used for initialize the code and it will load at the time JVM start for execution.
static block is used in previous versions of java but in latest version it doesn't work.
I think you might not see fractals as an algorithm or something to program. Fractals is a concept! It is a mathematical concept of detailed pattern repeating itself.
Therefore you can create a fractal in many ways, using different approaches, as shown in the image below.
Choose an approach and then investigate how to implement it. These four examples were implemented using Marvin Framework. The source codes are available here
Note that this isn't perfect, since if you had something like, say, <a title=">">
it would break. However, it's about the closest you'd get in non-library Python without a really complex function:
import re
TAG_RE = re.compile(r'<[^>]+>')
def remove_tags(text):
return TAG_RE.sub('', text)
However, as lvc mentions xml.etree
is available in the Python Standard Library, so you could probably just adapt it to serve like your existing lxml
version:
def remove_tags(text):
return ''.join(xml.etree.ElementTree.fromstring(text).itertext())
I was just playing a bit to try to make a dict comprehension with reduce, and come up with this one liner hack:
In [1]: from functools import reduce
In [2]: reduce(lambda d, i: (i[0] < 7 and d.__setitem__(*i[::-1]), d)[-1], [{}, *{1:2, 3:4, 5:6, 7:8}.items()])
Out[3]: {2: 1, 4: 3, 6: 5}
I was just trying to do the same as what was done in this Javascript dict comprehension: https://stackoverflow.com/a/11068265
check if the app is in background or foreground. This method will return true if the app is in background.
First add the GET_TASKS permission to your AndroidManifest.xml
private boolean isAppIsInBackground(Context context) {
boolean isInBackground = true;
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
for (String activeProcess : processInfo.pkgList) {
if (activeProcess.equals(context.getPackageName())) {
isInBackground = false;
}
}
}
}
} else {
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
if (componentInfo.getPackageName().equals(context.getPackageName())) {
isInBackground = false;
}
}
return isInBackground;
}
If you look in the source code of the JDK, you can see that for unix systems the property is read at compile time from the paths.h or hard coded. For windows the function GetTempPathW
from win32 returns the tmpdir
name.
For posix systems you might expect the standard TMPDIR
to work, but that is not the case. You can confirm that TMPDIR
is not used by running TMPDIR=/mytmp java -XshowSettings
Assume you got a file called file.txt that you want to read in a program and the content is this:
this is the content of the file
with open you can read it and
then with a loop you can print it
on the screen. Using enconding='utf-8'
you avoid some strange convertions of
caracters. With strip(), you avoid printing
an empty line between each (not empty) line
You can read this content: write the following script in notepad:
with open("file.txt", "r", encoding="utf-8") as file:
for line in file:
print(line.strip())
save it as readfile.py for example, in the same folder of the txt file.
Then you run it (shift + right click of the mouse and select the prompt from the contextual menu) writing in the prompt:
C:\examples> python readfile.py
You should get this. Play attention to the word, they have to be written just as you see them and to the indentation. It is important in python. Use always the same indentation in each file (4 spaces are good).
output
this is the content of the file
with open you can read it and
then with a loop you can print it
on the screen. Using enconding='utf-8'
you avoid some strange convertions of
caracters. With strip(), you avoid printing
an empty line between each (not empty) line
If the date is given in a fixed form, you can simply use a regular expression to extract the date and "datetime.datetime.strptime" to parse the date:
import re
from datetime import datetime
match = re.search(r'\d{4}-\d{2}-\d{2}', text)
date = datetime.strptime(match.group(), '%Y-%m-%d').date()
Otherwise, if the date is given in an arbitrary form, you can't extract it easily.
If you actually have a database, this is the most-simple way:
var lsPetOwners = ( from person in context.People
from pets in context.Pets
.Where(mypet => mypet.Owner == person.ID)
.DefaultIfEmpty()
select new { OwnerName = person.Name, Pet = pets.Name }
).ToList();
Let's merge these responses:
See the "powered by Subversion" line when accessing the server via a browser.
Access the repository via browser and then look for the version string embedded in the HTML source. From earlier answers by elviejo and jaredjacobs. Similarly, from ??, use your browser's developer tools (usually Ctrl + Shift + I) to read the full response. This is also the easiest (non-automated) way to deal with certificates and authorization - your browser does it for you.
Check the response tags (these are not shown in the HTML source), from an earlier answer by Christopher
wget -S --spider 'http://svn.server.net/svn/repository' 2>&1 |
sed -n '/SVN/s/.*\(SVN[0-9\/\.]*\).*/\1/p'
From an earlier answer by Milen
svnserve --version (run on svn server)
From an earlier answer by Glenn
ssh user@host svnserve --version
Check out the current version in a FAQ:
http://code.google.com/p/support/wiki/SubversionFAQ#What_version_of_Subversion_do_you_use?
TBD
Please edit to finish this answer
svn --version
I had a similar problem and google was sending me to this post. My solution was a bit different and less compact, but hopefully this can be useful to someone.
Showing your image with matplotlib.pyplot.imshow is generally a fast way to display 2D data. However this by default labels the axes with the pixel count. If the 2D data you are plotting corresponds to some uniform grid defined by arrays x and y, then you can use matplotlib.pyplot.xticks and matplotlib.pyplot.yticks to label the x and y axes using the values in those arrays. These will associate some labels, corresponding to the actual grid data, to the pixel counts on the axes. And doing this is much faster than using something like pcolor for example.
Here is an attempt at this with your data:
import matplotlib.pyplot as plt
# ... define 2D array hist as you did
plt.imshow(hist, cmap='Reds')
x = np.arange(80,122,2) # the grid to which your data corresponds
nx = x.shape[0]
no_labels = 7 # how many labels to see on axis x
step_x = int(nx / (no_labels - 1)) # step between consecutive labels
x_positions = np.arange(0,nx,step_x) # pixel count at label position
x_labels = x[::step_x] # labels you want to see
plt.xticks(x_positions, x_labels)
# in principle you can do the same for y, but it is not necessary in your case
Solution using display: flex (with responsive behavior): http://jsfiddle.net/dkulahin/w3472kct
HTML:
<div class="content">
<img src="myimage.jpg" alt="" />
<div class="details">
<p>Lorem ipsum dolor sit amet...</p>
</div>
</div>
CSS:
.content{
display: flex;
align-items: flex-start;
justify-content: flex-start;
}
.content img {
width: 150px;
}
.details {
width: calc(100% - 150px);
}
@media only screen and (max-width: 480px) {
.content {
flex-direction: column;
}
.details {
width: 100%;
}
}
There are so many reasons for this error.I also got one and solved it.
It may be possible that you are adding a third party framework and not including it in the Copy Bundle Resources.That solved the problem for me.
Do this as follows. Go to Target -> BuildPhases -> CopyBundleResources -> Drag and drop your framework and run the code.