cd into the repo/directory that you're pushing into on the remote machine and enter
$ git config core.bare true
git config --global core.askpass "git-gui--askpass"
This worked for me. It may take 3-5 secs for the prompt to appear just enter your login credentials and you are good to go.
You can create your own personal API token (OAuth) and use it the same way as you would use your normal credentials (at: /settings/tokens
). For example:
git remote add fork https://[email protected]/foo/bar
git push fork
.netrc
Another method is to configure your user/password in ~/.netrc
(_netrc
on Windows), e.g.
machine github.com
login USERNAME
password PASSWORD
For HTTPS, add the extra line:
protocol https
To cache your GitHub password in Git when using HTTPS, you can use a credential helper to tell Git to remember your GitHub username and password every time it talks to GitHub.
git config --global credential.helper osxkeychain
(osxkeychain helper
is required),git config --global credential.helper wincred
git config --global credential.helper cache
Related:
This worked for my GIT version 1.8.4:
there's no problem - everything works as expected.
In GitLab some branches can be protected. By default only Maintainer/Owner users can commit to protected branches (see permissions docs). master
branch is protected by default - it forces developers to issue merge requests to be validated by project maintainers before integrating them into main code.
You can turn on and off protection on selected branches in Project Settings (where exactly depends on GitLab version - see instructions below).
On the same settings page you can also allow developers to push into the protected branches. With this setting on, protection will be limited to rejecting operations requiring git push --force
(rebase etc.)
Go to project: "Settings" ? "Repository" ? "Expand" on "Protected branches"
I'm not really sure when this change was introduced, screenshots are from 10.3 version.
Now you can select who is allowed to merge or push into selected branches (for example: you can turn off pushes to master
at all, forcing all changes to branch to be made via Merge Requests). Or you can click "Unprotect" to completely remove protection from branch.
Similarly to GitLab 9.3, but no need to click "Expand" - everything is already expanded:
Go to project: "Settings" ? "Repository" ? scroll down to "Protected branches".
Project: "Settings" ? "Protected branches" (if you are at least 'Master' of given project).
Then click on "Unprotect" or "Developers can push":
git commit
is to commit the files that is staged in the local repo. git push
is to fast-forward merge the master branch of local side with the remote master branch. But the merge won't always success. If rejection appears, you have to pull
so that you can make a successful git push
.
For pushing a single tag: git push <reponame> <tagname>
For instance, git push production 1.0.0
. Tags are not bound to branches, they are bound to commits.
When you want to have the tag's content in the master branch, do that locally on your machine. I would assume that you continued developing in your local master branch. Then just a git push origin master
should suffice.
Try to create remote origin first, maybe is missing because you change name of the remote repo
git remote add origin URL_TO_YOUR_REPO
pull is always the right approach but one exception could be when you are trying to convert a none-Git file system to a Github repository. There you would have to force the first commit in.
git init
git add README.md
git add .
git commit -m "first commit"
git remote add origin https://github.com/userName/repoName.git
git push --force origin master
Another technique I just found for solving this (even if I deleted origin first, what appears to be a mistake) is manipulating git config directly:
git config remote.origin.url url-to-my-other-remote
I did the following steps to resolve the issue. On the branch which was giving me the error:
git pull origin [branch-name]<current branch>
First of all, Relax.
"Nothing is under our control. Our control is mere illusion.", "To err is human"
I get that you've unintentionally pushed your code to remote-master
. THIS is going to be alright.
1. At first, get the SHA-1
value of the commit you are trying to return, e.g. commit to master branch. run this:
git log
you'll see bunch of 'f650a9e398ad9ca606b25513bd4af9fe...' like strings along with each of the commits. copy that number from the commit that you want to return back.
2. Now, type in below command:
git reset --hard your_that_copied_string_but_without_quote_mark
you should see message like "HEAD is now at ". you are on clear. What it just have done is to reflect that change locally.
3. Now, type in below command:
git push -f
you should see like
"warning: push.default is unset; its implicit value has changed in..... ... Total 0 (delta 0), reused 0 (delta 0) ... ...your_branch_name -> master (forced update)."
Now, you are all clear. Check the master with "git log" again, your fixed_destination_commit should be on top of the list.
You are welcome (in advance ;))
UPDATE:
Now, the changes you had made before all these began, are now gone. If you want to bring those hard-works back again, it's possible. Thanks to git reflog, and git cherry-pick commands.
For that, i would suggest to please follow this blog or this post.
The following solved the problem for me.
First I used this command to figure what was the github account used:
ssh -T [email protected]
This gave me an answer like this:
Hi <github_account_name>! You've successfully authenticated, but GitHub does not provide shell access. I just had to give the access to fix the problem.
Then I understood that the Github user described in the answer (github_account_name) wasn't authorized on the Github repository I was trying to pull.
Some files are write-protected that even git cannot over write it. Change the folder permission to allow writing e.g. sudo chmod 775 foldername
And then execute
git pull
again
git push
can push all branches or a single one dependent on this configuration:
Push all branches
git config --global push.default matching
It will push all the branches to the remote branch and would merge them.
If you don't want to push all branches, you can push the current branch if you fully specify its name, but this is much is not different from default
.
Push only the current branch if its named upstream is identical
git config --global push.default simple
So, it's better, in my opinion, to use this option and push your code branch by branch. It's better to push branches manually and individually.
What you basically want to do is to force push your local branch, in order to overwrite the remote one.
If you want a more detailed explanation of each of the following commands, then see my details section below. You basically have 4 different options for force pushing with Git:
git push <remote> <branch> -f
git push origin master -f # Example
git push <remote> -f
git push origin -f # Example
git push -f
git push <remote> <branch> --force-with-lease
If you want a more detailed explanation of each command, then see my long answers section below.
Warning: force pushing will overwrite the remote branch with the state of the branch that you're pushing. Make sure that this is what you really want to do before you use it, otherwise you may overwrite commits that you actually want to keep.
You can completely specify specific branches and a remote. The -f
flag is the short version of --force
git push <remote> <branch> --force
git push <remote> <branch> -f
When the branch to push branch is omitted, Git will figure it out based on your config settings. In Git versions after 2.0, a new repo will have default settings to push the currently checked-out branch:
git push <remote> --force
while prior to 2.0, new repos will have default settings to push multiple local branches. The settings in question are the remote.<remote>.push
and push.default
settings (see below).
When both the remote and the branch are omitted, the behavior of just git push --force
is determined by your push.default
Git config settings:
git push --force
As of Git 2.0, the default setting, simple
, will basically just push your current branch to its upstream remote counter-part. The remote is determined by the branch's branch.<remote>.remote
setting, and defaults to the origin repo otherwise.
Before Git version 2.0, the default setting, matching
, basically just pushes all of your local branches to branches with the same name on the remote (which defaults to origin).
You can read more push.default
settings by reading git help config
or an online version of the git-config(1) Manual Page.
--force-with-lease
Force pushing with a "lease" allows the force push to fail if there are new commits on the remote that you didn't expect (technically, if you haven't fetched them into your remote-tracking branch yet), which is useful if you don't want to accidentally overwrite someone else's commits that you didn't even know about yet, and you just want to overwrite your own:
git push <remote> <branch> --force-with-lease
You can learn more details about how to use --force-with-lease
by reading any of the following:
The solution is very simple and worked for me.
Try this :
git pull --rebase <url>
then
git push -u origin master
If you prefer using GitHub Desktop, you can simply navigate inside the parent directory of your local repository and delete all of the files inside the parent directory. Then, commit and push your changes. Your repository will be cleansed of all files.
Track the remote branch
You can specify the default remote repository for pushing and pulling using git-branch’s track option. You’d normally do this by specifying the --track option when creating your local master branch, but as it already exists we’ll just update the config manually like so:
Edit your .git/config
[branch "master"]
remote = origin
merge = refs/heads/master
Now you can simply git push and git pull.
[source]
If you already have your SSH keys set up and are still getting the password prompt, make sure your repo URL is in the form
git+ssh://[email protected]/username/reponame.git
as opposed to
https://github.com/username/reponame.git
To see your repo URL, run:
git remote show origin
You can change the URL with git remote set-url
like so:
git remote set-url origin git+ssh://[email protected]/username/reponame.git
First of all, I would not make any changes directly in the "main" repo. If you really want to have a "main" repo, then you should only push to it, never change it directly.
Regarding the error you are getting, have you tried git pull
from your local repo, and then git push
to the main repo? What you are currently doing (if I understood it well) is forcing the push and then losing your changes in the "main" repo. You should merge the changes locally first.
The safest command to push different local Git branches to Heroku/master.
git push -f heroku branch_name:master
Note: Although, you can push without using the -f, the -f (force flag) is recommended in order to avoid conflicts with other developers’ pushes.
git push
or
git push server_name master
should do the trick, after you have made a commit to your local repository.
git status #then file which you need to push git add example.FileExtension
git commit "message is example"
git push -u origin(or whatever name you used) master(or name of some branch where you want to push it)
As an extend to @Eugene's answer another version which will work to push code from local repo to master/develop branch .
Switch to branch ‘master’:
$ git checkout master
Merge from local repo to master:
$ git merge --no-ff FEATURE/<branch_Name>
Push to master:
$ git push
if you want to create a new repository with the same project inside the github and the previous Remote is not allowing you to do that in that case First Delete That Repository on github then you simply need to delete the .git folder C:\Users\Shiva\AndroidStudioProjects\yourprojectname\.git delete that folder,(make sure you click on hidden file because this folder is hidden )
Also click on the minus(Remove button) from the android studio Setting->VersionControl click here for removing the Version control from android And then you will be able to create new Repository.
I got this error on Azure Git, and this solves the problem:
git fetch
git pull
git push --no-verify
Since January 2013, GitHub included a Delete branch button next to each branch in your "Branches" page.
Relevant blog post: Create and delete branches
So let's say you have a local branch foo, a remote called origin and a remote branch origin/master.
To push the contents of foo to origin/master, you first need to set its upstream:
git checkout foo
git branch -u origin/master
Then you can push to this branch using:
git push origin HEAD:master
In the last command you can add --force to replace the entire history of origin/master with that of foo.
git branch --set-upstream <remote-branch>
sets the default remote branch for the current local branch.
Any future git pull
command (with the current local branch checked-out),
will attempt to bring in commits from the <remote-branch>
into the current local branch.
One way to avoid having to explicitly type --set-upstream
is to use its shorthand flag -u
as follows:
git push -u origin local-branch
This sets the upstream association for any future push/pull attempts automatically.
For more details, checkout this detailed explanation about upstream branches and tracking.
To avoid confusion, recent versions of
git
deprecate this somewhat ambiguous--set-upstream
option in favour of a more verbose--set-upstream-to
option with identical syntax and behaviourgit branch --set-upstream-to <origin/remote-branch>
I have faced this error, Previous I had push in root directory, and now I have push another directory, so I could be remove this error and run below commands.
git add .
git commit -m "some comments"
git push --set-upstream origin master
A git push will try and push all local branches to the remote server, this is likely what you do not want. I have a couple of conveniences setup to deal with this:
Alias "gpull" and "gpush" appropriately:
In my ~/.bash_profile
get_git_branch() {
echo `git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/'`
}
alias gpull='git pull origin `get_git_branch`'
alias gpush='git push origin `get_git_branch`'
Thus, executing "gpush" or "gpull" will push just my "currently on" branch.
You can get around this "limitation" by editing the .git/config
on the destination server. Add the following to allow a git repository to be pushed to even if it is "checked out":
[receive]
denyCurrentBranch = warn
or
[receive]
denyCurrentBranch = false
The first will allow the push while warning of the possibility to mess up the branch, whereas the second will just quietly allow it.
This can be used to "deploy" code to a server which is not meant for editing. This is not the best approach, but a quick one for deploying code.
One classic root cause for this message is:
git init lis4368/assignments
),Ie, if you don't have added and committed at least once, there won't be a local master
branch to push to.
Try first to create a commit:
git add .
) then git commit -m "first commit"
git commit --allow-empty -m "Initial empty commit"
And then try git push -u origin master
again.
See "Why do I need to explicitly push a new branch?" for more.
You need to make sure that no other users of this repository are fetching the incorrect changes or trying to build on top of the commits that you want removed because you are about to rewind history.
Then you need to 'force' push the old reference.
git push -f origin last_known_good_commit:branch_name
or in your case
git push -f origin cc4b63bebb6:alpha-0.3.0
You may have receive.denyNonFastForwards
set on the remote repository. If this is the case, then you will get an error which includes the phrase [remote rejected]
.
In this scenario, you will have to delete and recreate the branch.
git push origin :alpha-0.3.0
git push origin cc4b63bebb6:refs/heads/alpha-0.3.0
If this doesn't work - perhaps because you have receive.denyDeletes
set, then you have to have direct access to the repository. In the remote repository, you then have to do something like the following plumbing command.
git update-ref refs/heads/alpha-0.3.0 cc4b63bebb6 83c9191dea8
If the SSH key or .netrc
file did not work for you, then another simple, but less secure solution, that could work for you is git-credential-store - Helper to store credentials on disk:
git config --global credential.helper store
By default, credentials will be saved in file ~/.git-credentials
. It will be created and written to.
Please note using this helper will store your passwords unencrypted on disk, protected only by filesystem permissions. If this may not be an acceptable security tradeoff.
[ Solution ]
$ git push origin
^ this solved it for me. What it did, it synchronized my master (on laptop) with "origin" that's on the remote server.
To push specific, one tag do following
git push origin tag_name
I simply do
git push -u origin localBranch:remoteBranchToBeCreated
over an already cloned project.
Git creates a new branch named remoteBranchToBeCreated
under my commits I did in localBranch
.
Edit: this changes your current local branch's (possibly named localBranch
) upstream to origin/remoteBranchToBeCreated
. To fix that, simply type:
git branch --set-upstream-to=origin/localBranch
or
git branch -u origin/localBranch
So your current local branch now tracks origin/localBranch
back.
If you get a message from git complaining about the value 'simple' in the configuration, check your git version.
After upgrading Xcode (on a Mac running Mountain Lion), which also upgraded git from 1.7.4.4 to 1.8.3.4, shells started before the upgrade were still running git 1.7.4.4 and complained about the value 'simple' for push.default in the global config.
The solution was to close the shells running the old version of git and use the new version.
Here's something I found super helpful if you've already been messing around with your repo before you asked for help. First type:
git status
After this, you should see something along the lines of
On branch master
Your branch is ahead of 'origin/master' by 2 commits.
(use "git push" to publish your local commits)
nothing to commit, working tree clean
The important part is the "2 commits"! From here, go ahead and type in:
git reset HEAD~<HOWEVER MANY COMMITS YOU WERE BEHIND>
So, for the example above, one would type:
git reset HEAD~2
After you typed that, your "git status" should say:
On branch master
Your branch is up to date with 'origin/master'.
nothing to commit, working tree clean
From there, you can delete the large file (assuming you haven't already done so), and you should be able to re-commit everything without losing your work.
I know this isn't a super fancy reply, but I hope it helps!
If you follow the principle of Occam's razor, you might think setting all the weights to 0 or 1 would be the best solution. This is not the case.
With every weight the same, all the neurons at each layer are producing the same output. This makes it hard to decide which weights to adjust.
# initialize two NN's with 0 and 1 constant weights
model_0 = Net(constant_weight=0)
model_1 = Net(constant_weight=1)
Validation Accuracy
9.625% -- All Zeros
10.050% -- All Ones
Training Loss
2.304 -- All Zeros
1552.281 -- All Ones
A uniform distribution has the equal probability of picking any number from a set of numbers.
Let's see how well the neural network trains using a uniform weight initialization, where low=0.0
and high=1.0
.
Below, we'll see another way (besides in the Net class code) to initialize the weights of a network. To define weights outside of the model definition, we can:
- Define a function that assigns weights by the type of network layer, then
- Apply those weights to an initialized model using
model.apply(fn)
, which applies a function to each model layer.
# takes in a module and applies the specified weight initialization
def weights_init_uniform(m):
classname = m.__class__.__name__
# for every Linear layer in a model..
if classname.find('Linear') != -1:
# apply a uniform distribution to the weights and a bias=0
m.weight.data.uniform_(0.0, 1.0)
m.bias.data.fill_(0)
model_uniform = Net()
model_uniform.apply(weights_init_uniform)
Validation Accuracy
36.667% -- Uniform Weights
Training Loss
3.208 -- Uniform Weights
The general rule for setting the weights in a neural network is to set them to be close to zero without being too small.
Good practice is to start your weights in the range of [-y, y] where
y=1/sqrt(n)
(n is the number of inputs to a given neuron).
# takes in a module and applies the specified weight initialization
def weights_init_uniform_rule(m):
classname = m.__class__.__name__
# for every Linear layer in a model..
if classname.find('Linear') != -1:
# get the number of the inputs
n = m.in_features
y = 1.0/np.sqrt(n)
m.weight.data.uniform_(-y, y)
m.bias.data.fill_(0)
# create a new model with these weights
model_rule = Net()
model_rule.apply(weights_init_uniform_rule)
below we compare performance of NN, weights initialized with uniform distribution [-0.5,0.5) versus the one whose weight is initialized using general rule
Validation Accuracy
75.817% -- Centered Weights [-0.5, 0.5)
85.208% -- General Rule [-y, y)
Training Loss
0.705 -- Centered Weights [-0.5, 0.5)
0.469 -- General Rule [-y, y)
The normal distribution should have a mean of 0 and a standard deviation of
y=1/sqrt(n)
, where n is the number of inputs to NN
## takes in a module and applies the specified weight initialization
def weights_init_normal(m):
'''Takes in a module and initializes all linear layers with weight
values taken from a normal distribution.'''
classname = m.__class__.__name__
# for every Linear layer in a model
if classname.find('Linear') != -1:
y = m.in_features
# m.weight.data shoud be taken from a normal distribution
m.weight.data.normal_(0.0,1/np.sqrt(y))
# m.bias.data should be 0
m.bias.data.fill_(0)
below we show the performance of two NN one initialized using uniform-distribution and the other using normal-distribution
Validation Accuracy
85.775% -- Uniform Rule [-y, y)
84.717% -- Normal Distribution
Training Loss
0.329 -- Uniform Rule [-y, y)
0.443 -- Normal Distribution
list1 = sorted(csv1, key=lambda x: (x[1], x[2]) )
Cleaner way to remove those spaces is by using float: left;
:
HTML:
<div>Some Text</div>
<div>Some Text</div>
CSS:
div {
background-color: red;
float: left;
}
I'ts supported in all new browsers. Never got it why back when IE ruled lot's of developers didn't make sue their site works well on firefox/chrome, but today, when IE is down to 14.3 %. anyways, didn't have many issues in IE-9 even thought it's not supported, for example the above demo works fine.
move.CompleteMove()
does not return a value (perhaps it just prints something). Any method that does not return a value returns None
, and you have assigned None
to self.values
.
Here is an example of this:
>>> def hello(x):
... print x*2
...
>>> hello('world')
worldworld
>>> y = hello('world')
worldworld
>>> y
>>>
You'll note y
doesn't print anything, because its None
(the only value that doesn't print anything on the interactive prompt).
Using aws s3 cp
from the AWS Command-Line Interface (CLI) will require the --recursive
parameter to copy multiple files.
aws s3 cp s3://myBucket/dir localdir --recursive
The aws s3 sync
command will, by default, copy a whole directory. It will only copy new/modified files.
aws s3 sync s3://mybucket/dir localdir
Just experiment to get the result you want.
Documentation:
use this code in teminal :
python -m pip install --upgrade PAKAGE_NAME #instead of PAKAGE_NAME
for example i want update pip pakage :
python -m pip install --upgrade pip
more example :
python -m pip install --upgrade selenium
python -m pip install --upgrade requests
...
hey recently i figured it out how to set width if your gridview databound with sql dataset.first set these control RowStyle-Wrap="false" HeaderStyle-Wrap="false"
and then you can set the column width as much as you like. ex : ItemStyle-Width="150px" HeaderStyle-Width="150px"
Forwarding the example by @ritiek, I'm a beginner in ML too, maybe this kind of formatting will help see the name instead of just class number.
images = np.vstack([x, y])
prediction = model.predict(images)
print(prediction)
i = 1
for things in prediction:
if(things == 0):
print('%d.It is cancer'%(i))
else:
print('%d.Not cancer'%(i))
i = i + 1
If you want to escape user input in a variable you can do like below within SQL
Set @userinput = replace(@userinput,'''','''''')
The @userinput will be now escaped with an extra single quote for every occurance of a quote
Use array_splice
rather than unset
:
$array = array(1,2,3,4,5);
foreach($array as $i => $info)
{
if($info == 1 || $info == 2)
{
array_splice($array, $i, 1);
}
}
print_r($array);
It failed because you used ajax="false"
. This fires a full synchronous request which in turn causes a full page reload, causing the oncomplete
to be never fired (note that all other ajax-related attributes like process
, onstart
, onsuccess
, onerror
and update
are also never fired).
That it worked when you removed actionListener
is also impossible. It should have failed the same way. Perhaps you also removed ajax="false"
along it without actually understanding what you were doing. Removing ajax="false"
should indeed achieve the desired requirement.
Also is it possible to execute actionlistener and oncomplete simultaneously?
No. The script can only be fired before or after the action listener. You can use onclick
to fire the script at the moment of the click. You can use onstart
to fire the script at the moment the ajax request is about to be sent. But they will never exactly simultaneously be fired. The sequence is as follows:
onclick
JavaScript code is executedprocess
and current HTML DOM treeonstart
JavaScript code is executedprocess
actionListener
JSF backing bean method is executedaction
JSF backing bean method is executedupdate
and current JSF component treeonsuccess
JavaScript code is executedonerror
JavaScript code is executedupdate
based on ajax response and current HTML DOM treeoncomplete
JavaScript code is executedNote that the update
is performed after actionListener
, so if you were using onclick
or onstart
to show the dialog, then it may still show old content instead of updated content, which is poor for user experience. You'd then better use oncomplete
instead to show the dialog. Also note that you'd better use action
instead of actionListener
when you intend to execute a business action.
VAL1 and VAL2 need to be dimmed as integer, not as string, to be used as an argument for Cells, which takes integers, not strings, as arguments.
Dim val1 As Integer, val2 As Integer, i As Integer
For i = 1 To 333
Sheets("Feuil2").Activate
ActiveSheet.Cells(i, 1).Select
val1 = Cells(i, 1).Value
val2 = Cells(i, 2).Value
Sheets("Classeur2.csv").Select
Cells(val1, val2).Select
ActiveCell.FormulaR1C1 = "1"
Next i
Also seems nobody noticed -x operator on symlinks. A symlink (chain) to a regular file (not classified as executable) fails the test.
Looks like you might want the ISO format so that you can retain the timezone.
var dateTime = new Date(1370001284000);
dateTime.toISOString(); // Returns "2013-05-31T11:54:44.000Z"
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
SELECT
*
FROM
primarytable P
WHERE
NOT EXISTS (SELECT * FROM secondarytable S
WHERE
P.PKCol = S.FKCol)
Generally, (NOT) EXISTS
is a better choice then (NOT) IN
or (LEFT) JOIN
First, define a new function to read the input (according to the structure of your input) and store the string, which means the memory in stack used. Set the length of string to be enough for your input.
Second, use strlen
to measure the exact used length of string stored before, and malloc
to allocate memory in heap, whose length is defined by strlen
. The code is shown below.
int strLength = strlen(strInStack);
if (strLength == 0) {
printf("\"strInStack\" is empty.\n");
}
else {
char *strInHeap = (char *)malloc((strLength+1) * sizeof(char));
strcpy(strInHeap, strInStack);
}
return strInHeap;
Finally, copy the value of strInStack
to strInHeap
using strcpy
, and return the pointer to strInHeap
. The strInStack
will be freed automatically because it only exits in this sub-function.
I was able to use
return View::make('myviewfolder.myview', compact('view1','view2','view3'));
I don't know if it's because I am using PHP 5.5 it works great :)
finalize()
is called just before garbage collection. It is not called when an object goes out of scope. This means that you cannot know when or even if finalize()
will be executed.
Example:
If your program end before garbage collector occur, then finalize()
will not execute. Therefore, it should be used as backup procedure to ensure the proper handling of other resources, or for special use applications, not as the means that your program uses in its normal operation.
There's an entire practice that says it's a bad idea to have inline functions/styles. Taking into account you already have an ID for your button, consider
JS
var myvar=15;
function init(){
document.getElementById('EditBanner').onclick=function(){EditBanner(myvar);};
}
window.onload=init;
HTML
<input id="EditBanner" type="button" value="Edit Image" />
I wonder why nobody mentioned the Minted package. It has far better syntax highlighting than the LaTeX listing package. It uses Pygments.
$ pip install Pygments
Example in LaTeX:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage{minted}
\begin{document}
\begin{minted}{python}
import numpy as np
def incmatrix(genl1,genl2):
m = len(genl1)
n = len(genl2)
M = None #to become the incidence matrix
VT = np.zeros((n*m,1), int) #dummy variable
#compute the bitwise xor matrix
M1 = bitxormatrix(genl1)
M2 = np.triu(bitxormatrix(genl2),1)
for i in range(m-1):
for j in range(i+1, m):
[r,c] = np.where(M2 == M1[i,j])
for k in range(len(r)):
VT[(i)*n + r[k]] = 1;
VT[(i)*n + c[k]] = 1;
VT[(j)*n + r[k]] = 1;
VT[(j)*n + c[k]] = 1;
if M is None:
M = np.copy(VT)
else:
M = np.concatenate((M, VT), 1)
VT = np.zeros((n*m,1), int)
return M
\end{minted}
\end{document}
Which results in:
You need to use the flag -shell-escape
with the pdflatex command.
For more information: https://www.sharelatex.com/learn/Code_Highlighting_with_minted
glob.glob
or os.listdir
will do it.
You can add/edit content on multiple lines by using control button. This is multi edit feature in Notepad++, we need to enable it from settings. Press and hold control, select places where you want to enter text, release control and start typing, this will update the text at all the places selected previously.
Ref: http://notepad-plus-plus.org/features/multi-editing.html
searchfile = open("file.txt", "r")
for line in searchfile:
if "searchphrase" in line: print line
searchfile.close()
To print out multiple lines (in a simple way)
f = open("file.txt", "r")
searchlines = f.readlines()
f.close()
for i, line in enumerate(searchlines):
if "searchphrase" in line:
for l in searchlines[i:i+3]: print l,
print
The comma in print l,
prevents extra spaces from appearing in the output; the trailing print statement demarcates results from different lines.
Or better yet (stealing back from Mark Ransom):
with open("file.txt", "r") as f:
searchlines = f.readlines()
for i, line in enumerate(searchlines):
if "searchphrase" in line:
for l in searchlines[i:i+3]: print l,
print
It takes a long time, and we did all the above solutions and they didn't work at all so our team decided to remove Pod
files and run pod install
again. finally, our OTA uploaded ipa installed on the user's device.
best Solution
clean project menu > Product > Clean Build Folder
and /Users/{you user name}/Library/Developer/Xcode/DerivedData
go to your project directory and remove Podfile.lock
,Pods
folder,pod_***.framework
run pod install
again
Done
Lets take a case when you have an array of 1 element, and you want to extend the size to accommodate 1 million elements dynamically.
Case 1:
String [] wordList = new String[1];
String [] tmp = new String[wordList.length + 1];
for(int i = 0; i < wordList.length ; i++){
tmp[i] = wordList[i];
}
wordList = tmp;
Case 2 (increasing size by a addition factor):
String [] wordList = new String[1];
String [] tmp = new String[wordList.length + 10];
for(int i = 0; i < wordList.length ; i++){
tmp[i] = wordList[i];
}
wordList = tmp;
Case 3 (increasing size by a multiplication factor):
String [] wordList = new String[1];
String [] tmp = new String[wordList.length * 2];
for(int i = 0; i < wordList.length ; i++){
tmp[i] = wordList[i];
}
wordList = tmp;
When extending the size of an Array dynamically, using Array.copy or iterating over the array and copying the elements to a new array using the for loop, actually iterates over each element of the array. This is a costly operation. Array.copy would be clean and optimized, still costly. So, I'd suggest increasing the array length by a multiplication factor.
How it helps is,
In case 1, to accommodate 1 million elements you have to increase the size of array 1 million - 1 times i.e. 999,999 times.
In case 2, you have to increase the size of array 1 million / 10 - 1 times i.e. 99,999 times.
In case 3, you have to increase the size of array by log21 million - 1 time i.e. 18.9 (hypothetically).
This works for me for more or less standard forms:
<button type="submit" value="Submit" name="ButtonType" id="whateveristheId" class="button-class">Submit<img src="/img/selectedImage.png" alt=""></button>
Say you want to fill with number 13.
int[] myarr = Enumerable.Range(0, 10).Select(n => 13).ToArray();
or
List<int> myarr = Enumerable.Range(0,10).Select(n => 13).ToList();
if you prefer a list.
Well, I'm sure that you didn't set the models yet, so what dose it migrate now ??
So the solution is setting all variables and set Charfield, Textfield....... and migrate them and it will work.
Another way to reduce bundle, is to serve GZIP instead of JS. We went from 2.6mb to 543ko.
Character varying is different than text. Try running
ALTER TABLE product_product ALTER COLUMN code TYPE text;
That will change the column type to text, which is limited to some very large amount of data (you would probably never actually hit it.)
just write it yourself using simple recursion:
public List<File> addFiles(List<File> files, File dir)
{
if (files == null)
files = new LinkedList<File>();
if (!dir.isDirectory())
{
files.add(dir);
return files;
}
for (File file : dir.listFiles())
addFiles(files, file);
return files;
}
Perhaps you were looking at the space complexity? That is O(n). The other complexities are as expected on the hash table entry. The search complexity approaches O(1) as the number of buckets increases. If at the worst case you have only one bucket in the hash table, then the search complexity is O(n).
Edit in response to comment I don't think it is correct to say O(1) is the average case. It really is (as the wikipedia page says) O(1+n/k) where K is the hash table size. If K is large enough, then the result is effectively O(1). But suppose K is 10 and N is 100. In that case each bucket will have on average 10 entries, so the search time is definitely not O(1); it is a linear search through up to 10 entries.
double *ptr = malloc(sizeof(double *) * TIME); /* ... */ for(tcount = 0; tcount <= TIME; tcount++) ^^
<=
to <
or alloc
SIZE + 1
elementsmalloc
is wrong, you'll want sizeof(double)
instead of
sizeof(double *)
ouah
comments, although not directly linked to your corruption problem, you're using *(ptr+tcount)
without initializing itptr[tcount]
instead of *(ptr + tcount)
malloc
+ free
since you already know SIZE
I know it is been answered long time ago, but i would like to share this also:
This code works very well:
SQLiteDatabase db = this.getReadableDatabase();
long taskCount = DatabaseUtils.queryNumEntries(db, TABLE_TODOTASK);
BUT what if i dont want to count all rows and i have a condition to apply?
DatabaseUtils have another function for this: DatabaseUtils.longForQuery
long taskCount = DatabaseUtils.longForQuery(db, "SELECT COUNT (*) FROM " + TABLE_TODOTASK + " WHERE " + KEY_TASK_TASKLISTID + "=?",
new String[] { String.valueOf(tasklist_Id) });
The longForQuery
documentation says:
Utility method to run the query on the db and return the value in the first column of the first row.
public static long longForQuery(SQLiteDatabase db, String query, String[] selectionArgs)
It is performance friendly and save you some time and boilerplate code
Hope this will help somebody someday :)
Along with the latest software (latest Eclipse and Java) and more RAM, you may need to
Keep radio buttons hidden, and on clicking of images, select them using JavaScript and style your image so that it look like selected. Here is the markup -
<div id="radio-button-wrapper">
<span class="image-radio">
<input name="any-name" style="display:none" type="radio"/>
<img src="...">
</span>
<span class="image-radio">
<input name="any-name" style="display:none" type="radio"/>
<img src="...">
</span>
</div>
and JS
$(".image-radio img").click(function(){
$(this).prev().attr('checked',true);
})
CSS
span.image-radio input[type="radio"]:checked + img{
border:1px solid red;
}
If your table columns contains duplicate data and If you directly apply row_ number() and create PARTITION on column, there is chance to have result in duplicated row and with row number value.
To remove duplicate row, you need one more INNER query in from clause which eliminates duplicate rows and then it will give output to it's foremost outer FROM clause where you can apply PARTITION and ROW_NUMBER ().
As like below example:
SELECT DATE, STATUS, TITLE, ROW_NUMBER() OVER (PARTITION BY DATE, STATUS, TITLE ORDER BY QUANTITY ASC) AS Row_Num
FROM (
SELECT DISTINCT <column names>...
) AS tbl
If creating a SSLSocketFactory
is not an option, just import the key into the JVM
Retrieve the public key:
$openssl s_client -connect dev-server:443
, then create a file dev-server.pem that looks like
-----BEGIN CERTIFICATE-----
lklkkkllklklklklllkllklkl
lklkkkllklklklklllkllklkl
lklkkkllklk....
-----END CERTIFICATE-----
Import the key: #keytool -import -alias dev-server -keystore $JAVA_HOME/jre/lib/security/cacerts -file dev-server.pem
.
Password: changeit
Restart JVM
I'm unsure if this is still an issue for this individual, but I know it can be a pain for many people in general. Granted, the above solutions will work in some instances, but if you are, for example, using a CMS like WordPress, and the outlines are being generated by either a plugin or theme, you will most likely not have this issue resolved, depending on how you are adding the CSS.
I'd suggest having a separate StyleSheet (for example, use 'Lazyest StyleSheet' plugin), and enter the following CSS within it to override the existing plugin (or theme)-forced style:
a:hover,a:active,a:link {
outline: 0 !important;
text-decoration: none !important;
}
Adding '!important' to the specific rule will make this a priority to generate even if the rule may be elsewhere (whether it's in a plugin, theme, etc.).
This helps save time when developing. Sure, you can dig for the original source, but when you're working on many projects, or need to perform updates (where your changes can be overridden [not suggested!]), or add new plugins or themes, this is the best recourse to save time.
Hope this helps...Peace!
Imports System.Net.NetworkInformation
Public Function PingHost(ByVal nameOrAddress As String) As Boolean
Dim pingable As Boolean = False
Dim pinger As Ping
Dim lPingReply As PingReply
Try
pinger = New Ping()
lPingReply = pinger.Send(nameOrAddress)
MessageBox.Show(lPingReply.Status)
If lPingReply.Status = IPStatus.Success Then
pingable = True
Else
pingable = False
End If
Catch PingException As Exception
pingable = False
End Try
Return pingable
End Function
Here are 3 examples:
$(document).on('click', 'ul li a', function (e) {_x000D_
e.preventDefault();_x000D_
_x000D_
var example1 = $(this).parents('ul:first').attr('id');_x000D_
$('#results').append('<p>Result from example 1: <strong>' + example1 + '</strong></p>');_x000D_
_x000D_
var example2 = $(this).parents('ul:eq(0)').attr('id');_x000D_
$('#results').append('<p>Result from example 2: <strong>' + example2 + '</strong></p>');_x000D_
_x000D_
var example3 = $(this).closest('ul').attr('id');_x000D_
$('#results').append('<p>Result from example 3: <strong>' + example3 + '</strong></p>');_x000D_
_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<ul id ="myList">_x000D_
<li><a href="www.example.com">Click here</a></li>_x000D_
</ul>_x000D_
_x000D_
<div id="results">_x000D_
<h1>Results:</h1>_x000D_
</div>
_x000D_
Let me know whether it was helpful.
I'm using the following configuration:
#site.yml:
- name: Example play
hosts: all
remote_user: ansible
become: yes
become_method: sudo
vars:
ansible_ssh_private_key_file: "/home/ansible/.ssh/id_rsa"
enum Constants
{
Abc = 1,
Def = 2,
Ghi = 3
}
...
int i = (int)Enum.Parse(typeof(Constants), "Def");
I see a similar problem...
I need to spool CSV file from SQLPLUS, but the output has 250 columns.
What I did to avoid annoying SQLPLUS output formatting:
set linesize 9999
set pagesize 50000
spool myfile.csv
select x
from
(
select col1||';'||col2||';'||col3||';'||col4||';'||col5||';'||col6||';'||col7||';'||col8||';'||col9||';'||col10||';'||col11||';'||col12||';'||col13||';'||col14||';'||col15||';'||col16||';'||col17||';'||col18||';'||col19||';'||col20||';'||col21||';'||col22||';'||col23||';'||col24||';'||col25||';'||col26||';'||col27||';'||col28||';'||col29||';'||col30 as x
from (
... here is the "core" select
)
);
spool off
the problem is you will lose column header names...
you can add this:
set heading off
spool myfile.csv
select col1_name||';'||col2_name||';'||col3_name||';'||col4_name||';'||col5_name||';'||col6_name||';'||col7_name||';'||col8_name||';'||col9_name||';'||col10_name||';'||col11_name||';'||col12_name||';'||col13_name||';'||col14_name||';'||col15_name||';'||col16_name||';'||col17_name||';'||col18_name||';'||col19_name||';'||col20_name||';'||col21_name||';'||col22_name||';'||col23_name||';'||col24_name||';'||col25_name||';'||col26_name||';'||col27_name||';'||col28_name||';'||col29_name||';'||col30_name from dual;
select x
from
(
select col1||';'||col2||';'||col3||';'||col4||';'||col5||';'||col6||';'||col7||';'||col8||';'||col9||';'||col10||';'||col11||';'||col12||';'||col13||';'||col14||';'||col15||';'||col16||';'||col17||';'||col18||';'||col19||';'||col20||';'||col21||';'||col22||';'||col23||';'||col24||';'||col25||';'||col26||';'||col27||';'||col28||';'||col29||';'||col30 as x
from (
... here is the "core" select
)
);
spool off
I know it`s kinda hardcore, but it works for me...
You can try this:
template<typename T>
inline const char* getTypeName() {
return typeid(T).name();
}
#define DEFINE_TYPE_NAME(type, type_name) \
template<> \
inline const char* getTypeName<type>() { \
return type_name; \
}
DEFINE_TYPE_NAME(int, "int")
DEFINE_TYPE_NAME(float, "float")
DEFINE_TYPE_NAME(double, "double")
DEFINE_TYPE_NAME(std::string, "string")
DEFINE_TYPE_NAME(bool, "bool")
DEFINE_TYPE_NAME(uint32_t, "uint")
DEFINE_TYPE_NAME(uint64_t, "uint")
// add your custom types' definitions
And call it like that:
void main() {
std::cout << getTypeName<int>();
}
Using cin's >> operator will drop leading whitespace and stop input at the first trailing whitespace. To grab an entire line of input, including spaces, try cin.getline()
. To grab one character at a time, you can use cin.get()
.
With a newer VS Code version it's quite simple.
Open VS Code in your project's folder.
Then open Python Terminal
(Ctrl-Shift-P: Python: Create Terminal)
In the terminal:
python -m venv .venv
you'll then see the following dialog:
click Yes
Then Python: Select Interpreter
(via Ctrl-Shift-P)
and select the option (in my case towards the bottom)
Python 3.7 (venv)
./venv/Scripts/python.exe
If you see
Activate.ps1 is not digitally signed. You cannot run this script on the current system.
you'll need to do the following: https://stackoverflow.com/a/18713789/2705777
For more information see: https://code.visualstudio.com/docs/python/environments#_global-virtual-and-conda-environments
Try this:
var funcNames = ["log", "warn", "error"];
var colors = ['color:green', 'color:orange', 'color:red'];
for (var i = 0; i < funcNames.length; i++) {
let funcName = funcNames[i];
let color = colors[i];
let oldFunc = console[funcName];
console[funcName] = function () {
var args = Array.prototype.slice.call(arguments);
if (args.length) args = ['%c' + args[0]].concat(color, args.slice(1));
oldFunc.apply(null, args);
};
}
now they all are as you wanted:
console.log("Log is green.");
console.warn("Warn is orange.");
console.error("Error is red.");
note: formatting like console.log("The number = %d", 123);
is not broken.
You cannot.
According to the XML Schema specification, a boolean is true
or false
. True
is not valid:
3.2.2.1 Lexical representation An instance of a datatype that is defined as ·boolean· can have the following legal literals {true, false, 1, 0}. 3.2.2.2 Canonical representation The canonical representation for boolean is the set of literals {true, false}.
If the tool you are using truly validates against the XML Schema standard, then you cannot convince it to accept True for a boolean.
My Stored Procedure Requires 2 Parameters and I needed my function to return a datatable here is 100% working code
Please make sure that your procedure return some rows
Public Shared Function Get_BillDetails(AccountNumber As String) As DataTable
Try
Connection.Connect()
debug.print("Look up account number " & AccountNumber)
Dim DP As New SqlDataAdapter("EXEC SP_GET_ACCOUNT_PAYABLES_GROUP '" & AccountNumber & "' , '" & 08/28/2013 &"'", connection.Con)
Dim DST As New DataSet
DP.Fill(DST)
Return DST.Tables(0)
Catch ex As Exception
Return Nothing
End Try
End Function
You can try this:
#!/bin/sh
nohup java -jar /web/server.jar &
The & symbol, switches the program to run in the background.
The nohup utility makes the command passed as an argument run in the background even after you log out.
Add a margin
to your li
tags. That will create space between the li
and you can use line-height
to set the spacing to the text within the li
tags.
As a few people have mentioned, the parameters in paramMap
should be accessed using the common Map
API:
To get a snapshot of the params, when you don't care that they may change:
this.bankName = this.route.snapshot.paramMap.get('bank');
To subscribe and be alerted to changes in the parameter values (typically as a result of the router's navigation)
this.route.paramMap.subscribe( paramMap => {
this.bankName = paramMap.get('bank');
})
Since Angular 4, params
have been deprecated in favor of the new interface paramMap
. The code for the problem above should work if you simply substitute one for the other.
If you inject ActivatedRoute
in your component, you'll be able to extract the route parameters
import {ActivatedRoute} from '@angular/router';
...
constructor(private route:ActivatedRoute){}
bankName:string;
ngOnInit(){
// 'bank' is the name of the route parameter
this.bankName = this.route.snapshot.params['bank'];
}
If you expect users to navigate from bank to bank directly, without navigating to another component first, you ought to access the parameter through an observable:
ngOnInit(){
this.route.params.subscribe( params =>
this.bankName = params['bank'];
)
}
For the docs, including the differences between the two check out this link and search for "activatedroute"
type "ls -ltrh /path_to_directory"
I guess you can install it via Parallel or in any other Virtual machine with windows in it
I definitely wouldn't use Block1. It doesn't seem right having the Error block in an IF statement unrelated to Errors.
Blocks 2,3 & 4 I guess are variations of a theme. I prefer the use of Blocks 3 & 4 over 2 only because of a dislike of the GOTO statement; I generally use the Block4 method. This is one example of code I use to check if the Microsoft ActiveX Data Objects 2.8 Library is added and if not add or use an earlier version if 2.8 is not available.
Option Explicit
Public booRefAdded As Boolean 'one time check for references
Public Sub Add_References()
Dim lngDLLmsadoFIND As Long
If Not booRefAdded Then
lngDLLmsadoFIND = 28 ' load msado28.tlb, if cannot find step down versions until found
On Error GoTo RefErr:
'Add Microsoft ActiveX Data Objects 2.8
Application.VBE.ActiveVBProject.references.AddFromFile _
Environ("CommonProgramFiles") + "\System\ado\msado" & lngDLLmsadoFIND & ".tlb"
On Error GoTo 0
Exit Sub
RefErr:
Select Case Err.Number
Case 0
'no error
Case 1004
'Enable Trust Centre Settings
MsgBox ("Certain VBA References are not available, to allow access follow these steps" & Chr(10) & _
"Goto Excel Options/Trust Centre/Trust Centre Security/Macro Settings" & Chr(10) & _
"1. Tick - 'Disable all macros with notification'" & Chr(10) & _
"2. Tick - 'Trust access to the VBA project objects model'")
End
Case 32813
'Err.Number 32813 means reference already added
Case 48
'Reference doesn't exist
If lngDLLmsadoFIND = 0 Then
MsgBox ("Cannot Find Required Reference")
End
Else
For lngDLLmsadoFIND = lngDLLmsadoFIND - 1 To 0 Step -1
Resume
Next lngDLLmsadoFIND
End If
Case Else
MsgBox Err.Number & vbCrLf & Err.Description, vbCritical, "Error!"
End
End Select
On Error GoTo 0
End If
booRefAdded = TRUE
End Sub
Not sure how to apply that to your file on your server, but typically, the regex to match the beginning of a string would be :
^CTR
The ^
means beginning of string / line
In Other ways to get difference between date;
import dateutil.parser
import datetime
last_sent_date = "" # date string
timeDifference = current_date - dateutil.parser.parse(last_sent_date)
time_difference_in_minutes = (int(timeDifference.days) * 24 * 60) + int((timeDifference.seconds) / 60)
So get output in Min.
Thanks
$lookup can now directly use an array as the local field. $unwind
is no longer needed.
The $lookup
aggregation pipeline stage will not work directly with an array. The main intent of the design is for a "left join" as a "one to many" type of join ( or really a "lookup" ) on the possible related data. But the value is intended to be singular and not an array.
Therefore you must "de-normalise" the content first prior to performing the $lookup
operation in order for this to work. And that means using $unwind
:
db.orders.aggregate([
// Unwind the source
{ "$unwind": "$products" },
// Do the lookup matching
{ "$lookup": {
"from": "products",
"localField": "products",
"foreignField": "_id",
"as": "productObjects"
}},
// Unwind the result arrays ( likely one or none )
{ "$unwind": "$productObjects" },
// Group back to arrays
{ "$group": {
"_id": "$_id",
"products": { "$push": "$products" },
"productObjects": { "$push": "$productObjects" }
}}
])
After $lookup
matches each array member the result is an array itself, so you $unwind
again and $group
to $push
new arrays for the final result.
Note that any "left join" matches that are not found will create an empty array for the "productObjects" on the given product and thus negate the document for the "product" element when the second $unwind
is called.
Though a direct application to an array would be nice, it's just how this currently works by matching a singular value to a possible many.
As $lookup
is basically very new, it currently works as would be familiar to those who are familiar with mongoose as a "poor mans version" of the .populate()
method offered there. The difference being that $lookup
offers "server side" processing of the "join" as opposed to on the client and that some of the "maturity" in $lookup
is currently lacking from what .populate()
offers ( such as interpolating the lookup directly on an array ).
This is actually an assigned issue for improvement SERVER-22881, so with some luck this would hit the next release or one soon after.
As a design principle, your current structure is neither good or bad, but just subject to overheads when creating any "join". As such, the basic standing principle of MongoDB in inception applies, where if you "can" live with the data "pre-joined" in the one collection, then it is best to do so.
The one other thing that can be said of $lookup
as a general principle, is that the intent of the "join" here is to work the other way around than shown here. So rather than keeping the "related ids" of the other documents within the "parent" document, the general principle that works best is where the "related documents" contain a reference to the "parent".
So $lookup
can be said to "work best" with a "relation design" that is the reverse of how something like mongoose .populate()
performs it's client side joins. By idendifying the "one" within each "many" instead, then you just pull in the related items without needing to $unwind
the array first.
You can use pure Python to do it:
import json
list = [1, 2, (3, 4)] # Note that the 3rd element is a tuple (3, 4)
json.dumps(list) # '[1, 2, [3, 4]]'
Based on the documentation you should be able to use auto
in combination with the preferred placement e.g. auto left
http://getbootstrap.com/javascript/#popovers: "When "auto" is specified, it will dynamically reorient the popover. For example, if placement is "auto left", the tooltip will display to the left when possible, otherwise it will display right."
I was trying to do the same thing and then realised that this functionality already existed.
SQLite has a printf
function which does exactly that:
SELECT printf('%s-%.2d-%.4d', col1, col2, col3) FROM mytable
There's no hard and fast rule. The documentation for a class should indicate whether subclasses should call the superclass method. Sometimes you want to completely replace superclass behaviour, and at other times augment it - i.e. call your own code before and/or after a superclass call.
Update: The same basic logic applies to any method call. Constructors sometimes need special consideration (as they often set up state which determines behaviour) and destructors because they parallel constructors (e.g. in the allocation of resources, e.g. database connections). But the same might apply, say, to the render()
method of a widget.
Further update: What's the OPP? Do you mean OOP? No - a subclass often needs to know something about the design of the superclass. Not the internal implementation details - but the basic contract that the superclass has with its clients (using classes). This does not violate OOP principles in any way. That's why protected
is a valid concept in OOP in general (though not, of course, in Python).
ES6: Using async/await
you can do below getMeta
function in sequence-like way and you can use it as follows (which is almost identical to code in your question (I add await
keyword and change variable end
to img
, and change var
to let
keyword). You need to run getMeta
by await
only from async
function (run).
function getMeta(url) {
return new Promise((resolve, reject) => {
let img = new Image();
img.onload = () => resolve(img);
img.onerror = () => reject();
img.src = url;
});
}
async function run() {
let img = await getMeta("http://shijitht.files.wordpress.com/2010/08/github.png");
let w = img.width;
let h = img.height;
size.innerText = `width=${w}px, height=${h}px`;
size.appendChild(img);
}
run();
_x000D_
<div id="size" />
_x000D_
You can also do the following;
string json = myJObject.ToString(Newtonsoft.Json.Formatting.None);
[HttpGet]
public RedirectResult Get()
{
return RedirectPermanent("https://www.google.com");
}
Having 2 elements with the same ID is not valid html according to the W3C specification.
When your CSS selector only has an ID selector (and is not used on a specific context), jQuery uses the native document.getElementById
method, which returns only the first element with that ID.
However, in the other two instances, jQuery relies on the Sizzle selector engine (or querySelectorAll
, if available), which apparently selects both elements. Results may vary on a per browser basis.
However, you should never have two elements on the same page with the same ID. If you need it for your CSS, use a class instead.
If you absolutely must select by duplicate ID, use an attribute selector:
$('[id="a"]');
Take a look at the fiddle: http://jsfiddle.net/P2j3f/2/
Note: if possible, you should qualify that selector with a tag selector, like this:
$('span[id="a"]');
I just build a pack to do this, hope you like it ;) https://www.npmjs.com/package/writelog
Define a converter:
public class RowIndexConverter : IValueConverter
{
public object Convert( object value, Type targetType,
object parameter, CultureInfo culture )
{
var row = (IDictionary<string, object>) value;
var key = (string) parameter;
return row.Keys.Contains( key ) ? row[ key ] : null;
}
public object ConvertBack( object value, Type targetType,
object parameter, CultureInfo culture )
{
throw new NotImplementedException( );
}
}
Bind to a custom definition of a Dictionary. There's lot of overrides that I've omitted, but the indexer is the important one, because it emits the property changed event when the value is changed. This is required for source to target binding.
public class BindableRow : INotifyPropertyChanged, IDictionary<string, object>
{
private Dictionary<string, object> _data = new Dictionary<string, object>( );
public object Dummy // Provides a dummy property for the column to bind to
{
get
{
return this;
}
set
{
var o = value;
}
}
public object this[ string index ]
{
get
{
return _data[ index ];
}
set
{
_data[ index ] = value;
InvokePropertyChanged( new PropertyChangedEventArgs( "Dummy" ) ); // Trigger update
}
}
}
In your .xaml file use this converter. First reference it:
<UserControl.Resources>
<ViewModelHelpers:RowIndexConverter x:Key="RowIndexConverter"/>
</UserControl.Resources>
Then, for instance, if your dictionary has an entry where the key is "Name", then to bind to it: use
<TextBlock Text="{Binding Dummy, Converter={StaticResource RowIndexConverter}, ConverterParameter=Name}">
I found this to be a more elegant solution, without flex:
.wrapper {
overflow: hidden;
}
.wrapper img {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
/* height: 100%; */ /* optional */
}
As a more general solution (but ASCII only!), to include any other separators between words (like commas and semicolons), I suggest:
String s = "I want to walk my dog, cat, and tarantula; maybe even my tortoise.";
String[] words = s.split("\\W+");
The regex means that the delimiters will be anything that is not a word [\W], in groups of at least one [+]. Because [+] is greedy, it will take for instance ';' and ' ' together as one delimiter.
Now it makes sense to do 2 ways in the view model. if you want to save the first as a saved instance: You can add state parameter in view model like this https://developer.android.com/topic/libraries/architecture/viewmodel-savedstate#java
or you can save variables or object in view model, in this case the view model will hold the life cycle until the activity is destroyed.
public class HelloAndroidViewModel extends ViewModel {
public Booelan firstInit = false;
public HelloAndroidViewModel() {
firstInit = false;
}
...
}
public class HelloAndroid extends Activity {
private TextView mTextView = null;
HelloAndroidViewModel viewModel = ViewModelProviders.of(this).get(HelloAndroidViewModel.class);
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTextView = new TextView(this);
//Because even if the state is deleted, the data in the viewmodel will be kept because the activity does not destroy
if(!viewModel.firstInit){
viewModel.firstInit = true
mTextView.setText("Welcome to HelloAndroid!");
}else{
mTextView.setText("Welcome back.");
}
setContentView(mTextView);
}
}
It works for me:
CREATE TABLE `users`(
`user_id` INT(10) NOT NULL AUTO_INCREMENT,
`username` VARCHAR(255) NOT NULL,
`password` VARCHAR(255) NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE = MyISAM;
If you're in Ubuntu, execute these commands to add your proxy.
sudo nano /etc/default/docker
And uncomment the lines that specifies
#export http_proxy = http://username:[email protected]:8050
And replace it with your appropriate proxy server and username.
Then restart Docker using:
service docker restart
Now you can run Docker commands behind proxy:
docker search ubuntu
A better solution is not to make your page dependable on zoom settings. If you set limits like the one you are proposing, you are limiting accessibility. If someone cannot read your text well, they just won't be able to change that. I would use proper CSS to make it look nice in any zoom.
If your really insist, take a look at this question on how to detect zoom level using JavaScript (nightmare!): How to detect page zoom level in all modern browsers?
Just a slight modification to @JohnnyHK answer
collection.find().sort({datefield: -1}, function(err, cursor){...});
In many use cases we wish to have latest records to be returned (like for latest updates / inserts).
Select
Count(Distinct user_id) As countUsers
, Count(site_id) As countVisits
, site_id As site
From cp_visits
Where ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)
Group By site_id
Add this class in .css class
.scrol {
font: bold 14px Arial;
border:1px solid black;
width:100% ;
color:#616D7E;
height:20px;
overflow:scroll;
overflow-y:scroll;
overflow-x:hidden;
}
and use the class in div. like here.
<div> <p class = "scrol" id = "title">-</p></div>
I have attached image , you see the out put of the above code
This issue can also occur when you pull code from git and not yet installed node modules "npm install".
The accepted answer does not show 0 in integer place on giving input like 0.299. It shows .3 in WPF UI. So my suggestion to use following string format
<TextBox Text="{Binding Value, StringFormat={}{0:#,0.0}}"
Simply put, linear regression is a regression algorithm, which outpus a possible continous and infinite value; logistic regression is considered as a binary classifier algorithm, which outputs the 'probability' of the input belonging to a label (0 or 1).
Today, with jQuery, I do this:
$("#foo").change(function(){
var foo = $("#foo option:selected").text();
});
\#foo
is the drop-down box id.
Read more.
origin is a name for remote git url. There can be many more remotes example below.
bangalore => bangalore.example.com:project.git boston => boston.example.com:project.git
as far as origin/master (example bangalore/master) goes, it is pointer to "master" commit on bangalore site . You see it in your clone.
It is possible that remote bangalore has advanced since you have done "fetch" or "pull"
Using create will cause one query per new item. If you want to reduce the number of INSERT queries, you'll need to use something else.
I've had some success using the Bulk Insert snippet, even though the snippet is quite old. Perhaps there are some changes required to get it working again.
Why not set stdout
directly to sys.stdout
? And if you need to output to a log as well, then you can simply override the write method of f.
import sys
import subprocess
class SuperFile(open.__class__):
def write(self, data):
sys.stdout.write(data)
super(SuperFile, self).write(data)
f = SuperFile("log.txt","w+")
process = subprocess.Popen(command, stdout=f, stderr=f)
If the pattern inside .gitignore
ends with a slash /
, it will only find a match with a directory.
In other words, bin/
will match a directory bin
and paths underneath it, but will not match a regular file or a symbolic link bin
.
If the pattern does not contain a slash, like in bin
Git treats it as a shell glob pattern (greedy). So best would be to use simple /bin
.
bin
would not be the best solution for this particular problem.
I've experimented the exact same error. My problem was that the SetUp method I had created was declared as static.
If using eclipse, one could get a good description by clicking above the error and then checking the Failure trace window, just below... That's how I found the real problem!
Yes. In the javascript code:
window.location.href = "http://new.website.com/that/you/want_to_go_to.html";
I had this same problem, using an old version of the route-me library. I "skipped" all the libraries, and the libraries inside of libraries (proj4), but I still had the same problem. Turns out that route-me and proj4 were installing public header files, even when the libraries were being skipped, which was messing it up in the same way! So I just went into the route-me and proj4 targets "Build Phases" tab, opened "Copy Headers", opened "Public", and dragged those headers from "Public" into "Project". Now they don't get installed in $(BUILD)/usr/local/include, and I'm able to make an ipa file from the archive!
I hope Apple fixes this horrible usability problem with XCode. It gives absolutely no indication of what's wrong, it just doesn't work. I hate dimmed out controls that don't tell you anything about why they're dimmed out. How about instead of ignoring clicks, the disabled controls could pop up a message telling you why the hell they're disabled when you click on them in frustration?
In my case (dealing with my assemblies loaded [as file] into Outlook):
typeof(OneOfMyTypes).Assembly.CodeBase
Note the use of CodeBase
(not Location
) on the Assembly
. Others have pointed out alternative methods of locating the assembly.
To answer the question posted in the comment above - try something like this:
unsigned short int x = 65529U;
short int y = (short int)x;
printf("%d\n", y);
or
unsigned short int x = 65529U;
short int y = 0;
memcpy(&y, &x, sizeof(short int);
printf("%d\n", y);
If you're using jQuery 2.1.4 or above, try this:
$("#" + this.d);
Or, you can define var before using it. It makes your code simpler.
var d = this.d
$("#" + d);
Your problem is comparable to the creation of a file object and opening the file. In fact there are a lot of classes where you have to perform two steps before you can actually use the object: create + Initialize (often called something similar to Open).
The advantage of this is that the constructor can be lightweight. If desired, you can change some properties before actually initializing the object. When all properties are set, the Initialize
/Open
function is called to prepare the object to be used. This Initialize
function can be async.
The disadvantage is that you have to trust the user of your class that he will call Initialize()
before he uses any other function of your class. In fact if you want to make your class full proof (fool proof?) you have to check in every function that the Initialize()
has been called.
The pattern to make this easier is to declare the constructor private and make a public static function that will construct the object and call Initialize()
before returning the constructed object. This way you'll know that everyone who has access to the object has used the Initialize
function.
The example shows a class that mimics your desired async constructor
public MyClass
{
public static async Task<MyClass> CreateAsync(...)
{
MyClass x = new MyClass();
await x.InitializeAsync(...)
return x;
}
// make sure no one but the Create function can call the constructor:
private MyClass(){}
private async Task InitializeAsync(...)
{
// do the async things you wanted to do in your async constructor
}
public async Task<int> OtherFunctionAsync(int a, int b)
{
return await ... // return something useful
}
Usage will be as follows:
public async Task<int> SomethingAsync()
{
// Create and initialize a MyClass object
MyClass myObject = await MyClass.CreateAsync(...);
// use the created object:
return await myObject.OtherFunctionAsync(4, 7);
}
Look into BufferedReader
. If that isn't general/high-level enough, I recommend reading the I/O tutorial.
Looks like im very late but for those of you who need to switch to new screen and clear back button stack here is a very simple solution.
startActivity(new Intent(this,your-new-screen.class));
finishAffinity();
The finishAffinity(); method clears back button stack.
I got this Error after re-creating a Repository on my Server (Codebeamer) - the User in Question lacked some permissions, after granting them, everything worked fine.
There is also another straight and more clear way
git commit -m "Title" -m "Description ..........";
Dependencies can be updated by using "Maven --> Update Project.." in Eclipse using m2e plugin, after pom.xml file modification.
I had this problem with an ordinary VB6 program. It turned out that I had omitted a class definition, not a user-defined type. Apparently VB saw something like "Thing.name" and assumed Thing was a UDT. Yes, it's a serious VB6 bug, but you could hardly expect Microsoft to support something they sold sixteen years ago. So what versions of the various products involved are you using? This is only interesting if it occurs with a product that MS supports.
Keep your own back stack: myBackStack
. As you Add
a fragment to the FragmentManager
, also add it to myBackStack
. In onBackStackChanged()
pop from myBackStack
when its length is greater than getBackStackEntryCount
.
I think that the object you received in your response payload isn't an array. Perhaps the array you want to iterate is contained into an attribute. You should check the structure of the received data...
You could try something like that:
getusers() {
this.http.get(`https://api.github.com/search/users?q=${this.input1.value}`)
.map(response => response.json().items) // <------
.subscribe(
data => this.users = data,
error => console.log(error)
);
}
Edit
Following the Github doc (developer.github.com/v3/search/#search-users), the format of the response is:
{
"total_count": 12,
"incomplete_results": false,
"items": [
{
"login": "mojombo",
"id": 1,
(...)
"type": "User",
"score": 105.47857
}
]
}
So the list of users is contained into the items
field and you should use this:
getusers() {
this.http.get(`https://api.github.com/search/users?q=${this.input1.value}`)
.map(response => response.json().items) // <------
.subscribe(
data => this.users = data,
error => console.log(error)
);
}
With Java 8, you could use a primitive stream:
if (IntStream.of(12, 16, 19).anyMatch(i -> i == x))
but this may have a slight overhead (or not), depending on the number of comparisons.
If you're trying to just count how many of your cells in a range are not blank try this:
=COUNTA(range)
Example: (assume that it starts from A1 downwards):
---------
Something
---------
Something
---------
---------
Something
---------
---------
Something
---------
=COUNTA(A1:A6)
returns 4
since there are two blank cells in there.
To avoid x !instance of Long
prob
Add
<property name="openjpa.Compatibility" value="StrictIdentityValues=false"/>
in your persistence.xml
My issue is resolved when I use the below code:
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn=DriverManager.getConnection("jdbc:oracle:thin:@IPAddress:1521/servicename","userName","Password");
Make sure HttpClient has access to the full client certificate (including the private key).
You are calling GetCert with a file "ClientCertificate.cer" which leads to the assumption that there is no private key contained - should rather be a pfx file within windows. It may be even better to access the certificate from the windows cert store and search it using the fingerprint.
Be careful when copying the fingerprint: There are some non-printable characters when viewing in cert management (copy the string over to notepad++ and check the length of the displayed string).
If you really want to prune your history of .gitignore
d files, first save .gitignore
outside the repo, e.g. as /tmp/.gitignore
, then run
git filter-branch --force --index-filter \
"git ls-files -i -X /tmp/.gitignore | xargs -r git rm --cached --ignore-unmatch -rf" \
--prune-empty --tag-name-filter cat -- --all
Notes:
git filter-branch --index-filter
runs in the .git
directory I think, i.e. if you want to use a relative path you have to prepend one more ../
first. And apparently you cannot use ../.gitignore
, the actual .gitignore
file, that yields a "fatal: cannot use ../.gitignore as an exclude file" for some reason (maybe during a git filter-branch --index-filter
the working directory is (considered) empty?)git ls-files -iX <(git show $(git hash-object -w .gitignore))
instead to avoid copying .gitignore
somewhere else, but that alone already returns an empty string (whereas cat <(git show $(git hash-object -w .gitignore))
indeed prints .gitignore
's contents as expected), so I cannot use <(git show $GITIGNORE_HASH)
in git filter-branch
....gitignore
-clean a specific branch, replace --all
in the last line with its name. The --tag-name-filter cat
might not work properly then, i.e. you'll probably not be able to directly transfer a single branch's tags properlyWell, Pavel was close, but there's even a more simple and elegant solution to initialize a sequential container from a c style array.
In your case:
w_ (array, std::end(array))
It's not possible right now, on Netbeans 7.0.1 . The GUI tool to create columns on a tables is very limited and does not exist a plugin that offer that feature.
I have Far.exe as the first item in the start menu.
Richtext in the clipboard ->
ctrl-escape,arrdown,enter,shift-f4,$,enter
shift-insert,ctrl-insert,alt-backspace,
f10,enter
-> plaintext in the clipboard
Pros: no mouse, just blind typing, ends exactly where i was before
Cons: ANSI encoding - international symbols are lost
Luckily, I do not have to do that too often :)
Please make use of the code below to display images inline:
<img style='vertical-align:middle;' src='somefolder/icon.gif'>
<div style='vertical-align:middle; display:inline;'>
Your text here
</div>
The 1
s are because everything is perfectly correlated with itself, and the NA
s are because there are NA
s in your variables.
You will have to specify how you want R to compute the correlation when there are missing values, because the default is to only compute a coefficient with complete information.
You can change this behavior with the use
argument to cor
, see ?cor
for details.
cvc-elt.1: Cannot find the declaration of element 'Root'. [7]
Your schemaLocation
attribute on the root element should be xsi:schemaLocation
, and you need to fix it to use the right namespace.
You should probably change the targetNamespace
of the schema and the xmlns
of the document to http://myNameSpace.com
(since namespaces are supposed to be valid URIs, which Test.Namespace
isn't, though urn:Test.Namespace
would be ok). Once you do that it should find the schema. The point is that all three of the schema's target namespace, the document's namespace, and the namespace for which you're giving the schema location must be the same.
(though it still won't validate as your <element2>
contains an <element3>
in the document where the schema expects item
)
There is a simple concise way, using regex flag (case insensitive {i}):
String s1 = "hello abc efg";
String s2 = "ABC";
s1.matches(".*(?i)"+s2+".*");
/*
* .* denotes every character except line break
* (?i) denotes case insensitivity flag enabled for s2 (String)
* */
No there isn't. If you watch the http traffic and dump the page source you can see that there is an API below the covers, but it's not published nor available for 3rd party apps.
Check this link: https://developers.google.com/gsuite/products for updates.
However, there is an unofficial Python API under active development: https://github.com/kiwiz/gkeepapi
In addition to the answers above.
I wrote following test.exe as console application
static void Main(string[] args) {
Console.WriteLine(
System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
Console.WriteLine(
System.Reflection.Assembly.GetEntryAssembly().Location);
Console.WriteLine(
System.Reflection.Assembly.GetExecutingAssembly().Location);
Console.WriteLine(
System.Reflection.Assembly.GetCallingAssembly().Location);
}
Then I compiled the project and renamed its output to the test2.exe file. The output lines were correct and the same.
But, if I start it in the Visual Studio, the result is:
d:\test2.vhost.exe
d:\test2.exe
d:\test2.exe
C:\Windows\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll
The ReSharper plug-in to the Visual Studio has underlined the
System.Diagnostics.Process.GetCurrentProcess().MainModule
as possible System.NullReferenceException. If you look into documentation of the MainModule you will find that this property can throw also NotSupportedException, PlatformNotSupportedException and InvalidOperationException.
The GetEntryAssembly method is also not 100% "safe". MSDN:
The GetEntryAssembly method can return null when a managed assembly has been loaded from an unmanaged application. For example, if an unmanaged application creates an instance of a COM component written in C#, a call to the GetEntryAssembly method from the C# component returns null, because the entry point for the process was unmanaged code rather than a managed assembly.
For my solutions, I prefer the Assembly.GetEntryAssembly().Location
.
More interest is if need to solve the problem for the virtualization. For example, we have a project, where we use a Xenocode Postbuild to link the .net code into one executable. This executable must be renamed. So all the methods above didn't work, because they only gets the information for the original assembly or inner process.
The only solution I found is
var location = System.Reflection.Assembly.GetEntryAssembly().Location;
var directory = System.IO.Path.GetDirectoryName(location);
var file = System.IO.Path.Combine(directory,
System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe");
HTML5 is supported on both Google (android) phones such as Galaxy S, and iPhone. iPhone however doesn't support Flash, which Google phones do support.
The syntax "select top (@var) ..." only works in SQL SERVER 2005+. For SQL 2000, you can do:
set rowcount @top
select * from sometable
set rowcount 0
Hope this helps
Oisin.
(edited to replace @@rowcount with rowcount - thanks augustlights)
You can't do this, which is by design. The Django framework authors intended a strict separation of presentation code from data logic. Filtering models is data logic, and outputting HTML is presentation logic.
So you have several options. The easiest is to do the filtering, then pass the result to render_to_response
. Or you could write a method in your model so that you can say {% for object in data.filtered_set %}
. Finally, you could write your own template tag, although in this specific case I would advise against that.
This works in my case. I hope you can extract meaning out of it.
//div[text()='building1' and @class='wrap']/ancestor::tr/td/div/div[@class='x-grid-row-checker']
This works for me on [{"id":"data"},{"id":"data"}]
function getObjects(obj, key, val)
{
var newObj = false;
$.each(obj, function()
{
var testObject = this;
$.each(testObject, function(k,v)
{
//alert(k);
if(val == v && k == key)
{
newObj = testObject;
}
});
});
return newObj;
}
The answers are OK if you only require those two fields, but for a more complex object, maybe this approach could be useful:
from x in db.Serials
group x by x.Serial_Number into g
orderby g.Key
select g.OrderByDescending(z => z.uid)
.FirstOrDefault()
... this will avoid the "select new"
Use the checked attribute.
<input type="radio" name="imgsel" value="" checked />
or
<input type="radio" name="imgsel" value="" checked="checked" />
Simple! Add at the end of dockerfile:
ENTRYPOINT service mysql start && /bin/bash
Error 127
means one of two things:
$PATH
, or in this case, the relative path is correct -- remember that the current working directory for a random terminal might not be the same for the IDE you're using. it might be better to just use an absolute path instead.file -L
on /bin/sh
(to get your default/native format) and on the compiler itself (to see what format it is).if the problem is (2), then you can solve it in a few diff ways:
In the "Developer Tab" go to "Visual Basic" and create a Module. Copy paste the following. Remember changing the code, depending on what you want. Then run the module.
Sub sbDelete_Rows_IF_Cell_Contains_String_Text_Value()
Dim lRow As Long
Dim iCntr As Long
lRow = 390
For iCntr = lRow To 1 Step -1
If Cells(iCntr, 5).Value = "none" Then
Rows(iCntr).Delete
End If
Next
End Sub
lRow : Put the number of the rows that the current file has.
The number "5" in the "If" is for the fifth (E) column
You could refer to column alias but you need to define it using CROSS/OUTER APPLY
:
SELECT s.logcount, s.logUserID, s.maxlogtm, c.daysdiff
FROM statslogsummary s
CROSS APPLY (SELECT DATEDIFF(day, s.maxlogtm, GETDATE()) AS daysdiff) c
WHERE c.daysdiff > 120;
Pros:
WHERE/GROUP BY/ORDER BY
I'm going to assume you want to build a the regex dynamically to contain other words than part1 and part2, and that you want order not to matter. If so you can use something like this:
((^|, )(part1|part2|part3))+$
Positive matches:
part1
part2, part1
part1, part2, part3
Negative matches:
part1, //with and without trailing spaces.
part3, part2,
otherpart1
If you want to treat a null
as false, then I would say that the most succinct way to do that is to use the null coalesce operator (??
), as you describe:
if (nullableBool ?? false) { ... }
I use the IntelliJ one, because I'm mostly concerned with IntelliJ flagging things that might produce a NPE. I agree that it's frustrating not having a standard annotation in the JDK. There's talk of adding it, it might make it into Java 7. In which case there will be one more to choose from!
You could try exe4j. This is effectively what we use through its cousin install4j.
What worked for me was to create a new report from scratch.
This done and the new report working, I will compare the 2 .rdl files in Visual Studio. These are in XML format and I am hoping a quick WindDiff or something would reveal what the issue was.
An initial look shows there are 700 lines of code or a bit more difference between both files, with the larger of the 2 being the faulty file. A cursory look at the TablixHeader tags didn't reveal anything obvious.
But in my case it was a corrupted .rdl file. This was originally copied from a working report so in the process of removing what wasn't re-used, this could have corrupted it. However, other reports where this same process was done, the headers could repeat when the correct settings were made in Properties.
Hope this helps. If you've got a complex report, this isn't the quick fix but it works.
Perhaps comparing known good XML files to faulty ones on your end would make a good forum post. I'll be trying that on my end.
You are replacing the starting tag and then putting that back in innerHTML
, so the code will be invalid. Make all the replacements before you put the code back in the element:
var html = strMessage1.innerHTML;
html = html.replace( /aaaaaa./g,'<a href=\"http://www.google.com/');
html = html.replace( /.bbbbbb/g,'/world\">Helloworld</a>');
strMessage1.innerHTML = html;
I encountered with this issue spending couple of hours, however solved it in different ways. You can see, I have just created an assets folder outside application folder. Finally I linked my style sheet in the page header section. Folder structure are below images.
Before action this you should include url helper file either in your controller class method/__constructor files or by in autoload.php file. Also change $config['base_url'] = 'http://yoursiteurl';
in the following file application/config/config.php
If you include it in controller class method/__constructor then it look like
public function __construct()
{
$this->load->helper('url');
}
or If you load in autoload file then it would looks like
$autoload['helper'] = array('url');
Finally, add your stylesheet file. You can link a style sheet by different ways, include it in your inside section
-><link rel="stylesheet" href="<?php echo base_url();?>assets/css/style.css" type="text/css" />
-> or
<?php
$main = array(
'href' => 'assets/css/style.css',
'rel' => 'stylesheet',
'type' => 'text/css',
'title' => 'main stylesheet',
'media' => 'all',
'index_page' => true
);
echo link_tag($main); ?>
-> or
finally I get more reliable code cleaner concept. Just create a config file, named styles.php in you application/config/styles.php folder. Then add some links in styles.php file looks like below
<?php
$config['style'] = array(
'main' => array(
'href' => 'assets/css/style.css',
'rel' => 'stylesheet',
'type' => 'text/css',
'title' => 'main stylesheet',
'media' => 'all',
'index_page' => true
)
);
?>
call/add this config to your controller class method looks like below
$this->config->load('styles');
$data['style'] = $this->config->config['style'];
Pass this data in your header template looks like below.
$this->load->view('templates/header', $data);
And finally add or link your css file looks like below.
<?php echo link_tag($style['main']); ?>
Since FFT is symmetric over it's centre, half the values are just enough.
import numpy as np
import matplotlib.pyplot as plt
fs = 30.0
t = np.arange(0,10,1/fs)
x = np.cos(2*np.pi*10*t)
xF = np.fft.fft(x)
N = len(xF)
xF = xF[0:N/2]
fr = np.linspace(0,fs/2,N/2)
plt.ion()
plt.plot(fr,abs(xF)**2)
kubectl exec -it POD_NAME -c CONTAINER_NAME bash - then kill 1
Assuming the container is run as root which is not recommended.
In my case when I changed the application config, I had to reboot the container which was used in a sidecar pattern, I would kill the PID for the spring boot application which is owned by the docker user.
Can I ask why this is important?
I know that this is not a direct answer to your question, but the fact that you are trying to preserve the object ID of a string might indicate that you should look again at what you are trying to do.
You might find, for instance, that relying on the object ID of a string will lead to bugs that are quite hard to track down.
I solved this problem by doing the "subselect" like it:
string newQuery = "select * from (" + query + ") as temp";
When do it on mysql, all collunms properties (unique, non-null ...) will be cleared.
I have modified AsyncTask
class to handle creation of progressDialog
at the same context .I think following code will be more reusable.
(it can be called from any activity just pass context,target File,dialog message)
public static class DownloadTask extends AsyncTask<String, Integer, String> {
private ProgressDialog mPDialog;
private Context mContext;
private PowerManager.WakeLock mWakeLock;
private File mTargetFile;
//Constructor parameters :
// @context (current Activity)
// @targetFile (File object to write,it will be overwritten if exist)
// @dialogMessage (message of the ProgresDialog)
public DownloadTask(Context context,File targetFile,String dialogMessage) {
this.mContext = context;
this.mTargetFile = targetFile;
mPDialog = new ProgressDialog(context);
mPDialog.setMessage(dialogMessage);
mPDialog.setIndeterminate(true);
mPDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mPDialog.setCancelable(true);
// reference to instance to use inside listener
final DownloadTask me = this;
mPDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
me.cancel(true);
}
});
Log.i("DownloadTask","Constructor done");
}
@Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
Log.i("DownloadTask","Response " + connection.getResponseCode());
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream(mTargetFile,false);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
Log.i("DownloadTask","Cancelled");
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
mPDialog.show();
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
mPDialog.setIndeterminate(false);
mPDialog.setMax(100);
mPDialog.setProgress(progress[0]);
}
@Override
protected void onPostExecute(String result) {
Log.i("DownloadTask", "Work Done! PostExecute");
mWakeLock.release();
mPDialog.dismiss();
if (result != null)
Toast.makeText(mContext,"Download error: "+result, Toast.LENGTH_LONG).show();
else
Toast.makeText(mContext,"File Downloaded", Toast.LENGTH_SHORT).show();
}
}
This becomes a one-liner if you download File Checksum Integrity Verifier (FCIV) from Microsoft.
I downloaded FCIV from here: Availability and description of the File Checksum Integrity Verifier utility
Run the following command. I had ten files to check.
Get-ChildItem WTAM*.tar | % {.\fciv $_.Name}
DO it like
$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$yourPHPVAR%'");
Do not forget the %
at the end
Session is used for maintaining a dialogue between server and user. It is more secure because it is stored on the server, we cannot easily access it. It embeds cookies on the user computer. It stores unlimited data.
Cookies are stored on the local computer. Basically, it maintains user identification, meaning it tracks visitors record. It is less secure than session. It stores limited amount of data, and is maintained for a limited time.
Try the following:
document.getElementById("successAndErrorMessages").innerHTML="someContent";
msdn link for detail : innerHTML Property
Is it possible you have a race condition where another thread or process is adding files to the directory:
The sequence would be:
Deleter process A:
If someone else adds a file between 1 & 2, then maybe 2 would throw the exception listed?
You cannot store arrays in a vector
or any other container. The type of the elements to be stored in a container (called the container's value type) must be both copy constructible and assignable. Arrays are neither.
You can, however, use an array
class template, like the one provided by Boost, TR1, and C++0x:
std::vector<std::array<double, 4> >
(You'll want to replace std::array
with std::tr1::array
to use the template included in C++ TR1, or boost::array
to use the template from the Boost libraries. Alternatively, you can write your own; it's quite straightforward.)
First of all, all the reasons are subjective. It's more like a matter of taste rather than a reason.
Personally, I find heredoc quite useless and use it occasionally, most of the time when I need to get some HTML into a variable and don't want to bother with output buffering, to form an HTML email message for example.
Formatting doesn't fit general indentation rules, but I don't think it's a big deal.
//some code at it's proper level
$this->body = <<<HERE
heredoc text sticks to the left border
but it seems OK to me.
HERE;
$this->title = "Feedback";
//and so on
As for the examples in the accepted answer, it is merely cheating.
String examples, in fact, being more concise if one won't cheat on them
$sql = "SELECT * FROM $tablename
WHERE id in [$order_ids_list]
AND product_name = 'widgets'";
$x = 'The point of the "argument" was to illustrate the use of here documents';
This was a straightforward solution for me:
from datetime import timedelta, datetime
today = datetime.today().strftime("%Y-%m-%d")
tomorrow = datetime.today() + timedelta(1)
Expanding on zoul's answer:
If you want to setup Vim to use specific settings when editing a particular filetype, you'll want to use autocommands:
autocmd Filetype css setlocal tabstop=4
This will make it so that tabs are displayed as 4 spaces. Setting expandtab
will cause Vim to actually insert spaces (the number of them being controlled by tabstop
) when you press tab; you might want to use softtabstop
to make backspace work properly (that is, reduce indentation when that's what would happen should tabs be used, rather than always delete one char at a time).
To make a fully educated decision as to how to set things up, you'll need to read Vim docs on tabstop
, shiftwidth
, softtabstop
and expandtab
. The most interesting bit is found under expandtab
(:help 'expandtab
):
There are four main ways to use tabs in Vim:
Always keep 'tabstop' at 8, set 'softtabstop' and 'shiftwidth' to 4 (or 3 or whatever you prefer) and use 'noexpandtab'. Then Vim will use a mix of tabs and spaces, but typing and will behave like a tab appears every 4 (or 3) characters.
Set 'tabstop' and 'shiftwidth' to whatever you prefer and use 'expandtab'. This way you will always insert spaces. The formatting will never be messed up when 'tabstop' is changed.
Set 'tabstop' and 'shiftwidth' to whatever you prefer and use a |modeline| to set these values when editing the file again. Only works when using Vim to edit the file.
Always set 'tabstop' and 'shiftwidth' to the same value, and 'noexpandtab'. This should then work (for initial indents only) for any tabstop setting that people use. It might be nice to have tabs after the first non-blank inserted as spaces if you do this though. Otherwise aligned comments will be wrong when 'tabstop' is changed.
It's worth mentioning that in some cases
File myFolder = new File("directory");
doesn't point to the root elements. For example when you place your application on C:
drive (C:\myApp.jar
) then myFolder
points to (windows)
C:\Users\USERNAME\directory
instead of
C:\Directory
I viewed the Eclipse ADT documentation and found out the way to get around this issue. I was able to Update My SDK Tool to 22.0.4 (Latest Version).
Solution is: First Update ADT to 22.0.4(Latest version) and then Update SDK Tool to 22.0.4(Latest Version)
The above link says,
ADT 22.0.4 is designed for use with SDK Tools r22.0.4. If you haven't already installed SDK Tools r22.0.4 into your SDK, use the Android SDK Manager to do so
What I had to do was update my ADT to 22.0.4 (Latest Version) and then I was able to update SDK tool to 22.0.4. I thought only SDK Tool has been updated not ADT, so I was updating the SDK Tool with Older ADT Version (22.0.1).
How to Update your ADT to Latest Version
Help
Install New Software
---> Add
Add Repository
write the Name: ADT
(or whatever you want)https://dl-ssl.google.com/android/eclipse/
Developer Tools
and NDK Plugins
Developer Tool
onlyNext
Finish
Worked here too:
Sub test544()
Dim chromePath As String
chromePath = """C:\Program Files\Google\Chrome\Application\chrome.exe"""
Shell (chromePath & " -url http:google.ca")
End Sub
I use Goto
For x= 1 to 20
If something then goto continue
skip this code
Continue:
Next x
SELECT last_number
FROM all_sequences
WHERE sequence_owner = '<sequence owner>'
AND sequence_name = '<sequence_name>';
You can get a variety of sequence metadata from user_sequences
, all_sequences
and dba_sequences
.
These views work across sessions.
EDIT:
If the sequence is in your default schema then:
SELECT last_number
FROM user_sequences
WHERE sequence_name = '<sequence_name>';
If you want all the metadata then:
SELECT *
FROM user_sequences
WHERE sequence_name = '<sequence_name>';
Hope it helps...
EDIT2:
A long winded way of doing it more reliably if your cache size is not 1 would be:
SELECT increment_by I
FROM user_sequences
WHERE sequence_name = 'SEQ';
I
-------
1
SELECT seq.nextval S
FROM dual;
S
-------
1234
-- Set the sequence to decrement by
-- the same as its original increment
ALTER SEQUENCE seq
INCREMENT BY -1;
Sequence altered.
SELECT seq.nextval S
FROM dual;
S
-------
1233
-- Reset the sequence to its original increment
ALTER SEQUENCE seq
INCREMENT BY 1;
Sequence altered.
Just beware that if others are using the sequence during this time - they (or you) may get
ORA-08004: sequence SEQ.NEXTVAL goes below the sequences MINVALUE and cannot be instantiated
Also, you might want to set the cache to NOCACHE
prior to the resetting and then back to its original value afterwards to make sure you've not cached a lot of values.
This might be useful for someone.
Numpy's histogram function returns the edges of each bin, rather than the value of the bin. This makes sense for floating-point numbers, which can lie within an interval, but may not be the desired result when dealing with discrete values or integers (0, 1, 2, etc). In particular, the length of bins returned from np.histogram is not equal to the length of the counts / density.
To get around this, I used np.digitize to quantize the input, and count the fraction of counts for each bin. You could easily edit to get the integer number of counts.
def compute_PMF(data):
import numpy as np
from collections import Counter
_, bins = np.histogram(data, bins='auto', range=(data.min(), data.max()), density=False)
h = Counter(np.digitize(data,bins) - 1)
weights = np.asarray(list(h.values()))
weights = weights / weights.sum()
values = np.asarray(list(h.keys()))
return weights, values
####
Refs:
[1] https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html
[2] https://docs.scipy.org/doc/numpy/reference/generated/numpy.digitize.html
You could basically use html tags in your string resource like:
<resource>
<string name="styled_welcome_message">We are <b><i>so</i></b> glad to see you.</string>
</resources>
And use Html.fromHtml or use spannable, check the link I posted.
Old similar question: Is it possible to have multiple styles inside a TextView?
git
isn't a centralized scm like svn
so you have two options:
It may be annoying to implement for many different platforms (GitHub, GitLab, BitBucket, SourceForge, Launchpad, Gogs, ...) but fetching data is pretty slow (we talk about seconds) - no solution is perfect.
An example with fetching into a temporary directory:
git clone https://github.com/rust-lang/rust.git -b master --depth 3 --bare --filter=blob:none -q .
git log -n 3 --no-decorate --format=oneline
Alternatively:
git init --bare -q
git remote add -t master origin https://github.com/rust-lang/rust.git
git fetch --depth 3 --filter=blob:none -q
git log -n 3 --no-decorate --format=oneline origin/master
Both are optimized for performance by restricting to exactly 3 commits of one branch into a minimal local copy without file contents and preventing console outputs. Though opening a connection and calculating deltas during fetch takes some time.
An example with GitHub:
GET https://api.github.com/repos/rust-lang/rust/commits?sha=master&per_page=3
An example with GitLab:
GET https://gitlab.com/api/v4/projects/inkscape%2Finkscape/repository/commits?ref_name=master&per_page=3
Both are really fast but have different interfaces (like every platform).
Disclaimer: Rust and Inkscape were chosen because of their size and safety to stay, no advertisement
If you are using SASS, you can just install it via npm
npm install font-awesome --save
and import it in your /src/styles.scss
with:
$fa-font-path: "../node_modules/font-awesome/fonts";
@import "../node_modules/font-awesome/scss/font-awesome.scss";
Tip: Whenever possible, avoid to mess with angular-cli
infrastructure. ;)
Here's another way to do this:
- name: my command
command: echo stuff
when: "'groupname' not in group_names"
group_names
is a magic variable as documented here: https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#accessing-information-about-other-hosts-with-magic-variables :
group_names is a list (array) of all the groups the current host is in.
EDIT: I hadn't noticed you needed the position as well. You can't use IndexOf
directly on a value of an array type, because it's implemented explicitly. However, you can use:
IList<string> arrayAsList = (IList<string>) stringArray;
int index = arrayAsList.IndexOf(value);
if (index != -1)
{
...
}
(This is similar to calling Array.IndexOf
as per Darin's answer - just an alternative approach. It's not clear to me why IList<T>.IndexOf
is implemented explicitly in arrays, but never mind...)
After installing git-extentions (http://gitextensions.github.io/) you can run .sh file from the command prompt. (No ./script.sh required, just run it like a bat/cmd file) Or you can run them in a "full" bash environment by using the MinGW Git bash shell.
I am not a great fan of Cygwin (yes I am sure it's really powerful), so running bash scripts on windows without having to install it perfect for me.
You could try using an array of bool
:
bool i[8] = {0,0,1,1,0,1,0,1}
I would recommend that you start by pulling your task apart into it's component parts.
Once you do that, it should be fairly trivial to use one of the libraries you link to (which most certainly will handle task #1). Then iterate through the returned values, and cast/convert each String value to the value you want.
If the question is how to convert strings to different objects, it's going to depend on what format you are starting with, and what format you want to wind up with.
DateFormat.parse(), for example, will parse dates from strings. See SimpleDateFormat for quickly constructing a DateFormat for a certain string representation. Integer.parseInt() will prase integers from strings.
Currency, you'll have to decide how you want to capture it. If you want to just capture as a float, then Float.parseFloat() will do the trick (just use String.replace() to remove all $ and commas before you parse it). Or you can parse into a BigDecimal (so you don't have rounding problems). There may be a better class for currency handling (I don't do much of that, so am not familiar with that area of the JDK).
Below query can work :
SELECT user_id, value, date , row_number() OVER (PARTITION BY user_id ORDER BY date desc) AS rn
FROM table_name
WHERE rn= 1
See ?merge
:
the name "row.names" or the number 0 specifies the row names.
Example:
R> de <- merge(d, e, by=0, all=TRUE) # merge by row names (by=0 or by="row.names")
R> de[is.na(de)] <- 0 # replace NA values
R> de
Row.names a b c d e f g h i j k l m n o p q r s
1 1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2 2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 0 0 0 0 0 0 0 0 0
3 3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0 21 22 23 24 25 26 27 28 29
t
1 20
2 0
3 30
The onkeypress event works for all the keys except ALT, CTRL, SHIFT, ESC in all browsers where as onkeydown event works for all keys. Means onkeydown event captures all the keys.
I'd say the switch is the way to go, it is both faster and better practise.
There are various links such as (http://www.blackwasp.co.uk/SpeedTestIfElseSwitch.aspx) that show benchmark tests comparing the two.
I fixed it by added the jquery.slim.min.js after the jquery.min.js, as the Solution Sequence.
Problem Sequence
<script src="./vendor/jquery/jquery.min.js"></script>
<script src="./vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
Solution Sequence
<script src="./vendor/jquery/jquery.min.js"></script>
<script src="./vendor/jquery/jquery.slim.min.js"></script>
<script src="./vendor/jquery-easing/jquery.easing.min.js"></script>
This note relates to basarat's answer, not the original question.
I had an odd issue in my own project where the compiler was giving an error roughly equivalent to "cannot convert string to Color" using the equivalent of this code:
var colorId = myOtherObject.colorId; // value "Green";
var color: Color = <Color>Color[colorId]; // TSC error here: Cannot convert string to Color.
I found that the compiler type inferencing was getting confused and it thought that colorId
was an enum value and not an ID. To fix the problem I had to cast the ID as a string:
var colorId = <string>myOtherObject.colorId; // Force string value here
var color: Color = Color[colorId]; // Fixes lookup here.
I'm not sure what caused the issue but I'll leave this note here in case anyone runs into the same problem I did.
You can use the instanceof
operator for this. From MDN:
The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.
If you don't know what prototypes and prototype chains are I highly recommend looking it up. Also here is a JS (TS works similar in this respect) example which might clarify the concept:
class Animal {_x000D_
name;_x000D_
_x000D_
constructor(name) {_x000D_
this.name = name;_x000D_
}_x000D_
}_x000D_
_x000D_
const animal = new Animal('fluffy');_x000D_
_x000D_
// true because Animal in on the prototype chain of animal_x000D_
console.log(animal instanceof Animal); // true_x000D_
// Proof that Animal is on the prototype chain_x000D_
console.log(Object.getPrototypeOf(animal) === Animal.prototype); // true_x000D_
_x000D_
// true because Object in on the prototype chain of animal_x000D_
console.log(animal instanceof Object); _x000D_
// Proof that Object is on the prototype chain_x000D_
console.log(Object.getPrototypeOf(Animal.prototype) === Object.prototype); // true_x000D_
_x000D_
console.log(animal instanceof Function); // false, Function not on prototype chain_x000D_
_x000D_
_x000D_
The prototype chain in this example is:
animal > Animal.prototype > Object.prototype
To replace multiples columns convert to numpy array using .values
:
df.loc[df.A==0, ['B', 'C']] = df.loc[df.A==0, ['B', 'C']].values / 2
The problem is you defined myList
from main.py
, but subfile.py
needs to use it. Here is a clean way to solve this problem: move all globals to a file, I call this file settings.py
. This file is responsible for defining globals and initializing them:
# settings.py
def init():
global myList
myList = []
Next, your subfile
can import globals:
# subfile.py
import settings
def stuff():
settings.myList.append('hey')
Note that subfile
does not call init()
— that task belongs to main.py
:
# main.py
import settings
import subfile
settings.init() # Call only once
subfile.stuff() # Do stuff with global var
print settings.myList[0] # Check the result
This way, you achieve your objective while avoid initializing global variables more than once.
You could use the pickle
module in the standard library.
Here's an elementary application of it to your example:
import pickle
class Company(object):
def __init__(self, name, value):
self.name = name
self.value = value
with open('company_data.pkl', 'wb') as output:
company1 = Company('banana', 40)
pickle.dump(company1, output, pickle.HIGHEST_PROTOCOL)
company2 = Company('spam', 42)
pickle.dump(company2, output, pickle.HIGHEST_PROTOCOL)
del company1
del company2
with open('company_data.pkl', 'rb') as input:
company1 = pickle.load(input)
print(company1.name) # -> banana
print(company1.value) # -> 40
company2 = pickle.load(input)
print(company2.name) # -> spam
print(company2.value) # -> 42
You could also define your own simple utility like the following which opens a file and writes a single object to it:
def save_object(obj, filename):
with open(filename, 'wb') as output: # Overwrites any existing file.
pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)
# sample usage
save_object(company1, 'company1.pkl')
Since this is such a popular answer, I'd like touch on a few slightly advanced usage topics.
cPickle
(or _pickle
) vs pickle
It's almost always preferable to actually use the cPickle
module rather than pickle
because the former is written in C and is much faster. There are some subtle differences between them, but in most situations they're equivalent and the C version will provide greatly superior performance. Switching to it couldn't be easier, just change the import
statement to this:
import cPickle as pickle
In Python 3, cPickle
was renamed _pickle
, but doing this is no longer necessary since the pickle
module now does it automatically—see What difference between pickle and _pickle in python 3?.
The rundown is you could use something like the following to ensure that your code will always use the C version when it's available in both Python 2 and 3:
try:
import cPickle as pickle
except ModuleNotFoundError:
import pickle
pickle
can read and write files in several different, Python-specific, formats, called protocols as described in the documentation, "Protocol version 0" is ASCII and therefore "human-readable". Versions > 0 are binary and the highest one available depends on what version of Python is being used. The default also depends on Python version. In Python 2 the default was Protocol version 0
, but in Python 3.8.1, it's Protocol version 4
. In Python 3.x the module had a pickle.DEFAULT_PROTOCOL
added to it, but that doesn't exist in Python 2.
Fortunately there's shorthand for writing pickle.HIGHEST_PROTOCOL
in every call (assuming that's what you want, and you usually do), just use the literal number -1
— similar to referencing the last element of a sequence via a negative index.
So, instead of writing:
pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)
You can just write:
pickle.dump(obj, output, -1)
Either way, you'd only have specify the protocol once if you created a Pickler
object for use in multiple pickle operations:
pickler = pickle.Pickler(output, -1)
pickler.dump(obj1)
pickler.dump(obj2)
etc...
Note: If you're in an environment running different versions of Python, then you'll probably want to explicitly use (i.e. hardcode) a specific protocol number that all of them can read (later versions can generally read files produced by earlier ones).
While a pickle file can contain any number of pickled objects, as shown in the above samples, when there's an unknown number of them, it's often easier to store them all in some sort of variably-sized container, like a list
, tuple
, or dict
and write them all to the file in a single call:
tech_companies = [
Company('Apple', 114.18), Company('Google', 908.60), Company('Microsoft', 69.18)
]
save_object(tech_companies, 'tech_companies.pkl')
and restore the list and everything in it later with:
with open('tech_companies.pkl', 'rb') as input:
tech_companies = pickle.load(input)
The major advantage is you don't need to know how many object instances are saved in order to load them back later (although doing so without that information is possible, it requires some slightly specialized code). See the answers to the related question Saving and loading multiple objects in pickle file? for details on different ways to do this. Personally I like @Lutz Prechelt's answer the best. Here's it adapted to the examples here:
class Company:
def __init__(self, name, value):
self.name = name
self.value = value
def pickled_items(filename):
""" Unpickle a file of pickled data. """
with open(filename, "rb") as f:
while True:
try:
yield pickle.load(f)
except EOFError:
break
print('Companies in pickle file:')
for company in pickled_items('company_data.pkl'):
print(' name: {}, value: {}'.format(company.name, company.value))
I know this has been answered for quite some time but not solve my problem. I am using DictReader and StringIO for my csv reading due to some other complications. I was able to solve problem more simply by replacing delimiters explicitly:
with urllib.request.urlopen(q) as response:
raw_data = response.read()
encoding = response.info().get_content_charset('utf8')
data = raw_data.decode(encoding)
if '\r\n' not in data:
# proably a windows delimited thing...try to update it
data = data.replace('\r', '\r\n')
Might not be reasonable for enormous CSV files, but worked well for my use case.
I ran across this error on a Beaglebone Black using the standard Angstrom distribution. It is currently running Python 2.7.3, but does not include distutils. The solution for me was to install distutils. (It required su privileges.)
su
opkg install python-distutils
After that installation, the previously erroring command ran fine.
python setup.py build
This is an issue in the Chrome family and has been there forever.
A bug has been raised https://bugs.chromium.org/p/chromium/issues/detail?id=904208
It can be shown here: https://codepen.io/anon/pen/Jedvwj as soon as you add a border to anything button-like (say role="button" has been added to a tag for example) Chrome messes up and sets the focus state when you click with your mouse. You should see that outline only on keyboard tab-press.
I highly recommend using this fix: https://github.com/wicg/focus-visible.
Just do the following
npm install --save focus-visible
Add the script to your html:
<script src="/node_modules/focus-visible/dist/focus-visible.min.js"></script>
or import into your main entry file if using webpack or something similar:
import 'focus-visible/dist/focus-visible.min';
then put this in your css file:
// hide the focus indicator if element receives focus via mouse, but show on keyboard focus (on tab).
.js-focus-visible :focus:not(.focus-visible) {
outline: none;
}
// Define a strong focus indicator for keyboard focus.
// If you skip this then the browser's default focus indicator will display instead
// ideally use outline property for those users using windows high contrast mode
.js-focus-visible .focus-visible {
outline: magenta auto 5px;
}
You can just set:
button:focus {outline:0;}
but if you have a large number of users, you're disadvantaging those who cannot use mice or those who just want to use their keyboard for speed.
In order to navigate to a different drive just use
cd /E/Study/Codes
It will solve your problem.
Method names which are same as the class name are called constructors. Constructors do not have a return type. So correct as:
private Flow()
{
X = x;
Y = y;
}
Or rename the function as:
private void DoFlow()
{
X = x;
Y = y;
}
Though the whole code does not make any sense to me.
You are not setting a classpath that includes your compiled class! java
can't find any classes if you don't tell it where to look.
java -cp [compiler outpur dir] HelloWorld
Incidentally you do not need to set CLASSPATH the way you have done.
To clear all SharedPreferences centrally from any class:
public static SharedPreferences.Editor getEditor(Context context) {
return getPreferences(context).edit();
}
And then from any class: (commit returns a Boolean where you can check whether your Preferences cleared or not)
Navigation.getEditor(this).clear().commit();
Or you can use apply; it returns void
Navigation.getEditor(this).clear().apply();
In a nutshell :
List/Array Sort() :
OrderBy/ThenBy() :
x => x.Id
). All keys are extracted first before sorting. This might result in better performance than using Sort() and a custom comparer. Sources: MDSN, reference source and dotnet/coreclr repository (GitHub).
Some of the statements listed above are based on current .NET framework implementation (4.7.2). It might change in the future.
The total of 7 numbers in an array can be created as:
import java.util.*;
class Sum
{
public static void main(String arg[])
{
int a[]=new int[7];
int total=0;
Scanner n=new Scanner(System.in);
System.out.println("Enter the no. for total");
for(int i=0;i<=6;i++)
{
a[i]=n.nextInt();
total=total+a[i];
}
System.out.println("The total is :"+total);
}
}
For an element in a table row, use JQuery to get the row above the one you want, and simply scroll to that row instead.
Suppose I have multiple rows in a table, some of which should be reviewed by and admin. Each row requiring review has both and up and a down arrow to take you to the previous or next item for review.
Here's a complete example that should just run if you make a new HTML document in notepad and save it. There's extra code to detect the top and bottom of our items for review so we don't throw any errors.
<html>
<head>
<title>Scrolling Into View</title>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<style>
div.scroll { height: 6em; width: 20em; overflow: auto; }
thead th { position: sticky; top: -1px; background: #fff; }
.up, .down { cursor: pointer; }
.up:hover, .down:hover { color: blue; text-decoration:underline; }
</style>
</head>
<body>
<div class='scroll'>
<table border='1'>
<thead>
<tr>
<th>Review</th>
<th>Data</th>
</tr>
</thead>
<tbody>
<tr id='row_1'>
<th></th>
<td>Row 1 (OK)</td>
</tr>
<tr id='row_2'>
<th></th>
<td>Row 2 (OK)</td>
</tr>
<tr id='row_3'>
<th id='jump_1'><span class='up'>UP</span> <span class='down'>DN</span></th>
<td>Row 3 (REVIEW)</td>
</tr>
<tr id='row_4'>
<th></th>
<td>Row 4 (OK)</td>
</tr>
<tr id='row_5'>
<th id='jump_2'><span class='up'>UP</span> <span class='down'>DN</span></th>
<td>Row 5 (REVIEW)</td>
</tr>
<tr id='row_6'>
<th></th>
<td>Row 6 (OK)</td>
</tr>
<tr id='row_7'>
<th></th>
<td>Row 7 (OK)</td>
</tr>
<tr id='row_8'>
<th id='jump_3'><span class='up'>UP</span> <span class='down'>DN</span></th>
<td>Row 8 (REVIEW)</td>
</tr>
<tr id='row_9'>
<th></th>
<td>Row 9 (OK)</td>
</tr>
<tr id='row_10'>
<th></th>
<td>Row 10 (OK)</td>
</tr>
</tbody>
</table>
</div>
<script>
$(document).ready( function() {
$('.up').on('click', function() {
var id = parseInt($(this).parent().attr('id').split('_')[1]);
if (id>1) {
var row_id = $('#jump_' + (id - 1)).parent().attr('id').split('_')[1];
document.getElementById('row_' + (row_id-1)).scrollIntoView({behavior: 'smooth', block: 'start'});
} else {
alert('At first');
}
});
$('.down').on('click', function() {
var id = parseInt($(this).parent().attr('id').split('_')[1]);
if ($('#jump_' + (id + 1)).length) {
var row_id = $('#jump_' + (id + 1)).parent().attr('id').split('_')[1];
document.getElementById('row_' + (row_id-1)).scrollIntoView({behavior: 'smooth', block: 'start'});
} else {
alert('At last');
}
});
});
</script>
</body>
</html>
This should work
import { Router } from "@angular/router"
export class YourClass{
constructor(private router: Router) { }
YourFunction() {
this.router.navigate(['/path']);
}
}
You can use attributes from the System.ComponentModel.DataAnnotations
namespace to set validation rules. Refer Model Validation - By Mike Wasson for details.
Also refer video ASP.NET Web API, Part 5: Custom Validation - Jon Galloway
Other References
You can't access the method fxn since it's not static. Static methods can only access other static methods directly. If you want to use fxn in your main method you need to:
...
Two two = new Two();
x = two.fxn(x)
...
That is, make a Two-Object and call the method on that object.
...or make the fxn method static.
(Copy/paste of an answer I provided elsewhere)
Falling through switch
-case
s can be achieved by having no code in a case
(see case 0
), or using the special goto case
(see case 1
) or goto default
(see case 2
) forms:
switch (/*...*/) {
case 0: // shares the exact same code as case 1
case 1:
// do something
goto case 2;
case 2:
// do something else
goto default;
default:
// do something entirely different
break;
}
Another option:
if( ![string]::IsNullOrEmpty($user_sam) -and ![string]::IsNullOrEmpty($user_case) )
{
...
}
print
outputs each argument, followed by $,
, to $stdout
, followed by $\
. It is equivalent to args.join($,) + $\
puts
sets both $,
and $\
to "\n" and then does the same thing as print
. The key difference being that each argument is a new line with puts
.
You can require 'english'
to access those global variables with user-friendly names.
Maven is packaged for Fedora since mid 2014, so it is now pretty easy. Just type
sudo dnf install maven
Now test the installation, just run maven in a random directory
mvn
And it will fail, because you did not specify a goal, e.g. mvn package
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.102 s
[INFO] Finished at: 2017-11-14T13:45:00+01:00
[INFO] Final Memory: 8M/176M
[INFO] ------------------------------------------------------------------------
[ERROR] No goals have been specified for this build
[...]
I just had this issue as well on a server I own, and the root cause was APC. I commented out the "apc.so" extension in the php.ini file, reloaded Apache, and the sites came right back up.
How about just using the built-in types like this:
config = {
"mysql": {
"user": "root",
"pass": "secret",
"tables": {
"users": "tb_users"
}
# etc
}
}
You'd access the values as follows:
config["mysql"]["tables"]["users"]
If you are willing to sacrifice the potential to compute expressions inside your config tree, you could use YAML and end up with a more readable config file like this:
mysql:
- user: root
- pass: secret
- tables:
- users: tb_users
and use a library like PyYAML to conventiently parse and access the config file
stdlib float modf (float x, float *ipart) splits into two parts, check if return value (fractional part) == 0.
Checking out more than one repo at a time in a single workspace is not possible with Jenkins + Git Plugin.
As a workaround, you can either have multiple upstream jobs which checkout a single repo each and then copy to your final project workspace (Problematic on a number of levels), or you can set up a shell scripting step which checks out each needed repo to the job workspace at build time.
Previously the Multiple SCM plugin could help with this issue but it is now deprecated. From the Multiple SCM plugin page: "Users should migrate to https://wiki.jenkins-ci.org/display/JENKINS/Pipeline+Plugin . Pipeline offers a better way of checking out of multiple SCMs, and is supported by the Jenkins core development team."
I think the best solution would be to do a subquery and then join that to the table. The sub query would return the primary key of the table. Here is an example:
select *
from (
SELECT row_number() over(partition by link order by day, month) row_id
, *
FROM posted
WHERE ad='$key'
) x
where x.row_id = 1
What this does is the row_number function puts a numerical sequence partitioned by each distinct link that results in the query.
By taking only those row_numbers that = 1, then you only return 1 row for each link.
The way you change what link gets marked "1" is through the order-by clause in the row_number function.
Hope this helps.
If think you are looking for something like this.
public static char toUnsigned(byte b) {
return (char) (b >= 0 ? b : 256 + b);
}
You need to store all of the extra rows in the files in your dictionary, not just one of them:
dict1 = {row[0]: row[1:] for row in r}
...
dict2 = {row[0]: row[1:] for row in r}
Then, since the values in the dictionaries are lists, you need to just concatenate the lists together:
w.writerows([[key] + dict1.get(key, []) + dict2.get(key, []) for key in keys])
var answer = Math.floor(x)
I sincerely hope this will help future searchers when googling for this common question.