Programs & Examples On #Github

GitHub is a web-based hosting service for software development projects that use Git for version control. Use this tag for questions specific to problems with repositories hosted on GitHub, features specific to GitHub and using GitHub for collaborating with other users. Do not use this tag for Git-related issues simply because a repository happens to be hosted on GitHub.

Pull new updates from original GitHub repository into forked GitHub repository

In addition to VonC's answer, you could tweak it to your liking even further.

After fetching from the remote branch, you would still have to merge the commits. I would replace

$ git fetch upstream

with

$ git pull upstream master

since git pull is essentially git fetch + git merge.

What is the difference between README and README.md in GitHub projects?

README.md or .mkdn or .markdown denotes that the file is markdown formatted. Markdown is a markup language. With it you can easily display headers or have italic words, or bold or almost anything that can be done to text

How to state in requirements.txt a direct github source

Normally your requirements.txt file would look something like this:

package-one==1.9.4
package-two==3.7.1
package-three==1.0.1
...

To specify a Github repo, you do not need the package-name== convention.

The examples below update package-two using a GitHub repo. The text between @ and # denotes the specifics of the package.

Specify commit hash (41b95ec in the context of updated requirements.txt):

package-one==1.9.4
git+git://github.com/path/to/package-two@41b95ec#egg=package-two
package-three==1.0.1

Specify branch name (master):

git+git://github.com/path/to/package-two@master#egg=package-two

Specify tag (0.1):

git+git://github.com/path/to/[email protected]#egg=package-two

Specify release (3.7.1):

git+git://github.com/path/to/package-two@releases/tag/v3.7.1#egg=package-two

Note that #egg=package-two is not a comment here, it is to explicitly state the package name

This blog post has some more discussion on the topic.

How to remove a directory from git repository?

One of my colleague suggested BFG Repo-Cleaner which I think powerful. It is not only delete unwanted data but also clean your repository from any related commit information.

Issue in installing php7.2-mcrypt

I followed below steps to install mcrypt for PHP7.2 using PECL.

  1. Install PECL

apt-get install php-pecl

  1. Before installing MCRYPT you must install libmcrypt

apt-get install libmcrypt-dev libreadline-dev

  1. Install MCRYPT 1.0.1 using PECL

pecl install mcrypt-1.0.1

  1. After the successful installation

You should add "extension=mcrypt.so" to php.ini

Please comment below if you need any assistance. :-)

IMPORTANT !

According to php.net reference many (all) mcrypt functions have been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Git: Pull from other remote

upstream in the github example is just the name they've chosen to refer to that repository. You may choose any that you like when using git remote add. Depending on what you select for this name, your git pull usage will change. For example, if you use:

git remote add upstream git://github.com/somename/original-project.git

then you would use this to pull changes:

git pull upstream master

But, if you choose origin for the name of the remote repo, your commands would be:

To name the remote repo in your local config: git remote add origin git://github.com/somename/original-project.git

And to pull: git pull origin master

How to add empty spaces into MD markdown readme on GitHub?

Markdown really changes everything to html and html collapses spaces so you really can't do anything about it. You have to use the   for it. A funny example here that I'm writing in markdown and I'll use couple of         here.

Above there are some   without backticks

Unable to Connect to GitHub.com For Cloning

I had the same error because I was using proxy. As the answer is given but in case you are using proxy then please set your proxy first using these commands:

git config --global http.proxy http://proxy_username:proxy_password@proxy_ip:port
git config --global https.proxy https://proxy_username:proxy_password@proxy_ip:port

Change name of folder when cloning from GitHub?

Here is one more answer from @Marged in comments

  1. Create a folder with the name you want
  2. Run the command below from the folder you created

    git clone <path to your online repo> .
    

Remove directory from remote repository after adding them to .gitignore

The rules in your .gitignore file only apply to untracked files. Since the files under that directory were already committed in your repository, you have to unstage them, create a commit, and push that to GitHub:

git rm -r --cached some-directory
git commit -m 'Remove the now ignored directory "some-directory"'
git push origin master

You can't delete the file from your history without rewriting the history of your repository - you shouldn't do this if anyone else is working with your repository, or you're using it from multiple computers. If you still want to do that, you can use git filter-branch to rewrite the history - there is a helpful guide to that here.

Additionally, note the output from git rm -r --cached some-directory will be something like:

rm 'some-directory/product/cache/1/small_image/130x130/small_image.jpg'
rm 'some-directory/product/cache/1/small_image/135x/small_image.jpg'
rm 'some-directory/.htaccess'
rm 'some-directory/logo.jpg'

The rm is feedback from git about the repository; the files are still in the working directory.

.gitignore after commit

I had to remove .idea and target folders and after reading all comments this worked for me:

git rm -r .idea
git rm -r target
git commit -m 'removed .idea folder'

and then push to master

Github Push Error: RPC failed; result=22, HTTP code = 413

I figured it out!!! Of course I would right after I hit post!

I had the repo set to use the HTTPS url, I changed it to the SSH address, and everything resumed working flawlessly.

Git Clone - Repository not found

You may need to create an empty file named git-daemon-export-ok within the repository directory.

How to resolve "git pull,fatal: unable to access 'https://github.com...\': Empty reply from server"

I had tried most of the answers here but didn't manage to resolve the issue (on Windows 10).

What resolved the problem was simply to upgrade version from git version 2.8.1.windows.1 to the latest version git version 2.10.1.windows.1

Git: force user and password prompt

Add a -v flag with your git command . e.g. git pull -v

v stands for verify .

Renaming a branch in GitHub

Three simple steps

  • git push origin head

  • git branch -m old-branch-name new-branch-name

  • git push origin head

Is it possible to find out the users who have checked out my project on GitHub?

If by "checked out" you mean people who have cloned your project, then no it is not possible. You don't even need to be a GitHub user to clone a repository, so it would be infeasible to track this.

github changes not staged for commit

WARNING! THIS WILL DELETE THE ENTIRE GIT HISTORY FOR YOUR SUBMODULE. ONLY DO THIS IF YOU CREATED THE SUBMODULE BY ACCIDENT. CERTAINLY NOT WHAT YOU WANT TO DO IN MOST CASES.

In my situation, there was a sub-directory which had a .git directory.

What I do is simply remove that .git directory from my sub-directory.

How to pull remote branch from somebody else's repo

git remote add coworker git://path/to/coworkers/repo.git
git fetch coworker
git checkout --track coworker/foo

This will setup a local branch foo, tracking the remote branch coworker/foo. So when your co-worker has made some changes, you can easily pull them:

git checkout foo
git pull

Response to comments:

Cool :) And if I'd like to make my own changes to that branch, should I create a second local branch "bar" from "foo" and work there instead of directly on my "foo"?

You don't need to create a new branch, even though I recommend it. You might as well commit directly to foo and have your co-worker pull your branch. But that branch already exists and your branch foo need to be setup as an upstream branch to it:

git branch --set-upstream foo colin/foo

assuming colin is your repository (a remote to your co-workers repository) defined in similar way:

git remote add colin git://path/to/colins/repo.git

How to add color to Github's README.md file

You cannot color plain text in a GitHub README.md file. You can however add color to code samples with the tags below.

To do this just add tags such as these samples to your README.md file:

```json
   // code for coloring
```
```html
   // code for coloring
```
```js
   // code for coloring
```
```css
   // code for coloring
```
// etc.

No "pre" or "code" tags needed.

This is covered in the GitHub Markdown documentation (about half way down the page, there's an example using Ruby). GitHub uses Linguist to identify and highlight syntax - you can find a full list of supported languages (as well as their markdown keywords) over in the Linguist's YAML file.

How to do a GitHub pull request

I wrote a bash program that does all the work of setting up a PR branch for you. It performs forking if needed, syncing with the upstream, setting up upstream remote, etc. and you just need to commit your modifications, push and submit a PR.

Here is how you run it:

github-make-pr-branch ssh your-github-username orig_repo_user orig_repo_name new-feature

You will find the program here and its repository also includes a step-by-step guide to performing the same process manually if you'd like to understand how it works, and also extra information on how to keep your feature branch up-to-date with the upstream master and other useful tidbits.

How to show math equations in general github's markdown(not github's blog)

Markdown supports inline HTML. Inline HTML can be used for both quick and simple inline equations and, with and external tool, more complex rendering.

Quick and Simple Inline

For quick and simple inline items use HTML ampersand entity codes. An example that combines this idea with subscript text in markdown is: h?(x) = ?o x + ?1x, the code for which follows.

    h<sub>&theta;</sub>(x) = &theta;<sub>o</sub> x + &theta;<sub>1</sub>x

HTML ampersand entity codes for common math symbols can be found here. Codes for Greek letters here.

While this approach has limitations it works in practically all markdown and does not require any external libraries.

Complex Scalable Inline Rendering with LaTeX and Codecogs

If your needs are greater use an external LaTeX renderer like CodeCogs. Create an equation with CodeCogs editor. Choose svg for rendering and HTML for the embed code. Svg renders well on resize. HTML allows LaTeX to be easily read when you are looking at the source. Copy the embed code from the bottom of the page and paste it into your markdown.

<img src="https://latex.codecogs.com/svg.latex?\Large&space;x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}" title="\Large x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}" />

Expressed in markdown becomes

![\Large x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}](https://latex.codecogs.com/svg.latex?\Large&space;x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}) 

\Large x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}

This combines this answer and this answer.

GitHub support only somtimes worked using the above raw html syntax for readable LaTeX for me. If the above does not work for you another option is to instead choose URL Encoded rendering and use that output to manually create a link like:

\Large x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}

![\Large x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}](https://latex.codecogs.com/svg.latex?x%3D%5Cfrac%7B-b%5Cpm%5Csqrt%7Bb%5E2-4ac%7D%7D%7B2a%7D)

This manually incorporates LaTex in the alt image text and uses an encoded URL for rendering on GitHub.

Multi-line Rendering

If you need multi-line rendering check out this answer.

How do I update a GitHub forked repository?

Assuming your fork is https://github.com/me/foobar and original repository is https://github.com/someone/foobar

  1. Visit https://github.com/me/foobar/compare/master...someone:master

  2. If you see green text Able to merge then press Create pull request

  3. On the next page, scroll to the bottom of the page and click Merge pull request and Confirm merge.

Pushing to Git returning Error Code 403 fatal: HTTP request failed

To definitely be able to login using https protocol, you should first set your authentication credential to the git Remote URI:

git remote set-url origin https://[email protected]/user/repo.git

Then you'll be asked for a password when trying to git push.

In fact, this is on the http authentication format. You could set a password too:

https://youruser:[email protected]/user/repo.git

You should be aware that if you do this, your github password will be stored in plaintext in your .git directory, which is obviously undesirable.

How do I set up Eclipse/EGit with GitHub?

Install Mylyn connector for GitHub from this update site, it provides great integration: you can directly import your repositories using Import > Projects from Git > GitHub. You can set the default repository folder in Preferences > Git.

Git: Could not resolve host github.com error while cloning remote repository in git

Based on other solutions, what worked for me :

1. writing this in terminal :

git config --global --unset http.proxy
git config --global --unset https.proxy

2. restart - router restart - mac

You can first try -2- , If that not working, then try -1- and -2-

How to download source in ZIP format from GitHub?

As of December 2016, the Clone or download button is still under the <> Code tab, however it is now to the far right of the header:

Github Clone or download screenshot

How do I reverse a commit in git?

Or you can try using git revert http://www.kernel.org/pub/software/scm/git/docs/git-revert.html. I think something like git revert HEAD~1 -m 1 will revert your last commit (if it's still the last commit).

How can I see the size of a GitHub repository before cloning it?

If you're trying to find out the size of your own repositories.

All you have to do is go to GitHub settings repositories and you see all the sizes right there in the browser no extra work needed.

https://github.com/settings/repositories

GitHub - failed to connect to github 443 windows/ Failed to connect to gitHub - No Error

Well I did following steps

  1. Google the error

  2. Got to SO Links(here, here) which suggested the same thing, that I have to update the Git Config for proxy setting

  3. Damn, can not see proxy information from control panel. IT guys must have hidden it. I can not even change the setting to not to use proxy.

  4. Found this wonderful tutorial of finding which proxy your are connected to

  5. Updated the http.proxy key in git config by following command

git config --global http.proxy http[s]://userName:password@proxyaddress:port

  1. Error - could not resolve proxy some@proxyaddress:port. It turned out my password had @ symbol in it.

  2. Encode @ in your password to %40, because git splits the proxy setting by @

  3. If your userName is a email address, which has @, also encode it to %40. (see this answer)

git config --global http.proxy http[s]://userName(encoded):password(encoded)@proxyaddress:port

Baam ! It worked !

Note - I just wanted to answer this question for souls like me, who would come looking for answer on SO :D

How to upload folders on GitHub

You can also use the command line, Change directory where your folder is located then type the following :

     git init
     git add <folder1> <folder2> <etc.>
     git commit -m "Your message about the commit"
     git remote add origin https://github.com/yourUsername/yourRepository.git
     git push -u origin master
     git push origin master  

Using an image caption in Markdown Jekyll

You can use table for this. It works fine.

| ![space-1.jpg](http://www.storywarren.com/wp-content/uploads/2016/09/space-1.jpg) | 
|:--:| 
| *Space* |

Result:

enter image description here

Is it possible to create a remote repo on GitHub from the CLI without opening browser?

For all the Python 2.7.* users. There is a Python wrapper around the Github API that is currently on Version 3, called GitPython. Simply install using easy_install PyGithub or pip install PyGithub.

from github import Github
g = Github(your-email-addr, your-passwd)
repo = g.get_user().user.create_repo("your-new-repos-name")

# Make use of Repository object (repo)

The Repository object docs are here.

SSH Key - Still asking for password and passphrase

I had to execute:

eval `ssh-agent -s`
ssh-add

Note: You will have to do this again after every restart. If you want to avoid it, then enter it in your ".bashrc" file which is in C:\Users\<<USERNAME>>\.bashrc on windows. It is probably hidden, so make sure that you can see hidden files.

Solution found here.

git status shows fatal: bad object HEAD

In my case the error came out of nowhere, but didn't let me push to the remote branch.

git fetch origin

And that solved it.

I agree this may not solve the issue for everyone, but before trying a more complex approach give it a shot at this one, nothing to loose.

Pushing from local repository to GitHub hosted remote

open the command prompt Go to project directory

type git remote add origin your git hub repository location with.git

Can you issue pull requests from the command line on GitHub?

I ended up making my own, I find that it works better the other solutions that were around.

https://npmjs.org/package/pullr

How do I merge a specific commit from one branch into another in Git?

If BranchA has not been pushed to a remote then you can reorder the commits using rebase and then simply merge. It's preferable to use merge over rebase when possible because it doesn't create duplicate commits.

git checkout BranchA
git rebase -i HEAD~113
... reorder the commits so the 10 you want are first ...
git checkout BranchB
git merge [the 10th commit]

How can I check out a GitHub pull request with git?

I prefer to fetch and checkout without creating a local branch and to be in HEAD detached state. It allows me quickly to check the pull request without polluting my local machine with unnecessary local branches.

git fetch upstream pull/ID/head && git checkout FETCH_HEAD

where ID is a pull request ID and upstream where is original pull request has been created (it could be origin, for example).

I hope it helps.

"Auth Failed" error with EGit and GitHub

I resolved it by selecting https as the protocol and then adding my github username and password

How do I clone a github project to run locally?

I use @Thiho answer but i get this error:

'git' is not recognized as an internal or external command

For solving that i use this steps:

I add the following paths to PATH:

  • C:\Program Files\Git\bin\

  • C:\Program Files\Git\cmd\

In windows 7:

  1. Right-click "Computer" on the Desktop or Start Menu.
  2. Select "Properties".
  3. On the very far left, click the "Advanced system settings" link.
  4. Click the "Environment Variables" button at the bottom.
  5. Double-click the "Path" entry under "System variables".
  6. At the end of "Variable value", insert a ; if there is not already one, and then C:\Program Files\Git\bin\;C:\Program Files\Git\cmd. Do not put a space between ; and the entry.

Finally close and re-open your console.

How can I reference a commit in an issue comment on GitHub?

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).

enter image description here

Hope this saves you some time.

GitHub - error: failed to push some refs to '[email protected]:myrepo.git'

you can write in your console:

git pull origin

then press TAB and write your "master" repository

How do I push to GitHub under a different username?

git add .
git commit -m "initial commit"
git config --local credential.helper ""
git push https://github.com/youraccount/repo.git --all

After this push command, a username password prompt will be opened.

How to download a folder from github?

If you want to automate the steps, the suggestions here will work only to an extent.

I came across this tool called fetch and it worked quite fine for me. You can even specify the release. So, it takes a step to download and set it as executable, then fetch the required folder:

curl -sSLfo ./fetch \
https://github.com/gruntwork-io/fetch/releases/download/v0.3.12/fetch_linux_amd64
chmod +x ./fetch
./fetch --repo="https://github.com/foo/bar" --tag="${VERSION}" --source-path="/baz" /tmp/baz

Git adding files to repo

my problem (git on macOS) was solved by using sudo git instead of just git in all add and commit commands

Resize image in the wiki of GitHub using Markdown

GitHub Pages now uses kramdown as its markdown engine so you can use the following syntax:

Here is an inline ![smiley](smiley.png){:height="36px" width="36px"}.

http://kramdown.gettalong.org/syntax.html#images

I haven't tested it on GitHub wiki though.

Change Git repository directory location.

This did not work for me. I moved a repo from (e.g.) c:\project1\ to c:\repo\project1\ and Git for windows does not show any changes.

git status shows an error because one of the submodules "is not a git repository" and shows the old path. e.g. (names changed to protect IP)

fatal: Not a git repository: C:/project1/.git/modules/subproject/subproject2 fatal: 'git status --porcelain' failed in submodule subproject

I had to manually edit the .git files in the submodules to point to the correct relative path to the submodule's repo (in the main repo's .git/modules directory)

Trying to pull files from my Github repository: "refusing to merge unrelated histories"

When I used --allow-unrelated-histories, this command generated too many conflicts. There were conflicts in files which I didn't even work on. To get over the error " Refusing to merge unrelated histories", I used following rebase command:

git pull --rebase=preserve --allow-unrelated-histories

After this commit the uncommitted changes with a commit message. Finally, run the following command:

git rebase --continue

After this, my working copy was up-to-date with the remote copy and I was able to push my changes as before. No more unrelated histories error while pulling.

Git credential helper - update password

Solution using command line for Windows, Linux, and MacOS

If you have updated your GitHub password on the GitHub server, in the first attempt of the git fetch/pull/push command it generates the authentication failed message.

Execute the same git fetch/pull/push command a second time and it prompts for credentials (username and password). Enter the username and the new updated password of the GitHub server and login will be successful.

Even I had this problem, and I performed the above steps and done!!

git clone error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 10054

All these tips did not work for me, what worked was cloning over ssh rather that http

Jenkins - how to build a specific branch

enter image description here

There will be an option in configure under Build Triggers

Check the GitHub Branches

A hook will be created and then you can build any branch you like from Jenkins when you select github Branches enter image description here

Hope it helps :)

How to use 'git pull' from the command line?

Open up your git bash and type

echo $HOME

This shall be the same folder as you get when you open your command window (cmd) and type

echo %USERPROFILE%

And – of course – the .ssh folder shall be present on THAT directory.

Include an SVG (hosted on GitHub) in MarkDown

Use this site: https://rawgit.com , it works for me as I don't have permission issue with the svg file.
Please pay attention that RawGit is not a service of github, as mentioned in Rawgit FAQ :

RawGit is not associated with GitHub in any way. Please don't contact GitHub asking for help with RawGit

Enter the url of svg you need, such as :

https://github.com/sel-fish/redis-experiments/blob/master/dat/memDistrib-jemalloc-4.0.3.svg

Then, you can get the url bellow which can be used to display:

https://cdn.rawgit.com/sel-fish/redis-experiments/master/dat/memDistrib-jemalloc-4.0.3.svg

There is no tracking information for the current branch

With Git 2.24, you won't have to do

git branch --set-upstream-to=origin/master master
git pull

You will be able to do:

git pull --set-upstream-to=origin/master master

See more at "default remote and branch using -u option - works with push but not pull".

Git: Installing Git in PATH with GitHub client for Windows

If you are using vscode's terminal then it might not work even if you do the environment variable thing, test by typing git

Restart vscode, it should work.

How to remove a branch locally?

You can delete multiple branches on windows using Git GUI:

  1. Go to your Project folder
  2. Open Git Gui: enter image description here
  3. Click on 'Branch': enter image description here
  4. Now choose 'Delete': enter image description here
  5. If you want to delete all branches besides the fact they are merged or not, then check 'Always (Do not perform merge checks)' enter image description here

Download a single folder or directory from a GitHub repo

If the directoy you want to download is a separated library, it's better to create an other git repo, and then to use the git submodule function.

Of course, you have to be the owner of the initial repo you want

Can't clone a github repo on Linux via HTTPS

I had to specify user name to work on 1.7.1 git version:

git remote set-url origin https://[email protected]/org/project.git

How to merge remote changes at GitHub?

When I got this error, I backed up my entire project folder. Then I did something like

$ git config branch.master.remote origin
$ git config branch.master.merge refs/heads/master

...depending on your branch name (if it's not master).

Then I did git pull --rebase. After that, I replaced the pulled files with my backed-up project's files. Now I am ready to commit my changes again and push.

Git: How to remove proxy

You config proxy settings for some network and now you connect another network. Now have to remove the proxy settings. For that use these commands:

git config --global --unset https.proxy
git config --global --unset http.proxy

Now you can push too. (If did not remove proxy configuration still you can use git commands like add , commit and etc)

Git push requires username and password

For Windows Git users, after running git config --global credential.helper store, if it still prompts for a password, you'd better check where the configuration file is written to, using this command

git config --list --show-origin

In my case, after manually editing configuration file 'C:\Program Files\Git\mingw64\etc\gitconfig', and adding the following text, it worked.

[credential]
    helper = store

git diff between cloned and original remote repository

1) Add any remote repositories you want to compare:

git remote add foobar git://github.com/user/foobar.git

2) Update your local copy of a remote:

git fetch foobar

Fetch won't change your working copy.

3) Compare any branch from your local repository to any remote you've added:

git diff master foobar/master

Github: Can I see the number of downloads for a repo?

As mentioned, GitHub API returns downloads count of binary file releases. I developed a little script to easly get downloads count by command line.

How to sync with a remote Git repository?

For Linux:

git add * 
git commit -a --message "Initial Push All"
git push -u origin --all

Copy a git repo without history

#!/bin/bash
set -e

# Settings
user=xxx
pass=xxx
dir=xxx
repo_src=xxx
repo_trg=xxx
src_branch=xxx

repo_base_url=https://$user:[email protected]/$user
repo_src_url=$repo_base_url/$repo_src.git
repo_trg_url=$repo_base_url/$repo_trg.git

echo "Clone Source..."
git clone --depth 1 -b $src_branch $repo_src_url $dir

echo "CD"
cd ./$dir

echo "Remove GIT"
rm -rf .git

echo "Init GIT"
git init
git add .
git commit -m "Initial Commit"
git remote add origin $repo_trg_url

echo "Push..."
git push -u origin master

Git pull a certain branch from GitHub

But I get an error "! [rejected]" and something about "non fast forward"

That's because Git can't merge the changes from the branches into your current master. Let's say you've checked out branch master, and you want to merge in the remote branch other-branch. When you do this:

$ git pull origin other-branch

Git is basically doing this:

$ git fetch origin other-branch && git merge other-branch

That is, a pull is just a fetch followed by a merge. However, when pull-ing, Git will only merge other-branch if it can perform a fast-forward merge. A fast-forward merge is a merge in which the head of the branch you are trying to merge into is a direct descendent of the head of the branch you want to merge. For example, if you have this history tree, then merging other-branch would result in a fast-forward merge:

O-O-O-O-O-O
^         ^
master    other-branch

However, this would not be a fast-forward merge:

    v master
O-O-O
\
 \-O-O-O-O
         ^ other-branch

To solve your problem, first fetch the remote branch:

$ git fetch origin other-branch

Then merge it into your current branch (I'll assume that's master), and fix any merge conflicts:

$ git merge origin/other-branch
# Fix merge conflicts, if they occur
# Add merge conflict fixes
$ git commit    # And commit the merge!

How can I rollback a git repository to a specific commit?

git reset --hard <old-commit-id>
git push -f <remote-name> <branch-name>

Note: As written in comments below, Using this is dangerous in a collaborative environment: you're rewriting history

Why is Github asking for username/password when following the instructions on screen and pushing a new repo?

If you've enabled two factor authentication, then you'll need to generate a personal access token and use that instead of your regular password. More info here: https://help.github.com/articles/creating-an-access-token-for-command-line-use/

How to unmerge a Git merge?

git revert -m allows to un-merge still keeping the history of both merge and un-do operation. Might be good for documenting probably.

Is there a way to represent a directory tree in a Github README.md?

If you are working on windows write tree /f inside the directory you want to achieve that in command prompt. This should do your job. you can copy and paste the output on markdown surrounded my triple back ticks i.e. '''{tree structure here}'''

Git Clone from GitHub over https with two-factor authentication

1st: Get personal access token. https://github.com/settings/tokens
2nd: Put account & the token. Example is here:

$ git push
Username for 'https://github.com':            # Put your GitHub account name
Password for 'https://{USERNAME}@github.com': # Put your Personal access token

Link on how to create a personal access token: https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line

Warning: Permanently added the RSA host key for IP address

I solved it by using git push -u origin master

Jenkins: Failed to connect to repository

Check with below settings. That always work for me.

Jenkins Configuration :

1) Check whether git executable is appropriately specified

2) Provide SSH repository link git@blahblah

3) Under credentials >> Select Username and Authentication key (go to your server, Generate SSH keys ssh-keygen... Copy keys to JENKINS_HOME/,ssh) You should be able to connect to your GIT repository from Jenkins

Saving ssh key fails

I was using bash on windows that came with git. The problem was I assumed the tilde (~) which I was using to denote my home path would expand properly. It does work when using cd, but to fix this error I had to just give it the absolute path.

Does the target directory for a git clone have to match the repo name?

Yes, it is possible:

git clone https://github.com/pitosalas/st3_packages Packages 

You can specify the local root directory when using git clone.

<directory> 

The name of a new directory to clone into.
The "humanish" part of the source repository is used if no directory is explicitly given (repo for /path/to/repo.git and foo for host.xz:foo/.git).
Cloning into an existing directory is only allowed if the directory is empty.


As Chris comments, you can then rename that top directory.
Git only cares about the .git within said top folder, which you can get with various commands:

git rev-parse --show-toplevel git rev-parse --git-dir 

How to style a JSON block in Github Wiki?

```javascript
{ "some": "json" }
```

I tried using json but didn't like the way it looked. javascript looks a bit more pleasing to my eye.

In Jenkins, how to checkout a project into a specific directory (using GIT)

The default git plugin for Jenkins does the job quite nicely.

After adding a new git repository (project configuration > Source Code Management > check the GIT option) to the project navigate to the bottom of the plugin settings, just above Repository browser region. There should be an Advanced button. After clicking it a new form should appear, with a value described as Local subdirectory for repo (optional). Setting this to folder will make the plugin to check out the repository into the folder relative to your workspace. This way you can have as many repositories in your project as you need, all in separate locations.

Alternatively, if the project you're using will allow that, you can use GIT sub modules, which are similar to external paths in SVN. In the GIT Book there is a section on that very topic. If that will not be against some policy, submodules are fairly simple to use, giving you powerful way to control the locations, versions/tags/branches that will be imported AND it will be available on your local repository as well giving you better portability.

Obviously the GIT plugin supports checking out submodules, so Jenkins can work with them quite effectively.

GitHub "fatal: remote origin already exists"

The concept of remote is simply the URL of your remote repository.

The origin is an alias pointing to that URL. So instead of writing the whole URL every single time we want to push something to our repository, we just use this alias and run:

git push -u origin master

Telling to git to push our code from our local master branch to the remote origin repository.

Whenever we clone a repository, git creates this alias for us by default. Also whenever we create a new repository, we just create it our self.

Whatever the case it is, we can always change this name to anything we like, running this:

git remote rename [current-name] [new-name]

Since it is stored on the client side of the git application (on our machine) changing it will not affect anything in our development process, neither at our remote repository. Remember, it is only a name pointing to an address.

The only thing that changes here by renaming the alias, is that we have to declare this new name every time we push something to our repository.

git push -u my-remote-alias master

Obviously a single name can not point to two different addresses. That's why you get this error message. There is already an alias named origin at your local machine. To see how many aliases you have and what are they, you can initiate this command:

git remote -v

This will show you all the aliases you have plus the corresponding URLs.

You can remove them as well if you like running this:

git remote rm my-remote-alias

So in brief:

  • find out what do you have already,
  • remove or rename them,
  • add your new aliases.

Happy coding.

Why Git is not allowing me to commit even after configuration?

You're setting the global git options, but the local checkout possibly has overrides set. Try setting them again with git config --local <setting> <value>. You can look at the .git/config file in your local checkout to see what local settings the checkout has defined.

How to find out "The most popular repositories" on Github?

Ranking by stars or forks is not working. Each promoted or created by a famous company repository is popular at the beginning. Also it is possible to have a number of them which are in trend right now (publications, marketing, events). It doesn't mean that those repositories are useful/popular.

The gitmostwanted.com project (repo at github) analyses GH Archive data in order to highlight the most interesting repositories and exclude others. Just compare the results with mentioned resources.

Git error: "Please make sure you have the correct access rights and the repository exists"

For me it was because of no SSH key on the machine. Check the SSH key locally:

$ cat ~/.ssh/id_rsa.pub

This is your SSH key. Add it to your SSH keys in the repository.
In gitlab go to

profile settings -> SSH Keys

and add the key

Git pull till a particular commit

If you merge a commit into your branch, you should get all the history between.

Observe:

$ git init ./
Initialized empty Git repository in /Users/dfarrell/git/demo/.git/
$ echo 'a' > letter
$ git add letter
$ git commit -m 'Initial Letter'
[master (root-commit) 6e59e76] Initial Letter
 1 file changed, 1 insertion(+)
 create mode 100644 letter
$ echo 'b' >> letter
$ git add letter && git commit -m 'Adding letter'
[master 7126e6d] Adding letter
 1 file changed, 1 insertion(+)
$ echo 'c' >> letter; git add letter && git commit -m 'Adding letter'
[master f2458be] Adding letter
 1 file changed, 1 insertion(+)
$ echo 'd' >> letter; git add letter && git commit -m 'Adding letter'
[master 7f77979] Adding letter
 1 file changed, 1 insertion(+)
$ echo 'e' >> letter; git add letter && git commit -m 'Adding letter'
[master 790eade] Adding letter
 1 file changed, 1 insertion(+)
$ git log
commit 790eade367b0d8ab8146596cd717c25fd895302a
Author: Dan Farrell 
Date:   Thu Jul 16 14:21:26 2015 -0500

    Adding letter

commit 7f77979efd17f277b4be695c559c1383d2fc2f27
Author: Dan Farrell 
Date:   Thu Jul 16 14:21:24 2015 -0500

    Adding letter

commit f2458bea7780bf09fe643095dbae95cf97357ccc
Author: Dan Farrell 
Date:   Thu Jul 16 14:21:19 2015 -0500

    Adding letter

commit 7126e6dcb9c28ac60cb86ae40fb358350d0c5fad
Author: Dan Farrell 
Date:   Thu Jul 16 14:20:52 2015 -0500

    Adding letter

commit 6e59e7650314112fb80097d7d3803c964b3656f0
Author: Dan Farrell 
Date:   Thu Jul 16 14:20:33 2015 -0500

    Initial Letter
$ git checkout 6e59e7650314112fb80097d7d3803c964b3656f
$ git checkout 7126e6dcb9c28ac60cb86ae40fb358350d0c5fad
Note: checking out '7126e6dcb9c28ac60cb86ae40fb358350d0c5fad'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b new_branch_name

HEAD is now at 7126e6d... Adding letter
$ git checkout -b B 7126e6dcb9c28ac60cb86ae40fb358350d0c5fad
Switched to a new branch 'B'
$ git pull 790eade367b0d8ab8146596cd717c25fd895302a
fatal: '790eade367b0d8ab8146596cd717c25fd895302a' does not appear to be a git repository
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
$ git merge 7f77979efd17f277b4be695c559c1383d2fc2f27
Updating 7126e6d..7f77979
Fast-forward
 letter | 2 ++
 1 file changed, 2 insertions(+)
$ cat letter
a
b
c
d

Track a new remote branch created on GitHub

git fetch
git branch --track branch-name origin/branch-name

First command makes sure you have remote branch in local repository. Second command creates local branch which tracks remote branch. It assumes that your remote name is origin and branch name is branch-name.

--track option is enabled by default for remote branches and you can omit it.

Git Bash: Could not open a connection to your authentication agent

above solution doesn't work for me for unknown reason. below is my workaround which was worked successfully.

1) DO NOT generate a new ssh key by using command ssh-keygen -t rsa -C"[email protected]", you can delete existing SSH keys.

2) but use Git GUI, -> "Help" -> "Show ssh key" -> "Generate key", the key will saved to ssh automatically and no need to use ssh-add anymore.

Link and execute external JavaScript file hosted on GitHub

I found the error was shown due to the comments at the beginning of file , You can solve this issue , by simply creating your own file without comment and push to git, it shows no error

For proof you can try these two file with same code of easy pagination :

without comment

with comment

! [rejected] master -> master (fetch first)

You should use git pull, that´s command do a git fetch and next do the git merge.

If you use a git push origin master --force command, you may have problems in the future.

Jenkins returned status code 128 with github

Also make sure you using the ssh github url and not the https

Remove a modified file from pull request

A pull request is just that: a request to merge one branch into another.

Your pull request doesn't "contain" anything, it's just a marker saying "please merge this branch into that one".

The set of changes the PR shows in the web UI is just the changes between the target branch and your feature branch. To modify your pull request, you must modify your feature branch, probably with a force push to the feature branch.

In your case, you'll probably want to amend your commit. Not sure about your exact situation, but some combination of interactive rebase and add -p should sort you out.

Understanding the basics of Git and GitHub

  1. What is the difference between Git and GitHub?

    Git is a distributed version control system. It usually runs at the command line of your local machine. It keeps track of your files and modifications to those files in a "repository" (or "repo"), but only when you tell it to do so. (In other words, you decide which files to track and when to take a "snapshot" of any modifications.)

    In contrast, GitHub is a website that allows you to publish your Git repositories online, which can be useful for many reasons (see #3).

  2. Is Git saving every repository locally (in the user's machine) and in GitHub?

    Git is known as a "distributed" (rather than "centralized") version control system because you can run it locally and disconnected from the Internet, and then "push" your changes to a remote system (such as GitHub) whenever you like. Thus, repo changes only appear on GitHub when you manually tell Git to push those changes.

  3. Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?

    Yes, you can use Git without GitHub. Git is the "workhorse" program that actually tracks your changes, whereas GitHub is simply hosting your repositories (and provides additional functionality not available in Git). Here are some of the benefits of using GitHub:

    • It provides a backup of your files.
    • It gives you a visual interface for navigating your repos.
    • It gives other people a way to navigate your repos.
    • It makes repo collaboration easy (e.g., multiple people contributing to the same project).
    • It provides a lightweight issue tracking system.
  4. How does Git compare to a backup system such as Time Machine?

    Git does backup your files, though it gives you much more granular control than a traditional backup system over what and when you backup. Specifically, you "commit" every time you want to take a snapshot of changes, and that commit includes both a description of your changes and the line-by-line details of those changes. This is optimal for source code because you can easily see the change history for any given file at a line-by-line level.

  5. Is this a manual process, in other words if you don't commit you won't have a new version of the changes made?

    Yes, this is a manual process.

  6. If are not collaborating and you are already using a backup system why would you use Git?

    • Git employs a powerful branching system that allows you to work on multiple, independent lines of development simultaneously and then merge those branches together as needed.
    • Git allows you to view the line-by-line differences between different versions of your files, which makes troubleshooting easier.
    • Git forces you to describe each of your commits, which makes it significantly easier to track down a specific previous version of a given file (and potentially revert to that previous version).
    • If you ever need help with your code, having it tracked by Git and hosted on GitHub makes it much easier for someone else to look at your code.

For getting started with Git, I recommend the online book Pro Git as well as GitRef as a handy reference guide. For getting started with GitHub, I like the GitHub's Bootcamp and their GitHub Guides. Finally, I created a short videos series to introduce Git and GitHub to beginners.

Why does GitHub recommend HTTPS over SSH?

Either you are quoting wrong or github has different recommendation on different pages or they may learned with time and updated their reco.

We strongly recommend using an SSH connection when interacting with GitHub. SSH keys are a way to identify trusted computers, without involving passwords. The steps below will walk you through generating an SSH key and then adding the public key to your GitHub account.

https://help.github.com/articles/generating-ssh-keys

Superscript in markdown (Github flavored)?

Use the <sup></sup>tag (<sub></sub> is the equivalent for subscripts). See this gist for an example.

Put current changes in a new Git branch

You can simply check out a new branch, and then commit:

git checkout -b my_new_branch
git commit

Checking out the new branch will not discard your changes.

Search code inside a Github project

I search the source code inside of Github Repositories with the free Sourcegraph Chrome Extension ... But I Downloaded Chrome First, I knew other browsers support it though, such as - and maybe just only - Firefox.

I skimmed through SourceForge's Chrome Extension Docs and then also I looked at just what I needed for searching for directory names with Github's Search Engine itself, by reading some of Github's Codebase Searching Doc

Failed to add the host to the list of know hosts

Okay so ideal permissions look like this
For ssh directory (You can get this by typing ls -ld ~/.ssh/)
drwx------ 2 oroborus oroborus 4096 Nov 28 12:05 /home/oroborus/.ssh/

d means directory, rwx means the user oroborus has read write and execute permission. Here oroborus is my computer name, you can find yours by echoing $USER. The second oroborus is actually the group. You can read more about what does each field mean here. It is very important to learn this because if you are working on ubuntu/osx or any Linux distro chances are you will encounter it again.

Now to make your permission look like this, you need to type
sudo chmod 700 ~/.ssh

7 in binary is 111 which means read 1 write 1 and execute 1, you can decode 6 by similar logic means only read-write permissions

You have given your user read write and execute permissions. Make sure your file permissions look like this.

total 20
-rw------- 1 oroborus oroborus  418 Nov  8  2014 authorized_keys
-rw------- 1 oroborus oroborus   34 Oct 19 14:25 config
-rw------- 1 oroborus oroborus 1679 Nov 15  2015 id_rsa
-rw------- 1 oroborus oroborus  418 Nov 15  2015 id_rsa.pub
-rw-r--r-- 1 oroborus root      222 Nov 28 12:12 known_hosts

You have given here read-write permission to your user here for all files. You can see this by typing ls -l ~/.ssh/

This issue occurs because ssh is a program is trying to write to a file called known_hosts in its folder. While writing if it knows that it doesn't have sufficient permissions it will not write in that file and hence fail. This is my understanding of the issue, more knowledgeable people can throw more light in this. Hope it helps

git - remote add origin vs remote set-url origin

1. git remote add origin [email protected]:User/UserRepo.git

  • This command is the second step in the command series after you initialize git into your current working repository using git init.
  • This command simply means "you are adding the location of your remote repository where you wish to push/pull your files to/from !!.."
  • Your remote repository could be anywhere on github, gitlab, bitbucket, etc.
  • Here origin is an alias/alternate name for your remote repository so that you don't have to type the entire path for remote every time and henceforth you are declaring that you will use this name(origin) to refer to your remote. This name could be anything.
  • To verify that the remote is set properly type : git remote -v

OR git remote get-url origin

2. git remote set-url origin [email protected]:User/UserRepo.git

This command means that if at any stage you wish to change the location of your repository(i.e if you made a mistake while adding the remote path using the git add command) the first time, you can easily go back & "reset(update) your current remote repository path" by using the above command.

3. git push -u remote master

This command simply pushes your files to the remote repository.Git has a concept of something known as a "branch", so by default everything is pushed to the master branch unless explicitly specified an alternate branch.

To know about the list of all branches you have in your repository type :git branch

How to use gitignore command in git

If you dont have a .gitignore file, first use:

touch .gitignore

then this command to add lines in your gitignore file:

echo 'application/cache' >> .gitignore

Be careful about new lines

Git Push ERROR: Repository not found

I was having the same issue with one of my Github Repository.

Way around:

Used SSH instead of HTTPS and then push/pull started working fine.

Import existing source code to GitHub

Create your repository in git hub

Allow to track your project by GIT

  1. using CMD go to folder where your project file is kept->cd /automation/xyz/codebase check for git intialization with command git status If you get this error message: fatal: Not a git repository (or any of the parent directories): .git, that means the folder you are currently in is not being tracked by git. In that case, initialize git inside your project folder by typing git init, then going through the process of adding and committing your project.

If you get another error message, read carefully what it says. Is it saying git isn't installed on your computer by saying that the word 'git' is not recognized? Is it saying that you're already in a folder or sub-folder where git is initialized? Google your error and/or output to understand it, and to figure out how to fix it.

now run following command

#

echo "your git hub repository name" >> README.md git init git add README.md git commit -m "first commit" git remote add origin https:// #

above block you will get when first time you are opening your repository

If error occurs or nothing happens after last command run"git push -u origin master" dont worry

go to folder where code is available and through git extention push it to git [URL], branch

"Insufficient Storage Available" even there is lot of free space in device memory

This is the easiest thing to do. Go to settings look for storage or memory touch it and look for cached data. touch it and clear your data from there. SIMPLE!!!

Algorithm for Determining Tic Tac Toe Game Over

You know a winning move can only happen after X or O has made their most recent move, so you can only search row/column with optional diag that are contained in that move to limit your search space when trying to determine a winning board. Also since there are a fixed number of moves in a draw tic-tac-toe game once the last move is made if it wasn't a winning move it's by default a draw game.

edit: this code is for an n by n board with n in a row to win (3x3 board requries 3 in a row, etc)

edit: added code to check anti diag, I couldn't figure out a non loop way to determine if the point was on the anti diag so thats why that step is missing

public class TripleT {

    enum State{Blank, X, O};

    int n = 3;
    State[][] board = new State[n][n];
    int moveCount;

    void Move(int x, int y, State s){
        if(board[x][y] == State.Blank){
            board[x][y] = s;
        }
        moveCount++;

        //check end conditions

        //check col
        for(int i = 0; i < n; i++){
            if(board[x][i] != s)
                break;
            if(i == n-1){
                //report win for s
            }
        }

        //check row
        for(int i = 0; i < n; i++){
            if(board[i][y] != s)
                break;
            if(i == n-1){
                //report win for s
            }
        }

        //check diag
        if(x == y){
            //we're on a diagonal
            for(int i = 0; i < n; i++){
                if(board[i][i] != s)
                    break;
                if(i == n-1){
                    //report win for s
                }
            }
        }

        //check anti diag (thanks rampion)
        if(x + y == n - 1){
            for(int i = 0; i < n; i++){
                if(board[i][(n-1)-i] != s)
                    break;
                if(i == n-1){
                    //report win for s
                }
            }
        }

        //check draw
        if(moveCount == (Math.pow(n, 2) - 1)){
            //report draw
        }
    }
}

Swift Open Link in Safari

Swift 3 & IOS 10.2

UIApplication.shared.open(URL(string: "http://www.stackoverflow.com")!, options: [:], completionHandler: nil)

Swift 3 & IOS 10.2

What is the best Java library to use for HTTP POST, GET etc.?

I would recommend Apache HttpComponents HttpClient, a successor of Commons HttpClient

I would also recommend to take a look at HtmlUnit. HtmlUnit is a "GUI-Less browser for Java programs". http://htmlunit.sourceforge.net/

How to set default text for a Tkinter Entry widget

Use Entry.insert. For example:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
e = Entry(root)
e.insert(END, 'default text')
e.pack()
root.mainloop()

Or use textvariable option:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
v = StringVar(root, value='default text')
e = Entry(root, textvariable=v)
e.pack()
root.mainloop()

MySQL > Table doesn't exist. But it does (or it should)

For me on Mac OS (MySQL DMG Installation) a simple restart of the MySQL server solved the problem. I am guessing the hibernation caused it.

Correct way to populate an Array with a Range in Ruby

This works for me in irb:

irb> (1..4).to_a
=> [1, 2, 3, 4]

I notice that:

irb> 1..4.to_a
(irb):1: warning: default `to_a' will be obsolete
ArgumentError: bad value for range
        from (irb):1

So perhaps you are missing the parentheses?

(I am running Ruby 1.8.6 patchlevel 114)

Show current assembly instruction in GDB

If you want the next few instructions to display automatically while stepping through the program you can use the display command as follows -

display /3i $pc

The above will display 3 instructions whenever a breakpoint is hit or when you single step the program.

More details at the blog entry here.

How do I use Access-Control-Allow-Origin? Does it just go in between the html head tags?

If you use Java and spring MVC you just need to add the following annotation to your method returning your page :

@CrossOrigin(origins = "*")

"*" is to allow your page to be accessible from anywhere. See https://developer.mozilla.org/fr/docs/Web/HTTP/Headers/Access-Control-Allow-Origin for more details about that.

Where does Java's String constant pool live, the heap or the stack?

As explained by this answer, the exact location of the string pool is not specified and can vary from one JVM implementation to another.

It is interesting to note that until Java 7, the pool was in the permgen space of the heap on hotspot JVM but it has been moved to the main part of the heap since Java 7:

Area: HotSpot
Synopsis: In JDK 7, interned strings are no longer allocated in the permanent generation of the Java heap, but are instead allocated in the main part of the Java heap (known as the young and old generations), along with the other objects created by the application. This change will result in more data residing in the main Java heap, and less data in the permanent generation, and thus may require heap sizes to be adjusted. Most applications will see only relatively small differences in heap usage due to this change, but larger applications that load many classes or make heavy use of the String.intern() method will see more significant differences. RFE: 6962931

And in Java 8 Hotspot, Permanent Generation has been completely removed.

Call PHP function from jQuery?

Thanks all. I took bits of each of your solutions and made my own.

The final working solution is:

<script type="text/javascript">
    $(document).ready(function(){
        $.ajax({
            url: '<?php bloginfo('template_url'); ?>/functions/twitter.php',
            data: "tweets=<?php echo $ct_tweets; ?>&account=<?php echo $ct_twitter; ?>",
            success: function(data) {
                $('#twitter-loader').remove();
                $('#twitter-container').html(data);
            }
        });
   });
</script>

Reading from stdin

From the man read:

#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);

Input parameters:

  • int fd file descriptor is an integer and not a file pointer. The file descriptor for stdin is 0

  • void *buf pointer to buffer to store characters read by the read function

  • size_t count maximum number of characters to read

So you can read character by character with the following code:

char buf[1];

while(read(0, buf, sizeof(buf))>0) {
   // read() here read from stdin charachter by character
   // the buf[0] contains the character got by read()
   ....
}

T-SQL datetime rounded to nearest minute and nearest hours with using functions

"Rounded" down as in your example. This will return a varchar value of the date.

DECLARE @date As DateTime2
SET @date = '2007-09-22 15:07:38.850'

SELECT CONVERT(VARCHAR(16), @date, 120) --2007-09-22 15:07
SELECT CONVERT(VARCHAR(13), @date, 120) --2007-09-22 15

Linq where clause compare only date value without time value

Simple workaround to this problem to compare date part only

var _My_ResetSet_Array = _DB
                    .tbl_MyTable
                    .Where(x => x.Active == true && 
                               x.DateTimeValueColumn.Year == DateTime.Now.Year
                            && x.DateTimeValueColumn.Month == DateTime.Now.Month
                            && x.DateTimeValueColumn.Day == DateTime.Now.Day);

Because 'Date' datatype is not supported by linq to entity , where as Year, Month and Day are 'int' datatypes and are supported.

How do I get the current timezone name in Postgres 9.3?

This may or may not help you address your problem, OP, but to get the timezone of the current server relative to UTC (UT1, technically), do:

SELECT EXTRACT(TIMEZONE FROM now())/3600.0;

The above works by extracting the UT1-relative offset in minutes, and then converting it to hours using the factor of 3600 secs/hour.

Example:

SET SESSION timezone TO 'Asia/Kabul';
SELECT EXTRACT(TIMEZONE FROM now())/3600.0;
-- output: 4.5 (as of the writing of this post)

(docs).

Why can't Python import Image from PIL?

All the answers were great however what did it for me was a combination of uninstalling Pillow

pip uninstall Pillow

Then installing whatever packages you need e.g.

sudo apt-get -y install python-imaging
sudo apt-get -y install zlib1g-dev
sudo apt-get -y install libjpeg-dev

And then using easy_install to reinstall Pillow

easy_install Pillow

Hope this helps others

Subset and ggplot2

With option 2 in @agstudy's answer now deprecated, defining data with a function can be handy.

library(plyr)
ggplot(data=dat) + 
  geom_line(aes(Value1, Value2, group=ID, colour=ID),
            data=function(x){x$ID %in% c("P1", "P3"))

This approach comes in handy if you wish to reuse a dataset in the same plot, e.g. you don't want to specify a new column in the data.frame, or you want to explicitly plot one dataset in a layer above the other.:

library(plyr)
ggplot(data=dat, aes(Value1, Value2, group=ID, colour=ID)) + 
  geom_line(data=function(x){x[!x$ID %in% c("P1", "P3"), ]}, alpha=0.5) +
  geom_line(data=function(x){x[x$ID %in% c("P1", "P3"), ]})

Swift - encode URL

This one is working for me.

func stringByAddingPercentEncodingForFormData(plusForSpace: Bool=false) -> String? {

    let unreserved = "*-._"
    let allowed = NSMutableCharacterSet.alphanumericCharacterSet()
    allowed.addCharactersInString(unreserved)

    if plusForSpace {
        allowed.addCharactersInString(" ")
    }

    var encoded = stringByAddingPercentEncodingWithAllowedCharacters(allowed)

    if plusForSpace {
        encoded = encoded?.stringByReplacingOccurrencesOfString(" ", withString: "+")
    }
    return encoded
}

I found above function from this link: http://useyourloaf.com/blog/how-to-percent-encode-a-url-string/.

Rebasing a Git merge commit

Given that I just lost a day trying to figure this out and actually found a solution with the help of a coworker, I thought I should chime in.

We have a large code base and we have to deal with 2 branch heavily being modified at the same time. There is a main branch and a secondary branch if you which.

While I merge the secondary branch into the main branch, work continues in the main branch and by the time i'm done, I can't push my changes because they are incompatible.

I therefore need to "rebase" my "merge".

This is how we finally did it :

1) make note of the SHA. ex.: c4a924d458ea0629c0d694f1b9e9576a3ecf506b

git log -1

2) Create the proper history but this will break the merge.

git rebase -s ours --preserve-merges origin/master

3) make note of the SHA. ex.: 29dd8101d78

git log -1

4) Now reset to where you were before

git reset c4a924d458ea0629c0d694f1b9e9576a3ecf506b --hard

5) Now merge the current master into your working branch

git merge origin/master
git mergetool
git commit -m"correct files

6) Now that you have the right files, but the wrong history, get the right history on top of your change with :

git reset 29dd8101d78 --soft

7) And then --amend the results in your original merge commit

git commit --amend

Voila!

Android: why is there no maxHeight for a View?

if you guys want to make a non-overflow scrollview or listview, just but it on a RelativeLayout with a topview and bottomview on top and bottom for it:

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/topview"
    android:layout_below="@+id/bottomview" >

how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application?

This is how we can set it in run-time:

public class Program
{
    public static void Main(string[] args)
    {
        Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development");

        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}

How to get UTF-8 working in Java webapps?

Faced the same issue on Spring MVC 5 + Tomcat 9 + JSP.
After the long research, came to an elegant solution (no need filters and no need changes in the Tomcat server.xml (starting from 8.0.0-RC3 version))

  1. In the WebMvcConfigurer implementation set default encoding for messageSource (for reading data from messages source files in the UTF-8 encoding.

    @Configuration
    @EnableWebMvc
    @ComponentScan("{package.with.components}")
    public class WebApplicationContextConfig implements WebMvcConfigurer {
    
        @Bean
        public MessageSource messageSource() {
            final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
    
            messageSource.setBasenames("messages");
            messageSource.setDefaultEncoding("UTF-8");
    
            return messageSource;
        }
    
        /* other beans and methods */
    
    }
    
  2. In the DispatcherServletInitializer implementation @Override the onStartup method and set request and resource character encoding in it.

    public class DispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    
        @Override
        public void onStartup(final ServletContext servletContext) throws ServletException {
    
            // https://wiki.apache.org/tomcat/FAQ/CharacterEncoding
            servletContext.setRequestCharacterEncoding("UTF-8");
            servletContext.setResponseCharacterEncoding("UTF-8");
    
            super.onStartup(servletContext);
        }
    
        /* servlet mappings, root and web application configs, other methods */
    
    }
    
  3. Save all message source and view files in UTF-8 encoding.

  4. Add <%@ page contentType="text/html;charset=UTF-8" %> or <%@ page pageEncoding="UTF-8" %> in each *.jsp file or add jsp-config descriptor to web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
     id="WebApp_ID" version="3.0">
        <display-name>AppName</display-name>
    
        <jsp-config>
            <jsp-property-group>
                <url-pattern>*.jsp</url-pattern>
                <page-encoding>UTF-8</page-encoding>
            </jsp-property-group>
        </jsp-config>
    </web-app>
    

Django return redirect() with parameters

urls.py:

#...    
url(r'element/update/(?P<pk>\d+)/$', 'element.views.element_update', name='element_update'),

views.py:

from django.shortcuts import redirect
from .models import Element


def element_info(request):
    # ...
    element = Element.object.get(pk=1)
    return redirect('element_update', pk=element.id)

def element_update(request, pk)
    # ...

LINQ to SQL - How to select specific columns and return strongly typed list

The issue was in fact that one of the properties was a relation to another table. I changed my LINQ query so that it could get the same data from a different method without needing to load the entire table.

Thank you all for your help!

Android - setOnClickListener vs OnClickListener vs View.OnClickListener

Imagine that we have 3 buttons for example

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        // Capture our button from layout
        Button button = (Button)findViewById(R.id.corky);
        Button button2 = (Button)findViewById(R.id.corky2);
        Button button3 = (Button)findViewById(R.id.corky3);
        // Register the onClick listener with the implementation above
        button.setOnClickListener(mCorkyListener);
        button2.setOnClickListener(mCorkyListener);
        button3.setOnClickListener(mCorkyListener);

    }

    // Create an anonymous implementation of OnClickListener
    private View.OnClickListener mCorkyListener = new View.OnClickListener() {
        public void onClick(View v) {
            // do something when the button is clicked 
            // Yes we will handle click here but which button clicked??? We don't know

        }
    };

}

So what we will do?

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        // Capture our button from layout
        Button button = (Button)findViewById(R.id.corky);
        Button button2 = (Button)findViewById(R.id.corky2);
        Button button3 = (Button)findViewById(R.id.corky3);
        // Register the onClick listener with the implementation above
        button.setOnClickListener(mCorkyListener);
        button2.setOnClickListener(mCorkyListener);
        button3.setOnClickListener(mCorkyListener);

    }

    // Create an anonymous implementation of OnClickListener
    private View.OnClickListener mCorkyListener = new View.OnClickListener() {
        public void onClick(View v) {
            // do something when the button is clicked
            // Yes we will handle click here but which button clicked??? We don't know

            // So we will make
            switch (v.getId() /*to get clicked view id**/) {
                case R.id.corky:

                    // do something when the corky is clicked

                    break;
                case R.id.corky2:

                    // do something when the corky2 is clicked

                    break;
                case R.id.corky3:

                    // do something when the corky3 is clicked

                    break;
                default:
                    break;
            }
        }
    };

}

Or we can do this:

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        // Capture our button from layout
        Button button = (Button)findViewById(R.id.corky);
        Button button2 = (Button)findViewById(R.id.corky2);
        Button button3 = (Button)findViewById(R.id.corky3);
        // Register the onClick listener with the implementation above
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // do something when the corky is clicked
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // do something when the corky2 is clicked
            }
        });
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // do something when the corky3 is clicked
            }
        });

    }

}

Or we can implement View.OnClickListener and i think it's the best way:

public class MainActivity extends ActionBarActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        // Capture our button from layout
        Button button = (Button)findViewById(R.id.corky);
        Button button2 = (Button)findViewById(R.id.corky2);
        Button button3 = (Button)findViewById(R.id.corky3);
        // Register the onClick listener with the implementation above
        button.setOnClickListener(this);
        button2.setOnClickListener(this);
        button3.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        // do something when the button is clicked
        // Yes we will handle click here but which button clicked??? We don't know

        // So we will make
        switch (v.getId() /*to get clicked view id**/) {
            case R.id.corky:

                // do something when the corky is clicked

                break;
            case R.id.corky2:

                // do something when the corky2 is clicked

                break;
            case R.id.corky3:

                // do something when the corky3 is clicked

                break;
            default:
                break;
        }
    }
}

Finally there is no real differences here Just "Way better than the other"

mysql - move rows from one table to another

The answer of Fabio is really good but it take a long execution time (as Trilarion already has written)

I have an other solution with faster execution.

START TRANSACTION;
set @N := (now());
INSERT INTO table2 select * from table1 where ts < date_sub(@N,INTERVAL 32 DAY);
DELETE FROM table1 WHERE ts < date_sub(@N,INTERVAL 32 DAY);
COMMIT;

@N gets the Timestamp at the begin and is used for both commands. All is in a Transaction to be sure nobody is disturbing

How to get current time in milliseconds in PHP?

Use microtime. This function returns a string separated by a space. The first part is the fractional part of seconds, the second part is the integral part. Pass in true to get as a number:

var_dump(microtime());       // string(21) "0.89115400 1283846202"
var_dump(microtime(true));   // float(1283846202.89)

Beware of precision loss if you use microtime(true).

There is also gettimeofday that returns the microseconds part as an integer.

var_dump(gettimeofday());
/*
array(4) {
  ["sec"]=>
  int(1283846202)
  ["usec"]=>
  int(891199)
  ["minuteswest"]=>
  int(-60)
  ["dsttime"]=>
  int(1)
}
*/

ASP.Net MVC 4 Form with 2 submit buttons/actions

Here is a good eplanation: ASP.NET MVC – Multiple buttons in the same form

In 2 words:
you may analize value of submitted button in yout action
or
make separate actions with your version of ActionMethodSelectorAttribute (which I personaly prefer and suggest).

Oracle PL/SQL : remove "space characters" from a string

Since you're comfortable with regular expressions, you probably want to use the REGEXP_REPLACE function. If you want to eliminate anything that matches the [:space:] POSIX class

REGEXP_REPLACE( my_value, '[[:space:]]', '' )


SQL> ed
Wrote file afiedt.buf

  1  select '|' ||
  2         regexp_replace( 'foo ' || chr(9), '[[:space:]]', '' ) ||
  3         '|'
  4*   from dual
SQL> /

'|'||
-----
|foo|

If you want to leave one space in place for every set of continuous space characters, just add the + to the regular expression and use a space as the replacement character.

with x as (
  select 'abc 123  234     5' str
    from dual
)
select regexp_replace( str, '[[:space:]]+', ' ' )
  from x

How to reset Jenkins security settings from the command line?

The simplest solution is to completely disable security - change true to false in /var/lib/jenkins/config.xml file.

<useSecurity>true</useSecurity>

Then just restart Jenkins, by

sudo service jenkins restart

And then go to admin panel and set everything once again.

If you in case are running your Jenkins inside k8s pod from a docker, which is my case and can not run service command, then you can just restart Jenkins by deleting the pod:

kubectl delete pod <jenkins-pod-name>

Once the command was issued, the k8s will terminate the old pod and start a new one.

How to make an AJAX call without jQuery?

If you don't want to include JQuery, I'd try out some lightweight AJAX libraries.

My favorite is reqwest. It's only 3.4kb and very well built out: https://github.com/ded/Reqwest

Here's a sample GET request with reqwest:

reqwest({
    url: url,
    method: 'GET',
    type: 'json',
    success: onSuccess
});

Now if you want something even more lightweight, I'd try microAjax at a mere 0.4kb: https://code.google.com/p/microajax/

This is all the code right here:

function microAjax(B,A){this.bindFunction=function(E,D){return function(){return E.apply(D,[D])}};this.stateChange=function(D){if(this.request.readyState==4){this.callbackFunction(this.request.responseText)}};this.getRequest=function(){if(window.ActiveXObject){return new ActiveXObject("Microsoft.XMLHTTP")}else{if(window.XMLHttpRequest){return new XMLHttpRequest()}}return false};this.postBody=(arguments[2]||"");this.callbackFunction=A;this.url=B;this.request=this.getRequest();if(this.request){var C=this.request;C.onreadystatechange=this.bindFunction(this.stateChange,this);if(this.postBody!==""){C.open("POST",B,true);C.setRequestHeader("X-Requested-With","XMLHttpRequest");C.setRequestHeader("Content-type","application/x-www-form-urlencoded");C.setRequestHeader("Connection","close")}else{C.open("GET",B,true)}C.send(this.postBody)}};

And here's a sample call:

microAjax(url, onSuccess);

Remove quotes from a character vector in R

as.name(char[1]) will work, although I'm not sure why you'd ever really want to do this -- the quotes won't get carried over in a paste for example:

> paste("I am counting to", char[1], char[2], char[3])
[1] "I am counting to one two three"

Jenkins Host key verification failed

Had same problem, i fix it like that :

reset permission on id_rsa* only for current user no group no other

chmod o-rwx ~/.ssh/id*
chmod G-rwx ~/.ssh/id*

ls -lart ~/.ssh/


-rw-------  1 jenkins nogroup  398 avril  3 09:34 id_rsa.pub
-rw-------  1 jenkins nogroup 1675 avril  3 09:34 id_rsa

And clear ~/.ssh/know_hosts

Now Connect as jenkins

sudo su jenkins

Try the jenkins commands

git ls-remote -h [email protected]:user/project.git HEAD

If no problem appears, now jenkins will be able to connect the repo (for me ^^ at least)

What are functional interfaces used for in Java 8?

Functional Interfaces: An interface is called a functional interface if it has a single abstract method irrespective of the number of default or static methods. Functional Interface are use for lamda expression. Runnable, Callable, Comparable, Comparator are few examples of Functional Interface.

KeyNotes:

  • Annotation @FunctionalInterface is used(Optional).
  • It should have only 1 abstract method(irrespective of number of default and static methods).
  • Two abstract method gives compilation error(Provider @FunctionalInterface annotation is used).

This thread talks more in detail about what benefit functional Interface gives over anonymous class and how to use them.

Unix tail equivalent command in Windows Powershell

For completeness I'll mention that Powershell 3.0 now has a -Tail flag on Get-Content

Get-Content ./log.log -Tail 10

gets the last 10 lines of the file

Get-Content ./log.log -Wait -Tail 10

gets the last 10 lines of the file and waits for more

Also, for those *nix users, note that most systems alias cat to Get-Content, so this usually works

cat ./log.log -Tail 10

Spark - SELECT WHERE or filtering?

As Yaron mentioned, there isn't any difference between where and filter.

filter is an overloaded method that takes a column or string argument. The performance is the same, regardless of the syntax you use.

filter overloaded method

We can use explain() to see that all the different filtering syntaxes generate the same Physical Plan. Suppose you have a dataset with person_name and person_country columns. All of the following code snippets will return the same Physical Plan below:

df.where("person_country = 'Cuba'").explain()
df.where($"person_country" === "Cuba").explain()
df.where('person_country === "Cuba").explain()
df.filter("person_country = 'Cuba'").explain()

These all return this Physical Plan:

== Physical Plan ==
*(1) Project [person_name#152, person_country#153]
+- *(1) Filter (isnotnull(person_country#153) && (person_country#153 = Cuba))
   +- *(1) FileScan csv [person_name#152,person_country#153] Batched: false, Format: CSV, Location: InMemoryFileIndex[file:/Users/matthewpowers/Documents/code/my_apps/mungingdata/spark2/src/test/re..., PartitionFilters: [], PushedFilters: [IsNotNull(person_country), EqualTo(person_country,Cuba)], ReadSchema: struct<person_name:string,person_country:string>

The syntax doesn't change how filters are executed under the hood, but the file format / database that a query is executed on does. Spark will execute the same query differently on Postgres (predicate pushdown filtering is supported), Parquet (column pruning), and CSV files. See here for more details.

How to remove \xa0 from string in Python?

0xA0 (Unicode) is 0xC2A0 in UTF-8. .encode('utf8') will just take your Unicode 0xA0 and replace with UTF-8's 0xC2A0. Hence the apparition of 0xC2s... Encoding is not replacing, as you've probably realized now.

How to see data from .RData file?

you can try

isfar <- get(load('c:/users/isfar.Rdata'))

this will assign the variable in isfar.Rdata to isfar . After this assignment, you can use str(isfar) or ls(isfar) or head(isfar) to get a rough look of the isfar.

How to wait for a process to terminate to execute another process in batch file

Use start /w programname to wait for the end of programname

START /W notepad
ECHO Back from notepad  
START /W wordpad
ECHO Back from wordpad
START /W notepad

How to navigate to a directory in C:\ with Cygwin?

I'll add something that helps me out a lot with cygwin. Whenever setting up a new system, I always do this

ln -s /cygdrive/c /c

This creates a symbolic link to /cygdrive/c with a new file called /c (in the home directory)

Then you can do this in your shell

cd /c/Foo
cd /c/

Very handy.

nginx error "conflicting server name" ignored

I assume that you're running a Linux, and you're using gEdit to edit your files. In the /etc/nginx/sites-enabled, it may have left a temp file e.g. default~ (watch the ~).

Depending on your editor, the file could be named .save or something like it. Just run $ ls -lah to see which files are unintended to be there and remove them (Thanks @Tisch for this).

Delete this file, and it will solve your problem.

Understanding string reversal via slicing

we can use append and pop to do it

def rev(s):
    i = list(s)
    o = list()
    while len(i) > 0:
        o.append(t.pop())

    return ''.join(o)

Converting array to list in Java

  1. Using Guava:

    Integer[] array = { 1, 2, 3};
    List<Integer> list = Lists.newArrayList(sourceArray);
    
  2. Using Apache Commons Collections:

    Integer[] array = { 1, 2, 3};
    List<Integer> list = new ArrayList<>(6);
    CollectionUtils.addAll(list, array);
    

Batch file include external file for variables

Note: I'm assuming Windows batch files as most people seem to be unaware that there are significant differences and just blindly call everything with grey text on black background DOS. Nevertheless, the first variant should work in DOS as well.

Executable configuration

The easiest way to do this is to just put the variables in a batch file themselves, each with its own set statement:

set var1=value1
set var2=value2
...

and in your main batch:

call config.cmd

Of course, that also enables variables to be created conditionally or depending on aspects of the system, so it's pretty versatile. However, arbitrary code can run there and if there is a syntax error, then your main batch will exit too. In the UNIX world this seems to be fairly common, especially for shells. And if you think about it, autoexec.bat is nothing else.

Key/value pairs

Another way would be some kind of var=value pairs in the configuration file:

var1=value1
var2=value2
...

You can then use the following snippet to load them:

for /f "delims=" %%x in (config.txt) do (set "%%x")

This utilizes a similar trick as before, namely just using set on each line. The quotes are there to escape things like <, >, &, |. However, they will themselves break when quotes are used in the input. Also you always need to be careful when further processing data in variables stored with such characters.

Generally, automatically escaping arbitrary input to cause no headaches or problems in batch files seems pretty impossible to me. At least I didn't find a way to do so yet. Of course, with the first solution you're pushing that responsibility to the one writing the config file.

Parsing XML in Python using ElementTree example

So I have ElementTree 1.2.6 on my box now, and ran the following code against the XML chunk you posted:

import elementtree.ElementTree as ET

tree = ET.parse("test.xml")
doc = tree.getroot()
thingy = doc.find('timeSeries')

print thingy.attrib

and got the following back:

{'name': 'NWIS Time Series Instantaneous Values'}

It appears to have found the timeSeries element without needing to use numerical indices.

What would be useful now is knowing what you mean when you say "it doesn't work." Since it works for me given the same input, it is unlikely that ElementTree is broken in some obvious way. Update your question with any error messages, backtraces, or anything you can provide to help us help you.

PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client

Faced the same problem, I was not able to run wordpress docker container with mysql version 8 as its default authentication mechanism is caching_sha2_password instead of mysql_native_password.

In order to fix this problem we must reset default authentication mechanism to mysql_native_password.

Find my.cnf file in your mysql installation, usually on a linux machine it is at the following location - /etc/mysql

Edit my.cnf file and add following line just under heading [mysqld]

default_authentication_plugin= mysql_native_password

Save the file then log into mysql command line using root user

run command FLUSH PRIVILEGES;

How to start MySQL server on windows xp

use the command "mysql -u root -p" in the bin folder path. and give the MY SQL password which you have set earlier.

Run bash script from Windows PowerShell

There is now a "native" solution on Windows 10, after enabling Bash on Windows, you can enter Bash shell by typing bash: Bash on Windows

You can run Bash script like bash ./script.sh, but keep in mind that C drive is located at /mnt/c, and external hard drives are not mountable. So you might need to change your script a bit so it is compatible to Windows.

Also, even as root, you can still get permission denied when moving files around in /mnt, but you have your full root power in the / file system.

Also make sure your shell script is formatted with Unix style, or there can be errors. Example script

HTML form readonly SELECT tag/input

So for whatever reason all jquery based solutions mentioned here did not work for me. So here is a pure javascript solution which should also preserve the selected value when doing a POST.

setDropdownReadOnly('yourIdGoesHere',true/false)
    function setDropdownReadOnly(controlName, state) {
        var ddl = document.getElementById(controlName);

        for (i = 0; i < ddl.length; i++) {
            if (i == ddl.selectedIndex)
                ddl[i].disabled = false;
            else
                ddl[i].disabled = state;
        }
    }

How to quickly and conveniently disable all console.log statements in my code?

I have used winston logger earlier.

Nowadays I am using below simpler code from experience:

  1. Set the environment variable from cmd/ command line (on Windows):

    cmd
    setx LOG_LEVEL info
    

Or, you could have a variable in your code if you like, but above is better.

  1. Restart cmd/ command line, or, IDE/ editor like Netbeans

  2. Have below like code:

    console.debug = console.log;   // define debug function
    console.silly = console.log;   // define silly function
    
    switch (process.env.LOG_LEVEL) {
        case 'debug':
        case 'silly':
            // print everything
            break;
    
        case 'dir':
        case 'log':
            console.debug = function () {};
            console.silly = function () {};
            break;
    
        case 'info':
            console.debug = function () {};
            console.silly = function () {};
            console.dir = function () {};
            console.log = function () {};
            break;
    
        case 'trace':   // similar to error, both may print stack trace/ frames
        case 'warn':    // since warn() function is an alias for error()
        case 'error':
            console.debug = function () {};
            console.silly = function () {};
            console.dir = function () {};
            console.log = function () {};
            console.info = function () {};
            break;
    }
    
  3. Now use all console.* as below:

    console.error(' this is a error message '); // will print
    console.warn(' this is a warn message '); // will print
    console.trace(' this is a trace message '); // will print
    console.info(' this is a info message '); // will print, LOG_LEVEL is set to this
    
    console.log(' this is a log message '); // will NOT print
    console.dir(' this is a dir message '); // will NOT print
    console.silly(' this is a silly message '); // will NOT print
    console.debug(' this is a debug message '); // will NOT print
    

Now, based on your LOG_LEVEL settings made in the point 1 (like, setx LOG_LEVEL log and restart command line), some of the above will print, others won't print

Hope that helped.

openpyxl - adjust column width size

You could estimate (or use a mono width font) to achieve this. Let's assume data is a nested array like [['a1','a2'],['b1','b2']]

We can get the max characters in each column. Then set the width to that. Width is exactly the width of a monospace font (if not changing other styles at least). Even if you use a variable width font it is a decent estimation. This will not work with formulas.

from openpyxl.utils import get_column_letter

column_widths = []
for row in data:
    for i, cell in enumerate(row):
        if len(column_widths) > i:
            if len(cell) > column_widths[i]:
                column_widths[i] = len(cell)
        else:
            column_widths += [len(cell)]

for i, column_width in enumerate(column_widths):
    worksheet.column_dimensions[get_column_letter(i+1)].width = column_width

A bit of a hack but your reports will be more readable.

Convert date to datetime in Python

You can use datetime.combine(date, time); for the time, you create a datetime.time object initialized to midnight.

from datetime import date
from datetime import datetime

dt = datetime.combine(date.today(), datetime.min.time())

Annotations from javax.validation.constraints not working

I came across this problem recently in a very similar situation: Met all requirements as the top-rated answer listed but still got the wrong result.

So I looked at my dependencies and found I was missing some of them. I corrected it by adding the missing dependencies.

I was using hibernate, the required dependencies were: Dependencies Snapshot

*Snapshot taken in class "Spring & Hibernate for Beginners" @ Udemy

How to open remote files in sublime text 3

Base on this.

Step by step:

  • On your local workstation: On Sublime Text 3, open Package Manager (Ctrl-Shift-P on Linux/Win, Cmd-Shift-P on Mac, Install Package), and search for rsub
  • On your local workstation: Add RemoteForward 52698 127.0.0.1:52698 to your .ssh/config file, or -R 52698:localhost:52698 if you prefer command line
  • On your remote server:

    sudo wget -O /usr/local/bin/rsub https://raw.github.com/aurora/rmate/master/rmate
    sudo chmod a+x /usr/local/bin/rsub
    

Just keep your ST3 editor open, and you can easily edit remote files with

rsub myfile.txt

EDIT: if you get "no such file or directory", it's because your /usr/local/bin is not in your PATH. Just add the directory to your path:

echo "export PATH=\"$PATH:/usr/local/bin\"" >> $HOME/.bashrc

Now just log off, log back in, and you'll be all set.

Is there a need for range(len(a))?

It's nice to have when you need to use the index for some kind of manipulation and having the current element doesn't suffice. Take for instance a binary tree that's stored in an array. If you have a method that asks you to return a list of tuples that contains each nodes direct children then you need the index.

#0 -> 1,2 : 1 -> 3,4 : 2 -> 5,6 : 3 -> 7,8 ...
nodes = [0,1,2,3,4,5,6,7,8,9,10]
children = []
for i in range(len(nodes)):
  leftNode = None
  rightNode = None
  if i*2 + 1 < len(nodes):
    leftNode = nodes[i*2 + 1]
  if i*2 + 2 < len(nodes):
    rightNode = nodes[i*2 + 2]
  children.append((leftNode,rightNode))
return children

Of course if the element you're working on is an object, you can just call a get children method. But yea, you only really need the index if you're doing some sort of manipulation.

combining results of two select statements

While it is possible to combine the results, I would advise against doing so.

You have two fundamentally different types of queries that return a different number of rows, a different number of columns and different types of data. It would be best to leave it as it is - two separate queries.

Array.push() and unique items

Your logic is saying, "if this item exists already, then add it." It should be the opposite of that.

Change it to...

if (this.items.indexOf(item) == -1) {
    this.items.push(item);
}

How can I find a specific element in a List<T>?

Or if you do not prefer to use LINQ you can do it the old-school way:

List<MyClass> list = new List<MyClass>();
foreach (MyClass element in list)
{
    if (element.GetId() == "heres_where_you_put_what_you_are_looking_for")
    {

        break; // If you only want to find the first instance a break here would be best for your application
    }
}

How to cut a string after a specific character in unix

For completeness, using cut

cut -d : -f 2 <<< $var

And using only bash:

IFS=: read a b <<< $var ; echo $b

assembly to compare two numbers

input password program
.modle small
.stack 100h
.data
s pasword db 34
input pasword db "enter pasword","$"
valid db ?
invalid db?
.code
mov ax, @ data 
mov db, ax
mov ah,09h
mov dx, offest s pasword
int 21h
mov ah, 01h
cmp al, s pasword
je v
jmp nv
v:
mov ah, 09h
mov dx, offset valid 
int 21h
nv:
mov ah, 09h
mov dx, offset invalid 
int 21h
mov ah, 04ch 
int 21
end 

Why does CSS not support negative padding?

Fitting an Iframe inside containers will not match the size of the container. It adds about 20px of padding. Currently there is no easy way to fix this. You need javascript (http://css-tricks.com/snippets/jquery/fit-iframe-to-content/)

Negative margins would be an easy solution.

Twitter Bootstrap Use collapse.js on table cells [Almost Done]

I'm not sure you have gotten past this yet, but I had to work on something very similar today and I got your fiddle working like you are asking, basically what I did was make another table row under it, and then used the accordion control. I tried using just collapse but could not get it working and saw an example somewhere on SO that used accordion.

Here's your updated fiddle: http://jsfiddle.net/whytheday/2Dj7Y/11/

Since I need to post code here is what each collapsible "section" should look like ->

<tr data-toggle="collapse" data-target="#demo1" class="accordion-toggle">
    <td>1</td>
    <td>05 May 2013</td>
    <td>Credit Account</td>
    <td class="text-success">$150.00</td>
    <td class="text-error"></td>
    <td class="text-success">$150.00</td>
</tr>

<tr>
    <td colspan="6" class="hiddenRow">
        <div class="accordion-body collapse" id="demo1">Demo1</div>
    </td>
</tr>

Apply formula to the entire column

Just so I don't lose my answer that works:

  1. Select the cell to copy
  2. Select the final cell in the column
  3. Press CTRL+D

belongs_to through associations

Just use has_one instead of belongs_to in your :through, like this:

class Choice
  belongs_to :user
  belongs_to :answer
  has_one :question, :through => :answer
end

Unrelated, but I'd be hesitant to use validates_uniqueness_of instead of using a proper unique constraint in your database. When you do this in ruby you have race conditions.

How to delete a cookie using jQuery?

You can also delete cookies without using jquery.cookie plugin:

document.cookie = 'NAMEOFYOURCOOKIE' + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';

How to comment and uncomment blocks of code in the Office VBA Editor

There is a built-in Edit toolbar in the VBA editor that has the Comment Block and Uncomment Block buttons by default, and other useful tools.

If you right-click any toolbar or menu (or go to the View menu > Toolbars), you will see a list of available toolbars (above the "Customize..." option). The Standard toolbar is selected by default. Select the Edit toolbar and the new toolbar will appear, with the Comment Block buttons in the middle.

enter image description here

*This is a simpler option to the ones mentioned.

How can I display a tooltip message on hover using jQuery?

You can use bootstrap tooltip. Do not forget to initialize it.

<span class="tooltip-r" data-toggle="tooltip" data-placement="left" title="Explanation">
inside span
</span>

Will be shown text Explanation on the left side.

and run it with js:

$('.tooltip-r').tooltip();

Getting the inputstream from a classpath resource (XML file)

ClassLoader.class.getResourceAsStream("/path/file.ext");

How to hide columns in an ASP.NET GridView with auto-generated columns?

Try this to hide columns in an ASP.NET GridView with auto-generated columns, both RowDataBound/RowCreated work too.

Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound

    If e.Row.RowType = DataControlRowType.DataRow Or _
        e.Row.RowType = DataControlRowType.Header Then   // apply to datarow and header 

        e.Row.Cells(e.Row.Cells.Count - 1).Visible = False // last column
        e.Row.Cells(0).Visible = False  // first column

    End If
End Sub

Protected Sub GridView1_RowCreated(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowCreated

    If e.Row.RowType = DataControlRowType.DataRow Or _
        e.Row.RowType = DataControlRowType.Header Then

        e.Row.Cells(e.Row.Cells.Count - 1).Visible = False
        e.Row.Cells(0).Visible = False

    End If
End Sub

Python Inverse of a Matrix

Make sure you really need to invert the matrix. This is often unnecessary and can be numerically unstable. When most people ask how to invert a matrix, they really want to know how to solve Ax = b where A is a matrix and x and b are vectors. It's more efficient and more accurate to use code that solves the equation Ax = b for x directly than to calculate A inverse then multiply the inverse by B. Even if you need to solve Ax = b for many b values, it's not a good idea to invert A. If you have to solve the system for multiple b values, save the Cholesky factorization of A, but don't invert it.

See Don't invert that matrix.

Any good boolean expression simplifiers out there?

Try Logic Friday 1 It includes tools from the Univerity of California (Espresso and misII) and makes them usable with a GUI. You can enter boolean equations and truth tables as desired. It also features a graphical gate diagram input and output.

The minimization can be carried out two-level or multi-level. The two-level form yields a minimized sum of products. The multi-level form creates a circuit composed out of logical gates. The types of gates can be restricted by the user.

Your expression simplifies to C.

jQuery UI Dialog OnBeforeUnload

This works for me:

_x000D_
_x000D_
window.addEventListener("beforeunload", function(event) {_x000D_
  event.returnValue = "You may have unsaved Data";_x000D_
});
_x000D_
_x000D_
_x000D_

Java - removing first character of a string

public String removeFirst(String input)
{
    return input.substring(1);
}

What's the difference between a POST and a PUT HTTP REQUEST?

Only semantics.

An HTTP PUT is supposed to accept the body of the request, and then store that at the resource identified by the URI.

An HTTP POST is more general. It is supposed to initiate an action on the server. That action could be to store the request body at the resource identified by the URI, or it could be a different URI, or it could be a different action.

PUT is like a file upload. A put to a URI affects exactly that URI. A POST to a URI could have any effect at all.

How to make a Div appear on top of everything else on the screen?

One form to do this is insert the panel that you want to expand inside a DIV setted as relative: let me show you:

<div style="position:relative">
  <div style="position:absolute; z-index: 1000;">
    your code
  </div>
</div>

You use the first div to position the inner content in a specific area inside your page and the second absolute should be referred to the container (because is relative) The z-index in this case is referred also to container and if it higher that the container should be at top. You can put the style in a CSS class and change the size of the absolute div to expand it on hover or another action that you want to control.

I hope that this help

Reverse of JSON.stringify?

Recommended is to use JSON.parse

There is an alternative you can do :

 var myObject = eval('(' + myJSONtext + ')');

Json in javascript

Why is using the JavaScript eval function a bad idea?

Stopping a windows service when the stop option is grayed out

Open command prompt with admin access and type the following commands there .

a)

tasklist

it displays list of all available services . There you can see the service you want to stop/start/restart . Remember PID value of the service you want to force stop.

b) Now type

taskkill /f /PID [PID value of the service] 

and press enter. On success you will get the message “SUCCESS: The process with PID has been terminated”.

Ex : taskkill /f /PID 5088

This will forcibly kill the frozen service. You can now return to Server Manager and restart the service.

Calling filter returns <filter object at ... >

It looks like you're using python 3.x. In python3, filter, map, zip, etc return an object which is iterable, but not a list. In other words,

filter(func,data) #python 2.x

is equivalent to:

list(filter(func,data)) #python 3.x

I think it was changed because you (often) want to do the filtering in a lazy sense -- You don't need to consume all of the memory to create a list up front, as long as the iterator returns the same thing a list would during iteration.

If you're familiar with list comprehensions and generator expressions, the above filter is now (almost) equivalent to the following in python3.x:

( x for x in data if func(x) ) 

As opposed to:

[ x for x in data if func(x) ]

in python 2.x

Writing your own square root function

Calculate square root with arbitrary precision in Python

#!/usr/bin/env python
import decimal

def sqrt(n):
    assert n > 0
    with decimal.localcontext() as ctx:
        ctx.prec += 2 # increase precision to minimize round off error
        x, prior = decimal.Decimal(n), None
        while x != prior: 
            prior = x
            x = (x + n/x) / 2 # quadratic convergence 
    return +x # round in a global context


decimal.getcontext().prec = 80 # desirable precision
r = sqrt(12345)
print r
print r == decimal.Decimal(12345).sqrt()

Output:

111.10805551354051124500443874307524148991137745969772997648567316178259031751676
True

_DEBUG vs NDEBUG

Visual Studio defines _DEBUG when you specify the /MTd or /MDd option, NDEBUG disables standard-C assertions. Use them when appropriate, ie _DEBUG if you want your debugging code to be consistent with the MS CRT debugging techniques and NDEBUG if you want to be consistent with assert().

If you define your own debugging macros (and you don't hack the compiler or C runtime), avoid starting names with an underscore, as these are reserved.

How to run a script file remotely using SSH

I don't know if it's possible to run it just like that.

I usually first copy it with scp and then log in to run it.

scp foo.sh user@host:~
ssh user@host
./foo.sh

Return multiple values from a function in swift

Also:

func getTime() -> (hour: Int, minute: Int,second: Int) {
    let hour = 1
    let minute = 2
    let second = 3
    return ( hour, minute, second)
}

Then it's invoked as:

let time = getTime()
print("hour: \(time.hour), minute: \(time.minute), second: \(time.second)")

This is the standard way how to use it in the book The Swift Programming Language written by Apple.

or just like:

let time = getTime()
print("hour: \(time.0), minute: \(time.1), second: \(time.2)")

it's the same but less clearly.

How to Decode Json object in laravel and apply foreach loop on that in laravel

you can use json_decode function

foreach (json_decode($response) as $area)
{
 print_r($area); // this is your area from json response
}

See this fiddle

how to update the multiple rows at a time using linq to sql?

Do not use the ToList() method as in the accepted answer !

Running SQL profiler, I verified and found that ToList() function gets all the records from the database. It is really bad performance !!

I would have run this query by pure sql command as follows:

string query = "Update YourTable Set ... Where ...";    
context.Database.ExecuteSqlCommandAsync(query, new SqlParameter("@ColumnY", value1), new SqlParameter("@ColumnZ", value2));

This would operate the update in one-shot without selecting even one row.

display Java.util.Date in a specific format

Use the SimpleDateFormat.format

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
String sDate= sdf.format(date);

Heap space out of memory

Java is supposed to clear the heap space for you when all of the objects are no longer referenced. It won't generally release it back to the OS though, it will keep that memory for it's own internal reuse. Maybe check to see if you have some arrays which are not being cleared or something.

Add button to a layout programmatically

If you just have included a layout file at the beginning of onCreate() inside setContentView and want to get this layout to add new elements programmatically try this:

ViewGroup linearLayout = (ViewGroup) findViewById(R.id.linearLayoutID);

then you can create a new Button for example and just add it:

Button bt = new Button(this);
bt.setText("A Button");
bt.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 
                                    LayoutParams.WRAP_CONTENT));
linerLayout.addView(bt);

How do I turn a C# object into a JSON string in .NET?

Use the below code for converting XML to JSON.

var json = new JavaScriptSerializer().Serialize(obj);

Creating random colour in Java?

I know it's a bit late for this answer, but I've not seen anyone else put this.

Like Greg said, you want to use the Random class

Random rand = new Random();

but the difference I'm going to say is simple do this:

Color color = new Color(rand.nextInt(0xFFFFFF));

And it's as simple as that! no need to generate lots of different floats.

Declaring variable workbook / Worksheet vba

Third solution: I would set ws to a sheet of workbook wb as the use of Sheet("name") always refers to the active workbook, which might change as your code develops.

sub kl() 

    Dim wb As Workbook
    Dim ws As Worksheet

    Set wb = ActiveWorkbook
    'be aware as this might produce an error, if Shet "name" does not exist
    Set ws = wb.Sheets("name")
    ' if wb is other than the active workbook
    wb.activate
    ws.Select

End Sub

Remove menubar from Electron app

Most of the answers here are not valid for newer versions. With the version of 9.0 or upper, Menu.setApplicationMenu(null); should work. By the way, Menu exported from electron package: const {Menu} = require('electron');

Postgres Error: More than one row returned by a subquery used as an expression

This means your nested SELECT returns more than one rows.

You need to add a proper WHERE clause to it.

HTML form with multiple "actions"

this really worked form for I am making a table using thymeleaf and inside the table there is two buttons in one form...thanks man even this thread is old it still helps me alot!

_x000D_
_x000D_
<th:block th:each="infos : ${infos}">_x000D_
<tr>_x000D_
<form method="POST">_x000D_
<td><input class="admin" type="text" name="firstName" id="firstName" th:value="${infos.firstName}"/></td>_x000D_
<td><input class="admin" type="text" name="lastName" id="lastName" th:value="${infos.lastName}"/></td>_x000D_
<td><input class="admin" type="email" name="email" id="email" th:value="${infos.email}"/></td>_x000D_
<td><input class="admin" type="text" name="passWord" id="passWord" th:value="${infos.passWord}"/></td>_x000D_
<td><input class="admin" type="date" name="birthDate" id="birthDate" th:value="${infos.birthDate}"/></td>_x000D_
<td>_x000D_
<select class="admin" name="gender" id="gender">_x000D_
<option><label th:text="${infos.gender}"></label></option>_x000D_
<option value="Male">Male</option>_x000D_
<option value="Female">Female</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="status" id="status">_x000D_
<option><label th:text="${infos.status}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="ustatus" id="ustatus">_x000D_
<option><label th:text="${infos.ustatus}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="type" id="type">_x000D_
<option><label th:text="${infos.type}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select></td>_x000D_
<td><input class="register" id="mobileNumber" type="text" th:value="${infos.mobileNumber}" name="mobileNumber" onkeypress="return isNumberKey(event)" maxlength="11"/></td>_x000D_
<td><input class="table" type="submit" id="submit" name="submit" value="Upd" Style="color: white; background-color:navy; border-color: black;" th:formaction="@{/updates}"/></td>_x000D_
<td><input class="table" type="submit" id="submit" name="submit" value="Del" Style="color: white; background-color:navy; border-color: black;" th:formaction="@{/delete}"/></td>_x000D_
</form>_x000D_
</tr>_x000D_
</th:block>
_x000D_
_x000D_
_x000D_

Parse JSON String into a Particular Object Prototype in JavaScript

I created a package called json-dry. It supports (circular) references and also class instances.

You have to define 2 new methods in your class (toDry on the prototype and unDry as a static method), register the class (Dry.registerClass), and off you go.

css absolute position won't work with margin-left:auto margin-right: auto

I already had this same issue and I've got the solution writing a container (.divtagABS-container, in your case) absolutely positioned and then relatively positioning the content inside it (.divtagABS, in your case).

Done! The margin-left and margin-right AUTO for your .divtagABS will now work.

Iterate over the lines of a string

You can iterate over "a file", which produces lines, including the trailing newline character. To make a "virtual file" out of a string, you can use StringIO:

import io  # for Py2.7 that would be import cStringIO as io

for line in io.StringIO(foo):
    print(repr(line))

WCF on IIS8; *.svc handler mapping doesn't work

On windows 10 (client) you can also script this using

Enable-WindowsOptionalFeature -Online -NoRestart -FeatureName WCF-HTTP-Activation45 -All

Note that this is a different command from the server skus

Relative paths in Python

Instead of using

import os
dirname = os.path.dirname(__file__)
filename = os.path.join(dirname, 'relative/path/to/file/you/want')

as in the accepted answer, it would be more robust to use:

import inspect
import os
dirname = os.path.dirname(os.path.abspath(inspect.stack()[0][1]))
filename = os.path.join(dirname, 'relative/path/to/file/you/want')

because using __file__ will return the file from which the module was loaded, if it was loaded from a file, so if the file with the script is called from elsewhere, the directory returned will not be correct.

These answers give more detail: https://stackoverflow.com/a/31867043/5542253 and https://stackoverflow.com/a/50502/5542253

How to increase executionTimeout for a long-running query?

When a query takes that long, I would advice to run it asynchronously and use a callback function for when it's complete.

I don't have much experience with ASP.NET, but maybe you can use AJAX for this asynchronous behavior.

Typically a web page should load in mere seconds, not minutes. Don't keep your users waiting for so long!

clearing a char array c

You should use memset. Setting just the first element won't work, you need to set all elements - if not, how could you set only the first element to 0?

How to convert a string or integer to binary in Ruby?

I asked a similar question. Based on @sawa's answer, the most succinct way to represent an integer in a string in binary format is to use the string formatter:

"%b" % 245
=> "11110101"

You can also choose how long the string representation to be, which might be useful if you want to compare fixed-width binary numbers:

1.upto(10).each { |n| puts "%04b" % n }
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010

How to find out what character key is pressed?

More recent and much cleaner: use event.key. No more arbitrary number codes!

NOTE: The old properties (.keyCode and .which) are Deprecated.

node.addEventListener('keydown', function(event) {
    const key = event.key; // "a", "1", "Shift", etc.
});

If you want to make sure only single characters are entered, check key.length === 1, or that it is one of the characters you expect.

Mozilla Docs

Supported Browsers

How to extract this specific substring in SQL Server?

An alternative to the answer provided by @Marc

SELECT SUBSTRING(LEFT(YOUR_FIELD, CHARINDEX('[', YOUR_FIELD) - 1), CHARINDEX(';', YOUR_FIELD) + 1, 100)
FROM YOUR_TABLE
WHERE CHARINDEX('[', YOUR_FIELD) > 0 AND
    CHARINDEX(';', YOUR_FIELD) > 0;

This makes sure the delimiters exist, and solves an issue with the currently accepted answer where doing the LEFT last is working with the position of the last delimiter in the original string, rather than the revised substring.

How to convert milliseconds to "hh:mm:ss" format?

The answer marked as correct has a little mistake,

String myTime = String.format("%02d:%02d:%02d",
            TimeUnit.MILLISECONDS.toHours(millis),
            TimeUnit.MILLISECONDS.toMinutes(millis) -
                    TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), // The change is in this line
            TimeUnit.MILLISECONDS.toSeconds(millis) -
                    TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));

for example this is an example of the value that i get:

417474:44:19

This is the solution to get the right format is:

String myTime =  String.format("%02d:%02d:%02d",
                //Hours
                TimeUnit.MILLISECONDS.toHours(millis) -
                        TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(millis)),
                //Minutes
                TimeUnit.MILLISECONDS.toMinutes(millis) -
                        TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
                //Seconds
                TimeUnit.MILLISECONDS.toSeconds(millis) -
                        TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));

getting as a result a correct format:

18:44:19

other option to get the format hh:mm:ss is just :

   Date myDate = new Date(timeinMillis);
   SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
   String myTime = formatter.format(myDate);

JQuery Parsing JSON array

var dataArray = [];
var obj = jQuery.parseJSON(yourInput);

$.each(obj, function (index, value) {
    dataArray.push([value["yourID"].toString(), value["yourValue"] ]);
});

this helps me a lot :-)

What is the difference between Integrated Security = True and Integrated Security = SSPI?

In my point of view,

If you dont use Integrated security=SSPI,then you need to hardcode the username and password in the connection string which means "relatively insecure" why because, all the employees have the access even ex-employee could use the information maliciously.

How might I convert a double to the nearest integer value?

For Unity, use Mathf.RoundToInt.

using UnityEngine;

public class ExampleScript : MonoBehaviour
{
    void Start()
    {
        // Prints 10
        Debug.Log(Mathf.RoundToInt(10.0f));
        // Prints 10
        Debug.Log(Mathf.RoundToInt(10.2f));
        // Prints 11
        Debug.Log(Mathf.RoundToInt(10.7f));
        // Prints 10
        Debug.Log(Mathf.RoundToInt(10.5f));
        // Prints 12
        Debug.Log(Mathf.RoundToInt(11.5f));

        // Prints -10
        Debug.Log(Mathf.RoundToInt(-10.0f));
        // Prints -10
        Debug.Log(Mathf.RoundToInt(-10.2f));
        // Prints -11
        Debug.Log(Mathf.RoundToInt(-10.7f));
        // Prints -10
        Debug.Log(Mathf.RoundToInt(-10.5f));
        // Prints -12
        Debug.Log(Mathf.RoundToInt(-11.5f));
    }
}

Source

public static int RoundToInt(float f) { return (int)Math.Round(f); }

CSS show div background image on top of other contained elements

How about making the <div id="mainWrapperDivWithBGImage"> as three divs, where the two outside divs hold the rounded corners images, and the middle div simply has a background-color to match the rounded corner images. Then you could simply place the other elements inside the middle div, or:

#outside_left{width:10px; float:left;}
#outside_right{width:10px; float:right;}
#middle{background-color:#color of rnd_crnrs_foo.gif; float:left;}

Then

HTML:

<div id="mainWrapperDivWithBGImage">
  <div id="outside_left><img src="rnd_crnrs_left.gif" /></div>
  <div id="middle">
    <div id="another_div"><img src="foo.gif" /></div>
  <div id="outside_right><img src="rnd_crnrs_right.gif" /></div>
</div>

You may have to do position:relative; and such.

What is difference between monolithic and micro kernel?

Monolithic kernel has all kernel services along with kernel core part, thus are heavy and has negative impact on speed and performance. On the other hand micro kernel is lightweight causing increase in performance and speed.
I answered same question at wordpress site. For the difference between monolithic, microkernel and exokernel in tabular form, you can visit here

How to make a website secured with https

4.Do I need to make all my pages secured or only the login page...

Just keep the login page under https

this will ensure there is no overhead when browsing other pages. the condition is you need to provide correct authentication settings in the web config. This is to ensure users who are not logged in will not be able to browse pages that would need authentication.

java how to use classes in other package?

You have to provide the full path that you want to import.

import com.my.stuff.main.Main;
import com.my.stuff.second.*;

So, in your main class, you'd have:

package com.my.stuff.main

import com.my.stuff.second.Second;   // THIS IS THE IMPORTANT LINE FOR YOUR QUESTION

class Main {
   public static void main(String[] args) {
      Second second = new Second();
      second.x();  
   }
}

EDIT: adding example in response to Shawn D's comment

There is another alternative, as Shawn D points out, where you can specify the full package name of the object that you want to use. This is very useful in two locations. First, if you're using the class exactly once:

class Main {
    void function() {
        int x = my.package.heirarchy.Foo.aStaticMethod();

        another.package.heirarchy.Baz b = new another.package.heirarchy.Bax();
    }
}

Alternatively, this is useful when you want to differentiate between two classes with the same short name:

class Main {
    void function() {
        java.util.Date utilDate = ...;
        java.sql.Date sqlDate = ...;
    }
}

How to decrypt Hash Password in Laravel

For compare hashed password with the plain text password string you can use the PHP password_verify

if(password_verify('1234567', $crypt_password_string)) {
    // in case if "$crypt_password_string" actually hides "1234567"
}

Android Push Notifications: Icon not displaying in notification, white square shown instead

I really suggest following Google's Design Guidelines:

which says "Notification icons must be entirely white."

How can I use a JavaScript variable as a PHP variable?

<script type="text/javascript">
var jvalue = 'this is javascript value';

<?php $abc = "<script>document.write(jvalue)</script>"?>   
</script>
<?php echo  'php_'.$abc;?>

Format numbers in thousands (K) in Excel

The examples above use a 'K' an uppercase k used to represent kilo or 1000. According to wiki, kilo or 1000's should be represented in lower case. So, rather than £300K, use £300k or in a code example :-

[>=1000]£#,##0,"k";[red][<=-1000]-£#,##0,"k";0

Eloquent get only one column as an array

I came across this question and thought I would clarify that the lists() method of a eloquent builder object was depreciated in Laravel 5.2 and replaced with pluck().

// <= Laravel 5.1
Word_relation::where('word_one', $word_id)->lists('word_one')->toArray();
// >= Laravel 5.2
Word_relation::where('word_one', $word_id)->pluck('word_one')->toArray();

These methods can also be called on a Collection for example

// <= Laravel 5.1
  $collection = Word_relation::where('word_one', $word_id)->get();
  $array = $collection->lists('word_one');

// >= Laravel 5.2
  $collection = Word_relation::where('word_one', $word_id)->get();
  $array = $collection->pluck('word_one');

Programmatically Hide/Show Android Soft Keyboard

Did you try InputMethodManager.SHOW_IMPLICIT in first window.

and for hiding in second window use InputMethodManager.HIDE_IMPLICIT_ONLY

EDIT :

If its still not working then probably you are putting it at the wrong place. Override onFinishInflate() and show/hide there.

@override
public void onFinishInflate() {
     /* code to show keyboard on startup */
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(mUserNameEdit, InputMethodManager.SHOW_IMPLICIT);
}

Generate getters and setters in NetBeans

Position the cursor inside the class, then press ALT + Ins and select Getters and Setters from the contextual menu.

The maximum recursion 100 has been exhausted before statement completion

it is just a sample to avoid max recursion error. we have to use option (maxrecursion 365); or option (maxrecursion 0);

DECLARE @STARTDATE datetime; 
DECLARE @EntDt datetime; 
set @STARTDATE = '01/01/2009';  
set @EntDt = '12/31/2009'; 
declare @dcnt int; 
;with DateList as   
 (   
    select @STARTDATE DateValue   
    union all   
    select DateValue + 1 from    DateList      
    where   DateValue + 1 < convert(VARCHAR(15),@EntDt,101)   
 )   
  select count(*) as DayCnt from (   
  select DateValue,DATENAME(WEEKDAY, DateValue ) as WEEKDAY from DateList
  where DATENAME(WEEKDAY, DateValue ) not IN ( 'Saturday','Sunday' )     
  )a
option (maxrecursion 365);

CSS Calc Viewport Units Workaround?

As a workaround you can use the fact percent vertical padding and margin are computed from the container width. It's quite a ugly solution and I don't know if you'll be able to use it but well, it works: http://jsfiddle.net/bFWT9/

<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
    <body>
        <div>It works!</div>
    </body>
</html>

html, body, div {
    height: 100%;
}
body {
    margin: 0;
}
div {
    box-sizing: border-box;
    margin-top: -75%;
    padding-top: 75%;
    background: #d35400;
    color: #fff;
}

WARNING: UNPROTECTED PRIVATE KEY FILE! when trying to SSH into Amazon EC2 Instance

The private key file should be protected. In my case i have been using the public_key authentication for a long time and i used to set the permission as 600 (rw- --- ---) for private key and 644 (rw- r-- r--) and for the .ssh folder in the home folder you will have 700 permission (rwx --- ---). For setting this go to the user's home folder and run the following command


Set the 700 permission for .ssh folder

chmod 700 .ssh


Set the 600 permission for private key file

chmod 600 .ssh/id_rsa


Set 644 permission for public key file

chmod 644 .ssh/id_rsa.pub

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32'

Is the action method on your form pointing to /controller/edit/1?

Try using one of these:

// the null in the last position is the html attributes, which you usually won't use
// on a form.  These invocations are kinda ugly
Html.BeginForm("Edit", "User", new { Id = Model.Id }, FormMethod.Post, null)

Html.BeginForm(new { action="Edit", controller="User", id = Model.Id })

Or inside your form add a hidden "Id" field

@Html.HiddenFor(m => m.Id)

Under what circumstances can I call findViewById with an Options Menu / Action Bar item?

I am trying to obtain a handle on one of the views in the Action Bar

I will assume that you mean something established via android:actionLayout in your <item> element of your <menu> resource.

I have tried calling findViewById(R.id.menu_item)

To retrieve the View associated with your android:actionLayout, call findItem() on the Menu to retrieve the MenuItem, then call getActionView() on the MenuItem. This can be done any time after you have inflated the menu resource.

How to make inline functions in C#

Not only Inside methods, it can be used inside classes also.

class Calculator
    {
        public static int Sum(int x,int y) => x + y;
        public static Func<int, int, int>  Add = (x, y) => x + y;
        public static Action<int,int> DisplaySum = (x, y) => Console.WriteLine(x + y);
    }

jQuery if checkbox is checked

See main difference between ATTR | PROP | IS below:

Source: http://api.jquery.com/attr/

_x000D_
_x000D_
$( "input" )_x000D_
  .change(function() {_x000D_
    var $input = $( this );_x000D_
    $( "p" ).html( ".attr( 'checked' ): <b>" + $input.attr( "checked" ) + "</b><br>" +_x000D_
      ".prop( 'checked' ): <b>" + $input.prop( "checked" ) + "</b><br>" +_x000D_
      ".is( ':checked' ): <b>" + $input.is( ":checked" ) + "</b>" );_x000D_
  })_x000D_
  .change();
_x000D_
p {_x000D_
    margin: 20px 0 0;_x000D_
  }_x000D_
  b {_x000D_
    color: blue;_x000D_
  }
_x000D_
<meta charset="utf-8">_x000D_
  <title>attr demo</title>_x000D_
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
 _x000D_
<input id="check1" type="checkbox" checked="checked">_x000D_
<label for="check1">Check me</label>_x000D_
<p></p>_x000D_
 _x000D_
_x000D_
 _x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

sorting and paging with gridview asp.net

<asp:GridView 
    ID="GridView1" runat="server" AutoGenerateColumns="false" AllowSorting="True" onsorting="GridView1_Sorting" EnableViewState="true"> 
    <Columns>
        <asp:BoundField DataField="bookid" HeaderText="BOOK ID"SortExpression="bookid"  />
        <asp:BoundField DataField="bookname" HeaderText="BOOK NAME" />
        <asp:BoundField DataField="writer" HeaderText="WRITER" />
        <asp:BoundField DataField="totalbook" HeaderText="TOTALBOOK" SortExpression="totalbook"  />
        <asp:BoundField DataField="availablebook" HeaderText="AVAILABLE BOOK" />
    </Columns>
</asp:GridView>

Code behind:

protected void Page_Load(object sender, EventArgs e) {
        if (!IsPostBack) {
            string query = "SELECT * FROM book";
            DataTable DT = new DataTable();
            SqlDataAdapter DA = new SqlDataAdapter(query, sqlCon);
            DA.Fill(DT);

            GridView1.DataSource = DT;
            GridView1.DataBind();
        }
    }

    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) {

        string query = "SELECT * FROM book";
        DataTable DT = new DataTable();
        SqlDataAdapter DA = new SqlDataAdapter(query, sqlCon);
        DA.Fill(DT);

        GridView1.DataSource = DT;
        GridView1.DataBind();

        if (DT != null) {
            DataView dataView = new DataView(DT);
            dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);

            GridView1.DataSource = dataView;
            GridView1.DataBind();
        }
    }

    private string GridViewSortDirection {
        get { return ViewState["SortDirection"] as string ?? "DESC"; }
        set { ViewState["SortDirection"] = value; }
    }

    private string ConvertSortDirectionToSql(SortDirection sortDirection) {
        switch (GridViewSortDirection) {
            case "ASC":
                GridViewSortDirection = "DESC";
                break;

            case "DESC":
                GridViewSortDirection = "ASC";
                break;
        }

        return GridViewSortDirection;
    }
}

Extracting first n columns of a numpy matrix

I know this is quite an old question -

A = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]

Let's say, you want to extract the first 2 rows and first 3 columns

A_NEW = A[0:2, 0:3]
A_NEW = [[1, 2, 3],
         [4, 5, 6]]

Understanding the syntax

A_NEW = A[start_index_row : stop_index_row, 
          start_index_column : stop_index_column)]

If one wants row 2 and column 2 and 3

A_NEW = A[1:2, 1:3]

Reference the numpy indexing and slicing article - Indexing & Slicing

Loop through JSON in EJS

JSON.stringify returns a String. So, for example:

var data = [
    { id: 1, name: "bob" },
    { id: 2, name: "john" },
    { id: 3, name: "jake" },
];

JSON.stringify(data)

will return the equivalent of:

"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]"

as a String value.

So when you have

<% for(var i=0; i<JSON.stringify(data).length; i++) {%>

what that ends up looking like is:

<% for(var i=0; i<"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]".length; i++) {%>

which is probably not what you want. What you probably do want is something like this:

<table>
<% for(var i=0; i < data.length; i++) { %>
   <tr>
     <td><%= data[i].id %></td>
     <td><%= data[i].name %></td>
   </tr>
<% } %>
</table>

This will output the following table (using the example data from above):

<table>
  <tr>
    <td>1</td>
    <td>bob</td>
  </tr>
  <tr>
    <td>2</td>
    <td>john</td>
  </tr>
  <tr>
    <td>3</td>
    <td>jake</td>
  </tr>
</table>

Why do I get a warning icon when I add a reference to an MEF plugin project?

Make sure you have the projects targeting the same framework version. Most of the times the reason would be that current project ( where you are adding reference of another project ) points to a different .net framework version than the rest ones.

Parse JSON with R

The jsonlite package is easy to use and tries to convert json into data frames.

Example:

library(jsonlite)

# url with some information about project in Andalussia
url <- 'http://www.juntadeandalucia.es/export/drupaljda/ayudas.json'

# read url and convert to data.frame
document <- fromJSON(txt=url)

Simple java program of pyramid

public static void printPyramid(int number) {
    int size = 5;
    for (int k = 1; k <= size; k++) {
        for (int i = (size+2); i > k; i--) {
            System.out.print(" ");
        }
        for (int j = 1; j <= k; j++) {
            System.out.print(" *");
        }
        System.out.println();
    }
}

Filename too long in Git for Windows

Move repository to root of your drive (temporary fix)

You can try to temporarily move the local repository (the entire folder) to the root of your drive or as close to the root as possible.

Since the path is smaller at the root of the drive, it sometimes fixes the issues.

On Windows, I'd move this to C:\ or another drive's root.

Combining border-top,border-right,border-left,border-bottom in CSS

Or if all borders have same style, just:

border:10px;

Print "hello world" every X seconds

public class HelloWorld extends TimerTask{

    public void run() {

        System.out.println("Hello World");
    }
}


public class PrintHelloWorld {
    public static void main(String[] args) {
        Timer timer = new Timer();
        timer.schedule(new HelloWorld(), 0, 5000);

        while (true) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                System.out.println("InterruptedException Exception" + e.getMessage());
            }
        }
    }
}

infinite loop is created ad scheduler task is configured.

Pie chart with jQuery

jqPlot looks pretty good and it is open source.

Here's a link to the most impressive and up-to-date jqPlot examples.

How do I get the file name from a String containing the Absolute file path?

This answer works for me in c#:

using System.IO;
string fileName = Path.GetFileName("C:\Hello\AnotherFolder\The File Name.PDF");

Eclipse doesn't stop at breakpoints

Sometimes you do start the debug mode but the debugger doesn't actually get attached/gets detached. I've also had this issue a few times when my laptop was reacting really slowly. A reboot always solved it for me.

Also try doing a clean all (works miracles in Eclipse).

How can I String.Format a TimeSpan object with a custom format in .NET?

This is awesome one:

string.Format("{0:00}:{1:00}:{2:00}",
               (int)myTimeSpan.TotalHours,
               myTimeSpan.Minutes,
               myTimeSpan.Seconds);

Is JavaScript object-oriented?

Languages do not need to behave exactly like Java to be object-oriented. Everything in Javascript is an object; compare to C++ or earlier Java, which are widely considered object-oriented to some degree but still based on primitives. Polymorphism is a non-issue in Javascript, as it doesn't much care about types at all. The only core OO feature not directly supported by the syntax is inheritance, but that can easily be implemented however the programmer wants using prototypes: here is one such example.

Which exception should I raise on bad/illegal argument combinations in Python?

I would just raise ValueError, unless you need a more specific exception..

def import_to_orm(name, save=False, recurse=False):
    if recurse and not save:
        raise ValueError("save must be True if recurse is True")

There's really no point in doing class BadValueError(ValueError):pass - your custom class is identical in use to ValueError, so why not use that?

Python variables as keys to dict

A one-liner is:-

fruitdict = dict(zip(('apple','banana','carrot'), (1,'f', '3'))

SQL query for finding records where count > 1

create table payment(
    user_id int(11),
    account int(11) not null,
    zip int(11) not null,
    dt date not null
);

insert into payment values
(1,123,55555,'2009-12-12'),
(1,123,66666,'2009-12-12'),
(1,123,77777,'2009-12-13'),
(2,456,77777,'2009-12-14'),
(2,456,77777,'2009-12-14'),
(2,789,77777,'2009-12-14'),
(2,789,77777,'2009-12-14');

select foo.user_id, foo.cnt from
(select user_id,count(account) as cnt, dt from payment group by account, dt) foo
where foo.cnt > 1;

Unable to find the requested .Net Framework Data Provider. It may not be installed. - when following mvc3 asp.net tutorial

I had the same when following MvcMusicStore Tutorial in Part 4 and replaced the given connection String with this:

add name="MusicStoreEntities" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;database=MvcMusicStore;User ID=sa;password=" providerName="System.Data.SqlClient"/>

It worked for me.

android.content.res.Resources$NotFoundException: String resource ID Fatal Exception in Main

This always can happen in DataBinding. Try to stay away from adding logic in your bindings, including appending an empty string. You can make your own custom adapter, and use it multiple times.

@BindingAdapter("numericText")
fun numericText(textView: TextView, value: Number?) {
    value?.let {
        textView.text = value.toString()
    }
}

<TextView app:numericText="@{list.size()}" .../>

Reading inputStream using BufferedReader.readLine() is too slow

I have a longer test to try. This takes an average of 160 ns to read each line as add it to a List (Which is likely to be what you intended as dropping the newlines is not very useful.

public static void main(String... args) throws IOException {
    final int runs = 5 * 1000 * 1000;

    final ServerSocket ss = new ServerSocket(0);
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Socket serverConn = ss.accept();
                String line = "Hello World!\n";
                BufferedWriter br = new BufferedWriter(new OutputStreamWriter(serverConn.getOutputStream()));
                for (int count = 0; count < runs; count++)
                    br.write(line);
                serverConn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();

    Socket conn = new Socket("localhost", ss.getLocalPort());

    long start = System.nanoTime();
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;

    List<String> responseData = new ArrayList<String>();
    while ((line = in.readLine()) != null) {
        responseData.add(line);
    }
    long time = System.nanoTime() - start;
    System.out.println("Average time to read a line was " + time / runs + " ns.");
    conn.close();
    ss.close();
}

prints

Average time to read a line was 158 ns.

If you want to build a StringBuilder, keeping newlines I would suggets the following approach.

Reader r = new InputStreamReader(conn.getInputStream());
String line;

StringBuilder sb = new StringBuilder();
char[] chars = new char[4*1024];
int len;
while((len = r.read(chars))>=0) {
    sb.append(chars, 0, len);
}

Still prints

Average time to read a line was 159 ns.

In both cases, the speed is limited by the sender not the receiver. By optimising the sender, I got this timing down to 105 ns per line.

The activity must be exported or contain an intent-filter

Double check your manifest, your first activity should have tag

    <intent-filter>
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

inside of activity tag.

If that doesn't work, look for target build, which located in the left of run button (green-colored play button), it should be targeting "app" folder, not a particular activity. if it doesn't targeting "app", just click it and choose "app" from drop down list.

Hope it helps!

How to convert JSON string into List of Java object?

You can also use Gson for this scenario.

Gson gson = new Gson();
NameList nameList = gson.fromJson(data, NameList.class);

List<Name> list = nameList.getList();

Your NameList class could look like:

class NameList{
 List<Name> list;
 //getter and setter
}

multiple classes on single element html

It's a good practice if you need them. It's also a good practice is they make sense, so future coders can understand what you're doing.

But generally, no it's not a good practice to attach 10 class names to an object because most likely whatever you're using them for, you could accomplish the same thing with far fewer classes. Probably just 1 or 2.

To qualify that statement, javascript plugins and scripts may append far more classnames to do whatever it is they're going to do. Modernizr for example appends anywhere from 5 - 25 classes to your body tag, and there's a very good reason for it. jQuery UI appends lots of classnames when you use one of the widgets in that library.

How can I link a photo in a Facebook album to a URL

Unfortunately, no. This feature is not available for facebook albums.

How to increment datetime by custom months in python without using library

Well with some tweaks and use of timedelta here we go:

from datetime import datetime, timedelta


def inc_date(origin_date):
    day = origin_date.day
    month = origin_date.month
    year = origin_date.year
    if origin_date.month == 12:
        delta = datetime(year + 1, 1, day) - origin_date
    else:
        delta = datetime(year, month + 1, day) - origin_date
    return origin_date + delta

final_date = inc_date(datetime.today())
print final_date.date()

What does character set and collation mean exactly?

From MySQL docs:

A character set is a set of symbols and encodings. A collation is a set of rules for comparing characters in a character set. Let's make the distinction clear with an example of an imaginary character set.

Suppose that we have an alphabet with four letters: 'A', 'B', 'a', 'b'. We give each letter a number: 'A' = 0, 'B' = 1, 'a' = 2, 'b' = 3. The letter 'A' is a symbol, the number 0 is the encoding for 'A', and the combination of all four letters and their encodings is a character set.

Now, suppose that we want to compare two string values, 'A' and 'B'. The simplest way to do this is to look at the encodings: 0 for 'A' and 1 for 'B'. Because 0 is less than 1, we say 'A' is less than 'B'. Now, what we've just done is apply a collation to our character set. The collation is a set of rules (only one rule in this case): "compare the encodings." We call this simplest of all possible collations a binary collation.

But what if we want to say that the lowercase and uppercase letters are equivalent? Then we would have at least two rules: (1) treat the lowercase letters 'a' and 'b' as equivalent to 'A' and 'B'; (2) then compare the encodings. We call this a case-insensitive collation. It's a little more complex than a binary collation.

In real life, most character sets have many characters: not just 'A' and 'B' but whole alphabets, sometimes multiple alphabets or eastern writing systems with thousands of characters, along with many special symbols and punctuation marks. Also in real life, most collations have many rules: not just case insensitivity but also accent insensitivity (an "accent" is a mark attached to a character as in German 'ö') and multiple-character mappings (such as the rule that 'ö' = 'OE' in one of the two German collations).

Is it wrong to place the <script> tag after the </body> tag?

Google actually recommends this in regards to 'CSS Optimization'. They recommend in-lining critical above-fold styles and deferring the rest(css file).

Example:

<html>
  <head>
    <style>
      .blue{color:blue;}
    </style>
    </head>
  <body>
    <div class="blue">
      Hello, world!
    </div>
  </body>
</html>
<noscript><link rel="stylesheet" href="small.css"></noscript>

See: https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery

Validate date in dd/mm/yyyy format using JQuery Validate

You don't need the date validator. It doesn't support dd/mm/yyyy format, and that's why you are getting "Please enter a valid date" message for input like 13/01/2014. You already have the dateITA validator, which uses dd/mm/yyyy format as you need.

Just like the date validator, your code for dateGreaterThan and dateLessThan calls new Date for input string and has the same issue parsing dates. You can use a function like this to parse the date:

function parseDMY(value) {
    var date = value.split("/");
    var d = parseInt(date[0], 10),
        m = parseInt(date[1], 10),
        y = parseInt(date[2], 10);
    return new Date(y, m - 1, d);
}

Difference between Static methods and Instance methods

The static modifier when placed in front of a function implies that only one copy of that function exists. If the static modifier is not placed in front of the function then with every object or instance of that class a new copy of that function is made. :) Same is the case with variables.

Get value (String) of ArrayList<ArrayList<String>>(); in Java

listOfSomething.Clear();
listOfSomething.Add("first");
collection.Add(listOfSomething);

You are clearing the list here and adding one element ("first"), the 1st reference of listOfSomething is updated as well sonce both reference the same object, so when you access the second element myList.get(1) (which does not exist anymore) you get the null.

Notice both collection.Add(listOfSomething); save two references to the same arraylist object.

You need to create two different instances for two elements:

ArrayList<ArrayList<String>> collection = new ArrayList<ArrayList<String>>();

ArrayList<String> listOfSomething1 = new ArrayList<String>();
listOfSomething1.Add("first");
listOfSomething1.Add("second");

ArrayList<String> listOfSomething2 = new ArrayList<String>();
listOfSomething2.Add("first");

collection.Add(listOfSomething1);    
collection.Add(listOfSomething2);

Dynamic type languages versus static type languages

The ability of the interpreter to deduce type and type conversions makes development time faster, but it also can provoke runtime failures which you just cannot get in a statically typed language where you catch them at compile time. But which one's better (or even if that's always true) is hotly discussed in the community these days (and since a long time).

A good take on the issue is from Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages by Erik Meijer and Peter Drayton at Microsoft:

Advocates of static typing argue that the advantages of static typing include earlier detection of programming mistakes (e.g. preventing adding an integer to a boolean), better documentation in the form of type signatures (e.g. incorporating number and types of arguments when resolving names), more opportunities for compiler optimizations (e.g. replacing virtual calls by direct calls when the exact type of the receiver is known statically), increased runtime efficiency (e.g. not all values need to carry a dynamic type), and a better design time developer experience (e.g. knowing the type of the receiver, the IDE can present a drop-down menu of all applicable members). Static typing fanatics try to make us believe that “well-typed programs cannot go wrong”. While this certainly sounds impressive, it is a rather vacuous statement. Static type checking is a compile-time abstraction of the runtime behavior of your program, and hence it is necessarily only partially sound and incomplete. This means that programs can still go wrong because of properties that are not tracked by the type-checker, and that there are programs that while they cannot go wrong cannot be type-checked. The impulse for making static typing less partial and more complete causes type systems to become overly complicated and exotic as witnessed by concepts such as “phantom types” [11] and “wobbly types” [10]. This is like trying to run a marathon with a ball and chain tied to your leg and triumphantly shouting that you nearly made it even though you bailed out after the first mile.

Advocates of dynamically typed languages argue that static typing is too rigid, and that the softness of dynamically languages makes them ideally suited for prototyping systems with changing or unknown requirements, or that interact with other systems that change unpredictably (data and application integration). Of course, dynamically typed languages are indispensable for dealing with truly dynamic program behavior such as method interception, dynamic loading, mobile code, runtime reflection, etc. In the mother of all papers on scripting [16], John Ousterhout argues that statically typed systems programming languages make code less reusable, more verbose, not more safe, and less expressive than dynamically typed scripting languages. This argument is parroted literally by many proponents of dynamically typed scripting languages. We argue that this is a fallacy and falls into the same category as arguing that the essence of declarative programming is eliminating assignment. Or as John Hughes says [8], it is a logical impossibility to make a language more powerful by omitting features. Defending the fact that delaying all type-checking to runtime is a good thing, is playing ostrich tactics with the fact that errors should be caught as early in the development process as possible.

Argparse: Required arguments listed under "optional arguments"?

Parameters starting with - or -- are usually considered optional. All other parameters are positional parameters and as such required by design (like positional function arguments). It is possible to require optional arguments, but this is a bit against their design. Since they are still part of the non-positional arguments, they will still be listed under the confusing header “optional arguments” even if they are required. The missing square brackets in the usage part however show that they are indeed required.

See also the documentation:

In general, the argparse module assumes that flags like -f and --bar indicate optional arguments, which can always be omitted at the command line.

Note: Required options are generally considered bad form because users expect options to be optional, and thus they should be avoided when possible.

That being said, the headers “positional arguments” and “optional arguments” in the help are generated by two argument groups in which the arguments are automatically separated into. Now, you could “hack into it” and change the name of the optional ones, but a far more elegant solution would be to create another group for “required named arguments” (or whatever you want to call them):

parser = argparse.ArgumentParser(description='Foo')
parser.add_argument('-o', '--output', help='Output file name', default='stdout')
requiredNamed = parser.add_argument_group('required named arguments')
requiredNamed.add_argument('-i', '--input', help='Input file name', required=True)
parser.parse_args(['-h'])
usage: [-h] [-o OUTPUT] -i INPUT

Foo

optional arguments:
  -h, --help            show this help message and exit
  -o OUTPUT, --output OUTPUT
                        Output file name

required named arguments:
  -i INPUT, --input INPUT
                        Input file name

What causes: "Notice: Uninitialized string offset" to appear?

The error may occur when the number of times you iterate the array is greater than the actual size of the array. for example:

 $one="909";
 for($i=0;$i<10;$i++)
    echo ' '.$one[$i];

will show the error. first case u can take the mod of i.. for example

function mod($i,$length){
  $m = $i % $size;
  if ($m > $size)
  mod($m,$size)
  return $m;
}

for($i=0;$i<10;$i++)
{
  $k=mod($i,3);
  echo ' '.$one[$k];
}

or might be it not an array (maybe it was a value and you tried to access it like an array) for example:

$k = 2;
$k[0];

Problems with installation of Google App Engine SDK for php in OS X

It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:

openssl sha1 [put the full path to the file here without brackets] 

For example:

openssl sha1 /Users/me/Desktop/myFile.dmg 

If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.

SQL Developer with JDK (64 bit) cannot find JVM

If folder sqldeveloper/jdk doesn't contain folder bin, you can copy folder bin from folder sqldeveloper/jdk/jre into sqldeveloper/jdk.

Why does modulus division (%) only work with integers?

The modulo operator % in C and C++ is defined for two integers, however, there is an fmod() function available for usage with doubles.

How to multiply duration by integer?

For multiplication of variable to time.Second using following code

    oneHr:=3600
    addOneHrDuration :=time.Duration(oneHr)
    addOneHrCurrTime := time.Now().Add(addOneHrDuration*time.Second)

Python dictionary get multiple values

As I see no similar answer here - it is worth pointing out that with the usage of a (list / generator) comprehension, you can unpack those multiple values and assign them to multiple variables in a single line of code:

first_val, second_val = (myDict.get(key) for key in [first_key, second_key])

Possible to perform cross-database queries with PostgreSQL?

If performance is important and most queries are read-only, I would suggest to replicate data over to another database. While this seems like unneeded duplication of data, it might help if indexes are required.

This can be done with simple on insert triggers which in turn call dblink to update another copy. There are also full-blown replication options (like Slony) but that's off-topic.

Best way to check for IE less than 9 in JavaScript without library

Javascript

var ie = (function(){

    var undef,
        v = 3,
        div = document.createElement('div'),
        all = div.getElementsByTagName('i');

    while (
        div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
        all[0]
    );

    return v > 4 ? v : undef;

}());

You can then do:

ie < 9

By James Panolsey from here: http://james.padolsey.com/javascript/detect-ie-in-js-using-conditional-comments

ArrayList filter

Iterate through the list and check if contains your string "How" and if it does then remove. You can use following code:

// need to construct a new ArrayList otherwise remove operation will not be supported
List<String> list = new ArrayList<String>(Arrays.asList(new String[] 
                                  {"How are you?", "How you doing?","Joe", "Mike"}));
System.out.println("List Before: " + list);
for (Iterator<String> it=list.iterator(); it.hasNext();) {
    if (!it.next().contains("How"))
        it.remove(); // NOTE: Iterator's remove method, not ArrayList's, is used.
}
System.out.println("List After: " + list);

OUTPUT:

List Before: [How are you?, How you doing?, Joe, Mike]
List After: [How are you?, How you doing?]

convert a list of objects from one type to another using lambda expression

Try the following

var targetList = origList
  .Select(x => new TargetType() { SomeValue = x.SomeValue })
  .ToList();

This is using a combination of Lambdas and LINQ to achieve the solution. The Select function is a projection style method which will apply the passed in delegate (or lambda in this case) to every value in the original collection. The result will be returned in a new IEnumerable<TargetType>. The .ToList call is an extension method which will convert this IEnumerable<TargetType> into a List<TargetType>.

What does the red exclamation point icon in Eclipse mean?

I found another scenario in which the red exclamation mark might appear. I copied a directory from one project to another. This directory included a hidden .svn directory (the original project had been committed to version control). When I checked my new project into SVN, the copied directory still contained the old SVN information, incorrectly identifying itself as an element in its original project.

I discovered the problem by looking at the Properties for the directory, selecting SVN Info, and reviewing the Resource URL. I fixed the problem by deleting the hidden .svn directory for my copied directory and refreshing my project. The red exclamation mark disappeared, and I was able to check in the directory and its contents correctly.

Downloading folders from aws s3, cp or sync?

sync method first lists both source and destination paths and copies only differences (name, size etc.).

cp --recursive method lists source path and copies (overwrites) all to the destination path.

If you have possible matches in the destination path, I would suggest sync as one LIST request on the destination path will save you many unnecessary PUT requests - meaning cheaper and possibly faster.

How can I convert a Unix timestamp to DateTime and vice versa?

To supplement ScottCher's answer, I recently found myself in the annoying scenario of having both seconds and milliseconds UNIX timestamps arbitrarily mixed together in an input data set. The following code seems to handle this well:

static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
static readonly double MaxUnixSeconds = (DateTime.MaxValue - UnixEpoch).TotalSeconds;

public static DateTime UnixTimeStampToDateTime(double unixTimeStamp)
{
   return unixTimeStamp > MaxUnixSeconds
      ? UnixEpoch.AddMilliseconds(unixTimeStamp)
      : UnixEpoch.AddSeconds(unixTimeStamp);
}

heroku - how to see all the logs

for WAR files:

I did not use github, instead I uploaded directly, a WAR file ( which I found to be much easier and faster ).

So the following helped me:

heroku logs --app appname

Hope it will help someone.

MySQL Insert into multiple tables? (Database normalization?)

What would happen, if you want to create many such records ones (to register 10 users, not just one)? I find the following solution (just 5 queryes):

Step I: Create temporary table to store new data.

CREATE TEMPORARY TABLE tmp (id bigint(20) NOT NULL, ...)...;

Next, fill this table with values.

INSERT INTO tmp (username, password, bio, homepage) VALUES $ALL_VAL

Here, instead of $ALL_VAL you place list of values: ('test1','test1','bio1','home1'),...,('testn','testn','bion','homen')

Step II: Send data to 'user' table.

INSERT IGNORE INTO users (username, password)
SELECT username, password FROM tmp;

Here, "IGNORE" can be used, if you allow some users already to be inside. Optionaly you can use UPDATE similar to step III, before this step, to find whom users are already inside (and mark them in tmp table). Here we suppouse, that username is declared as PRIMARY in users table.

Step III: Apply update to read all users id from users to tmp table. THIS IS ESSENTIAL STEP.

UPDATE tmp JOIN users ON tmp.username=users.username SET tmp.id=users.id

Step IV: Create another table, useing read id for users

INSERT INTO profiles (userid, bio, homepage) 
SELECT id, bio, homepage FROM tmp

Code signing is required for product type 'Application' in SDK 'iOS5.1'

I had same problem with an Apple Sample Code. In project "PhotoPicker", in Architectures, the base SDK was:

screen shot 1

This parametrization provokes the message:

CodeSign error: code signing is required for product type 'Application' in SDK 'iOS 7.1'

It assumes you have a developer user, so... use it and change:

screen shot 2

And the error disappears.

window.location (JS) vs header() (PHP) for redirection

The first case will fail when JS is off. It's also a little bit slower since JS must be parsed first (DOM must be loaded). However JS is safer since the destination doesn't know the referer and your redirect might be tracked (referers aren't reliable in general yet this is something).

You can also use meta refresh tag. It also requires DOM to be loaded.

How to break line in JavaScript?

Add %0D%0A to any place you want to encode a line break on the URL.

  • %0D is a carriage return character
  • %0A is a line break character

This is the new line sequence on windows machines, though not the same on linux and macs, should work in both.

If you want a linebreak in actual javascript, use the \n escape sequence.


onClick="parent.location='mailto:[email protected]?subject=Thanks for writing to me &body=I will get back to you soon.%0D%0AThanks and Regards%0D%0ASaurav Kumar'

generating variable names on fly in python

Another example, which is really a variation of another answer, in that it uses a dictionary too:

>>> vr={} 
... for num in range(1,4): 
...     vr[str(num)] = 5 + num
...     
>>> print vr["3"]
8
>>> 

Load text file as strings using numpy.loadtxt()

There is also read_csv in Pandas, which is fast and supports non-comma column separators and automatic typing by column:

import pandas as pd
df = pd.read_csv('your_file',sep='\t')

It can be converted to a NumPy array if you prefer that type with:

import numpy as np
arr = np.array(df)

This is by far the easiest and most mature text import approach I've come across.

re.sub erroring with "Expected string or bytes-like object"

The simplest solution is to apply Python str function to the column you are trying to loop through.

If you are using pandas, this can be implemented as:

dataframe['column_name']=dataframe['column_name'].apply(str)

How do I pretty-print existing JSON data with Java?

Underscore-java library has methods U.formatJson(json) and U.formatXml(xml). I am the maintainer of the project.

Matplotlib: Specify format of floats for tick labels

In matplotlib 3.1, you can also use ticklabel_format. To prevents scientific notation without offsets:

plt.gca().ticklabel_format(axis='both', style='plain', useOffset=False)

How to install PIP on Python 3.6?

pip is bundled with Python > 3.4

On Unix-like systems use:

python3.6 -m pip install [Package_to_install]

On a Windows system use:

py -m pip install [Package_to_install]

(On Windows you may need to run the command prompt as administrator to be able to write into python installation directory)

Anchor links in Angularjs?

I don't know if that answers your question, but yes, you can use angularjs links, such as:

<a ng-href="http://www.gravatar.com/avatar/{{hash}}"/>

There is a good example on the AngularJS website:

http://docs.angularjs.org/api/ng.directive:ngHref

UPDATE: The AngularJS documentation was a bit obscure and it didn't provide a good solution for it. Sorry!

You can find a better solution here: How to handle anchor hash linking in AngularJS

SQL Server: Null VS Empty String

NULL values are stored separately in a special bitmap space for all the columns.

If you do not distinguish between NULL and '' in your application, then I would recommend you to store '' in your tables (unless the string column is a foreign key, in which case it would probably be better to prohibit the column from storing empty strings and allow the NULLs, if that is compatible with the logic of your application).

CSS vertical alignment of inline/inline-block elements

vertical-align applies to the elements being aligned, not their parent element. To vertically align the div's children, do this instead:

div > * {
    vertical-align:middle;  // Align children to middle of line
}

See: http://jsfiddle.net/dfmx123/TFPx8/1186/

NOTE: vertical-align is relative to the current text line, not the full height of the parent div. If you wanted the parent div to be taller and still have the elements vertically centered, set the div's line-height property instead of its height. Follow jsfiddle link above for an example.

Get property value from C# dynamic object by string (reflection?)

you can try like this:

d?.property1 , d?.property2

I have tested it and working with .netcore 2.1

Map vs Object in JavaScript

The key difference is that Objects only support string and Symbol keys where as Maps support more or less any key type.

If I do obj[123] = true and then Object.keys(obj) then I will get ["123"] rather than [123]. A Map would preserve the type of the key and return [123] which is great. Maps also allow you to use Objects as keys. Traditionally to do this you would have to give objects some kind of unique identifier to hash them (I don't think I've ever seen anything like getObjectId in JS as part of the standard). Maps also guarantee preservation of order so are all round better for preservation and can sometimes save you needing to do a few sorts.

Between maps and objects in practice there are several pros and cons. Objects gain both advantages and disadvantages being very tightly integrated into the core of JavaScript which sets them apart from significantly Map beyond the difference in key support.

An immediate advantage is that you have syntactical support for Objects making it easy to access elements. You also have direct support for it with JSON. When used as a hash it's annoying to get an object without any properties at all. By default if you want to use Objects as a hash table they will be polluted and you will often have to call hasOwnProperty on them when accessing properties. You can see here how by default Objects are polluted and how to create hopefully unpolluted objects for use as hashes:

({}).toString
    toString() { [native code] }
JSON.parse('{}').toString
    toString() { [native code] }
(Object.create(null)).toString
    undefined
JSON.parse('{}', (k,v) => (typeof v === 'object' && Object.setPrototypeOf(v, null) ,v)).toString
    undefined

Pollution on objects is not only something that makes code more annoying, slower, etc but can also have potential consequences for security.

Objects are not pure hash tables but are trying to do more. You have headaches like hasOwnProperty, not being able to get the length easily (Object.keys(obj).length) and so on. Objects are not meant to purely be used as hash maps but as dynamic extensible Objects as well and so when you use them as pure hash tables problems arise.

Comparison/List of various common operations:

    Object:
       var o = {};
       var o = Object.create(null);
       o.key = 1;
       o.key += 10;
       for(let k in o) o[k]++;
       var sum = 0;
       for(let v of Object.values(m)) sum += v;
       if('key' in o);
       if(o.hasOwnProperty('key'));
       delete(o.key);
       Object.keys(o).length
    Map:
       var m = new Map();
       m.set('key', 1);
       m.set('key', m.get('key') + 10);
       m.foreach((k, v) => m.set(k, m.get(k) + 1));
       for(let k of m.keys()) m.set(k, m.get(k) + 1);
       var sum = 0;
       for(let v of m.values()) sum += v;
       if(m.has('key'));
       m.delete('key');
       m.size();

There are a few other options, approaches, methodologies, etc with varying ups and downs (performance, terse, portable, extendable, etc). Objects are a bit strange being core to the language so you have a lot of static methods for working with them.

Besides the advantage of Maps preserving key types as well as being able to support things like objects as keys they are isolated from the side effects that objects much have. A Map is a pure hash, there's no confusion about trying to be an object at the same time. Maps can also be easily extended with proxy functions. Object's currently have a Proxy class however performance and memory usage is grim, in fact creating your own proxy that looks like Map for Objects currently performs better than Proxy.

A substantial disadvantage for Maps is that they are not supported with JSON directly. Parsing is possible but has several hangups:

JSON.parse(str, (k,v) => {
    if(typeof v !== 'object') return v;
    let m = new Map();
    for(k in v) m.set(k, v[k]);
    return m;
});

The above will introduce a serious performance hit and will also not support any string keys. JSON encoding is even more difficult and problematic (this is one of many approaches):

// An alternative to this it to use a replacer in JSON.stringify.
Map.prototype.toJSON = function() {
    return JSON.stringify({
        keys: Array.from(this.keys()),
        values: Array.from(this.values())
    });
};

This is not so bad if you're purely using Maps but will have problems when you are mixing types or using non-scalar values as keys (not that JSON is perfect with that kind of issue as it is, IE circular object reference). I haven't tested it but chances are that it will severely hurt performance compared to stringify.

Other scripting languages often don't have such problems as they have explicit non-scalar types for Map, Object and Array. Web development is often a pain with non-scalar types where you have to deal with things like PHP merges Array/Map with Object using A/M for properties and JS merges Map/Object with Array extending M/O. Merging complex types is the devil's bane of high level scripting languages.

So far these are largely issues around implementation but performance for basic operations is important as well. Performance is also complex because it depends on engine and usage. Take my tests with a grain of salt as I cannot rule out any mistake (I have to rush this). You should also run your own tests to confirm as mine examine only very specific simple scenarios to give a rough indication only. According to tests in Chrome for very large objects/maps the performance for objects is worse because of delete which is apparently somehow proportionate to the number of keys rather than O(1):

Object Set Took: 146
Object Update Took: 7
Object Get Took: 4
Object Delete Took: 8239
Map Set Took: 80
Map Update Took: 51
Map Get Took: 40
Map Delete Took: 2

Chrome clearly has a strong advantage with getting and updating but the delete performance is horrific. Maps use a tiny amount more memory in this case (overhead) but with only one Object/Map being tested with millions of keys the impact of overhead for maps is not expressed well. With memory management objects also do seem to free earlier if I am reading the profile correctly which might be one benefit in favor of objects.

In Firefox for this particular benchmark it is a different story:

Object Set Took: 435
Object Update Took: 126
Object Get Took: 50
Object Delete Took: 2
Map Set Took: 63
Map Update Took: 59
Map Get Took: 33
Map Delete Took: 1

I should immediately point out that in this particular benchmark deleting from objects in Firefox is not causing any problems, however in other benchmarks it has caused problems especially when there are many keys just as in Chrome. Maps are clearly superior in Firefox for large collections.

However this is not the end of the story, what about many small objects or maps? I have done a quick benchmark of this but not an exhaustive one (setting/getting) of which performs best with a small number of keys in the above operations. This test is more about memory and initialization.

Map Create: 69    // new Map
Object Create: 34 // {}

Again these figures vary but basically Object has a good lead. In some cases the lead for Objects over maps is extreme (~10 times better) but on average it was around 2-3 times better. It seems extreme performance spikes can work both ways. I only tested this in Chrome and creation to profile memory usage and overhead. I was quite surprised to see that in Chrome it appears that Maps with one key use around 30 times more memory than Objects with one key.

For testing many small objects with all the above operations (4 keys):

Chrome Object Took: 61
Chrome Map Took: 67
Firefox Object Took: 54
Firefox Map Took: 139

In terms of memory allocation these behaved the same in terms of freeing/GC but Map used 5 times more memory. This test used 4 keys where as in the last test I only set one key so this would explain the reduction in memory overhead. I ran this test a few times and Map/Object are more or less neck and neck overall for Chrome in terms of overall speed. In Firefox for small Objects there is a definite performance advantage over maps overall.

This of course doesn't include the individual options which could vary wildly. I would not advice micro-optimizing with these figures. What you can get out of this is that as a rule of thumb, consider Maps more strongly for very large key value stores and objects for small key value stores.

Beyond that the best strategy with these two it to implement it and just make it work first. When profiling it is important to keep in mind that sometimes things that you wouldn't think would be slow when looking at them can be incredibly slow because of engine quirks as seen with the object key deletion case.

How can I color Python logging output?

What about highlighting also log message arguments with alternating colors, in addition to coloring by level? I recently wrote simple code for that. Another advantage is that log call is made with Python 3 brace-style formatting. ("{}").

See latest code and examples here: https://github.com/davidohana/colargulog

Sample Logging code:

root_logger = logging.getLogger()
console_handler = logging.StreamHandler(stream=sys.stdout)
console_format = "%(asctime)s - %(levelname)-8s - %(name)-25s - %(message)s"
colored_formatter = ColorizedArgsFormatter(console_format)
console_handler.setFormatter(colored_formatter)
root_logger.addHandler(console_handler)

logger = logging.getLogger(__name__)
logger.info("Hello World")
logger.info("Request from {} handled in {:.3f} ms", socket.gethostname(), 11)
logger.info("Request from {} handled in {:.3f} ms", "127.0.0.1", 33.1)
logger.info("My favorite drinks are {}, {}, {}, {}", "milk", "wine", "tea", "beer")
logger.debug("this is a {} message", logging.getLevelName(logging.DEBUG))
logger.info("this is a {} message", logging.getLevelName(logging.INFO))
logger.warning("this is a {} message", logging.getLevelName(logging.WARNING))
logger.error("this is a {} message", logging.getLevelName(logging.ERROR))
logger.critical("this is a {} message", logging.getLevelName(logging.CRITICAL))
logger.info("Does old-style formatting also work? %s it is, but no colors (yet)", True)

Output:

enter image description here

Implementation:

"""
colargulog - Python3 Logging with Colored Arguments and new string formatting style

Written by [email protected]
License: Apache-2.0
"""

import logging
import logging.handlers
import re


class ColorCodes:
    grey = "\x1b[38;21m"
    green = "\x1b[1;32m"
    yellow = "\x1b[33;21m"
    red = "\x1b[31;21m"
    bold_red = "\x1b[31;1m"
    blue = "\x1b[1;34m"
    light_blue = "\x1b[1;36m"
    purple = "\x1b[1;35m"
    reset = "\x1b[0m"


class ColorizedArgsFormatter(logging.Formatter):
    arg_colors = [ColorCodes.purple, ColorCodes.light_blue]
    level_fields = ["levelname", "levelno"]
    level_to_color = {
        logging.DEBUG: ColorCodes.grey,
        logging.INFO: ColorCodes.green,
        logging.WARNING: ColorCodes.yellow,
        logging.ERROR: ColorCodes.red,
        logging.CRITICAL: ColorCodes.bold_red,
    }

    def __init__(self, fmt: str):
        super().__init__()
        self.level_to_formatter = {}

        def add_color_format(level: int):
            color = ColorizedArgsFormatter.level_to_color[level]
            _format = fmt
            for fld in ColorizedArgsFormatter.level_fields:
                search = "(%\(" + fld + "\).*?s)"
                _format = re.sub(search, f"{color}\\1{ColorCodes.reset}", _format)
            formatter = logging.Formatter(_format)
            self.level_to_formatter[level] = formatter

        add_color_format(logging.DEBUG)
        add_color_format(logging.INFO)
        add_color_format(logging.WARNING)
        add_color_format(logging.ERROR)
        add_color_format(logging.CRITICAL)

    @staticmethod
    def rewrite_record(record: logging.LogRecord):
        if not BraceFormatStyleFormatter.is_brace_format_style(record):
            return

        msg = record.msg
        msg = msg.replace("{", "_{{")
        msg = msg.replace("}", "_}}")
        placeholder_count = 0
        # add ANSI escape code for next alternating color before each formatting parameter
        # and reset color after it.
        while True:
            if "_{{" not in msg:
                break
            color_index = placeholder_count % len(ColorizedArgsFormatter.arg_colors)
            color = ColorizedArgsFormatter.arg_colors[color_index]
            msg = msg.replace("_{{", color + "{", 1)
            msg = msg.replace("_}}", "}" + ColorCodes.reset, 1)
            placeholder_count += 1

        record.msg = msg.format(*record.args)
        record.args = []

    def format(self, record):
        orig_msg = record.msg
        orig_args = record.args
        formatter = self.level_to_formatter.get(record.levelno)
        self.rewrite_record(record)
        formatted = formatter.format(record)

        # restore log record to original state for other handlers
        record.msg = orig_msg
        record.args = orig_args
        return formatted


class BraceFormatStyleFormatter(logging.Formatter):
    def __init__(self, fmt: str):
        super().__init__()
        self.formatter = logging.Formatter(fmt)

    @staticmethod
    def is_brace_format_style(record: logging.LogRecord):
        if len(record.args) == 0:
            return False

        msg = record.msg
        if '%' in msg:
            return False

        count_of_start_param = msg.count("{")
        count_of_end_param = msg.count("}")

        if count_of_start_param != count_of_end_param:
            return False

        if count_of_start_param != len(record.args):
            return False

        return True

    @staticmethod
    def rewrite_record(record: logging.LogRecord):
        if not BraceFormatStyleFormatter.is_brace_format_style(record):
            return

        record.msg = record.msg.format(*record.args)
        record.args = []

    def format(self, record):
        orig_msg = record.msg
        orig_args = record.args
        self.rewrite_record(record)
        formatted = self.formatter.format(record)

        # restore log record to original state for other handlers
        record.msg = orig_msg
        record.args = orig_args
        return formatted

When saving, how can you check if a field has changed?

The optimal solution is probably one that does not include an additional database read operation prior to saving the model instance, nor any further django-library. This is why laffuste's solutions is preferable. In the context of an admin site, one can simply override the save_model-method, and invoke the form's has_changed method there, just as in Sion's answer above. You arrive at something like this, drawing on Sion's example setting but using changed_data to get every possible change:

class ModelAdmin(admin.ModelAdmin):
   fields=['name','mode']
   def save_model(self, request, obj, form, change):
     form.changed_data #output could be ['name']
     #do somethin the changed name value...
     #call the super method
     super(self,ModelAdmin).save_model(request, obj, form, change)
  • Override save_model:

https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_model

  • Built-in changed_data-method for a Field:

https://docs.djangoproject.com/en/1.10/ref/forms/api/#django.forms.Form.changed_data

How to exit from Python without traceback?

The following code will not raise an exception and will exit without a traceback:

import os
os._exit(1)

See this question and related answers for more details. Surprised why all other answers are so overcomplicated.

Select every Nth element in CSS

As the name implies, :nth-child() allows you to construct an arithmetic expression using the n variable in addition to constant numbers. You can perform addition (+), subtraction (-) and coefficient multiplication (an where a is an integer, including positive numbers, negative numbers and zero).

Here's how you would rewrite the above selector list:

div:nth-child(4n)

For an explanation on how these arithmetic expressions work, see my answer to this question, as well as the spec.

Note that this answer assumes that all of the child elements within the same parent element are of the same element type, div. If you have any other elements of different types such as h1 or p, you will need to use :nth-of-type() instead of :nth-child() to ensure you only count div elements:

<body>
  <h1></h1>
  <div>1</div>  <div>2</div>
  <div>3</div>  <div>4</div>
  <h2></h2>
  <div>5</div>  <div>6</div>
  <div>7</div>  <div>8</div>
  <h2></h2>
  <div>9</div>  <div>10</div>
  <div>11</div> <div>12</div>
  <h2></h2>
  <div>13</div> <div>14</div>
  <div>15</div> <div>16</div>
</body>

For everything else (classes, attributes, or any combination of these), where you're looking for the nth child that matches an arbitrary selector, you will not be able to do this with a pure CSS selector. See my answer to this question.


By the way, there's not much of a difference between 4n and 4n + 4 with regards to :nth-child(). If you use the n variable, it starts counting at 0. This is what each selector would match:

:nth-child(4n)

4(0) = 0
4(1) = 4
4(2) = 8
4(3) = 12
4(4) = 16
...

:nth-child(4n+4)

4(0) + 4 = 0  + 4 = 4
4(1) + 4 = 4  + 4 = 8
4(2) + 4 = 8  + 4 = 12
4(3) + 4 = 12 + 4 = 16
4(4) + 4 = 16 + 4 = 20
...

As you can see, both selectors will match the same elements as above. In this case, there is no difference.

What does android:layout_weight mean?

If there are multiple views spanning a LinearLayout, then layout_weight gives them each a proportional size. A view with a bigger layout_weight value "weighs" more, so it gets a bigger space.

Here is an image to make things more clear.

enter image description here

Theory

The term layout weight is related to the concept of weighted average in math. It is like in a college class where homework is worth 30%, attendance is worth 10%, the midterm is worth 20%, and the final is worth 40%. Your scores for those parts, when weighted together, give you your total grade.

enter image description here

It is the same for layout weight. The Views in a horizontal LinearLayout can each take up a certain percentage of the total width. (Or a percentage of the height for a vertical LinearLayout.)

The Layout

The LinearLayout that you use will look something like this:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <!-- list of subviews -->

</LinearLayout>

Note that you must use layout_width="match_parent" for the LinearLayout. If you use wrap_content, then it won't work. Also note that layout_weight does not work for the views in RelativeLayouts (see here and here for SO answers dealing with this issue).

The Views

Each view in a horizontal LinearLayout looks something like this:

<Button
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1" />

Note that you need to use layout_width="0dp" together with layout_weight="1". Forgetting this causes many new users problems. (See this article for different results you can get by not setting the width to 0.) If your views are in a vertical LinearLayout then you would use layout_height="0dp", of course.

In the Button example above I set the weight to 1, but you can use any number. It is only the total that matters. You can see in the three rows of buttons in the first image that I posted, the numbers are all different, but since the proportions are the same, the weighted widths don't change in each row. Some people like to use decimal numbers that have a sum of 1 so that in a complex layout it is clear what the weight of each part is.

One final note. If you have lots of nested layouts that use layout_weight, it can be bad for performance.

Extra

Here is the xml layout for the top image:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android:layout_weight="
        android:textSize="24sp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="1" />

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:text="2" />

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="1" />

    </LinearLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android:layout_weight="
        android:textSize="24sp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="10"
            android:text="10" />

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="20"
            android:text="20" />

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="10"
            android:text="10" />

    </LinearLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android:layout_weight="
        android:textSize="24sp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight=".25"
            android:text=".25" />

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight=".50"
            android:text=".50" />

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight=".25"
            android:text=".25" />

    </LinearLayout>

</LinearLayout>

Printing with "\t" (tabs) does not result in aligned columns

In continuation of the comments by Péter and duncan, I normally use a quick padding method, something like -

public String rpad(String inStr, int finalLength)
{
    return (inStr + "                          " // typically a sufficient length spaces string.
        ).substring(0, finalLength);
}

similarly you can have a lpad() as well

Enable vertical scrolling on textarea

Simply, change

<textarea rows="15" cols="50" id="aboutDescription"
style="resize: none;"></textarea>

to

<textarea rows="15" cols="50" id="aboutDescription"
style="resize: none;" data-role="none"></textarea>

ie, add:

data-role="none"

error: ORA-65096: invalid common user or role name in oracle

SQL> alter session set "_ORACLE_SCRIPT"=true;  
SQL> create user sec_admin identified by "Chutinhbk123@!";

Shell script not running, command not found

Also make sure /bin/bash is the proper location for bash .... if you took that line from an example somewhere it may not match your particular server. If you are specifying an invalid location for bash you're going to have a problem.

R cannot be resolved - Android error

My solution (on Eclipse Juno) was to click on "Fix Project Properities" by:

  1. Click right mouse button on project
  2. Choose Android Tools menu
  3. Click on Fix Project Properities

ps. First check if R library is not implemented and if all files in res/ folder are ok.

Android: Align button to bottom-right of screen using FrameLayout?

I also ran into this situation and figured out how to do it using FrameLayout. The following output is produced by the code given below.

Some right-bottom aligned text showing up over an image using FrameLayout.

              <FrameLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" >

                    <ImageView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:src="@drawable/contactbook_icon"
                        android:layout_gravity="center" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="140"
                        android:textSize="12dp"
                        android:textColor="#FFFFFF"
                        android:layout_gravity="bottom|right"
                        android:layout_margin="15dp" />
                </FrameLayout>

Change the margin value to adjust the text position over the image. Removing margin might make the text to go out of the view sometimes.

Login credentials not working with Gmail SMTP

if you are getting error this(535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials o60sm2132303pje.21 - gsmtp')

then simply go in you google accountsettings of security section and make a less secure account and turn on the less secure button

How to test an Internet connection with bash?

Execute the following command to check whether a web site is up, and what status message the web server is showing:

curl -Is http://www.google.com | head -1 HTTP/1.1 200 OK

Status code ‘200 OK’ means that the request has succeeded and a website is reachable.

How to replace all double quotes to single quotes using jquery?

Use double quote to enclose the quote or escape it.

newTemp = mystring.replace(/"/g, "'");

or

newTemp = mystring.replace(/"/g, '\'');