You'll find the junit launch commands in .metadata/.plugins/org.eclipse.debug.core/.launches, assuming your Eclipse works like mine does. The files are named {TestClass}.launch.
You will probably also need the .classpath file in the project directory that contains the test class.
Like the run configurations, they're XML files (even if they don't have an xml extension).
It's not clear whether you're asking this because you are new to programming, but if that's the case then you should probably read this article on loops and indeed read some basic materials on programming.
If you already know about control structures and you want the R-specific implementation details then there are dozens of tutorials around, such as this one. The other answer uses replicate
and colMeans
, which is idiomatic when writing in R and probably blazing fast as well, which is important if you want 10,000 iterations.
However, one more general and (for beginners) straightforward way to approach problems of this sort would be to use a for
loop.
> for (ii in 1:5) { + print(ii) + } [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 >
So in your case, if you just wanted to print the mean of your Tandem
object 5 times:
for (ii in 1:5) { Tandem <- sample(OUT, size = 815, replace = TRUE, prob = NULL) TandemMean <- mean(Tandem) print(TandemMean) }
As mentioned above, replicate
is a more natural way to deal with this specific problem using R. Either way, if you want to store the results - which is surely the case - you'll need to start thinking about data structures like vectors and lists. Once you store something you'll need to be able to access it to use it in future, so a little knowledge is vital.
set.seed(1234) OUT <- runif(100000, 1, 2) tandem <- list() for (ii in 1:10000) { tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) } tandem[1] tandem[100] tandem[20:25]
...creates this output:
> set.seed(1234) > OUT <- runif(100000, 1, 2) > tandem <- list() > for (ii in 1:10000) { + tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) + } > > tandem[1] [[1]] [1] 1.511923 > tandem[100] [[1]] [1] 1.496777 > tandem[20:25] [[1]] [1] 1.500669 [[2]] [1] 1.487552 [[3]] [1] 1.503409 [[4]] [1] 1.501362 [[5]] [1] 1.499728 [[6]] [1] 1.492798 >
My 2 cents.
This is a loaded question imho. A rule of thumb I use to is see how this function will be called. If the caller is something I have control over then , its ok to assume that it will be called with the right parameters and with proper initialization.
On the other hand if its some client I don't control then it is a good idea to do thorough error checking.
We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.
Check your linker flags:
Target > Build Settings > Other Linker Flags
You should see -lApptentiveConnect
listed as a linker flag:
... -ObjC -lApptentiveConnect ...
You should also see our required Frameworks listed:
UIKit
-ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit
After some time with Google I asked on the ask ubuntu chat room.
A user there was king enough to help me find the solution I was looking for and i wanted to share so that any following suers running into this may find it:
grep -P "(^|\s)abc(\s|$)"
gives the result I was looking for. -P is an experimental implementation of perl regexps.
grepping for abc
and then using filters like grep -v '@abc'
(this is far from perfect...) should also work, but my patch does something similar.
When you read()
the file, you may get a newline character '\n'
in your string. Try either
if UserInput.strip() == 'List contents':
or
if 'List contents' in UserInput:
Also note that your second file open
could also use with
:
with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile: if UserInput.strip() == 'List contents': # or if s in f: UserInputFile.write("ls") else: print "Didn't work"
You're storing the .Text
properties of the textboxes directly into the database, this doesn't work. The .Text
properties are String
s (i.e. simple text) and not typed as DateTime
instances. Do the conversion first, then it will work.
Do this for each date parameter:
Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) )
Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse
or DateTime.TryParseExact
, but implementing that is an exercise for the reader.
IDLE's console does not support ANSI escape sequences, or any other form of escapes for coloring your output.
You can learn how to talk to IDLE's console directly instead of just treating it like normal stdout and printing to it (which is how it does things like color-coding your syntax), but that's pretty complicated. The idle
documentation just tells you the basics of using IDLE itself, and its idlelib
library has no documentation (well, there is a single line of documentation—"(New in 2.3) Support library for the IDLE development environment."—if you know where to find it, but that isn't very helpful). So, you need to either read the source, or do a whole lot of trial and error, to even get started.
Alternatively, you can run your script from the command line instead of from IDLE, in which case you can use whatever escape sequences your terminal handles. Most modern terminals will handle at least basic 16/8-color ANSI. Many will handle 16/16, or the expanded xterm-256 color sequences, or even full 24-bit colors. (I believe gnome-terminal
is the default for Ubuntu, and in its default configuration it will handle xterm-256, but that's really a question for SuperUser or AskUbuntu.)
Learning to read the termcap
entries to know which codes to enter is complicated… but if you only care about a single console—or are willing to just assume "almost everything handles basic 16/8-color ANSI, and anything that doesn't, I don't care about", you can ignore that part and just hardcode them based on, e.g., this page.
Once you know what you want to emit, it's just a matter of putting the codes in the strings before printing them.
But there are libraries that can make this all easier for you. One really nice library, which comes built in with Python, is curses
. This lets you take over the terminal and do a full-screen GUI, with colors and spinning cursors and anything else you want. It is a little heavy-weight for simple uses, of course. Other libraries can be found by searching PyPI, as usual.
The folder is part of the URL you set when you create request
: "ftp://www.contoso.com/test.htm"
. If you use "ftp://www.contoso.com/wibble/test.htm"
then the file will be uploaded to a folder named wibble
.
You may need to first use a request with Method = WebRequestMethods.Ftp.MakeDirectory
to make the wibble
folder if it doesn't already exist.
The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.
The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.
The primary flag seems to only work for vagrant ssh
for me.
In the past I have used the following method to hack around the issue.
# stage box intended for configuration closely matching production if ARGV[1] == 'stage' config.vm.define "stage" do |stage| box_setup stage, \ "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml" end end
This is version problem, install the right dependant version
npm uninstall node-sass
npm install [email protected]
i simply change my import from import from { AngularFirestore} from '@angular/fire/firestore';
to
import { AngularFirestoreModule } from '@angular/fire/firestore';
and it's working fine
According to your package.json, you're using Angular 8.3, but you've imported angular/cdk v9. You can downgrade your angular/cdk version or you can upgrade your Angular version to v9 by running:
ng update @angular/core @angular/cli
That will update your local angular version to 9. Then, just to sync material, run:
ng update @angular/material
I had same problem & i have installed "create-react-app" globally on my machine. There is error :
"A template was not provided. This is likely because you're using an outdated version of create-react-app. Please note that global installs of create-react-app are no longer supported."
Then i removed previous install by using this command.
npm uninstall -g create-react-app
Then install new react app.
npx create-react-app new-app
This is caused by node v12.11.0 due to the way it deals regular location there two ways to solve this problem
Method I
You can downgrade to node v12.10.0 this will apply the correct way to deal with parsing error
Method II
You can correctly terminate the regular expression in you case by changing the file located a:
\node_modules\metro-config\src\defaults\blacklist.js
From:
var sharedBlacklist = [
/node_modules[/\\]react[/\\]dist[/\\].*/,
/website\/node_modules\/.*/,
/heapCapture\/bundle\.js/,
/.*\/__tests__\/.*/
];
To:
var sharedBlacklist = [
/node_modules[\/\\]react[\/\\]dist[\/\\].*/,
/website\/node_modules\/.*/,
/heapCapture\/bundle\.js/,
/.*\/__tests__\/.*/
];
I solved my problem by running below command
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
I already had multidex enabled but the version was too old so upgraded and it fixed the issue:
// Old version
implementation 'com.android.support:multidex:1.0.3'
// New version
def multidex_version = "2.0.1"
implementation 'androidx.multidex:multidex:$multidex_version'
Delete node_modules
rm -r node_modules
install packages again
npm install
You need to add the package containing the executable pg_config.
A prior answer should have details you need: pg_config executable not found
You can also use Python to press the arrow keys. I added a little bit of randomness in the following code as well.
from pyautogui import press, typewrite, hotkey
import time
from random import shuffle
array = ["left", "right", "up", "down"]
while True:
shuffle(array)
time.sleep(10)
press(array[0])
press(array[1])
press(array[2])
press(array[3])
For everyone using .NET Core CLI on MinGW MSYS. After installing using
dotnet tool install --global dotnet-ef
add this line to to bashrc file c:\msys64\home\username\ .bashrc (location depend on your setup)
export PATH=$PATH:/c/Users/username/.dotnet/tools
If you want to display an icon and are using a dark theme. Which means the icon provided above doesn't look that great. Then you can find the icon here
C:\Program Files\Git\mingw64\share\git\git-for-windows
I copied it into.
%LOCALAPPDATA%\packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\RoamingState
and named it git-bash_32px
as suggested above.
Control the opacity with CTRL + SHIFT + scrolling.
{
"acrylicOpacity" : 0.75,
"closeOnExit" : true,
"colorScheme" : "Campbell",
"commandline" : "\"%PROGRAMFILES%\\git\\usr\\bin\\bash.exe\" -i -l",
"cursorColor" : "#FFFFFF",
"cursorShape" : "bar",
"fontFace" : "Consolas",
"fontSize" : 10,
"guid" : "{73225108-7633-47ae-80c1-5d00111ef646}",
"historySize" : 9001,
"icon" : "ms-appdata:///roaming/git-bash_32px.ico",
"name" : "Bash",
"padding" : "0, 0, 0, 0",
"snapOnInput" : true,
"startingDirectory" : "%USERPROFILE%",
"useAcrylic" : true
},
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()
in your tsconfig you have to add: "esModuleInterop": true - it should help.
This is because the compatibility issue between node
and gulp
in your system. Downgrading the node
or upgrading the gulp
will fix this issue.
sudo npm i -g n
sudo n 11.15.0
Try removing the node_modules
folder and package-lock.json
file and installing again using npm i
command if still not working.
These warnings are very helpful for finding components that do not update consistently: https://reactjs.org/docs/hooks-faq.html#is-it-safe-to-omit-functions-from-the-list-of-dependencies.
However, If you want to remove the warnings throughout your project, you can add this to your eslint config:
{
"plugins": ["react-hooks"],
"rules": {
"react-hooks/exhaustive-deps": 0
}
}
Based on responses and comments below, the following was the simple solution for my issue and THIS WORKED. Now my app, Match4app, is fully compatible with latest iOS versions!
I have also faced this issue. I resolved this following step.
Check android sdk path in Environment Veritable.
Add
ANDROID_HOME = C:\Users\user_name\AppData\Local\Android\Sdk
in System Variable
and
C:\Users\user_name\AppData\Local\Android\Sdk\platform-tools
path in System Variable
replace sharedBlacklist as below code segment,
var sharedBlacklist = [
/node_modules[\/\\]react[\/\\]dist[\/\\].*/,
/website\/node_modules\/.*/,
/heapCapture\/bundle\.js/,
/.*\/__tests__\/.*/
];
in node_modules/metro-config/src/default/blacklist.js
Then run npx react-native run-android --port 9001
Happy Coding..!
Try following command sequence on Ubuntu terminal:
sudo apt-get install software-properties-common
sudo apt-add-repository universe
sudo apt-get update
sudo apt-get install python-pip
As mentioned in Scott Kuhl's answer this issue is mentioned in https://github.com/madskristensen/WebCompiler/issues/413
For me, running the command npm i caniuse-lite- browserslist
only worked for about 1/2 a day before it was an issue again.
The following solution, mentioned in the post, works much better. This updates the node.js file so that it uses console.log
instead of console.warn
when returning these errors.
You can manually update this file located at C:\Users\[Username]\AppData\Local\Temp\WebCompiler[VersionNumber]\node_modules\browserslist
Or, so that it is done automatically, add the following to your .csproj file by:
</Project>
end tag and before the build web compiler package was imported. <ItemGroup>
<PackageReference Include="MSBuildTasks" Version="1.5.0.235">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
</ItemGroup>
<PropertyGroup>
<TempFolder>$([System.IO.Path]::GetTempPath())</TempFolder>
</PropertyGroup>
<ItemGroup>
<BrowsersListNodeJsFiles Include="$(TempFolder)\WebCompiler*\node_modules\browserslist\node.js" />
</ItemGroup>
<Target Name="BrowsersListWarningsAsInfo" BeforeTargets="WebCompile">
<FileUpdate Files="@(BrowsersListNodeJsFiles)"
Regex="console.warn"
ReplacementText="console.log" />
</Target>
Here is the a possible solution
If this is your code, the correct solution is to rewrite it to not use Session()
, since that's no longer necessary in TensorFlow 2
If this is just code you're running, you can downgrade to TensorFlow 1 by running
pip3 install --upgrade --force-reinstall tensorflow-gpu==1.15.0
(or whatever the latest version of TensorFlow 1 is)
If you are using Typescript 3.7 or newer you can now also do:
const data = change?.after?.data();
if(!data) {
console.error('No data here!');
return null
}
const maxLen = 100;
const msgLen = data.messages.length;
const charLen = JSON.stringify(data).length;
const batch = db.batch();
if (charLen >= 10000 || msgLen >= maxLen) {
// Always delete at least 1 message
const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
data.messages.splice(0, deleteCount);
const ref = db.collection("chats").doc(change.after.id);
batch.set(ref, data, { merge: true });
return batch.commit();
} else {
return null;
}
Typescript is saying that change
or data
is possibly undefined
(depending on what onUpdate
returns).
So you should wrap it in a null/undefined check:
if(change && change.after && change.after.data){
const data = change.after.data();
const maxLen = 100;
const msgLen = data.messages.length;
const charLen = JSON.stringify(data).length;
const batch = db.batch();
if (charLen >= 10000 || msgLen >= maxLen) {
// Always delete at least 1 message
const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
data.messages.splice(0, deleteCount);
const ref = db.collection("chats").doc(change.after.id);
batch.set(ref, data, { merge: true });
return batch.commit();
} else {
return null;
}
}
If you are 100% sure that your object
is always defined then you can put this:
const data = change.after!.data();
I installed pip3
using
python3.7 -m pip install pip
But upon using pip3
to install other dependencies, it was using python3.6.
You can check the by typing pip3 --version
Hence, I used pip3
like this (stated in one of the above answers):
python3.7 -m pip install <module>
or use it like this:
python3.7 -m pip install -r requirements.txt
I made a bash alias for later use in ~/.bashrc file as alias pip3='python3.7 -m pip'
. If you use alias, don't forget to source ~/.bashrc
after making the changes and saving it.
If you want to keep your bashrc simple, you can remove all the conda init
generated clutter, and keep only a single line:
. "/Users/geoff/anaconda2/etc/profile.d/conda.sh"
See Recommended change to enable conda in your shell.
This will make the conda command available without activating the base environment.
If you want to use your bashrc on other systems where conda is not installed in the same path, you can keep the if
/fi
lines as well to avoid error messages, i.e.:
if [ -f "/Users/geoff/anaconda2/etc/profile.d/conda.sh" ]; then
. "/Users/geoff/anaconda2/etc/profile.d/conda.sh"
fi
As distributionUrl
is still pointing to older version, upgrade wrapper using:
gradle wrapper --gradle-version 5.1.1
Note: Use gradle
and not gradlew
in my case I just installed a new version of android studio on a new laptop and cloned the old repository where
buildToolsVersion "30.0.2"
at application level build.gradle.
I just upgraded to 30.0.3
which android studio recommended on its own and the problem went away
I had the same problem and the solution was pretty easy:
"If you create a new conda environment while VS Code is running, use the Reload Window command to refresh the environment list shown with Python: Select Interpreter; otherwise you may not see the environment there. It might take a short time to appear; if you don't see it at first, wait 15 seconds then try using the command again."
That's written on Vscode site
Note: to Reload Window: ctrl+shift+p in Vscode, then write reload window
I encountered the same problem after freshly installing git on Windows 10 and running it for the first time. Restarting the bash window solved the problem.
Edit: I just realized the warning is referencing a component called TextLayerInternal
. That's likely where your bug is. The rest of this is still relevant, but it might not fix your problem.
1) Getting the instance of a component for this warning is tough. It looks like there is some discussion to improve this in React but there currently is no easy way to do it. The reason it hasn't been built yet, I suspect, is likely because components are expected to be written in such a way that setState after unmount isn't possible no matter what the state of the component is. The problem, as far as the React team is concerned, is always in the Component code and not the Component instance, which is why you get the Component Type name.
That answer might be unsatisfactory, but I think I can fix your problem.
2) Lodashes throttled function has a cancel
method. Call cancel
in componentWillUnmount
and ditch the isComponentMounted
. Canceling is more "idiomatically" React than introducing a new property.
You should not set state (or do anything else with side effects) from within the rendering function. When using hooks, you can use useEffect
for this.
The following version works:
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
const StateSelector = () => {
const initialValue = [
{ id: 0, value: " --- Select a State ---" }];
const allowedState = [
{ id: 1, value: "Alabama" },
{ id: 2, value: "Georgia" },
{ id: 3, value: "Tennessee" }
];
const [stateOptions, setStateValues] = useState(initialValue);
// initialValue.push(...allowedState);
console.log(initialValue.length);
// ****** BEGINNING OF CHANGE ******
useEffect(() => {
// Should not ever set state during rendering, so do this in useEffect instead.
setStateValues(allowedState);
}, []);
// ****** END OF CHANGE ******
return (<div>
<label>Select a State:</label>
<select>
{stateOptions.map((localState, index) => (
<option key={localState.id}>{localState.value}</option>
))}
</select>
</div>);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<StateSelector />, rootElement);
and here it is in a code sandbox.
I'm assuming that you want to eventually load the list of states from some dynamic source (otherwise you could just use allowedState
directly without using useState
at all). If so, that api call to load the list could also go inside the useEffect
block.
This issue is due to incompatible of your plugin Verison and required Gradle version; they need to match with each other. I am sharing how my problem was solved.
Required Gradle version is here
more compatibility you can see from here. Android Plugin for Gradle Release Notes
if you have the android studio version 4.0.1
then your top level gradle file must be like this
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:4.0.2'
classpath 'com.google.firebase:firebase-crashlytics-gradle:2.4.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
and the gradle version should be
and your app gradle look like this
This post aims to give readers a primer on SQL-flavored merging with pandas, how to use it, and when not to use it.
In particular, here's what this post will go through:
The basics - types of joins (LEFT, RIGHT, OUTER, INNER)
What this post (and other posts by me on this thread) will not go through:
Note
Most examples default to INNER JOIN operations while demonstrating various features, unless otherwise specified.Furthermore, all the DataFrames here can be copied and replicated so you can play with them. Also, see this post on how to read DataFrames from your clipboard.
Lastly, all visual representation of JOIN operations have been hand-drawn using Google Drawings. Inspiration from here.
merge
!np.random.seed(0)
left = pd.DataFrame({'key': ['A', 'B', 'C', 'D'], 'value': np.random.randn(4)})
right = pd.DataFrame({'key': ['B', 'D', 'E', 'F'], 'value': np.random.randn(4)})
left
key value
0 A 1.764052
1 B 0.400157
2 C 0.978738
3 D 2.240893
right
key value
0 B 1.867558
1 D -0.977278
2 E 0.950088
3 F -0.151357
For the sake of simplicity, the key column has the same name (for now).
An INNER JOIN is represented by
Note
This, along with the forthcoming figures all follow this convention:
- blue indicates rows that are present in the merge result
- red indicates rows that are excluded from the result (i.e., removed)
- green indicates missing values that are replaced with
NaN
s in the result
To perform an INNER JOIN, call merge
on the left DataFrame, specifying the right DataFrame and the join key (at the very least) as arguments.
left.merge(right, on='key')
# Or, if you want to be explicit
# left.merge(right, on='key', how='inner')
key value_x value_y
0 B 0.400157 1.867558
1 D 2.240893 -0.977278
This returns only rows from left
and right
which share a common key (in this example, "B" and "D).
A LEFT OUTER JOIN, or LEFT JOIN is represented by
This can be performed by specifying how='left'
.
left.merge(right, on='key', how='left')
key value_x value_y
0 A 1.764052 NaN
1 B 0.400157 1.867558
2 C 0.978738 NaN
3 D 2.240893 -0.977278
Carefully note the placement of NaNs here. If you specify how='left'
, then only keys from left
are used, and missing data from right
is replaced by NaN.
And similarly, for a RIGHT OUTER JOIN, or RIGHT JOIN which is...
...specify how='right'
:
left.merge(right, on='key', how='right')
key value_x value_y
0 B 0.400157 1.867558
1 D 2.240893 -0.977278
2 E NaN 0.950088
3 F NaN -0.151357
Here, keys from right
are used, and missing data from left
is replaced by NaN.
Finally, for the FULL OUTER JOIN, given by
specify how='outer'
.
left.merge(right, on='key', how='outer')
key value_x value_y
0 A 1.764052 NaN
1 B 0.400157 1.867558
2 C 0.978738 NaN
3 D 2.240893 -0.977278
4 E NaN 0.950088
5 F NaN -0.151357
This uses the keys from both frames, and NaNs are inserted for missing rows in both.
The documentation summarizes these various merges nicely:
If you need LEFT-Excluding JOINs and RIGHT-Excluding JOINs in two steps.
For LEFT-Excluding JOIN, represented as
Start by performing a LEFT OUTER JOIN and then filtering (excluding!) rows coming from left
only,
(left.merge(right, on='key', how='left', indicator=True)
.query('_merge == "left_only"')
.drop('_merge', 1))
key value_x value_y
0 A 1.764052 NaN
2 C 0.978738 NaN
Where,
left.merge(right, on='key', how='left', indicator=True)
key value_x value_y _merge
0 A 1.764052 NaN left_only
1 B 0.400157 1.867558 both
2 C 0.978738 NaN left_only
3 D 2.240893 -0.977278 both
And similarly, for a RIGHT-Excluding JOIN,
(left.merge(right, on='key', how='right', indicator=True)
.query('_merge == "right_only"')
.drop('_merge', 1))
key value_x value_y
2 E NaN 0.950088
3 F NaN -0.151357
Lastly, if you are required to do a merge that only retains keys from the left or right, but not both (IOW, performing an ANTI-JOIN),
You can do this in similar fashion—
(left.merge(right, on='key', how='outer', indicator=True)
.query('_merge != "both"')
.drop('_merge', 1))
key value_x value_y
0 A 1.764052 NaN
2 C 0.978738 NaN
4 E NaN 0.950088
5 F NaN -0.151357
If the key columns are named differently—for example, left
has keyLeft
, and right
has keyRight
instead of key
—then you will have to specify left_on
and right_on
as arguments instead of on
:
left2 = left.rename({'key':'keyLeft'}, axis=1)
right2 = right.rename({'key':'keyRight'}, axis=1)
left2
keyLeft value
0 A 1.764052
1 B 0.400157
2 C 0.978738
3 D 2.240893
right2
keyRight value
0 B 1.867558
1 D -0.977278
2 E 0.950088
3 F -0.151357
left2.merge(right2, left_on='keyLeft', right_on='keyRight', how='inner')
keyLeft value_x keyRight value_y
0 B 0.400157 B 1.867558
1 D 2.240893 D -0.977278
When merging on keyLeft
from left
and keyRight
from right
, if you only want either of the keyLeft
or keyRight
(but not both) in the output, you can start by setting the index as a preliminary step.
left3 = left2.set_index('keyLeft')
left3.merge(right2, left_index=True, right_on='keyRight')
value_x keyRight value_y
0 0.400157 B 1.867558
1 2.240893 D -0.977278
Contrast this with the output of the command just before (that is, the output of left2.merge(right2, left_on='keyLeft', right_on='keyRight', how='inner')
), you'll notice keyLeft
is missing. You can figure out what column to keep based on which frame's index is set as the key. This may matter when, say, performing some OUTER JOIN operation.
DataFrames
For example, consider
right3 = right.assign(newcol=np.arange(len(right)))
right3
key value newcol
0 B 1.867558 0
1 D -0.977278 1
2 E 0.950088 2
3 F -0.151357 3
If you are required to merge only "new_val" (without any of the other columns), you can usually just subset columns before merging:
left.merge(right3[['key', 'newcol']], on='key')
key value newcol
0 B 0.400157 0
1 D 2.240893 1
If you're doing a LEFT OUTER JOIN, a more performant solution would involve map
:
# left['newcol'] = left['key'].map(right3.set_index('key')['newcol']))
left.assign(newcol=left['key'].map(right3.set_index('key')['newcol']))
key value newcol
0 A 1.764052 NaN
1 B 0.400157 0.0
2 C 0.978738 NaN
3 D 2.240893 1.0
As mentioned, this is similar to, but faster than
left.merge(right3[['key', 'newcol']], on='key', how='left')
key value newcol
0 A 1.764052 NaN
1 B 0.400157 0.0
2 C 0.978738 NaN
3 D 2.240893 1.0
To join on more than one column, specify a list for on
(or left_on
and right_on
, as appropriate).
left.merge(right, on=['key1', 'key2'] ...)
Or, in the event the names are different,
left.merge(right, left_on=['lkey1', 'lkey2'], right_on=['rkey1', 'rkey2'])
merge*
operations and functionsMerging a DataFrame with Series on index: See this answer.
Besides merge
, DataFrame.update
and DataFrame.combine_first
are also used in certain cases to update one DataFrame with another.
pd.merge_ordered
is a useful function for ordered JOINs.
pd.merge_asof
(read: merge_asOf) is useful for approximate joins.
This section only covers the very basics, and is designed to only whet your appetite. For more examples and cases, see the documentation on merge
, join
, and concat
as well as the links to the function specs.
Jump to other topics in Pandas Merging 101 to continue learning:
* you are here
Change file type from tsx -> ts, jsx -> js
You can get this error if you are working on .tsx or .jsx file and you are just exporting styles etc and not jsx. In this case the error is solved by changing the file type to .ts or .js
Go to
Keychain Access
-> Right-click on login
-> Lock & unlock again
Xcode
-> Clean Xcode project
->Make build again
I have deleted the existing node module and run the below commands to fix my issue
npm install -all
npm audit fix
Since, nobody seem to mention this apart myself. My own solution to the above problem is most often to make sure to disable the cached copy by using: pip install <package> --no-cache-dir
.
Finally, the command below fixed the issue for me!
ng update --all --force
For RobotFramework
I solved it! using --no-sandbox
${chrome_options}= Evaluate sys.modules['selenium.webdriver'].ChromeOptions() sys, selenium.webdriver
Call Method ${chrome_options} add_argument test-type
Call Method ${chrome_options} add_argument --disable-extensions
Call Method ${chrome_options} add_argument --headless
Call Method ${chrome_options} add_argument --disable-gpu
Call Method ${chrome_options} add_argument --no-sandbox
Create Webdriver Chrome chrome_options=${chrome_options}
Instead of
Open Browser about:blank headlesschrome
Open Browser about:blank chrome
If you're using scss for your styles you can use a mixin to help generate the code. Your styles will quickly get out of hand if you put all the properties every time.
This is a very simple example - really nothing more than a proof of concept, you can extend this with multiple properties and rules as needed.
@mixin mat-table-columns($columns)
{
.mat-column-
{
@each $colName, $props in $columns {
$width: map-get($props, 'width');
&#{$colName}
{
flex: $width;
min-width: $width;
@if map-has-key($props, 'color')
{
color: map-get($props, 'color');
}
}
}
}
}
Then in your component where your table is defined you just do this:
@include mat-table-columns((
orderid: (width: 6rem, color: gray),
date: (width: 9rem),
items: (width: 20rem)
));
This generates something like this:
.mat-column-orderid[_ngcontent-c15] {
flex: 6rem;
min-width: 6rem;
color: gray; }
.mat-column-date[_ngcontent-c15] {
flex: 9rem;
min-width: 9rem; }
In this version width
becomes flex: value; min-width: value
.
For your specific example you could add wrap: true
or something like that as a new parameter.
For me on my archlinux system the line was already uncommented. I had to replace "none" by "read | write " to make it work.
If you want to use python3+ to install the packages you need to use pip3 install package_name
And to solve the errno 13 you have to add --user
at the end
pip3 install package_name --user
EDIT:
For any project in python it's highly recommended to work on a Virtual enviroment, is a tool that helps to keep dependencies required by different projects separate by creating isolated python virtual environments for them.
In order to create one with python3+ you have to use the following command:
virtualenv enviroment_name -p python3
And then you work on it just by activating it:
source enviroment_name/bin/activate
Once the virtual environment is activated, the name of your virtual environment will appear on left side of terminal. This will let you know that the virtual environment is currently active.
Now you can install dependencies related to the project in this virtual environment by just using pip
.
pip install package_name
Open Terminal:
install XCode developer tools and fix the problem.
$ xcode-select --install
Reset the path to Xcode if you have several versions:
$ xcode-select --switch /Applications/Xcode.app
$ xcode-select --switch /Library/Developer/CommandLineTools
apue.h dependency was still missing in my /usr/local/include
after I managed to fix this problem on Mac OS Catalina following the instructions of this answer
I downloaded the dependency manually from git and placed it in /usr/local/include
In Ubuntu, you can simply install Open JDK by following commands.
sudo apt-get update
sudo apt-get install default-jdk
You can check the java version by following the command.
java -version
If you want to install Oracle JDK 8 follow the below commands.
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer
If you want to switch java versions you can try below methods.
vi ~/.bashrc
and add the following line export JAVA_HOME=/usr/lib/jvm/jdk1.8.0_221
(path/jdk folder)
or
sudo vi /etc/profile
and add the following lines
#JAVA_HOME=/usr/lib/jvm/jdk1.8.0_221
JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64
export PATH=$JAVA_HOME/bin:$PATH
export JAVA_HOME
export JRE_HOME
export PATH
You can comment on the other version. This needs to sign out and sign back in to use. If you want to try it on the go you can type the below command in the same terminal. It'll only update the java version for a particular terminal.
source /etc/profile
You can always check the java version by java -version
command.
I will post my solution. This solution worked for me, since none of the previous worked. The issue first occurred right after last update of XCode cli toolset (not sure if this is the confirmation bias).
I tried some of the instructions (ie. Unlock Keychain Trick).
What worked for me in a case of error:
Command CodeSign failed with a nonzero exit code (Something.framework)
Link Binary With Libraries
Something.framework
,General => Something.framework => EMBED
Do not embed
Cmd+B
(Build Project)Just adding to this question. My issue didn't have anything to do with CommonCrypto. It created a new Single App application and tested to run. Compiler was complaining about using Swift 4.2
Changing the Swift language to version 4.0 in Build settings fixed the issue. Not sure if this is a bug.
Use WORKSPACE environment variable to change workspace directory.
If doing using Jenkinsfile, use following code :
dir("${env.WORKSPACE}/aQA"){
sh "pwd"
}
First run your IDE or CMD as Administrator and run the following:
pip install pipwin
pipwin install pyaudio
This worked for me (using WSL)
sudo /etc/init.d/redis start
(for any other service, check the init.d folder for filenames)
In case you need the []
syntax, useful for "edit forms" when you need to pass parameters like id with the route, you would do something like:
[routerLink]="['edit', business._id]"
As for an "about page" with no parameters like yours,
[routerLink]="/about"
or
[routerLink]=['about']
will do the trick.
Upgrading pip in windows with -
python -m pip install --upgrade pip
and then running pip install with --user option -
pip install --user package_name
solved my problem.
If you have installed Android Studio more than one time, the command prompt or PowerShell assigned on the first one and maybe you are running the second one. So, browse for Android Studio, if you have more than one installation, delete the first one. Then, download the Plugins in Android Studio by following theese steps.
Step 1:Studio --> File --> Settings --> Plugins --> Browse Repositories
Step 2: Search for Flutter and download it
Step 3: When you're done restart Android Studio.
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();
}
)
}
I use a Mac with Visual Studio Code and this is what worked:
Shutdown your PC and switch it on again. Don't use the restart function. I restarted 2 times and it didn't work. Only shutdown worked.
PS: I tried out the following:
killall -9 dart
;But they all didn't work.
Run the Gradle build with a command line argument --warning-mode=all
to see what exactly the deprecated features are.
It will give you a detailed description of found issues with links to the Gradle docs for instructions how to fix your build.
Adding --stacktrace
to that, you will also be able to pinpoint where the warning comes from, if it's triggered by outdated code in one of the plugins and not your build script.
This worked for me:
File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)
clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.
Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.
then in:
Run >> Edit Configurations
Add this line to VM Options:
--module-path /path/to/JavaFX/lib --add-modules=javafx.controls
(oh and don't forget to set the SDK)
How about using direct axios
API?
axios({
method: 'post',
url: baseUrl + 'applications/' + appName + '/dataexport/plantypes' + plan,
headers: {},
data: {
foo: 'bar', // This is the body part
}
});
Source: axios api
MSDocs state this for your scenario:
In order to execute the first time, PackageManagement requires an internet connection to download the Nuget package provider. However, if your computer does not have an internet connection and you need to use the Nuget or PowerShellGet provider, you can download them on another computer and copy them to your target computer. Use the following steps to do this:
Run
Install-PackageProvider -Name NuGet -RequiredVersion 2.8.5.201 -Force
to install the provider from a computer with an internet connection.After the install, you can find the provider installed in
$env:ProgramFiles\PackageManagement\ReferenceAssemblies\\\<ProviderName\>\\\<ProviderVersion\>
or$env:LOCALAPPDATA\PackageManagement\ProviderAssemblies\\\<ProviderName\>\\\<ProviderVersion\>
.Place the folder, which in this case is the Nuget folder, in the corresponding location on your target computer. If your target computer is a Nano server, you need to run Install-PackageProvider from Nano Server to download the correct Nuget binaries.
Restart PowerShell to auto-load the package provider. Alternatively, run
Get-PackageProvider -ListAvailable
to list all the package providers available on the computer. Then useImport-PackageProvider -Name NuGet -RequiredVersion 2.8.5.201
to import the provider to the current Windows PowerShell session.
You can get this issue if Apple update their terms. Simply log into your dev account and accept any updated terms and you should be good (you will need to goto Xcode -> project->signing and capabilities and retry the certificate check. This should get you going if terms are the issue.
You can use date:'yyyy-MM-dd'
pipe
curDate=new Date();
<p>{{curDate | date:'yyyy-MM-dd'}}</p>
If you don't need typesafe, just bring block to a new separated file and change the extension to .js,.jsx
Install/update RVM with last ruby version
\curl -sSL https://get.rvm.io | bash -s stable
Install bundler
gem install bundler
after this two commands (sudo) gem install ....
started to work
In case anyone face pip issue like below
pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
The root cause is openssl 1.1 doesn’t support python 3.6 anymore. So you need to install old version openssl 1.0
here is the solution:
brew uninstall --ignore-dependencies openssl
brew install https://github.com/tebelorg/Tump/releases/download/v1.0.0/openssl.rb
https://fettblog.eu/gulp-4-parallel-and-series/
Because
gulp.task(name, deps, func)
was replaced by gulp.task(name, gulp.{series|parallel}(deps, func))
.
You are using the latest version of gulp but older code. Modify the code or downgrade.
Before applying WORKDIR. Here the WORKDIR is at the wrong place and is not used wisely.
FROM microsoft/aspnetcore:2
COPY --from=build-env /publish /publish
WORKDIR /publish
ENTRYPOINT ["dotnet", "/publish/api.dll"]
We corrected the above code to put WORKDIR at the right location and optimised the following statements by removing /Publish
FROM microsoft/aspnetcore:2
WORKDIR /publish
COPY --from=build-env /publish .
ENTRYPOINT ["dotnet", "api.dll"]
So it acts like a cd
and sets the tone for the upcoming statements.
To create an environment named py37
with python 3.7, using the channel conda-forge and a list of packages:
conda create -y --name py37 python=3.7
conda install --force-reinstall -y -q --name py37 -c conda-forge --file requirements.txt
conda activate py37
...
conda deactivate
Flags explained:
-y
: Do not ask for confirmation.--force-reinstall
: Install the package even if it already exists.-q
: Do not display progress bar.-c
: Additional channel to search for packages. These are URLs searched in the orderThe ansible-role dockpack.base_miniconda can manage conda environments and can be used to create a docker base image.
Alternatively you can create an environment.yml file instead of requirements.txt:
name: py37
channels:
- conda-forge
dependencies:
- python=3.7
- numpy=1.9.*
- pandas
Use this command to list the environments you have:
conda info --envs
Use this command to remove the environment:
conda env remove -n py37
The official tutorial discusses deploying an app to production. One option is to use Waitress, a production WSGI server. Other servers include Gunicorn and uWSGI.
When running publicly rather than in development, you should not use the built-in development server (
flask run
). The development server is provided by Werkzeug for convenience, but is not designed to be particularly efficient, stable, or secure.Instead, use a production WSGI server. For example, to use Waitress, first install it in the virtual environment:
$ pip install waitress
You need to tell Waitress about your application, but it doesn’t use
FLASK_APP
like flask run does. You need to tell it to import and call the application factory to get an application object.$ waitress-serve --call 'flaskr:create_app' Serving on http://0.0.0.0:8080
Or you can use waitress.serve()
in the code instead of using the CLI command.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "<h1>Hello!</h1>"
if __name__ == "__main__":
from waitress import serve
serve(app, host="0.0.0.0", port=8080)
$ python hello.py
An alternative way to put images in your app (for me it just worked that way):
1 - Create an assets/images folder
2 - Add your image to the new folder
3 - Register the assets folder in pubspec.yaml
4 - Use this code:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
var assetsImage = new AssetImage('assets/images/mountain.jpg'); //<- Creates an object that fetches an image.
var image = new Image(image: assetsImage, fit: BoxFit.cover); //<- Creates a widget that displays an image.
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Climb your mountain!"),
backgroundColor: Colors.amber[600], //<- background color to combine with the picture :-)
),
body: Container(child: image), //<- place where the image appears
),
);
}
}
Simple answer
If you are behind a proxy server, please set the proxy for curl. The curl is not able to connect to server so it shows wrong version number. Set proxy by opening subl ~/.curlrc or use any other text editor. Then add the following line to file: proxy= proxyserver:proxyport For e.g. proxy = 10.8.0.1:8080
If you are not behind a proxy, make sure that the curlrc file does not contain the proxy settings.
.env
and .env.production
VUE_APP_
eg: VUE_APP_WHATEVERYOUWANT
.env
and build uses .env.production
process.env.VUE_APP_WHATEVERYOUWANT
to call valueBe sure you are using vue-cli version 3 or above
For more information: https://cli.vuejs.org/guide/mode-and-env.html
I am also a Windows user. And I have installed Python 3.7 and when I try to install any package it throws the same error that you are getting.
Try this out. This worked for me.
python -m pip install numpy
And whenever you install new package just write python -m pip install <package_name>
Hope this is helpful.
By Default angular return responseType as Json, but we can configure below types according to your requirement.
responseType: 'arraybuffer'|'blob'|'json'|'text'
Ex:
this.http.post(
'http://localhost:8080/order/addtocart',
{ dealerId: 13, createdBy: "-1", productId, quantity },
{ headers, responseType: 'text'});
I faced the same issue:
E: gnupg, gnupg2 and gnupg1 do not seem to be installed, but one of them is required for this operation
I resolved by using the following commands:
apt-get update
apt-get install gnupg
react-scripts
is a set of scripts from the create-react-app
starter pack. create-react-app helps you kick off projects without configuring, so you do not have to setup your project by yourself.
react-scripts start
sets up the development environment and starts a server, as well as hot module reloading. You can read here to see what everything it does for you.
with create-react-app you have following features out of the box.
- React, JSX, ES6, and Flow syntax support.
- Language extras beyond ES6 like the object spread operator.
- Autoprefixed CSS, so you don’t need -webkit- or other prefixes.
- A fast interactive unit test runner with built-in support for coverage reporting.
- A live development server that warns about common mistakes.
- A build script to bundle JS, CSS, and images for production, with hashes and sourcemaps.
- An offline-first service worker and a web app manifest, meeting all the Progressive Web App criteria.
- Hassle-free updates for the above tools with a single dependency.
npm start
is a shortcut for npm run start
.
npm run
is used to run scripts that you define in the scripts
object of your package.json
if there is no start
key in the scripts object, it will default to node server.js
Sometimes you want to do more than the react scripts gives you, in this case you can do react-scripts eject
. This will transform your project from a "managed" state into a not managed state, where you have full control over dependencies, build scripts and other configurations.
Go in Project Build Phase and Remove info.plist from the Compile Sources. It will remove that issue and project will be active again.
I had this error and as I'm on shared hosting I don't have access to the php.ini so wasn't sure how I could fix it, the host didn't seem to have a clue either. In the end I emptied my browser cache and reloaded phpmyadmin and it came back!
First, download the Flutter here: https://flutter.dev/docs/get-started/install/macos
When you created the folder with Flutter SDK, open it in Terminal using the following command:
cd ~/development
If there is no development folder run this command first:
mkdir /development
After that, you need to run the unzip command. Make sure you specify the correct path to the downloaded Flutter archive file. Run the command below:
unzip ~/Downloads/flutter_macos_1.17.1-stable.zip
Setting the Flutter tool path
In order to set up the Flutter tool path you should run this command:
export PATH="$PATH:`pwd`/flutter/bin"
Next, you need to know which shell you are using. For this run this command:
echo $SHELL
Depending on the shell run the following command: [Note, the command you will be using depends on the shell you have.]
sudo nano ~/.zshrc
or
sudo nano /.bashrc
After that in the new window, you need to add a path to the flutter tool.
Use the following command:
export PATH=$PATH:~/development/flutter/bin
The next thing you need to do is to check the Flutter dependencies.
For this, run the command:
flutter doctor
This operation will help you to identify if there are any dependencies you need to install. After the results will be prepared click Agree and wait for the installation of the needed dependencies to complete the setup. enter image description here
Simple Definition:
npm - Javascript package manager
npx - Execute npm package binaries
I struggled with the same problem just a minute ago. My project was generated using the v 1.6.0 of angular-cli.
npm update -g @angular/cli editing my package.json changing the line "@angular/cli": "1.6.0", to "@angular/cli": "^1.6.0", npm update did the trick.
npm start
runs a script that the app maker built for easy starting of the app
npm install
installs all the packages in package.json
run npm install
first
then run npm start
with the help of below commands your application will work as you aspected run each command as I mention
1.npm list -g --depth=0
2.npm i npm-check-updates
3.npm install
and finally, run the below command to open your project in browser
ng serve --open
Sometimes a dependency added with ng add
will add more than one package, typing npm uninstall lib1 lib2
could be error prone and slow, so just remove the not needed libraries from package.json
and run npm i
This will work. Set the environment variable PYTHONHTTPSVERIFY to 0.
export PYTHONHTTPSVERIFY = 0
OR
import os
os.environ["PYTHONHTTPSVERIFY"] = "0"
Annotate class public static void main
with, for example: @SpringBootApplication
Downgrading might not be a good option as:
You can use mysql2
package in place of mysql
. Its mostly API compatible with mysqljs.
Also, it has promises support.
Use it like:
const mysql = require('mysql2/promise')
(for promise based methods)
You can read more about mysql2
here: https://www.npmjs.com/package/mysql2
Hope it helps. :)
In my case there was a need for:
@Injectable({
providedIn: 'root' // <- ADD THIS
})
export class FooService { ...
instead of just:
@Injectable()
export class FooService { ...
You could try BeeWare - as described on their website:
Write your apps in Python and release them on iOS, Android, Windows, MacOS, Linux, Web, and tvOS using rich, native user interfaces. One codebase. Multiple apps.
Gives you want you want now to write Android Apps in Python, plus has the advantage that you won't need to learn yet another framework in future if you end up also wanting to do something on one of the other listed platforms.
Here's the Tutorial for Android Apps.
Are you using python2 or python3? The following commands could be different!
python3 -m pip --version
to see if you have pip installed.python3 -m pip install --upgrade pip
.sudo apt-get install python3-pip
, and do it again.Might have todo with one of these:
I returned to a system after a while, and even though it had Node 12.x, there was no npx
or even npm
available. I had installed Node via nvm
, so I removed it, reinstalled it and then installed the latest Node LTS. This got me both npm
and npx
.
If you installed with pip, to upgrade you can just use:
pip install --upgrade docker-compose
or as Mariyo states with pip3 explicitly:
pip3 install --upgrade docker-compose
~/Desktop $ ng serve
Local workspace file ('angular.json') could not be found.
Error: Local workspace file ('angular.json') could not be found.
at WorkspaceLoader._getProjectWorkspaceFilePath (/usr/lib/node_modules/@angular/cli/models/workspace-loader.js:37:19)
at WorkspaceLoader.loadWorkspace (/usr/lib/node_modules/@angular/cli/models/workspace-loader.js:24:21)
at ServeCommand._loadWorkspaceAndArchitect (/usr/lib/node_modules/@angular/cli/models/architect-command.js:180:32)
at ServeCommand.<anonymous> (/usr/lib/node_modules/@angular/cli/models/architect-command.js:47:25)
at Generator.next (<anonymous>)
at /usr/lib/node_modules/@angular/cli/models/architect-command.js:7:71
at new Promise (<anonymous>)
at __awaiter (/usr/lib/node_modules/@angular/cli/models/architect-command.js:3:12)
at ServeCommand.initialize (/usr/lib/node_modules/@angular/cli/models/architect-command.js:46:16)
at Object.<anonymous> (/usr/lib/node_modules/@angular/cli/models/command-runner.js:87:23)
This is because I haven't choose the Angular project directory.
It should be like:
~/Desktop/angularproject $ ng serve
The right solution would be if you have android studio installed then
Android SDK Tools (Obsolete)
flutter doctor
and it should now prompt you to run flutter doctor --android-licenses
once you run the license command accept all licenses by hitting y and it should solve the problemdotenv
as devDependencies:npm i --save-dev dotenv
.env
file in the root directory:my-react-app/
|- node-modules/
|- public/
|- src/
|- .env
|- .gitignore
|- package.json
|- package.lock.json.
|- README.md
.env
file like below & REACT_APP_ is the compulsory prefix for the variable name.REACT_APP_BASE_URL=http://localhost:8000
REACT_APP_API_KEY=YOUR-API-KEY
For example, I've create a file named base.js
and update it like below:
export const BASE_URL = process.env.REACT_APP_BASE_URL;
export const API_KEY = process.env.REACT_APP_API_KEY;
process.env.REACT_APP_BASE_URL
I just encountered the same issue after adding the bin folder to .gitignore, not sure if that caused the issue.
I solved it by going to Project/Properties/Build Path and I removed the scr folder and added it again.
In my case, I had to create a new app, reinstall my node packages, and copy my src document over. That worked.
Sometimes the problem is in the composer memory limit. In my case, I tried increasing the php memory limit but still got the error.
You can use COMPOSER_MEMORY_LIMIT=-1
to get around that.
Use it as a prefix:
COMPOSER_MEMORY_LIMIT=-1 composer require the/library
You have to prefix it again in the future.
Hope this helps.
In my case I accidentally wrote:
app:displayViewTitle="@string/instructions_defineExtract_confirm_email"
Interestingly, Android Studio were able to navigate the string via CTRL+click. It was just giving Build Time error. Changing to standard "dot seperation" did the trick
app:displayViewTitle="@string/instructions.defineExtract.confirm.email"
i ran into this problem and below is a different solution. I were export my components as
export default {
MyComponent1,
MyComponent2
}
and I imported like this:
import { MyComponent1, MyComponent2} from '@/index'
export default {
name: 'App',
components: {
MyComponent1,
MyComponent2
},
};
And it gave this error.
Just use export { ... }
don't use export default
First you have to deactivate your environment before removing it. You can remove conda environment by using the following command
Suppose your environment name is "sample_env" , you can remove this environment by using
source deactivate
conda remove -n sample_env --all
'--all' will be used to remove all the dependencies
Go to the directory where you put additional libraries and delete duplicated libraries.
Spring Boot 2.0.*
or aboveIf you need to configure multiple data sources, you have to mark one of the DataSource instances as @Primary
, because various auto-configurations down the road expect to be able to get one by type.
If you create your own DataSource, the auto-configuration backs off. In the following example, we provide the exact same feature set as the auto-configuration provides on the primary data source:
@Bean
@Primary
@ConfigurationProperties("app.datasource.first")
public DataSourceProperties firstDataSourceProperties() {
return new DataSourceProperties();
}
@Bean
@Primary
@ConfigurationProperties("app.datasource.first")
public DataSource firstDataSource() {
return firstDataSourceProperties().initializeDataSourceBuilder().build();
}
@Bean
@ConfigurationProperties("app.datasource.second")
public BasicDataSource secondDataSource() {
return DataSourceBuilder.create().type(BasicDataSource.class).build();
}
firstDataSourceProperties
has to be flagged as@Primary
so that the database initializer feature uses your copy (if you use the initializer).
And your application.propoerties
will look something like this:
app.datasource.first.url=jdbc:oracle:thin:@localhost/first
app.datasource.first.username=dbuser
app.datasource.first.password=dbpass
app.datasource.first.driver-class-name=oracle.jdbc.OracleDriver
app.datasource.second.url=jdbc:mariadb://localhost:3306/springboot_mariadb
app.datasource.second.username=dbuser
app.datasource.second.password=dbpass
app.datasource.second.driver-class-name=org.mariadb.jdbc.Driver
The above method is the correct to way to init multiple database in spring boot 2.0 migration and above. More read can be found here.
We can use ls
and many other Linux commands in Windows cmd. Just follow these steps.
Steps:
1) Install Git in your computer - https://git-scm.com/downloads.
2) After installing Git, go to the folder in which Git is installed.
Mostly it will be in C drive
and then Program Files
Folder.
3) In Program Files
folder, you will find the folder named Git
, find the bin
folder
which is inside usr
folder in the Git folder.
In my case, the location for bin folder was - C:\Program Files\Git\usr\bin
4) Add this location (C:\Program Files\Git\usr\bin
) in path variable, in system
environment variables.
5) You are done. Restart cmd and try to run ls
and other Linux commands.
You can specify maven source/target version by adding these properties to your pom.xml file
<properties>
<maven.compiler.source>1.6</maven.compiler.source>
<maven.compiler.target>1.6</maven.compiler.target>
</properties>
Use one way flow syntax property binding:
<div [innerHTML]="comment"></div>
From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script>
tag but keeps safe content such as the <b>
element."
I had this similar error when using wget ...
, and after much unfruitful searching in the Internet, I discovered that it was happening when hostnames were being resolved to IPv6 addresses. I discovered this by comparing the outputs of wget ...
in two machines, one was resolving to IPv4 and it worked there, the other was resolving to IPv6 and it failed there.
So the solution in my case was to run networksetup -setv6off Wi-Fi
on macOS High Sierra 10.13.6. (I discovered this command in this page).
Hope this helps you.
just open terminal and type this command
sudo chmod 666 /var/run/docker.sock
If you are facing this issue on you Mac. Follow these steps
First checking who is owner of this file by using below command
ls -la /usr/local/lib/node_modules
you will find some file like below one of them is below
drwxr-xr-x 3 root wheel 768 May 29 02:21 node_modules
have you notice that above file is own by root, for make changes inside for you need to change owner ship of path.
you can use check who is current user by this command
id -un (in my case user is yamsol)
and then you can change by calling this command (just replace your user name with ownerName)
sudo chown -R ownerName: /usr/local/lib/node_modules
in my case as you know user is "yamsol" i will call this command in this way
sudo chown -R yamsol: /usr/local/lib/node_modules
thats it.
Just default the variable to the expected type:
(number=1) => ...
(number=1.0) => ...
(string='str') ...
If you just want to read an image in Python using the specified libraries only, I will go with
matplotlib
In matplotlib :
import matplotlib.image
read_img = matplotlib.image.imread('your_image.png')
Python version is not supported Uninstall python
https://www.python.org/downloads/release/python-362/
You should check and use the exact version in install page. https://www.tensorflow.org/install/install_windows
python 3.6.2 or python 3.5.2 solved this issue for me
Try this in your docker-compose.yml file
image: php:rc-zts-alpine
Mac: cmd + k
Windows: ctrl + k
If the shortcuts do not work for you, the most likely scenario is that either you or an extension you installed has added an open ended ctrl + k / cmd + k chord to another shortcut.
Open ended meaning, the shortcut does not have an explicit when
clause that excludes terminal focus. There are two possible solutions here.
Solution 1:
If you added the shortcut, simply go to your keybindings.json file and add a when
clause that does not include terminal focus. Example:
{
"key": "cmd+k cmd+c",
"command": "someCommandHere",
"when": "editorTextFocus",
}
Solution 2:
Alternatively, you can add the workbench.action.terminal.clear
command to the very bottom of keybindings.json
, ensuring it takes precedence over other shortcuts. It'd be wise to add a comment so you don't forget and later place new chords below it. Example:
// Keep this keybinding at very bottom of file to ensure terminal clearing.
{
"key": "cmd+k",
"command": "workbench.action.terminal.clear",
"when": "terminalFocus",
}
For additional information, check out this GitHub issue.
In my case Dart also installed separately for dart development with latest. So when IntelliJ suggest me to configure dart, I hit it and then it pointed to C:/tools/dart
that was the case.
So, I had to go to File->Settings->Language & Framework->dart
and add the SDK path to my Flutter sdk path with Dart SDK C:\flutter\bin\cache\dart-sdk
.
Note that as others mentioned if you pointed out the Flutter SDK path, you may not be needed to setup Dart SDK path because of Flutter SDK comes with Dart SDK in it.
I found that running the npm install
command in the same directory where your Angular project is, eliminates these warnings. I do not know the reason why.
Specifically, I was trying to use ng2-completer
$ npm install ng2-completer --save
npm WARN saveError ENOENT: no such file or directory, open 'C:\Work\foo\package.json'
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN enoent ENOENT: no such file or directory, open 'C:\Work\foo\package.json'
npm WARN [email protected] requires a peer of @angular/common@>= 6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/core@>= 6.0.0 but noneis installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/forms@>= 6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN foo No description
npm WARN foo No repository field.
npm WARN foo No README data
npm WARN foo No license field.
I was unable to compile. When I tried again, this time in my Angular project directory which was in foo/foo_app, it worked fine.
cd foo/foo_app
$ npm install ng2-completer --save
This worked for me: added this package source: Microsoft and .net https://www.nuget.org/api/v2/curated-feeds/microsoftdotnet/ then run "dotnet restore" in the console
If it has to be accessible with a global scope
global.fetch = require("node-fetch");
This is a quick dirty fix, please try to eliminate this usage in production code.
The easiest thing to do is to create a file.txt
file and pass the link url link so:
https://www.youtube.com/watch?v=5Lj1BF0Kn8c&list=PL9YFoJnn53xyf9GNZrtiraspAIKc80s1i
make sure to include the -a
parameter in terminal:
youtube-dl -a file.txt
This is a very common question seen on Stackoverflow.
The important part here is not the command displayed in the error, but what the actual error tells you instead.
a Quick breakdown on why this error is received.
cmd.exe
Being a terminal window relies on input and system Environment variables, in order to perform what you request it to do. it does NOT know the location of everything and it also does not know when to distinguish between commands or executable names which are separated by whitespace like space and tab or commands with whitespace as switch variables.
How do I fix this:
When Actual Command/executable fails
First we make sure, is the executable actually installed? If yes, continue with the rest, if not, install it first.
If you have any executable which you are attempting to run from cmd.exe
then you need to tell cmd.exe
where this file is located. There are 2 ways of doing this.
specify the full path to the file.
"C:\My_Files\mycommand.exe"
Add the location of the file to your environment Variables.
Goto:
------> Control Panel-> System-> Advanced System Settings->Environment Variables
In the System Variables
Window, locate path
and select edit
Now simply add your path to the end of the string, seperated by a semicolon ;
as:
;C:\My_Files\
Save the changes and exit. You need to make sure that ANY cmd.exe
windows you had open are then closed and re-opened to allow it to re-import the environment variables.
Now you should be able to run mycommand.exe from any path, within cmd.exe
as the environment is aware of the path to it.
When C:\Program
or Similar fails
This is a very simple error. Each string after a white space is seen as a different command in cmd.exe
terminal, you simply have to enclose the entire path in double quotes in order for cmd.exe
to see it as a single string, and not separate commands.
So to execute C:\Program Files\My-App\Mobile.exe
simply run as:
"C:\Program Files\My-App\Mobile.exe"
All I did is go to my project directory from the cmd (command prompt) I typed java -version.it told me what version it was looking for. so I Installed that version and I changed the path to were the jdk of that version was located .
I followed below steps to install mcrypt for PHP7.2 using PECL.
apt-get install php-pecl
apt-get install libmcrypt-dev libreadline-dev
pecl install mcrypt-1.0.1
You should add "extension=mcrypt.so" to php.ini
Please comment below if you need any assistance. :-)
IMPORTANT !
According to php.net reference many (all) mcrypt functions have been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.
When using MatAutocompleteModule in your angular application, you need to import Input Module also in app.module.ts
Please import below:
import { MatInputModule } from '@angular/material';
try this. If you do like this you don't need to fire always any command You need to fire only one time
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
cat /proc/sys/fs/inotify/max_user_watches
fs.inotify.max_user_watches=524288
this happened after 27,use targetSdkVersion 26 replace, wait for google fixed it
I'm on Android Studio 3.1 Build #AI-173.4670197, built on March 22, 2018 JRE: 1.8.0_152-release-1024-b02 amd64 JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o Windows 10 10.
I had the same issue and it only worked after changing my build.grade file to
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
Prior to this change nothing worked and all compiles would fail. previously my settings were
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_8
docker run mcr.microsoft.com/windows/servercore:ltsc2016
try the above command. what you are pulling should be compatible with the underlying windows version you are in. above will work if you are in windows server 2016.
follow this thread for more info
Writing the whole path/directory eg. (for windows) C:\Programs\Python\Python36-32\Scripts\pip3.exe install mypackage
. This worked well for me when I had trouble with pip.
You can use another shell to execute the same command:
Error I get when i execute:
[jenkins@localhost jenkins_data]$ docker exec -it mysqldb \bin\bash
OCI runtime exec failed: exec failed: container_linux.go:345: starting container process caused "exec: \"binsh\": executable file not found in $PATH": unknown
Solution: When I execute it with below command, using bash shell it works:
[jenkins@localhost jenkins_data]$ docker exec -it mysqldb bash
root@<container-ID>:/#
This worked for me:
Go to the project folder in CLI and type npm install.Go for a similar command if using yarn etc.
Then type npm start if you are using Npm. Go for a similar command if using yarn etc.
The file starts working
The latest 2020 build doesn't have the shorten command line option by default we need to add that option from the configuration.
Run > Edit Configurations > Select the corresponding run configuration and click on Modify options for adding the shorten command-line configuration to the UI.
Select the shorten command line option
Now choose jar manifest from the shorten command line option
I added "\Anaconda3_64\" and "\Anaconda3_64\Scripts\" to the PATH variable. Then I can use conda from powershell or command prompt.
Current Version 1.38.1
I had a problem with intending. The default Command+] is set to 4 and I wanted it to be 2. Installed "Indent 4-to-2" but it changed the entire file and not the selected text.
I changed the tab spacing in settings and it was simple.
Go to Settings
-> Text Editor
-> Tab Size
For me it was some other git URL placed in config file, so I did change it manually:
[remote "origin"]
url = [email protected]:prat3ik/my-project.git
And it was working!!
Spring Boot provide the plugin with maven.
So you can go to your project directory and run
mvn spring-boot:run
This command line run will be easily when you're using spring-boot-devs-tool with auto reload/restart when you have changed you application.
After this npm cache clean --force
may be you can hangup or waiting for further execution
npm WARN using --force I sure hope you know what you are doing.
So you can also use this one. This resolve my issue.
npm install --cache /tmp/empty-cache
The OS is not recognizing 'python' command. So try 'py'
Use 'py -m pip'
I had this error and no meaningful message to tell me what was wrong. I finally removed this line from gradle.properties and got a meaningful error message.
android.enableAapt2=false
In my case somebody on the team had changed a .jpg extension to a .png and the file header didn't match the extension. Fun.
pip install --upgrade django
pip3 install --upgrade django
python -m django --version # 2.0.2
python3 -m django --version # 2.0.2
According to the official ReactJs documentation, you need to pass argument in the default format witch is:
P = {} // default for your props
S = {} // default for yout state
interface Component<P = {}, S = {}> extends ComponentLifecycle<P, S> { }
Or to define your own type like below: (just an exp)
interface IProps {
clients: Readonly<IClientModel[]>;
onSubmit: (data: IClientModel) => void;
}
interface IState {
clients: Readonly<IClientModel[]>;
loading: boolean;
}
class ClientsPage extends React.Component<IProps, IState> {
// ...
}
I had done above solutions , finally this works solved my problem :
Close the visual studio
Run the git bash in the project folder
Write :
git add .
git commit -m "[your comment]"
git push
A POST with httpClient in Angular 6 was also doing an OPTIONS request:
Headers General:
Request URL:https://hp-probook/perl-bin/muziek.pl/=/postData Request Method:OPTIONS Status Code:200 OK Remote Address:127.0.0.1:443 Referrer Policy:no-referrer-when-downgrade
My Perl REST server implements the OPTIONS request with return code 200.
The next POST request Header:
Accept:*/* Accept-Encoding:gzip, deflate, br Accept-Language:nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4 Access-Control-Request-Headers:content-type Access-Control-Request-Method:POST Connection:keep-alive Host:hp-probook Origin:http://localhost:4200 Referer:http://localhost:4200/ User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36
Notice Access-Control-Request-Headers:content-type.
So, my backend perl script uses the following headers:
-"Access-Control-Allow-Origin" => '*', -"Access-Control-Allow-Methods" => 'GET,POST,PATCH,DELETE,PUT,OPTIONS', -"Access-Control-Allow-Headers" => 'Origin, Content-Type, X-Auth-Token, content-type',
With this setup the GET and POST worked for me!
For identifying NaN
values use boolean indexing
:
print(df[df['x'].isnull()])
Then for removing all non-numeric values use to_numeric
with parameter errors='coerce'
- to replace non-numeric values to NaN
s:
df['x'] = pd.to_numeric(df['x'], errors='coerce')
And for remove all rows with NaN
s in column x
use dropna
:
df = df.dropna(subset=['x'])
Last convert values to int
s:
df['x'] = df['x'].astype(int)
Do not use authorization instead of authentication. I should get whole access to service all clients with header. The working code is :
public class TokenAuthenticationHandler : AuthenticationHandler<TokenAuthenticationOptions>
{
public IServiceProvider ServiceProvider { get; set; }
public TokenAuthenticationHandler (IOptionsMonitor<TokenAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, IServiceProvider serviceProvider)
: base (options, logger, encoder, clock)
{
ServiceProvider = serviceProvider;
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync ()
{
var headers = Request.Headers;
var token = "X-Auth-Token".GetHeaderOrCookieValue (Request);
if (string.IsNullOrEmpty (token)) {
return Task.FromResult (AuthenticateResult.Fail ("Token is null"));
}
bool isValidToken = false; // check token here
if (!isValidToken) {
return Task.FromResult (AuthenticateResult.Fail ($"Balancer not authorize token : for token={token}"));
}
var claims = new [] { new Claim ("token", token) };
var identity = new ClaimsIdentity (claims, nameof (TokenAuthenticationHandler));
var ticket = new AuthenticationTicket (new ClaimsPrincipal (identity), this.Scheme.Name);
return Task.FromResult (AuthenticateResult.Success (ticket));
}
}
Startup.cs :
#region Authentication
services.AddAuthentication (o => {
o.DefaultScheme = SchemesNamesConst.TokenAuthenticationDefaultScheme;
})
.AddScheme<TokenAuthenticationOptions, TokenAuthenticationHandler> (SchemesNamesConst.TokenAuthenticationDefaultScheme, o => { });
#endregion
And mycontroller.cs
[Authorize(AuthenticationSchemes = SchemesNamesConst.TokenAuthenticationDefaultScheme)]
public class MainController : BaseController
{ ... }
I can't find TokenAuthenticationOptions now, but it was empty. I found the same class PhoneNumberAuthenticationOptions :
public class PhoneNumberAuthenticationOptions : AuthenticationSchemeOptions
{
public Regex PhoneMask { get; set; }// = new Regex("7\\d{10}");
}
You should define static class SchemesNamesConst
. Something like:
public static class SchemesNamesConst
{
public const string TokenAuthenticationDefaultScheme = "TokenAuthenticationScheme";
}
You are getting error for HttpClient so, you are missing HttpClientModule for that.
You should import it in app.module.ts file like this -
import { HttpClientModule } from '@angular/common/http';
and mention it in the NgModule Decorator like this -
@NgModule({
...
imports:[ HttpClientModule ]
...
})
If this even doesn't work try clearing cookies of the browser and try restarting your server. Hopefully it may work, I was getting the same error.
Let’s create a JSON file, we name it navbar.json you can name it whatever you want!
navbar.json
[
{
"href": "#",
"text": "Home",
"icon": ""
},
{
"href": "#",
"text": "Bundles",
"icon": "",
"children": [
{
"href": "#national",
"text": "National",
"icon": "assets/images/national.svg"
}
]
}
]
Now we’ve created a JSON file with some menu data. We’ll go to app component file and paste the below code.
app.component.ts
import { Component } from '@angular/core';
import menudata from './navbar.json';
@Component({
selector: 'lm-navbar',
templateUrl: './navbar.component.html'
})
export class NavbarComponent {
mainmenu:any = menudata;
}
Now your Angular 7 app is ready to serve the data from the local JSON file.
Go to app.component.html and paste the following code in it.
app.component.html
<ul class="navbar-nav ml-auto">
<li class="nav-item" *ngFor="let menu of mainmenu">
<a class="nav-link" href="{{menu.href}}">{{menu.icon}} {{menu.text}}</a>
<ul class="sub_menu" *ngIf="menu.children && menu.children.length > 0">
<li *ngFor="let sub_menu of menu.children"><a class="nav-link" href="{{sub_menu.href}}"><img src="{{sub_menu.icon}}" class="nav-img" /> {{sub_menu.text}}</a></li>
</ul>
</li>
</ul>
You can use window.location.reload();
in your componentDidMount()
lifecycle method. If you are using react-router
, it has a refresh method to do that.
Edit: If you want to do that after a data update, you might be looking to a re-render
not a reload
and you can do that by using this.setState(). Here is a basic example of it to fire a re-render
after data is fetched.
import React from 'react'
const ROOT_URL = 'https://jsonplaceholder.typicode.com';
const url = `${ROOT_URL}/users`;
class MyComponent extends React.Component {
state = {
users: null
}
componentDidMount() {
fetch(url)
.then(response => response.json())
.then(users => this.setState({users: users}));
}
render() {
const {users} = this.state;
if (users) {
return (
<ul>
{users.map(user => <li>{user.name}</li>)}
</ul>
)
} else {
return (<h1>Loading ...</h1>)
}
}
}
export default MyComponent;
Enable Multidex through build.gradle
of your app module
multiDexEnabled true
Same as below -
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.xx.xxx"
minSdkVersion 15
targetSdkVersion 27
versionCode 1
versionName "1.0"
multiDexEnabled true //Add this
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
shrinkResources true
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
Then follow below steps -
Build
menu -> press the Clean Project
button.Rebuild Project
button from the Build
menu.File -> Invalidate cashes / Restart
compile
is now deprecated so it's better to use implementation
or api
This is the answer to make this work for Java 11 and above since the entire JAXB APIs were removed.
Download Jakarta XML Binding, specifically this zip file. You need only the 3 files within mod folder i.e. jakarta.activation.jar, jakarta.xml.bind-api.jar and jakarta.xml.bind-api.jar and you can toss the rest off.
Move these files to APP_HOME/lib folder. I created a sub folder jaxb inside for this. So, on my macOS system this was: $HOME/Library/Android/sdk/tools/lib/jaxb
Now open sdkmanager using your favorite text editor and under CLASSPATH= add the following at th beginning:
$APP_HOME/lib/jaxb/jakarta.activation.jar:$APP_HOME/lib/jaxb/jakarta.xml.bind-api.jar:$APP_HOME/lib/jaxb/jaxb-impl.jar
So it ended up looking like:
CLASSPATH=$APP_HOME/lib/jaxb/jakarta.activation.jar:$APP_HOME/lib/jaxb/jakarta.xml.bind-api.jar:$APP_HOME/lib/jaxb/jaxb-impl.jar:$APP_HOME/lib/dvlib-26.0.0-dev.jar:$APP_HOME/lib/jimfs-1.1.jar:$APP_HOME/lib/jsr305-1.3.9.jar:$APP_HOME/lib/repository-26.0.0-dev.jar:$APP_HOME/lib/j2objc-annotations-1.1.jar:$APP_HOME/lib/layoutlib-api-26.0.0-dev.jar:$APP_HOME/lib/gson-2.3.jar:$APP_HOME/lib/httpcore-4.2.5.jar:$APP_HOME/lib/commons-logging-1.1.1.jar:$APP_HOME/lib/commons-compress-1.12.jar:$APP_HOME/lib/annotations-26.0.0-dev.jar:$APP_HOME/lib/error_prone_annotations-2.0.18.jar:$APP_HOME/lib/animal-sniffer-annotations-1.14.jar:$APP_HOME/lib/httpclient-4.2.6.jar:$APP_HOME/lib/commons-codec-1.6.jar:$APP_HOME/lib/common-26.0.0-dev.jar:$APP_HOME/lib/kxml2-2.3.0.jar:$APP_HOME/lib/httpmime-4.1.jar:$APP_HOME/lib/annotations-12.0.jar:$APP_HOME/lib/sdklib-26.0.0-dev.jar:$APP_HOME/lib/guava-22.0.jar
And that's pretty much it, should solve the issue.
I did these steps because flutter doctor --android-licenses
was giving me issues. And this fixed it.
Go to the Team Explorer tab then click Branches. In the branches select your branch from remotes/origin. For example, you want to reset your master branch. Right-click at the master branch in remotes/origin then select Reset then click Delete changes. This will reset your local branch and removes all locally committed changes.
I recently started using VMWare Octant https://github.com/vmware-tanzu/octant. This is a better UI than the Kubernetes Dashboard. You can view the Kubernetes cluster and look at the details of the cluster and the PODS. This will allow you to check the logs and open a terminal into the POD(s).
If you're on Windows I suggest manually uninstalling node and installing chocolatey to handle your node installation. choco
is a great CLI for provisioning a ton of popular software.
Then you can just do,
choco install nodejs --version $VersionNumber
and if you already have it installed via chocolatey you can do,
choco uninstall nodejs
choco install nodejs --version $VersionNumber
For example,
choco uninstall nodejs
choco install nodejs --version 12.9.1
For those who, like me, came from Google for the keyword "upload file colab":
from google.colab import files
uploaded = files.upload()
Inside your git repository directory, run git config user.name
.
Why is running this command within your git repo directory important?
If you are outside of a git repository, git config user.name
gives you the value of user.name
at global level. When you make a commit, the associated user name is read at local level.
Although unlikely, let's say user.name
is defined as foo
at global level, but bar
at local level. Then, when you run git config user.name
outside of the git repo directory, it gives bar
. However, when you really commits something, the associated value is foo
.
Git config variables can be stored in 3 different levels. Each level overrides values in the previous level.
1. System level (applied to every user on the system and all their repositories)
git config --list --system
(may need sudo
)git config --system color.ui true
git config --edit --system
2. Global level (values specific personally to you, the user. )
git config --list --global
git config --global user.name xyz
git config --edit --global
3. Repository level (specific to that single repository)
git config --list --local
git config --local core.ignorecase true
(--local
optional)git config --edit --local
(--local
optional)How to view all settings?
git config --list
, showing system, global, and (if inside a repository) local configsgit config --list --show-origin
, also shows the origin file of each config itemHow to read one particular config?
git config user.name
to get user.name
, for example.--system
, --global
, --local
to read that value at a particular level.Reference: 1.6 Getting Started - First-Time Git Setup
If anyone get this error for ionic cordova install . just use this code npm install --no-optional
in your cmd.
And then run this code npm install -g ionic@latest cordova
In your case removing ./ should solve the issue. I had another case wherein I was using a directory from the parent directory and docker can only access files present below the directory where Dockerfile is present so if I have a directory structure /root/dir and Dockerfile /root/dir/Dockerfile
I cannot copy do the following
COPY root/src /opt/src
pip install pymysql
Then, edit the __init__.py file in your project origin dir(the same as settings.py)
add:
import pymysql
pymysql.install_as_MySQLdb()
Yes you can upload your git repo from vs code. You have to get in the projects working directory and type git init in the terminal. Then add the files to your repository like you do with regular git commits.
ng g c component-name
For specify custom location: ng g c specific-folder/component-name
here component-name
will be created inside specific-folder.
Similarl approach can be used for generating other components like directive
, pipe
, service
, class
, guard
, interface
, enum
, module
, etc.
You can see the errors after stopping debbuging by choosing the option to display ASP.NET Core Web Server output in the output window. In my case I was pointing to a different templateUrl.
Just use the gcloud projects list
to get the project you have . Get the PROJECT_ID of the poject to use
After that use gcloud set project --project=PROJECT_ID
to set the project.
You have to dispatch after the async request ends.
This would work:
export function bindComments(postId) {
return function(dispatch) {
return API.fetchComments(postId).then(comments => {
// dispatch
dispatch({
type: BIND_COMMENTS,
comments,
postId
});
});
};
}
Just a note for people who may have found this later (and want java way of achieving this); FirefoxOptions
is also capable of enabling the headless mode:
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setHeadless(true);
clear site data in your browser. and it will be fixed. sometimes when you run proxies, vpns or some other programs this error happens.
Context: I was having a similar issue "Command CompileStoryboard failed with a nonzero exit code" after trying to build an iOS flutter app with the latest and Android studio and XCode 11.3 (new installation on Mojave). This was an existing flutter android app I had built with Android studio on Windows 10.
Tried and failed: Command+Shift+K, Command+B, Delete Derived data, SWIFT_ENABLE_BATCH_MODE = NO
Solution: - Open Finder and Navigate to project name > ios > Runner > Base.Iproj - Delete .storyboard files (main and launch) - Open terminal and run "flutter create ." - Open Xcode and run
DON'T DO THIS IN PRODUCTION
The answer given by @ravi-luthra technically works but it has some issues!
In my case, I was just trying to recover disk space. The lib/docker/overlay
folder was taking 30GB of space and I only run a few containers regularly. Looks like docker has some issue with data leakage and some of the temporary data are not cleared when the container stops.
So I went ahead and deleted all the contents of lib/docker/overlay
folder. After that, My docker instance became un-useable. When I tried to run or build any container, It gave me this error:
failed to create rwlayer: symlink ../04578d9f8e428b693174c6eb9a80111c907724cc22129761ce14a4c8cb4f1d7c/diff /var/lib/docker/overlay2/l/C3F33OLORAASNIYB3ZDATH2HJ7: no such file or directory
Then with some trial and error, I solved this issue by running
(WARNING: This will delete all your data inside docker volumes)
docker system prune --volumes -a
So It is not recommended to do such dirty clean ups unless you completely understand how the system works.
add
type: NodePort for the Service
And then run this command:
kubectl apply -f kubernetes-dashboard.yaml
Find the exposed port with the command :
kubectl get services -n kube-system
You should be able to get the dashboard at http://hostname:exposedport/ with no authentication
You can remove the entire line below:
.map((res: Response) => res.json());
No need to use the map method at all.
Step 1 : Delete "npm" folder from the following path
C:\Users\YourUserName\AppData\Roaming
Step 2 : Once you have the "npm" folder deleted, uninstall Node.Js.
Step 3 : Reinstall Node.JS
Step 4 : Install Angular CLI Using this command npm install -g @angular/cli@latest
Step 5: Now try : ng --version
or ng -v
You get this error when you wrongly add shared service to "declaration" in your appmodules instead of adding it to "provider".
because you didn't start mongod process before you try starting mongo shell.
Start mongod server
mongod
Open another terminal window
Start mongo shell
mongo
You should do mkdir build
and cd build
while inside opencv
folder, not the opencv-contrib
folder. The CMakeLists.txt
is there.
For Linux users (I'm using a Debian Distro, Kali) Here's how I resolved mine.
If you don't already have jdk-8, you want to get it at oracle's site
https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
I got the jdk-8u191-linux-x64.tar.gz
Step 1 - Installing Java Move and unpack it at a suitable location like so
$ mv jdk-8u191-linux-x64.tar.gz /suitablelocation/
$ tar -xzvf /suitablelocation/jdk-8u191-linux-x64.tar.gz
You should get an unzipped folder like jdk1.8.0_191 You can delete the tarball afterwards to conserve space
Step 2 - Setting up alternatives to the default java location
$ update-alternatives --install /usr/bin/java java /suitablelocation/jdk1.8.0_191/bin/java 1
$ update-alternatives --install /usr/bin/javac javac /suitablelocation/jdk1.8.0_191/bin/javac 1
Step 3 - Selecting your alternatives as default
$ update-alternatives --set java /suitablelocation/jdk1.8.0_191/bin/java
$ update-alternatives --set javac /suitablelocation/jdk1.8.0_191/bin/javac
Step 4 - Confirming default java version
$ java -version
Notes
I don't know what happened, but the following did the work (under mac os catalina)
$ brew install pipenv
$ brew update pipenv
after doing this i am able to use
$ pipenv install [package_name]
To check if a specific package is installed:
conda list html5lib
which outputs something like this if installed:
# packages in environment at C:\ProgramData\Anaconda3:
#
# Name Version Build Channel
html5lib 1.0.1 py37_0
or something like this if not installed:
# packages in environment at C:\ProgramData\Anaconda3:
#
# Name Version Build Channel
you don't need to type the exact package name. Partial matches are supported:
conda list html
This outputs all installed packages containing 'html':
# packages in environment at C:\ProgramData\Anaconda3:
#
# Name Version Build Channel
html5lib 1.0.1 py37_0
sphinxcontrib-htmlhelp 1.0.2 py_0
sphinxcontrib-serializinghtml 1.1.3 py_0
Update to the latest conda and latest navigator will resolve this issue.
Open the Anaconda Prompt and type
and
Angular CLI ng v does output few more thing than just the version.
If you only want the version from it the you can add pipe grep and filter for angular like:
ng v | grep 'Angular:'
OUTPUT:
Angular: #.#.# <-- VERSION
For this, I have an alias which is
alias ngv='ng v | grep 'Angular:''
Then just use ngv
For express, upgrade your express library to 4.17.1
which is the latest stable version. Then;
In CorsOption: Set origin
to your localhost url or your frontend production url and credentials
to true
e.g
const corsOptions = {
origin: config.get("origin"),
credentials: true,
};
I set my origin dynamically using config npm module.
Then , in res.cookie:
For localhost: you do not need to set sameSite and secure option at all, you can set httpOnly
to true
for http cookie to prevent XSS attack and other useful options depending on your use case.
For production environment, you need to set sameSite
to none
for cross-origin request and secure
to true
. Remember sameSite
works with express latest version only as at now and latest chrome version only set cookie over https
, thus the need for secure option.
Here is how I made mine dynamic
res
.cookie("access_token", token, {
httpOnly: true,
sameSite: app.get("env") === "development" ? true : "none",
secure: app.get("env") === "development" ? false : true,
})
None of the above worked for me but the below did:
sudo chown -R user: /Library/Frameworks/Python.framework/Versions/3.9/share/jupyter/
Where user is your username.
add this in your app/build.gradle. It will work
implementation 'com.android.support:design:27.1.0'
When you install Django on your computer all things go fine but when you install a Virtual environment it gets separated from all things. You will know it's importance when you will make a final project and deploy it to any cloud or hosting.
Just reinstall Django in the virtual environment and baam:
pip install Django
and then just run the command for testing:
python manage.py runsever
and you are all done.
Above two answers are correct but didn't work for me.
docker container ls
docker container ls -a
and after that it showed all the process previously exited and running.docker stop <container id>
or docker container stop <container id>
didn't work docker rm -f <container id>
and it worked.docker container ls -a
and this process wasn't present.If you are using Ubuntu 18.04 or higher with python3.xxx then try this command
$ sudo apt install python3-sklearn
then try your command. hope it will work
For me it was changing.
this.name = response.data;
To what computed returns so;
this.$store.state.name = response.data;
In simple terms you need to build your payload into a key array
payload = {'key1': 'value1', 'key2': 'value2'}
Then send the payload directly to the action
this.$store.dispatch('yourAction', payload)
No change in your action
yourAction: ({commit}, payload) => {
commit('YOUR_MUTATION', payload )
},
In your mutation call the values with the key
'YOUR_MUTATION' (state, payload ){
state.state1 = payload.key1
state.state2 = payload.key2
},
For PHP7.1 install this
sudo apt-get install php7.1-zip
I had a similar issue and solved after running these instructions!
npm install npm -g
npm install --save-dev @angular/cli@latest
npm install
npm start
I use the following to create a temp exact as the table but without the identity:
SELECT TOP 0 CONVERT(INT,0)myid,* INTO #temp FROM originaltable
ALTER TABLE #temp DROP COLUMN id
EXEC tempdb.sys.sp_rename N'#temp.myid', N'id', N'COLUMN'
Gets a warning about renames but no big deal. I use this on production class systems. Helps make sure the copy will follow any future table modifications and the temp produced is capable of getting rows additional times within a task. Please note that the PK constraint is also removed - if you need it you can add it at the end.
The problem I think is that the view is still the activity, not the fragment. The fragments doesn't have any independent view of its own and is attached to the parent activities view. Thats why the event ends up in the Activity, not the fragment. Its unfortunate, but I think you will need some code to make this work.
What I've been doing during conversions is simply adding a click listener that calls the old event handler.
for instance:
final Button loginButton = (Button) view.findViewById(R.id.loginButton);
loginButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
onLoginClicked(v);
}
});
Use vertical-align:top; for the element you want at the top, as I have demonstrated on your jsfiddle.
No, you can't. Just declare the variable outside the function. You don't have to declare it at the same time as you assign the value:
var trailimage;
function makeObj(address) {
trailimage = [address, 50, 50];
To correct this mistake very easily, If you read logs. The problem occurs because of the sudden shutdown of the IDEA. And the log files do not correctly write data. Just delete the file on the path
C:/Users/{UserName}/.Gradle/demon/{gradleVersion}/registry.bin.lock.
List
is an interface. Interfaces cannot be instantiated. Only concrete types can be instantiated. You probably want to use an ArrayList
, which is an implementation of the List
interface.
List<Product> products = new ArrayList<Product>();
Actually, I believe you want to use the __getattr__
special method instead.
Quote from the Python docs:
__getattr__( self, name)
Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception.
Note that if the attribute is found through the normal mechanism,__getattr__()
is not called. (This is an intentional asymmetry between__getattr__()
and__setattr__()
.) This is done both for efficiency reasons and because otherwise__setattr__()
would have no way to access other attributes of the instance. Note that at least for instance variables, you can fake total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object). See the__getattribute__()
method below for a way to actually get total control in new-style classes.
Note: for this to work, the instance should not have a test
attribute, so the line self.test=20
should be removed.
use this format....
//get current date in javascript
var currentDate = new Date();
// for getting a date from a textbox as string format
var newDate=document.getElementById("<%=textBox1.ClientID%>").value;
// convert this date to date time
var MyDate = new Date(newDate);
Specifically, to install the pdf.js plugin for firefox, you do not use the app store. Instead, go to addons.mozilla.org from inside mozilla and install it from there. Also, to see if it's installed properly, go to the menu Tools:Add-ons (not the "about:plugins" url as you might think from the desktop version).
(New account, otherwise I'd put this as a comment on the answer above)
I did the test (but it is not your example) and the data does not return them orderly or complete
>>> ind = ['p5','p1','p8','p4','p2','p8']
>>> newind = {x.replace('p','') for x in ind}
>>> newind
{'1', '2', '8', '5', '4'}
I proved that this works:
>>> ind = ['p5','p1','p8','p4','p2','p8']
>>> newind = [x.replace('p','') for x in ind]
>>> newind
['5', '1', '8', '4', '2', '8']
or
>>> newind = []
>>> ind = ['p5','p1','p8','p4','p2','p8']
>>> for x in ind:
... newind.append(x.replace('p',''))
>>> newind
['5', '1', '8', '4', '2', '8']
You should define source code encoding, add this to the top of your script:
# -*- coding: utf-8 -*-
The reason why it works differently in console and in the IDE is, likely, because of different default encodings set. You can check it by running:
import sys
print sys.getdefaultencoding()
Also see:
What is the difference between Git and GitHub?
Linus Torvalds would kill you for this. Git is the name of the version manager program he wrote. GitHub is a website on which there are source code repositories manageable by Git. Thus, GitHub is completely unrelated to the original Git tool.
Is git saving every repository locally (in the user's machine) and in GitHub?
If you commit changes, it stores locally. Then, if you push the commits, it also sotres them remotely.
Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?
You can, but I'm sure you don't want to manually set up a git server for yourself. Benefits of GitHub? Well, easy to use, lot of people know it so others may find your code and follow/fork it to make improvements as well.
How does Git compare to a backup system such as Time Machine?
Git is specifically designed and optimized for source code.
Is this a manual process, in other words if you don't commit you wont have a new version of the changes made?
Exactly.
If are not collaborating and you are already using a backup system why would you use Git?
See #4.
To see a list of current buffers, I use:
:ls
To open a new file, I use
:e ../myFile.pl
with enhanced tab completion (put set wildmenu
in your .vimrc
).
Note: you can also use :find
which will search a set of paths for you, but you need to customize those paths first.
To switch between all open files, I use
:b myfile
with enhanced tab completion (still set wildmenu
).
Note: :b#
chooses the last visited file, so you can use it to switch quickly between two files.
Ctrl-W s
and Ctrl-W v
to split the current window horizontally and vertically. You can also use :split
and :vertical split
(:sp
and :vs
)
Ctrl-W w
to switch between open windows, and Ctrl-W h
(or j
or k
or l
) to navigate through open windows.
Ctrl-W c
to close the current window, and Ctrl-W o
to close all windows except the current one.
Starting vim with a -o
or -O
flag opens each file in its own split.
With all these I don't need tabs in Vim, and my fingers find my buffers, not my eyes.
Note: if you want all files to go to the same instance of Vim, start Vim with the --remote-silent
option.
You are missing the ?
in the second URL (Also, it should be URL-encoded to be %3F
).
Also, I believe that the remaining &
need to be URL, not HTML-encoded. Change &second=12&third=5
to %26second=12%26third=5
and everything should just work.
This:
&u=http://www.foobar.com/first=12&sec=25&position=2
should be:
&u=http://www.foobar.com/%3Ffirst=12%26sec=25%26position=2
Here is a way to remove a specific commit id knowing only the commit id you would like to remove.
git rebase --onto commit-id^ commit-id
Note that this actually removes the change that was introduced by the commit.
Try spannableStringbuilder. Using this we can create string with multiple font sizes.
You should use .NET Core, instead of .NET Framework or Xamarin, in the following 6 typical scenarios according to the documentation here.
1. Cross-Platform needs
Clearly, if your goal is to have an application (web/service) that should be able to run across platforms (Windows, Linux and MacOS), the best choice in the .NET ecosystem is to use .NET Core as its runtime (CoreCLR) and libraries are cross-platform. The other choice is to use the Mono Project.
Both choices are open source, but .NET Core is directly and officially supported by Microsoft and will have a heavy investment moving forward.
When using .NET Core across platforms, the best development experience exists on Windows with the Visual Studio IDE which supports many productivity features including project management, debugging, source control, refactoring, rich editing including Intellisense, testing and much more. But rich development is also supported using Visual Studio Code on Mac, Linux and Windows including intellisense and debugging. Even third party editors like Sublime, Emacs, VI and more work well and can get editor intellisense using the open source Omnisharp project.
2. Microservices
When you are building a microservices oriented system composed of multiple independent, dynamically scalable, stateful or stateless microservices, the great advantage that you have here is that you can use different technologies/frameworks/languages at a microservice level. That allows you to use the best approach and technology per micro areas in your system, so if you want to build very performant and scalable microservices, you should use .NET Core. Eventually, if you need to use any .NET Framework library that is not compatible with .NET Core, there’s no issue, you can build that microservice with the .NET Framework and in the future you might be able to substitute it with the .NET Core.
The infrastructure platform you could use are many. Ideally, for large and complex microservice systems, you should use Azure Service Fabric. But for stateless microservices you can also use other products like Azure App Service or Azure Functions.
Note that as of June 2016, not every technology within Azure supports the .NET Core, but .NET Core support in Azure will be increasing dramatically now that .NET Core is RTM released.
3. Best performant and scalable systems
When your system needs the best possible performance and scalability so you get the best responsiveness no matter how many users you have, then is where .NET Core and ASP.NET Core really shine. The more you can do with the same amount of infrastructure/hardware, the richer the experience you’ll have for your end users – at a lower cost.
The days of Moore’s law performance improvements for single CPUs does not apply anymore; yet you need to do more while your system is growing and need higher scalability and performance for everyday’ s more demanding users which are growing exponentially in numbers. You need to get more efficient, optimize everywhere, and scale better across clusters of machines, VMs and CPU cores, ultimately. It is not just a matter of user’s satisfaction; it can also make a huge difference in cost/TCO. This is why it is important to strive for performance and scalability.
As mentioned, if you can isolate small pieces of your system as microservices or any other loosely-coupled approach, it’ll be better as you’ll be able to not just evolve each small piece/microservice independently and have a better long-term agility and maintenance, but also you’ll be able to use any other technology at a microservice level if what you need to do is not compatible with .NET Core. And eventually you’d be able to refactor it and bring it to .NET Core when possible.
4. Command line style development for Mac, Linux or Windows.
This approach is optional when using .NET Core. You can also use the full Visual Studio IDE, of course. But if you are a developer that wants to develop with lightweight editors and heavy use of command line, .NET Core is designed for CLI. It provides simple command line tools available on all supported platforms, enabling developers to build and test applications with a minimal installation on developer, lab or production machines. Editors like Visual Studio Code use the same command line tools for their development experiences. And IDE’s like Visual Studio use the same CLI tools but hide them behind a rich IDE experience. Developers can now choose the level they want to interact with the tool chain from CLI to editor to IDE.
5. Need side by side of .NET versions per application level.
If you want to be able to install applications with dependencies on different versions of frameworks in .NET, you need to use .NET Core which provides 100% side-by side as explained previously in this document.
6. Windows 10 UWP .NET apps.
In addition, you may also want to read:
After looking at all the suggestions here, I've discovered a few things which I hope will be useful to others in my position:
hop is right to point me back
at /etc/init.d/functions
: the
daemon
function already allows you
to set an alternate user:
daemon --user=my_user my_cmd &>/dev/null &
This is implemented by wrapping the
process invocation with runuser
-
more on this later.
Jonathan Leffler is right: there is setuid in Python:
import os
os.setuid(501) # UID of my_user is 501
I still don't think you can setuid from inside a JVM, however.
Neither su
nor runuser
gracefully handle the case where you
ask to run a command as the user you
already are. E.g.:
[my_user@my_host]$ id
uid=500(my_user) gid=500(my_user) groups=500(my_user)
[my_user@my_host]$ su my_user -c "id"
Password: # don't want to be prompted!
uid=500(my_user) gid=500(my_user) groups=500(my_user)
To workaround that behaviour of su
and runuser
, I've changed my init script to something like:
if [[ "$USER" == "my_user" ]]
then
daemon my_cmd &>/dev/null &
else
daemon --user=my_user my_cmd &>/dev/null &
fi
Thanks all for your help!
Well, they don't do the same thing, really.
$_SERVER['REQUEST_METHOD']
contains the request method (surprise).
$_POST
contains any post data.
It's possible for a POST request to contain no POST data.
I check the request method — I actually never thought about testing the $_POST
array. I check the required post fields, though. So an empty post request would give the user a lot of error messages - which makes sense to me.
Use typeof arrayName[index] === 'undefined'
i.e.
if(typeof arrayName[index] === 'undefined') {
// does not exist
}
else {
// does exist
}
cd to sessions directory and then:
1) View sessions older than 40 min:
find . -amin +40 -exec stat -c "%n %y" {} \;
2) Remove sessions older than 40 min:
find . -amin +40 -exec rm {} \;
I think error is not coming from the specified line but from the first 3 lines. Try this instead :
node {
stage("first") {
def foo = "foo"
sh "echo ${foo}"
}
}
I think you had some extra lines that are not valid...
From declaractive pipeline model documentation, it seems that you have to use an environment
declaration block to declare your variables, e.g.:
pipeline {
environment {
FOO = "foo"
}
agent none
stages {
stage("first") {
sh "echo ${FOO}"
}
}
}
Each call to nextLine()
moves onto the next line, so when you are actually at the last readable line and the while
check passes inspection, the next call to nextLine()
will return EOF
.
Perhaps you could do one of the following instead:
If fileReader
is of type Scanner
:
while ((line = fileReader.hasNextLine()) != null) {
String line = fileReader.nextLine();
System.out.println(line);
}
If fileReader
is of type BufferedReader
:
String line;
while ((line = fileReader.readLine()) != null) {
System.out.println(line);
}
So you're reading the current line in the while condition and saving the line in a string for later use.
Here is one-liner to verify certificate chain:
openssl verify -verbose -x509_strict -CAfile ca.pem cert_chain.pem
This doesn't require to install CA anywhere.
See How does an SSL certificate chain bundle work? for details.
Threaded:
/// <summary>
/// Usage: var timer = SetIntervalThread(DoThis, 1000);
/// UI Usage: BeginInvoke((Action)(() =>{ SetIntervalThread(DoThis, 1000); }));
/// </summary>
/// <returns>Returns a timer object which can be disposed.</returns>
public static System.Threading.Timer SetIntervalThread(Action Act, int Interval)
{
TimerStateManager state = new TimerStateManager();
System.Threading.Timer tmr = new System.Threading.Timer(new TimerCallback(_ => Act()), state, Interval, Interval);
state.TimerObject = tmr;
return tmr;
}
Regular
/// <summary>
/// Usage: var timer = SetInterval(DoThis, 1000);
/// UI Usage: BeginInvoke((Action)(() =>{ SetInterval(DoThis, 1000); }));
/// </summary>
/// <returns>Returns a timer object which can be stopped and disposed.</returns>
public static System.Timers.Timer SetInterval(Action Act, int Interval)
{
System.Timers.Timer tmr = new System.Timers.Timer();
tmr.Elapsed += (sender, args) => Act();
tmr.AutoReset = true;
tmr.Interval = Interval;
tmr.Start();
return tmr;
}
Try:
cl /v
Actually, any time I give cl an argument, it prints out the version number on the first line.
You could just feed it a garbage argument and then parse the first line of the output, which contains the verison number.
To delete trailing whitespace at end of line in a file portably, use ed
:
test -s file &&
printf '%s\n' H ',g/[[:space:]]*$/s///' 'wq' | ed -s file
I think the best option is to use guide_legend
within guides
:
p + guides(fill=guide_legend(
keywidth=0.1,
keyheight=0.1,
default.unit="inch")
)
Note the use of default.unit
, no need to load grid
package.
Once you have the source trees, e.g.
diff -ENwbur repos1/ repos2/
Even better
diff -ENwbur repos1/ repos2/ | kompare -o -
and have a crack at it in a good gui tool :)
you can find multiple options listed at http://httpd.apache.org/docs/current/platform/windows.html#down
ApacheHaus Apache Lounge BitNami WAMP Stack WampServer XAMPP
I had this issue, when I was browsing internet through my mobile hotspot. it was also compressing images and added the following script at the bottom of body tag
<script language="javascript"><!--
bmi_SafeAddOnload(bmi_load,"bmi_orig_img");//-->
</script>
When I connected to proper wifi connection, all seems to work find for me. Hope this help someone.
Scala is supported. See example.
Support for other languages is problematic:
7) Something like the dx tool can be forced into the phone, so that Java code could in principle continue to generate bytecodes, yet have them be translated into a VM-runnable form. But, at present, Java code cannot be generated on the fly. This means Dalvik cannot run dynamic languages (JRuby, Jython, Groovy). Yet. (Perhaps the dex format needs a detuned variant which can be easily generated from bytecodes.)
Regardless of what error Oracle SQL Developer may indicate in the syntax highlighting, actually running your alter
statement exactly the way you originally had it works perfectly:
ALTER TABLE TEST_PROJECT2 MODIFY proj_name VARCHAR2(300);
You only need to add parenthesis if you need to alter more than one column at once, such as:
ALTER TABLE TEST_PROJECT2 MODIFY (proj_name VARCHAR2(400), proj_desc VARCHAR2(400));
This will not work java -cp lib\*.jar -jar myproject.jar
. You have to put it jar by jar.
So in case of commons-codec-1.3.jar
.
java -cp lib/commons-codec-1.3.jar;lib/next_jar.jar
and so on.
The other solution might be putting all your jars to ext
directory of your JRE. This is ok if you are using a standalone JRE. If you are using the same JRE for running more than one application I do not recommend doing it.
Note that in case of IE 7 and IE 9 if statment will give true for ("onhashchange" in windows) but the window.onhashchange will never fire, so its better to store hash and check it after every 100 millisecond whether its changed or not for all versions of IE.
if (("onhashchange" in window) && !($.browser.msie)) {
window.onhashchange = function () {
alert(window.location.hash);
}
// Or $(window).bind( 'hashchange',function(e) {
// alert(window.location.hash);
// });
}
else {
var prevHash = window.location.hash;
window.setInterval(function () {
if (window.location.hash != prevHash) {
prevHash = window.location.hash;
alert(window.location.hash);
}
}, 100);
}
So ... you need to change some things in your code
<form method="POST" id="form-pass">
Password: <input type="text" name="pwd" id="input-pwd">
<input type="submit" value="Submit">
</form>
<script>
var form = document.querySelector('#form-pass');
var pwd = document.querySelector('#input-pwd');
pwd.focus();
form.onsubmit = checkForm;
function checkForm() {
alert(pwd.value);
}
</script>
Try this way.
Create a dummy DOM element and add the string to it. Then, you can manipulate it like any DOM element.
var el = document.createElement( 'html' );
el.innerHTML = "<html><head><title>titleTest</title></head><body><a href='test0'>test01</a><a href='test1'>test02</a><a href='test2'>test03</a></body></html>";
el.getElementsByTagName( 'a' ); // Live NodeList of your anchor elements
Edit: adding a jQuery answer to please the fans!
var el = $( '<div></div>' );
el.html("<html><head><title>titleTest</title></head><body><a href='test0'>test01</a><a href='test1'>test02</a><a href='test2'>test03</a></body></html>");
$('a', el) // All the anchor elements
Actually I have imports messed up. In latest version of RxJS we can import it like that:
import 'rxjs/add/observable/of';
SOLVED: Always be sure to update your Xcode folks!
Protip: And don't do it from the apple store (but always do it from an official apple website of course)
tip from: http://ericasadun.com/2016/03/22/xcode-upgrades-lessons-learned/
official apple download page: https://developer.apple.com/download/more/
For those who are unable to resolve with above method
Go to project settings in Xcode. Menu File->Project Settings
Go to per-User Project Settings section.
Click on advanced.
Select Xcode Default option. previously this used to be Legacy for my project.
I have analysed on similar lines and concluded that clean is causing the archive to fail. So, the new build system is not clearing the custom/legacy build directory.
delete the build/ folder in ios/ and rerun if that doesn't do any change then
File -> Project Settings (or WorkSpace Settings) -> Build System -> Legacy Build System
Rerun and voilà!
If it still Fails you need to clean full project
Do the following:
npm cache clean --force
react-native eject
npm install
react-native link
react-native run-ios
Catalina Update / Desktop Permissions
I come across this once a year on macOS. I usually use apache2 for hosting a folder on my desktop.
If you are trying to give access to the desktop
folder you need to follow this to allow httpd to have access to all folders: https://apple.stackexchange.com/a/373139/353465
Follow the given steps in order to setup it up to use MySQL database:
1) Install MySQL Database Connector :
sudo apt-get install libmysqlclient-dev
2) Install the mysqlclient library :
pip install mysqlclient
3) Install MySQL server, with the following command :
sudo apt-get install mysql-server
4) Create the Database :
i) Verify that the MySQL service is running:
systemctl status mysql.service
ii) Log in with your MySQL credentials using the following command where -u is the flag for declaring your username and -p is the flag that tells MySQL that this user requires a password :
mysql -u db_user -p
iii) CREATE DATABASE db_name;
iv) Exit MySQL server, press CTRL + D.
5) Add the MySQL Database Connection to your Application:
i) Navigate to the settings.py file and replace the current DATABASES lines with the following:
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS': {
'read_default_file': '/etc/mysql/my.cnf',
},
}
}
...
ii) Next, let’s edit the config file so that it has your MySQL credentials. Use vi as sudo to edit the file and add the following information:
sudo vi /etc/mysql/my.cnf
database = db_name
user = db_user
password = db_password
default-character-set = utf8
6) Once the file has been edited, we need to restart MySQL for the changes to take effect :
systemctl daemon-reload
systemctl restart mysql
7) Test MySQL Connection to Application:
python manage.py runserver your-server-ip:8000
I had the same problem and I solved it by using an absolute import instead of a relative one.
for example in your case, you will write something like this:
from app.mymodule import myclass
You can see in the documentation.
Note that relative imports are based on the name of the current module. Since the name of the main module is always "
__main__
", modules intended for use as the main module of a Python application must always use absolute imports.
In other words, you want to pipe stdout into one filter (tee bbb.out
) and stderr into another filter (tee ccc.out
). There is no standard way to pipe anything other than stdout into another command, but you can work around that by juggling file descriptors.
{ { ./aaa.sh | tee bbb.out; } 2>&1 1>&3 | tee ccc.out; } 3>&1 1>&2
See also How to grep standard error stream (stderr)? and When would you use an additional file descriptor?
In bash (and ksh and zsh), but not in other POSIX shells such as dash, you can use process substitution:
./aaa.sh > >(tee bbb.out) 2> >(tee ccc.out)
Beware that in bash, this command returns as soon as ./aaa.sh
finishes, even if the tee
commands are still executed (ksh and zsh do wait for the subprocesses). This may be a problem if you do something like ./aaa.sh > >(tee bbb.out) 2> >(tee ccc.out); process_logs bbb.out ccc.out
. In that case, use file descriptor juggling or ksh/zsh instead.
You can charge the customer more if you claim it's a web application :)
Seriously, the line is fine. Historically, web apps were the ones with code and/or scripts (in Perl/CGI, PHP, ASP, etc.) on the server, and sites were the ones with static pages. Currently, everyone and their uncle's cat are running forums, guestbooks, CMS - that's all server code.
Another distinction is along the subject matter lines. If it's a line-of-business solution, then it's an app. If it's consumer oriented - they call it a site. Although technology-wise, it's more or less the same.
Just add ToolTip tool from toolbox to the form and add this code in a mousemove event of any control you want to make the tooltip start on its mousemove
private void textBox3_MouseMove(object sender, MouseEventArgs e)
{
toolTip1.SetToolTip(textBox3,"Tooltip text"); // you can change the first parameter (textbox3) on any control you wanna focus
}
hope it helps
peace
Try this one.
String[] array1= new String[]{};
System.out.println(array1.length);
String[] array2= new String[0];
System.out.println(array2.length);
Note: there is no byte code difference between new String[]{}; and new String[0];
new String[]{}
is array initialization with values.
new String[0];
is array declaration(only allocating memory)
new String[10]{};
is not allowed because new String[10]{ may be here 100 values};
I don't know of any JVM that actually checks the JAVA_OPTS
environment variable. Usually this is used in scripts which launch the JVM and they usually just add it to the java
command-line.
The key thing to understand here is that arguments to java
that come before the -jar analyse.jar
bit will only affect the JVM and won't be passed along to your program. So, modifying the java
line in your script to:
java $JAVA_OPTS -jar analyse.jar $*
Should "just work".
Or simply
add to your element
[ngStyle]="{'color': myVariableColor}"
eg
<mat-icon [ngStyle]="{'color': myVariableColor}">{{ getActivityIcon() }}</mat-icon>
Where color
can be defined at another component etc
The :
is a bitfield. As for !!
, that is logical double negation and so returns 0
for false or 1
for true. And the -
is a minus sign, i.e. arithmetic negation.
It's all just a trick to get the compiler to barf on invalid inputs.
Consider BUILD_BUG_ON_ZERO
. When -!!(e)
evaluates to a negative value, that produces a compile error. Otherwise -!!(e)
evaluates to 0, and a 0 width bitfield has size of 0. And hence the macro evaluates to a size_t
with value 0.
The name is weak in my view because the build in fact fails when the input is not zero.
BUILD_BUG_ON_NULL
is very similar, but yields a pointer rather than an int
.
Replacing all zeroes to NA:
df[df == 0] <- NA
Explanation
1. It is not NULL
what you should want to replace zeroes with. As it says in ?'NULL'
,
NULL represents the null object in R
which is unique and, I guess, can be seen as the most uninformative and empty object.1 Then it becomes not so surprising that
data.frame(x = c(1, NULL, 2))
# x
# 1 1
# 2 2
That is, R does not reserve any space for this null object.2 Meanwhile, looking at ?'NA'
we see that
NA is a logical constant of length 1 which contains a missing value indicator. NA can be coerced to any other vector type except raw.
Importantly, NA
is of length 1 so that R reserves some space for it. E.g.,
data.frame(x = c(1, NA, 2))
# x
# 1 1
# 2 NA
# 3 2
Also, the data frame structure requires all the columns to have the same number of elements so that there can be no "holes" (i.e., NULL
values).
Now you could replace zeroes by NULL
in a data frame in the sense of completely removing all the rows containing at least one zero. When using, e.g., var
, cov
, or cor
, that is actually equivalent to first replacing zeroes with NA
and setting the value of use
as "complete.obs"
. Typically, however, this is unsatisfactory as it leads to extra information loss.
2. Instead of running some sort of loop, in the solution I use df == 0
vectorization. df == 0
returns (try it) a matrix of the same size as df
, with the entries TRUE
and FALSE
. Further, we are also allowed to pass this matrix to the subsetting [...]
(see ?'['
). Lastly, while the result of df[df == 0]
is perfectly intuitive, it may seem strange that df[df == 0] <- NA
gives the desired effect. The assignment operator <-
is indeed not always so smart and does not work in this way with some other objects, but it does so with data frames; see ?'<-'
.
1 The empty set in the set theory feels somehow related.
2 Another similarity with the set theory: the empty set is a subset of every set, but we do not reserve any space for it.
Just an addition to what Greg said:
$("#whatever").offset().left + $("#whatever").outerWidth()
This code will get the right position relative to the left side. If the intention was to get the right side position relative to the right (like when using the CSS right
property) then an addition to the code is necessary as follows:
$("#parent_container").innerWidth() - ($("#whatever").offset().left + $("#whatever").outerWidth())
This code is useful in animations where you have to set the right side as a fixed anchor when you can't initially set the right
property in CSS.
Is this what you are looking for?
Option Explicit
Public Sub addDataToTable(ByVal strTableName As String, ByVal strData As String, ByVal col As Integer)
Dim lLastRow As Long
Dim iHeader As Integer
With ActiveSheet.ListObjects(strTableName)
'find the last row of the list
lLastRow = ActiveSheet.ListObjects(strTableName).ListRows.Count
'shift from an extra row if list has header
If .Sort.Header = xlYes Then
iHeader = 1
Else
iHeader = 0
End If
End With
'add the data a row after the end of the list
ActiveSheet.Cells(lLastRow + 1 + iHeader, col).Value = strData
End Sub
It handles both cases whether you have header or not.
If the column data type is datetime then you can do this following to eliminate time from datetime and compare between date range only.
where cast(getdate() as date) between cast(loginTime as date) and cast(logoutTime as date)
List
interface have several different classes - ArrayList
and LinkedList
. LinkedList
is used to create an indexed collections and ArrayList
- to create sorted lists. So, you can use any of it in your arguments, but you can allow others developers who use your code, library, etc. to use different types of lists, not only which you use, so, in this method
ArrayList<Object> myMethod (ArrayList<Object> input) {
// body
}
you can use it only with ArrayList
, not LinkedList
, but you can allow to use any of List
classes on other places where it method is using, it's just your choise, so using an interface can allow it:
List<Object> myMethod (List<Object> input) {
// body
}
In this method arguments you can use any of List
classes which you want to use:
List<Object> list = new ArrayList<Object> ();
list.add ("string");
myMethod (list);
CONCLUSION:
Use the interfaces everywhere when it possible, don't restrict you or others to use different methods which they want to use.
On Windows my go to solution is using the rmdir
command:
rd /S .\node_modules\
If it fails the first time -- try one more time.
Also check if you have running scripts currently using the modules (npm run serve
or similar).
Starting Scala 2.13
, the standard library provides a dedicated resource management utility: Using
.
It can be used in this case with resources such as PrintWriter
or BufferedWriter
which extends AutoCloseable
in order to write to a file and, no matter what, close the resource afterwards:
For instance, with java.io
api:
import scala.util.Using, java.io.{PrintWriter, File}
// val lines = List("hello", "world")
Using(new PrintWriter(new File("file.txt"))) {
writer => lines.foreach(writer.println)
}
Or with java.nio
api:
import scala.util.Using, java.nio.file.{Files, Paths}, java.nio.charset.Charset
// val lines = List("hello", "world")
Using(Files.newBufferedWriter(Paths.get("file.txt"), Charset.forName("UTF-8"))) {
writer => lines.foreach(line => writer.write(line + "\n"))
}
There are three ways I am aware of. The first not being the prettiest and the second being the common way in most programming languages:
'I mustn''t sin!'
\
before the single quote'
: 'I mustn\'t sin!'
"I mustn't sin!"
tmpColumnsSQL = ("show columns in dim.date_dim")
hiveCursor.execute(tmpColumnsSQL)
columnlist = hiveCursor.fetchall()
for columns in jayscolumnlist:
print columns[0]
for i in range(len(jayscolumnlist)):
print columns[i][0])
You define var scatterSeries = [];
, and then try to parse it as a json string at console.info(JSON.parse(scatterSeries));
which obviously fails. The variable is converted to an empty string, which causes an "unexpected end of input" error when trying to parse it.
A "JSON object" is actually an oxymoron. JSON is a text format describing an object, not an actual object, so data can either be in the form of JSON, or deserialised into an object.
The JSON for that would look like this:
{"KEY1":{"NAME":"XXXXXX","VALUE":100},"KEY2":{"NAME":"YYYYYYY","VALUE":200},"KEY3":{"NAME":"ZZZZZZZ","VALUE":500}}
Once you have parsed the JSON into a Javascript object (called data
in the code below), you can for example access the object for KEY2
and it's properties like this:
var obj = data.KEY2;
alert(obj.NAME);
alert(obj.VALUE);
If you have the key as a string, you can use index notation:
var key = 'KEY3';
var obj = data[key];
Go to Solution properties ? Common Properties ? Startup Project and select Multiple startup projects.
Oracle has a page for this issue with SQL and trouble shooting suggestions.
"Troubleshooting Open Cursor Issues" http://docs.oracle.com/cd/E40329_01/admin.1112/e27149/cursor.htm#OMADM5352
>>> dic0 = {'dic0':0}
>>> dic1 = {'dic1':1}
>>> ndic = dict(dic0.items() + dic1.items())
>>> ndic
{'dic0': 0, 'dic1': 1}
>>>
Can also shift -
byte[] ba = new byte[4];
int val = Integer.MAX_VALUE;
for(byte i=0;i<4;i++)
ba[i] = (byte)(val >> i*8);
//ba[3-i] = (byte)(val >> i*8); //Big-endian
I tried this query and it works for me.
SELECT username FROM dba_users
ORDER BY username;
If you want to get the list of all that users which are created by end-user, then you can try this:
SELECT username FROM dba_users where Default_TableSpace not in ('SYSAUX', 'SYSTEM', 'USERS')
ORDER BY username;
Anonymous FTP usage is covered by RFC 1635: How to Use Anonymous FTP:
What is Anonymous FTP?
Anonymous FTP is a means by which archive sites allow general access to their archives of information. These sites create a special account called "anonymous".
…
Traditionally, this special anonymous user account accepts any string as a password, although it is common to use either the password "guest" or one's electronic mail (e-mail) address. Some archive sites now explicitly ask for the user's e-mail address and will not allow login with the "guest" password. Providing an e-mail address is a courtesy that allows archive site operators to get some idea of who is using their services.
These are general recommendations, though. Each FTP server may have its own guidelines.
For sample use of the ftp
command on anonymous FTP access, see appendix A:
atlas.arc.nasa.gov% ftp naic.nasa.gov Connected to naic.nasa.gov. 220 naic.nasa.gov FTP server (Wed May 4 12:15:15 PDT 1994) ready. Name (naic.nasa.gov:amarine): anonymous 331 Guest login ok, send your complete e-mail address as password. Password: 230----------------------------------------------------------------- 230-Welcome to the NASA Network Applications and Info Center Archive 230- 230- Access to NAIC's online services is also available through: 230- 230- Gopher - naic.nasa.gov (port 70) 230- World-Wide-Web - http://naic.nasa.gov/naic/naic-home.html 230- 230- If you experience any problems please send email to 230- 230- [email protected] 230- 230- or call +1 (800) 858-9947 230----------------------------------------------------------------- 230- 230-Please read the file README 230- it was last modified on Fri Dec 10 13:06:33 1993 - 165 days ago 230 Guest login ok, access restrictions apply. ftp> cd files/rfc 250-Please read the file README.rfc 250- it was last modified on Fri Jul 30 16:47:29 1993 - 298 days ago 250 CWD command successful. ftp> get rfc959.txt 200 PORT command successful. 150 Opening ASCII mode data connection for rfc959.txt (147316 bytes). 226 Transfer complete. local: rfc959.txt remote: rfc959.txt 151249 bytes received in 0.9 seconds (1.6e+02 Kbytes/s) ftp> quit 221 Goodbye. atlas.arc.nasa.gov%
See also the example session at the University of Edinburgh site.
To check whether a Byte array is empty, the simplest way is to use the VBA function StrPtr()
.
If the Byte array is empty, StrPtr()
returns 0
; otherwise, it returns a non-zero value (however, it's not the address to the first element).
Dim ar() As Byte
Debug.Assert StrPtr(ar) = 0
ReDim ar(0 to 3) As Byte
Debug.Assert StrPtr(ar) <> 0
However, it only works with Byte array.
**@page {
margin-top:21% !important;
@top-left{
content: element(header);
}
@bottom-left {
content: element(footer
}
div.header {
position: running(header);
}
div.footer {
position: running(footer);
border-bottom: 2px solid black;
}
.pagenumber:before {
content: counter(page);
}
.pagecount:before {
content: counter(pages);
}
<div class="footer" style="font-size:12pt; font-family: Arial; font-family: Arial;">
<span>Page <span class="pagenumber"/> of <span class="pagecount"/></span>
</div >**
Heres how to change all databases/tables/columns. Run these queries and they will output all of the subsequent queries necessary to convert your entire schema to utf8. Hope this helps!
-- Change DATABASE Default Collation
SELECT DISTINCT concat('ALTER DATABASE `', TABLE_SCHEMA, '` CHARACTER SET utf8 COLLATE utf8_unicode_ci;')
from information_schema.tables
where TABLE_SCHEMA like 'database_name';
-- Change TABLE Collation / Char Set
SELECT concat('ALTER TABLE `', TABLE_SCHEMA, '`.`', table_name, '` CHARACTER SET utf8 COLLATE utf8_unicode_ci;')
from information_schema.tables
where TABLE_SCHEMA like 'database_name';
-- Change COLUMN Collation / Char Set
SELECT concat('ALTER TABLE `', t1.TABLE_SCHEMA, '`.`', t1.table_name, '` MODIFY `', t1.column_name, '` ', t1.data_type , '(' , t1.CHARACTER_MAXIMUM_LENGTH , ')' , ' CHARACTER SET utf8 COLLATE utf8_unicode_ci;')
from information_schema.columns t1
where t1.TABLE_SCHEMA like 'database_name' and t1.COLLATION_NAME = 'old_charset_name';
If you have files you still want to keep:
git clean -di
will do an interactive clean which allows you to only delete the files/dirs you don't want anymore.
In my case, there was a .git folder in the subdirectory because I had previously initialized a git repo there. When I added the subdirectory it simply added it as a subproject without adding any of the contained files.
I solved the issue by removing the git repository from the subdirectory and then re-adding the folder.
clone: copying the remote server repository to your local machine.
pull: get new changes other have added to your local machine.
This is the difference.
Clone is generally used to get remote repo copy.
Pull is used to view other team mates added code, if you are working in teams.
Yes, you can do that like this:
BEGIN
DECLARE @Results TABLE (Tid INT PRIMARY KEY);
INSERT @Results
EXEC Procedure2 [parameters];
SET @total 1;
END
SELECT @total
I have found this page
http://schemas.xmlsoap.org/wsdl/soap12/soap12WSDL.htm
which says that Soap 1.2 uses the new namespace http://schemas.xmlsoap.org/wsdl/soap12/
It is in the 'WSDL 1.1 Binding extension for SOAP 1.1'.
As a follow-up to another answer, I was asked how I changed the spinner icon to get something like this:
One pretty easy way is to use a custom spinner item layout:
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,
R.layout.view_spinner_item,
ITEMS
);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
In res/layout/view_spinner_item.xml
, define a TextView with android:drawableRight
pointing to the desired icon (along with any customisations to text size, paddings and so on, if you wish):
<?xml version="1.0" encoding="utf-8"?>
<!-- Custom spinner item layout -->
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
style="?android:attr/spinnerItemStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:textSize="@dimen/text_size_medium"
android:drawablePadding="@dimen/spacing_medium"
android:drawableRight="@drawable/ic_arrow_down"
/>
(For the opened state, just use android.R.layout.simple_spinner_dropdown_item
or similarly create a customised layout if you want to tweak every aspect of your spinner.)
To get the background & colours looking nice, set the Spinner's android:background
and android:popupBackground
as shown in that other question. And if you were wondering about the custom font in the screenshot above, you'll need a custom SpinnerAdapter.
Create a *.bat
file beside of your windows service exe
file for installing with the following context:
CLS
ECHO Installing My Windows Service
START %windir%\Microsoft.NET\Framework\v4.0.30319\installutil.exe "%~d0%~p0\YourWindowsServiceExeName.exe"
Create a *.bat
file beside of your windows service exe
file for uninstalling with the following context:
CLS
ECHO Uninstalling My Windows Service
START %windir%\Microsoft.NET\Framework\v4.0.30319\installutil.exe -u "%~d0%~p0\YourWindowsServiceExeName.exe"
Run each of bat
file as Admin to install or uninstall your windows service.
Had the same problem in Linux. This solved it. (I'm on Debian 9 derived Bunsen Helium)
$ sudo apt-get install python3-tk
It is useful for annotating your classes, either at the method, class, or field level, something about that class that is not quite related to the class.
You could have your own annotations, used to mark certain classes as test-use only. It could simply be for documentation purposes, or you could enforce it by filtering it out during your compile of a production release candidate.
You could use annotations to store some meta data, like in a plugin framework, e.g., name of the plugin.
Its just another tool, its has many purposes.
The thing is that two double may not be exactly equal due to precision issues inherent to floating point numbers. With this delta value you can control the evaluation of equality based on a error factor.
Also some floating-point values can have special values like NAN and -Infinity/+Infinity which can influence results.
If you really intend to compare that two doubles are exactly equal it is best compare them as an long representation
Assert.assertEquals(Double.doubleToLongBits(expected), Double.doubleToLongBits(result));
Or
Assert.assertEquals(0, Double.compareTo(expected, result));
Which can take these nuances into account.
I have not delved into the Assert method in question, but I can only assume the previous was deprecated for this kind of issues and the new one does take them into account.
You can add a comment to an MSAccess query as follows: Create a dummy field in the query. Not elegant but is self-documentating and contained in the query, which makes cheking it into source code control alot more feasible! Jere's an example. Go into SQL view and add the dummy field (you can do from design view too):
SELECT "2011-01-21;JTR;Added FIELD02;;2011-01-20;JTR;Added qryHISTORY;;" as qryHISTORY, ...rest of query here...
Run the query:
qryHISTORY FIELD01 FIELD02 ...
2011-01-21;JTR;Added FIELD02;;2011-01-20;JTR;Added qryHISTORY;;" 0000001 ABCDEF ...
Note the use of ";" as field delimiter in qryHISTORY field, and ";;" as an end of comment, and use of ISO date format and intials, as well as comment. Have tested this with up to 646 characters in the qryHISTORY field.
UTF files that contain a BOM will cause Excel to treat new lines literally even in that field is surrounded by quotes. (Tested Excel 2008 Mac)
The solution is to make any new lines a carriage return (CHR 13) rather than a line feed.
The error you are receiving is due to how you define jet
. You are creating the base class Colormap
with the name 'jet', but this is very different from getting the default definition of the 'jet' colormap. This base class should never be created directly, and only the subclasses should be instantiated.
What you've found with your example is a buggy behavior in Matplotlib. There should be a clearer error message generated when this code is run.
This is an updated version of your example:
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx
import numpy as np
# define some random data that emulates your indeded code:
NCURVES = 10
np.random.seed(101)
curves = [np.random.random(20) for i in range(NCURVES)]
values = range(NCURVES)
fig = plt.figure()
ax = fig.add_subplot(111)
# replace the next line
#jet = colors.Colormap('jet')
# with
jet = cm = plt.get_cmap('jet')
cNorm = colors.Normalize(vmin=0, vmax=values[-1])
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)
print scalarMap.get_clim()
lines = []
for idx in range(len(curves)):
line = curves[idx]
colorVal = scalarMap.to_rgba(values[idx])
colorText = (
'color: (%4.2f,%4.2f,%4.2f)'%(colorVal[0],colorVal[1],colorVal[2])
)
retLine, = ax.plot(line,
color=colorVal,
label=colorText)
lines.append(retLine)
#added this to get the legend to work
handles,labels = ax.get_legend_handles_labels()
ax.legend(handles, labels, loc='upper right')
ax.grid()
plt.show()
Resulting in:
Using a ScalarMappable
is an improvement over the approach presented in my related answer:
creating over 20 unique legend colors using matplotlib
A B+tree is a balanced tree in which every path from the root of the tree to a leaf is of the same length, and each nonleaf node of the tree has between [n/2] and [n] children, where n is fixed for a particular tree. It contains index pages and data pages. Binary trees only have two children per parent node, B+ trees can have a variable number of children for each parent node
After spent a lot of hours on Google search, I found the below solution as when I locally give date time, no exception while from other server, there was Error......... Date is not in proper format.. Before saving/ searching Text box date time in C#, just checking either the outer Serer Culture is same like database server culture.. Ex both should be "en-US" or must be both "en-GB" asp below snap shot.
Even with different date format like (dd/mm/yyyy) or (yyyy/mm/dd), it will save or search accurately.
Need some adjusts but should work for Express v4. Including those routes added with .use()
.
function listRoutes(routes, stack, parent){
parent = parent || '';
if(stack){
stack.forEach(function(r){
if (r.route && r.route.path){
var method = '';
for(method in r.route.methods){
if(r.route.methods[method]){
routes.push({method: method.toUpperCase(), path: parent + r.route.path});
}
}
} else if (r.handle && r.handle.name == 'router') {
const routerName = r.regexp.source.replace("^\\","").replace("\\/?(?=\\/|$)","");
return listRoutes(routes, r.handle.stack, parent + routerName);
}
});
return routes;
} else {
return listRoutes([], app._router.stack);
}
}
//Usage on app.js
const routes = listRoutes(); //array: ["method: path", "..."]
edit: code improvements
you just need to divide the Date Time stamp by 1000 like:
var a = 1437203995000;
a = (a)/1000;
Just add this to your Action file in some div or td, so that it comes with incoming XML object
<script type="text/javascript">
$("#formname").resetForm();
</script>
Where "formname" is the id of form you want to edit
On my Mac:
/System/Library/Frameworks/JavaVM.framework/Home/
btw, did you tried which java
?
I agree with the answer by Kenny Eliasson. Go with Extension methods. Here is a brief overview of extension methods and your required IfNotNull method.
You should use a RelativeLayout and just drag them until it looks good :)
<ImageView
android:id="@+id/button_info"
android:layout_width="30dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="10dp"
android:contentDescription="@string/pizza"
android:src="@drawable/header_info_button" />
</RelativeLayout>
Just stack two bootstrap tables; one for columns, the other for content. No plugins, just pure bootstrap (and that ain't no bs, haha!)
<table id="tableHeader" class="table" style="table-layout:fixed">
<thead>
<tr>
<th>Col1</th>
...
</tr>
</thead>
</table>
<div style="overflow-y:auto;">
<table id="tableData" class="table table-condensed" style="table-layout:fixed">
<tbody>
<tr>
<td>data</td>
...
</tr>
</tbody>
</table>
</div>
The content table div needs overflow-y:auto
, for vertical scroll bars. Had to use table-layout:fixed
, otherwise, columns did not line up. Also, had to put the whole thing inside a bootstrap panel to eliminate space between the tables.
Have not tested with custom column widths, but provided you keep the widths consistent between the tables, it should work.
// ADD THIS JS FUNCTION TO MATCH UP COL WIDTHS
$(function () {
//copy width of header cells to match width of cells with data
//so they line up properly
var tdHeader = document.getElementById("tableHeader").rows[0].cells;
var tdData = document.getElementById("tableData").rows[0].cells;
for (var i = 0; i < tdData.length; i++)
tdHeader[i].style.width = tdData[i].offsetWidth + 'px';
});
The answers here are not actually completely correct. Close, but there's an edge case.
The difference is that $('body') actually selects the element by the tag name, whereas document.body references the direct object on the document.
That means if you (or a rogue script) overwrites the document.body element (shame!) $('body') will still work, but $(document.body) will not. So by definition they're not equivalent.
I'd venture to guess there are other edge cases (such as globally id'ed elements in IE) that would also trigger what amounts to an overwritten body element on the document object, and the same situation would apply.
In Java, a String is a reference to heap-allocated storage. Returning "ans" only returns the reference so there is no need for stack-allocated storage. In fact, there is no way in Java to allocate objects in stack storage.
I would change to this, though. You don't need "ans" at all.
return String.format("%d:%d", mins, secs);
Here's the list of all Win32 error codes. You can use this page to lookup the error code mentioned in IIS logs:
http://msdn.microsoft.com/en-us/library/ms681381.aspx
You can also use command line utility net
to find information about a Win32 error code. The syntax would be:
net helpmsg Win32_Status_Code
This has been answered a few times but here's one more just for fun :-)
public class Tmp {
public static void main(String[] args) {
System.out.println(swapChars("abcde", 0, 1));
}
private static String swapChars(String str, int lIdx, int rIdx) {
StringBuilder sb = new StringBuilder(str);
char l = sb.charAt(lIdx), r = sb.charAt(rIdx);
sb.setCharAt(lIdx, r);
sb.setCharAt(rIdx, l);
return sb.toString();
}
}
Using LINQ you could write:
static int LCM(int[] numbers)
{
return numbers.Aggregate(LCM);
}
static int LCM(int a, int b)
{
return a * b / GCD(a, b);
}
Should add using System.Linq;
and don't forget to handle the exceptions ...
If you want to do something AFTER the rotation is complete, you can use the UIViewControllerTransitionCoordinator
completion handler like this
public override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
// Hook in to the rotation animation completion handler
coordinator.animate(alongsideTransition: nil) { (_) in
// Updates to your UI...
self.tableView.reloadData()
}
}
Here are the steps to install JSToolNPP
plugin on your Notepad++.
Download 64bit version from Sourceforge or the 32bit version if you are on a 32-bit OS.
64bit - JSToolNPP.1.21.0.uni.64.zip: Download from SourceForget.net
Notepad++ before installation
Unzip the downloaded JSToolNPP.1.21.0.uni.64
and copy the JSMinNPP.dll
and place it under C:\Program Files\Notepad++\plugins
.
Close Notepad++ and reopen it. If you have downloaded an incompatible dll, then it will complain, else it will open successfully. If it complains about incompatibility, go back to STEP 1 and download the correct bit version as per your OS. Check Plugins in Notepad++.
Paste a sample unformatted but valid JSON data in Notepad++.
Select all text in Notepad++ (CTRL+A)
and format using Plugins -> JSTool -> JSFormat
.
NOTE: On side note, if you do not want to install any plugins like this, I would recommend using the following 2 best online formatters.
This worked for me in SQL 2000:
IF EXISTS
(
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'table_name'
AND column_name = 'column_name'
)
BEGIN
...
END
@PaulR posted this as a comment, but people should view it as an answer (and this answer works best for my needs):
sed -i 's/abc/xyz/g' xa*
This will work for a moderate amount of files, probably on the order of tens, but probably not on the order of millions.
<a id="topbutton" href="#top">first page </a>
Basically what you have to do is replace the " #top" with the id of the first section or your page, or it could be the nav... Any id locate in the first part of the page and then try to set some style with css!
http://fetchak.com/ie-css3/ works for IE 6+. Use this if css3pie doesn't work for you.
with jQuery :
html :
<form method="POST" name="myform" action="index.php?action=contact_agent&agent_id=" onsubmit="SetData()">
<select name="agent" id="agent">
<option value="1">Agent Homer</option>
<option value="2">Agent Lenny</option>
<option value="3">Agent Carl</option>
</select>
</form>
jQuery :
$('form').submit(function(){
$(this).attr('action',$(this).attr('action')+$('#agent').val());
$(this).submit();
});
javascript :
function SetData(){
var select = document.getElementById('agent');
var agent_id = select.options[select.selectedIndex].value;
document.myform.action = "index.php?action=contact_agent&agent_id="+agent_id ; # or .getAttribute('action')
myform.submit();
}
strict-ssl=false
proxy = http://ip_address_of_proxy:8088 https-proxy = https://ip_address_of_proxy:8088
registry = http://registry.npmjs.org/
var mystring = "this,is,a,test"
mystring.replace(/,/g, "newchar");
Use the global(g
) flag
conda activate myEnv
conda list --explicit > myEnvBkp.txt
conda create --name myEnvRestored --file myEnvBkp.txt
Or this:
Range("A2", Range("D" & Rows.Count).End(xlUp).Address).Sort Key1:=[b3], _
Order1:=xlAscending, Header:=xlYes
From iOS 6.0 and above, toggling torch flash on/off,
- (void) toggleFlash {
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device hasTorch] && [device hasFlash]){
[device lockForConfiguration:nil];
[device setFlashMode:(device.flashActive) ? AVCaptureFlashModeOff : AVCaptureFlashModeOn];
[device setTorchMode:(device.torchActive) ? AVCaptureTorchModeOff : AVCaptureTorchModeOn];
[device unlockForConfiguration];
}
}
P.S. This approach is only suggestible if you don't have on/off function. Remember there's one more option Auto
. i.e. AVCaptureFlashModeAuto
and AVCaptureTorchModeAuto
. To support auto mode as well, you've keep track of current mode and based on that change mode of flash & torch.
Many hours spent to clarify what was that. Please, read this post to get the advanced .HTACCESS
codes and learn what they do.
You can use:
Header append Vary "Accept-Encoding"
#or
Header set Vary "Accept-Encoding"
use DATE_DIFF
Select I.Fee
From Item I
WHERE DATEDIFF(day, GETDATE(), I.DateCreated) < 365
$('#abc span').html('A new text for the span.');
For HttpEntity
, the below answer works
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("email", "[email protected]");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );
For reference: How to POST form data with Spring RestTemplate?
I was getting this exception when debugging in PyCharm, given that no breakpoint was being hit. To prevent it, I added a breakpoint just after the with
block, and then it stopped happening.
You can do it with grep alone (without find).
grep -riL "foo" .
This is the explanation of the parameters used on grep
-L, --files-without-match
each file processed.
-R, -r, --recursive
Recursively search subdirectories listed.
-i, --ignore-case
Perform case insensitive matching.
If you use l
(lowercased) you will get the opposite (files with matches)
-l, --files-with-matches
Only the names of files containing selected lines are written
According to the Java docs, it looks like you need to use the MemoryImageSource Class to put your byte array into an object in memory, and then use Component.createImage(ImageProducer) next (passing in your MemoryImageSource, which implements ImageProducer).
git filter-branch --tree-filter 'rm -f path/to/file' HEAD
worked pretty well for me, although I ran into the same problem as described here, which I solved by following this suggestion.
The pro-git book has an entire chapter on rewriting history - have a look at the filter-branch
/Removing a File from Every Commit section.
Replacing all AppSettings
This is the overkill case where you just want to replace an entire section of the web.config. In this case I will replace all AppSettings in the web.config will new settings in web.release.config. This is my baseline web.config appSettings:
<appSettings>
<add key="KeyA" value="ValA"/>
<add key="KeyB" value="ValB"/>
</appSettings>
Now in my web.release.config file, I am going to create a appSettings section except I will include the attribute xdt:Transform=”Replace” since I want to just replace the entire element. I did not have to use xdt:Locator because there is nothing to locate – I just want to wipe the slate clean and replace everything.
<appSettings xdt:Transform="Replace">
<add key="ProdKeyA" value="ProdValA"/>
<add key="ProdKeyB" value="ProdValB"/>
<add key="ProdKeyC" value="ProdValC"/>
</appSettings>
Note that in the web.release.config file my appSettings section has three keys instead of two, and the keys aren’t even the same. Now let’s look at the generated web.config file what happens when we publish:
<appSettings>
<add key="ProdKeyA" value="ProdValA"/>
<add key="ProdKeyB" value="ProdValB"/>
<add key="ProdKeyC" value="ProdValC"/>
</appSettings>
Just as we expected – the web.config appSettings were completely replaced by the values in web.release config. That was easy!
A null key can also be helpful when the map stores data for UI selections where the map key represents a bean field.
A corresponding null field value would for example be represented as "(please select)" in the UI selection.
The problem is that when we use application/x-www-form-urlencoded, Spring doesn't understand it as a RequestBody. So, if we want to use this we must remove the @RequestBody annotation.
Then try the following:
@RequestMapping(value = "/patientdetails", method = RequestMethod.POST,consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public @ResponseBody List<PatientProfileDto> getPatientDetails(
PatientProfileDto name) {
List<PatientProfileDto> list = new ArrayList<PatientProfileDto>();
list = service.getPatient(name);
return list;
}
Note that removed the annotation @RequestBody
in my idea, you must go to a certain path for example:
from google.colab import drive drive.mount('/content/drive/') cd drive/MyDrive/f/
then :
!apt install unzip !unzip zip_folder.zip -d unzip_folder enter image description here
Set Multiple Unique key into table
ALTER TABLE table_name
ADD CONSTRAINT UC_table_name UNIQUE (field1,field2);
to load a KeyStore, you'll need to tell it the type of keystore it is (probably jceks), provide an inputstream, and a password. then, you can load it like so:
KeyStore ks = KeyStore.getInstance(TYPE_OF_KEYSTORE);
ks.load(new FileInputStream(PATH_TO_KEYSTORE), PASSWORD);
this can throw a KeyStoreException, so you can surround in a try block if you like, or re-throw. Keep in mind a keystore can contain multiple keys, so you'll need to look up your key with an alias, here's an example with a symmetric key:
SecretKeyEntry entry = (KeyStore.SecretKeyEntry)ks.getEntry(SOME_ALIAS,new KeyStore.PasswordProtection(SOME_PASSWORD));
SecretKey someKey = entry.getSecretKey();
Coloured, word-level diff
ouput
Here's what you can do with the the below script and diff-highlight:
#!/bin/sh -eu
# Use diff-highlight to show word-level differences
diff -U3 --minimal "$@" |
sed 's/^-/\x1b[1;31m-/;s/^+/\x1b[1;32m+/;s/^@/\x1b[1;34m@/;s/$/\x1b[0m/' |
diff-highlight
(Credit to @retracile's answer for the sed
highlighting)
A scrolling comes from a box with class pre-scrollable
<div class="pre-scrollable"></div>
There's more examples: http://getbootstrap.com/css/#code-block
Wish it helps.
You can read files in raw/res using getResources().openRawResource(R.raw.myfilename)
.
BUT there is an IDE limitation that the file name you use can only contain lower case alphanumeric characters and dot. So file names like XYZ.txt
or my_data.bin
will not be listed in R.
Thumbnailator is an open-source image resizing library for Java with a fluent interface, distributed under the MIT license.
I wrote this library because making high-quality thumbnails in Java can be surprisingly difficult, and the resulting code could be pretty messy. With Thumbnailator, it's possible to express fairly complicated tasks using a simple fluent API.
A simple example
For a simple example, taking a image and resizing it to 100 x 100 (preserving the aspect ratio of the original image), and saving it to an file can achieved in a single statement:
Thumbnails.of("path/to/image")
.size(100, 100)
.toFile("path/to/thumbnail");
An advanced example
Performing complex resizing tasks is simplified with Thumbnailator's fluent interface.
Let's suppose we want to do the following:
0.85
,thumbnail.
appended to the beginningTranslated to Thumbnailator, we'd be able to perform the above with the following:
Thumbnails.of(new File("path/to/directory").listFiles())
.size(100, 100)
.outputFormat("JPEG")
.outputQuality(0.85)
.toFiles(Rename.PREFIX_DOT_THUMBNAIL);
A note about image quality and speed
This library also uses the progressive bilinear scaling method highlighted in Filthy Rich Clients by Chet Haase and Romain Guy in order to generate high-quality thumbnails while ensuring acceptable runtime performance.
Actually the determination of what type of file a file is very complicated, so now the operating system can't just know. It can make lots of guesses based on -
But the command line doesn't bother with all that, because it runs on a limited backwards compatible layer, from when that fancy nonsense didn't mean anything. If you double click it sure, a modern OS can figure that out- but if you run it from a terminal then no, because the terminal doesn't care about your fancy OS specific file typing APIs.
Regarding the other points. It's a convenience, it's similarly possible to run
python3 path/to/your/script
If your python isn't in the path specified, then it won't work, but we tend to install things to make stuff like this work, not the other way around. It doesn't actually matter if you're under *nix, it's up to your shell whether to consider this line because it's a shellcode
. So for example you can run bash
under Windows.
You can actually ommit this line entirely, it just mean the caller will have to specify an interpreter. Also don't put your interpreters in nonstandard locations and then try to call scripts without providing an interpreter.
If the question is docker related... the official nginx docker images do this by making softlinks towards stdout/stderr
RUN ln -sf /dev/stdout /var/log/nginx/access.log && ln -sf /dev/stderr /var/log/nginx/error.log
Python tells me where it lives when it gives me an error message :)
>>> import os
>>> os.environ['PYTHONPATH'].split(os.pathsep)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\martin\AppData\Local\Programs\Python\Python36-32\lib\os.py", line 669, in __getitem__
raise KeyError(key) from None
KeyError: 'PYTHONPATH'
>>>
Try
set wildmenu
set wildmode=list:full
set wildcharm=<C-z>
let mapleader=','
nnoremap <leader>c :colorscheme <C-z><S-Tab>
in your ~/.vimrc
.
The first two lines make possible matches appear as lists. You can use either or both.
The fourth line makes leader ,
instead of the default \
.
The last line allows you to simply type ,c
to get a list and a prompt to change your colorscheme.
The third line effectively allows for Tab
s to appear in key maps.
(Of course, all of these strategies I've learned from the internet, and mostly SO, very recently.)
r = 13 + 7.*rand(100,1);
Where 100,1 is the size of the desidered vector
Just to go a little bit further in the matter, you can also set a bitmap directly, like this:
ImageView imageView = new ImageView(this);
Bitmap bImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.my_image);
imageView.setImageBitmap(bImage);
Of course, this technique is only useful if you need to change the image.
As mentioned before, you need more than a css selector because it doesn't access the stored value of the node, so javascript is definitely needed. Heres another possible solution:
<style>
input:not([value=""]){
border:2px solid red;
}
</style>
<input type="text" onkeyup="this.setAttribute('value', this.value);"/>
If the binary is something more than a dll or something that can be edited directly like an image, or a blend file (and you don't need to trash/select one file or the other) a real merge would be some like:
I suggest searching for a diff tool oriented to what are your binary file, for example, there are some free ones for image files for example
and compare them.
If there is no diff tool out there for comparing your files, then if you have the original generator of the bin file (that is, there exist an editor for it... like blender 3d, you can then manually inspect those files, also see the logs, and ask the other person what you should include) and do output of the files with https://git-scm.com/book/es/v2/Git-Tools-Advanced-Merging#_manual_remerge
$ git show :1:hello.blend > hello.common.blend
$ git show :2:hello.blend > hello.ours.blend
$ git show :3:hello.blend > hello.theirs.blend
You probably don't want to do it that way. By putting an explicit sleep()
in your button-clicked event handler, you would actually lock up the whole UI for a second. One alternative is to use some sort of single-shot Timer. Create a TimerTask to change the background color back to the default color, and schedule it on the Timer.
Another possibility is to use a Handler. There's a tutorial about somebody who switched from using a Timer to using a Handler.
Incidentally, you can't pause a process. A Java (or Android) process has at least 1 thread, and you can only sleep threads.
One gotcha with Jquery is that the click function do not acknowledge the hand coded onclick from the html.
So, you pretty much have to choose. Set up all your handlers in the init function or all of them in html.
The click event in JQuery is the click function $("myelt").click (function ....).
Check out this one:
https://github.com/VBA-tools/VBA-Web
It's a high level library for dealing with REST. It's OOP, works with JSON, but also works with any other format.
Transparency can be coded in the color argument as well. It is just two more hex numbers coding a transparency between 0 (fully transparent) and 255 (fully visible). I once wrote this function to add transparency to a color vector, maybe it is usefull here?
addTrans <- function(color,trans)
{
# This function adds transparancy to a color.
# Define transparancy with an integer between 0 and 255
# 0 being fully transparant and 255 being fully visable
# Works with either color and trans a vector of equal length,
# or one of the two of length 1.
if (length(color)!=length(trans)&!any(c(length(color),length(trans))==1)) stop("Vector lengths not correct")
if (length(color)==1 & length(trans)>1) color <- rep(color,length(trans))
if (length(trans)==1 & length(color)>1) trans <- rep(trans,length(color))
num2hex <- function(x)
{
hex <- unlist(strsplit("0123456789ABCDEF",split=""))
return(paste(hex[(x-x%%16)/16+1],hex[x%%16+1],sep=""))
}
rgb <- rbind(col2rgb(color),trans)
res <- paste("#",apply(apply(rgb,2,num2hex),2,paste,collapse=""),sep="")
return(res)
}
Some examples:
cols <- sample(c("red","green","pink"),100,TRUE)
# Fully visable:
plot(rnorm(100),rnorm(100),col=cols,pch=16,cex=4)
# Somewhat transparant:
plot(rnorm(100),rnorm(100),col=addTrans(cols,200),pch=16,cex=4)
# Very transparant:
plot(rnorm(100),rnorm(100),col=addTrans(cols,100),pch=16,cex=4)
Check out python-nvd3. It is a python wrapper for nvd3. Looks cooler than d3.py and also has more chart options.
As all answers posted above are well explained, I want to add something which I faced today.
When you export something using exports then you have to use it with variable. Like,
File1.js
exports.a = 5;
In another file
File2.js
const A = require("./File1.js");
console.log(A.a);
and using module.exports
File1.js
module.exports.a = 5;
In File2.js
const A = require("./File1.js");
console.log(A.a);
and default module.exports
File1.js
module.exports = 5;
in File2.js
const A = require("./File2.js");
console.log(A);
Use jquery cookie plugin, the link as working today: https://github.com/js-cookie/js-cookie
There are three options, that you can use. -I
is to exclude binary files in grep. Other are for line numbers and file names.
grep -I -n -H
-I -- process a binary file as if it did not contain matching data;
-n -- prefix each line of output with the 1-based line number within its input file
-H -- print the file name for each match
So this might be a way to run grep:
grep -InH your-word *
I have a nvidia GPU, and if nView is enabled it happens all the time. Try to disable it.
It seems that eclipse is not very compatible with softwares that override system window management on multi screen.
Hint how to disable nView: http://nviewdesktopmanager.blogspot.com/2011/08/how-to-disable-nview-desktop-manager.html
Feel free to use this method I wrote:
int dpToPx(int dp)
{
return (int) (dp * getResources().getDisplayMetrics().density + 0.5f);
}
What is the utility of an only one Ampersand? This morning, I made a launcher in the XFCE panel (in Manjaro+XFCE) to launch 2 passwords managers simultaneously:
sh -c "keepassx && password-gorilla"
or
sh -c "keepassx; password-gorilla"
But it does not work as I want. I.E., the first app starts but the second starts only when the previous is closed
However, I found that (with only one ampersand):
sh -c "keepassx & password-gorilla"
and it works as I want now...
If you want a way to iterate the item pairs of a dictionary that works with both Python 2 and 3, try something like this:
DICT_ITER_ITEMS = (lambda d: d.iteritems()) if hasattr(dict, 'iteritems') else (lambda d: iter(d.items()))
Use it like this:
for key, value in DICT_ITER_ITEMS(myDict):
# Do something with 'key' and/or 'value'.
Usually when I get these kinds of errors, opening the __init__.py
file and poking around helps. Go to the directory C:\Python27\lib\site-packages\sklearn
and ensure that there's a sub-directory called __check_build
as a first step. On my machine (with a working sklearn installation, Mac OSX, Python 2.7.3) I have __init__.py
, setup.py
, their associated .pyc
files, and a binary _check_build.so
.
Poking around the __init__.py
in that directory, the next step I'd take is to go to sklearn/__init__.py
and comment out the import statement---the check_build stuff just checks that things were compiled correctly, it doesn't appear to do anything but call a precompiled binary. This is, of course, at your own risk, and (to be sure) a work around. If your build failed you'll likely soon run into other, bigger problems.
It is never a good idea to break out of a for-loop. If you are using a for-loop it means that you know how many times you want to iterate. Use a while-loop with 2 conditions.
for example
var done = false
while (i <= length && !done) {
if (sum > 1000) {
done = true
}
}
exit(0)
indicates that the program terminated without errors. exit(1)
indicates that there were an error.
You can use different values other than 1
to differentiate between different kind of errors.
Since TypeScript is a typed superset of ES6 JavaScript. And lodash are a library of javascript.
Using lodash to checks if value is null or undefined can be done using _.isNil()
.
_.isNil(value)
value (*): The value to check.
(boolean): Returns true if value is nullish, else false.
_.isNil(null);
// => true
_.isNil(void 0);
// => true
_.isNil(NaN);
// => false
An alternative way would be:
import java.util.regex.Pattern;
...
private static final Pattern SPACE = Pattern.compile(" ");
String[] arr = SPACE.split(str); // str is the string to be split
Saw it here
You can use lapply
to pass each column to str_length
, then cbind
it to your original data.frame
...
library(stringr)
out <- lapply( df , str_length )
df <- cbind( df , out )
# col1 col2 col1 col2
#1 abc adf qqwe 3 8
#2 abcd d 4 1
#3 a e 1 1
#4 abcdefg f 7 1
There's no right answer to this question. I really depends on what you're doing with the data. In the simple example above, I would strongly suggest:
Is it important that the values 1 and 2 above have names? In other words, why is it important in this example that 1 and 2 be named a and b, rather than just r[1] and r[2]? One important thing to understand in this context is that a and b are also both vectors of length 1. So you're not really changing anything in the process of making that assignment, other than having 2 new vectors that don't need subscripts to be referenced:
> r <- c(1,2)
> a <- r[1]
> b <- r[2]
> class(r)
[1] "numeric"
> class(a)
[1] "numeric"
> a
[1] 1
> a[1]
[1] 1
You can also assign the names to the original vector if you would rather reference the letter than the index:
> names(r) <- c("a","b")
> names(r)
[1] "a" "b"
> r["a"]
a
1
[Edit] Given that you will be applying min and max to each vector separately, I would suggest either using a matrix (if a and b will be the same length and the same data type) or data frame (if a and b will be the same length but can be different data types) or else use a list like in your last example (if they can be of differing lengths and data types).
> r <- data.frame(a=1:4, b=5:8)
> r
a b
1 1 5
2 2 6
3 3 7
4 4 8
> min(r$a)
[1] 1
> max(r$b)
[1] 8
How about
SELECT user()
I use this before.MySQL, H2 is OK, I don't know others.
psql: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/tmp/.s.PGSQL.5432"?
I searching the solution for a while. So, this one fixed the issue for me as well (reinit db):
rm -r /usr/local/var/postgres
initdb /usr/local/var/postgres -E utf8
pg_ctl -D /usr/local/var/postgres -l logfile start
I use OS X 10.11.3 with brew.
You can use str()
to cast it, or formatters:
"ME%d.txt" % (num,)
if ( !driver.findElement(By.id("idOfTheElement")).isSelected() )
{
driver.findElement(By.id("idOfTheElement")).click();
}
I needed to edit a file with restricted write permissions so needed sudo
. working from ghostdog74's answer and using a temp file:
awk 'FNR==NR && /configs.*projectname\.conf/{f=1;next}f==0;END{ if(!f) { print "your line"}} ' file > /tmp/file
sudo mv /tmp/file file
If you want to get the inputs of that type with that class use:
$("input.myClass[type=checkbox]")
the [] selector syntax allows you to check against any of the elements attributes. Check out the spec for more details
Also The function can help in sorting. To be more clear about sorting. strcmp() returns less than 0 if string1 sorts before string2, greater than 0 if string2 sorts before string1 or 0 if they are the same. For example
$first_string = "aabo";
$second_string = "aaao";
echo $n = strcmp($first_string,$second_string);
The function will return greater than zero, as aaao is sorting before aabo.
You are wrong in the way you display the data I guess, because for me:
String dateString = "03/26/2012 11:49:00 AM";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa");
Date convertedDate = new Date();
try {
convertedDate = dateFormat.parse(dateString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(convertedDate);
Prints:
Mon Mar 26 11:49:00 EEST 2012
Span is inline-block and adjusts to inline text size, with a tenacity that blocks most efforts to style out of inline context. To simplify layout style (limit conflicts), add div to 'p' tag with line break.
<p> some default stuff
<br>
<div style="text-align: center;"> your entered stuff </div>
To have it in one line, this is what I did:
if any(([True if 'MICHAEL89' in username.upper() else False for username in USERNAMES])):
print('username exists in list')
I didn't test it time-wise though. I am not sure how fast/efficient it is.
Write the below command from your repo terminal:
git remote set-url origin [email protected]:<username>/<repo>.git
Refer this link for more details about changing the url in the remote.
Use this html to get the clicked element:
<div class="row" style="padding-left:21px;">
<ul class="nav nav-tabs" style="padding-left:40px;">
<li class="active filter"><a href="#month" onclick="Data('month', this)">This Month</a></li>
<li class="filter"><a href="#year" onclick="Data('year', this)">Year</a></li>
<li class="filter"><a href="#last60" onclick="Data('last60', this)">60 Days</a></li>
<li class="filter"><a href="#last90" onclick="Data('last90', this)">90 Days</a></li>
</ul>
</div>
Script:
function Data(string, el)
{
$('.filter').removeClass('active');
$(el).parent().addClass('active');
}
Action y; //declared inside class
label1.Invoke(y=()=>label1.Text="text");
Should be :
<h2 class="col-md-4 col-md-offset-1">Browse.</h2>
<h2 class="col-md-4 col-md-offset-2">create.</h2>
<h2 class="col-md-4 col-md-offset-3">share.</h2>
"Domain" is not a property of an LDAP object. It is more like the name of the database the object is stored in.
So you have to connect to the right database (in LDAP terms: "bind to the domain/directory server") in order to perform a search in that database.
Once you bound successfully, your query in it's current shape is all you need.
BTW: Choosing "ObjectCategory=Person"
over "ObjectClass=user"
was a good decision. In AD, the former is an "indexed property" with excellent performance, the latter is not indexed and a tad slower.
You can use different types of redirect method in laravel -
return redirect()->intended('http://heera.it');
OR
return redirect()->to('http://heera.it');
OR
use Illuminate\Support\Facades\Redirect;
return Redirect::to('/')->with(['type' => 'error','message' => 'Your message'])->withInput(Input::except('password'));
OR
return redirect('/')->with(Auth::logout());
OR
return redirect()->route('user.profile', ['step' => $step, 'id' => $id]);
401 means "Unauthorized", so there must be something with your credentials.
I think that java URL
does not support the syntax you are showing. You could use an Authenticator instead.
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(login, password.toCharArray());
}
});
and then simply invoking the regular url, without the credentials.
The other option is to provide the credentials in a Header:
String loginPassword = login+ ":" + password;
String encoded = new sun.misc.BASE64Encoder().encode (loginPassword.getBytes());
URLConnection conn = url.openConnection();
conn.setRequestProperty ("Authorization", "Basic " + encoded);
PS: It is not recommended to use that Base64Encoder but this is only to show a quick solution. If you want to keep that solution, look for a library that does. There are plenty.
The root of the problem is that Spring (via ResponseEntity, RestController, and/or ResponseBody) will use the contents of the string as the raw response value, rather than treating the string as JSON value to be encoded. This is true even when the controller method uses produces = MediaType.APPLICATION_JSON_VALUE
, as in the question here.
It's essentially like the difference between the following:
// yields: This is a String
System.out.println("This is a String");
// yields: "This is a String"
System.out.println("\"This is a String\"");
The first output cannot be parsed as JSON, but the second output can.
Something like '"'+myString+'"'
is probably not a good idea however, as that won't handle proper escaping of double-quotes within the string and will not produce valid JSON for any such string.
One way to handle this would be to embed your string inside an object or list, so that you're not passing a raw string to Spring. However, that changes the format of your output, and really there's no good reason not to be able to return a properly-encoded JSON string if that's what you want to do. If that's what you want, the best way to handle it is via a JSON formatter such as Json or Google Gson. Here's how it might look with Gson:
import com.google.gson.Gson;
@RestController
public class MyController
private static final Gson gson = new Gson();
@RequestMapping(value = "so", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<String> so() {
return ResponseEntity.ok(gson.toJson("This is a String"));
}
}
These will also redirect both:
yourcommand &> /dev/null
yourcommand >& /dev/null
though the bash manual says the first is preferred.
What's worked for me recently is to remove all height=""
and width=""
attributes from the <svg>
tag and all child tags. Then you can use scaling using a percentage of the parent container's height or width.
Before:
<svg width="3212" height="3212" viewBox="0 0 3212 3212" fill="none" xmlns="http://www.w3.org/2000/svg">
circle cx="1606" cy="1606" r="1387" stroke="black" stroke-width="438"/>
</svg>
After:
<svg viewBox="0 0 3212 3212" fill="none" xmlns="http://www.w3.org/2000/svg">
circle cx="1606" cy="1606" r="1387" stroke="black" stroke-width="438"/>
</svg>
In my Case, Adding the below functions to WebViewClient fixed the error.
the functions are:onReceivedSslError
and Depricated and new api versions of shouldOverrideUrlLoading
webView.setWebViewClient(new WebViewClient() {
@SuppressWarnings("deprecation")
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
Log.i(TAG, "loading: deprecation");
return true;
//return super.shouldOverrideUrlLoading(view, url);
}
@Override
@TargetApi(Build.VERSION_CODES.N)
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
view.loadUrl(request.getUrl().toString());
Log.i(TAG, "loading: build.VERSION_CODES.N");
return true;
//return super.shouldOverrideUrlLoading(view, request);
}
@Override
public void onPageStarted(
WebView view, String url, Bitmap favicon) {
Log.i(TAG, "page started:"+url);
super.onPageStarted(view, url, favicon);
}
@Override
public void onPageFinished(WebView view, final String url) {
Log.i(TAG, "page finished:"+url);
}
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError er) {
handler.proceed();
}
});
Wildcard method: Add the following entry into your DNS server and change the domain and IP address accordingly.
*.example.com IN A 1.2.3.4
As of iOS 12, NWPathMonitor replaced Reachability. Use this:
import Network
struct Internet {
private static let monitor = NWPathMonitor()
static var active = false
static var expensive = false
/// Monitors internet connectivity changes. Updates with every change in connectivity.
/// Updates variables for availability and if it's expensive (cellular).
static func start() {
guard monitor.pathUpdateHandler == nil else { return }
monitor.pathUpdateHandler = { update in
Internet.active = update.status == .satisfied ? true : false
Internet.expensive = update.isExpensive ? true : false
}
monitor.start(queue: DispatchQueue(label: "InternetMonitor"))
}
}
In use:
Internet.start()
if Internet.active {
// do something
}
if Internet.expensive {
// device is using Cellular data or WiFi hotspot
}
as long as you did not commit you can type
git merge --abort
just as the command line suggested.
Usually if I have to check which are the commits that differ from the master I do:
git rebase -i origin/master
In this way I can see the commits and decide to drop it or pick...
I got same problem. If I run brew link --overwrite python2
. There was still zsh: /usr/local/bin//fab: bad interpreter: /usr/local/opt/python/bin/python2.7: no such file or directory
.
cd /usr/local/opt/
mv python2 python
Solved it! Now we can use python2 version fabric.
=== 2018/07/25 updated
There is convinient way to use python2 version fab when your os python linked to python3. .sh
for your command.
# fab python2
cd /usr/local/opt
rm python
ln -s python2 python
# use the fab cli
...
# link to python3
cd /usr/local/opt
rm python
ln -s python3 python
Hope this helps.
In my case the underlying system account through which the package was running was locked out. Once we got the system account unlocked and reran the package, it executed successfully. The developer said that he got to know of this while debugging wherein he directly tried to connect to the server and check the status of the connection.
in console (cmd), go to app root path and execute:
type .env.example > .env
Swift 5 version of the solution
func myCriticalFunction() {
var value1: String?
var value2: String?
let group = DispatchGroup()
group.enter()
//async operation 1
DispatchQueue.global(qos: .default).async {
// Network calls or some other async task
value1 = //out of async task
group.leave()
}
group.enter()
//async operation 2
DispatchQueue.global(qos: .default).async {
// Network calls or some other async task
value2 = //out of async task
group.leave()
}
group.wait()
print("Value1 \(value1) , Value2 \(value2)")
}
Paint your two canvases onto a third canvas.
I had this same problem and none of the solutions here solved my problem. I had one opaque canvas with another transparent canvas above it. The opaque canvas was completely invisible but the background of the page body was visible. The drawings from the transparent canvas on top were visible while the opaque canvas below it was not.
If you want to use a RecyclerView
with the GridLayoutManager
, this is the way to achieve horizontal scroll.
recyclerView.setLayoutManager(
new GridLayoutManager(recyclerView.getContext(), rows, GridLayoutManager.HORIZONTAL, false));
Short answer: set the maxWidth options property in the constructor. Yes, even if setting the maximum width was not what you wanted to do.
Longer story: Migrating a v2 map to v3, I saw exactly the problem described. Windows varied in width and height, and some had vertical scrollbars and some didn't. Some had <br /> embedded in the data, but at least one with that sized OK.
I didn't think the InfoWindowsOptions.maxWidth property was relevant, since I didn't care to constrain the width... but by setting it with the InfoWindow constructor, I got what I wanted, and the windows now autosize (vertically) and show the full content without a vertical scrollbar. Doesn't make a lot of sense to me, but it works!
There is no single simple way to do it, because PostgreSQL might be installed and set up in many different ways:
/opt
or /usr/local
, manually started or started by an init scriptrpm
/ deb
packages and started via init scriptrpm
/ deb
packages and started via init scriptPATH
or default portYou can't rely on psql
being on the PATH
. You can't rely on there being only one psql
on the system (multiple versions might be installed in different ways). You can't do it based on port, as there's no guarantee it's on port 5432, or that there aren't multiple versions.
Prompt the user and ask them.
JAR files allow to package multiple files in order to use it as a library, plugin, or any kind of application. On the other hand, WAR files are used only for web applications.
JAR can be created with any desired structure. In contrast, WAR has a predefined structure with WEB-INF and META-INF directories.
A JAR file allows Java Runtime Environment (JRE) to deploy an entire application including the classes and the associated resources in a single request. On the other hand, a WAR file allows testing and deploying a web application easily.
I'm not sure what types of files you are trying to write the properties for but taglib-sharp is an excellent open source tagging library that wraps up all this functionality nicely. It has a lot of built in support for most of the popular media file types but also allows you to do more advanced tagging with pretty much any file.
EDIT: I've updated the link to taglib sharp. The old link no longer worked.
EDIT: Updated the link once again per kzu's comment.
Since you've already looked into strtok
just continue down the same path and split your string using space (' '
) as a delimiter, then use something as realloc
to increase the size of the array containing the elements to be passed to execvp
.
See the below example, but keep in mind that strtok
will modify the string passed to it. If you don't want this to happen you are required to make a copy of the original string, using strcpy
or similar function.
char str[]= "ls -l";
char ** res = NULL;
char * p = strtok (str, " ");
int n_spaces = 0, i;
/* split string and append tokens to 'res' */
while (p) {
res = realloc (res, sizeof (char*) * ++n_spaces);
if (res == NULL)
exit (-1); /* memory allocation failed */
res[n_spaces-1] = p;
p = strtok (NULL, " ");
}
/* realloc one extra element for the last NULL */
res = realloc (res, sizeof (char*) * (n_spaces+1));
res[n_spaces] = 0;
/* print the result */
for (i = 0; i < (n_spaces+1); ++i)
printf ("res[%d] = %s\n", i, res[i]);
/* free the memory allocated */
free (res);
res[0] = ls
res[1] = -l
res[2] = (null)
There is a lot of lesson to learn handcrafting state machines in C, but let me also suggest Ragel state machine compiler:
http://www.complang.org/ragel/
It has quite simple way of defining state machines and then you can generate graphs, generate code in different styles (table-driven, goto-driven), analyze that code if you want to, etc. And it's powerful, can be used in production code for various protocols.
I had Java 1.7 & 1.8 installed (with SBT 2.4 that requires Java 1.8). Even though my project was linked to Java 1.8, I had to change the JAVA_HOME environment variable to point 1.8. Finally, problem solved.
I just figured out how to do this:
It appears that when you add a parent folder to version control, Eclipse adds all sub-folders. Once the sub-folders are added to version control, it is not possible to ignore them.
Here's how to do it:
Right click on the top level folder and add to version control Right click on the child folder you want to ignore, revert Right click on the child folder you want to ignore, svn:ignore (which will now be available)
Javascript
This method is quite easy and blocks the pop up asking for form resubmission on refresh once the form is submitted. Just place this line of javascript code at the footer of your file and see the magic.
<script>
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
</script>
As has been mentioned, you may run into several issues if you use ISNUMERIC
:
-- Incorrectly gives 0:
SELECT CASE WHEN ISNUMERIC('-') = 1 THEN CAST('-' AS INT) END
-- Error (conversion failure):
SELECT CASE WHEN ISNUMERIC('$') = 1 THEN CAST('$' AS INT) END
SELECT CASE WHEN ISNUMERIC('4.4') = 1 THEN CAST('4.4' AS INT) END
SELECT CASE WHEN ISNUMERIC('1,300') = 1 THEN CAST('1,300' AS INT) END
-- Error (overflow):
SELECT CASE WHEN ISNUMERIC('9999999999') = 1 THEN CAST('9999999999' AS INT) END
If you want a reliable conversion, you'll need to code one yourself.
Update: My new recommendation would be to use an intermediary test conversion to FLOAT
to validate the number. This approach is based on adrianm's comment. The logic can be defined as an inline table-valued function:
CREATE FUNCTION TryConvertInt (@text NVARCHAR(MAX))
RETURNS TABLE
AS
RETURN
(
SELECT
CASE WHEN ISNUMERIC(@text + '.e0') = 1 THEN
CASE WHEN CONVERT(FLOAT, @text) BETWEEN -2147483648 AND 2147483647
THEN CONVERT(INT, @text)
END
END AS [Result]
)
Some tests:
SELECT [Conversion].[Result]
FROM ( VALUES
( '1234' ) -- 1234
, ( '1,234' ) -- NULL
, ( '1234.0' ) -- NULL
, ( '-1234' ) -- -1234
, ( '$1234' ) -- NULL
, ( '1234e10' ) -- NULL
, ( '1234 5678' ) -- NULL
, ( '123-456' ) -- NULL
, ( '1234.5' ) -- NULL
, ( '123456789000000' ) -- NULL
, ( 'N/A' ) -- NULL
, ( '-' ) -- NULL
, ( '$' ) -- NULL
, ( '4.4' ) -- NULL
, ( '1,300' ) -- NULL
, ( '9999999999' ) -- NULL
, ( '00000000000000001234' ) -- 1234
, ( '212110090000000235698741' ) -- NULL
) AS [Source] ([Text])
OUTER APPLY TryConvertInt ([Source].[Text]) AS [Conversion]
Results are similar to Joseph Sturtevant's answer, with the following main differences:
.
or ,
in order to mimic the behaviour of native INT
conversions. '1,234'
and '1234.0'
return NULL
.'00000000000000001234'
evaluates to 12
. Increasing the parameter length would result in errors on numbers that overflow BIGINT
, such as BBANs (basic bank account numbers) like '212110090000000235698741'
.Withdrawn: The approach below is no longer recommended, as is left just for reference.
The snippet below works on non-negative integers. It checks that your string does not contain any non-digit characters, is not empty, and does not overflow (by exceeding the maximum value for the int
type). However, it also gives NULL
for valid integers whose length exceeds 10 characters due to leading zeros.
SELECT
CASE WHEN @text NOT LIKE '%[^0-9]%' THEN
CASE WHEN LEN(@text) BETWEEN 1 AND 9
OR LEN(@text) = 10 AND @text <= '2147483647'
THEN CAST (@text AS INT)
END
END
If you want to support any number of leading zeros, use the below. The nested CASE
statements, albeit unwieldy, are required to promote short-circuit evaluation and reduce the likelihood of errors (arising, for example, from passing a negative length to LEFT
).
SELECT
CASE WHEN @text NOT LIKE '%[^0-9]%' THEN
CASE WHEN LEN(@text) BETWEEN 1 AND 9 THEN CAST (@text AS INT)
WHEN LEN(@text) >= 10 THEN
CASE WHEN LEFT(@text, LEN(@text) - 10) NOT LIKE '%[^0]%'
AND RIGHT(@text, 10) <= '2147483647'
THEN CAST (@text AS INT)
END
END
END
If you want to support positive and negative integers with any number of leading zeros:
SELECT
-- Positive integers (or 0):
CASE WHEN @text NOT LIKE '%[^0-9]%' THEN
CASE WHEN LEN(@text) BETWEEN 1 AND 9 THEN CAST (@text AS INT)
WHEN LEN(@text) >= 10 THEN
CASE WHEN LEFT(@text, LEN(@text) - 10) NOT LIKE '%[^0]%'
AND RIGHT(@text, 10) <= '2147483647'
THEN CAST (@text AS INT)
END
END
-- Negative integers:
WHEN LEFT(@text, 1) = '-' THEN
CASE WHEN RIGHT(@text, LEN(@text) - 1) NOT LIKE '%[^0-9]%' THEN
CASE WHEN LEN(@text) BETWEEN 2 AND 10 THEN CAST (@text AS INT)
WHEN LEN(@text) >= 11 THEN
CASE WHEN SUBSTRING(@text, 2, LEN(@text) - 11) NOT LIKE '%[^0]%'
AND RIGHT(@text, 10) <= '2147483648'
THEN CAST (@text AS INT)
END
END
END
END
Depending on the file type you are focused on, Ctrl+H will open up different types of search screens.
A more consistent hotkey would be using the Alt method: Tap Alt, then A, then F.
Efficient Order of Operations:
You can find more details in my blog post: http://blog.simplyadvanced.net/android-how-to-findreplace-in-multiple-files-using-eclipse/
I was running Jenkins executing java -jar jenkins.war
.
In my case Jenkins wrote webroot in an stdout: webroot: $user.home/.jenkins
. So admin secret key was placed in a ~/.jenkins/secrets/initialAdminPassword
.
From Version 4.0.0 on RegionUtil
-methods have a new signature. For example:
RegionUtil.setBorderBottom(BorderStyle.DOUBLE,
CellRangeAddress.valueOf("A1:B7"), sheet);
I would suggest writing an extension method for this:
public static IEnumerable<T> Select<T>(this IDataReader reader,
Func<IDataReader, T> projection)
{
while (reader.Read())
{
yield return projection(reader);
}
}
You can then use LINQ's ToList()
method to convert that into a List<T>
if you want, like this:
using (IDataReader reader = ...)
{
List<Customer> customers = reader.Select(r => new Customer {
CustomerId = r["id"] is DBNull ? null : r["id"].ToString(),
CustomerName = r["name"] is DBNull ? null : r["name"].ToString()
}).ToList();
}
I would actually suggest putting a FromDataReader
method in Customer
(or somewhere else):
public static Customer FromDataReader(IDataReader reader) { ... }
That would leave:
using (IDataReader reader = ...)
{
List<Customer> customers = reader.Select<Customer>(Customer.FromDataReader)
.ToList();
}
(I don't think type inference would work in this case, but I could be wrong...)
PHP has JSON_PRETTY_PRINT option since 5.4.0 (release date 01-Mar-2012).
This should do the job:
$json = json_decode($string);
echo json_encode($json, JSON_PRETTY_PRINT);
See http://www.php.net/manual/en/function.json-encode.php
Note: Don't forget to echo "<pre>" before and "</pre>" after, if you're printing it in HTML to preserve formatting ;)