It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:
openssl sha1 [put the full path to the file here without brackets]
For example:
openssl sha1 /Users/me/Desktop/myFile.dmg
If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.
Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.
So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.
Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.
I made a mistake by adding a service
into imports
array instead of providers
array.
@NgModule({
imports: [
MyService // wrong here
],
providers: [
MyService // should add here
]
})
export class AppModule { }
Angular
says you need to add Injectables
into providers
array.
If your are using IntelliJ, go to setting => compiler and change the version to your current java version.
This worked with R reticulate. Found it here.
1: matplotlib.use( 'tkagg' )
or
2: matplotlib$use( 'tkagg' )
For example:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
import matplotlib
matplotlib.use( 'tkagg' )
style.use("ggplot")
from sklearn import svm
x = [1, 5, 1.5, 8, 1, 9]
y = [2, 8, 1.8, 8, 0.6, 11]
plt.scatter(x,y)
plt.show()
If you face this issue in Linux, one of the common reasons can be that the folder "anaconda3" or "anaconda2" has root ownership. This prevents other users from writing into the folder. This can be resolved by changing the ownership of the folder from root to "USER" by running the command:
sudo chown -R $USER:$USER anaconda3
or sudo chown -R $USER:$USER <path of anaconda 3/2 folder>
Note: How to figure out whether a folder has root ownership? -- There will be a lock symbol on the top right corner of the respective folder. Or right-click on the folder->properties and you will be able to see the owner details
The -R argument lets the $USER access all the folders and files within the folder anaconda3 or anaconda2 or any respective folder. It stands for "recursive".
Using Anaconda + Spyder (Python 3.7)
[code]
import tensorflow as tf
valor1 = tf.constant(2)
valor2 = tf.constant(3)
type(valor1)
print(valor1)
soma=valor1+valor2
type(soma)
print(soma)
sess = tf.compat.v1.Session()
with sess:
print(sess.run(soma))
[console]
import tensorflow as tf
valor1 = tf.constant(2)
valor2 = tf.constant(3)
type(valor1)
print(valor1)
soma=valor1+valor2
type(soma)
Tensor("Const_8:0", shape=(), dtype=int32)
Out[18]: tensorflow.python.framework.ops.Tensor
print(soma)
Tensor("add_4:0", shape=(), dtype=int32)
sess = tf.compat.v1.Session()
with sess:
print(sess.run(soma))
5
One thing that hasn't been pointed out, is that there is little to no difference between not having an active environment and and activating the base environment, if you just want to run applications from Conda's (Python's) scripts directory (as @DryLabRebel wants).
You can install and uninstall via conda and conda shows the base environment as active - which essentially it is:
> echo $Env:CONDA_DEFAULT_ENV
> conda env list
# conda environments:
#
base * F:\scoop\apps\miniconda3\current
> conda activate
> echo $Env:CONDA_DEFAULT_ENV
base
> conda env list
# conda environments:
#
base * F:\scoop\apps\miniconda3\current
I changed file -> project structure -> project settings -> modules In the source tab, I set the Language Level from : 14, or 11, to: "Project Default". This fixed my issue.
If your using vs code on mac, it's important to have your venv installed in the same directory as your workspace.
In my case my venv was in a different directory( not in my project workspace) so a simple cut/copy-paste of my venv to the project workspace did the trick.
As soon as your venv is copied to the project workspace, your vs code will pick that up and show a notification giving you an option to select venv as an interpreter.
None of the previous answers worked for me. Adding both of the lines below to my settings.json file did, however.
"python.analysis.disabled": [
"unresolved-import"
],
"python.linting.pylintArgs": ["--load-plugin","pylint_protobuf"]
The first line really just hides the linting error. Certainly not a permanent solution, but de-clutters the screen.
This answer gave me the second line: VS Code PyLint Error E0602 (undefined variable) with ProtoBuf compiled Python Structure
Maybe someone who understands Python more than me can explain that one more.
For others who have the same problem in IntelliJ:
upgrading to the latest IDE version should resolve the issue.
In my case going from 2018.1 -> 2018.3.3
I already tried all suggestion posted in here, yet I'm still getting the errno 13,
I'm using Windows and my python version is 3.7.3
After 5 hours of trying to solve it, this step worked for me:
I try to open the command prompt by run as administrator
Using an elevated command prompt worked wonders. All you have to do is run
pip install <package-name>
With an administrative privilege.
Blobs are returned with file type from backend. The following function will accept any file type and popup download window:
downloadFile(route: string, filename: string = null): void{
const baseUrl = 'http://myserver/index.php/api';
const token = 'my JWT';
const headers = new HttpHeaders().set('authorization','Bearer '+token);
this.http.get(baseUrl + route,{headers, responseType: 'blob' as 'json'}).subscribe(
(response: any) =>{
let dataType = response.type;
let binaryData = [];
binaryData.push(response);
let downloadLink = document.createElement('a');
downloadLink.href = window.URL.createObjectURL(new Blob(binaryData, {type: dataType}));
if (filename)
downloadLink.setAttribute('download', filename);
document.body.appendChild(downloadLink);
downloadLink.click();
}
)
}
Requirements:
Worked great without restart on Xcode 10
If for some people (like me earlier) the above answers don't work, I think the following answer would work (for Mac users I think) Enter the following commands to do flask run
$ export FLASK_APP = hello.py
$ export FLASK_ENV = development
$ flask run
Alternatively you can do the following (I haven't tried this but one resource online talks about it)
$ export FLASK_APP = hello.py
$ python -m flask run
source: For more
Prefix the variable name with env
:
$env:path
For example, if you want to print the value of environment value "MINISHIFT_USERNAME", then command will be:
$env:MINISHIFT_USERNAME
You can also enumerate all variables via the env
drive:
Get-ChildItem env:
For those using Vue CLI 3 and the webpack-simple install, Aaron's answer did work for me however I wasn't keen on adding my environment variables to my webpack.config.js
as I wanted to commit it to GitHub. Instead I installed the dotenv-webpack plugin and this appears to load environment variables fine from a .env
file at the root of the project without the need to prepend VUE_APP_
to the environment variables.
pip install --user package-name
Seems to work, but the package is install the the path of user. such as :
"c:\users\***\appdata\local\temp\pip-req-tracker-_akmzo\42a6c7d627641b148564ff35597ec30fd5543aa1cf6e41118b98d7a3"
I want to install the package in python folder such c:\Python27. I install the module into the expected folder by:
pip install package-name --no-cache-dir
Try this:
implementation 'com.android.support:appcompat-v7:28.0.0-alpha1'
You can install openssl
using one single line if you have chocolatey installed
choco install openssl
From angular 6 you can run the command below to fix that issue
npm install --save-dev @angular-devkit/build-angular
OR
yarn add @angular-devkit/build-angular --dev
If your you still can not resolve issues, you can see other option from an unhandled exception occurred: cannot find module '@angular-devkit/build-angular/package.json'
Install @angular-devkit/build-angular
as dev dependency. This package is newly introduced in Angular 6.0
npm install --save-dev @angular-devkit/build-angular
or,
yarn add @angular-devkit/build-angular --dev
You need to use the new configuration
option (this works for ng build
and ng serve
as well)
ng serve --configuration=local
or
ng serve -c local
If you look at your angular.json
file, you'll see that you have finer control over settings for each configuration (aot, optimizer, environment files,...)
"configurations": {
"production": {
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
]
}
}
You can get more info here for managing environment specific configurations.
As pointed in the other response below, if you need to add a new 'environment', you need to add a new configuration to the build task and, depending on your needs, to the serve and test tasks as well.
Adding a new environment
Edit:
To make it clear, file replacements must be specified in the build
section. So if you want to use ng serve
with a specific environment
file (say dev2), you first need to modify the build
section to add a new dev2 configuration
"build": {
"configurations": {
"dev2": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.dev2.ts"
}
/* You can add all other options here, such as aot, optimization, ... */
],
"serviceWorker": true
},
Then modify your serve
section to add a new configuration as well, pointing to the dev2 build
configuration you just declared
"serve":
"configurations": {
"dev2": {
"browserTarget": "projectName:build:dev2"
}
Then you can use ng serve -c dev2
, which will use the dev2 config file
Android, Python !
When I saw these two keywords together in your question, Kivy is the one which came to my mind first.
Before coming to native Android development in Java using Android Studio, I had tried Kivy. It just awesome. Here are a few advantage I could find out.
Simple to use
With a python basics, you won't have trouble learning it.
Good community
It's well documented and has a great, active community.
Cross platform.
You can develop thing for Android, iOS, Windows, Linux and even Raspberry Pi with this single framework. Open source.
It is a free software
At least few of it's (Cross platform) competitors want you to pay a fee if you want a commercial license.
Accelerated graphics support
Kivy's graphics engine build over OpenGL ES 2 makes it suitable for softwares which require fast graphics rendering such as games.
Now coming into the next part of question, you can't use Android Studio IDE for Kivy. Here is a detailed guide for setting up the development environment.
Those who are not having web.config file. Output Type other than web application. update the project file (.csproj) with below give code.
It may cause due to adding/removing the .netframework in improper way or it may broke unexpected way.
<ItemGroup>
<Reference Include="netstandard" />
</ItemGroup>
Output Type
If all sorts of updating commando's won't do it. Try deleting package-lock.json. And then run npm install. Did the trick for me after going through tons of update commando's.
I found this solution.I download JDK 8.Then I add downloading jdk file path name of JAVA_HOME into user variables in environment variable.
Following what @viveknuna suggested, I upgraded to the latest version of node.js and npm using the downloaded installer. I also installed the latest version of yarn using a downloaded installer. Then, as you can see below, I upgraded angular-cli and typescript. Here's what that process looked like:
D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>npm install -g @angular/cli@latest
C:\Users\Jack\AppData\Roaming\npm\ng -> C:\Users\Jack\AppData\Roaming\npm\node_modules\@angular\cli\bin\ng
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\@angular\cli\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
+ @angular/[email protected]
added 75 packages, removed 166 packages, updated 61 packages and moved 24 packages in 29.084s
D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>npm install -g typescript
C:\Users\Jack\AppData\Roaming\npm\tsserver -> C:\Users\Jack\AppData\Roaming\npm\node_modules\typescript\bin\tsserver
C:\Users\Jack\AppData\Roaming\npm\tsc -> C:\Users\Jack\AppData\Roaming\npm\node_modules\typescript\bin\tsc
+ [email protected]
updated 1 package in 2.427s
D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>node -v
v8.10.0
D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>npm -v
5.6.0
D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>yarn --version
1.5.1
Thereafter, I ran yarn
and npm start
in my angular folder and all appears to be well. Here's what that looked like:
D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>yarn
yarn install v1.5.1
[1/4] Resolving packages...
[2/4] Fetching packages...
info [email protected]: The platform "win32" is incompatible with this module.
info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
warning "@angular/cli > @schematics/[email protected]" has incorrect peer dependency "@angular-devkit/[email protected]".
warning "@angular/cli > @angular-devkit/schematics > @schematics/[email protected]" has incorrect peer dependency "@angular-devkit/[email protected]".
warning " > [email protected]" has incorrect peer dependency "@angular/compiler@^2.3.1 || >=4.0.0-beta <5.0.0".
warning " > [email protected]" has incorrect peer dependency "@angular/core@^2.3.1 || >=4.0.0-beta <5.0.0".
[4/4] Building fresh packages...
Done in 232.79s.
D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>npm start
> [email protected] start D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular
> ng serve --host 0.0.0.0 --port 4200
** NG Live Development Server is listening on 0.0.0.0:4200, open your browser on http://localhost:4200/ **
Date: 2018-03-22T13:17:28.935Z
Hash: 8f226b6fa069b7c201ea
Time: 22494ms
chunk {account.module} account.module.chunk.js () 129 kB [rendered]
chunk {app.module} app.module.chunk.js () 497 kB [rendered]
chunk {common} common.chunk.js (common) 1.46 MB [rendered]
chunk {inline} inline.bundle.js (inline) 5.79 kB [entry] [rendered]
chunk {main} main.bundle.js (main) 515 kB [initial] [rendered]
chunk {polyfills} polyfills.bundle.js (polyfills) 1.1 MB [initial] [rendered]
chunk {styles} styles.bundle.js (styles) 1.53 MB [initial] [rendered]
chunk {vendor} vendor.bundle.js (vendor) 15.1 MB [initial] [rendered]
webpack: Compiled successfully.
For mac users,
It was working fine yesterday, now the hell broke. I was able to fix it.
My issue was with ANDROID_HOME
// This is wrong. No idea how it was working earlier.
ANDROID_HOME = Library/Android/sdk
If you did the same, change it to:
ANDROID_HOME = /Users/rana.singh/Library/Android/sdk
.bash_profile has
export ANDROID_HOME=/Users/rana.singh/Library/Android/sdk
export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
Environments created with the --prefix
or -p
flag must be removed with the -p
flag (not -n
).
For example:
conda remove -p </filepath/myenvironment> --all
, in which </filepath/myenvironment>
is substituted with a complete or relative path to the environment.
In my machine, flutter was installed in
C:\src\flutter
I set dart sdk path as
C:\src\flutter\bin\cache\dart-sdk
This solved my problem
If you've already assigned the variables using the npm module dotenv
, then they should show up in your global variables. That module is here.
While running the debugger, go to your variables tab (right click to reopen if not visible) and then open "global" and then "process." There should then be an env section...
Make sure you have an Android Virtual Device selected to output the app to. In the picture I put on this post you can see I selected the Android Virtual Device "Nexus 5" as the output device. Doing this removed the error for me.
Try adding the conda-forge channel to your list of channels with this command:
conda config --append channels conda-forge
. It tells conda to also look on the conda-forge channel when you search for packages. You can then simply install the two packages with conda install slycot control
.
Channels are basically servers for people to host packages on and the community-driven conda-forge is usually a good place to start when packages are not available via the standard channels. I checked and both slycot and control seem to be available there.
Below solution is a clean work around.It does not compromises security because we are using same strict firewall.
The Steps for fixing is as below:
STEP 1 : Create a Class overriding StrictHttpFirewall as below.
package com.biz.brains.project.security.firewall;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpMethod;
import org.springframework.security.web.firewall.DefaultHttpFirewall;
import org.springframework.security.web.firewall.FirewalledRequest;
import org.springframework.security.web.firewall.HttpFirewall;
import org.springframework.security.web.firewall.RequestRejectedException;
public class CustomStrictHttpFirewall implements HttpFirewall {
private static final Set<String> ALLOW_ANY_HTTP_METHOD = Collections.unmodifiableSet(Collections.emptySet());
private static final String ENCODED_PERCENT = "%25";
private static final String PERCENT = "%";
private static final List<String> FORBIDDEN_ENCODED_PERIOD = Collections.unmodifiableList(Arrays.asList("%2e", "%2E"));
private static final List<String> FORBIDDEN_SEMICOLON = Collections.unmodifiableList(Arrays.asList(";", "%3b", "%3B"));
private static final List<String> FORBIDDEN_FORWARDSLASH = Collections.unmodifiableList(Arrays.asList("%2f", "%2F"));
private static final List<String> FORBIDDEN_BACKSLASH = Collections.unmodifiableList(Arrays.asList("\\", "%5c", "%5C"));
private Set<String> encodedUrlBlacklist = new HashSet<String>();
private Set<String> decodedUrlBlacklist = new HashSet<String>();
private Set<String> allowedHttpMethods = createDefaultAllowedHttpMethods();
public CustomStrictHttpFirewall() {
urlBlacklistsAddAll(FORBIDDEN_SEMICOLON);
urlBlacklistsAddAll(FORBIDDEN_FORWARDSLASH);
urlBlacklistsAddAll(FORBIDDEN_BACKSLASH);
this.encodedUrlBlacklist.add(ENCODED_PERCENT);
this.encodedUrlBlacklist.addAll(FORBIDDEN_ENCODED_PERIOD);
this.decodedUrlBlacklist.add(PERCENT);
}
public void setUnsafeAllowAnyHttpMethod(boolean unsafeAllowAnyHttpMethod) {
this.allowedHttpMethods = unsafeAllowAnyHttpMethod ? ALLOW_ANY_HTTP_METHOD : createDefaultAllowedHttpMethods();
}
public void setAllowedHttpMethods(Collection<String> allowedHttpMethods) {
if (allowedHttpMethods == null) {
throw new IllegalArgumentException("allowedHttpMethods cannot be null");
}
if (allowedHttpMethods == ALLOW_ANY_HTTP_METHOD) {
this.allowedHttpMethods = ALLOW_ANY_HTTP_METHOD;
} else {
this.allowedHttpMethods = new HashSet<>(allowedHttpMethods);
}
}
public void setAllowSemicolon(boolean allowSemicolon) {
if (allowSemicolon) {
urlBlacklistsRemoveAll(FORBIDDEN_SEMICOLON);
} else {
urlBlacklistsAddAll(FORBIDDEN_SEMICOLON);
}
}
public void setAllowUrlEncodedSlash(boolean allowUrlEncodedSlash) {
if (allowUrlEncodedSlash) {
urlBlacklistsRemoveAll(FORBIDDEN_FORWARDSLASH);
} else {
urlBlacklistsAddAll(FORBIDDEN_FORWARDSLASH);
}
}
public void setAllowUrlEncodedPeriod(boolean allowUrlEncodedPeriod) {
if (allowUrlEncodedPeriod) {
this.encodedUrlBlacklist.removeAll(FORBIDDEN_ENCODED_PERIOD);
} else {
this.encodedUrlBlacklist.addAll(FORBIDDEN_ENCODED_PERIOD);
}
}
public void setAllowBackSlash(boolean allowBackSlash) {
if (allowBackSlash) {
urlBlacklistsRemoveAll(FORBIDDEN_BACKSLASH);
} else {
urlBlacklistsAddAll(FORBIDDEN_BACKSLASH);
}
}
public void setAllowUrlEncodedPercent(boolean allowUrlEncodedPercent) {
if (allowUrlEncodedPercent) {
this.encodedUrlBlacklist.remove(ENCODED_PERCENT);
this.decodedUrlBlacklist.remove(PERCENT);
} else {
this.encodedUrlBlacklist.add(ENCODED_PERCENT);
this.decodedUrlBlacklist.add(PERCENT);
}
}
private void urlBlacklistsAddAll(Collection<String> values) {
this.encodedUrlBlacklist.addAll(values);
this.decodedUrlBlacklist.addAll(values);
}
private void urlBlacklistsRemoveAll(Collection<String> values) {
this.encodedUrlBlacklist.removeAll(values);
this.decodedUrlBlacklist.removeAll(values);
}
@Override
public FirewalledRequest getFirewalledRequest(HttpServletRequest request) throws RequestRejectedException {
rejectForbiddenHttpMethod(request);
rejectedBlacklistedUrls(request);
if (!isNormalized(request)) {
request.setAttribute("isNormalized", new RequestRejectedException("The request was rejected because the URL was not normalized."));
}
String requestUri = request.getRequestURI();
if (!containsOnlyPrintableAsciiCharacters(requestUri)) {
request.setAttribute("isNormalized", new RequestRejectedException("The requestURI was rejected because it can only contain printable ASCII characters."));
}
return new FirewalledRequest(request) {
@Override
public void reset() {
}
};
}
private void rejectForbiddenHttpMethod(HttpServletRequest request) {
if (this.allowedHttpMethods == ALLOW_ANY_HTTP_METHOD) {
return;
}
if (!this.allowedHttpMethods.contains(request.getMethod())) {
request.setAttribute("isNormalized", new RequestRejectedException("The request was rejected because the HTTP method \"" +
request.getMethod() +
"\" was not included within the whitelist " +
this.allowedHttpMethods));
}
}
private void rejectedBlacklistedUrls(HttpServletRequest request) {
for (String forbidden : this.encodedUrlBlacklist) {
if (encodedUrlContains(request, forbidden)) {
request.setAttribute("isNormalized", new RequestRejectedException("The request was rejected because the URL contained a potentially malicious String \"" + forbidden + "\""));
}
}
for (String forbidden : this.decodedUrlBlacklist) {
if (decodedUrlContains(request, forbidden)) {
request.setAttribute("isNormalized", new RequestRejectedException("The request was rejected because the URL contained a potentially malicious String \"" + forbidden + "\""));
}
}
}
@Override
public HttpServletResponse getFirewalledResponse(HttpServletResponse response) {
return new FirewalledResponse(response);
}
private static Set<String> createDefaultAllowedHttpMethods() {
Set<String> result = new HashSet<>();
result.add(HttpMethod.DELETE.name());
result.add(HttpMethod.GET.name());
result.add(HttpMethod.HEAD.name());
result.add(HttpMethod.OPTIONS.name());
result.add(HttpMethod.PATCH.name());
result.add(HttpMethod.POST.name());
result.add(HttpMethod.PUT.name());
return result;
}
private static boolean isNormalized(HttpServletRequest request) {
if (!isNormalized(request.getRequestURI())) {
return false;
}
if (!isNormalized(request.getContextPath())) {
return false;
}
if (!isNormalized(request.getServletPath())) {
return false;
}
if (!isNormalized(request.getPathInfo())) {
return false;
}
return true;
}
private static boolean encodedUrlContains(HttpServletRequest request, String value) {
if (valueContains(request.getContextPath(), value)) {
return true;
}
return valueContains(request.getRequestURI(), value);
}
private static boolean decodedUrlContains(HttpServletRequest request, String value) {
if (valueContains(request.getServletPath(), value)) {
return true;
}
if (valueContains(request.getPathInfo(), value)) {
return true;
}
return false;
}
private static boolean containsOnlyPrintableAsciiCharacters(String uri) {
int length = uri.length();
for (int i = 0; i < length; i++) {
char c = uri.charAt(i);
if (c < '\u0020' || c > '\u007e') {
return false;
}
}
return true;
}
private static boolean valueContains(String value, String contains) {
return value != null && value.contains(contains);
}
private static boolean isNormalized(String path) {
if (path == null) {
return true;
}
if (path.indexOf("//") > -1) {
return false;
}
for (int j = path.length(); j > 0;) {
int i = path.lastIndexOf('/', j - 1);
int gap = j - i;
if (gap == 2 && path.charAt(i + 1) == '.') {
// ".", "/./" or "/."
return false;
} else if (gap == 3 && path.charAt(i + 1) == '.' && path.charAt(i + 2) == '.') {
return false;
}
j = i;
}
return true;
}
}
STEP 2 : Create a FirewalledResponse class
package com.biz.brains.project.security.firewall;
import java.io.IOException;
import java.util.regex.Pattern;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
class FirewalledResponse extends HttpServletResponseWrapper {
private static final Pattern CR_OR_LF = Pattern.compile("\\r|\\n");
private static final String LOCATION_HEADER = "Location";
private static final String SET_COOKIE_HEADER = "Set-Cookie";
public FirewalledResponse(HttpServletResponse response) {
super(response);
}
@Override
public void sendRedirect(String location) throws IOException {
// TODO: implement pluggable validation, instead of simple blacklisting.
// SEC-1790. Prevent redirects containing CRLF
validateCrlf(LOCATION_HEADER, location);
super.sendRedirect(location);
}
@Override
public void setHeader(String name, String value) {
validateCrlf(name, value);
super.setHeader(name, value);
}
@Override
public void addHeader(String name, String value) {
validateCrlf(name, value);
super.addHeader(name, value);
}
@Override
public void addCookie(Cookie cookie) {
if (cookie != null) {
validateCrlf(SET_COOKIE_HEADER, cookie.getName());
validateCrlf(SET_COOKIE_HEADER, cookie.getValue());
validateCrlf(SET_COOKIE_HEADER, cookie.getPath());
validateCrlf(SET_COOKIE_HEADER, cookie.getDomain());
validateCrlf(SET_COOKIE_HEADER, cookie.getComment());
}
super.addCookie(cookie);
}
void validateCrlf(String name, String value) {
if (hasCrlf(name) || hasCrlf(value)) {
throw new IllegalArgumentException(
"Invalid characters (CR/LF) in header " + name);
}
}
private boolean hasCrlf(String value) {
return value != null && CR_OR_LF.matcher(value).find();
}
}
STEP 3: Create a custom Filter to suppress the RejectedException
package com.biz.brains.project.security.filter;
import java.io.IOException;
import java.util.Objects;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.security.web.firewall.RequestRejectedException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;
import lombok.extern.slf4j.Slf4j;
@Component
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RequestRejectedExceptionFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
try {
RequestRejectedException requestRejectedException=(RequestRejectedException) servletRequest.getAttribute("isNormalized");
if(Objects.nonNull(requestRejectedException)) {
throw requestRejectedException;
}else {
filterChain.doFilter(servletRequest, servletResponse);
}
} catch (RequestRejectedException requestRejectedException) {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
log
.error(
"request_rejected: remote={}, user_agent={}, request_url={}",
httpServletRequest.getRemoteHost(),
httpServletRequest.getHeader(HttpHeaders.USER_AGENT),
httpServletRequest.getRequestURL(),
requestRejectedException
);
httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
}
STEP 4: Add the custom filter to spring filter chain in security configuration
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(new RequestRejectedExceptionFilter(),
ChannelProcessingFilter.class);
}
Now using above fix, we can handle RequestRejectedException
with Error 404 page.
I had this problem when I used a inner class in Post parameters
[HttpPost]
public async Task Post([FromBody] Foo value)
{
}
Where Foo is
public class Foo
{
public IEnumerable<Bar> Bars {get;set;}
public class Bar
{
}
}
For those still not able to set JAVA_HOME from Android Studio installation, for me the path was actually not in C:\...\Android Studio\jre
but rather in the ...\Android Studio\jre\jre
.
Don't ask me why though.
I know that question is a bit old but
pipenv --venv
/Users/your_user_name/.local/share/virtualenvs/model-N-S4uBGU
rm -rf /Users/your_user_name/.local/share/virtualenvs/model-N-S4uBGU
I solved it by deleting "/.idea/libraries" from project. Thanks
Expanding a bit on Serhan C.'s answer...
According to the blog post How to Setup dotenv with Jest Testing - In-depth Explanation, you can include "dotenv/config"
directly in setupFiles
, without having to create and reference an external script that calls require("dotenv").config()
.
I.e., simply do
module.exports = {
setupFiles: ["dotenv/config"]
}
If someone is still trying how to resolve this error, I have done this like below.
const MongoClient = require('mongodb').MongoClient;
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'mytestingdb';
const retrieveCustomers = (db, callback)=>{
// Get the customers collection
const collection = db.collection('customers');
// Find some customers
collection.find({}).toArray((err, customers) =>{
if(err) throw err;
console.log("Found the following records");
console.log(customers)
callback(customers);
});
}
const retrieveCustomer = (db, callback)=>{
// Get the customers collection
const collection = db.collection('customers');
// Find some customers
collection.find({'name': 'mahendra'}).toArray((err, customers) =>{
if(err) throw err;
console.log("Found the following records");
console.log(customers)
callback(customers);
});
}
const insertCustomers = (db, callback)=> {
// Get the customers collection
const collection = db.collection('customers');
const dataArray = [{name : 'mahendra'}, {name :'divit'}, {name : 'aryan'} ];
// Insert some customers
collection.insertMany(dataArray, (err, result)=> {
if(err) throw err;
console.log("Inserted 3 customers into the collection");
callback(result);
});
}
// Use connect method to connect to the server
MongoClient.connect(url,{ useUnifiedTopology: true }, (err, client) => {
console.log("Connected successfully to server");
const db = client.db(dbName);
insertCustomers(db, ()=> {
retrieveCustomers(db, ()=> {
retrieveCustomer(db, ()=> {
client.close();
});
});
});
});
I had a similar issue from the console after building a Jar in Intellij. Using the Java configuration to update to a newer version (Windows -> Configure Java -> Update -> Update Now) didn't work and stuck at version 1.8 (Java 8).
To switch to a more recent version locally I had to install the Java 15 JDK from https://www.oracle.com/uk/java/technologies/javase-jdk15-downloads.html and add that to my Java runtime environment settings.
import { ParamMap, Router, ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute) {}
ngOnInit() {
console.log(this.route.snapshot.queryParamMap);
}
UPDATE
import { Router, RouterStateSnapshot } from '@angular/router';
export class LoginComponent {
constructor(private router: Router) {
const snapshot: RouterStateSnapshot = router.routerState.snapshot;
console.log(snapshot); // <-- hope it helps
}
}
Adding AngularFirestoreModule.enablePersistence()
in import section resolved my issue:
imports: [
BrowserModule, AngularFireModule,
AngularFireModule.initializeApp(config),
AngularFirestoreModule.enablePersistence()
]
My solution is similar to Payam's, except I am using
//older code
//postman.setGlobalVariable("currentDate", new Date().toLocaleDateString());
pm.globals.set("currentDate", new Date().toLocaleDateString());
If you hit the "3 dots" on the folder and click "Edit"
Then set Pre-Request Scripts for the all calls, so the global variable is always available.
If nothing works for you, you can specify the full path of your python environment setup by conda.
For me, I set up an environment called "testenv" using conda.
I searched all python environments using
whereis python | grep 'miniconda'
It returned a list of python environments. Then I ran my_python_file.py using the following command.
~/miniconda3/envs/testenv/bin/python3.8 my_python_file.py
You can do the same thing on windows too but looking up for python and conda python environments is a bit different.
I was facing the same issue, the funny thing was I had two projects opened on simultaneously, I have changed the wrong app.modules.ts files.
First, check that.
After that change add the following code to the app.module.ts file
import { HttpClientModule } from '@angular/common/http';
After that add the following to the imports array in the app.module.ts file
imports: [
HttpClientModule,....
],
Now you should be ok!
If you are using flutter,
Run this command flutter doctor --android-licenses
in my case I have used -
(Hyphen) in my script name in case of Jenkinsfile Library.
Got resolved after replacing Hyphen(-) with Underscore(_)
I guess the simplest way is by DI. An example of reaching into Controller.
// StartUp.cs
public void ConfigureServices(IServiceCollection services)
{
...
// for get appsettings from anywhere
services.AddSingleton(Configuration);
}
public class ContactUsController : Controller
{
readonly IConfiguration _configuration;
public ContactUsController(
IConfiguration configuration)
{
_configuration = configuration;
// sample:
var apiKey = _configuration.GetValue<string>("SendGrid:CAAO");
...
}
}
You can remove the entire line below:
.map((res: Response) => res.json());
No need to use the map method at all.
The reason why Python base environment is unable to import Tensorflow is that Anaconda does not store the tensorflow package in the base environment.
create a new separate environment in Anaconda dedicated to TensorFlow as follows:
conda create -n newenvt anaconda python=python_version
replace python_version by your python version
activate the new environment as follows:
activate newenvt
Then install tensorflow into the new environment (newenvt) as follows:
conda install tensorflow
Now you can check it by issuing the following python code and it will work fine.
import tensorflow
Just had this error, solved by downloading the Android SDK Command-line Tools (latest)
on Android Studio, under settings > Appearance & Behavior > System Settings > Android SDK > SDK Tools
and re-running flutter doctor --android-licenses
You can add the configuration name as the ASPNETCORE_ENVIRONMENT
in the launchSettings.json
as below
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:58446/",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"environmentVariables": {
ASPNETCORE_ENVIRONMENT": "$(Configuration)"
}
}
}
I faced the same problem when I was doing it on windows 10. The problem could be that the path is not defined for manage.py in the environment variables. I did the following steps and it worked out for me!
I really hope it works!
I had same problems with Sublime Text.
I came up with following solution: I just edited
tsconfig.json
in the root of Angular workspace to include my freshly created application.
{
"files": [],
"references": [
{
"path": "./projects/client/tsconfig.app.json"
},
{
"path": "./projects/client/tsconfig.spec.json"
},
{
"path": "./projects/vehicle-market/tsconfig.app.json"
},
{
"path": "./projects/vehicle-market/tsconfig.spec.json"
},
{
"path": "./projects/mobile-de-lib/tsconfig.lib.json"
},
{
"path": "./projects/mobile-de-lib/tsconfig.spec.json"
}
]
}
A quick solution from the internet search was npm config set strict-ssl false
, luckily it worked. But as a part of my work environment, I am restricted to set the strict-ssl flag to false.
Later I found a safe and working solution,
npm config set registry http://registry.npmjs.org/
this worked perfectly and I got a success message Happy Hacking!
by not setting the strict-ssl flag to false.
I had node 15.x.x
, and "node-sass": "^4.11.0"
.
I saw in the release notes from node-sass
and saw the node higest version compatible with node-sass 4.11.0 was 11, so I uninstalled node and reinstall 11.15.0 version (I'm working with Windows).
Check node-sass releases.
(this is what you should see in the node-sass releases.)
Hope that helps and sorry for my english :)
In my case, I don't put namespace_name in the url tag ex: {% url 'url_name or pattern name' %}.
you have to specify the namespace_name like: {% url 'namespace_name:url_name or pattern name' %}.
Explanation: In project urls.py path('', include('blog.urls',namespace='blog')),
and in app's urls.py you have to specify the app_name. like app_name = 'blog'
. namespace_name is the app_name.
You should set it with C:\Program Files\Java\jdk1.8.0_12
.
\bin
is not required.
If you are looking inside dockerfile while creating image, add this line:
RUN apk add --update yourPackageName
I ran into the same situation where commands such as git diff origin
or git diff origin master
produced the error reported in the question, namely Fatal: ambiguous argument...
To resolve the situation, I ran the command
git symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/master
to set refs/remotes/origin/HEAD to point to the origin/master branch.
Before running this command, the output of git branch -a
was:
* master
remotes/origin/master
After running the command, the error no longer happened and the output of git branch -a
was:
* master
remotes/origin/HEAD -> origin/master
remotes/origin/master
(Other answers have already identified that the source of the error is HEAD not being set for origin. But I thought it helpful to provide a command which may be used to fix the error in question, although it may be obvious to some users.)
Additional information:
For anybody inclined to experiment and go back and forth between setting and unsetting refs/remotes/origin/HEAD, here are some examples.
To unset:
git remote set-head origin --delete
To set:
(additional ways, besides the way shown at the start of this answer)
git remote set-head origin master
to set origin/head explicitly
OR
git remote set-head origin --auto
to query the remote and automatically set origin/HEAD to the remote's current branch.
References:
git remote --help
see set-head descriptiongit symbolic-ref --help
The problem is the import of ProjectsListComponent
in your ProjectsModule
. You should not import that, but add it to the export array, if you want to use it outside of your ProjectsModule
.
Other issues are your project routes. You should add these to an exportable variable, otherwise it's not AOT compatible. And you should -never- import the BrowserModule
anywhere else but in your AppModule
. Use the CommonModule
to get access to the *ngIf, *ngFor...etc
directives:
@NgModule({
declarations: [
ProjectsListComponent
],
imports: [
CommonModule,
RouterModule.forChild(ProjectRoutes)
],
exports: [
ProjectsListComponent
]
})
export class ProjectsModule {}
project.routes.ts
export const ProjectRoutes: Routes = [
{ path: 'projects', component: ProjectsListComponent }
]
I ran into the same error.
NAME READY STATUS RESTARTS AGE pod/webapp 0/1 CrashLoopBackOff 5 47h
My problem was that I was trying to run two different pods with the same metadata name.
kind: Pod metadata: name: webapp labels: ...
To find all the names of your pods run: kubectl get pods
NAME READY STATUS RESTARTS AGE webapp 1/1 Running 15 47h
then I changed the conflicting pod name and everything worked just fine.
NAME READY STATUS RESTARTS AGE webapp 1/1 Running 17 2d webapp-release-0-5 1/1 Running 0 13m
The SETX
command does not modify the current environment.
If you run the following batch file:
setx AAA aaa
echo AAA=%AAA%
It will print
AAA=
So your batch file is wrong. You have to use set
:
set AAA=aaa
See What is the difference between SETX and SET in environment variables in Windows.
Although you were offered a good solution by others I think it is helpful to point out what is really happening. As per the Anaconda 4.4 changelog, https://docs.anaconda.com/anaconda/reference/release-notes/#what-s-new-in-anaconda-4-4:
On Windows, the PATH environment variable is no longer changed by default, as this can cause trouble with other software. The recommended approach is to instead use Anaconda Navigator or the Anaconda Command Prompt (located in the Start Menu under “Anaconda”) when you wish to use Anaconda software.
(Note: recent Win 10 does not assume you have privileges to install or update. If the command fails, right-click on the Anaconda Command Prompt, choose "More", chose "Run as administrator")
This is a change from previous installations. It is suggested to use Navigator or the Anaconda Prompt although you can always add it to your PATH as well. During the install the box to add Anaconda to the PATH is now unchecked but you can select it.
df.to_html()
has a columns parameter.
Just pass the columns into the to_html()
method.
df.to_html(columns=['A','B','C','D','E','F','G'])
You can try this it will help for you.You can't get path from WhatsApp directly.If you need an file path first copy file and send new file path. Using the code below
public static String getFilePathFromURI(Context context, Uri contentUri) {
String fileName = getFileName(contentUri);
if (!TextUtils.isEmpty(fileName)) {
File copyFile = new File(TEMP_DIR_PATH + fileName+".jpg");
copy(context, contentUri, copyFile);
return copyFile.getAbsolutePath();
}
return null;
}
public static String getFileName(Uri uri) {
if (uri == null) return null;
String fileName = null;
String path = uri.getPath();
int cut = path.lastIndexOf('/');
if (cut != -1) {
fileName = path.substring(cut + 1);
}
return fileName;
}
public static void copy(Context context, Uri srcUri, File dstFile) {
try {
InputStream inputStream = context.getContentResolver().openInputStream(srcUri);
if (inputStream == null) return;
OutputStream outputStream = new FileOutputStream(dstFile);
IOUtils.copy(inputStream, outputStream);
inputStream.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
Then IOUtils class is like below
public class IOUtils {
private static final int BUFFER_SIZE = 1024 * 2;
private IOUtils() {
// Utility class.
}
public static int copy(InputStream input, OutputStream output) throws Exception, IOException {
byte[] buffer = new byte[BUFFER_SIZE];
BufferedInputStream in = new BufferedInputStream(input, BUFFER_SIZE);
BufferedOutputStream out = new BufferedOutputStream(output, BUFFER_SIZE);
int count = 0, n = 0;
try {
while ((n = in.read(buffer, 0, BUFFER_SIZE)) != -1) {
out.write(buffer, 0, n);
count += n;
}
out.flush();
} finally {
try {
out.close();
} catch (IOException e) {
Log.e(e.getMessage(), e.toString());
}
try {
in.close();
} catch (IOException e) {
Log.e(e.getMessage(), e.toString());
}
}
return count;
}
}
You can change location of legend using loc argument. https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend
import matplotlib.pyplot as plt
plt.subplot(211)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend above this subplot, expanding itself to
# fully use the given bounding box.
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
ncol=2, mode="expand", borderaxespad=0.)
plt.subplot(223)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend to the right of this smaller subplot.
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
Because you have a very simple CORS policy (Allow all requests from XXX domain), you don't need to make it so complicated. Try doing the following first (A very basic implementation of CORS).
If you haven't already, install the CORS nuget package.
Install-Package Microsoft.AspNetCore.Cors
In the ConfigureServices method of your startup.cs, add the CORS services.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(); // Make sure you call this previous to AddMvc
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
Then in your Configure method of your startup.cs, add the following :
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// Make sure you call this before calling app.UseMvc()
app.UseCors(
options => options.WithOrigins("http://example.com").AllowAnyMethod()
);
app.UseMvc();
}
Now give it a go. Policies are for when you want different policies for different actions (e.g. different hosts or different headers). For your simple example you really don't need it. Start with this simple example and tweak as you need to from there.
Further reading : http://dotnetcoretutorials.com/2017/01/03/enabling-cors-asp-net-core/
Update: Incredibly frustrating, but the Google redirect of the maven.google.com
repo seems to mess with loading the resources. If you instead set your repository to
maven { url 'https://dl.google.com/dl/android/maven2' }
the files will resolve. You can prove this out by attempting to get the fully qualified resource at https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/3.0.0-alpha1/gradle-3.0.0-alpha1.pom
3.0.0 Alpha
This is because currently the gradle:3.0.0-alpha1
is only being served via the new 'https://maven.google.com'
repository, but the site currently 404s at that location otherwise, being a public directory, you'd see a tree listing of all the files available by simply navigating to that location in your browser. When they resolve their outage, your CI build should pass immediately.
You can import database afterwards:
docker exec -i mysql-container mysql -uuser -ppassword name_db < data.sql
You shouldn't use ${varName}
when you're outside of strings, you should just use varName
. Inside strings you use it like this; echo "this is a string ${someVariable}";
. Infact you can place an general java expression inside of ${...}
; echo "this is a string ${func(arg1, arg2)}
.
run gradle assembleDebug --scan
in Android studio Terminal, in my case I removed an element in XML and forgotten to remove it from code, but the compiler couldn't compile and show Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details
to me.
Hello React Developers,
Instead of doing this
disableHostCheck: true,
in webpackDevServer.config.js. You can easily solve 'invalid host headers' error by adding a .env file to you project, add the variables HOST=0.0.0.0 and DANGEROUSLY_DISABLE_HOST_CHECK=true in .env file. If you want to make changes in webpackDevServer.config.js, you need to extract the react-scripts by using 'npm run eject' which is not recommended to do it. So the better solution is adding above mentioned variables in .env file of your project.
Happy Coding :)
go to files-> preference-> settings-> and search pylint and we got some few options and uncheck the option 'whether to lint python files' from 'python Linting:Enabled'.
The solution...services and rxjs...event emitters and property binding both use rxjs..you are better of implementing it your self, more control, easier to debug. Remember that event emitters are using rxjs. Simply, create a service and within an observable, have each component subscribe to tha observer and either pass new value or cosume value as needed
As I was not able to solve my problem by suggested ways, I will share how I fixed it.
First of all, even if I was able to activate an environment, the corresponding environment folder was not present in C:\ProgramData\Anaconda3\envs
directory.
So I created a new anaconda environment using Anaconda prompt,
a new folder named same as your given environment name will be created in the envs
folder.
Next, I activated that environment in Anaconda prompt.
Installed python with conda install python
command.
Then on anaconda navigator, selected the newly created environment in the 'Applications on' menu. Launched vscode through Anaconda navigator.
Now as suggested by other answers, in vscode, opened command palette with Ctrl + Shift + P
keyboard shortcut.
Searched and selected Python: Select Interpreter
If the interpreter with newly created environment isn't listed out there, select Enter Interpreter Path
and choose the newly created python.exe which is located similar to C:\ProgramData\Anaconda3\envs\<your-new-env>\
.
So the total path will look like C:\ProgramData\Anaconda3\envs\<your-nev-env>\python.exe
Next time onwards the interpreter will be automatically listed among other interpreters.
Now you might see your selected conda environment at bottom left side in vscode.
I believe a short video showing all the details if you have Anaconda is the following for mac (it is very similar to windows users as well) just open Anaconda navigator and everything is just the same (almost!)
https://www.youtube.com/watch?v=gDzAm25CORk
Then go to jupyter notebook and code
!pip install tensorflow
Then
import tensorflow as tf
It work for me! :)
I guess you are using an old version of hibernate. You can download the latest version, 5.2, from here.
As the error message states, the method used to get the F score is from the "Classification" part of sklearn - thus the talking about "labels".
Do you have a regression problem? Sklearn provides a "F score" method for regression under the "feature selection" group: http://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.f_regression.html
In case you do have a classification problem, @Shovalt's answer seems correct to me.
You can create a .timer
systemd unit file to control the execution of your .service
unit file.
So for example, to wait for 1 minute after boot-up before starting your foo.service
, create a foo.timer
file in the same directory with the contents:
[Timer]
OnBootSec=1min
It is important that the service is disabled (so it doesn't start at boot), and the timer enabled, for all this to work (thanks to user tride for this):
systemctl disable foo.service
systemctl enable foo.timer
You can find quite a few more options and all information needed here: https://wiki.archlinux.org/index.php/Systemd/Timers
Given this .env
file:
DB_NAME=foo
DB_USER=bar
DB_PASSWORD=baz
And this mongo-init.sh
file:
mongo --eval "db.auth('$MONGO_INITDB_ROOT_USERNAME', '$MONGO_INITDB_ROOT_PASSWORD'); db = db.getSiblingDB('$DB_NAME'); db.createUser({ user: '$DB_USER', pwd: '$DB_PASSWORD', roles: [{ role: 'readWrite', db: '$DB_NAME' }] });"
This docker-compose.yml
will create the admin database and admin user, authenticate as the admin user, then create the real database and add the real user:
version: '3'
services:
# app:
# build: .
# env_file: .env
# environment:
# DB_HOST: 'mongodb://mongodb'
mongodb:
image: mongo:4
environment:
MONGO_INITDB_ROOT_USERNAME: admin-user
MONGO_INITDB_ROOT_PASSWORD: admin-password
DB_NAME: $DB_NAME
DB_USER: $DB_USER
DB_PASSWORD: $DB_PASSWORD
ports:
- 27017:27017
volumes:
- db-data:/data/db
- ./mongo-init.sh:/docker-entrypoint-initdb.d/mongo-init.sh
volumes:
db-data:
I was able to figure out this using a PyCharm plugin called EnvFile. This plugin, basically allows setting environment variables to run configurations from one or multiple files.
The installation is pretty simple:
Preferences > Plugins > Browse repositories... > Search for "Env File" > Install Plugin.
Then, I created a file, in my project root, called environment.env
which contains:
DATABASE_URL=postgres://127.0.0.1:5432/my_db_name
DEBUG=1
Then I went to Run->Edit Configurations, and I followed the steps in the next image:
In 3, I chose the file environment.env
, and then I could just click the play button in PyCharm, and everything worked like a charm.
(Basically what @user3464070 already said)
For Mac:
cd ~/Library/Android/sdk
# download latest tools
curl -O https://dl.google.com/android/repository/tools_r25.2.3-macosx.zip
# overwrite existing tools folder without prompting
unzip -o tools_r25.2.3-macosx.zip
# clean up
rm tools_r25.2.3-macosx.zip
The error is generated by using a later version of Django with an old python, probably of version 2.x.
To fix this I had to delete the .venv
folder and recreate it with virtualenv -p python3 .venv && source .venv/bin/activate
The error is due to that you're only allowed to use pipeline steps inside the steps
directive. One workaround that I know is to use the script
step and wrap arbitrary pipeline script inside of it and save the result in the environment variable so that it can be used later.
So in your case:
pipeline {
agent any
stages {
stage("foo") {
steps {
script {
env.FILENAME = readFile 'output.txt'
}
echo "${env.FILENAME}"
}
}
}
}
if the project is not a big ,
1- change the name of folder project
2- make a new project with the same project (before renaming)
3- add existing files from the old project to the new project (totally same , same folders , same names , ...)
4- open the the new project file (as xml ) and the old project
5- copy the new project file (xml content ) and paste it in the old project file
6- delete the old project
7- rename the old folder project to old name
deploy:
resources:
limits:
cpus: '0.001'
memory: 50M
reservations:
cpus: '0.0001'
memory: 20M
More: https://docs.docker.com/compose/compose-file/compose-file-v3/#resources
In you specific case:
version: "3"
services:
node:
image: USER/Your-Pre-Built-Image
environment:
- VIRTUAL_HOST=localhost
volumes:
- logs:/app/out/
command: ["npm","start"]
cap_drop:
- NET_ADMIN
- SYS_ADMIN
deploy:
resources:
limits:
cpus: '0.001'
memory: 50M
reservations:
cpus: '0.0001'
memory: 20M
volumes:
- logs
networks:
default:
driver: overlay
Note:
Also Note: Networks in Swarm mode do not bridge. If you would like to connect internally only, you have to attach to the network. You can 1) specify an external network within an other compose file, or have to create the network with --attachable parameter (docker network create -d overlay My-Network --attachable) Otherwise you have to publish the port like this:
ports:
- 80:80
Comments work fine in any of the usual Java/Groovy forms, but you can't currently use groovydoc
to process your Jenkinsfile
(s).
First, groovydoc
chokes on files without extensions with the wonderful error
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.codehaus.groovy.tools.GroovyStarter.rootLoader(GroovyStarter.java:109)
at org.codehaus.groovy.tools.GroovyStarter.main(GroovyStarter.java:131)
Caused by: java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1967)
at org.codehaus.groovy.tools.groovydoc.SimpleGroovyClassDocAssembler.<init>(SimpleGroovyClassDocAssembler.java:67)
at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.parseGroovy(GroovyRootDocBuilder.java:131)
at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.getClassDocsFromSingleSource(GroovyRootDocBuilder.java:83)
at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.processFile(GroovyRootDocBuilder.java:213)
at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.buildTree(GroovyRootDocBuilder.java:168)
at org.codehaus.groovy.tools.groovydoc.GroovyDocTool.add(GroovyDocTool.java:82)
at org.codehaus.groovy.tools.groovydoc.GroovyDocTool$add.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
at org.codehaus.groovy.tools.groovydoc.Main.execute(Main.groovy:214)
at org.codehaus.groovy.tools.groovydoc.Main.main(Main.groovy:180)
... 6 more
... and second, as far as I can tell Javadoc-style commments at the start of a groovy
script are ignored. So even if you copy/rename your Jenkinsfile
to Jenkinsfile.groovy
, you won't get much useful output.
I want to be able to use a
/**
* Document my Jenkinsfile's overall purpose here
*/
comment at the start of my Jenkinsfile. No such luck (yet).
groovydoc
will process classes and methods defined in your Jenkinsfile
if you pass -private
to the command, though.
I had been suffering from a similar issue. I was trying to import my config file to my container so that I can fix it every time I need without re-building the image.
I mean I thought the below command would map $(pwd)/config.py
from Docker host to /root/app/config.py
into the container as a file.
docker run -v $(pwd)/config.py:/root/app/config.py my_docker_image
However, it always created a directory named config.py
, not a file.
while looking for clue, I found the reason(from here)
If you use -v or --volume to bind-mount a file or directory that does not yet exist on the Docker host, -v will create the endpoint for you. It is always created as a directory.
Therefore, it is always created as a directory because my docker host does not have $(pwd)/config.py
.
Even if I create config.py in docker host.
$(pwd)/config.py
just overwirte /root/app/config.py
not exporting /root/app/config.py
.
conda create --name new_name --copy --clone old_name
is better
I use conda create --name new_name --clone old_name
which is without --copy
but encountered pip breaks...
the following url may help Installing tensorflow in cloned conda environment breaks conda environment it was cloned from
I know this is an old thread, but there is a particular case when this may happen:
If you are using AWS api gateway coupled with a VPC link, and if the Network Load Balancer has proxy protocol v2 enabled, a 400 Bad Request will happen as well.
Took me the whole afternoon to figure it out, so if it may help someone I'd be glad :)
I happened to encounter a similar kind of issue after setting up local internal JFrog Docker Private Registry on Amazon Linux.
THE followings I did to solve the issue:
Added "--insecure-registry xx.xx.xx.xx:8081" by modifying the OPTIONS variable in the /etc/sysconfig/docker file:
OPTIONS="--default-ulimit nofile=1024:40961 --insecure-registry hostname:8081"
Then restarted the docker.
I was then able to login to the local docker registry using:
docker login -u admin -p password hostname:8081
Webpack's configuration file has changed over the years (likely with each major release). The answer to the question:
Why do I get this error
Invalid configuration object. Webpack has been initialised using a
configuration object that does not match the API schema
is because the configuration file doesn't match the version of webpack being used.
The accepted answer doesn't state this and other answers allude to this but don't state it clearly npm install [email protected], Just change from "loaders" to "rules" in "webpack.config.js", and this. So I decide to provide my answer to this question.
Uninstalling and re-installing webpack, or using the global version of webpack will not fix this problem. Using the correct version of webpack for the configuration file being used is what is important.
If this problem was fixed when using a global version it likely means that your global version was "old" and the webpack.config.js file format your using is "old" so they match and viola things now work. I'm all for things working, but want readers to know why they worked.
Whenever you get a webpack configuration that you hope is going to solve your problem ... ask yourself what version of webpack the configuration is for.
There are a lot of good resources for learning webpack. Some are:
Webpack (v3?) by Example - takes a bite-sized approach for learning webpack, picking a problem and then showing how to solve it in webpack. I like this approach. Unfortunately it is not teaching webpack 4 but is still good.
Setting up Webpack4, Babel and React from scratch, revisited - This is specific to React but good if you want to learn many of the things that are required to create a react single page app.
Webpack (v3) — The Confusing Parts - Good and covers a lot of ground. It is dated Apr 10, 2016 and doesn't cover webpack4 but many of the teaching points are valid or useful to learn.
There are a lot more good resources for learning webpack4 by example, please add comments if you know of others. Hopefully, future webpack articles will state the versions being used/explained.
I added @Component
annotation from import org.springframework.stereotype.Component
and the problem was solved.
You can access the same environment variables from groovy using the same names (e.g. JOB_NAME
or env.JOB_NAME
).
From the documentation:
Environment variables are accessible from Groovy code as env.VARNAME or simply as VARNAME. You can write to such properties as well (only using the env. prefix):
env.MYTOOL_VERSION = '1.33' node { sh '/usr/local/mytool-$MYTOOL_VERSION/bin/start' }
These definitions will also be available via the REST API during the build or after its completion, and from upstream Pipeline builds using the build step.
For the rest of the documentation, click the "Pipeline Syntax" link from any Pipeline job
I can't tell you what's best, but a tool I have used with success in the past was cx_Freeze. They recently updated (on Jan. 7, '17) to version 5.0.1 and it supports Python 3.6.
Here's the pypi https://pypi.python.org/pypi/cx_Freeze
The documentation shows that there is more than one way to do it, depending on your needs. http://cx-freeze.readthedocs.io/en/latest/overview.html
I have not tried it out yet, so I'm going to point to a post where the simple way of doing it was discussed. Some things may or may not have changed though.
This is how we can set it in run-time:
public class Program
{
public static void Main(string[] args)
{
Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development");
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
You were looking for help on installations with pip. You can find it with the following command:
pip install --help
Running pip install -e /path/to/package
installs the package in a way, that you can edit the package, and when a new import call looks for it, it will import the edited package code. This can be very useful for package development.
I can't find anything in the conda
specs which allow you to export an environment file without the prefix: ...
line. However, as Alex pointed out in the comments, conda doesn't seem to care about the prefix line when creating an environment from file.
With that in mind, if you want the other user to have no knowledge of your default install path, you can remove the prefix line with grep
before writing to environment.yml
.
conda env export | grep -v "^prefix: " > environment.yml
Either way, the other user then runs:
conda env create -f environment.yml
and the environment will get installed in their default conda environment path.
If you want to specify a different install path than the default for your system (not related to 'prefix' in the environment.yml), just use the -p
flag followed by the required path.
conda env create -f environment.yml -p /home/user/anaconda3/envs/env_name
Note that Conda recommends creating the environment.yml
by hand, which is especially important if you are wanting to share your environment across platforms (Windows/Linux/Mac). In this case, you can just leave out the prefix
line.
The following three steps are used to fix Running Scripts is disabled on this System error
Step1 : To fix this kind of problem, we have to start power shell in administrator mode.
Step2 : Type the following command set-ExecutionPolicy RemoteSigned Step3: Press Y for your Confirmation.
Visit the following for more information https://youtu.be/J_596H-sWsk
If you ONLY want to have a conda installation. Just remove all of the other python paths from your PATH variable.
Leaving only:
C:\ProgramData\Anaconda3
C:\ProgramData\Anaconda3\Scripts
C:\ProgramData\Anaconda3\Library\bin
This allows you to just use pip install *
and it will install straight into your conda installation.
You can find using CLI ng --version
As I am using
angular-cli: 1.0.0-beta.28.3
node: 6.10.1
os: darwin x64
If you would like to mount a particular host directory (/disk1/prometheus-data
in the following example) as a volume in the volumes
section of the Docker Compose YAML file, you can do it as below, e.g.:
version: '3'
services:
prometheus:
image: prom/prometheus
volumes:
- prometheus-data:/prometheus
volumes:
prometheus-data:
driver: local
driver_opts:
o: bind
type: none
device: /disk1/prometheus-data
By the way, in prometheus's Dockerfile, You may find the VOLUME
instruction as below, which marks it as holding externally mounted volumes from native host, etc. (Note however: this instruction is not a must though to mount a volume into a container.):
Dockerfile
...
VOLUME ["/prometheus"]
...
Refs:
You can only install a language pack at install time in VS 2017 RC. To install RC with a different language:
You can have multiple instances of VS 2017 side by side so this shouldn't interfere with your other installation.
Disclosure: I work on Visual Studio at Microsoft.
Use the first; it directly tries to check if something is defined in environ
. Though the second form works equally well, it's lacking semantically since you get a value back if it exists and only use it for a comparison.
You're trying to see if something is present in environ
, why would you get just to compare it and then toss it away?
That's exactly what getenv
does:
Get an environment variable, return
None
if it doesn't exist. The optional second argument can specify an alternate default.
(this also means your check could just be if getenv("FOO")
)
you don't want to get it, you want to check for it's existence.
Either way, getenv
is just a wrapper around environ.get
but you don't see people checking for membership in mappings with:
from os import environ
if environ.get('Foo') is not None:
To summarize, use:
if "FOO" in os.environ:
pass
if you just want to check for existence, while, use getenv("FOO")
if you actually want to do something with the value you might get.
As per keras tutorial, you can simply use the same tf.device
scope as in regular tensorflow:
with tf.device('/gpu:0'):
x = tf.placeholder(tf.float32, shape=(None, 20, 64))
y = LSTM(32)(x) # all ops in the LSTM layer will live on GPU:0
with tf.device('/cpu:0'):
x = tf.placeholder(tf.float32, shape=(None, 20, 64))
y = LSTM(32)(x) # all ops in the LSTM layer will live on CPU:0
For me this setting was working.
In my windows 8.1 the path for php7 is
C:\user\test\tools\php7\php.exe
settings.json
{
"php.executablePath":"/user/test/tools/php7/php.exe",
"php.validate.executablePath": "/user/test/tools/php7/php.exe"
}
Angular only points to src/assets
folder, nothing else is public to access via url so you should use full path
this.fullImagePath = '/assets/images/therealdealportfoliohero.jpg'
Or
this.fullImagePath = 'assets/images/therealdealportfoliohero.jpg'
This will only work if the base href tag is set with /
You can also add other folders for data in angular/cli
.
All you need to modify is angular-cli.json
"assets": [
"assets",
"img",
"favicon.ico",
".htaccess"
]
Note in edit : Dist command will try to find all attachments from assets so it is also important to keep the images and any files you want to access via url inside assets, like mock json data files should also be in assets.
If you use JDK 1.8.0_201 or latest try it with older JDK.
I have same issue with JDK1.8.0_201, however it works with JDK1.8.0_101 without any code change.
These need to go as different commands e.g.:
NAME=sam; echo "$NAME"
NAME=sam && echo "$NAME"
The expansion $NAME
to empty string is done by the shell earlier, before running echo
, so at the time the NAME
variable is passed to the echo
command's environment, the expansion is already done (to null string).
To get the same result in one command:
NAME=sam printenv NAME
There is no python3.exe file, that is why it fails.
Try:
py
instead.
py is just a launcher for python.exe. If you have more than one python versions installed on your machine (2.x, 3.x) you can specify what version of python to launch by
py -2 or py -3
Try add this command in your build.gradle
So for running configure that shape:
A delarative way to do that (In fact, a minor tweek to @Compito's original answer):
spring.profiles.active=test
in test/resources/application-default.properties
.test/resources/application-test.properties
for tests and override only the properties you need.You can also set the GPU in the command line so that you don't need to hard-code the device into your script (which may fail on systems without multiple GPUs). Say you want to run your script on GPU number 5, you can type the following on the command line and it will run your script just this once on GPU#5:
CUDA_VISIBLE_DEVICES=5, python test_script.py
This worked for me in windows 10 and latest solution :
1) Go inside that conda environment ( activate your_env_name )
2) conda install -n your_env_name ipykernel
3) python -m ipykernel install --user --name build_central --display-name "your_env_name"
(NOTE : Include the quotes around "your_env_name", in step 3)
I was facing some difficulties with an environment variable that is with custom name (not with container name /port convention for KAPACITOR_BASE_URL and KAPACITOR_ALERTS_ENDPOINT). If we give service name in this case it wouldn't resolve the ip as
KAPACITOR_BASE_URL: http://kapacitor:9092
In above http://[**kapacitor**]:9092
would not resolve to http://172.20.0.2:9092
I resolved the static IPs issues using subnetting configurations.
version: "3.3"
networks:
frontend:
ipam:
config:
- subnet: 172.20.0.0/24
services:
db:
image: postgres:9.4.4
networks:
frontend:
ipv4_address: 172.20.0.5
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
redis:
image: redis:latest
networks:
frontend:
ipv4_address: 172.20.0.6
ports:
- "6379"
influxdb:
image: influxdb:latest
ports:
- "8086:8086"
- "8083:8083"
volumes:
- ../influxdb/influxdb.conf:/etc/influxdb/influxdb.conf
- ../influxdb/inxdb:/var/lib/influxdb
networks:
frontend:
ipv4_address: 172.20.0.4
environment:
INFLUXDB_HTTP_AUTH_ENABLED: "false"
INFLUXDB_ADMIN_ENABLED: "true"
INFLUXDB_USERNAME: "db_username"
INFLUXDB_PASSWORD: "12345678"
INFLUXDB_DB: db_customers
kapacitor:
image: kapacitor:latest
ports:
- "9092:9092"
networks:
frontend:
ipv4_address: 172.20.0.2
depends_on:
- influxdb
volumes:
- ../kapacitor/kapacitor.conf:/etc/kapacitor/kapacitor.conf
- ../kapacitor/kapdb:/var/lib/kapacitor
environment:
KAPACITOR_INFLUXDB_0_URLS_0: http://influxdb:8086
web:
build: .
environment:
RAILS_ENV: $RAILS_ENV
command: bundle exec rails s -b 0.0.0.0
ports:
- "3000:3000"
networks:
frontend:
ipv4_address: 172.20.0.3
links:
- db
- kapacitor
depends_on:
- db
volumes:
- .:/var/app/current
environment:
DATABASE_URL: postgres://postgres@db
DATABASE_USERNAME: postgres
DATABASE_PASSWORD: postgres
INFLUX_URL: http://influxdb:8086
INFLUX_USER: db_username
INFLUX_PWD: 12345678
KAPACITOR_BASE_URL: http://172.20.0.2:9092
KAPACITOR_ALERTS_ENDPOINT: http://172.20.0.3:3000
volumes:
postgres_data:
NEW_VAR=""
if [[ ${ENV_VAR} && ${ENV_VAR-x} ]]; then
NEW_VAR=${ENV_VAR}
else
NEW_VAR="new value"
fi
I looked into the options pattern sample and saw this:
public class Startup
{
public Startup(IConfiguration config)
{
// Configuration from appsettings.json has already been loaded by
// CreateDefaultBuilder on WebHost in Program.cs. Use DI to load
// the configuration into the Configuration property.
Configuration = config;
}
...
}
When adding Iconfiguration in the constructor of my class, I could access the configuration options through DI.
Example:
public class MyClass{
private Iconfiguration _config;
public MyClass(Iconfiguration config){
_config = config;
}
... // access _config["myAppSetting"] anywhere in this class
}
Actually this is the path and you should mention a valid path for this to work. If your data directory is in current directory then instead of my-data
you should mention ./my-data
, otherwise it will give you that error in mysql
and mariadb
also.
volumes:
./my-data:/var/lib/mysql
I had similar issue when connecting to RDS Oracle even when client and server were both set to TLSv1.2 the certs was right and java was 1.8.0_141 So Finally I had to apply patch at Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files
After applying the patch the issue went away and connection went fine.
In my case I was using the Test class from wrong package.
when I replaced import org.junit.Test;
with import org.junit.jupiter.api.Test;
it worked.
You can use .filter() or .find(). One difference that filter
will iterate over all items and returns any which passes the condition as array while find
will return the first matched item and break the iteration.
Example
var questions = [_x000D_
{id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},_x000D_
{id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},_x000D_
{id: 3, question: "Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},_x000D_
{id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},_x000D_
{id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},_x000D_
{id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},_x000D_
{id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},_x000D_
{id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},_x000D_
{id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},_x000D_
{id: 10, question: "Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},_x000D_
{id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},_x000D_
{id: 12, question: "Do you feel a sense of peace and contentment in your home? ", category: "Home Environment", subs: []},_x000D_
{id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},_x000D_
{id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},_x000D_
{id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}_x000D_
];_x000D_
_x000D_
function getDimensionsByFilter(id){_x000D_
return questions.filter(x => x.id === id);_x000D_
}_x000D_
_x000D_
function getDimensionsByFind(id){_x000D_
return questions.find(x => x.id === id);_x000D_
}_x000D_
_x000D_
var test = getDimensionsByFilter(10);_x000D_
console.log(test);_x000D_
_x000D_
test = getDimensionsByFind(10);_x000D_
console.log(test);
_x000D_
if working in MS windows, you can use Anaconda navigator. click on the environment, in the drop-down box, it's "installed" by default. You can select "updatable" and start from there
Ok, it's developed finally and now you are able to use Ctrl+Shift+C/V to Copy/Paste as of Windows 10 Insider build #17643.
You'll need to enable the "Use Ctrl+Shift+C/V as Copy/Paste" option in the Console "Options" properties page:
referenced in blogs.msdn.microsoft.com/
If you have tried installing via the official docker-compose page, where you need to download the binary using curl:
curl -L https://github.com/docker/compose/releases/download/1.8.0/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose
Then do not forget to add executable flag to the binary:
chmod +x /usr/local/bin/docker-compose
If docker-compose is installed using python-pip
sudo apt-get -y install python-pip
sudo pip install docker-compose
try using pip show --files docker-compose
to see where it is installed.
If docker-compose is installed in user path, then try:
sudo "PATH=$PATH" docker-compose
As I see from your updated post, docker-compose is installed in user path /home/user/.local/bin
and if this path is not in your local path $PATH
, then try:
sudo "PATH=$PATH:/home/user/.local/bin" docker-compose
You probably haven't run the Android SDK in forever. So you probably just have to update it. If you open the Android Studio Software it'll probably let you know that and ask to update it for you. Otherwise refer to following link: Update Android SDK
The following works in tensorflow 2:
import tensorflow as tf
gpus = tf.config.experimental.list_physical_devices('GPU')
for gpu in gpus:
print("Name:", gpu.name, " Type:", gpu.device_type)
From 2.1, you can drop experimental
:
gpus = tf.config.list_physical_devices('GPU')
https://www.tensorflow.org/api_docs/python/tf/config/list_physical_devices
You can use conda remove --force
.
The documentation says:
--force Forces removal of a package without removing packages
that depend on it. Using this option will usually
leave your environment in a broken and inconsistent
state
To install a specific package:
conda install <pkg>=<version>
eg:
conda install matplotlib=1.4.3
If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.
The error message says your DbContext
(LogManagerContext
) needs a constructor which accepts a DbContextOptions
. But i couldn't find such a constructor in your DbContext
. So adding below constructor probably solves your problem.
public LogManagerContext(DbContextOptions options) : base(options)
{
}
Edit for comment
If you don't register IHttpContextAccessor
explicitly, use below code:
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
In my case I added dependency via Nuget:
Microsoft.EntityFrameworkCore.Tools
And then run via Package Manager Console:
add-migration Initial -Context "ContextName" -StartupProject "EntryProject.Name" -Project "MigrationProject.Name"
In your invoke web request just use the parameter -UseBasicParsing
e.g. in your script (line 2) you should use:
$rss = Invoke-WebRequest -UseBasicParsing
According to the documentation, this parameter is necessary on systems where IE isn't installed or configured.
Uses the response object for HTML content without Document Object Model (DOM) parsing. This parameter is required when Internet Explorer is not installed on the computers, such as on a Server Core installation of a Windows Server operating system.
npm rebuild node-sass --force
Or, if you are using node-sass within a container:
docker exec <container-id> npm rebuild node-sass --force
This error occurs when node-sass does not have the correct binding for the current operating system.
If you use Docker, this error usually happens when you add node_modules
directly to the container filesystem in your Dockerfile (or mount them using a Docker volume).
The container architecture is probably different than your current operating system. For example, I installed node-sass on macOS but my container runs Ubuntu.
If you force node-sass to rebuild from within the container, node-sass will download the correct bindings for the container operating system.
See my repro case to learn more.
By publishing your whole node_modules
folder you are deploying far more files than you will actually need in production.
Instead, use a task runner as part of your build process to package up those files you require, and deploy them to your wwwroot
folder. This will also allow you to concat and minify your assets at the same time, rather than having to serve each individual library separately.
You can then also completely remove the FileServer
configuration and rely on UseStaticFiles
instead.
Currently, gulp is the VS task runner of choice. Add a gulpfile.js
to the root of your project, and configure it to process your static files on publish.
For example, you can add the following scripts
section to your project.json
:
"scripts": {
"prepublish": [ "npm install", "bower install", "gulp clean", "gulp min" ]
},
Which would work with the following gulpfile (the default when scaffolding with yo
):
/// <binding Clean='clean'/>
"use strict";
var gulp = require("gulp"),
rimraf = require("rimraf"),
concat = require("gulp-concat"),
cssmin = require("gulp-cssmin"),
uglify = require("gulp-uglify");
var webroot = "./wwwroot/";
var paths = {
js: webroot + "js/**/*.js",
minJs: webroot + "js/**/*.min.js",
css: webroot + "css/**/*.css",
minCss: webroot + "css/**/*.min.css",
concatJsDest: webroot + "js/site.min.js",
concatCssDest: webroot + "css/site.min.css"
};
gulp.task("clean:js", function (cb) {
rimraf(paths.concatJsDest, cb);
});
gulp.task("clean:css", function (cb) {
rimraf(paths.concatCssDest, cb);
});
gulp.task("clean", ["clean:js", "clean:css"]);
gulp.task("min:js", function () {
return gulp.src([paths.js, "!" + paths.minJs], { base: "." })
.pipe(concat(paths.concatJsDest))
.pipe(uglify())
.pipe(gulp.dest("."));
});
gulp.task("min:css", function () {
return gulp.src([paths.css, "!" + paths.minCss])
.pipe(concat(paths.concatCssDest))
.pipe(cssmin())
.pipe(gulp.dest("."));
});
gulp.task("min", ["min:js", "min:css"]);
I ran into a similar situation. I did have access to a larger data drive. Depending on your situation, and the access you have to the server you can consider
ln -s /datavol/path/to/your/.conda /home/user/.conda
Then subsequent conda commands will put data to the symlinked dir in datavol
Paul's answer is very good and it is actually how Kafka & Zk work together from a broker point of view.
I would say that another easy option to check if a Kafka server is running is to create a simple KafkaConsumer pointing to the cluste and try some action, for example, listTopics(). If kafka server is not running, you will get a TimeoutException and then you can use a try-catch
sentence.
def validateKafkaConnection(kafkaParams : mutable.Map[String, Object]) : Unit = {
val props = new Properties()
props.put("bootstrap.servers", kafkaParams.get("bootstrap.servers").get.toString)
props.put("group.id", kafkaParams.get("group.id").get.toString)
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
val simpleConsumer = new KafkaConsumer[String, String](props)
simpleConsumer.listTopics()
}
I tried to resolve with the suggested answer and still ran into some issues...
This was a solution to my problem:
ARG APP_EXE="AppName.exe"
ENV _EXE=${APP_EXE}
# Build a shell script because the ENTRYPOINT command doesn't like using ENV
RUN echo "#!/bin/bash \n mono ${_EXE}" > ./entrypoint.sh
RUN chmod +x ./entrypoint.sh
# Run the generated shell script.
ENTRYPOINT ["./entrypoint.sh"]
Specifically targeting your problem:
RUN echo "#!/bin/bash \n ./greeting --message ${ADDRESSEE}" > ./entrypoint.sh
RUN chmod +x ./entrypoint.sh
ENTRYPOINT ["./entrypoint.sh"]
Technically you can if you use something like OpenCL, but Nvidia's CUDA is much better and OpenCL requires other steps that may or may not work. I would recommend if you have an AMD gpu, use something like Google Colab where they provide a free Nvidia GPU you can use when coding.
You can try these some steps:
Stop Mysql Service 1st
sudo /etc/init.d/mysql stop
Login as root without password
sudo mysqld_safe --skip-grant-tables &
After login mysql terminal you should need execute commands more:
use mysql;
UPDATE mysql.user SET authentication_string=PASSWORD('solutionclub3@*^G'), plugin='mysql_native_password' WHERE User='root';
flush privileges;
sudo mysqladmin -u root -p -S /var/run/mysqld/mysqld.sock shutdown
After you restart your mysql server If you still facing error you must visit : Reset MySQL 5.7 root password Ubuntu 16.04
There is no variable included for that yet, so you have to use shell-out-read-file method:
sh 'pwd > workspace'
workspace = readFile('workspace').trim()
Or (if running on master node):
workspace = pwd()
Check if you have the linebreak-style
rule configure as below either in your .eslintrc or in source code:
/*eslint linebreak-style: ["error", "unix"]*/
Since you're working on Windows, you may want to use this rule instead:
/*eslint linebreak-style: ["error", "windows"]*/
Refer to the documentation of linebreak-style
:
When developing with a lot of people all having different editors, VCS applications and operating systems it may occur that different line endings are written by either of the mentioned (might especially happen when using the windows and mac versions of SourceTree together).
The linebreaks (new lines) used in windows operating system are usually carriage returns (CR) followed by a line feed (LF) making it a carriage return line feed (CRLF) whereas Linux and Unix use a simple line feed (LF). The corresponding control sequences are
"\n"
(for LF) and"\r\n"
for (CRLF).
This is a rule that is automatically fixable. The --fix
option on the command line automatically fixes problems reported by this rule.
But if you wish to retain CRLF
line-endings in your code (as you're working on Windows) do not use the fix
option.
you can create and initialize array of any object like this.
hero:Hero[]=[];
You can solve it by adding these two lines in the VERY beginning of your .py script.
import matplotlib
matplotlib.use('Agg')
PS: The error will still exists if these two lines are not added in the very beginning of the source code.
In my case, I have set up a new app but I was getting errors, tried many possible ways and answers from github and stackoverflow. nothing worked
error The solution for me was .. check if you already have an app with the same name is installed in android..
Delete old apps and run react-native run-android
Worked for me.
for visual studio 2019 need change MSBuild path
npm config set msvs_version 2017
npm config set msbuild_path "C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Current\Bin\MSBuild.exe"
npm rebuild node-sass
I was getting this error even when all the relevant dependencies were in place because I hadn't created the schema in MySQL.
I thought it would be created automatically but it wasn't. Although the table itself will be created, you have to create the schema.
I was facing a similar issue. Actually the command is :
java -version and not java --version.
You will get output something like this:
java version "1.8.0_162"
Java(TM) SE Runtime Environment (build 1.8.0_162-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.162-b12, mixed mode)
I have tried every method mentioned above and nothing worked, except installing jupyter in the new environment.
to activate the new environment
conda activate new_env
replace 'new_env' with your environment name.
next install jupyter 'pip install jupyter'
you can also install jupyter by going to anaconda navigator and selecting the right environment, and installing jupyter notebook from Home tab
The easiest and quickest way is to use following url to print all environment variables
http://localhost:8080/env-vars.html/
Where does pip installations happen in python?
I will give a windows solution which I was facing and took a while to solve.
First of all, in windows (I will be taking Windows as the OS here), if you do pip install <package_name>
, it will be by default installed globally (if you have not activated a virtual enviroment).
Once you activate a virtual enviroment and you are inside it, all pip installations will be inside that virtual enviroment.
pip is installing the said packages but not I cannot use them?
For this pip might be giving you a warning that the pip executables like pip3.exe
, pip.exe
are not on your path variable.
For this you might add this path ( usually - C:\Users\<your_username>\AppData\Roaming\Programs\Python\
) to your enviromental variables.
After this restart your cmd
, and now try to use your installed python package. It should work now.
You want 3+ slave machines with a master outside the radiation environment. All I/O passes through the master which contains a vote and/or retry mechanism. The slaves must have a hardware watchdog each and the call to bump them should be surrounded by CRCs or the like to reduce the probability of involuntary bumping. Bumping should be controlled by the master, so lost connection with master equals reboot within a few seconds.
One advantage of this solution is that you can use the same API to the master as to the slaves, so redundancy becomes a transparent feature.
Edit: From the comments I feel the need to clarify the "CRC idea." The possibilty of the slave bumping it's own watchdog is close to zero if you surround the bump with CRC or digest checks on random data from the master. That random data is only sent from master when the slave under scrutiny is aligned with the others. The random data and CRC/digest are immediately cleared after each bump. The master-slave bump frequency should be more than double the watchdog timeout. The data sent from the master is uniquely generated every time.
In my case, I had to do the following while running with Junit5
@SpringBootTest(classes = {abc.class}) @ExtendWith(SpringExtension.class
Here abc.class was the class that was being tested
Either you experienced database connection issue or you missed any of the hibernate configurations to connect to database such as database DIALECT.
Happens if your database server was disconnected due to network related issue.
If you're using spring boot along with hibernate connected to Oracle Db, use
hibernate.dialect=org.hibernate.dialect.HSQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
hibernate.generate_statistics=true
entitymanager.packagesToScan: com
In case you're using Gradle Kotlin syntax, you also can do:
tasks.taskName {
environment(mapOf("A" to 1, "B" to "C"))
}
So for test
task this would be:
tasks.test {
environment(mapOf("SOME_TEST_VAR" to "aaa"))
}
As the official docs of redux suggest, better to export the unconnected component as well.
In order to be able to test the App component itself without having to deal with the decorator, we recommend you to also export the undecorated component:
import { connect } from 'react-redux'
// Use named export for unconnected component (for tests)
export class App extends Component { /* ... */ }
// Use default export for the connected component (for app)
export default connect(mapStateToProps)(App)
Since the default export is still the decorated component, the import statement pictured above will work as before so you won't have to change your application code. However, you can now import the undecorated App components in your test file like this:
// Note the curly braces: grab the named export instead of default export
import { App } from './App'
And if you need both:
import ConnectedApp, { App } from './App'
In the app itself, you would still import it normally:
import App from './App'
You would only use the named export for tests.
For those having a portable SDK edition on windows, simply add the 2 following path to your system.
F:\ADT_SDK\sdk\platforms
F:\ADT_SDK\sdk\platform-tools
This worked for me.
Straightforward and easy solution is:
docker build .
=> ....
=> Successfully built a3e628814c67
docker run -p 3000:3000 a3e628814c67
3000
- can be any port
a3e628814c68
- hash result given by success build command
NOTE: you should be within directory that contains Dockerfile.
I face this problem too when making new project from android studio.
I've been able to resolve this by downgrading buildToolsVersion in app gradle setting: change {module-name}/build.gradle line
buildToolsVersion "24.0.0 rc1"
to
buildToolsVersion "23.0.3"
@Edit:
In Android Studio 2.1 Go to File-> Project Structure->App -> Build Tool Version. Change it to 23.0.3
Do the method above, only when you are using java version 7 and for some reason do not want to upgrade to java 8 yet.
Hope this helps
i was also getting this error, remove oracle folder from
C:\Program Files (x86)\Oracle\Inventory
and
C:\Program Files\Oracle\Inventory
Also remove all component of oracle other version (which you had already in your system).
Go to services and remove all oracle component and delete old client from
C:\app\username\product\11.2.0\client_1\
I stumbled upon this question because I created, successfully built and published a PyPI Package, but couldn't execute it after installation. The $PATH
variable was correctly set.
In my case the problem was that I hadn't set the entry_point
in the setup.py
file:
entry_points = {'console_scripts':
['YOUR_CONSOLE_COMMAND=MODULE_NAME.FILE_NAME:FUNCTION_NAME'],},
I know this is an old question, but I spent a couple of days looking through solutions which didn't work for me so maybe this helps someone else.
My project had a plugin which was throwing an error. I had to remove the plugin and add it again, and suddenly I could make it through the build process.
$ cordova add phonegap-plugin-push
$ cordova plugin add phonegap-plugin-push
I just ran the above and it was solved.
For New versions
Older versions of python may not have pip installed and get-pip will throw errors. Please update your python (2.7.15 as of Aug 12, 2018).
All current versions have an option to install pip and add it to the path.
Steps:
Powershell
as admin. (win+x
then a
)python -m pip install <package>
.If python is not in PATH, it'll throw an error saying unrecognized cmd. To fix, simply add it to the path as mentioned below.
[OLD Answer]
Python 2.7 must be having pip pre-installed.
Try installing your package by:
win+x
then a
)C:\Python27\Scripts
pip install "package name"
.Note: Else reinstall python: https://www.python.org/downloads/
Also note: You must be in C:\Python27\Scripts
in order to use pip command, Else add it to your path by typing:
[Environment]::SetEnvironmentVariable("Path","$env:Path;C:\Python27\;C:\Python27\Scripts\", "User")
There are various ways to achieve this. Here are three.
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
System.out.println("using entrySet and toString");
for (Entry<String, String> entry : map.entrySet()) {
System.out.println(entry);
}
System.out.println();
System.out.println("using entrySet and manual string creation");
for (Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
System.out.println();
System.out.println("using keySet");
for (String key : map.keySet()) {
System.out.println(key + "=" + map.get(key));
}
System.out.println();
using entrySet and toString
key1=value1
key2=value2
key3=value3
using entrySet and manual string creation
key1=value1
key2=value2
key3=value3
using keySet
key1=value1
key2=value2
key3=value3
Another option is to open the terminal at the pycharm & install it with pip
sudo pip install numpy
This is the case you are using Julia:
The analogue of IPython's %matplotlib in Julia is to use the PyPlot package, which gives a Julia interface to Matplotlib including inline plots in IJulia notebooks. (The equivalent of numpy is already loaded by default in Julia.) Given PyPlot, the analogue of %matplotlib inline is using PyPlot, since PyPlot defaults to inline plots in IJulia.
You don't need to use java variables. To include system env variables add the following to your application.properties
file:
spring.datasource.url = ${OPENSHIFT_MYSQL_DB_HOST}:${OPENSHIFT_MYSQL_DB_PORT}/"nameofDB"
spring.datasource.username = ${OPENSHIFT_MYSQL_DB_USERNAME}
spring.datasource.password = ${OPENSHIFT_MYSQL_DB_PASSWORD}
But the way suggested by @Stefan Isele is more preferable, because in this case you have to declare just one env variable: spring.profiles.active
. Spring will read the appropriate property file automatically by application-{profile-name}.properties
template.
starting the hive metastore service worked for me. First, set up the database for hive metastore:
$ hive --service metastore
Second, run the following commands:
$ schematool -dbType mysql -initSchema
$ schematool -dbType mysql -info
https://cwiki.apache.org/confluence/display/Hive/Hive+Schema+Tool
Make sure that you are installing the Anaconda binary that is compatible with your kernel. I was in the same situation.Turned out I have an x64_86 CPU and was trying to install a 64 bit Power 8 installer.You can find out the same for your CPU by using the following command.It gives you a basic information about a computer's software and hardware.-
$ uname -a
https://www.anaconda.com/download/#linux
The page in the link above, displays 2 different types of 64-Bit installers -
There is one other reason that can cause Test Explorer not showing any tests, and it has to do with the new portable .pdb
file format introduced with Visual Studio 2017 / for .NET Core which can break some VS tooling. (Background: See the bug report "Mono.Cecil causes OutOfMemoryException with new .csproj PDBs".)
.pdb
(debug symbols) format?If you see output like to the following (possibly repeated once for each of your tests), then you've got the problem described in this answer:
Exception System.OutOfMemoryException, Exception converting <SignatureOfYourTestMethod>
Array dimensions exceeded supported range.
none
, pdb-only
, or full
, but NOT portable
. It is this last setting that causes the tests to not be found..pdb
files before rebuilding. Now your tests should be back.Mac & Big Sur. Python 3.8.6 w/vs code. While it should have been included in diagrams package, I had to manually install graphviz.
(mymltools) ? infrastructure git:(master) pip list
Package Version
---------- -------
diagrams 0.18.0
graphviz 0.13.2
Jinja2 2.11.2
MarkupSafe 1.1.1
pip 20.3.2
setuptools 51.0.0
wheel 0.36.2
Running diagrams failed. Then manually ran
pipenv install graphviz
Works like a charm.
Do not log in as a root user, try another one with sudo permissions.
I found out that it also happens if you uninstalled some packages from your react-native project and there is still packages in your build gradle dependencies in the bottom of page like:
{
project(':react-native-sound-player')
}
Follow the below steps,
I have also faced the same issue and solved it later. first of all execute the artisan command:
php artisan cache:clear
And after that restart the project. Hope it will help.
Download the Visual C++ Redistributable 2015
Updated links to VC++ file:
I ran into this issue as well running on OSX. I saw Oliver Salzburg's response and checked my ~/.docker/config.json. It had multiple authorization credentials inside it from the different AWS accounts I have. I deleted the file and after running get-login again it worked.
For me the fix was to install a newer version (1.24) of docker-compose
using this article.
The previous version (1.17) was installed from ubuntu
's default repository, but after installing a newer version I managed to launch the container. Hope it helps somebody.
If Android Studio shows you the path /Users/<name>/Library/Android/sdk
but you can not find it in your folder, just right-click and select "Show View Option". There you will be able to select "Show Library Folder"; select it and you can access the SDK.
One of the following solutions will work for you:
c:\Python\27\python.exe
or set PYTHON=D:\Python\bin\Python.exe
npm config set python D:\Library\Python\Python27\python.exe
npm --add-python-to-path='true' --debug install --global windows-build-tools
(Must be executed via "Run As Administrator" PowerShell)If not... Try to install the required package on your own (I did so, and it was node-sass
, after installing it manually, the whole npm install
was successfully completed
To simplify: Only configuration files can access environment variables - and then pass them on.
Step 1.) Add your variable to your .env
file, for example,
EXAMPLE_URL="http://google.com"
Step 2.) Create a new file inside of the config
folder, with any name, for example,
config/example.php
Step 3.) Inside of this new file, I add an array being returned, containing that environment variable.
<?php
return [
'url' => env('EXAMPLE_URL')
];
Step 4.) Because I named it "example", my configuration 'namespace' is now example. So now, in my controller I can access this variable with:
$url = \config('example.url');
Tip - if you add use Config;
at the top of your controller, you don't need the backslash (which designates the root namespace). For example,
namespace App\Http\Controllers;
use Config; // Added this line
class ExampleController extends Controller
{
public function url() {
return config('example.url');
}
}
Finally, commit the changes:
php artisan config:cache
--- IMPORTANT --- Remember to enter php artisan config:cache
into the console once you have created your example.php file. Configuration files and variables are cached, so if you make changes you need to flush that cache - the same applies to the .env
file being changed / added to.
According to the packages list in Ubuntu Wily Xenial Bionic there is a package named openjfx. This should be a candidate for what you're looking for:
JavaFX/OpenJFX 8 - Rich client application platform for Java
You can install it via:
sudo apt-get install openjfx
It provides the following JAR files to the OpenJDK installation on Ubuntu systems:
/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/jfxrt.jar
/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/jfxswt.jar
/usr/lib/jvm/java-8-openjdk-amd64/lib/ant-javafx.jar
/usr/lib/jvm/java-8-openjdk-amd64/lib/javafx-mx.jar
If you want to have sources available, for example for debugging, you can additionally install:
sudo apt-get install openjfx-source
Well I am new to tensorflow, I have Geforce 740m or something GPU with 2GB ram, I was running mnist handwritten kind of example for a native language with training data containing of 38700 images and 4300 testing images and was trying to get precision , recall , F1 using following code as sklearn was not giving me precise reults. once i added this to my existing code i started getting GPU errors.
TP = tf.count_nonzero(predicted * actual)
TN = tf.count_nonzero((predicted - 1) * (actual - 1))
FP = tf.count_nonzero(predicted * (actual - 1))
FN = tf.count_nonzero((predicted - 1) * actual)
prec = TP / (TP + FP)
recall = TP / (TP + FN)
f1 = 2 * prec * recall / (prec + recall)
plus my model was heavy i guess, i was getting memory error after 147, 148 epochs, and then I thought why not create functions for the tasks so I dont know if it works this way in tensrorflow, but I thought if a local variable is used and when out of scope it may release memory and i defined the above elements for training and testing in modules, I was able to achieve 10000 epochs without any issues, I hope this will help..
If you want to set environment variables permanently in Git-Bash, you have two options:
Set a regular Windows environment variable. Git-bash gets all existing Windows environment variables at startupp.
Set up env variables in .bash_profile
file.
.bash_profile
is by default located in a user home folder, like C:\users\userName\git-home\.bash_profile
. You can change the path to the bash home folder by setting HOME
Windows environment variable.
.bash_profile
file uses the regular Bash syntax and commands
# Export a variable in .bash_profile
export DIR=c:\dir
# Nix path style works too
export DIR=/c/dir
# And don't forget to add quotes if a variable contains whitespaces
export ANOTHER_DIR="c:\some dir"
Read more information about Bash configurations files.
Try to remove and add ios again
ionic cordova platform remove ios
ionic cordova platform add ios
Worked in my case
From your question, you are running python2.7 and Cygwin.
Python should be installed for windows, which from your question it seems it is. If "which python" prints out /usr/bin/python , then from the bash prompt you are running the cygwin version.
Set the Python Environmental variables appropriately , for instance in my case:
PY_HOME=C:\opt\Python27
PYTHONPATH=C:\opt\Python27;c:\opt\Python27\Lib
In that case run cygwin setup and uninstall everything python. After that run "which pydoc", if it shows
/usr/bin/pydoc
Replace /usr/bin/pydoc with
#! /bin/bash
/cygdrive/c/WINDOWS/system32/cmd /c %PYTHONHOME%\Scripts\\pydoc.bat
Then add this to $PY_HOME/Scripts/pydoc.bat
rem wrapper for pydoc on Win32
@python c:\opt\Python27\Lib\pydoc.py %*
Now when you type in the cygwin bash prompt you should see:
$ pydoc
pydoc - the Python documentation tool
pydoc.py <name> ...
Show text documentation on something. <name>
may be the name of a Python keyword, topic,
function, module, or package, or a dotted
reference to a class or function within a
module or module in a package.
...
install by this command given below conda install -c conda-forge keras
this is error "CondaError: Cannot link a source that does not exist" ive get in win 10. for your error put this command in your command line.
conda update conda
this work for me .
@aisbaa's answer works if you don't care when the environment variable was declared. If you want the environment variable, even if it has been declared inside of an exec /bin/bash
session, use something like:
IFS="=" read -a out <<< $(docker exec container /bin/bash -c "env | grep ENV_VAR" 2>&1)
It's not very pretty, but it gets the job done.
To then get the value, use:
echo ${out[1]}
Provide the Directory/Folder path where python.exe is available in Anaconda folder like
C:\Users\user_name\Anaconda3\
This should must work.
To answer your question:
In my Dockerfile, I would like to define variables that I can use later in the Dockerfile.
You can define a variable with:
ARG myvalue=3
Spaces around the equal character are not allowed.
And use it later with:
RUN echo $myvalue > /test
As of now, Postman comes with its own "Console." Click the terminal-like icon on the bottom left to open the console. Send a request, and you can inspect the request from within Postman's console.
The only way I have found to change this is directly on the code :
at the very beginning of your app you set
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
you should include the system.net
class
I did this before calling a web service because we had to block tls1 too.
(VS Code 1.33.1 on Windows 7)
Zoom all (UI and editor): CTRL + +, CTRL + -.
Zoom editor: CTRL + Mouse Wheel.
See below how i fixed it.
As suggested by @Edwin: Pressing Control+Shift+P and then typing "settings" will allow you to easily find the user or workspace settings file.
My settings file is found here: "C:\Users\You_user\AppData\Roaming\Code\User\settings.json"
My file looks like this:
{
"editor.fontSize": 12,
"editor.suggestFontSize": 6,
"markdown.preview.fontSize": 0,
"terminal.integrated.fontSize": 10,
"window.zoomLevel": 0,
"workbench.sideBar.location": "left",
"editor.mouseWheelZoom": true
}
After 2 hrs of net surfing Finally For me the problem was fixed by creating a folder pip, with a file: pip.ini in C:\Users<username>\AppData\Roaming\ e.g:
C:\Users\<username>\AppData\Roaming\pip\pip.ini
Inside it I wrote:
[global]
trusted-host = pypi.python.org
pypi.org
files.pythonhosted.org
I restarted python, and then pip permanently trusted these sites, and used them to download packages from.
If you can't find the AppData Folder on windows, write %appdata% in file explorer and it should appear.
If you are running python version 3.9 pandas wont work as of now. So install python version 3.7 or below to mitigate this issue. Or else if you want to stick with python 3.9 try install pandas by compiling the library
There is another possible scenario that might get some people as well (if you have python and python3 on your system):
pip3 install boto3
Note the use of pip3
indicates the use of Python 3's pip installation vs just pip
which indicates the use of Python 2's.
In [44]: df['gdp'] = df['gdp'].shift(-1)
In [45]: df
Out[45]:
y gdp cap
0 1 3 5
1 2 7 9
2 8 4 2
3 3 7 7
4 6 NaN 7
In [46]: df[:-1]
Out[46]:
y gdp cap
0 1 3 5
1 2 7 9
2 8 4 2
3 3 7 7
Since I was helped with my project by the answer above (I asked a duplicate question and was referred here), I am submitting an answer (my test code) for bracket notation when nesting within the var:
<html>_x000D_
<head>_x000D_
<script type="text/javascript">_x000D_
function displayFile(whatOption, whatColor) {_x000D_
var Test01 = {_x000D_
rectangle: {_x000D_
red: "RectangleRedFile",_x000D_
blue: "RectangleBlueFile"_x000D_
},_x000D_
square: {_x000D_
red: "SquareRedFile",_x000D_
blue: "SquareBlueFile"_x000D_
}_x000D_
};_x000D_
var filename = Test01[whatOption][whatColor];_x000D_
alert(filename);_x000D_
}_x000D_
</script>_x000D_
</head>_x000D_
<body>_x000D_
<p onclick="displayFile('rectangle', 'red')">[ Rec Red ]</p>_x000D_
<br/>_x000D_
<p onclick="displayFile('square', 'blue')">[ Sq Blue ]</p>_x000D_
<br/>_x000D_
<p onclick="displayFile('square', 'red')">[ Sq Red ]</p>_x000D_
</body>_x000D_
</html>
_x000D_
<?php $sql = "SELECT * FROM guest_book";
$res = mysql_query($sql);
if (mysql_num_rows($res)) {
$query = mysql_query("SELECT * FROM guest_book ORDER BY id");
$i=1;
while($row = mysql_fetch_assoc($query)){
?>
<input type="checkbox" name="checkboxstatus[<?php echo $i; ?>]" value="<?php echo $row['id']; ?>" />
<?php $i++; }} ?>
<input type="submit" value="Delete" name="Delete" />
if($_REQUEST['Delete'] != '')
{
if(!empty($_REQUEST['checkboxstatus'])) {
$checked_values = $_REQUEST['checkboxstatus'];
foreach($checked_values as $val) {
$sqldel = "DELETE from guest_book WHERE id = '$val'";
mysql_query($sqldel);
}
}
}
PHP has some image processing functions along with the imagecreatefrompng
and imagejpeg
function. The first will create an internal representation of a PNG image file while the second is used to save that representation as JPEG image file.
<button [disabled]="this.model.IsConnected() == false"
[ngClass]="setStyles()"
class="action-button action-button-selected button-send"
(click)= "this.Send()">
SEND
</button>
.ts code
setStyles()
{
let styles = {
'action-button-disabled': this.model.IsConnected() == false
};
return styles;
}
Changing the casing to all lowercases worked for me.
You can use the following code:
return RedirectToAction("Index", "Home");
See RedirectToAction
We can check error & 404 statusCode, and use try {} catch (err) {}
.
You can try this :
const req = new XMLHttpRequest();_x000D_
req.onreadystatechange = function() {_x000D_
if (req.status == 404) {_x000D_
console.log("404");_x000D_
return false;_x000D_
}_x000D_
_x000D_
if (!(req.readyState == 4 && req.status == 200))_x000D_
return false;_x000D_
_x000D_
const json = (function(raw) {_x000D_
try {_x000D_
return JSON.parse(raw);_x000D_
} catch (err) {_x000D_
return false;_x000D_
}_x000D_
})(req.responseText);_x000D_
_x000D_
if (!json)_x000D_
return false;_x000D_
_x000D_
document.body.innerHTML = "Your city : " + json.city + "<br>Your isp : " + json.org;_x000D_
};_x000D_
req.open("GET", "https://ipapi.co/json/", true);_x000D_
req.send();
_x000D_
Read more :
You could set up a set of metrics to try to guess which encoding is being used. Again, not perfect, but could catch some of the misses from mb_detect_encoding().
In a comment to one of the answers you mention that to_date with a format doesn't help. In another comment you explain that the table is accessed via DBLINK.
So obviously the other system contains an invalid date that Oracle cannot accept. Fix this in the other dbms (or whatever you dblink to) and your query will work.
Having said this, I agree with the others: always use to_date with a format to convert a string literal to a date. Also never use only two digits for a year. For example '23/04/49' means 2049 in your system (format RR), but it confuses the reader (as you see from the answers suggesting a format with YY).
"...by a class and a div."
I assume when you say "div" you mean "id"? Try this:
$('#test2.test1').prop('checked', true);
No need to muck about with your [attributename=value]
style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".
Or more generally to select an input where you want to specify a multiple attribute selector:
$('input:radio[class=test1][id=test2]').prop('checked', true);
That is, list each attribute with its own square brackets.
Note that unless you have a pretty old version of jQuery you should use .prop()
rather than .attr()
for this purpose.
I am using php 5.6 on window 10 with zend 1.12 version for me adding
require_once 'PHPUnit/Autoload.php';
before
abstract class Zend_Test_PHPUnit_ControllerTestCase extends PHPUnit_Framework_TestCase
worked. We need to add this above statement in ControllerTestCase.php file
require 'net/http'
result = Net::HTTP.get(URI.parse('http://www.example.com/about.html'))
# or
result = Net::HTTP.get(URI.parse('http://www.example.com'), '/about.html')
Try adding to td
:
display: -webkit-box; // to make td as block
word-break: break-word; // to make content justify
overflowed tds will align with new row.
I believe this is the best solution:
let date = new Date(objDate);
date.setMinutes(date.getTimezoneOffset());
This will update your date by the offset appropriately since it is presented in minutes.
2020 Answer
With the release of node v14.14.0
you can now do.
fs.rmSync("path/to/file", {
force: true,
});
Try .html() instead of .val() :
var text = $('#frame1').contents().find('#area1').html();
The easy-to-remember, lazy and perhaps imperfect solution:
Directory.GetFiles(dir, "*.dll").Union(Directory.GetFiles(dir, "*.exe"))
FUNCTIONAL REQUIREMENTS the activities the system must perform
The final
keyword has several usages in Java. It corresponds to both the sealed
and readonly
keywords in C#, depending on the context in which it is used.
To prevent subclassing (inheritance from the defined class):
Java
public final class MyFinalClass {...}
C#
public sealed class MyFinalClass {...}
Prevent overriding of a virtual
method.
Java
public class MyClass
{
public final void myFinalMethod() {...}
}
C#
public class MyClass : MyBaseClass
{
public sealed override void MyFinalMethod() {...}
}
As Joachim Sauer points out, a notable difference between the two languages here is that Java by default marks all non-static methods as virtual
, whereas C# marks them as sealed
. Hence, you only need to use the sealed
keyword in C# if you want to stop further overriding of a method that has been explicitly marked virtual
in the base class.
To only allow a variable to be assigned once:
Java
public final double pi = 3.14; // essentially a constant
C#
public readonly double pi = 3.14; // essentially a constant
As a side note, the effect of the readonly
keyword differs from that of the const
keyword in that the readonly
expression is evaluated at runtime rather than compile-time, hence allowing arbitrary expressions.
The problem is that you used the select option, this is where you went wrong. Select signifies that a textbox or textArea has a focus. What you need to do is use change. "Fires when a new choice is made in a select element", also used like blur when moving away from a textbox or textArea.
function start(){
document.getElementById("activitySelector").addEventListener("change", addActivityItem, false);
}
function addActivityItem(){
//option is selected
alert("yeah");
}
window.addEventListener("load", start, false);
IsEmpty returns True if the variable is uninitialized, or is explicitly set to Empty; otherwise, it returns False. False is always returned if expression contains more than one variable. IsEmpty only returns meaningful information for variants. (https://msdn.microsoft.com/en-us/library/office/gg264227.aspx) . So you must check every cell in range separately:
Dim thisColumn as Byte, thisRow as Byte
For thisColumn = 1 To 5
For ThisRow = 1 To 6
If IsEmpty(Cells(thisRow, thisColumn)) = False Then
GoTo RangeIsNotEmpty
End If
Next thisRow
Next thisColumn
...........
RangeIsNotEmpty:
Of course here are more code than in solution with CountA function which count not empty cells, but GoTo can interupt loops if at least one not empty cell is found and do your code faster especially if range is large and you need to detect this case. Also this code for me is easier to understand what it is doing, than with Excel CountA function which is not VBA function.
Display errors could be turned off in the php.ini
or your Apache configuration file.
You can turn it on in the script:
error_reporting(E_ALL);
ini_set('display_errors', '1');
You should see the same messages in the PHP error log.
To concatenate strings, use the +
operator.
To insert data into a URI, encode it for URIs.
Bad:
var url = "http://localhost:8080/login?cid='username'&pwd='password'"
Good:
var url_safe_username = encodeURIComponent(username);
var url_safe_password = encodeURIComponent(password);
var url = "http://localhost:8080/login?cid=" + url_safe_username + "&pwd=" + url_safe_password;
The server will have to process the query string to make use of the data. You can't assign to arbitrary form fields.
… but don't trigger new windows or pass credentials in the URI (where they are exposed to over the shoulder attacks and may be logged).
I did not like any of the answers here, so I created a function that worked for me. Just want to share in case anyone else finds it useful.
function getFormattedCurrency(num) {
num = num.toFixed(2)
var cents = (num - Math.floor(num)).toFixed(2);
return Math.floor(num).toLocaleString() + '.' + cents.split('.')[1];
}
Hi, this will throw an error:
foreach ($product->sku as $sku){
// Code Here
}
because you cannot loop a model with a specific column ($product->sku) from the table.
So you must loop on the whole model:
foreach ($product as $p) {
// code
}
Inside the loop you can retrieve whatever column you want just adding "->[column_name]"
foreach ($product as $p) {
echo $p->sku;
}
Have a great day
SELECT SUBSTRING(subject, 1, 10) FROM tbl
the localhost:8080
means your explicitly targeting port 8080.
Try this script:
#!/bin/bash
echo $PATH | tr : '\n' |
while read e; do
for i in $e/*; do
if [[ -x "$i" && -f "$i" ]]; then
echo $i
fi
done
done
Use enumerate:
testlist = [1,2,3,5,3,1,2,1,6]
for position, item in enumerate(testlist):
if item == 1:
print position
The problem, in my case, was that I was using Amazon's Cloudflare and Cloudfront's Cloudfront in tandem, and Cloudfront did not like the settings that I had provided Cloudflare.
More specifically, in the Crypto settings on Cloudflare, I had set the "Minimum TLS Settings" to 1.2, without enabling the TLS 1.2 communication setting for the distribution in Cloudfront. This was enough to make Cloudfront declare a 502 Bad Gateway error when it tried to connect to the Cloudflare-protected server.
To fix this, I had to disable SSLv3 support in the Origin Settings for that Cloudfront distribution, and enable TLS 1.2 as a supported protocol for that origin server.
To debug this problem, I used command-line versions of curl, to see what Cloudfront was actually returning when you asked for an image from its CDN, and I also used the command-line version of openssl, to determine exactly which protocols Cloudflare was offering (it wasn't offering TLS 1.0).
tl:dr; make sure everything accepts and asks for TLS 1.2, or whatever latest and greatest TLS everyone is using by the time you read this.
Sets remove duplicate items. In order to do that, the item can't change while in the set. Lists can change after being created, and are termed 'mutable'. You cannot put mutable things in a set.
Lists have an unmutable equivalent, called a 'tuple'. This is how you would write a piece of code that took a list of lists, removed duplicate lists, then sorted it in reverse.
result = sorted(set(map(tuple, my_list)), reverse=True)
Additional note: If a tuple contains a list, the tuple is still considered mutable.
Some examples:
>>> hash( tuple() )
3527539
>>> hash( dict() )
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
hash( dict() )
TypeError: unhashable type: 'dict'
>>> hash( list() )
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
hash( list() )
TypeError: unhashable type: 'list'
It might be possible to do this with box-shadow
however, I can't get it to actually apply to an image. Only on solid color backgrounds
body {_x000D_
background: #131418;_x000D_
color: #999;_x000D_
text-align: center;_x000D_
}_x000D_
.mycooldiv {_x000D_
width: 400px;_x000D_
height: 300px;_x000D_
margin: 2% auto;_x000D_
border-radius: 100%;_x000D_
}_x000D_
.red {_x000D_
background: red_x000D_
}_x000D_
.blue {_x000D_
background: blue_x000D_
}_x000D_
.yellow {_x000D_
background: yellow_x000D_
}_x000D_
.green {_x000D_
background: green_x000D_
}_x000D_
#darken {_x000D_
box-shadow: inset 0px 0px 400px 110px rgba(0, 0, 0, .7);_x000D_
/*darkness level control - change the alpha value for the color for darken/ligheter effect */_x000D_
}
_x000D_
Red_x000D_
<div class="mycooldiv red"></div>_x000D_
Darkened Red_x000D_
<div class="mycooldiv red" id="darken"></div>_x000D_
Blue_x000D_
<div class="mycooldiv blue"></div>_x000D_
Darkened Blue_x000D_
<div class="mycooldiv blue" id="darken"></div>_x000D_
Yellow_x000D_
<div class="mycooldiv yellow"></div>_x000D_
Darkened Yellow_x000D_
<div class="mycooldiv yellow" id="darken"></div>_x000D_
Green_x000D_
<div class="mycooldiv green"></div>_x000D_
Darkened Green_x000D_
<div class="mycooldiv green" id="darken"></div>
_x000D_
Use the constructor that takes a File
and a boolean
FileOutputStream(File file, boolean append)
and set the boolean to true
. That way, the data you write will be appended to the end of the file, rather than overwriting what was already there.
Depends on what you call "best." From a theoretical point of view, you cannot solve the problem in less than O(n)
in a deterministic Turing machine.
The naive algorithm is too loop and update min, max. However, a recursive solution will require less comparisons than naive algorithm, if you want to get min, max simultaneously (it isn't necessarily faster due to function call overhead).
struct MinMax{
public int Min,Max;
}
MinMax FindMinMax(int[] array, int start, int end) {
if (start == end)
return new MinMax { Min = array[start], Max = array[start] };
if (start == end - 1)
return new MinMax { Min = Math.Min(array[start], array[end]), Max = Math.Max(array[start], array[end]) } ;
MinMax res1 = FindMinMax(array, start, (start + end)/2);
MinMax res2 = FindMinMax(array, (start+end)/2+1, end);
return new MinMax { Min = Math.Min(res1.Min, res2.Min), Max = Math.Max(res1.Max, res2.Max) } ;
}
The simplest solution would be to sort and get the first and last item, though it's obviously not the fastest ;)
The best solution, performance-wise, to find the minimum or maximum is the naive algorithm you written (with a single loop).
Can also invoke oShell.Exec in order to be able to read STDIN/STDOUT/STDERR responses. Perfect for error checking which it seems you're doing with your sanity .BAT.
Another option which has not been suggested here is to run the app you want to monitor in the Android emulator from the Android SDK. You can then easily capture the traffic with wireshark on the same machine.
This was the easiest option for me.
Varchar Date Convert to Date and Change the Format
Nov 12 2016 12:00 , 21/12/2016, 21-12-2016
this Query Works for above to change to this Format dd/MM/yyyy
SELECT [Member_ID],[Name] ,
Convert(varchar(50),Convert(date,[DOB],103),103) as DOB
,[NICNO],[Relation] FROM [dbo].[tbl_FamilMember]
var b bytes.Buffer
b.ReadFrom(r)
// b.String()
:w
- Write a file.
!sudo
- Call shell sudo command.
tee
- The output of write (vim :w) command redirected using tee. The % is nothing but current file name i.e. /etc/apache2/conf.d/mediawiki.conf. In other words tee command is run as root and it takes standard input and write it to a file represented by %. However, this will prompt to reload file again (hit L to load changes in vim itself):
Another option might be numpy.asarray:
import numpy as np
a = ["1.1", "2.2", "3.2"]
b = np.asarray(a, dtype=np.float64, order='C')
For Python 2*:
print a, type(a), type(a[0])
print b, type(b), type(b[0])
resulting in:
['1.1', '2.2', '3.2'] <type 'list'> <type 'str'>
[1.1 2.2 3.2] <type 'numpy.ndarray'> <type 'numpy.float64'>
You cannot use the same name for multiple captures. Thus you cannot use a quantifier on expressions with named captures.
So either don’t use named captures:
(?:(\b\w+\b)\s*=\s*("[^"]*"|'[^']*'|[^"'<>\s]+)\s+)+
Or don’t use the quantifier on this expression:
(?<name>\b\w+\b)\s*=\s*(?<value>"[^"]*"|'[^']*'|[^"'<>\s]+)
This does also allow attribute values like bar=' baz='quux
:
foo="bar=' baz='quux"
Well the drawback will be that you have to strip the leading and trailing quotes afterwards.
Here's another solution using df.transform
and df.set_index
:
>>> (df['teams']
.transform([lambda x:x[0], lambda x:x[1]])
.set_axis(['team1','team2'],
axis=1,
inplace=False)
)
team1 team2
0 SF NYG
1 SF NYG
2 SF NYG
3 SF NYG
4 SF NYG
5 SF NYG
6 SF NYG
it is important to remove the browser interpreted setting from the parent div. So if you want the real image width and height you can just use
$('.right-sidebar').find('img').each(function(){
$(this).removeAttr("width");
$(this).removeAttr("height");
$(this).imageResize();
});
This is one TYPO3 Project example from me where I need the real properties of the image to scale it with the right relation.
In Internet Explorer 7, 8 & 9, this works:
function getZoom() {
var screen;
screen = document.frames.screen;
return ((screen.deviceXDPI / screen.systemXDPI) * 100 + 0.9).toFixed();
}
The "+0.9" is added to prevent rounding errors (otherwise, you would get 104% and 109% when the browser zoom is set to 105% and 110% respectively).
In IE6 zoom doesn't exists, so it is unnecessary to check the zoom.
Just download "node.exe" from http://nodejs.org/dist/, select your favorite "node.js" version or take the latest. You can also take 64-bits version from "x64" sub-directory.
Then, go to http://nodejs.org/dist/npm/ to retrieve Zip-archive of your favorite "npm" version (recommanded : 1.4.10
). Extract the archive along "node.exe".
Finally, it is recommanded to add "node.js" directory to the PATH for convenience.
EDIT: I recommande to update npm using npm install npm -g
because versions provided by nodejs.org are very old.
If you want to keep original npm version, don't put npm alongside "node.exe"
. Just create a directory and use the same command with "global" flag, then copy .\node_modules\.bin\npm.cmd
to the new directory :
mkdir c:\app\npm\_latest
cd c:\app\npm\_latest
<NPM_ORIGINAL_PATH>\npm install npm
cp node_modules\.bin\npm.cmd npm.cmd
Finally change your PATH to use c:\app\npm\_latest
This is old I know, but just a pointer to anyone using this ass a reference. I have just tried this and if you are using Oracle, JOIN does not work in DELETE statements. You get a the following message:
ORA-00933: SQL command not properly ended.
WHERE MyColumn = COALESCE(@value,MyColumn)
If @value
is NULL
, it will compare MyColumn
to itself, ignoring
@value = no where
clause.
IF @value
has a value (NOT NULL
) it will compare MyColumn
to
@value
.
Reference: COALESCE (Transact-SQL).
I did that mistake once - embedding PDF files in HTML pages. I will suggest that you use a JavaScript library for displaying the content of the PDF. Like https://github.com/mozilla/pdf.js/
No, you cannot run windows containers directly on Linux.
But you can run Linux on Windows.
Windows Server/10 comes packaged with base image of ubuntu OS (after september 2016 beta service pack). That is the reason you can run linux on windows and not other wise. Check out here. https://thenewstack.io/finally-linux-containers-really-will-run-windows-linuxkit/
You can change between OS containers Linux and windows by right clicking on the docker in tray menu.
This answer might seem silly but I had my laptop's power plan set to something other than High performance (in Windows). I would constantly get out of memory warnings in Visual Studio and things would run a bit slow. After I changed the power setting to High performance, I no longer see any problem.
Based on the ObjectDumper of the LINQ samples I created a version that dumps each of the properties on its own line.
This Class Sample
namespace MyNamespace
{
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Address Address { get; set; }
public IList<Hobby> Hobbies { get; set; }
}
public class Hobby
{
public string Name { get; set; }
}
public class Address
{
public string Street { get; set; }
public int ZipCode { get; set; }
public string City { get; set; }
}
}
has an output of
{MyNamespace.User}
FirstName: "Arnold"
LastName: "Schwarzenegger"
Address: { }
{MyNamespace.Address}
Street: "6834 Hollywood Blvd"
ZipCode: 90028
City: "Hollywood"
Hobbies: ...
{MyNamespace.Hobby}
Name: "body building"
Here is the code.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
public class ObjectDumper
{
private int _level;
private readonly int _indentSize;
private readonly StringBuilder _stringBuilder;
private readonly List<int> _hashListOfFoundElements;
private ObjectDumper(int indentSize)
{
_indentSize = indentSize;
_stringBuilder = new StringBuilder();
_hashListOfFoundElements = new List<int>();
}
public static string Dump(object element)
{
return Dump(element, 2);
}
public static string Dump(object element, int indentSize)
{
var instance = new ObjectDumper(indentSize);
return instance.DumpElement(element);
}
private string DumpElement(object element)
{
if (element == null || element is ValueType || element is string)
{
Write(FormatValue(element));
}
else
{
var objectType = element.GetType();
if (!typeof(IEnumerable).IsAssignableFrom(objectType))
{
Write("{{{0}}}", objectType.FullName);
_hashListOfFoundElements.Add(element.GetHashCode());
_level++;
}
var enumerableElement = element as IEnumerable;
if (enumerableElement != null)
{
foreach (object item in enumerableElement)
{
if (item is IEnumerable && !(item is string))
{
_level++;
DumpElement(item);
_level--;
}
else
{
if (!AlreadyTouched(item))
DumpElement(item);
else
Write("{{{0}}} <-- bidirectional reference found", item.GetType().FullName);
}
}
}
else
{
MemberInfo[] members = element.GetType().GetMembers(BindingFlags.Public | BindingFlags.Instance);
foreach (var memberInfo in members)
{
var fieldInfo = memberInfo as FieldInfo;
var propertyInfo = memberInfo as PropertyInfo;
if (fieldInfo == null && propertyInfo == null)
continue;
var type = fieldInfo != null ? fieldInfo.FieldType : propertyInfo.PropertyType;
object value = fieldInfo != null
? fieldInfo.GetValue(element)
: propertyInfo.GetValue(element, null);
if (type.IsValueType || type == typeof(string))
{
Write("{0}: {1}", memberInfo.Name, FormatValue(value));
}
else
{
var isEnumerable = typeof(IEnumerable).IsAssignableFrom(type);
Write("{0}: {1}", memberInfo.Name, isEnumerable ? "..." : "{ }");
var alreadyTouched = !isEnumerable && AlreadyTouched(value);
_level++;
if (!alreadyTouched)
DumpElement(value);
else
Write("{{{0}}} <-- bidirectional reference found", value.GetType().FullName);
_level--;
}
}
}
if (!typeof(IEnumerable).IsAssignableFrom(objectType))
{
_level--;
}
}
return _stringBuilder.ToString();
}
private bool AlreadyTouched(object value)
{
if (value == null)
return false;
var hash = value.GetHashCode();
for (var i = 0; i < _hashListOfFoundElements.Count; i++)
{
if (_hashListOfFoundElements[i] == hash)
return true;
}
return false;
}
private void Write(string value, params object[] args)
{
var space = new string(' ', _level * _indentSize);
if (args != null)
value = string.Format(value, args);
_stringBuilder.AppendLine(space + value);
}
private string FormatValue(object o)
{
if (o == null)
return ("null");
if (o is DateTime)
return (((DateTime)o).ToShortDateString());
if (o is string)
return string.Format("\"{0}\"", o);
if (o is char && (char)o == '\0')
return string.Empty;
if (o is ValueType)
return (o.ToString());
if (o is IEnumerable)
return ("...");
return ("{ }");
}
}
and you can use it like that:
var dump = ObjectDumper.Dump(user);
Edit
For any Xamarin.iOS or Xamarin.Forms developers, additionally you will want to check the .csproj file (for the iOS project) and ensure that it contains references to the PNG's and not just the Asset Catalog i.e.
<ItemGroup>
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Contents.json" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-40.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-40%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-40%403x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-60%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-60%403x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-72.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-72%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-76.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-76%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-83.5%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-Small-50.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-Small-50%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-Small.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-Small%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-Small%403x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\NotificationIcon%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\NotificationIcon%403x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\NotificationIcon~ipad.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\NotificationIcon~ipad%402x.png" />
</ItemGroup>
I had a similar problem, I wanted to use a different user name for a svn+ssh repository. In the end, I used svn relocate
(as described in in this answer. In my case, I'm using svn 1.6.11 and did the following:
svn switch --relocate \
svn+ssh://olduser@svnserver/path/to/repo \
svn+ssh://newuser@svnserver/path/to/repo
where svn+ssh://olduser@svnserver/path/to/repo
can be found in the URL:
line output of svn info
command. This command asked me for the password of newuser
.
Note that this change is persistent, i.e. if you want only temporarily switch to the new username with this method, you'll have to issue a similar command again after svn update
etc.
** Problem Solved ** // Changed to delegate() method to use delegation from the body
$("body").delegate("#boundOnPageLoaded", "click", function(){
alert("Delegated Button Clicked")
});
if use phpmyadmin add: fastcgi_param HTTPS on;
Use the ×
code instead of ×
Because JSF don't understand the ×
code.
Use: ×
with ;
This link provides some additional information about the topic.
Just create a multi-line comment around it. When you want it back, just erase the comment tags.
For example, <!-- Stuff to comment out or make inactive -->
try this:
download firefox, add the plugin "firebug" and "firepath"; after install them go to your webpage, start firebug and find the xpath of the element, it unique in the page so you can't make any mistake.
browser.find_element_by_xpath('just copy and paste the Xpath').click()
In my case, you need to convert the column(you think this column is numeric, but actually not) to numeric
geom_segment(data=tmpp,
aes(x=start_pos,
y=lib.complexity,
xend=end_pos,
yend=lib.complexity)
)
# to
geom_segment(data=tmpp,
aes(x=as.numeric(start_pos),
y=as.numeric(lib.complexity),
xend=as.numeric(end_pos),
yend=as.numeric(lib.complexity))
)
Here is an easy way to detect the device orientation: (Swift 3)
override func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {
handleViewRotaion(orientation: toInterfaceOrientation)
}
//MARK: - Rotation controls
func handleViewRotaion(orientation:UIInterfaceOrientation) -> Void {
switch orientation {
case .portrait :
print("portrait view")
break
case .portraitUpsideDown :
print("portraitUpsideDown view")
break
case .landscapeLeft :
print("landscapeLeft view")
break
case .landscapeRight :
print("landscapeRight view")
break
case .unknown :
break
}
}
Another method is to use HTML5's Application Cache to download all files once and keep them in the browser's cache. The above link contains much more information. The following information is from the article:
Change your <html>
tag to include a manifest
attribute:
<html manifest="http://www.example.com/example.mf">
A manifest file must be served with the mime-type text/cache-manifest
.
A simple manifest looks something like this:
CACHE MANIFEST
index.html
stylesheet.css
images/logo.png
scripts/main.js
http://cdn.example.com/scripts/main.js
Once an application is offline it remains cached until one of the following happens:
Using LINQ is relatively much slower than using a predicate supplied to the Lists FindAll
method. Also be careful with LINQ as the enumeration of the list
is not actually executed until you access the result. This can mean that, when you think you have created a filtered list, the content may differ to what you expected when you actually read it.
The following snippet worked for me.
@Html.TextBoxFor(m => m.Crown, new { id = "", @style = "padding-left:5px", @readonly = "true" })
That will be possible only if the HTML file is also loaded with the file
protocol from the local user's harddisk.
If the HTML page is served by HTTP from a server, you can't access any local files by specifying them in a src
attribute with the file://
protocol as that would mean you could access any file on the users computer without the user knowing which would be a huge security risk.
As Dimitar Bonev said, you can access a file if the user selects it using a file selector on their own. Without that step, it's forbidden by all browsers for good reasons. Thus, while his answer might prove useful for many people, it loosens the requirement from the code in the original question.
If you are using iOS8, you should be using UIAlertController — UIAlertView is deprecated.
Here is an example of how to use it:
var refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.Alert)
refreshAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
print("Handle Ok logic here")
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { (action: UIAlertAction!) in
print("Handle Cancel Logic here")
}))
presentViewController(refreshAlert, animated: true, completion: nil)
As you can see the block handlers for the UIAlertAction handle the button presses. A great tutorial is here (although this tutorial is not written using swift): http://hayageek.com/uialertcontroller-example-ios/
Swift 3 update:
let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.alert)
refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
print("Handle Ok logic here")
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
print("Handle Cancel Logic here")
}))
present(refreshAlert, animated: true, completion: nil)
Swift 5 update:
let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.alert)
refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
print("Handle Ok logic here")
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
print("Handle Cancel Logic here")
}))
present(refreshAlert, animated: true, completion: nil)
Swift 5.3 update:
let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertController.Style.alert)
refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
print("Handle Ok logic here")
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
print("Handle Cancel Logic here")
}))
present(refreshAlert, animated: true, completion: nil)
If you set the the index than the dictionary will result in unique key value pairs
encoder=LabelEncoder()
df['airline_enc']=encoder.fit_transform(df['airline'])
dictAirline= df[['airline_enc','airline']].set_index('airline_enc').to_dict()
This will add an image to another.
using (Graphics grfx = Graphics.FromImage(image))
{
grfx.DrawImage(newImage, x, y)
}
Graphics is in the namespace System.Drawing
This is what I came up to when trying to copy-paste excel ranges with it's sizes and cell groups. It might be a little too specific for my problem but...:
'** 'Copies a table from one place to another 'TargetRange: where to put the new LayoutTable 'typee: If it is an Instalation Layout table(1) or Package Layout table(2) '**
Sub CopyLayout(TargetRange As Range, typee As Integer)
Application.ScreenUpdating = False
Dim ncolumn As Integer
Dim nrow As Integer
SheetLayout.Activate
If (typee = 1) Then 'is installation
Range("installationlayout").Copy Destination:=TargetRange '@SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
ElseIf (typee = 2) Then 'is package
Range("PackageLayout").Copy Destination:=TargetRange '@SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
End If
Sheet2.Select 'SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
If typee = 1 Then
nrow = SheetLayout.Range("installationlayout").Rows.Count
ncolumn = SheetLayout.Range("installationlayout").Columns.Count
Call RowHeightCorrector(SheetLayout.Range("installationlayout"), TargetRange.CurrentRegion, typee, nrow, ncolumn)
ElseIf typee = 2 Then
nrow = SheetLayout.Range("PackageLayout").Rows.Count
ncolumn = SheetLayout.Range("PackageLayout").Columns.Count
Call RowHeightCorrector(SheetLayout.Range("PackageLayout"), TargetRange.CurrentRegion, typee, nrow, ncolumn)
End If
Range("A1").Select 'Deselect the created table
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub
'** 'Receives the Pasted Table Range and rearranjes it's properties 'accordingly to the original CopiedTable 'typee: If it is an Instalation Layout table(1) or Package Layout table(2) '**
Function RowHeightCorrector(CopiedTable As Range, PastedTable As Range, typee As Integer, RowCount As Integer, ColumnCount As Integer)
Dim R As Long, C As Long
For R = 1 To RowCount
PastedTable.Rows(R).RowHeight = CopiedTable.CurrentRegion.Rows(R).RowHeight
If R >= 2 And R < RowCount Then
PastedTable.Rows(R).Group 'Main group of the table
End If
If R = 2 Then
PastedTable.Rows(R).Group 'both type of tables have a grouped section at relative position "2" of Rows
ElseIf (R = 4 And typee = 1) Then
PastedTable.Rows(R).Group 'If it is an installation materials table, it has two grouped sections...
End If
Next R
For C = 1 To ColumnCount
PastedTable.Columns(C).ColumnWidth = CopiedTable.CurrentRegion.Columns(C).ColumnWidth
Next C
End Function
Sub test ()
Call CopyLayout(Sheet2.Range("A18"), 2)
end sub
From sourcetree gui click on working directoy, right-click the file(s) that you want to discard, then click on Discard
Why not just using
<div [ngClass]="classes"> </div>
https://angular.io/docs/ts/latest/api/common/index/NgClass-directive.html
The problem with your conditional is in this part sshkey_result.rc == 1
, because sshkey_result
does not contain rc
attribute and entire conditional fails.
If you want to check if file exists check exists
attribute.
Here you can read more about stat module and how to use it.
I obtained the best results with groupby
from itertools
module with this function using Python 3.5.2:
from itertools import groupby
a = [1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 56, 6, 7, 67]
def occurrence():
occurrence, num_times = 0, 0
for key, values in groupby(a, lambda x : x):
val = len(list(values))
if val >= occurrence:
occurrence, num_times = key, val
return occurrence, num_times
occurrence, num_times = occurrence()
print("%d occurred %d times which is the highest number of times" % (occurrence, num_times))
Output:
4 occurred 6 times which is the highest number of times
Test with timeit
from timeit
module.
I used this script for my test with number= 20000
:
from itertools import groupby
def occurrence():
a = [1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 56, 6, 7, 67]
occurrence, num_times = 0, 0
for key, values in groupby(a, lambda x : x):
val = len(list(values))
if val >= occurrence:
occurrence, num_times = key, val
return occurrence, num_times
if __name__ == '__main__':
from timeit import timeit
print(timeit("occurrence()", setup = "from __main__ import occurrence", number = 20000))
Output (The best one):
0.1893607140000313
You can also do like this,
(for %i in (a b "c d") do @echo %~i)
The output will be,
a
b
c d
Note that when this is put in a batch file, '%' shall be doubled.
(for %%i in (a b "c d") do @echo %%~i)
Another similar method to those described above is to use plt.ylim
for example:
plt.ylim(max(y_array), min(y_array))
This method works for me when I'm attempting to compound multiple datasets on Y1 and/or Y2
Click on Store Listing and then click on 'Unpublish App'.
Try os.chdir
os.chdir(path)
Change the current working directory to path. Availability: Unix, Windows.
I've also seen people put it in their migration, but I'd rather see it defined in the model code.
Is there a canonical way to set default value for fields in ActiveRecord model?
The canonical Rails way, before Rails 5, was actually to set it in the migration, and just look in the db/schema.rb
for whenever wanting to see what default values are being set by the DB for any model.
Contrary to what @Jeff Perrin answer states (which is a bit old), the migration approach will even apply the default when using Model.new
, due to some Rails magic. Verified working in Rails 4.1.16.
The simplest thing is often the best. Less knowledge debt and potential points of confusion in the codebase. And it 'just works'.
class AddStatusToItem < ActiveRecord::Migration
def change
add_column :items, :scheduler_type, :string, { null: false, default: "hotseat" }
end
end
Or, for column change without creating a new one, then do either:
class AddStatusToItem < ActiveRecord::Migration
def change
change_column_default :items, :scheduler_type, "hotseat"
end
end
Or perhaps even better:
class AddStatusToItem < ActiveRecord::Migration
def change
change_column :items, :scheduler_type, :string, default: "hotseat"
end
end
Check the official RoR guide for options in column change methods.
The null: false
disallows NULL values in the DB, and, as an added benefit, it also updates so that all pre-existing DB records that were previously null is set with the default value for this field as well. You may exclude this parameter in the migration if you wish, but I found it very handy!
The canonical way in Rails 5+ is, as @Lucas Caton said:
class Item < ActiveRecord::Base
attribute :scheduler_type, :string, default: 'hotseat'
end
Here's a reusable Angular directive that will hide and show a Bootstrap modal.
app.directive("modalShow", function () {
return {
restrict: "A",
scope: {
modalVisible: "="
},
link: function (scope, element, attrs) {
//Hide or show the modal
scope.showModal = function (visible) {
if (visible)
{
element.modal("show");
}
else
{
element.modal("hide");
}
}
//Check to see if the modal-visible attribute exists
if (!attrs.modalVisible)
{
//The attribute isn't defined, show the modal by default
scope.showModal(true);
}
else
{
//Watch for changes to the modal-visible attribute
scope.$watch("modalVisible", function (newValue, oldValue) {
scope.showModal(newValue);
});
//Update the visible value when the dialog is closed through UI actions (Ok, cancel, etc.)
element.bind("hide.bs.modal", function () {
scope.modalVisible = false;
if (!scope.$$phase && !scope.$root.$$phase)
scope.$apply();
});
}
}
};
});
Usage Example #1 - this assumes you want to show the modal - you could add ng-if as a condition
<div modal-show class="modal fade"> ...bootstrap modal... </div>
Usage Example #2 - this uses an Angular expression in the modal-visible attribute
<div modal-show modal-visible="showDialog" class="modal fade"> ...bootstrap modal... </div>
Another Example - to demo the controller interaction, you could add something like this to your controller and it will show the modal after 2 seconds and then hide it after 5 seconds.
$scope.showDialog = false;
$timeout(function () { $scope.showDialog = true; }, 2000)
$timeout(function () { $scope.showDialog = false; }, 5000)
I'm late to contribute to this question - created this directive for another question here. Simple Angular Directive for Bootstrap Modal
Hope this helps.
Edited solution that will make your SplashScreen look great on all APIs including API21 to API23
If you are only targeting APIs24+ you can simply scale down your vector drawable directly in its xml file like so:
<vector xmlns:android="http://schemas.android.com/apk/res/android" xmlns:aapt="http://schemas.android.com/aapt"
android:viewportWidth="640"
android:viewportHeight="640"
android:width="240dp"
android:height="240dp">
<path
android:pathData="M320.96 55.9L477.14 345L161.67 345L320.96 55.9Z"
android:strokeColor="#292929"
android:strokeWidth="24" />
</vector>
in the code above I am rescaling a drawable I drew on a 640x640 canvas to be 240x240. then i just put it in my splash screen drawable like so and it works great:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" android:opacity="opaque"
android:paddingBottom="20dp" android:paddingRight="20dp" android:paddingLeft="20dp" android:paddingTop="20dp">
<!-- The background color, preferably the same as your normal theme -->
<item>
<shape>
<size android:height="120dp" android:width="120dp"/>
<solid android:color="@android:color/white"/>
</shape>
</item>
<!-- Your product logo - 144dp color version of your app icon -->
<item
android:drawable="@drawable/logo_vect"
android:gravity="center">
</item>
</layer-list>
my code is actually only drawing the triangle in the picture at the bottom but here you see what you can achieve with this. Resolution is finally great as opposed to the pixelated edges I was getting when using bitmap. so use a vector drawable by all means (there is a site called vectr that I used to create mine without the hasle of downloading specialized software).
EDIT in order to make it work also on API21-22-23
While the solution above works for devices runing API24+ I got really disappointed after installing my app a device running API22. I noticed that the splashscreen was again trying to fill the entire view and looking like shit. After tearing my eyebrows out for half a day I finally brute-forced a solution by sheer willpower.
you need to create a second file named exactly like the splashscreen xml (lets say splash_screen.xml) and place it into 2 folders called drawable-v22 and drawable-v21 that you will create in the res/ folder (in order to see them you have to change your project view from Android to Project). This serves to tell your phone to redirect to files placed in those folders whenever the relevant device runs an API corresponding to the -vXX suffix in the drawable folder, see this link. place the following code in the Layer-list of the splash_screen.xml file that you create in these folders:
<item>
<shape>
<size android:height="120dp" android:width="120dp"/>
<solid android:color="@android:color/white"/>
</shape>
</item>
<!-- Your product logo - 144dp color version of your app icon -->
<item android:gravity="center">
<bitmap android:gravity="center"
android:src="logo_vect"/>
</item>
For some reason for these APIs you have to wrap your drawable in a bitmap in order to make it work and jet the final result looks the same. The issue is that you have to use the aproach with the aditional drawable folders as the second version of the splash_screen.xml file will lead to your splash screen not being shown at all on devices running APIs higher than 23. You might also have to place the first version of the splash_screen.xml into drawable-v24 as android defaults to the closest drawable-vXX folder it can find for resources. hope this helps
Both are correct, but putting the input inside the label makes it much less flexible when styling with CSS.
First, a <label>
is restricted in which elements it can contain. For example, you can only put a <div>
between the <input>
and the label text, if the <input>
is not inside the <label>
.
Second, while there are workarounds to make styling easier like wrapping the inner label text with a span, some styles will be in inherited from parent elements, which can make styling more complicated.
You can use this code snippet ...
<html>
<body>
<form>
<input type="radio" name="color" value="black" required />
<input type="radio" name="color" value="white" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Specify "required" keyword in one of the select statements. If you want to change the default way of its appearance. You can follow these steps. This is just for extra info if you have any intention to modify the default behavior.
Add the following into you .css
file.
/* style all elements with a required attribute */
:required {
background: red;
}
For more information you can refer following URL.
If you are using sublime then this code may work if you add it in build as code for building system. You can use this link for more information.
{
"shell_cmd": "g++ \"${file}\" -std=c++1y -o \"${file_path}/${file_base_name}\"",
"file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",
"working_dir": "${file_path}",
"selector": "source.c, source.c++",
"variants":
[
{
"name": "Run",
"shell_cmd": "g++ \"${file}\" -std=c++1y -o \"${file_path}/${file_base_name}\" && \"${file_path}/${file_base_name}\""
}
]
}
You should be able to use Windows "UNC" paths with robocopy. For example:
robocopy \\myServer\myFolder\myFile.txt \\myOtherServer\myOtherFolder
Robocopy has the ability to recover from certain types of network hiccups automatically.
If you are on Mac run use root privilege
sudo npm install gulp-cli --global
To check if it's installed run
gulp -v
CLI version: 2.2.0 (The output)
Local version: Unknown
One way is to use DBMS_ASSERT.SQL_OBJECT_NAME :
This function verifies that the input parameter string is a qualified SQL identifier of an existing SQL object.
DECLARE
V_OBJECT_NAME VARCHAR2(30);
BEGIN
BEGIN
V_OBJECT_NAME := DBMS_ASSERT.SQL_OBJECT_NAME('tab1');
EXECUTE IMMEDIATE 'DROP TABLE tab1';
EXCEPTION WHEN OTHERS THEN NULL;
END;
END;
/
In ECMA2016 you can use the includes method. It's the cleanest way I've seen. (Supported by all major browsers)
if([1,3,12].includes(foo)) {
// ...
}
Looking at the controller, and learing a bit more about how MVC actually works, I was able to make sense of this.
My view was one of the auto-generated ones, and contained this line of code:
@Html.DropDownList("PriorityID", string.Empty)
To add html attributes, I needed to do something like this:
@Html.DropDownList("PriorityID", (IEnumerable<SelectListItem>)ViewBag.PriorityID, new { @class="dropdown" })
Thanks again to @Laurent for your help, I realise the question wasn't as clear as it could have been...
UPDATE:
A better way of doing this would be to use DropDownListFor where possible, that way you don't rely on a magic string for the name attribute
@Html.DropDownListFor(x => x.PriorityID, (IEnumerable<SelectListItem>)ViewBag.PriorityID, new { @class = "dropdown" })
You will always only get an indent error if there is actually an indent error. Double check that your final line is indented the same was as the other lines -- either with spaces or with tabs. Most likely, some of the lines had spaces (or tabs) and the other line had tabs (or spaces).
Trust in the error message -- if it says something specific, assume it to be true and figure out why.
$_ is an alias for automatic variable $PSItem (introduced in PowerShell V3.0; Usage information found here) which represents the current item from the pipe.
PowerShell (v6.0) online documentation for automatic variables is here.
If its possible uninstall wamp then run installation as administrator then change you mysql.conf file like that
<Directory "c:/wamp/apps/phpmyadmin3.5.1/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order Allow,Deny
Allow from all
Allow from all
</Directory>
Not: Before I reinstall as admin the solution above didn't work for me
Take a look at THREE.PointerLockControls
I Faced Same Problem what i did
but Same problem found than i run this artisan command
php artisan view:clear
Hope it will helpful.
SqlDependency doesn't watch the database it watches the SqlCommand you specify so if you are trying to lets say insert values into the database in 1 project and capture that event in another project it won't work because the event was from the SqlCommand from the 1º project not the database because when you create an SqlDependency you link it to a SqlCommand and only when that command from that project is used does it create a Change event.
You could use
var a = document.querySelector('a[data-a="1"]');
instead of
var a = document.querySelector('a[data-a=1]');
If you have your arguments in an array, you might be interested by the call_user_func_array
function.
If the number of arguments you want to pass depends on the length of an array, it probably means you can pack them into an array themselves -- and use that one for the second parameter of call_user_func_array
.
Elements of that array you pass will then be received by your function as distinct parameters.
For instance, if you have this function :
function test() {
var_dump(func_num_args());
var_dump(func_get_args());
}
You can pack your parameters into an array, like this :
$params = array(
10,
'glop',
'test',
);
And, then, call the function :
call_user_func_array('test', $params);
This code will the output :
int 3
array
0 => int 10
1 => string 'glop' (length=4)
2 => string 'test' (length=4)
ie, 3 parameters ; exactly like iof the function was called this way :
test(10, 'glop', 'test');
Actually there is a way, you need to have permissions of course for doing this ...
SET @sql = CONCAT('SELECT ', (SELECT REPLACE(GROUP_CONCAT(COLUMN_NAME), '<columns_to_omit>,', '') FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '<table>' AND TABLE_SCHEMA = '<database>'), ' FROM <table>');
PREPARE stmt1 FROM @sql;
EXECUTE stmt1;
Replacing <table>, <database> and <columns_to_omit>
I have an easier solution using fs.readFileSync(./my_local_image_path.jpg)
This is for reading images from Azure Cognative Services's Vision API
const subscriptionKey = 'your_azure_subscrition_key';
const uriBase = // **MUST change your location (mine is 'eastus')**
'https://eastus.api.cognitive.microsoft.com/vision/v2.0/analyze';
// Request parameters.
const params = {
'visualFeatures': 'Categories,Description,Adult,Faces',
'maxCandidates': '2',
'details': 'Celebrities,Landmarks',
'language': 'en'
};
const options = {
uri: uriBase,
qs: params,
body: fs.readFileSync(./my_local_image_path.jpg),
headers: {
'Content-Type': 'application/octet-stream',
'Ocp-Apim-Subscription-Key' : subscriptionKey
}
};
request.post(options, (error, response, body) => {
if (error) {
console.log('Error: ', error);
return;
}
let jsonString = JSON.stringify(JSON.parse(body), null, ' ');
body = JSON.parse(body);
if (body.code) // err
{
console.log("AZURE: " + body.message)
}
console.log('Response\n' + jsonString);
On pure JS:
let select = document.getElementById("select_id")
let to_hide = select[select.selectedIndex];
to_hide.setAttribute('hidden', 'hidden');
to unhide just
to_hide.removeAttr('hidden');
or
to_hide.hidden = true; // to hide
to_hide.hidden = false; // to unhide
Try adding an event listener for clicks:
document.getElementById('button').addEventListener("click", function() {
alert("You clicked me");
}?);?
Using addEventListener
is probably a better idea then setting onclick
- onclick
can easily be overwritten by another piece of code.
You can use a variable to store whether or not the button has been clicked before:
var clicked = false
document.getElementById('button').addEventListener("click", function() {
clicked = true
}?);?
If anyone would like the answer in Swift :
var blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark) // Change .Dark into .Light if you'd like.
var blurView = UIVisualEffectView(effect: blurEffect)
blurView.frame = theImage.bounds // 'theImage' is an image. I think you can apply this to the view too!
Update :
As of now, it's available under the IB so you don't have to code anything for it :)
To clarify one point in @EdChum's answer, per the documentation, you can include the object columns by using df.describe(include='all')
. It won't provide many statistics, but will provide a few pieces of info, including count, number of unique values, top value. This may be a new feature, I don't know as I am a relatively new user.
Try this:
mynewlist = [s for s in mylist if s.isdigit()]
From the docs:
str.isdigit()
Return true if all characters in the string are digits and there is at least one character, false otherwise.
For 8-bit strings, this method is locale-dependent.
As noted in the comments, isdigit()
returning True
does not necessarily indicate that the string can be parsed as an int via the int()
function, and it returning False
does not necessarily indicate that it cannot be. Nevertheless, the approach above should work in your case.
Same 404 response I got after service executed with the below code
@Controller
@RequestMapping("/duecreate/v1.0")
public class DueCreateController {
}
Response:
{
"timestamp": 1529692263422,
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/duecreate/v1.0/status"
}
after changing it to below code I received proper response
@RestController
@RequestMapping("/duecreate/v1.0")
public class DueCreateController {
}
Response:
{
"batchId": "DUE1529673844630",
"batchType": null,
"executionDate": null,
"status": "OPEN"
}
With C#6.0 you also have a new way of formatting date when using string interpolation e.g.
$"{DateTime.Now:yyyy-MM-dd HH:mm:ss}"
Can't say its any better, but it is slightly cleaner if including the formatted DateTime in a longer string.
I had to do this in a VB.Net 2.0 Web Service. I ended up specifying the parameters as strings, then converting them to whatever I needed. An optional parameter was specified with an empty string. Not the cleanest solution, but it worked. Just be careful that you catch all the exceptions that can occur.
based on accepted answer
$output = some_function();
echo $output;
if it results array then use json_encode it will result json array which is supportable by javascript
$output = some_function();
echo json_encode($output);
If someone wants to stop execution after you echo some result use exit method of php. It will work like return keyword
$output = some_function();
echo $output;
exit;
The only thing that a computer can store is bytes.
To store anything in a computer, you must first encode it, i.e. convert it to bytes. For example:
MP3
, WAV
, etc.PNG
, JPEG
, etc. ASCII
, UTF-8
, etc.MP3
, WAV
, PNG
, JPEG
, ASCII
and UTF-8
are examples of encodings. An encoding is a format to represent audio, images, text, etc in bytes.
In Python, a byte string is just that: a sequence of bytes. It isn't human-readable. Under the hood, everything must be converted to a byte string before it can be stored in a computer.
On the other hand, a character string, often just called a "string", is a sequence of characters. It is human-readable. A character string can't be directly stored in a computer, it has to be encoded first (converted into a byte string). There are multiple encodings through which a character string can be converted into a byte string, such as ASCII
and UTF-8
.
'I am a string'.encode('ASCII')
The above Python code will encode the string 'I am a string'
using the encoding ASCII
. The result of the above code will be a byte string. If you print it, Python will represent it as b'I am a string'
. Remember, however, that byte strings aren't human-readable, it's just that Python decodes them from ASCII
when you print them. In Python, a byte string is represented by a b
, followed by the byte string's ASCII
representation.
A byte string can be decoded back into a character string, if you know the encoding that was used to encode it.
b'I am a string'.decode('ASCII')
The above code will return the original string 'I am a string'
.
Encoding and decoding are inverse operations. Everything must be encoded before it can be written to disk, and it must be decoded before it can be read by a human.
First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.
For example,
> z <- factor(letters[c(3, 2, 3, 4)])
# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d
# internal structure of factor
> unclass(z)
[1] 2 1 2 3
attr(,"levels")
[1] "b" "c" "d"
here, z
has 4 elements.
The index is 2, 1, 2, 3
in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.
Then, as.numeric
converts simply the index part of factor into numeric.
as.character
handles the index and levels, and generates character vector expressed by its level.
?as.numeric
says that Factors are handled by the default method.
Another shorthand to (@maudulus's answer) to remove {maxFractionDigits}
since it's optional.
You can use {{numberExample | number : '1.2'}}
What does it mean for the ranges to overlap? It means there exists some number C which is in both ranges, i.e.
x1 <= C <= x2
and
y1 <= C <= y2
Now, if we are allowed to assume that the ranges are well-formed (so that x1 <= x2 and y1 <= y2) then it is sufficient to test
x1 <= y2 && y1 <= x2
A little editing about the code of Schnalle
<?php
$ids = array(1, 2, 3, 7, 8, 9);
$inQuery = implode(',', array_fill(0, count($ids)-1, '?'));
$db = new PDO(...);
$stmt = $db->prepare(
'SELECT *
FROM table
WHERE id IN(' . $inQuery . ')'
);
foreach ($ids as $k => $id)
$stmt->bindValue(($k+1), $id);
$stmt->execute();
?>
//implode(',', array_fill(0, count($ids)-1), '?'));
//'?' this should be inside the array_fill
//$stmt->bindValue(($k+1), $in);
// instead of $in, it should be $id
The answer is in the documentation for bindParam
:
Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.
And execute
call PDOStatement::bindParam() to bind PHP variables to the parameter markers: bound variables pass their value as input and receive the output value, if any, of their associated parameter markers
Example:
$value = 'foo';
$s = $dbh->prepare('SELECT name FROM bar WHERE baz = :baz');
$s->bindParam(':baz', $value); // use bindParam to bind the variable
$value = 'foobarbaz';
$s->execute(); // executed with WHERE baz = 'foobarbaz'
or
$value = 'foo';
$s = $dbh->prepare('SELECT name FROM bar WHERE baz = :baz');
$s->bindValue(':baz', $value); // use bindValue to bind the variable's value
$value = 'foobarbaz';
$s->execute(); // executed with WHERE baz = 'foo'
I configured the app.config
with the tool for EntLib configuration and set up my LoggingConfiguration
block. Then I copied this into the DotNetConfig.xsd
. Of course, it does not cover all attributes, only the ones I added but it does not display those annoying info messages anymore.
<xs:element name="loggingConfiguration">
<xs:complexType>
<xs:sequence>
<xs:element name="listeners">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="add">
<xs:complexType>
<xs:attribute name="fileName" type="xs:string" use="required" />
<xs:attribute name="footer" type="xs:string" use="required" />
<xs:attribute name="formatter" type="xs:string" use="required" />
<xs:attribute name="header" type="xs:string" use="required" />
<xs:attribute name="rollFileExistsBehavior" type="xs:string" use="required" />
<xs:attribute name="rollInterval" type="xs:string" use="required" />
<xs:attribute name="rollSizeKB" type="xs:unsignedByte" use="required" />
<xs:attribute name="timeStampPattern" type="xs:string" use="required" />
<xs:attribute name="listenerDataType" type="xs:string" use="required" />
<xs:attribute name="traceOutputOptions" type="xs:string" use="required" />
<xs:attribute name="filter" type="xs:string" use="required" />
<xs:attribute name="type" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="formatters">
<xs:complexType>
<xs:sequence>
<xs:element name="add">
<xs:complexType>
<xs:attribute name="template" type="xs:string" use="required" />
<xs:attribute name="type" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="logFilters">
<xs:complexType>
<xs:sequence>
<xs:element name="add">
<xs:complexType>
<xs:attribute name="enabled" type="xs:boolean" use="required" />
<xs:attribute name="type" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="categorySources">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="add">
<xs:complexType>
<xs:sequence>
<xs:element name="listeners">
<xs:complexType>
<xs:sequence>
<xs:element name="add">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="switchValue" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="specialSources">
<xs:complexType>
<xs:sequence>
<xs:element name="allEvents">
<xs:complexType>
<xs:attribute name="switchValue" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
<xs:element name="notProcessed">
<xs:complexType>
<xs:attribute name="switchValue" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
<xs:element name="errors">
<xs:complexType>
<xs:sequence>
<xs:element name="listeners">
<xs:complexType>
<xs:sequence>
<xs:element name="add">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="switchValue" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="tracingEnabled" type="xs:boolean" use="required" />
<xs:attribute name="defaultCategory" type="xs:string" use="required" />
<xs:attribute name="logWarningsWhenNoCategoriesMatch" type="xs:boolean" use="required" />
</xs:complexType>
</xs:element>
Show file and track error
systemctl status nginx.service
You can access sequence elements with arr.0 arr.1 and so on. See The Django template system chapter of the django book for more information.
You can add or increase the day of week for the following example and hope this will helpful for you.Lets see....
//Current date
var currentDate = new Date();
//to set Bangladeshi date need to add hour 6
currentDate.setUTCHours(6);
//here 2 is day increament for the date and you can use -2 for decreament day
currentDate.setDate(currentDate.getDate() +parseInt(2));
//formatting date by mm/dd/yyyy
var dateInmmddyyyy = currentDate.getMonth() + 1 + '/' + currentDate.getDate() + '/' + currentDate.getFullYear();
Updating this post (2015) : unbind/bind should not be used anymore with jQuery 1.7+. Use instead the function off(). Example :
$('#id').off('click');
$('#id').click(function(){
myNewFunction();
//Other code etc.
});
Be sure that you call a non-parameter function in .click, otherwise it will be ignored.
You can remove the warning by adding the below code in <intent-filter>
inside <activity>
<action android:name="android.intent.action.VIEW" />
found a way at http://www.dotnetspider.com/resources/21866-Count-pages-PDF-file.aspx this does not require purchase of a pdf library
I found very nice solution. Microsoft released a beta version of Entity Framework Power Tools: Entity Framework Power Tools Beta 2
There you can generate POCO classes, derived DbContext and Code First mapping for an existing database in some clicks. It is very nice!
After installation some context menu options would be added to your Visual Studio.
Right-click on a C# project. Choose Entity Framework-> Reverse Engineer Code First (Generates POCO classes, derived DbContext and Code First mapping for an existing database):
Then choose your database and click OK. That's all! It is very easy.
listview.setOnItemClickListener(new OnItemClickListener(){
//setting onclick to items in the listview.
@Override
public void onItemClick(AdapterView<?>adapter,View v, int position){
Intent intent;
switch(position){
// case 0 is the first item in the listView.
case 0:
intent = new Intent(Activity.this,firstActivity.class);
break;
//case 1 is the second item in the listView.
case 1:
intent = new Intent(Activity.this,secondActivity.class);
break;
case 2:
intent = new Intent(Activity.this,thirdActivity.class);
break;
//add more if you have more items in listView
startActivity(intent);
}
});
Have you tried using Timestamp.valueOf(String)
? It looks like it should do almost exactly what you want - you just need to change the separator between your date and time to a space, and the ones between hours and minutes, and minutes and hours, to colons:
import java.sql.*;
public class Test {
public static void main(String[] args) {
String text = "2011-10-02 18:48:05.123456";
Timestamp ts = Timestamp.valueOf(text);
System.out.println(ts.getNanos());
}
}
Assuming you've already validated the string length, this will convert to the right format:
static String convertSeparators(String input) {
char[] chars = input.toCharArray();
chars[10] = ' ';
chars[13] = ':';
chars[16] = ':';
return new String(chars);
}
Alternatively, parse down to milliseconds by taking a substring and using Joda Time or SimpleDateFormat
(I vastly prefer Joda Time, but your mileage may vary). Then take the remainder of the string as another string and parse it with Integer.parseInt
. You can then combine the values pretty easily:
Date date = parseDateFromFirstPart();
int micros = parseJustLastThreeDigits();
Timestamp ts = new Timestamp(date.getTime());
ts.setNanos(ts.getNanos() + micros * 1000);
The JDK provides
Collections.unmodifiableXXX
methods, but in our opinion, these can be unwieldy and verbose; unpleasant to use everywhere you want to make defensive copies unsafe: the returned collections are only truly immutable if nobody holds a reference to the original collection inefficient: the data structures still have all the overhead of mutable collections, including concurrent modification checks, extra space in hash tables, etc.
Based on the accepted answer and two other questions 1, 2 I have assembled the following query:
SELECT
QUOTENAME(t.name) AS TableName,
QUOTENAME(i.name) AS IndexName,
i.is_primary_key,
i.is_unique,
i.is_unique_constraint,
STUFF(REPLACE(REPLACE((
SELECT QUOTENAME(c.name) + CASE WHEN ic.is_descending_key = 1 THEN ' DESC' ELSE '' END AS [data()]
FROM sys.index_columns AS ic
INNER JOIN sys.columns AS c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
WHERE ic.object_id = i.object_id AND ic.index_id = i.index_id AND ic.is_included_column = 0
ORDER BY ic.key_ordinal
FOR XML PATH
), '<row>', ', '), '</row>', ''), 1, 2, '') AS KeyColumns,
STUFF(REPLACE(REPLACE((
SELECT QUOTENAME(c.name) AS [data()]
FROM sys.index_columns AS ic
INNER JOIN sys.columns AS c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
WHERE ic.object_id = i.object_id AND ic.index_id = i.index_id AND ic.is_included_column = 1
ORDER BY ic.index_column_id
FOR XML PATH
), '<row>', ', '), '</row>', ''), 1, 2, '') AS IncludedColumns,
u.user_seeks,
u.user_scans,
u.user_lookups,
u.user_updates
FROM sys.tables AS t
INNER JOIN sys.indexes AS i ON t.object_id = i.object_id
LEFT JOIN sys.dm_db_index_usage_stats AS u ON i.object_id = u.object_id AND i.index_id = u.index_id
WHERE t.is_ms_shipped = 0
AND i.type <> 0
This query returns results such as below which shows the list of indexes, their columns and usage. Very helpful in determining which index is performing better than others:
FULL is probably referring to a full table scan, which means that no indexes are in use. This is usually indicating that something is wrong, unless the query is supposed to use all the rows in a table.
Cost is a number that signals the sum of the different loads, processor, memory, disk, IO, and high numbers are typically bad. The numbers are added up when moving to the root of the plan, and each branch should be examined to locate the bottlenecks.
You may also want to query v$sql and v$session to get statistics about SQL statements, and this will have detailed metrics for all kind of resources, timings and executions.
There's a jQuery Timer plugin you may want to try
Use @media
queries. They serve this exact purpose. Here's an example how they work:
@media (max-width: 800px) {
/* CSS that should be displayed if width is equal to or less than 800px goes here */
}
This would work only on devices whose width is equal to or less than 800px.
Read up more about media queries on the Mozilla Developer Network.
Also, you can do this:
(this.DNATranscriber as any)[character];
Edit.
It's HIGHLY recommended that you cast the object with the proper type instead of any
. Casting an object as any
only help you to avoid type errors when compiling typescript but it doesn't help you to keep your code type-safe.
E.g.
interface DNA {
G: "C",
C: "G",
T: "A",
A: "U"
}
And then you cast it like this:
(this.DNATranscriber as DNA)[character];
To generate the DDL script for an entire SCHEMA i.e. a USER, you could use dbms_metadata.get_ddl.
Execute the following script in SQL*Plus created by Tim Hall:
Provide the username when prompted.
set long 20000 longchunksize 20000 pagesize 0 linesize 1000 feedback off verify off trimspool on
column ddl format a1000
begin
dbms_metadata.set_transform_param (dbms_metadata.session_transform, 'SQLTERMINATOR', true);
dbms_metadata.set_transform_param (dbms_metadata.session_transform, 'PRETTY', true);
end;
/
variable v_username VARCHAR2(30);
exec:v_username := upper('&1');
select dbms_metadata.get_ddl('USER', u.username) AS ddl
from dba_users u
where u.username = :v_username
union all
select dbms_metadata.get_granted_ddl('TABLESPACE_QUOTA', tq.username) AS ddl
from dba_ts_quotas tq
where tq.username = :v_username
and rownum = 1
union all
select dbms_metadata.get_granted_ddl('ROLE_GRANT', rp.grantee) AS ddl
from dba_role_privs rp
where rp.grantee = :v_username
and rownum = 1
union all
select dbms_metadata.get_granted_ddl('SYSTEM_GRANT', sp.grantee) AS ddl
from dba_sys_privs sp
where sp.grantee = :v_username
and rownum = 1
union all
select dbms_metadata.get_granted_ddl('OBJECT_GRANT', tp.grantee) AS ddl
from dba_tab_privs tp
where tp.grantee = :v_username
and rownum = 1
union all
select dbms_metadata.get_granted_ddl('DEFAULT_ROLE', rp.grantee) AS ddl
from dba_role_privs rp
where rp.grantee = :v_username
and rp.default_role = 'YES'
and rownum = 1
union all
select to_clob('/* Start profile creation script in case they are missing') AS ddl
from dba_users u
where u.username = :v_username
and u.profile <> 'DEFAULT'
and rownum = 1
union all
select dbms_metadata.get_ddl('PROFILE', u.profile) AS ddl
from dba_users u
where u.username = :v_username
and u.profile <> 'DEFAULT'
union all
select to_clob('End profile creation script */') AS ddl
from dba_users u
where u.username = :v_username
and u.profile <> 'DEFAULT'
and rownum = 1
/
set linesize 80 pagesize 14 feedback on trimspool on verify on
this looks like PHP to me. I'll delete if it's some other language.
Simply unset($arr[1]);
Your best options are CreateProcess() or CreateThread(). There is more information on porting here.
The regular expression you was looking for is: /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*\[\]"\';:_\-<>\., =\+\/\\]).{8,}$/u
.
Example and test: http://regexr.com/3fhr4
On a 64-bit system you have to make sure that both the Tomcat application and the JDK are the same architecture: either both are x86 or x64.
In case you want to change the Tomcat instance to x64 you might have to download the tomcat8.exe
or tomcat9.exe
and the tcnative-1.dll
with the appropriate x64 versions. You can get those at http://svn.apache.org/viewvc/tomcat/.
Alternatively you can point Tomcat to the x86 JDK by changing the Java Virtual Machine path in the Tomcat config.
<div id="normal>text..</div>
<div id="small1" class="smallDiv"></div>
<div id="small2" class="smallDiv"></div>
<div id="small3" class="smallDiv"></div>
css:
.smallDiv { height: 150px; width: 150px; }
The datetime.now()
is evaluated when the class is created, not when new record is being added to the database.
To achieve what you want define this field as:
date = models.DateTimeField(auto_now_add=True)
This way the date
field will be set to current date for each new record.
Your code below is zooming the map to fit the specified bounds:
addMarker(27.703402,85.311668,'New Road');
center = bounds.getCenter();
map.fitBounds(bounds);
If you only have 1 marker and add it to the bounds, that results in the closest zoom possible:
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
}
If you keep track of the number of markers you have "added" to the map (or extended the bounds with), you can only call fitBounds if that number is greater than one. I usually push the markers into an array (for later use) and test the length of that array.
If you will only ever have one marker, don't use fitBounds. Call setCenter
, setZoom
with the marker position and your desired zoom level.
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
map.setCenter(pt);
map.setZoom(your desired zoom);
}
html,
body,
#map {
height: 100%;
width: 100%;
padding: 0;
margin: 0;
}
_x000D_
<html>
<head>
<script src="http://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk" type="text/javascript"></script>
<script type="text/javascript">
var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/blue.png", new google.maps.Size(32, 32), new google.maps.Point(0, 0), new google.maps.Point(16, 32));
var center = null;
var map = null;
var currentPopup;
var bounds = new google.maps.LatLngBounds();
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
map.setCenter(pt);
map.setZoom(5);
var marker = new google.maps.Marker({
position: pt,
icon: icon,
map: map
});
var popup = new google.maps.InfoWindow({
content: info,
maxWidth: 300
});
google.maps.event.addListener(marker, "click", function() {
if (currentPopup != null) {
currentPopup.close();
currentPopup = null;
}
popup.open(map, marker);
currentPopup = popup;
});
google.maps.event.addListener(popup, "closeclick", function() {
map.panTo(center);
currentPopup = null;
});
}
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(0, 0),
zoom: 1,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
}
});
addMarker(27.703402, 85.311668, 'New Road');
// center = bounds.getCenter();
// map.fitBounds(bounds);
}
</script>
</head>
<body onload="initMap()" style="margin:0px; border:0px; padding:0px;">
<div id="map"></div>
</body>
</html>
_x000D_
You could also try putting your code in the Activated event of the form, if you want it to occur, just when the form is activated. You would need to put in a boolean "has executed" check though if it is only supposed to run on the first activation.
Did you check this question?
May be possible solution is:
rm -rf node_modules/
npm install
Here is a solution that does not require functions to get an accurate count for each table:
select table_schema,
table_name,
(xpath('/row/cnt/text()', xml_count))[1]::text::int as row_count
from (
select table_name, table_schema,
query_to_xml(format('select count(*) as cnt from %I.%I', table_schema, table_name), false, true, '') as xml_count
from information_schema.tables
where table_schema = 'public' --<< change here for the schema you want
) t
query_to_xml
will run the passed SQL query and return an XML with the result (the row count for that table). The outer xpath()
will then extract the count information from that xml and convert it to a number
The derived table is not really necessary, but makes the xpath()
a bit easier to understand - otherwise the whole query_to_xml()
would need to be passed to the xpath()
function.
var datatable_jquery_script = document.createElement("script");
datatable_jquery_script.src = "vendor/datatables/jquery.dataTables.min.js";
document.body.appendChild(datatable_jquery_script);
setTimeout(function(){
var datatable_bootstrap_script = document.createElement("script");
datatable_bootstrap_script.src = "vendor/datatables/dataTables.bootstrap4.min.js";
document.body.appendChild(datatable_bootstrap_script);
},100);
I used setTimeOut to make sure datatables.min.js loads first. I inspected the waterfall loading of each, bootstrap4.min.js always loads first.
Python dictionaries are unordered. If you want an ordered dictionary, use collections.OrderedDict
In your case, sort the dict by key before plotting,
import matplotlib.pylab as plt
lists = sorted(d.items()) # sorted by key, return a list of tuples
x, y = zip(*lists) # unpack a list of pairs into two tuples
plt.plot(x, y)
plt.show()
My dependencies;
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:25.1.0'
//RecyclerView dependency
compile 'com.android.support:recyclerview-v7:25.1.0'
// Instrumentation dependencies use androidTestCompile
// (as opposed to testCompile for local unit tests run in the JVM)
androidTestCompile 'junit:junit:4.12'
androidTestCompile 'com.android.support:support-annotations:25.1.0'
androidTestCompile 'com.android.support.test:runner:0.5'
androidTestCompile 'com.android.support.test:rules:0.5'
}
I added only compile 'com.android.support:recyclerview-v7:25.1.0'. The important thing is to add RecycleView dependency which is as the same version as appcompat
In python3, has_key(key)
is replaced by __contains__(key)
Tested in python3.7:
a = {'a':1, 'b':2, 'c':3}
print(a.__contains__('a'))
In Recycler Layout manager the second parameter is spanCount increase or decrease in span count will change number of elements show on your screen
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 2, //The number of Columns in the grid
,GridLayoutManager.HORIZONTAL,false);
recyclerView.setLayoutManager(mLayoutManager);
You can always do:
for k in sorted(d.keys()):
print d[k]
This will give you a consistently sorted (with respect to builtin.hash() I guess) set of keys you can process on if the sorting has any meaning to you. That means for example numeric types are sorted consistently even if you expand the dictionary.
EXAMPLE
# lets create a simple dictionary
d = {1:1, 2:2, 3:3, 4:4, 10:10, 100:100}
print d.keys()
print sorted(d.keys())
# add some other stuff
d['peter'] = 'peter'
d['parker'] = 'parker'
print d.keys()
print sorted(d.keys())
# some more stuff, numeric of different type, this will "mess up" the keys set order
d[0.001] = 0.001
d[3.14] = 'pie'
d[2.71] = 'apple pie'
print d.keys()
print sorted(d.keys())
Note that the dictionary is sorted when printed. But the key set is essentially a hashmap!
If installed Django using python setup.py install
python -c "import sys; sys.path = sys.path[1:]; import django; print(django.__path__)"
find the directory you need to remove, delete it
If you are getting a timeout while on the table designer, change the "Transaction time-out after" value under Tools --> Options --> Designers --> Table and Database Designers
This will get rid of this message: "Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding."
tried to format my answer, but couldn't.Please stackoverflow team, why posting answer is so hard.
neverthless,
answer:
git fetch origin
git status (you'll see result like "Your branch is behind 'origin/master' by 9 commits")
to update to remote changes : git pull
VarArgs and overloading have been mentioned. Another option is a Bloch Builder pattern, which would look something like this:
MyObject my = new MyObjectBuilder().setParam1(value)
.setParam3(otherValue)
.setParam6(thirdValue)
.build();
Although that pattern would be most appropriate for when you need optional parameters in a constructor.
Exceding the maximum value of a long doesnt throw an exception, instead it cicles back. If you do this:
Long.MAX_VALUE + 1
you will notice that the result is the equivalent to Long.MIN_VALUE.
From here: java number exceeds long.max_value - how to detect?
Try this, it should work for what you need:
editText.setOnEditorActionListener(new EditText.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
//do here your stuff f
return true;
}
return false;
}
});
Chrome appears to have bug renegotiating the device authentication. You can try disabling USB Debugging and enabling it again. Sometimes you'll get a pop-up asking you to trust your computer key again.
Or you can go to your Android SDK and run adb devices
which will force a renegotiation.
After either (or both), Chrome should start working.
My comments on Renaud Bompuis's answer messed up.
Actually, you can use late binding, and the reference to the 11.0 object library is not required.
The following code will work without any references:
Dim f As Object
Set f = Application.FileDialog(3)
f.AllowMultiSelect = True
f.Show
MsgBox "file choosen = " & f.SelectedItems.Count
Note that the above works well in the runtime also.
A quick update to Michael's excellent answer above.
For Rails 4.0+ you need to put your sort in a block like this:
class Book < ActiveRecord::Base
default_scope { order('created_at DESC') }
end
Notice that the order statement is placed in a block denoted by the curly braces.
They changed it because it was too easy to pass in something dynamic (like the current time). This removes the problem because the block is evaluated at runtime. If you don't use a block you'll get this error:
Support for calling #default_scope without a block is removed. For example instead of
default_scope where(color: 'red')
, please usedefault_scope { where(color: 'red') }
. (Alternatively you can just redefine self.default_scope.)
As @Dan mentions in his comment below, you can do a more rubyish syntax like this:
class Book < ActiveRecord::Base
default_scope { order(created_at: :desc) }
end
or with multiple columns:
class Book < ActiveRecord::Base
default_scope { order({begin_date: :desc}, :name) }
end
Thanks @Dan!
When you do this,
while((inputLine = buff_read.readLine())!= null){
System.out.println(inputLine);
}
You consume everything in instream, so instream is empty. Now when try to do this,
Document doc = builder.parse(instream);
The parsing will fail, because you have passed it an empty stream.
I give it a ton of memory (add a -Xmx
switch to the command that starts it) and try to avoid quitting and restarting it- I find the worst delays are on startup, so giving it lots of RAM lets me keep going longer before it crashes out.
If you want to import all Material modules, create your own module i.e. material.module.ts
and do something like the following:
import { NgModule } from '@angular/core';_x000D_
import * as MATERIAL_MODULES from '@angular/material';_x000D_
_x000D_
export function mapMaterialModules() {_x000D_
return Object.keys(MATERIAL_MODULES).filter((k) => {_x000D_
let asset = MATERIAL_MODULES[k];_x000D_
return typeof asset == 'function'_x000D_
&& asset.name.startsWith('Mat')_x000D_
&& asset.name.includes('Module');_x000D_
}).map((k) => MATERIAL_MODULES[k]);_x000D_
}_x000D_
const modules = mapMaterialModules();_x000D_
_x000D_
@NgModule({_x000D_
imports: modules,_x000D_
exports: modules_x000D_
})_x000D_
export class MaterialModule { }
_x000D_
Then import the module into your app.module.ts
This worked great I just add the -a option to ping to resolve the hostname. Thanks https://stackoverflow.com/users/4447323/wombat
@echo off setlocal enabledelayedexpansion set OUTPUT_FILE=result.csv
>nul copy nul %OUTPUT_FILE%
echo HOSTNAME,LONGNAME,IPADDRESS,STATE >%OUTPUT_FILE%
for /f %%i in (testservers.txt) do (
set SERVER_ADDRESS_I=UNRESOLVED
set SERVER_ADDRESS_L=UNRESOLVED
for /f "tokens=1,2,3" %%x in ('ping -n 1 -a %%i ^&^& echo SERVER_IS_UP') do (
if %%x==Pinging set SERVER_ADDRESS_L=%%y
if %%x==Pinging set SERVER_ADDRESS_I=%%z
if %%x==SERVER_IS_UP (set SERVER_STATE=UP) else (set SERVER_STATE=DOWN)
)
echo %%i [!SERVER_ADDRESS_L::=!] !SERVER_ADDRESS_I::=! is !SERVER_STATE!
echo %%i,!SERVER_ADDRESS_L::=!,!SERVER_ADDRESS_I::=!,!SERVER_STATE! >>%OUTPUT_FILE%
)
The PGADMIN4, version 30, can plot the ERD. Just click on the database with the mouse right-button and then select ERD(beta).
For a single style attribute, you can use the following syntax:
<div [style.background-color]="style1 ? 'red' : (style2 ? 'blue' : null)">
I assumed that the background color should not be set if neither style1
nor style2
is true
.
Since the question title mentions ngStyle
, here is the equivalent syntax with that directive:
<div [ngStyle]="{'background-color': style1 ? 'red' : (style2 ? 'blue' : null) }">
Yes. There are methods on the String itself for this.
Note that the result depends on the Locale the JVM is using. Beware, locales is an art in itself.
var pause_menu = {
pause_button : { someProperty : "prop1", someOther : "prop2" },
resume_button : { resumeProp : "prop", resumeProp2 : false },
quit_button : false
};
then:
pause_menu.pause_button.someProperty //evaluates to "prop1"
etc etc.
Bit of an amalgamation of the stuff above. But here's my crack at it.
def print_caller_name(stack_size=3):
def wrapper(fn):
def inner(*args, **kwargs):
import inspect
stack = inspect.stack()
modules = [(index, inspect.getmodule(stack[index][0]))
for index in reversed(range(1, stack_size))]
module_name_lengths = [len(module.__name__)
for _, module in modules]
s = '{index:>5} : {module:^%i} : {name}' % (max(module_name_lengths) + 4)
callers = ['',
s.format(index='level', module='module', name='name'),
'-' * 50]
for index, module in modules:
callers.append(s.format(index=index,
module=module.__name__,
name=stack[index][3]))
callers.append(s.format(index=0,
module=fn.__module__,
name=fn.__name__))
callers.append('')
print('\n'.join(callers))
fn(*args, **kwargs)
return inner
return wrapper
Use:
@print_caller_name(4)
def foo():
return 'foobar'
def bar():
return foo()
def baz():
return bar()
def fizz():
return baz()
fizz()
output is
level : module : name
--------------------------------------------------
3 : None : fizz
2 : None : baz
1 : None : bar
0 : __main__ : foo
Try this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TableRow >
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:layout_gravity="center_horizontal" >
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="1"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="2"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
</TableRow>
</TableLayout>
</FrameLayout>
</LinearLayout>
For future reference, you can get help for any command by using the /?
switch, which should explain what switches do what.
According to the set /?
screen, the format for set /p
is SET /P variable=[promptString]
which would indicate that the p in /p
is "prompt." It just prints in your example because <nul
passes in a nul character which immediately ends the prompt so it just acts like it's printing. It's still technically prompting for input, it's just immediately receiving it.
/L
in for /L
generates a List of numbers.
From ping /?
:
Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]
[-r count] [-s count] [[-j host-list] | [-k host-list]]
[-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name
Options:
-t Ping the specified host until stopped.
To see statistics and continue - type Control-Break;
To stop - type Control-C.
-a Resolve addresses to hostnames.
-n count Number of echo requests to send.
-l size Send buffer size.
-f Set Don't Fragment flag in packet (IPv4-only).
-i TTL Time To Live.
-v TOS Type Of Service (IPv4-only. This setting has been deprecated
and has no effect on the type of service field in the IP Header).
-r count Record route for count hops (IPv4-only).
-s count Timestamp for count hops (IPv4-only).
-j host-list Loose source route along host-list (IPv4-only).
-k host-list Strict source route along host-list (IPv4-only).
-w timeout Timeout in milliseconds to wait for each reply.
-R Use routing header to test reverse route also (IPv6-only).
-S srcaddr Source address to use.
-4 Force using IPv4.
-6 Force using IPv6.
Considering you want to check for ASCII Alphanumeric characters, Try this:
"^[a-zA-Z0-9]*$"
. Use this RegEx in String.matches(Regex)
, it will return true if the string is alphanumeric, else it will return false.
public boolean isAlphaNumeric(String s){
String pattern= "^[a-zA-Z0-9]*$";
return s.matches(pattern);
}
If it will help, read this for more details about regex: http://www.vogella.com/articles/JavaRegularExpressions/article.html
This is a solution that means that as you add new stored procedures to the schema, users can execute them without having to call grant execute on the new stored procedure:
IF EXISTS (SELECT * FROM sys.database_principals WHERE name = N'asp_net')
DROP USER asp_net
GO
IF EXISTS (SELECT * FROM sys.database_principals
WHERE name = N'db_execproc' AND type = 'R')
DROP ROLE [db_execproc]
GO
--Create a database role....
CREATE ROLE [db_execproc] AUTHORIZATION [dbo]
GO
--...with EXECUTE permission at the schema level...
GRANT EXECUTE ON SCHEMA::dbo TO db_execproc;
GO
--http://www.patrickkeisler.com/2012/10/grant-execute-permission-on-all-stored.html
--Any stored procedures that are created in the dbo schema can be
--executed by users who are members of the db_execproc database role
--...add a user e.g. for the NETWORK SERVICE login that asp.net uses
CREATE USER asp_net
FOR LOGIN [NT AUTHORITY\NETWORK SERVICE]
WITH DEFAULT_SCHEMA=[dbo]
GO
--...and add them to the roles you need
EXEC sp_addrolemember N'db_execproc', 'asp_net';
EXEC sp_addrolemember N'db_datareader', 'asp_net';
EXEC sp_addrolemember N'db_datawriter', 'asp_net';
GO
Reference: Grant Execute Permission on All Stored Procedures
int.TryPasrse() Methode is the best way so if the value was string you will never have an exception , instead of the TryParse Methode return to you bool value so you will know if the parse operation succeeded or failed
string yourText = "2";
int num;
bool res = int.TryParse(yourText, out num);
if (res == true)
{
// the operation succeeded and you got the number in num parameter
}
else
{
// the operation failed
}
You can use the strong
element in html, which is great semantically (also good for screen readers etc.), which typically renders as bold text:
See here, some <strong>emphasized text</strong>.
_x000D_
Or you can use the font-weight
css property to style any element's text as bold:
span { font-weight: bold; }
_x000D_
<p>This is a paragraph of <span>bold text</span>.</p>
_x000D_
This may be helpful for all using tools for GIT
Command
Switch branch - it will move your changes to new-branch. Then you can commit changes.
$ git checkout -b <new-branch>
TortoiseGIT
Right-click on your repository and then use TortoiseGit->Switch/Checkout
SourceTree
Use the "Checkout" button to switch branch. You will see the "checkout" button at the top after clicking on a branch. Changes from the current branch will be applied automatically. Then you can commit them.
Try using pip -V
(notice capital V)
If you are running the virtual env. it'll show the path to the env.'s location.
Attribute_Brands is a named range that should contain your list items. Use the drop down to the left of the formula bar to jump to the named range, then edit it. If you add or remove items you will need to adjust the range the named range covers.
For some kind of reason my NULL values where of data length 8. That is why none of the abovementioned seemed to work. If you encounter the same problem, use the following code:
--Check the length of your NULL values
SELECT DATALENGTH(COLUMN) as length_column
FROM your_table
--Filter the length of your NULL values (8 is used as example)
WHERE DATALENGTH(COLUMN) > 8
I just give other option for this question - you need to use '.dt' in your code:
import pandas as pd_x000D_
_x000D_
df.index = pd.to_datetime(df.index)_x000D_
_x000D_
#for get year_x000D_
df.index.dt.year_x000D_
_x000D_
#for get month_x000D_
df.index.dt.month_x000D_
_x000D_
#for get day_x000D_
df.index.dt.day_x000D_
_x000D_
#for get hour_x000D_
df.index.dt.hour_x000D_
_x000D_
#for get minute_x000D_
df.index.dt.minute
_x000D_
I know it's an old question but I learned alot from the various answers but came up with my own solution as a function. This should dynamically add the parent folder as a prefix to all files that matches a certain pattern but only if it does not have that prefix already.
function Add-DirectoryPrefix($pattern) {
# To debug, replace the Rename-Item with Select-Object
Get-ChildItem -Path .\* -Filter $pattern -Recurse |
Where-Object {$_.Name -notlike ($_.Directory.Name + '*')} |
Rename-Item -NewName {$_.Directory.Name + '-' + $_.Name}
# Select-Object -Property Directory,Name,@{Name = 'NewName'; Expression= {$_.Directory.Name + '-' + $_.Name}}
}
https://gist.github.com/kmpm/4f94e46e569ae0a4e688581231fa9e00
a % b
in c++ default:
(-7/3) => -2
-2 * 3 => -6
so a%b => -1
(7/-3) => -2
-2 * -3 => 6
so a%b => 1
in python:
-7 % 3 => 2
7 % -3 => -2
in c++ to python:
(b + (a%b)) % b
I was in need of a similar kind of solution, wanted to add data on a wall like facebook, when posted,use prepend()
to add the latest post on top, thought might be useful for others..
$("#statusupdate").submit( function () {
$.post(
'ajax.php',
$(this).serialize(),
function(data){
$("#box").prepend($(data).fadeIn('slow'));
$("#status").val('');
}
);
event.preventDefault();
});
the code in ajax.php is
if (isset($_POST))
{
$feed = $_POST['feed'];
echo "<p id=\"result\" style=\"width:200px;height:50px;background-color:lightgray;display:none;\">$feed</p>";
}
A few solutions to choose from:
json_pp: command utility available in Linux systems for JSON decoding/encoding
echo '{"type":"Bar","id":"1","title":"Foo"}' | json_pp -json_opt pretty,canonical
{
"id" : "1",
"title" : "Foo",
"type" : "Bar"
}
You may want to keep the -json_opt pretty,canonical
argument for predictable ordering.
jq: lightweight and flexible command-line JSON processor. It is written in portable C, and it has zero runtime dependencies.
echo '{"type":"Bar","id":"1","title":"Foo"}' | jq '.'
{
"type": "Bar",
"id": "1",
"title": "Foo"
}
The simplest jq
program is the expression .
, which takes the input and produces it unchanged as output.
For additinal jq
options check the manual
with python:
echo '{"type":"Bar","id":"1","title":"Foo"}' | python -m json.tool
{
"id": "1",
"title": "Foo",
"type": "Bar"
}
echo '{"type":"Bar","id":"1","title":"Foo"}' | node -e "console.log( JSON.stringify( JSON.parse(require('fs').readFileSync(0) ), 0, 1 ))"
{
"type": "Bar",
"id": "1",
"title": "Foo"
}
Here's an example DataFrame which show this, it has duplicate values with the same index. The question is, do you want to aggregate these or keep them as multiple rows?
In [11]: df
Out[11]:
0 1 2 3
0 1 2 a 16.86
1 1 2 a 17.18
2 1 4 a 17.03
3 2 5 b 17.28
In [12]: df.pivot_table(values=3, index=[0, 1], columns=2, aggfunc='mean') # desired?
Out[12]:
2 a b
0 1
1 2 17.02 NaN
4 17.03 NaN
2 5 NaN 17.28
In [13]: df1 = df.set_index([0, 1, 2])
In [14]: df1
Out[14]:
3
0 1 2
1 2 a 16.86
a 17.18
4 a 17.03
2 5 b 17.28
In [15]: df1.unstack(2)
ValueError: Index contains duplicate entries, cannot reshape
One solution is to reset_index
(and get back to df
) and use pivot_table
.
In [16]: df1.reset_index().pivot_table(values=3, index=[0, 1], columns=2, aggfunc='mean')
Out[16]:
2 a b
0 1
1 2 17.02 NaN
4 17.03 NaN
2 5 NaN 17.28
Another option (if you don't want to aggregate) is to append a dummy level, unstack it, then drop the dummy level...
If you have a project ready and just want to change some code and then build. Check out MSBuild which is located in the Microsoft.Net under windows directory.
C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild "C:\Projects\MyProject.csproj" /p:Configuration=Debug;DeployOnBuild=True;PackageAsSingleFile=False;outdir=C:\Projects\MyProjects\Publish\
(Please do not edit, leave as a single line)
... The line above broken up for readability
C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild "C:\Projects\MyProject.csproj"
/p:Configuration=Debug;DeployOnBuild=True;PackageAsSingleFile=False;
outdir=C:\Projects\MyProjects\Publish\
According to new Swift 2.0 we should use do try catch. The code would look like this:
var badumSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("BadumTss", ofType: "mp3"))
var audioPlayer = AVAudioPlayer()
do {
player = try AVAudioPlayer(contentsOfURL: badumSound)
} catch {
print("No sound found by URL:\(badumSound)")
}
player.prepareToPlay()
this helps for me:
on your build.gradle:
implementation 'com.android.support:design:28.0.0'
I was able to get @yeeking example to work by not using FormData but using javascript object to transfer the blob. Works with a sound blob created using recorder.js. Tested in Chrome version 32.0.1700.107
function uploadAudio( blob ) {
var reader = new FileReader();
reader.onload = function(event){
var fd = {};
fd["fname"] = "test.wav";
fd["data"] = event.target.result;
$.ajax({
type: 'POST',
url: 'upload.php',
data: fd,
dataType: 'text'
}).done(function(data) {
console.log(data);
});
};
reader.readAsDataURL(blob);
}
Contents of upload.php
<?
// pull the raw binary data from the POST array
$data = substr($_POST['data'], strpos($_POST['data'], ",") + 1);
// decode it
$decodedData = base64_decode($data);
// print out the raw data,
$filename = $_POST['fname'];
echo $filename;
// write the data out to the file
$fp = fopen($filename, 'wb');
fwrite($fp, $decodedData);
fclose($fp);
?>
Also, make sure that your environment variable is composed only by UPPER CASE LETTERS.... I don't know why (the documentation doesn't say nothing explicit about it, at least the link provided by @Andrew White), but if the variable is a lower case word (e.g. env.dummy), the variable always came empty or null...
i was struggling with this like an hour, until I decided to try an UPPER CASE VARIABLE, and problem solved.
OK Variables Examples:
(NOTE: I was using maven v3.0.5)
I Hope that this can help someone....
{
( VeryLongCondition_1 ) or last;
( VeryLongCondition_2 ) or last;
( VeryLongCondition_3 ) or last;
( VeryLongCondition_4 ) or last;
( VeryLongCondition_5 ) or last;
( VeryLongCondition_6 ) or last;
# Guarded code goes here
}
If any of the conditions fail it will just continue on, after the block. If you are defining any variables that you want to keep around after the block, you will need to define them before the block.
If I were to paraphrase the question - is it possible to pick server context for query execution in the DDL - the answer is no. Only database context can be programmatically chosen with USE. (having already preselected the server context externally)
Linked server and OPEN QUERY can give access to the DDL but require somewhat a rewrite of your code to encapsulate as a string - making it difficult to develop/debug.
Alternately you could resort to an external driver program to pickup SQL files to send to the remote server via OPEN QUERY. However in most cases you might as well have connected to the server directly in the 1st place to evaluate the DDL.
If you are using a router then:
Replace server.listen(yourport, 'localhost');
with server.listen(yourport, 'your ipv4 address');
in my machine it is
server.listen(3000, '192.168.0.3');
Make sure your port is forwarded to your ipv4 address.
On Windows Firewall, tick all on Node.js:Server-side JavaScript.
The below worked for me:
for col in df:
if 'Unnamed' in col:
#del df[col]
print col
try:
df.drop(col, axis=1, inplace=True)
except Exception:
pass
Quick note: if you're also using coord_flip()
to flip the x and the y axis, you won't be able to set range limits using coord_cartesian()
because those two functions are exclusive (see here).
Fortunately, this is an easy fix; set your limits within coord_flip()
like so:
p + coord_flip(ylim = c(3,5), xlim = c(100, 400))
This just alters the visible range (i.e. doesn't remove data points).
The Best way to Print particular Div or any Element
printDiv("myDiv");
function printDiv(id){
var printContents = document.getElementById(id).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
With PowerShell 5.1 (PackageManagement module)
Install-Package -Name MyPackage -Source (Get-Location).Path -Destination C:\outputdirectory
Just making any of the parameters for division in floating-point format also produces the output in floating-point.
Example:
>>> 4.0/3
1.3333333333333333
or,
>>> 4 / 3.0
1.3333333333333333
or,
>>> 4 / float(3)
1.3333333333333333
or,
>>> float(4) / 3
1.3333333333333333
Unfortunately, modules aren't supported by many browsers right now.
This feature is only just beginning to be implemented in browsers natively at this time. It is implemented in many transpilers, such as TypeScript and Babel, and bundlers such as Rollup and Webpack.
Found on MDN
In my case alter column was not working so one can use 'Modify' command, like:
alter table [table_name] MODIFY column [column_name] varchar(1200);
Thats my small solution... Can included to a class and set vars
private $dsepparator = '.'; // decimals private $tsepparator= ','; // thousand
That can be set by constructor and change to users lang.
class foo
{
private $dsepparator;
private $tsepparator;
function __construct(){
$langDatas = ['en' => ['dsepparator' => '.', 'tsepparator' => ','], 'de' => ['dsepparator' => ',', 'tsepparator' => '.']];
$usersLang = 'de'; // set iso code of lang from user
$this->dsepparator = $langDatas[$usersLang]['dsepparator'];
$this->tsepparator = $langDatas[$usersLang]['tsepparator'];
}
public function numberOmat($amount, $decimals = 2, $hideByZero = false)
{
return ( $hideByZero === true AND ($amount-floor($amount)) <= 0 ) ? number_format($amount, 0, $this->dsepparator, $this->tsepparator) : number_format($amount, $decimals, $this->dsepparator, $this->tsepparator);
}
/*
* $bar = new foo();
* $bar->numberOmat('5.1234', 2, true); // returns: 5,12
* $bar->numberOmat('5', 2); // returns: 5,00
* $bar->numberOmat('5.00', 2, true); // returns: 5
*/
}
You are not passing the array as copy. It is only a pointer pointing to the address where the first element of the array is in memory.
Great answers, but if you look for a singe line do all, you can concatenate, alias and enjoy the convenience:
git add * && git commit -am "<commit message>"
It is a single line but two commands, and as mentioned you can alias these commands:
alias git-aac="git add * && git commit -am "
(the space at the end is important) because you are going to parameterize the new short hand command.
From this moment on, you will be using this alias:
git-acc "<commit message>"
You basically say:
git, add for me all untracked files and commit them with this given commit message.
Hope you use Linux, hope this helps.
I had two incompatible dependencies.
The below dependencies caused the error.
compile 'com.google.android.gms:play-services-fitness:8.3.0'
compile 'com.google.android.gms:play-services-wearable:8.4.0'
By changing the fitness dependency to version 8.4.0 I was able to run the app.
compile 'com.google.android.gms:play-services-fitness:8.4.0'
compile 'com.google.android.gms:play-services-wearable:8.4.0'
If you need to compare an array of objects, this works in all cases:
let arr = [{ id: 1, title: "title1" },{ id: 2, title: "title2" }]
let brr = [{ id: 2, title: "title2" },{ id: 3, title: "title3" }]
const res = arr.filter(f => brr.some(item => item.id === f.id));
console.log(res);