git commit --amend
and press Enter.git push --force example-branch
command to force push over the old commit.Source: https://help.github.com/articles/changing-a-commit-message/
This article has an excellent explanation as to how to go about various scenarios (where a commit has been done as well as the push OR just a commit, before the push):
http://christoph.ruegg.name/blog/git-howto-revert-a-commit-already-pushed-to-a-remote-reposit.html
From the article, the easiest command I saw to revert a previous commit by its commit id, was:
git revert dd61ab32
As mentioned in "Polling must die: triggering Jenkins builds from a git hook", you can notify Jenkins of a new commit:
With the latest Git plugin 1.1.14 (that I just release now), you can now do this more >easily by simply executing the following command:
curl http://yourserver/jenkins/git/notifyCommit?url=<URL of the Git repository>
This will scan all the jobs that’s configured to check out the specified URL, and if they are also configured with polling, it’ll immediately trigger the polling (and if that finds a change worth a build, a build will be triggered in turn.)
This allows a script to remain the same when jobs come and go in Jenkins.
Or if you have multiple repositories under a single repository host application (such as Gitosis), you can share a single post-receive hook script with all the repositories. Finally, this URL doesn’t require authentication even for secured Jenkins, because the server doesn’t directly use anything that the client is sending. It runs polling to verify that there is a change, before it actually starts a build.
As mentioned here, make sure to use the right address for your Jenkins server:
since we're running Jenkins as standalone Webserver on port 8080 the URL should have been without the
/jenkins
, like this:http://jenkins:8080/git/notifyCommit?url=git@gitserver:tools/common.git
To reinforce that last point, ptha adds in the comments:
It may be obvious, but I had issues with:
curl http://yourserver/jenkins/git/notifyCommit?url=<URL of the Git repository>.
The url parameter should match exactly what you have in Repository URL of your Jenkins job.
When copying examples I left out the protocol, in our casessh://
, and it didn't work.
You can also use a simple post-receive hook like in "Push based builds using Jenkins and GIT"
#!/bin/bash
/usr/bin/curl --user USERNAME:PASS -s \
http://jenkinsci/job/PROJECTNAME/build?token=1qaz2wsx
Configure your Jenkins job to be able to “Trigger builds remotely” and use an authentication token (
1qaz2wsx
in this example).
However, this is a project-specific script, and the author mentions a way to generalize it.
The first solution is easier as it doesn't depend on authentication or a specific project.
I want to check in change set whether at least one java file is there the build should start.
Suppose the developers changed only XML files or property files, then the build should not start.
Basically, your build script can:
git notes
) on the first callHEAD
of your branch candidate for build and the commit referenced by the git notes
'build' (git show refs/notes/build
): git diff --name-only SHA_build HEAD
.git notes
'build
' to HEAD
.May 2016: cwhsu points out in the comments the following possible url:
you could just use
curl --user USER:PWD http://JENKINS_SERVER/job/JOB_NAME/build?token=YOUR_TOKEN
if you set trigger config in your item
June 2016, polaretto points out in the comments:
I wanted to add that with just a little of shell scripting you can avoid manual url configuration, especially if you have many repositories under a common directory.
For example I used these parameter expansions to get the repo namerepository=${PWD%/hooks}; repository=${repository##*/}
and then use it like:
curl $JENKINS_URL/git/notifyCommit?url=$GIT_URL/$repository
If you are at a certain branch mybranch
, just go ahead and git checkout commit_hash
. Then you can return to your branch by git checkout mybranch
. I had the same game bisecting a bug today :) Also, you should know about git bisect.
You can use git cherry-pick for this. 'cherry-pick' will apply a commit onto the branch your on now.
then do
git rebase --hard <SHA1 of A>
then apply the D and E commits.
git cherry-pick <SHA1 of D>
git cherry-pick <SHA1 of E>
This will skip out the B and C commit. Having said that it might be impossible to apply the D commit to the branch without B, so YMMV.
Looks like you missed -m for commit command
Just say :
git commit --amend -m "New commit message"
and then
git push --force
On Linux you can use gitk for this.
It can be installed using "sudo apt-get install git-gui gitk". It can be used to see commits of a specific file by "gitk <Filename>".
i would see a very simple way
git reset --hard HEAD <YOUR COMMIT ID>
and then reset remote branch
git push origin -f
I use this little bash script to look at a blame history.
First parameter: file to look at
Subsequent parameters: Passed to git blame
#!/bin/bash
f=$1
shift
{ git log --pretty=format:%H -- "$f"; echo; } | {
while read hash; do
echo "--- $hash"
git blame $@ $hash -- "$f" | sed 's/^/ /'
done
}
You may supply blame-parameters like -L 70,+10 but it is better to use the regex-search of git blame because line-numbers typically "change" over time.
Essentially you have to have admin rights (directly or indirectly) to the repository to do this. You can either configure the repository to allow all users to do this, or you can modify the log message directly on the server.
See this part of the Subversion FAQ (emphasis mine):
Log messages are kept in the repository as properties attached to each revision. By default, the log message property (svn:log) cannot be edited once it is committed. That is because changes to revision properties (of which svn:log is one) cause the property's previous value to be permanently discarded, and Subversion tries to prevent you from doing this accidentally. However, there are a couple of ways to get Subversion to change a revision property.
The first way is for the repository administrator to enable revision property modifications. This is done by creating a hook called "pre-revprop-change" (see this section in the Subversion book for more details about how to do this). The "pre-revprop-change" hook has access to the old log message before it is changed, so it can preserve it in some way (for example, by sending an email). Once revision property modifications are enabled, you can change a revision's log message by passing the --revprop switch to svn propedit or svn propset, like either one of these:
$svn propedit -r N --revprop svn:log URL $svn propset -r N --revprop svn:log "new log message" URL
where N is the revision number whose log message you wish to change, and URL is the location of the repository. If you run this command from within a working copy, you can leave off the URL.
The second way of changing a log message is to use svnadmin setlog. This must be done by referring to the repository's location on the filesystem. You cannot modify a remote repository using this command.
$ svnadmin setlog REPOS_PATH -r N FILE
where REPOS_PATH is the repository location, N is the revision number whose log message you wish to change, and FILE is a file containing the new log message. If the "pre-revprop-change" hook is not in place (or you want to bypass the hook script for some reason), you can also use the --bypass-hooks option. However, if you decide to use this option, be very careful. You may be bypassing such things as email notifications of the change, or backup systems that keep track of revision properties.
None of the above solutions worked for me when I got the src-refspec error.
My workflow:
I fixed the error by simply making a new branch, and pushing again.
(The weird thing was, I couldn't simply just rename the branch - it gave me fatal: Branch rename failed
.)
Most of these answers circulate around removing a file from the "staging area" pre-commit, but I often find myself looking here after I've already committed and I want to remove some sensitive information from the commit I just made.
An easy to remember trick for all of you git commit --amend
folks out there like me is that you can:
git add .
to add the deletion to the "staging area"git commit --amend
to remove the file from the previous commit.You will notice in the commit message that the unwanted file is now missing. Hooray! (Commit SHA
will have changed, so be careful if you already pushed your changes to the remote.)
If you just want to throw away the changes and revert to the last commit (the one you wanted to share):
git reset --hard HEAD~
You may want to check to make absolutely sure you want this (git log
), because you'll loose all changes.
A safer alternative is to run
git reset --soft HEAD~ # reset to the last commit
git stash # stash all the changes in the working tree
git push # push changes
git stash pop # get your changes back
Use a changeset. You can add as many files as you like to the changeset, all at once, or over several commands; and then commit them all in one go.
Cherry-pick works best compared to all other methods while pushing a specific commit.
The way to do that is:
Create a new branch -
git branch <new-branch>
Update your new-branch with your origin branch -
git fetch
git rebase
These actions will make sure that you exactly have the same stuff as your origin has.
Cherry-pick the sha id
that you want to do push -
git cherry-pick <sha id of the commit>
You can get the sha id
by running
git log
Push it to your origin -
git push
Run gitk
to see that everything looks the same way you wanted.
git add
adds files to the Git index, which is a staging area for objects prepared to be commited.git commit
commits the files in the index to the repository, git commit -a
is a shortcut to add all the modified tracked files to the index first.git push
sends all the pending changes to the remote repository to which your branch is mapped (eg. on GitHub).In order to understand Git you would need to invest more effort than just glancing over the documentation, but it's definitely worth it. Just don't try to map Git commands directly to Subversion, as most of them don't have a direct counterpart.
I fixed it, I'm not exactly sure what I did. I tried simply pushing and pulling using:
git pull <remote> dev
instead of
git pull <remote> master:dev
Hope this helps out someone if they are having the same issue.
I doubt it but maybe running svn cleanup on your working directory will help.
git commit -C HEAD --amend
will do what you want. The -C
option takes the metadata from another commit.
// on your branch that holds the commit you want to pass
$ git log
// copy the commit hash found
$ git checkout [branch that will copy the commit]
$ git reset --hard [hash of the commit you want to copy from the other branch]
// remove the [brackets]
Other more useful commands here with explanation: Git Guide
You can revert all your files under your working directory and index by typing following this command
git reset --hard <SHAsum of your commit>
You can also type
git reset --hard HEAD #your current head point
or
git reset --hard HEAD^ #your previous head point
Hope it helps
git checkout -b NEW_BRANCH_NAME COMMIT_ID
This will create a new branch called 'NEW_BRANCH_NAME' and check it out.
("check out" means "to switch to the branch")
git branch NEW_BRANCH_NAME COMMIT_ID
This just creates the new branch without checking it out.
in the comments many people seem to prefer doing this in two steps. here's how to do so in two steps:
git checkout COMMIT_ID
# you are now in the "detached head" state
git checkout -b NEW_BRANCH_NAME
Building on theosp's answer, I wrote a script called git-cdc
(for change date commit) that I put in my PATH
.
The name is important: git-xxx
anywhere in your PATH
allows you to type:
git xxx
# here
git cdc ...
That script is in bash, even on Windows (since Git will be calling it from its msys environment)
#!/bin/bash
# commit
# date YYYY-mm-dd HH:MM:SS
commit="$1" datecal="$2"
temp_branch="temp-rebasing-branch"
current_branch="$(git rev-parse --abbrev-ref HEAD)"
date_timestamp=$(date -d "$datecal" +%s)
date_r=$(date -R -d "$datecal")
if [[ -z "$commit" ]]; then
exit 0
fi
git checkout -b "$temp_branch" "$commit"
GIT_COMMITTER_DATE="$date_timestamp" GIT_AUTHOR_DATE="$date_timestamp" git commit --amend --no-edit --date "$date_r"
git checkout "$current_branch"
git rebase --autostash --committer-date-is-author-date "$commit" --onto "$temp_branch"
git branch -d "$temp_branch"
With that, you can type:
git cdc @~ "2014-07-04 20:32:45"
That would reset author/commit date of the commit before HEAD (@~
) to the specified date.
git cdc @~ "2 days ago"
That would reset author/commit date of the commit before HEAD (@~
) to the same hour, but 2 days ago.
Ilya Semenov mentions in the comments:
For OS X you may also install GNU
coreutils
(brew install coreutils
), add it toPATH
(PATH="/usr/local/opt/coreutils/libexec/gnubin:$PATH"
) and then use "2 days ago
" syntax.
I found the simplest solution:
git commit -am'save'
That's all,you will work around git commit message stuff.
you can even save that commend to a bash or other stuff to make it more simple.
Our team members always write those messages,but almost no one will see those message again.
Commit message is a time-kill stuff at least in our team,so we ignore it.
Simply doing the vim "save and quit" command :wq
should do the trick.
In order to have Git open it in another editor, you need to change the Git core.editor
setting to a command which runs the editor you want.
git config --global core.editor "command to start sublime text 2"
I had this problem even after setting the config properly. git config
My scenario was issuing git command through supervisor (in Linux). On further debugging, supervisor was not reading the git config from home folder. Hence, I had to set the environment HOME variable in the supervisor config so that it can locate the git config correctly. It's strange that supervisor was not able to locate the git config just from the username configured in supervisor's config (/etc/supervisor/conf.d).
Ideally your .gitignore
should prevent the untracked ( and ignored )files from being shown in status, added using git add
etc. So I would ask you to correct your .gitignore
You can do git add -u
so that it will stage the modified and deleted files.
You can also do git commit -a
to commit only the modified and deleted files.
Note that if you have Git of version before 2.0 and used git add .
, then you would need to use git add -u .
(See "Difference of “git add -A
” and “git add .
”").
None of those worked for me, so I had three commits to revert (the last three commits), so I did:
git revert HEAD
git revert HEAD~2
git revert HEAD~4
git rebase -i HEAD~3 # pick, squash, squash
Worked like a charm :)
Might not solve all the problems in the original question, but since this seems to be the de facto post on how mercurial can amend to previous commit, I'll add my 2 cents worth of information.
If you are like me, and only wish to modify the previous commit message (fix a typo etc) without adding any files, this will work
hg commit -X 'glob:**' --amend
Without any include or exclude patterns hg commit
will by default include all files in working directory. Applying pattern -X 'glob:**'
will exclude all possible files, allowing only to modify the commit message.
Functionally it is same as git commit --amend
when there are no files in index/stage.
If you want to merge changes in SubBranch to MainBranch
git checkout MainBranch
git merge SubBranch
Maybe can use git reflog
to get two commit before amend and after amend.
Then use git diff before_commit_id after_commit_id > d.diff
to get diff between before amend and after amend.
Next use git checkout before_commit_id
to back to before commit
And last use git apply d.diff
to apply the real change you did.
That solves my problem.
If it is VIM for Windows, you can do the following:
:wq
Enter or ZZ
.Note that in VIM there are often several ways to do one thing. Here there is a slight difference though. :wq
Enter always writes the current file before closing it, while ZZ
, :x
Enter, :xi
Enter, :xit
Enter, :exi
Enter and :exit
Enter only write it if the document is modified.
All these synonyms just have different numbers of keypresses.
Use the git add
command, followed by a list of space-separated filenames. Include paths if in other directories, e.g. directory-name/file-name
.
git add file-1 file-2 file-3
Any uncomitted transaction will leave the server locked and other queries won't execute on the server. You either need to rollback the transaction or commit it. Closing out of SSMS will also terminate the transaction which will allow other queries to execute.
git checkout my_other_branch
git add my_file my_other_file
git commit -m
And provide your commit message.
If you are in the folder which contains the file
git commit -m 'my notes' ./name_of_file.ext
Format
A U Thor <[email protected]>
simply mean that you should specify
FirstName MiddleName LastName <[email protected]>
Looks like middle and last names are optional (maybe the part before email doesn't have a strict format at all). Try, for example, this:
git commit --author="John <[email protected]>" -m "some fix"
As the docs say:
--author=<author>
Override the commit author. Specify an explicit author using the standard
A U Thor <[email protected]> format. Otherwise <author> is assumed to
be a pattern and is used to search for an existing commit by that author
(i.e. rev-list --all -i --author=<author>); the commit author is then copied
from the first such commit found.
if you don't use this format, git treats provided string as a pattern and tries to find matching name among the authors of other commits.
Answer above is missing an example which might not be obvious (it wasn't to me).
Url could be broken down into parts
https://github.com/liufa/Tuplinator/commit/f36e3c5b3aba23a6c9cf7c01e7485028a23c3811
\_____/\________/ \_______________________________________/
| | |
Account name | Hash of revision
Project name
Hash can be found here (you can click it and will get the url from browser).
Hope this saves you some time.
In mechanical terms a COMMIT makes a transaction. That is, a transaction is all the activity (one or more DML statements) which occurs between two COMMIT statements (or ROLLBACK).
In Oracle a DDL statement is a transaction in its own right simply because an implicit COMMIT is issued before the statement is executed and again afterwards. TRUNCATE is a DDL command so it doesn't need an explicit commit because calling it executes an implicit commit.
From a system design perspective a transaction is a business unit of work. It might consist of a single DML statement or several of them. It doesn't matter: only full transactions require COMMIT. It literally does not make sense to issue a COMMIT unless or until we have completed a whole business unit of work.
This is a key concept. COMMITs don't just release locks. In Oracle they also release latches, such as the Interested Transaction List. This has an impact because of Oracle's read consistency model. Exceptions such as ORA-01555: SNAPSHOT TOO OLD
or ORA-01002: FETCH OUT OF SEQUENCE
occur because of inappropriate commits. Consequently, it is crucial for our transactions to hang onto locks for as long as they need them.
Look into re-indexing tables in your database.
You can first find out the fragmentation level - and if it's above 10% or so you could benefit from re-indexing. If it's very high it's likely this is creating a significant performance bottle neck.
This should be done regularly.
You are using both ternary operator
and if
condition, use any one.
By ternary operator:
.map(id => {
return this.props.schema.collectionName.length < 0 ?
<Expandable>
<ObjectDisplay
key={id}
parentDocumentId={id}
schema={schema[this.props.schema.collectionName]}
value={this.props.collection.documents[id]}
/>
</Expandable>
:
<h1>hejsan</h1>
}
By if condition:
.map(id => {
if(this.props.schema.collectionName.length < 0)
return <Expandable>
<ObjectDisplay
key={id}
parentDocumentId={id}
schema={schema[this.props.schema.collectionName]}
value={this.props.collection.documents[id]}
/>
</Expandable>
return <h1>hejsan</h1>
}
sudo apt-get update
sudo apt purge python2.7-minimal
First I executed:
sudo chown -R $(whoami):admin /usr/local
Then:
cd $(brew --prefix) && git fetch origin && git reset --hard origin/master
If your onclick function returns false the default browser behaviour is cancelled. As such:
<a href='http://www.google.com' onclick='return check()'>check</a>
<script type='text/javascript'>
function check()
{
return false;
}
</script>
Either way, whether google does it or not isn't of much importance. It's cleaner to bind your onclick functions within javascript - this way you separate your HTML from other code.
Well,
Just worked it out. While having both installations we have two ORACLE_HOME directories and both have SQAORA32.dll files. While looking up for ORACLE_HOMe my app was getting confused..I just removed the Client oracle home entry as oracle client is by default present in oracle DB Now its working...Thanks!!
I never understand the concept of Unit Test but now I know what it's the objective.
A Unit Test is not a complete test. So, it's not a replacement for QA and manual test. The concept of TDD in this aspect is wrong since you can't test everything, including private methods but also, methods that use resources (especially resources that we don't have control). TDD is basing all its quality is something that it could not be achieved.
A Unit test is more a pivot test You mark some arbitrary pivot and the result of pivot should stay the same.
You can use this:
addedDate = datetime.now().replace(microsecond=0)
Better way till now:
If you give display:inline-block; to inner divs then child elements of inner divs will also get this property and disturb alignment of inner divs.
Better way is to use two different classes for inner divs with width, margin and float.
Best way till now:
Use flexbox.
I was getting this issue because i was generating my EDMX from an existing database (designed by somebody else, and i use the term 'designed' loosely here).
Turns out the table had no keys whatsoever. EF was generating the model with many multiple keys. I had to go add a primary key to the db table in SQL and then updated my model in VS.
That fixed it for me.
One can also use a test ApplicationContextInitializer to initialize a system property:
public class TestApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext>
{
@Override
public void initialize(ConfigurableApplicationContext applicationContext)
{
System.setProperty("myproperty", "value");
}
}
and then configure it on the test class in addition to the Spring context config file locations:
@ContextConfiguration(initializers = TestApplicationContextInitializer.class, locations = "classpath:whereever/context.xml", ...)
@RunWith(SpringJUnit4ClassRunner.class)
public class SomeTest
{
...
}
This way code duplication can be avoided if a certain system property should be set for all the unit tests.
That's of course only a matter of personal preference, but I'd write this function using yield return:
public IEnumerable<Friend> FindFriends()
{
//Many thanks to Rex-M for his help with this one.
//http://stackoverflow.com/users/67/rex-m
if (userExists)
{
foreach(var user in doc.Descendants("user"))
{
yield return new Friend
{
ID = user.Element("id").Value,
Name = user.Element("name").Value,
URL = user.Element("url").Value,
Photo = user.Element("photo").Value
}
}
}
}
For me the case was completely different. I had created a studio64.exe.vmoptions file in C:\Users\YourUserName\.AndroidStudio3.4\config. In that folder, I had a typo of extra spaces. Due to that I was getting the same error.
I replaced the studio64.exe.vmoptions with the following code.
# custom Android Studio VM options, see https://developer.android.com/studio/intro/studio-config.html
-server
-Xms1G
-Xmx8G
# I have 8GB RAM so it is 8G. Replace it with your RAM size.
-XX:MaxPermSize=1G
-XX:ReservedCodeCacheSize=512m
-XX:+UseCompressedOops
-XX:+UseConcMarkSweepGC
-XX:SoftRefLRUPolicyMSPerMB=50
-da
-Djna.nosys=true
-Djna.boot.library.path=
-Djna.debug_load=true
-Djna.debug_load.jna=true
-Dsun.io.useCanonCaches=false
-Djava.net.preferIPv4Stack=true
-XX:+HeapDumpOnOutOfMemoryError
-Didea.paths.selector=AndroidStudio2.1
-Didea.platform.prefix=AndroidStudio
I wonder why there is no example of stand alone jar project.
In eclipse, we just check "Is Library" box in project setting dialog.
In Android studio, I followed this steps and got a jar file.
Create a project.
open file in the left project menu.(app/build.gradle): Gradle Scripts > build.gradle(Module: XXX)
change one line: apply plugin: 'com.android.application'
-> 'apply plugin: com.android.library'
remove applicationId in the file: applicationId "com.mycompany.testproject"
build project: Build > Rebuild Project
then you can get aar file: app > build > outputs > aar folder
change aar
file extension name into zip
unzip, and you can see classes.jar
in the folder.
rename and use it!
Anyway, I don't know why google makes jar creation so troublesome in android studio.
onDestroyed()
is wrong name for
onDestroy()
Did you make a mistake only in this question or in your code too?
All this might not help say when you use rails remote form button to simulate click to. I tried to port nice event simulation from prototype here: my snippets. Just did it and it works for me.
Google Goggles is the perfect application for doing both OCR and translation.
And the good news is that Google Goggles to Become App Platform.
Until then, you can use IQ Engines.
Get at number:
window.getComputedStyle( *Element* , null).getPropertyValue( *CSS* );
Example:
window.getComputedStyle( document.body ,null).getPropertyValue('background-color');
window.getComputedStyle( document.body ,null).getPropertyValue('width');
~ document.body.clientWidth
For Groovy script in the Jenkinsfile using the $BUILD_NUMBER it works.
This code explains the use of the ~tilda character, which was the most confusing thing to me. Once I understood this, it makes things much easier to understand:
@ECHO off
SET "PATH=%~dp0;%PATH%"
ECHO %PATH%
ECHO.
CALL :testargs "these are days" "when the brave endure"
GOTO :pauseit
:testargs
SET ARGS=%~1;%~2;%1;%2
ECHO %ARGS%
ECHO.
exit /B 0
:pauseit
pause
in Swift 5
For those who don't want to use colored background to beat the selected state
Simply you can beat the problem by using #Selector & if statement to change the UIButton colors for each state individually easily
For Example:
override func viewDidLoad() {
super.viewDidLoad()
self.myButtonOutlet.backgroundColor = UIColor.white //to reset the button color to its original color ( optionally )
}
@IBOutlet weak var myButtonOutlet: UIButton!{
didSet{ // Button selector and image here
self.myButtonOutlet.setImage(UIImage(systemName: ""), for: UIControl.State.normal)
self.myButtonOutlet.setImage(UIImage(systemName: "checkmark"), for: UIControl.State.selected)
self.myButtonOutlet.addTarget(self, action: #selector(tappedButton), for: UIControl.Event.touchUpInside)
}
}
@objc func tappedButton() { // Colors selection is here
if self.myButtonOutlet.isSelected == true {
self.myButtonOutlet.isSelected = false
self.myButtonOutlet.backgroundColor = UIColor.white
} else {
self.myButtonOutlet.isSelected = true
self.myButtonOutlet.backgroundColor = UIColor.black
self.myButtonOutlet.tintColor00 = UIColor.white
}
}
The simplest way to get the html
element natively is:
document.documentElement
Here's the reference: https://developer.mozilla.org/en-US/docs/Web/API/Document.documentElement.
UPDATE: To then grab the html
element as a string you would do:
document.documentElement.outerHTML
This also happens when you attempt to create a file with the same name as a directory:
import os
conflict = 'conflict'
# Create a directory with a given name
try:
os.makedirs(conflict)
except OSError:
if not os.path.isdir(conflict):
raise
# Attempt to create a file with the same name
file = open(conflict, 'w+')
Result:
IOError: [Errno 13] Permission denied: 'conflict'
This will clean the caches used to store bundle dependency resolution and eclipse extension registry data. Using this option will force eclipse to reinitialize these caches.
eclipse -clean
df.to_sql(name = "owner", con= db_connection, schema = 'aws', if_exists='replace', index = >True, index_label='id')
Just add this in the .htaccess file:
DirectoryIndex index.php
RewriteEngine on
RewriteCond $1 !^(index\.php|images|css|js|robots\.txt|favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php?/$1 [L,QSA]
I encountered the same problem. When the folder /worker
is mounted to the container - all of it's content will be syncronized (so the node_modules folder will disappear if you don't have it locally.)
Due to incompatible npm packages based on OS, I could not just install the modules locally - then launch the container, so..
My solution to this, was to wrap the source in a src
folder, then link node_modules
into that folder, using this index.js file. So, the index.js
file is now the starting point of my application.
When I run the container, I mounted the /app/src
folder to my local src
folder.
So the container folder looks something like this:
/app
/node_modules
/src
/node_modules -> ../node_modules
/app.js
/index.js
It is ugly, but it works..
The other issue here lies under Code Signing Identity under the Build Settings. Be sure that it contains the Code Signing Identity: "iOS Developer" as opposed to "Don't Code Sign." This will allow you to deploy it to your iOS device. Especially, if you have downloaded a GitHub example or something to this effect.
You might be interested in Apache Bench tool which is basically used to do simple load testing.
example :
ab -n 500 -c 20 http://www.example.com/
n = total number of request, c = number of concurrent request
Why Pandas ? Have you tried Standard Python ?
The use of standard library python. Pandas is subject to frequent updates, even with the recent release of the stable version.
Using the standard python library your code will always run.
One way of doing it is to have an idea of the way you want your data to be stored , and which questions you want to solve regarding the data. Then draw a schema of how you can organise your data (think tables) that will help you query the data, not necessarily normalisation.
You can make good use of :
Ram and HDD is becoming cheaper and cheaper with time and standard python 3 is widely available and stable.
The fondamental question you are trying to solve is "how to query large sets of data ?". The hdfs architecture is more or less what I am describing here (data modelling with data being stored on disk).
Let's say you have 1000 petabytes of data, there no way you will be able to store it in Dask or Pandas, your best chances here is to store it on disk and process it with generators.
I made an application based on Mike Hadlow application: AsmSpy.
My app is a WPF app with GUI and can be download from my home webserver: AsmSpyPlus.exe.
Code is available at: GitHub
MySQL only listens to localhost, if we want to enable the remote access to it, then we need to made some changes in my.cnf file:
sudo nano /etc/mysql/my.cnf
We need to comment out the bind-address and skip-external-locking lines:
#bind-address = 127.0.0.1
# skip-external-locking
After making these changes, we need to restart the mysql service:
sudo service mysql restart
When you want to fetch max value of a date column from dataframe, just the value without object type or Row object information, you can refer to below code.
table = "mytable"
max_date = df.select(max('date_col')).first()[0]
2020-06-26
instead of Row(max(reference_week)=datetime.date(2020, 6, 26))
There is no uninstaller. Therefore, you need to:
Delete the directory containing Jenkins (or, if you're deploying the war -- remove the war from your container).
Remove ~/.jenkins.
Remove you startup scripts.
I faced this problem while trying to extend an existing class from GitHub. I'm gonna try to explain myself, first writing the class as I though it should be, and then the class as it is now.
What I though
namespace mycompany\CutreApi;
use mycompany\CutreApi\ClassOfVendor;
class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
public function whatever(): ClassOfVendor
{
return new ClassOfVendor();
}
}
What I've finally done
namespace mycompany\CutreApi;
use \vendor\AwesomeApi\ClassOfVendor;
class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
public function whatever(): ClassOfVendor
{
return new \mycompany\CutreApi\ClassOfVendor();
}
}
So seems that this errror raises also when you're using a method that return a namespaced class, and you try to return the same class but with other namespace. Fortunately I have found this solution, but I do not fully understand the benefit of this feature in php 7.2, for me it is normal to rewrite existing class methods as you need them, including the redefinition of input parameters and / or even behavior of the method.
One downside of the previous aproach, is that IDE's could not recognise the new methods implemented in \mycompany\CutreApi\ClassOfVendor(). So, for now, I will go with this implementation.
Currently done
namespace mycompany\CutreApi;
use mycompany\CutreApi\ClassOfVendor;
class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
public function getWhatever(): ClassOfVendor
{
return new ClassOfVendor();
}
}
So, instead of trying to use "whatever" method, I wrote a new one called "getWhatever". In fact both of them are doing the same, just returning a class, but with diferents namespaces as I've described before.
Hope this can help someone.
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT ) {
//Right arrow key code
} else if (e.getKeyCode() == KeyEvent.VK_LEFT ) {
//Left arrow key code
} else if (e.getKeyCode() == KeyEvent.VK_UP ) {
//Up arrow key code
} else if (e.getKeyCode() == KeyEvent.VK_DOWN ) {
//Down arrow key code
}
repaint();
}
The KeyEvent codes are all a part of the API: http://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html
If you have this problem when using an instaled version, when using setup.py
, make sure your module is included inside packages
setup(name='Your program',
version='0.7.0',
description='Your desccription',
packages=['foo', 'foo.bar'], # add `foo.bar` here
For me, align="center"
was enough to center FOO
vertically:
<v-row align="center">
<v-col>FOO</v-col>
</row>
One liner error raising can be done with assert statements if that's what you want to do. This will help you write statically fixable code and check errors early.
assert type(A) is type(""), "requires a string"
I've found a temporary solution that will at least let me process this job. I wrote a short AutoIt script that waits for the "Update Links" window to appear, then clicks the "Don't Update" button. Code is as follows:
while 1
if winexists("Microsoft Excel","This workbook contains links to other data sources.") Then
controlclick("Microsoft Excel","This workbook contains links to other data sources.",2)
EndIf
WEnd
So far this seems to be working. I'd really like to find a solution that's entirely VBA, however, so that I can make this a standalone application.
To receive the new commits
git fetch
Reset
You can reset the commit for a local branch using git reset
.
To change the commit of a local branch:
git reset origin/master --hard
Be careful though, as the documentation puts it:
Resets the index and working tree. Any changes to tracked files in the working tree since <commit> are discarded.
If you want to actually keep whatever changes you've got locally - do a --soft
reset instead. Which will update the commit history for the branch, but not change any files in the working directory (and you can then commit them).
Rebase
You can replay your local commits on top of any other commit/branch using git rebase
:
git rebase -i origin/master
This will invoke rebase in interactive mode where you can choose how to apply each individual commit that isn't in the history you are rebasing on top of.
If the commits you removed (with git push -f
) have already been pulled into the local history, they will be listed as commits that will be reapplied - they would need to be deleted as part of the rebase or they will simply be re-included into the history for the branch - and reappear in the remote history on the next push.
Use the help git command --help
for more details and examples on any of the above (or other) commands.
If you want to open it to read and write, I'm assuming you don't want to truncate it as you open it and you want to be able to read the file right after opening it. So this is the solution I'm using:
file = open('myfile.dat', 'a+')
file.seek(0, 0)
This seems to be what you're looking for:
g <- ggplot(x, aes(reorder(variable, value), value))
g + geom_bar() + scale_y_continuous(formatter="percent") + coord_flip()
The reorder()
function will reorder your x axis items according to the value
of variable
.
For variable argument functions like printf
and scanf
, the arguments are promoted, for example, any smaller integer types are promoted to int
, float
is promoted to double
.
scanf
takes parameters of pointers, so the promotion rule takes no effect. It must use %f
for float*
and %lf
for double*
.
printf
will never see a float
argument, float
is always promoted to double
. The format specifier is %f
. But C99 also says %lf
is the same as %f
in printf
:
C99 §7.19.6.1 The
fprintf
function
l
(ell) Specifies that a followingd
,i
,o
,u
,x
, orX
conversion specifier applies to along int
orunsigned long int
argument; that a followingn
conversion specifier applies to a pointer to along int
argument; that a followingc
conversion specifier applies to awint_t
argument; that a followings
conversion specifier applies to a pointer to awchar_t
argument; or has no effect on a followinga
,A
,e
,E
,f
,F
,g
, orG
conversion specifier.
Ians Answer is good, but you should use const instead of let for the key because it never gets updated.
for (const key in myDictionary) {
let value = myDictionary[key];
// Use `key` and `value`
}
simplify2array
is a base function that is fairly intuitive. However, since R's default is to fill in data by columns first, you will need to transpose the output. (sapply
uses simplify2array
, as documented in help(sapply)
.)
> t(simplify2array(a))
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 1 2 3 4 5
[2,] 2 1 2 3 4 5
[3,] 3 1 2 3 4 5
[4,] 4 1 2 3 4 5
[5,] 5 1 2 3 4 5
[6,] 6 1 2 3 4 5
[7,] 7 1 2 3 4 5
[8,] 8 1 2 3 4 5
[9,] 9 1 2 3 4 5
[10,] 10 1 2 3 4 5
Here is a version, basically the same as a couple of the other answers, but that you can copy paste into your SQL server Management Studio to test, (and without generating any unwanted tables), thanks to some inline values.
WITH [TestData]([ID],[SKU],[PRODUCT]) AS
(
SELECT *
FROM (
VALUES
(1, 'FOO-23', 'Orange'),
(2, 'BAR-23', 'Orange'),
(3, 'FOO-24', 'Apple'),
(4, 'FOO-25', 'Orange')
)
AS [TestData]([ID],[SKU],[PRODUCT])
)
SELECT * FROM [TestData] WHERE [ID] IN
(
SELECT MIN([ID])
FROM [TestData]
GROUP BY [PRODUCT]
)
Result
ID SKU PRODUCT
1 FOO-23 Orange
3 FOO-24 Apple
I have ignored the following ...
WHERE ([SKU] LIKE 'FOO-%')
as its only part of the authors faulty code and not part of the question. It's unlikely to be helpful to people looking here.
Set type=submit
to the button you'd like to be default and type=button
to other buttons. Now in the form below you can hit Enter in any input fields, and the Render
button will work (despite the fact it is the second button in the form).
Example:
<button id='close_button' class='btn btn-success'
type=button>
<span class='glyphicon glyphicon-edit'> </span> Edit program
</button>
<button id='render_button' class='btn btn-primary'
type=submit> <!-- Here we use SUBMIT, not BUTTON -->
<span class='glyphicon glyphicon-send'> </span> Render
</button>
Tested in FF24 and Chrome 35.
it's answered, but it could be done with a fancy 'map/reduce' use, e.g.:
def find_key(value, dictionary):
return reduce(lambda x, y: x if x is not None else y,
map(lambda x: x[0] if x[1] == value else None,
dictionary.iteritems()))
I think what you need is to use the event.currentTarget
. This will contain the element that actually has the event listener. So if the whole <section>
has the eventlistener event.target
will be the clicked element, the <section>
will be in event.currentTarget
.
Otherwise parentNode
might be what you're looking for.
You can achieve that by using the reference to an angular DOM element as follows:
Here is the example in stackblitz
the component template:
<div class="other-content">
Other content
<button (click)="element.scrollIntoView({ behavior: 'smooth', block: 'center' })">
Click to scroll
</button>
</div>
<div id="content" #element>
Some text to scroll
</div>
A tricky way:
If you develop under Lunux, you can use all the power of sed:
from subprocess import check_call, CalledProcessError
PATH_TO_FILE = '/home/user/some/path/to/file.csv'
try:
check_call("sed -i -e 's|\\x0||g' {}".format(PATH_TO_FILE), shell=True)
except CalledProcessError as err:
print(err)
The most efficient solution for huge files.
Checked for Python3, Kubuntu
It's possible to run application specifying package name only using monkey tool by follow this pattern:
adb shell monkey -p your.app.package.name -c android.intent.category.LAUNCHER 1
Command is used to run app using monkey tool which generates random input for application. The last part of command is integer which specify the number of generated random input for app. In this case the number is 1, which in fact is used to launch the app (icon click).
I created a JsFiddle here based on the answer given by Zachary. It provides a more accessible user interface and also escapes double quotes within strings properly.
in package.json we have to config like below (works in Linux and Mac OS)
the important thing is "export NODE_ENV=production" after your build commands below is an example:
"scripts": {
"start": "export NODE_ENV=production && npm run build && npm run start-server",
"dev": "export NODE_ENV=dev && npm run build && npm run start-server",
}
for dev environment, we have to hit "npm run dev" command
for a production environment, we have to hit "npm run start" command
Please make sure that you also add a __init__.py
file in the package where all your other .ipynb files are located.
This is in addition to the nbviewer link that minrk
and syi
provided above.
I also had some similar problem and then I wrote the solution as well as a link to my public google drive folder which has a working example :)
My Stackoverflow post with step by step experimentation and Solution:
Jupyter Notebook: Import .ipynb file and access it's method in other .ipynb file giving error
Hope this will help others as well. Thanks all!
Try something like this:
awk -vc=1 'NR%1000000==0{++c}{print $0 > c".txt"}' Datafile.txt
for filename in *.txt; do mv "$filename" "Prefix_$filename"; done;
I know this question is 4 years old, but I have a couple different options:
tar --to-command grep
The following line will look in example.tgz
for PATTERN
. This is similar to @Jester's example, but I couldn't get his pattern matching to work.
tar xzf example.tgz --to-command 'grep --label="$TAR_FILENAME" -H PATTERN ; true'
tar -tzf
The second option is using tar -tzf
to list the files, then go through them with grep
. You can create a function to use it over and over:
targrep () {
for i in $(tar -tzf "$1"); do
results=$(tar -Oxzf "$1" "$i" | grep --label="$i" -H "$2")
echo "$results"
done
}
Usage:
targrep example.tar.gz "pattern"
select column1, coulumn2, case when colum1=column2 then 'true' else 'false' end from table;
HTH
If it is just "access in other controller" then you can use angular constants for that, the benefit is; you can add some global settings or other things that you want to access throughout application
app.constant(‘appGlobals’, {
defaultTemplatePath: '/assets/html/template/',
appName: 'My Awesome App'
});
and then access it like:
app.controller(‘SomeController’, [‘appGlobals’, function SomeController(config) {
console.log(appGlobals);
console.log(‘default path’, appGlobals.defaultTemplatePath);
}]);
(didn't test)
more info: http://ilikekillnerds.com/2014/11/constants-values-global-variables-in-angularjs-the-right-way/
First and foremost design your view, preferably in something like Sketch or get an idea of what do you want as a scrollable content.
After this make the view controller free form (choose from attribute inspector) and set height and width as per the intrinsic content size of your view (to be chosen from the size inspector).
After this in the view controller put a scroll view and this is a logic, which I have found to be working almost all the times in iOS (it may require going through the documentation of that view class which one can obtain via command + click on that class or via googling)
If you are working with two or more views then first start with a view, which has been introduced earlier or is more primitive and then go to the view which has been introduced later or is more modern. So here since scroll view has been introduced first, start with the scroll view first and then go to the stack view. Here put scroll view constraints to zero in all direction vis-a-vis its super view. Put all your views inside this scroll view and then put them in stack view.
While working with stack view
First start with grounds up(bottoms up approach), ie., if you have labels, text fields and images in your view, then lay out these views first (inside the scroll view) and after that put them in the stack view.
After that tweak the property of stack view. If desired view is still not achieved, then use another stack view.
After making your view, put a constraint between the mother stack view and the scroll view, while constraint children stack view with the mother stack view. Hopefully by this time it should work fine or you may get a warning from Xcode giving suggestions, read what it says and implement those. Hopefully now you should have a working view as per your expectations:).
I am unable to get this working with the javac compiler, and I get the same error.
Error:(9, 14) java: package lombok does not exist
I have enabled annotation processor, and have also tried rebuilding the project, invalidate cache/restart. Doesn't help.
I did however get it to work partially with eclipse compiler. I say partial because although the build passes successfully, the editor still complains about "Cannot resolve symbol".
Idea - 15.04 community edition Lombok - 1.16.6 Lombok plugin (https://github.com/mplushnikov/lombok-intellij-plugin) - 0.9.8 JDK - 1.8.0_51
Update: Ok, I finally got this working. Mine was a gradle project, and lombok was configured as a custom "provided" configuration. Worked fine after adding this in build.gradle
idea {
module {
scopes.PROVIDED.plus += [configurations.provided]
}
}
So, 3 steps
Layout Weight works like a ratio. For example, if there is a vertical layout and there are two items(such as buttons or textviews), one having layout weight 2 and the other having layout weight 3 respectively. Then the 1st item will occupy 2 out of 5 portion of the screen/layout and the other one 3 out of 5 portion. Here 5 is the weight sum. i.e. Weight sum divides the whole layout into defined portions. And Layout Weight defines how much portion does the particular item occupies out of the total Weight Sum pre-defined. Weight sum can be manually declared as well. Buttons, textviews, edittexts etc all are organized using weightsum and layout weight when using linear layouts for UI design.
The class which implements KeyListener
interface becomes our custom key event listener. This listener can not directly listen the key events. It can only listen the key events through intermediate objects such as JFrame
. So
Make one Key listener class as
class MyListener implements KeyListener{
// override all the methods of KeyListener interface.
}
Now our class MyKeyListener
is ready to listen the key events. But it can not directly do so.
Create any object like JFrame
object through which MyListener
can listen the key events. for that you need to add MyListener
object to the JFrame
object.
JFrame f=new JFrame();
f.addKeyListener(new MyKeyListener);
You can also write a custom query using @Query
@Query(value = "from EntityClassTable t where yourDate BETWEEN :startDate AND :endDate")
public List<EntityClassTable> getAllBetweenDates(@Param("startDate")Date startDate,@Param("endDate")Date endDate);
pip freeze lists all installed packages even if not by pip/easy_install. On CentOs/Redhat a package installed through rpm is found.
Because they are two different kinds of controls...
You see, your web browser doesn't know about server side programming. it only knows about it's own DOM and the event models that it uses... And for click events of objects rendered to it. You should examine the final markup that is actually sent to the browser from ASP.Net to see the differences your self.
<asp:CheckBox runat="server" OnClick="alert(this.checked);" />
renders to
<input type="check" OnClick="alert(this.checked);" />
and
<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />
renders to
<input type="check" OnClientClick="alert(this.checked);" />
Now, as near as i can recall, there are no browsers anywhere that support the "OnClientClick" event in their DOM...
When in doubt, always view the source of the output as it is sent to the browser... there's a whole world of debug information that you can see.
SBJSON *parser = [[SBJSON alloc] init];
NSString *url_str=[NSString stringWithFormat:@"Example APi Here"];
url_str = [url_str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:url_str]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response1 encoding:NSUTF8StringEncoding]
NSDictionary *statuses = [parser2 objectWithString:json_string error:nil];
NSArray *news_array=[[statuses3 objectForKey:@"sold_list"] valueForKey:@"list"];
for(NSDictionary *news in news_array)
{
@try {
[title_arr addObject:[news valueForKey:@"gtitle"]]; //values Add to title array
}
@catch (NSException *exception) {
[title_arr addObject:[NSString stringWithFormat:@""]];
}
In this dynamicVar, I am creating dynamic variable "ele[i]" in which I will put value/elements of "arr" according to index. ele is blank at initial stage, so we will copy the elements of "arr" in array "ele".
function dynamicVar(){
var arr = ['a','b','c'];
var ele = [];
for (var i = 0; i < arr.length; ++i) {
ele[i] = arr[i];
] console.log(ele[i]);
}
}
dynamicVar();
I had a similar issue I was getting the entire object in this
but the value was displaying while doing #each
.
Solution: I re-structure my array of object like this:
let list = results.map((item)=>{
return { name:item.name, author:item.author }
});
and then in template file:
{{#each list}}
<tr>
<td>{{name }}</td>
<td>{{author}}</td>
</tr>
{{/each}}
It seems that
@Column(name="..")
is completely ignored unless there is
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.EJB3NamingStrategy
specified, so to me this is a bug.
I spent a few hours trying to figure out why @Column(name="..") was ignored.
I use the term program to include applications (apps), utilities and even operating systems like windows, linux and mac OS. We kinda need an overall term for all the different terms available. It might be wrong but works for me. :)
void main ()
{
int temp,integer,count=0,i,cnd=0;
char ascii[10]={0};
printf("enter a number");
scanf("%d",&integer);
if(integer>>31)
{
/*CONVERTING 2's complement value to normal value*/
integer=~integer+1;
for(temp=integer;temp!=0;temp/=10,count++);
ascii[0]=0x2D;
count++;
cnd=1;
}
else
for(temp=integer;temp!=0;temp/=10,count++);
for(i=count-1,temp=integer;i>=cnd;i--)
{
ascii[i]=(temp%10)+0x30;
temp/=10;
}
printf("\n count =%d ascii=%s ",count,ascii);
}
In IIS you can declare the mime type for WOFF2 font files by adding the following to your project's web.config:
<system.webServer>
<staticContent>
<remove fileExtension=".woff2" />
<mimeMap fileExtension=".woff2" mimeType="font/woff2" />
</staticContent>
</system.webServer>
Update:
The mime type may be changing according to the latest W3C Editor's Draft WOFF2 spec. See Appendix A: Internet Media Type Registration section 6.5. WOFF 2.0 which states the latest proposed format is font/woff2
from selenium import webdriver_x000D_
#driver = webdriver.Firefox()_x000D_
driver = webdriver.Chrome()_x000D_
driver.get("http://www.python.org")
_x000D_
Okay... so i know that i'm answering to a decade question, but wanted to add something! I wanted to add a google calendar with special iframe parameters. Problem is that the calendar didn't work without it. 30 seconds is a bit short for my use, so i changed that in my own file to 15 minutes This worked for me.
<script>
window.setInterval("reloadIFrame();", 30000);
function reloadIFrame() {
document.getElementById("calendar").src=calendar.src;
}
</script>
<iframe id="calendar" src="[URL]" style="border-width:0" width=100% height=100% frameborder="0" scrolling="no"></iframe>
You can also try this:
db.emails.find($and:[{sent_at:{$exists:true},'sent_at':null}]).count()
You don't need to change the compliance level here, or rather, you should but that's not the issue.
The code compliance ensures your code is compatible with a given Java version.
For instance, if you have a code compliance targeting Java 6, you can't use Java 7's or 8's new syntax features (e.g. the diamond, the lambdas, etc. etc.).
The actual issue here is that you are trying to compile something in a Java version that seems different from the project dependencies in the classpath.
Instead, you should check the JDK/JRE you're using to build.
In Eclipse, open the project properties and check the selected JRE in the Java build path.
If you're using custom Ant (etc.) scripts, you also want to take a look there, in case the above is not sufficient per se.
Please set parent div to overflow: hidden
then in child divs you can set a large amount for padding-bottom. for example
padding-bottom: 5000px
then margin-bottom: -5000px
and then all child divs will be the height of the parent.
Of course this wont work if you are trying to put content in the parent div (outside of other divs that is)
.parent{_x000D_
border: 1px solid black;_x000D_
overflow: hidden;_x000D_
height: auto;_x000D_
}_x000D_
.child{_x000D_
float: left;_x000D_
padding-bottom: 1500px;_x000D_
margin-bottom: -1500px;_x000D_
}_x000D_
.child1{_x000D_
background: red;_x000D_
padding-right: 10px; _x000D_
}_x000D_
.child2{_x000D_
background: green;_x000D_
padding-left: 10px;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child1 child">_x000D_
One line text in child1_x000D_
</div>_x000D_
<div class="child2 child">_x000D_
Three line text in child2<br />_x000D_
Three line text in child2<br />_x000D_
Three line text in child2_x000D_
</div>_x000D_
</div>
_x000D_
Example: http://jsfiddle.net/Tareqdhk/DAFEC/
I stylesheet may not get loaded for several reasons. But the main approach to solve such a problem is as follows:
1. After loading the page, press F12
to open the Developers Console. Check the console for any logged errors.
2. Then you should check the Stylesheet tab and see the list of stylesheets the browser loaded.
3. The URL you're using inside your HTML link
tag may be unaccessable, so manually try to visit the stylesheet with a browser and see if everything renders correctly.
4. Any typo inside your HTML or CSS stylesheet may cause the stylesheet from loading.
5. Check for any occurrences of fatal errors before your <link>
tag. A fatal error may stop the running code and suspend the page, thus not including your stylesheet.
Hope that helps.
Of course! Just use the ALTER TABLE...
syntax.
Example
ALTER TABLE YourTable
ADD Foo INT NULL /*Adds a new int column existing rows will be
given a NULL value for the new column*/
Or
ALTER TABLE YourTable
ADD Bar INT NOT NULL DEFAULT(0) /*Adds a new int column existing rows will
be given the value zero*/
In SQL Server 2008 the first one is a metadata only change. The second will update all rows.
In SQL Server 2012+ Enterprise edition the second one is a metadata only change too.
You are actually getting the correct value out.
The way your x86
(compatible) processor stores data like this, is in Little Endian order, meaning that, the MSB is last in your output.
So, given your output:
10101010
the last two hex values 10
are the Most Significant Byte (2 hex digits = 1 byte = 8 bits
(for (possibly unnecessary) clarification).
So, by reversing the memory storage order of the bytes, your value is actually: 01010101
.
Hope that clears it up!
In essence all you need to do are the following:
server = $1
branch = $2
git push $server $branch
ssh <username>@$server "cd /path/to/www; git pull"
I have those lines in my application as an executable called deploy
.
so when I want to do a deploy I type ./deploy myserver mybranch
.
This approach, df1 != df2
, works only for dataframes with identical rows and columns. In fact, all dataframes axes are compared with _indexed_same
method, and exception is raised if differences found, even in columns/indices order.
If I got you right, you want not to find changes, but symmetric difference. For that, one approach might be concatenate dataframes:
>>> df = pd.concat([df1, df2])
>>> df = df.reset_index(drop=True)
group by
>>> df_gpby = df.groupby(list(df.columns))
get index of unique records
>>> idx = [x[0] for x in df_gpby.groups.values() if len(x) == 1]
filter
>>> df.reindex(idx)
Date Fruit Num Color
9 2013-11-25 Orange 8.6 Orange
8 2013-11-25 Apple 22.1 Red
I had a similar problem with HttpClient
version 4.
I couldn't connect to the server because of a SOCKS proxy error and I fixed it using the below configuration:
client.getParams().setParameter("socksProxyHost",proxyHost);
client.getParams().setParameter("socksProxyPort",proxyPort);
It is very easy to connect remote MySQL Server Using PHP, what you have to do is:
Create a MySQL User in remote server.
Give Full privilege to the User.
Connect to the Server using PHP Code (Sample Given Below)
$link = mysql_connect('your_my_sql_servername or IP Address', 'new_user_which_u_created', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db('sandsbtob',$link) or die ("could not open db".mysql_error());
// we connect to localhost at port 3306
There are MYSQL functions you can use. Like this one that resolves the user:
SELECT USER();
This will return something like root@localhost
so you get the host and the user.
To get the current database run this statement:
SELECT DATABASE();
Other useful functions can be found here: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html
Try the following:
$ch = curl_init("http://www.example-webpage.com/file.html");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
$content = curl_exec($ch);
curl_close($ch);
I would only recommend this for small files. Big files are read as a whole and are likely to produce a memory error.
EDIT: after some discussion in the comments we found out that the problem was that the server couldn't resolve the host name and the page was in addition a HTTPS resource so here comes your temporary solution (until your server admin fixes the name resolving).
what i did is just pinging graph.facebook.com to see the IP address, replace the host name with the IP address and instead specify the header manually. This however renders the SSL certificate invalid so we have to suppress peer verification.
//$url = "https://graph.facebook.com/19165649929?fields=name";
$url = "https://66.220.146.224/19165649929?fields=name";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host: graph.facebook.com'));
$output = curl_exec($ch);
curl_close($ch);
Keep in mind that the IP address might change and this is an error source. you should also do some error handling using curl_error();
.
react native devs
run
sudo cd android && ./gradlew clean
and if you want release apk
sudo cd android && ./gradlew assembleRelease
Hope it will help someone
Here is some list functions based on Martin v. Löwis's representation:
cons = lambda el, lst: (el, lst)
mklist = lambda *args: reduce(lambda lst, el: cons(el, lst), reversed(args), None)
car = lambda lst: lst[0] if lst else lst
cdr = lambda lst: lst[1] if lst else lst
nth = lambda n, lst: nth(n-1, cdr(lst)) if n > 0 else car(lst)
length = lambda lst, count=0: length(cdr(lst), count+1) if lst else count
begin = lambda *args: args[-1]
display = lambda lst: begin(w("%s " % car(lst)), display(cdr(lst))) if lst else w("nil\n")
where w = sys.stdout.write
Although doubly linked lists are famously used in Raymond Hettinger's ordered set recipe, singly linked lists have no practical value in Python.
I've never used a singly linked list in Python for any problem except educational.
Thomas Watnedal suggested a good educational resource How to Think Like a Computer Scientist, Chapter 17: Linked lists:
A linked list is either:
a node that contains a cargo object and a reference to a linked list.
class Node:
def __init__(self, cargo=None, next=None):
self.car = cargo
self.cdr = next
def __str__(self):
return str(self.car)
def display(lst):
if lst:
w("%s " % lst)
display(lst.cdr)
else:
w("nil\n")
mmap
has the advantage when you have random access on big files. Another advantage is that you access it with memory operations (memcpy, pointer arithmetic), without bothering with the buffering. Normal I/O can sometimes be quite difficult when using buffers when you have structures bigger than your buffer. The code to handle that is often difficult to get right, mmap is generally easier. This said, there are certain traps when working with mmap
.
As people have already mentioned, mmap
is quite costly to set up, so it is worth using only for a given size (varying from machine to machine).
For pure sequential accesses to the file, it is also not always the better solution, though an appropriate call to madvise
can mitigate the problem.
You have to be careful with alignment restrictions of your architecture(SPARC, itanium), with read/write IO the buffers are often properly aligned and do not trap when dereferencing a casted pointer.
You also have to be careful that you do not access outside of the map. It can easily happen if you use string functions on your map, and your file does not contain a \0 at the end. It will work most of the time when your file size is not a multiple of the page size as the last page is filled with 0 (the mapped area is always in the size of a multiple of your page size).
If you're in a client-side web environment, the new auth2 javascript API contains a much-needed getBasicProfile()
function, which returns the user's name, email, and image URL.
https://developers.google.com/identity/sign-in/web/reference#googleusergetbasicprofile
If you're looking for a quick way to do this, for example debugging, you can simply concatenate an empty string on to the boolean:
System.out.println(b+"");
However, I strongly recommend using another method for production usage. This is a simple quick solution which is useful for debugging.
If you are just placing the code on the page, usually the code behind will get an auto generated field you to use like @Oded has shown.
In other cases, you can always use this code:
Label myLabel = this.FindControl("myLabel") as Label; // this is your Page class
if(myLabel != null)
myLabel.Text = "SomeText";
For Mac OS:
#ifdef __APPLE__
For MingW on Windows:
#ifdef __MINGW32__
For Linux:
#ifdef __linux__
For other Windows compilers, check this thread and this for several other compilers and architectures.
If you are sending alphanumeric data try changing
'Content-Type': 'multipart/form-data'
to
'Content-Type': 'application/x-www-form-urlencoded'
If you are sending non-alphanumeric data try to remove 'Content-Type' at all.
If it still does not work, consider trying request-promise (at least to test whether it is really axios problem or not)
Here's my modified version of Bill's code:
CREATE TRIGGER mytrigger ON sometable
INSTEAD OF INSERT
AS BEGIN
INSERT INTO sometable SELECT * FROM inserted WHERE ISNUMERIC(somefield) = 1 FROM inserted;
INSERT INTO sometableRejects SELECT * FROM inserted WHERE ISNUMERIC(somefield) = 0 FROM inserted;
END
This lets the insert always succeed, and any bogus records get thrown into your sometableRejects where you can handle them later. It's important to make your rejects table use nvarchar fields for everything - not ints, tinyints, etc - because if they're getting rejected, it's because the data isn't what you expected it to be.
This also solves the multiple-record insert problem, which will cause Bill's trigger to fail. If you insert ten records simultaneously (like if you do a select-insert-into) and just one of them is bogus, Bill's trigger would have flagged all of them as bad. This handles any number of good and bad records.
I used this trick on a data warehousing project where the inserting application had no idea whether the business logic was any good, and we did the business logic in triggers instead. Truly nasty for performance, but if you can't let the insert fail, it does work.
No, there is no straightforward way because Python dictionaries do not have a set ordering.
From the documentation:
Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.
In other words, the 'index' of b
depends entirely on what was inserted into and deleted from the mapping before:
>>> map={}
>>> map['b']=1
>>> map
{'b': 1}
>>> map['a']=1
>>> map
{'a': 1, 'b': 1}
>>> map['c']=1
>>> map
{'a': 1, 'c': 1, 'b': 1}
As of Python 2.7, you could use the collections.OrderedDict()
type instead, if insertion order is important to your application.
01. Integer can be null. But int cannot be null.
Integer value1 = null; //OK
int value2 = null //Error
02. Only can pass Wrapper Classes type values to any collection class.
(Wrapper Classes - Boolean,Character,Byte,Short,Integer,Long,Float,Double)
List<Integer> element = new ArrayList<>();
int valueInt = 10;
Integer valueInteger = new Integer(value);
element.add(valueInteger);
But normally we add primitive values to collection class? Is point 02 correct?
List<Integer> element = new ArrayList<>();
element.add(5);
Yes 02 is correct, beacouse autoboxing.
Autoboxing is the automatic conversion that the java compiler makes between the primitive type and their corresponding wrapper class.
Then 5 convert as Integer value by autoboxing.
You might want to use \n
instead of /n
.
The easiest way to solve the problem is to group the elements based on their value, and then pick a representative of the group if there are more than one element in the group. In LINQ, this translates to:
var query = lst.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(y => y.Key)
.ToList();
If you want to know how many times the elements are repeated, you can use:
var query = lst.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(y => new { Element = y.Key, Counter = y.Count() })
.ToList();
This will return a List
of an anonymous type, and each element will have the properties Element
and Counter
, to retrieve the information you need.
And lastly, if it's a dictionary you are looking for, you can use
var query = lst.GroupBy(x => x)
.Where(g => g.Count() > 1)
.ToDictionary(x => x.Key, y => y.Count());
This will return a dictionary, with your element as key, and the number of times it's repeated as value.
The following seems pretty natural to me, using Haskell. Iterate recursively over levels of the tree (here I collect names into a big ordered string to show the path through the tree):
data Node = Node {name :: String, children :: [Node]}
aTree = Node "r" [Node "c1" [Node "gc1" [Node "ggc1" []], Node "gc2" []] , Node "c2" [Node "gc3" []], Node "c3" [] ]
breadthFirstOrder x = levelRecurser [x]
where levelRecurser level = if length level == 0
then ""
else concat [name node ++ " " | node <- level] ++ levelRecurser (concat [children node | node <- level])
for window :
pip install mysqlclient pymysql
then:
import pymysql pymysql.install_as_MySQLdb()
for python 3 Ubuntu
sudo apt-get install -y python3-mysqldb
In Object Explorer, expand the table, and expand the Keys:
GitHub
git config --global url.ssh://[email protected]/.insteadOf https://github.com/
BitBucket
git config --global url.ssh://[email protected]/.insteadOf https://bitbucket.org/
That tells git to always use SSH instead of HTTPS when connecting to GitHub/BitBucket, so you'll authenticate by certificate by default, instead of being prompted for a password.
can you try this :
function f (){
fname = $("input[name='fname']").val();
lname = $("input[name='fname']").val();
att=form.attr("action") ;
$.post(att ,{fname : fname , lname :lname}).done(function(data){
alert(data);
});
return true;
}
threading.get_ident()
works, or threading.current_thread().ident
(or threading.currentThread().ident
for Python < 2.6).
The vast majority of current android 2.1+ phone screens are 480x800 (or in the case of motodroid oddities, 480x854)
However, this doesn't mean this should be your only concern. You need to make it looking good on tablets, and smaller or 4:3 ratio smaller screens.
RelativeLayout is your friend!
You can do the following, when your current directory is parent_directory
:
for d in [0-9][0-9][0-9]
do
( cd "$d" && your-command-here )
done
The (
and )
create a subshell, so the current directory isn't changed in the main script.
The 487 Response indicates that the previous request was terminated by user/application action. The most common occurrence is when the CANCEL happens as explained above. But it is also not limited to CANCEL. There are other cases where such responses can be relevant. So it depends on where you are seeing this behavior and whether its a user or application action that caused it.
15.1.2 UAS Behavior==> BYE Handling in RFC 3261
The UAS MUST still respond to any pending requests received for that dialog. It is RECOMMENDED that a 487 (Request Terminated) response be generated to those pending requests.
Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.
So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.
Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.
This.
$.each(
$('#some-element'),
function(i, item){
item.addEventListener('DOMNodeRemovedFromDocument',
function(e){ console.log('I has been removed'); console.log(e);
})
})
If you're using compass:
compass watch --output-style compressed
Yes. HTML2Canvas exists to render HTML onto <canvas>
(which you can then use as an image).
NOTE: There is a known issue, that this will not work with SVG
history.pushState
pushes the current page state onto the history stack, and changes the URL in the address bar. So, when you go back, that state (the object you passed) are returned to you.
Currently, that is all it does. Any other page action, such as displaying the new page or changing the page title, must be done by you.
The W3C spec you link is just a draft, and browser may implement it differently. Firefox, for example, ignores the title
parameter completely.
Here is a simple example of pushState
that I use on my website.
(function($){
// Use AJAX to load the page, and change the title
function loadPage(sel, p){
$(sel).load(p + ' #content', function(){
document.title = $('#pageData').data('title');
});
}
// When a link is clicked, use AJAX to load that page
// but use pushState to change the URL bar
$(document).on('click', 'a', function(e){
e.preventDefault();
history.pushState({page: this.href}, '', this.href);
loadPage('#frontPage', this.href);
});
// This event is triggered when you visit a page in the history
// like when yu push the "back" button
$(window).on('popstate', function(e){
loadPage('#frontPage', location.pathname);
console.log(e.originalEvent.state);
});
}(jQuery));
Use myList.get(3)
to get access to the current object and modify it, assuming instances of Customer
have a way to be modified.
Yes:
RelativeLayout.LayoutParams params= new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.BELOW, R.id.below_id);
viewToLayout.setLayoutParams(params);
First, the code creates a new layout params by specifying the height and width. The addRule
method adds the equivalent of the xml properly android:layout_below
. Then you just call View#setLayoutParams
on the view you want to have those params.
As a quick and very scoped solution:
Both Task.Result and Task.Wait won't allow to improving scalability when used with I/O, as they will cause the calling thread to stay blocked waiting for the I/O to end.
When you call .Result on an incomplete Task, the thread executing the method has to sit and wait for the task to complete, which blocks the thread from doing any other useful work in the meantime. This negates the benefit of the asynchronous nature of the task.
yes, by the concept of pointer you can do it like this for an int variable:
int *a;
int b=0;
a=NULL; // or a=&b; for giving the value of b to a
if(a==NULL)
printf("NULL");
else
printf(*a);
it is very simple and straitforward. it worked for me in Arduino IDE.
Anyone wants to use command line to sync projects with gradle files, please note:
Since Gradle 5.0,
The
--recompile-scripts
command-line option has been removed.
Correct me if wrong...I think request does persist between consecutive pages..
Think you traverse from page 1--> page 2-->page 3.
You have some value set in the request object using setAttribute from page 1, which you retrieve in page 2 using getAttribute,then if you try setting something again in same request object to retrieve it in page 3 then it fails giving you null value as "the request that created the JSP, and the request that gets generated when the JSP is submitted are completely different requests and any attributes placed on the first one will not be available on the second".
I mean something like this in page 2 fails:
Where as the same thing has worked in case of page 1 like:
So I think I would need to proceed with either of the two options suggested by Phill.
For a wrapper component, a simple solution would be to just use React.createElement
directly (using ES6).
import RaisedButton from 'mui/RaisedButton'
import FlatButton from 'mui/FlatButton'
import IconButton from 'mui/IconButton'
class Button extends React.Component {
render() {
const { type, ...props } = this.props
let button = null
switch (type) {
case 'flat': button = FlatButton
break
case 'icon': button = IconButton
break
default: button = RaisedButton
break
}
return (
React.createElement(button, { ...props, disableTouchRipple: true, disableFocusRipple: true })
)
}
}
Just set the header width to be 100vw to make it full screen width and set the header height to be 100vh to make it full screen height
You can use std::find
bool found = (std::find(my_list.begin(), my_list.end(), my_var) != my_list.end());
You need to include <algorithm>
. It should work on standard containers, vectors lists, etc...
I had a similar problem, but the differemce was: I didn't executed my JavaApp from localhost
, but from a remote PC. So I got something like java.sql.SQLException: Access denied for user 'root'@'a.remote.ip.adress' (using password: YES)
To solve this, you can simply login to phpMyAdmin, go to Users
, click add user
and enter the host from which you want to execute your JavaApp (or choose Any Host
)
The simple approach (gcc -dM -E - < /dev/null
) works fine for gcc but fails for g++. Recently I required a test for a C++11/C++14 feature. Recommendations for their corresponding macro names are published at https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations. But:
g++ -dM -E - < /dev/null | fgrep __cpp_alias_templates
always fails, because it silently invokes the C-drivers (as if invoked by gcc
). You can see this by comparing its output against that of gcc or by adding a g++-specific command line option like (-std=c++11) which emits the error message cc1: warning: command line option ‘-std=c++11’ is valid for C++/ObjC++ but not for C
.
Because (the non C++) gcc will never support "Templates Aliases" (see http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2258.pdf) you must add the -x c++
option to force the invocation of the C++ compiler (Credits for using the -x c++
options instead of an empty dummy file go to yuyichao, see below):
g++ -dM -E -x c++ /dev/null | fgrep __cpp_alias_templates
There will be no output because g++ (revision 4.9.1, defaults to -std=gnu++98) does not enable C++11-features by default. To do so, use
g++ -dM -E -x c++ -std=c++11 /dev/null | fgrep __cpp_alias_templates
which finally yields
#define __cpp_alias_templates 200704
noting that g++ 4.9.1 does support "Templates Aliases" when invoked with -std=c++11
.
You will have to provide a link to your file that is accessible through the browser, that is for instance:
<a href="http://my.domain.com/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">
versus
<a href="C:/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">
If you expose your "Projecten" folder directly to the public, then you may only have to provide the link as such:
<a href="/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">
But beware, that your files can then be indexed by search engines, can be accessed by anybody having this link, etc.
I use
chartRange = xlWorkSheet.Rows[1];
chartRange.Font.Bold = true;
to turn the first-row-cells-font into bold. And it works, and I am using also Excel 2007.
You can call in VBA directly
ActiveCell.Font.Bold = True
With this code I create a timestamp in the active cell, with bold font and yellow background
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
ActiveCell.Value = Now()
ActiveCell.Font.Bold = True
ActiveCell.Interior.ColorIndex = 6
End Sub
Nvm can be used to manage various node version :
Step1: Download nvm for Windows
Step2: Choose nvm-setup.zip
Step3: Unzip & click on installer.
Step4: Check if nvm properly installed, In new command prompt type nvm
Step5: Install node js using nvm :
nvm install <version> : The version can be a node.js version or "latest" for the latest stable version
Step6: check node version - node -v
Step7(Optional)If you want to install another version of node js - Use STEP 5 with different version.
Step8: Check list node js version - nvm list
Step9: If you want to use specific node version do - nvm use <version>
To add to the (really good) existing answer
open_basedir
is one that can stump you because it can be specified in a web server configuration. While this is easily remedied if you run your own dedicated server, there are some shared hosting software packages out there (like Plesk, cPanel, etc) that will configure a configuration directive on a per-domain basis. Because the software builds the configuration file (i.e. httpd.conf
) you cannot change that file directly because the hosting software will just overwrite it when it restarts.
With Plesk, they provide a place to override the provided httpd.conf
called vhost.conf
. Only the server admin can write this file. The configuration for Apache looks something like this
<Directory /var/www/vhosts/domain.com>
<IfModule mod_php5.c>
php_admin_flag engine on
php_admin_flag safe_mode off
php_admin_value open_basedir "/var/www/vhosts/domain.com:/tmp:/usr/share/pear:/local/PEAR"
</IfModule>
</Directory>
Have your server admin consult the manual for the hosting and web server software they use.
It's important to note that executing a file through your web server is very different from a command line or cron job execution. The big difference is that your web server has its own user and permissions. For security reasons that user is pretty restricted. Apache, for instance, is often apache
, www-data
or httpd
(depending on your server). A cron job or CLI execution has whatever permissions that the user running it has (i.e. running a PHP script as root will execute with permissions of root).
A lot of times people will solve a permissions problem by doing the following (Linux example)
chmod 777 /path/to/file
This is not a smart idea, because the file or directory is now world writable. If you own the server and are the only user then this isn't such a big deal, but if you're on a shared hosting environment you've just given everyone on your server access.
What you need to do is determine the user(s) that need access and give only those them access. Once you know which users need access you'll want to make sure that
That user owns the file and possibly the parent directory (especially the parent directory if you want to write files). In most shared hosting environments this won't be an issue, because your user should own all the files underneath your root. A Linux example is shown below
chown apache:apache /path/to/file
The user, and only that user, has access. In Linux, a good practice would be chmod 600
(only owner can read and write) or chmod 644
(owner can write but everyone can read)
You can read a more extended discussion of Linux/Unix permissions and users here
A rewrite of the answer by Sarfraz would be something like this, I think:
<script>
document.getElementById('change').onclick = changeColor;
function changeColor() {
document.body.style.color = "purple";
return false;
}
</script>
You'd either have to put this script at the bottom of your page, right before the closing body tag, or put the handler assignment in a function called onload - or if you're using jQuery there's the very elegant $(document).ready(function() { ... } );
Note that when you assign event handlers this way, it takes the functionality out of your HTML. Also note you set it equal to the function name -- no (). If you did onclick = myFunc();
the function would actually execute when the handler is being set.
And I'm curious -- you knew enough to script changing the background color, but not the text color? strange:)
This is to do with the encoding of your terminal not being set to UTF-8. Here is my terminal
$ echo $LANG
en_GB.UTF-8
$ python
Python 2.7.3 (default, Apr 20 2012, 22:39:59)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s = '(\xef\xbd\xa1\xef\xbd\xa5\xcf\x89\xef\xbd\xa5\xef\xbd\xa1)\xef\xbe\x89'
>>> s1 = s.decode('utf-8')
>>> print s1
(?????)?
>>>
On my terminal the example works with the above, but if I get rid of the LANG
setting then it won't work
$ unset LANG
$ python
Python 2.7.3 (default, Apr 20 2012, 22:39:59)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s = '(\xef\xbd\xa1\xef\xbd\xa5\xcf\x89\xef\xbd\xa5\xef\xbd\xa1)\xef\xbe\x89'
>>> s1 = s.decode('utf-8')
>>> print s1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-5: ordinal not in range(128)
>>>
Consult the docs for your linux variant to discover how to make this change permanent.
my_df = pd.DataFrame.from_dict(my_dict, orient='index', columns=['my_col'])
.. would have parsed the dict properly (putting each dict key into a separate df column, and key values into df rows), so the dicts would not get squashed into a single column in the first place.
FindViewById can be null if you call the wrong super constructor in a custom view. The ID tag is part of attrs, so if you ignore attrs, you delete the ID.
This would be wrong
public CameraSurfaceView(Context context, AttributeSet attrs) {
super(context);
}
This is correct
public CameraSurfaceView(Context context, AttributeSet attrs) {
super(context,attrs);
}
use this
function pnstest(){
$data = array('post_id'=>'12345','title'=>'A Blog post', 'message' =>'test msg');
$url = 'https://fcm.googleapis.com/fcm/send';
$server_key = 'AIzaSyDVpDdS7EyNgMUpoZV6sI2p-cG';
$target ='fO3JGJw4CXI:APA91bFKvHv8wzZ05w2JQSor6D8lFvEGE_jHZGDAKzFmKWc73LABnumtRosWuJx--I4SoyF1XQ4w01P77MKft33grAPhA8g-wuBPZTgmgttaC9U4S3uCHjdDn5c3YHAnBF3H';
$fields = array();
$fields['data'] = $data;
if(is_array($target)){
$fields['registration_ids'] = $target;
}else{
$fields['to'] = $target;
}
//header with content_type api key
$headers = array(
'Content-Type:application/json',
'Authorization:key='.$server_key
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
Use Application.ActiveWorkbook.Path
for just the path itself (without the workbook name) or Application.ActiveWorkbook.FullName
for the path with the workbook name.
I followed Mingcai SHEN's method.
But in my case, I changed the connector to
connector = C:\Program Files\MySQL\MySQL Connector.C 6.1
And the library_dirs is changed to
library_dirs = [ os.path.join(connector, r'lib\vs10') ]
because I don't have a vs9
directory. It works, but I don't know why.
I have vs2012 installed, and the lib directory of the connector only has vs10
and vs11
, in which vs11
doesn't work. The VCForPyhton27.mis I installed seems to support vs9
.
Anyway, this works. And if you want to risk it, you can try.
Type in your URL localhost/[name of your folder in htdocs]
Use ThisWorkbook
which will refer to the original workbook which holds the code.
Alternatively at code start
Dim Wb As Workbook
Set Wb = ActiveWorkbook
sample code that activates all open books before returning to ThisWorkbook
Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
Wb2.Activate
Next
Wb.Activate
End Sub
The problem is Firefox doesn't listen to width and height. Disable that and your good to go.
input[type=checkbox] {_x000D_
width: 25px;_x000D_
height: 25px;_x000D_
-moz-appearance: none;_x000D_
}
_x000D_
<label><input type="checkbox"> Test</label>
_x000D_
from http://code.google.com/p/fast-serialization/wiki/QuickStartHeapOff
What is Heap-Offloading ?
Usually all non-temporary objects you allocate are managed by java's garbage collector. Although the VM does a decent job doing garbage collection, at a certain point the VM has to do a so called 'Full GC'. A full GC involves scanning the complete allocated Heap, which means GC pauses/slowdowns are proportional to an applications heap size. So don't trust any person telling you 'Memory is Cheap'. In java memory consumtion hurts performance. Additionally you may get notable pauses using heap sizes > 1 Gb. This can be nasty if you have any near-real-time stuff going on, in a cluster or grid a java process might get unresponsive and get dropped from the cluster.
However todays server applications (frequently built on top of bloaty frameworks ;-) ) easily require heaps far beyond 4Gb.
One solution to these memory requirements, is to 'offload' parts of the objects to the non-java heap (directly allocated from the OS). Fortunately java.nio provides classes to directly allocate/read and write 'unmanaged' chunks of memory (even memory mapped files).
So one can allocate large amounts of 'unmanaged' memory and use this to save objects there. In order to save arbitrary objects into unmanaged memory, the most viable solution is the use of Serialization. This means the application serializes objects into the offheap memory, later on the object can be read using deserialization.
The heap size managed by the java VM can be kept small, so GC pauses are in the millis, everybody is happy, job done.
It is clear, that the performance of such an off heap buffer depends mostly on the performance of the serialization implementation. Good news: for some reason FST-serialization is pretty fast :-).
Sample usage scenarios:
Edit: For some scenarios one might choose more sophisticated Garbage Collection algorithms such as ConcurrentMarkAndSweep or G1 to support larger heaps (but this also has its limits beyond 16GB heaps). There is also a commercial JVM with improved 'pauseless' GC (Azul) available.
Dive right it, make it a hobby, and have fun :)
Coming from an electronics background myself I can tell you that you should pick it up pretty quickly. And having an electronics background will give you a deeper understanding of the underlying hardware.
IMHO the root of information technology is electronics.
For example..
Think of objects as components.
The .NET framework is essentially drawers full of standard components.
For example you know what a 7400 (NAND gate) is capable of doing. You have a data sheet showing the pin outs and sample configurations. You don't typically care about the circuitry inside. Software objects are the same way. We have inputs and we have methods that do something to the inputs to produce predictable outputs. As developers we typically don't care how the object was written... just that it does what it says it will do.
You also know that you can build additional logic circuits by using two or more NAND gates. This of this as instantiation.
You also know that you can take a NAND gate and place it inside a circuit where you can modify the input signals coming in so the outputs have different behaviors. This is a crude example but you can think of this as inheritance.
I have also learned it helps to have a project to work on. It could be a hobbyist project or a work project. Start small, get something very basic working, and work up from there.
To answer your specific question on "what should I learn first".
1) Take your project you have in mind and break it into steps. For example... get a number from the user, add one to the number, display the result. Think of this as your design.
2) Learn basic C#. Write a simple console application that does something. Learn what an if statement is (this is all boolean logic so it should be somewhat familiar), learn about loops, learn about mathematical operations, learn about functions (subroutines). Play with simple file i/o (reading and writing text files). The basic C# can be thought of as your wiring and discrete components (resistors, caps, transistors, etc) to your chips (object).
3) Learn how to instantiate and use objects from the framework. You have already been doing this but now it's time to delve in further. For example... play with System.Console some more... try making the speaker beep. Also start looking for objects that you may want to use for database work.
4) Learn basic SQL. Lots of help and examples online. Pick a database you want to work with. I personally think MS Access is a great beginners database. I would not use it for multi-user or cross platform desktop applications... but it is a great single user database for Windows users... and it is a great way to learn the basics of SQL. There are other simple free databases available (Open Office has one for example) if you don't want to shell out $ for Access.
5) Expand your app to do something with a database.
I kept having problems with this, the only solution was to add an image and label as subviews to the uibutton. Then I discovered that the main problem was that I was using a UIButton with title: Attributed. When I changed it to Plain, just setting the titleLabel.text did the trick!
jsfiddle: http://jsfiddle.net/mgtoz4d3/
I added a container which contains both buttons. Try this:
CSS:
#button1{
width: 300px;
height: 40px;
}
#button2{
width: 300px;
height: 40px;
}
#container{
text-align: center;
}
HTML:
<img src="kingstonunilogo.jpg" alt="uni logo" style="width:180px;height:160px">
<br><br>
<div id="container">
<button type="button home-button" id="button1" >Home</button>
<button type="button contact-button" id="button2">Contact Us</button>
</div>
Another way based on amadan:
SELECT * FROM [Purchasing].[Vendor] WHERE
( (@url IS null OR @url = '' OR @url = 'ALL') and PurchasingWebServiceURL LIKE '%')
or
( @url = 'blank' and PurchasingWebServiceURL = '')
or
(@url = 'fail' and PurchasingWebServiceURL NOT LIKE '%treyresearch%')
or( (@url not in ('fail','blank','','ALL') and @url is not null and
PurchasingWebServiceUrl Like '%'+@ur+'%')
END
Well you can really shoot yourself in the foot with operator overloading. It's like with pointers people make stupid mistakes with them and so it was decided to take the scissors away.
At least I think that's the reason. I'm on your side anyway. :)
It allows servlets to have multiple servlet mappings:
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-path>foo.Servlet</servlet-path>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/enroll</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/pay</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/bill</url-pattern>
</servlet-mapping>
It allows filters to be mapped on the particular servlet:
<filter-mapping>
<filter-name>Filter1</filter-name>
<servlet-name>Servlet1</servlet-name>
</filter-mapping>
Your proposal would support neither of them. Note that the web.xml
is read and parsed only once during application's startup, not on every HTTP request as you seem to think.
Since Servlet 3.0, there's the @WebServlet
annotation which minimizes this boilerplate:
@WebServlet("/enroll")
public class Servlet1 extends HttpServlet {
Where is your problem??
For the stored procedure, just create:
CREATE PROCEDURE dbo.ReadEmployees @EmpID INT
AS
SELECT * -- I would *strongly* recommend specifying the columns EXPLICITLY
FROM dbo.Emp
WHERE ID = @EmpID
That's all there is.
From your ASP.NET application, just create a SqlConnection
and a SqlCommand
(don't forget to set the CommandType = CommandType.StoredProcedure
)
DataTable tblEmployees = new DataTable();
using(SqlConnection _con = new SqlConnection("your-connection-string-here"))
using(SqlCommand _cmd = new SqlCommand("ReadEmployees", _con))
{
_cmd.CommandType = CommandType.StoredProcedure;
_cmd.Parameters.Add(new SqlParameter("@EmpID", SqlDbType.Int));
_cmd.Parameters["@EmpID"].Value = 42;
SqlDataAdapter _dap = new SqlDataAdapter(_cmd);
_dap.Fill(tblEmployees);
}
YourGridView.DataSource = tblEmployees;
YourGridView.DataBind();
and then fill e.g. a DataTable
with that data and bind it to e.g. a GridView.
My answer below doesn't solve the question but it relates to.
If someone is using enum
instead of a class model, like this example:
public enum Counter
{
[Display(Name = "Number 1")]
No1 = 1,
[Display(Name = "Number 2")]
No2 = 2,
[Display(Name = "Number 3")]
No3 = 3
}
And a property to get the value when submiting:
public int No { get; set; }
In the razor page, you can use Html.GetEnumSelectList<Counter>()
to get the enum properties.
<select asp-for="No" asp-items="@Html.GetEnumSelectList<Counter>()"></select>
It generates the following HTML:
<select id="No" name="No">
<option value="1">Number 1</option>
<option value="2">Number 2</option>
<option value="3">Number 3</option>
</select>
No requires converting the Task to int. Simply Use The Task Result.
int taskResult = AccessTheWebAndDouble().Result;
public async Task<int> AccessTheWebAndDouble()
{
int task = AccessTheWeb();
return task;
}
It will return the value if available otherwise it return 0.
Hovercraft Full Of Eels' answer is very good, but i had to change it a bit in order to get it working on my program:
int y1 = (int) ((this.height - 2 * BORDER_GAP) - (values.get(i) * yScale - BORDER_GAP));
instead of
int y1 = (int) (scores.get(i) * yScale + BORDER_GAP);
because if i used his way the graphic would be upside down
(you'd see it if you used hardcoded values (e.g 1,3,5,7,9) instead of random values)
Okay. If you do not want to store the file in database and store in the application, like assets (custom folder), you can define non-db instance variable defined by attr_accessor: document and use form_for - f.file_field
to get the file,
In controller,
@person = Person.new(person_params)
Here person_params
return whitelisted params[:person]
(define yourself)
Save file as,
dir = "#{Rails.root}/app/assets/custom_path"
FileUtils.mkdir(dir) unless File.directory? dir
document = @person.document.document_file_name # check document uploaded params
File.copy_stream(@font.document, "#{dir}/#{document}")
Note, Add this path in .gitignore
& if you want to use this file again add this path asset_path
an of application by application.rb
Whenever form read file field, it get store in tmp folder, later you can store at your place, I gave example to store at assets
note: Storing files like this will increase the size of the application, better to store in the database using paperclip
.
I found a solution for my problem while writing my question !
Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)
I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)
So it seems the problem comes from the use of RDP (windows7 and 8)
Update 2017: Problem occurs on Windows 10 aswell.
why not both to be sure?
if(opener.document){
$("#testdiv",opener.document).doStuff();
}else{
$("#testdiv",window.opener).doStuff();
}
items[node.ind] = items[node.ind]._replace(v=node.v)
(Note: Don't be discouraged to use this solution because of the leading underscore in the function _replace. Specifically for namedtuple some functions have leading underscore which is not for indicating they are meant to be "private")
In Java 8:
Map<String, Long> counts =
list.stream().collect(Collectors.groupingBy(e -> e, Collectors.counting()));
Quick and dirty version:
byte[] fileBytes = File.ReadAllBytes(inputFilename);
StringBuilder sb = new StringBuilder();
foreach(byte b in fileBytes)
{
sb.Append(Convert.ToString(b, 2).PadLeft(8, '0'));
}
File.WriteAllText(outputFilename, sb.ToString());
The best approach is Long.valueOf(str)
as it relies on Long.valueOf(long)
which uses an internal cache making it more efficient since it will reuse if needed the cached instances of Long
going from -128
to 127
included.
Returns a
Long
instance representing the specified long value. If a new Long instance is not required, this method should generally be used in preference to the constructorLong(long)
, as this method is likely to yield significantly better space and time performance by caching frequently requested values. Note that unlike the corresponding method in the Integer class, this method is not required to cache values within a particular range.
Thanks to auto-unboxing allowing to convert a wrapper class's instance into its corresponding primitive type, the code would then be:
long val = Long.valueOf(str);
Please note that the previous code can still throw a NumberFormatException
if the provided String
doesn't match with a signed long
.
Generally speaking, it is a good practice to use the static
factory method valueOf(str)
of a wrapper class like Integer
, Boolean
, Long
, ... since most of them reuse instances whenever it is possible making them potentially more efficient in term of memory footprint than the corresponding parse
methods or constructors.
Excerpt from Effective Java Item 1
written by Joshua Bloch:
You can often avoid creating unnecessary objects by using static factory methods (Item 1) in preference to constructors on immutable classes that provide both. For example, the static factory method
Boolean.valueOf(String)
is almost always preferable to the constructorBoolean(String)
. The constructor creates a new object each time it’s called, while the static factory method is never required to do so and won’t in practice.
On most POSIX systems, it is ignored. But, check your system to be sure.
XNU
The mode string can also include the letter 'b' either as last character or as a character between the characters in any of the two-character strings described above. This is strictly for compatibility with ISO/IEC 9899:1990 ('ISO C90') and has no effect; the 'b' is ignored.
Linux
The mode string can also include the letter 'b' either as a last character or as a character between the characters in any of the two- character strings described above. This is strictly for compatibility with C89 and has no effect; the 'b' is ignored on all POSIX conforming systems, including Linux. (Other systems may treat text files and binary files differently, and adding the 'b' may be a good idea if you do I/O to a binary file and expect that your program may be ported to non-UNIX environments.)
We can use it independently in this way:
var A = A|| {};
A.B = {};
A.B = {
itemOne: null,
itemTwo: null,
};
A.B.itemOne = function () {
//..
}
A.B.itemTwo = function () {
//..
}
If Existing Project Solution is planned to move on TSF in VS Code:
open Terminal and run following commands:
Initialize git in that folder (root Directory)
git init
Add Git
git add .
Link your TSf/Git to that Project - {url} replace with your git address
git remote add origin {url}
Commit those Changes:
git commit -m "initial commit"
Push - I pushed code as version1 you can use any name for your branch
git push origin HEAD:Version1
I was facing same issue (VS Code).Resolved by below method
1) Select Interpreter command from the Command Palette (Ctrl+Shift+P)
2) Search for "Select Interpreter"
3) Select the installed python directory
Ref:- https://code.visualstudio.com/docs/python/environments#_select-an-environment
Code summary:
using System.Windows.Forms;
...
MessageBox.Show( "hello world" );
Also (as per this other stack post): In Visual Studio expand the project in Solution Tree, right click on References, Add Reference, Select System.Windows.Forms
on Framework tab. This will get the MessageBox working in conjunction with the using System.Windows.Forms reference from above.
Try this definitely work.
SELECT p.PersonID AS person_id,
p.Name, p.SS,
f.FearID AS fear_id,
f.Fear
FROM person_fear AS pf
LEFT JOIN persons AS p ON pf.PersonID = p.PersonID
LEFT JOIN fears AS f ON pf.PersonID = f.FearID
WHERE f.FearID = pf.FearID AND p.PersonID = pf.PersonID
I arrived to this question looking for the same but for Chromium (actually I'm using https://ungoogled-software.github.io). So in case anyone else is looking for the same:
Handling of extension MIME type requests
Always prompt for install
If you really only want to see trailing spaces, this ST2 plugin will do the trick: https://github.com/SublimeText/TrailingSpaces
And as a context manager:
import signal
class GracefulInterruptHandler(object):
def __init__(self, sig=signal.SIGINT):
self.sig = sig
def __enter__(self):
self.interrupted = False
self.released = False
self.original_handler = signal.getsignal(self.sig)
def handler(signum, frame):
self.release()
self.interrupted = True
signal.signal(self.sig, handler)
return self
def __exit__(self, type, value, tb):
self.release()
def release(self):
if self.released:
return False
signal.signal(self.sig, self.original_handler)
self.released = True
return True
To use:
with GracefulInterruptHandler() as h:
for i in xrange(1000):
print "..."
time.sleep(1)
if h.interrupted:
print "interrupted!"
time.sleep(2)
break
Nested handlers:
with GracefulInterruptHandler() as h1:
while True:
print "(1)..."
time.sleep(1)
with GracefulInterruptHandler() as h2:
while True:
print "\t(2)..."
time.sleep(1)
if h2.interrupted:
print "\t(2) interrupted!"
time.sleep(2)
break
if h1.interrupted:
print "(1) interrupted!"
time.sleep(2)
break
From here: https://gist.github.com/2907502
Use JavaScript's formData API and set contentType
and processData
to false
$("form[name='uploader']").on("submit", function(ev) {
ev.preventDefault(); // Prevent browser default submit.
var formData = new FormData(this);
$.ajax({
url: "page.php",
type: "POST",
data: formData,
success: function (msg) {
alert(msg)
},
cache: false,
contentType: false,
processData: false
});
});
I struggled with this problem for awhile and did several reinstalls of MySQL before discovering this.
I know that MySQL server was running OK because I could access all my DB's using the command line.
Hope this works for you.
In MySQL Workbench (5.2.47 CE)
click Mange Server Instances (bottom right corner)
click Connection
in the Connection box select:
Local Instance ($ServerName) - [email protected]:3306 '<'Standard(TCP/IP)>
click Edit Selected...
under Parameters, Hostname change localhost or 127.0.0.1 to your NetBIOS name
click Test Connection
If this works for you, great. If not change the hostname back to what it was.
Here are some paths for tabs:
https://codepen.io/mochime/pen/VxxzMW
<!-- left tab -->_x000D_
<div>_x000D_
<svg width="60" height="60">_x000D_
<path d="M10,10 _x000D_
a10 10 0 0 1 10 -10_x000D_
h 50 _x000D_
v 47_x000D_
h -50_x000D_
a10 10 0 0 1 -10 -10_x000D_
z"_x000D_
fill="#ff3600"></path>_x000D_
</svg>_x000D_
</div>_x000D_
_x000D_
<!-- right tab -->_x000D_
<div>_x000D_
<svg width="60" height="60">_x000D_
<path d="M10 0 _x000D_
h 40_x000D_
a10 10 0 0 1 10 10_x000D_
v 27_x000D_
a10 10 0 0 1 -10 10_x000D_
h -40_x000D_
z"_x000D_
fill="#ff3600"></path>_x000D_
</svg>_x000D_
</div>_x000D_
_x000D_
<!-- tab tab :) -->_x000D_
<div>_x000D_
<svg width="60" height="60">_x000D_
<path d="M10,40 _x000D_
v -30_x000D_
a10 10 0 0 1 10 -10_x000D_
h 30_x000D_
a10 10 0 0 1 10 10_x000D_
v 30_x000D_
z"_x000D_
fill="#ff3600"></path>_x000D_
</svg>_x000D_
</div>
_x000D_
The other answers explained the mechanics. I especially liked hossein-maktoobian's answer.
The paths in the pen do the brunt of the work, the values can be modified to suite whatever desired dimensions.
As far as I understand VS has nothing to do with TS installed by NPM. (You may notice after you install TS using NPM, there is no tsc.exe file). VS targets only tsc.exe installed by TS for VS extension, which installes TS to c:\Program Files (x86)\Microsoft SDKs\TypeScript\X.Y. You may have multiple folders under c:\Program Files (x86)\Microsoft SDKs\TypeScript. Set TypeScriptToolsVersion to the highest version installed. In my case I had folders "1.0", "1.7", "1.8", so I set TypeScriptToolsVersion = 1.8, and if you run tsc - v inside that folder you will get 1.8.3 or something, however, when u run tsc outside that folder, it will use PATH variable pointing to TS version installed by NPM, which is in my case 1.8.10. I believe TS for VS will always be a little behind the latest version of TS you install using NPM. But as far as I understand, VS doesnt know anything about TS installed by NPM, it only targets whateve versions installed by TS for VS extensions, and the version specified in TypeScriptToolsVersion in your project file.
I changed the python interpreter and it worked. On the keyboard, I pressed ctrl+shift+p. On the next window, I typed python: select interpreter, and there was an option to select the interpreter I wanted. From here, I chose the python interpreter located in my virtual environment.
In this case, it was my ~\DevFolder\myenv\scripts\python.exe
I got the same error when I ran git status :
$ git status
On branch master
Your branch is ahead of 'origin/master' by 1 commit.
(use "git push" to publish your local commits)
nothing to commit, working directory clean
To fix it I can run:
$ git push and run
$ git push heroku master
The contexts used for HTML Canvases have a built-in method for checking the size of a font. This method returns a TextMetrics
object, which has a width property that contains the width of the text.
function getWidthOfText(txt, fontname, fontsize){
if(getWidthOfText.c === undefined){
getWidthOfText.c=document.createElement('canvas');
getWidthOfText.ctx=getWidthOfText.c.getContext('2d');
}
var fontspec = fontsize + ' ' + fontname;
if(getWidthOfText.ctx.font !== fontspec)
getWidthOfText.ctx.font = fontspec;
return getWidthOfText.ctx.measureText(txt).width;
}
Or, as some of the other users have suggested, you can wrap it in a span
element:
function getWidthOfText(txt, fontname, fontsize){
if(getWidthOfText.e === undefined){
getWidthOfText.e = document.createElement('span');
getWidthOfText.e.style.display = "none";
document.body.appendChild(getWidthOfText.e);
}
if(getWidthOfText.e.style.fontSize !== fontsize)
getWidthOfText.e.style.fontSize = fontsize;
if(getWidthOfText.e.style.fontFamily !== fontname)
getWidthOfText.e.style.fontFamily = fontname;
getWidthOfText.e.innerText = txt;
return getWidthOfText.e.offsetWidth;
}
EDIT 2020: added font name+size caching at Igor Okorokov's suggestion.
This is a circle shape with icon inside:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/ok_icon"/>
<item>
<shape
android:shape="oval">
<solid android:color="@color/transparent"/>
<stroke android:width="2dp" android:color="@color/button_grey"/>
</shape>
</item>
</layer-list>
Usually you should prefer static consts. It has no disadvantage. The prprocessor should mainly be used for conditional compilation (and sometimes for really dirty trics maybe).
http://api.football-data.org/index is free and useful. The API is in active development, stable and recently the first versioned release called alpha was put online. Check the blog section to follow updates and changes.
Meanwhile there is another way of how to do it with f-strings:
cursor.execute(f"INSERT INTO table VALUES {var1}, {var2}, {var3},")
Update the data ... change button titles..whatever stuff you have to update..
then just call
[self.view setNeedsDisplay];
If none of the solutions on this page work and you are having the below issue:
You can simply use this snippet of CSS:
td {
padding: 0;
}
You could use regular expressions to count for you.
String subject = "First Line\n Second Line\nThird Line";
Matcher wordM = Pattern.compile("\\b\\S+?\\b").matcher(subject); //matches a word
Matcher charM = Pattern.compile(".").matcher(subject); //matches a character
Matcher newLineM = Pattern.compile("\\r?\\n").matcher(subject); //matches a linebreak
int words=0,chars=0,newLines=1; //newLines is initially 1 because the first line has no corresponding linebreak
while(wordM.find()) words++;
while(charM.find()) chars++;
while(newLineM.find()) newLines++;
System.out.println("Words: "+words);
System.out.println("Chars: "+chars);
System.out.println("Lines: "+newLines);
If you can use only Java 8 or lower:
1) if you don't have spring-data
the best way so far is:
opt.<Runnable>map(param -> () -> System.out.println(param))
.orElse(() -> System.out.println("no-param-specified"))
.run();
Now I know it's not so readable and even hard to understand for someone, but looks fine for me personally and I don't see another nice fluent way for this case.
2) if you're lucky enough and you can use spring-data
the best way is
Optionals#ifPresentOrElse:
Optionals.ifPresentOrElse(opt, System.out::println,
() -> System.out.println("no-param-specified"));
If you can use Java 9, you should definitely go with:
opt.ifPresentOrElse(System.out::println,
() -> System.out.println("no-param-specified"));
Assuming you want to reset your PostgreSQL database and set it back up, use:
heroku apps
to list your applications on Heroku. Find the name of your current application (application_name
). Then run
heroku config | grep POSTGRESQL
to get the name of your databases. An example could be
HEROKU_POSTGRESQL_WHITE_URL
Finally, given application_name
and database_url
, you should run
heroku pg:reset `database_url` --confirm `application_name`
heroku run rake db:migrate
heroku restart
We can use _.difference
function to see if there is any difference or not.
function isSame(arrayOne, arrayTwo) {
var a = _.uniq(arrayOne),
b = _.uniq(arrayTwo);
return a.length === b.length &&
_.isEmpty(_.difference(b.sort(), a.sort()));
}
// examples
console.log(isSame([1, 2, 3], [1, 2, 3])); // true
console.log(isSame([1, 2, 4], [1, 2, 3])); // false
console.log(isSame([1, 2], [2, 3, 1])); // false
console.log(isSame([2, 3, 1], [1, 2])); // false
// Test cases pointed by Mariano Desanze, Thanks.
console.log(isSame([1, 2, 3], [1, 2, 2])); // false
console.log(isSame([1, 2, 2], [1, 2, 2])); // true
console.log(isSame([1, 2, 2], [1, 2, 3])); // false
I hope this will help you.
Adding example link at StackBlitz
Use this query:
UPDATE `table` SET date_date=now();
Sample code can be:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("UPDATE `table` SET date_date=now()");
mysql_close($con);
?>
Try this:
function toTitleCase(str) {
return str.replace(
/\w\S*/g,
function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
}
);
}
_x000D_
<form>
Input:
<br /><textarea name="input" onchange="form.output.value=toTitleCase(this.value)" onkeyup="form.output.value=toTitleCase(this.value)"></textarea>
<br />Output:
<br /><textarea name="output" readonly onclick="select(this)"></textarea>
</form>
_x000D_
In the upper right corner of the dialog, mouse over where the button should be, and see rather or not you get some effect (the button hover). Try clicking it and seeing if it closes. If it does close, then you're just missing your image sprites that came with your package download.
Swift 3, Swift 4
if movetoroot {
navigationController?.popToRootViewController(animated: true)
} else {
navigationController?.popViewController(animated: true)
}
navigationController is optional because there might not be one.
I've never heard of such a function, but it would be trivial enough to implement...
def die(msg)
puts msg
exit
end
Then, if this is defined in some .rb file that you include in all your scripts, you are golden.... just because it's not built in doesn't mean you can't do it yourself ;-)
Enter the command which php
in the terminal to see which version of PHP you are using. If it's not the PHP version from MAMP, the $PATH variable used by Bash will need to be updated.
First, you should use command "cd /Applications/MAMP/bin/php" to check which php version from MAMP and take note of the version (eg, php5.6.7).
Once you know the version, you should edit the ~/.bash_profile
file (that is, the .bash_profile
that is in your home directory) and add an export line:
export PATH=/Applications/MAMP/bin/php/php5.6.7/bin:$PATH
Make sure that you replace php5.6.7 with the version of PHP that you have selected in MAMP.
Once the file has been saved, make sure that you close close your Terminal and open it again. Once that has been done, you will be using the PHP that ships with MAMP.
One way to easily find what the line should be that you need to put inside your .bash_profile
is to run the following command inside your terminal:
echo export PATH=`cat /Applications/MAMP/conf/apache/httpd.conf \
| grep php | grep -i LoadModule | head -n1 \
| sed -e 's/^[^\/]*\/\(.*\)\/mod.*/\/\1/'`/bin:\$PATH
Copying and pasting those three lines into your terminal will correctly output the PHP version that has been selected inside the MAMP control panel.
Make sure that your path
contains /usr/local/bin/
(Homebrew) or /opt/local/bin
(MacPorts) if you are using PHP that comes with either of these two package managers.
You can find the exact location of PHP using MacPorts with the following command:
port contents php70 | grep bin/php
Note that you should replace php70
with the version of PHP that you have installed.
Homebrew-php (https://github.com/Homebrew/homebrew-php) is a tap that has various different versions of PHP.
You can find the exact location of PHP using Homebrew with the following command:
brew --prefix homebrew/php/php56
Note that you should replace php56
with the version of PHP that you have installed.
InstallUtil classes ( ServiceInstaller ) are considered an anti-pattern by the Windows Installer community. It's a fragile, out of process, reinventing of the wheel that ignores the fact that Windows Installer has built-in support for Services.
Visual Studio deployment projects ( also not highly regarded and deprecated in the next release of Visual Studio ) do not have native support for services. But they can consume merge modules. So I would take a look at this blog article to understand how to create a merge module using Windows Installer XML that can express the service and then consume that merge module in your VDPROJ solution.
Augmenting InstallShield using Windows Installer XML - Windows Services
No, but you can use the s///
substitution operator and the \s
whitespace assertion to get the same result.
As stated, there is no non Microsoft / compiler vendor way to do this on the windows platform. However, it is obviously useful to catch these types of exceptions in the normal try { } catch (exception ex) { } way for error reporting and more a graceful exit of your app (as JaredPar says, the app is now probably in trouble). We use _se_translator_function in a simple class wrapper that allows us to catch the following exceptions in a a try handler:
DECLARE_EXCEPTION_CLASS(datatype_misalignment)
DECLARE_EXCEPTION_CLASS(breakpoint)
DECLARE_EXCEPTION_CLASS(single_step)
DECLARE_EXCEPTION_CLASS(array_bounds_exceeded)
DECLARE_EXCEPTION_CLASS(flt_denormal_operand)
DECLARE_EXCEPTION_CLASS(flt_divide_by_zero)
DECLARE_EXCEPTION_CLASS(flt_inexact_result)
DECLARE_EXCEPTION_CLASS(flt_invalid_operation)
DECLARE_EXCEPTION_CLASS(flt_overflow)
DECLARE_EXCEPTION_CLASS(flt_stack_check)
DECLARE_EXCEPTION_CLASS(flt_underflow)
DECLARE_EXCEPTION_CLASS(int_divide_by_zero)
DECLARE_EXCEPTION_CLASS(int_overflow)
DECLARE_EXCEPTION_CLASS(priv_instruction)
DECLARE_EXCEPTION_CLASS(in_page_error)
DECLARE_EXCEPTION_CLASS(illegal_instruction)
DECLARE_EXCEPTION_CLASS(noncontinuable_exception)
DECLARE_EXCEPTION_CLASS(stack_overflow)
DECLARE_EXCEPTION_CLASS(invalid_disposition)
DECLARE_EXCEPTION_CLASS(guard_page)
DECLARE_EXCEPTION_CLASS(invalid_handle)
DECLARE_EXCEPTION_CLASS(microsoft_cpp)
The original class came from this very useful article:
Like Daniel said you can run python commands directly from Matlab using the py. command. To run any of the libraries you just have to make sure Malab is running the python environment where you installed the libraries:
On a Mac:
Open a new terminal window;
type: which python (to find out where the default version of python is installed);
Restart Matlab;
For example:
py.sys.version;
py.sklearn.cluster.dbscan
You need to assign the result back to $content
as preg_replace
does not modify the original string.
$content = preg_replace("/<img[^>]+\>/i", "(image) ", $content);
There are 2 ways of doing this
foreach($questions as $key => $question){
$questions[$key]['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
}
This way you save the key, so you can update it again in the main $questions
variable
or
foreach($questions as &$question){
Adding the &
will keep the $questions
updated. But I would say the first one is recommended even though this is shorter (see comment by Paystey)
Per the PHP foreach
documentation:
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
The entire section of the switch is a single declaration context. You can't declare a variable in a case statement like that. Try this instead:
switch (val)
{
case VAL:
{
// This will work
int newVal = 42;
break;
}
case ANOTHER_VAL:
...
break;
}
I suggest you to update your SDK and start new project and recompile everything you have. It seems you have some inner program errors. Or you are missing package.
And ofc do what Abdijeek said.
You can use the following code to copy files from one directory to another
public static void copyFile(File sourceFile, File destFile) throws IOException {
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(sourceFile);
out = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
} catch(Exception e){
e.printStackTrace();
}
finally {
in.close();
out.close();
}
}
Just as another possible solution based on ES6 Set ("arr. that can contain unique values only").
Examples of usage:
// Get 4 unique rnd. numbers: from 0 until 4 (inclusive):
getUniqueNumbersInRange(4, 0, 5) //-> [5, 0, 4, 1];
// Get 2 unique rnd. numbers: from -1 until 2 (inclusive):
getUniqueNumbersInRange(2, -1, 2) //-> [1, -1];
// Get 0 unique rnd. numbers (empty result): from -1 until 2 (inclusive):
getUniqueNumbersInRange(0, -1, 2) //-> [];
// Get 7 unique rnd. numbers: from 1 until 7 (inclusive):
getUniqueNumbersInRange(7, 1, 7) //-> [ 3, 1, 6, 2, 7, 5, 4];
The implementation:
function getUniqueNumbersInRange(uniqueNumbersCount, fromInclusive, untilInclusive) {
// 0/3. Check inputs.
if (0 > uniqueNumbersCount) throw new Error('The number of unique numbers cannot be negative.');
if (fromInclusive > untilInclusive) throw new Error('"From" bound "' + fromInclusive
+ '" cannot be greater than "until" bound "' + untilInclusive + '".');
const rangeLength = untilInclusive - fromInclusive + 1;
if (uniqueNumbersCount > rangeLength) throw new Error('The length of the range is ' + rangeLength + '=['
+ fromInclusive + '…' + untilInclusive + '] that is smaller than '
+ uniqueNumbersCount + ' (specified count of result numbers).');
if (uniqueNumbersCount === 0) return [];
// 1/3. Create a new "Set" – object that stores unique values of any type, whether primitive values or object references.
// MDN - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
// Support: Google Chrome 38+(2014.10), Firefox 13+, IE 11+
const uniqueDigits = new Set();
// 2/3. Fill with random numbers.
while (uniqueNumbersCount > uniqueDigits.size) {
// Generate and add an random integer in specified range.
const nextRngNmb = Math.floor(Math.random() * rangeLength) + fromInclusive;
uniqueDigits.add(nextRngNmb);
}
// 3/3. Convert "Set" with unique numbers into an array with "Array.from()".
// MDN – https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from
// Support: Google Chrome 45+ (2015.09+), Firefox 32+, not IE
const resArray = Array.from(uniqueDigits);
return resArray;
}
The benefits of the current implementation: