Programs & Examples On #Git merge

git-merge is a git command which integrates changes from another branch by incorporating commits into the currently checked-out branch.

error: Your local changes to the following files would be overwritten by checkout

You can force checkout your branch, if you do not want to commit your local changes.

git checkout -f branch_name

How do I merge a git tag onto a branch

I'm late to the game here, but another approach could be:

1) create a branch from the tag ($ git checkout -b [new branch name] [tag name])

2) create a pull-request to merge with your new branch into the destination branch

How to resolve git error: "Updates were rejected because the tip of your current branch is behind"

I had the exact same issue on my branch(lets call it branch B) and I followed three simple steps to get make it work

  1. Switched to the master branch (git checkout master)
  2. Did a pull on the master (git pull)
  3. Created new branch (git branch C) - note here that we are now branching from master
  4. Now when you are on branch C, merge with branch B (git merge B)
  5. Now do a push (git push origin C) - works :)

Now you can delete branch B and then rename branch C to branch B.

Hope this helps.

How can I selectively merge or pick changes from another branch in Git?

There is another way to go:

git checkout -p

It is a mix between git checkout and git add -p and might quite be exactly what you are looking for:

   -p, --patch
       Interactively select hunks in the difference between the <tree-ish>
       (or the index, if unspecified) and the working tree. The chosen
       hunks are then applied in reverse to the working tree (and if a
       <tree-ish> was specified, the index).

       This means that you can use git checkout -p to selectively discard
       edits from your current working tree. See the “Interactive Mode”
       section of git-add(1) to learn how to operate the --patch mode.

Git: How to pull a single file from a server repository in Git?

Try using:

git checkout branchName -- fileName

Ex:

git checkout master -- index.php

Merge up to a specific commit

Sure, being in master branch all you need to do is:

git merge <commit-id>

where commit-id is hash of the last commit from newbranch that you want to get in your master branch.

You can find out more about any git command by doing git help <command>. It that case it's git help merge. And docs are saying that the last argument for merge command is <commit>..., so you can pass reference to any commit or even multiple commits. Though, I never did the latter myself.

What is the best (and safest) way to merge a Git branch into master?

How I would do this

git checkout master
git pull origin master
git merge test
git push origin master

If I have a local branch from a remote one, I don't feel comfortable with merging other branches than this one with the remote. Also I would not push my changes, until I'm happy with what I want to push and also I wouldn't push things at all, that are only for me and my local repository. In your description it seems, that test is only for you? So no reason to publish it.

git always tries to respect yours and others changes, and so will --rebase. I don't think I can explain it appropriately, so have a look at the Git book - Rebasing or git-ready: Intro into rebasing for a little description. It's a quite cool feature

Git merge error "commit is not possible because you have unmerged files"

Since git 2.23 (August 2019) you now have a shortcut to do that: git restore --staged [filepath]. With this command, you could ignore a conflicted file without needing to add and remove that.

Example:

> git status

  ...
  Unmerged paths:
    (use "git add <file>..." to mark resolution)
      both modified:   file.ex

> git restore --staged file.ex

> git status

  ...
  Changes not staged for commit:
    (use "git add <file>..." to update what will be committed)
    (use "git restore <file>..." to discard changes in working directory)
      modified:   file.ex

Is there a "theirs" version of "git merge -s ours"?

I solved my problem using

git checkout -m old
git checkout -b new B
git merge -s ours old

What's the difference between 'git merge' and 'git rebase'?

Git rebase is closer to a merge. The difference in rebase is:

  • the local commits are removed temporally from the branch.
  • run the git pull
  • insert again all your local commits.

So that means that all your local commits are moved to the end, after all the remote commits. If you have a merge conflict, you have to solve it too.

How to resolve git status "Unmerged paths:"?

All you should need to do is:

# if the file in the right place isn't already committed:
git add <path to desired file>

# remove the "both deleted" file from the index:
git rm --cached ../public/images/originals/dog.ai

# commit the merge:
git commit

Git merge master into feature branch

In Eclipse -

1)Checkout master branch

Git Repositories ->Click on your repository -> click on Local ->double click master branch
->Click on yes for check out

2)Pull master branch

Right click on project ->click on Team -> Click on Pull

3)Checkout your feature branch(follow same steps mentioned in 1 point)

4)Merge master into feature

Git Repositories ->Click on your repository -> click on Local ->Right Click on your selected feature branch ->Click on merge ->Click on Local ->Click on Master ->Click on Merge.

5)Now you will get all changes of Master branch in feature branch. Remove conflict if any.

For conflict if any exists ,follow this -
Changes mentioned as Head(<<<<<< HEAD) is your change, Changes mentioned in branch(>>>>>>> branch) is other person change, you can update file accordingly.

Note - You need to do add to index for conflicts files

6)commit and push your changes in feature branch.

Right click on project ->click on Team -> Click on commit -> Commit and Push.

OR

Git Repositories ->Click on your repository -> click on Local ->Right Click on your selected feature branch ->Click on Push Branch ->Preview ->Push

How to undo a git merge with conflicts

Assuming you are using the latest git,

git merge --abort

Re-doing a reverted merge in Git

Instead of using git-revert you could have used this command in the devel branch to throw away (undo) the wrong merge commit (instead of just reverting it).

git checkout devel
git reset --hard COMMIT_BEFORE_WRONG_MERGE

This will also adjust the contents of the working directory accordingly. Be careful:

  • Save your changes in the develop branch (since the wrong merge) because they too will be erased by the git-reset. All commits after the one you specify as the git reset argument will be gone!
  • Also, don't do this if your changes were already pulled from other repositories because the reset will rewrite history.

I recommend to study the git-reset man-page carefully before trying this.

Now, after the reset you can re-apply your changes in devel and then do

git checkout devel
git merge 28s

This will be a real merge from 28s into devel like the initial one (which is now erased from git's history).

git remove merge commit from history

Starting with the repo in the original state

Original repo history

To remove the merge commit and squash the branch into a single commit in the mainline

Squashed commits, no merge commit

Use these commands (replacing 5 and 1 with the SHAs of the corresponding commits):

git checkout 5
git reset --soft 1
git commit --amend -m '1 2 3 4 5'
git rebase HEAD master

To retain a merge commit but squash the branch commits into one:

Squashed commits, retained merge commit

Use these commands (replacing 5, 1 and C with the SHAs of the corresponding commits):

git checkout -b tempbranch 5
git reset --soft 1
git commit --amend -m '1 2 3 4 5'
git checkout C
git merge --no-ff tempbranch
git rebase HEAD master

To remove the merge commit and replace it with individual commits from the branch

Branch moved into mainline, no merge commit

Just do (replacing 5 with the SHA of the corresponding commit):

git rebase 5 master

And finally, to remove the branch entirely

Branch removed entirely

Use this command (replacing C and D with the SHAs of the corresponding commits):

git rebase --onto C D~ master

How to merge specific files from Git branches

You can stash and stash pop the file:

git checkout branch1
git checkout branch2 file.py
git stash
git checkout branch1
git stash pop

Abort a Git Merge

as long as you did not commit you can type

git merge --abort

just as the command line suggested.

How to interactively (visually) resolve conflicts in SourceTree / git

From SourceTree, click on Tools->Options. Then on the "General" tab, make sure to check the box to allow SourceTree to modify your Git config files.

Then switch to the "Diff" tab. On the lower half, use the drop down to select the external program you want to use to do the diffs and merging. I've installed KDiff3 and like it well enough. When you're done, click OK.

Now when there is a merge, you can go under Actions->Resolve Conflicts->Launch External Merge Tool.

Undo a Git merge that hasn't been pushed yet

  1. First, make sure that you've committed everything.

  2. Then reset your repository to the previous working state:

    $ git reset f836e4c1fa51524658b9f026eb5efa24afaf3a36
    

    or using --hard (this will remove all local, not committed changes!):

    $ git reset f836e4c1fa51524658b9f026eb5efa24afaf3a36 --hard
    

    Use the hash which was there before your wrongly merged commit.

  3. Check which commits you'd like to re-commit on the top of the previous correct version by:

    $ git log 4c3e23f529b581c3cbe95350e84e66e3cb05704f
    
    commit 4c3e23f529b581c3cbe95350e84e66e3cb05704f
    
    ...
    
    commit 16b373a96b0a353f7454b141f7aa6f548c979d0a
    
    ...
    
  4. Apply your right commits on the top of the right version of your repository by:

    • By using cherry-pick (the changes introduced by some existing commits)

          git cherry-pick ec59ab844cf504e462f011c8cc7e5667ebb2e9c7
      
    • Or by cherry-picking the range of commits by:

      • First checking the right changes before merging them:

        git diff 5216b24822ea1c48069f648449997879bb49c070..4c3e23f529b581c3cbe95350e84e66e3cb05704f
        
      • First checking the right changes before merging them:

        git cherry-pick 5216b24822ea1c48069f648449997879bb49c070..4c3e23f529b581c3cbe95350e84e66e3cb05704f
        

        where this is the range of the correct commits which you've committed (excluding wrongly committed merge).

How to set Meld as git mergetool

meld 3.14.0

[merge]
    tool = meld
[mergetool "meld"]
    path = C:/Program Files (x86)/Meld/Meld.exe
    cmd = \"C:/Program Files (x86)/Meld/Meld.exe\" --diff \"$BASE\" \"$LOCAL\" \"$REMOTE\" --output \"$MERGED\"

When would you use the different git merge strategies?

With Git 2.30 (Q1 2021), there will be a new merge strategy: ORT ("Ostensibly Recursive's Twin").

git merge -s ort

This comes from this thread from Elijah Newren:

For now, I'm calling it "Ostensibly Recursive's Twin", or "ort" for short. > At first, people shouldn't be able to notice any difference between it and the current recursive strategy, other than the fact that I think I can make it a bit faster (especially for big repos).

But it should allow me to fix some (admittedly corner case) bugs that are harder to handle in the current design, and I think that a merge that doesn't touch $GIT_WORK_TREE or $GIT_INDEX_FILE will allow for some fun new features.
That's the hope anyway.

Problem:

In the ideal world, we should:

  • ask unpack_trees() to do "read-tree -m" without "-u";

  • do all the merge-recursive computations in-core and prepare the resulting index, while keeping the current index intact;

  • compare the current in-core index and the resulting in-core index, and notice the paths that need to be added, updated or removed in the working tree, and ensure that there is no loss of information when the change is reflected to the working tree;
    E.g. the result wants to create a file where the working tree currently has a directory with non-expendable contents in it, the result wants to remove a file where the working tree file has local modification, etc.;
    And then finally

  • carry out the working tree update to make it match what the resulting in-core index says it should look like.

Result:

See commit 14c4586 (02 Nov 2020), commit fe1a21d (29 Oct 2020), and commit 47b1e89, commit 17e5574 (27 Oct 2020) by Elijah Newren (newren).
(Merged by Junio C Hamano -- gitster -- in commit a1f9595, 18 Nov 2020)

merge-ort: barebones API of new merge strategy with empty implementation

Signed-off-by: Elijah Newren

This is the beginning of a new merge strategy.

While there are some API differences, and the implementation has some differences in behavior, it is essentially meant as an eventual drop-in replacement for merge-recursive.c.

However, it is being built to exist side-by-side with merge-recursive so that we have plenty of time to find out how those differences pan out in the real world while people can still fall back to merge-recursive.
(Also, I intend to avoid modifying merge-recursive during this process, to keep it stable.)

The primary difference noticable here is that the updating of the working tree and index is not done simultaneously with the merge algorithm, but is a separate post-processing step.
The new API is designed so that one can do repeated merges (e.g. during a rebase or cherry-pick) and only update the index and working tree one time at the end instead of updating it with every intermediate result.

Also, one can perform a merge between two branches, neither of which match the index or the working tree, without clobbering the index or working tree.

And:

See commit 848a856, commit fd15863, commit 23bef2e, commit c8c35f6, commit c12d1f2, commit 727c75b, commit 489c85f, commit ef52778, commit f06481f (26 Oct 2020) by Elijah Newren (newren).
(Merged by Junio C Hamano -- gitster -- in commit 66c62ea, 18 Nov 2020)

t6423, t6436: note improved ort handling with dirty files

Signed-off-by: Elijah Newren

The "recursive" backend relies on unpack_trees() to check if unstaged changes would be overwritten by a merge, but unpack_trees() does not understand renames -- and once it returns, it has already written many updates to the working tree and index.
As such, "recursive" had to do a special 4-way merge where it would need to also treat the working copy as an extra source of differences that we had to carefully avoid overwriting and resulting in moving files to new locations to avoid conflicts.

The "ort" backend, by contrast, does the complete merge inmemory, and only updates the index and working copy as a post-processing step.
If there are dirty files in the way, it can simply abort the merge.

t6423: expect improved conflict markers labels in the ort backend

Signed-off-by: Elijah Newren

Conflict markers carry an extra annotation of the form REF-OR-COMMIT:FILENAME to help distinguish where the content is coming from, with the :FILENAME piece being left off if it is the same for both sides of history (thus only renames with content conflicts carry that part of the annotation).

However, there were cases where the :FILENAME annotation was accidentally left off, due to merge-recursive's every-codepath-needs-a-copy-of-all-special-case-code format.

t6404, t6423: expect improved rename/delete handling in ort backend

Signed-off-by: Elijah Newren

When a file is renamed and has content conflicts, merge-recursive does not have some stages for the old filename and some stages for the new filename in the index; instead it copies all the stages corresponding to the old filename over to the corresponding locations for the new filename, so that there are three higher order stages all corresponding to the new filename.

Doing things this way makes it easier for the user to access the different versions and to resolve the conflict (no need to manually 'git rm '(man) the old version as well as 'git add'(man) the new one).

rename/deletes should be handled similarly -- there should be two stages for the renamed file rather than just one.
We do not want to destabilize merge-recursive right now, so instead update relevant tests to have different expectations depending on whether the "recursive" or "ort" merge strategies are in use.


With Git 2.30 (Q1 2021), Preparation for a new merge strategy.

See commit 848a856, commit fd15863, commit 23bef2e, commit c8c35f6, commit c12d1f2, commit 727c75b, commit 489c85f, commit ef52778, commit f06481f (26 Oct 2020) by Elijah Newren (newren).
(Merged by Junio C Hamano -- gitster -- in commit 66c62ea, 18 Nov 2020)

merge tests: expect improved directory/file conflict handling in ort

Signed-off-by: Elijah Newren

merge-recursive.c is built on the idea of running unpack_trees() and then "doing minor touch-ups" to get the result.
Unfortunately, unpack_trees() was run in an update-as-it-goes mode, leading merge-recursive.c to follow suit and end up with an immediate evaluation and fix-it-up-as-you-go design.

Some things like directory/file conflicts are not well representable in the index data structure, and required special extra code to handle.
But then when it was discovered that rename/delete conflicts could also be involved in directory/file conflicts, the special directory/file conflict handling code had to be copied to the rename/delete codepath.
...and then it had to be copied for modify/delete, and for rename/rename(1to2) conflicts, ...and yet it still missed some.
Further, when it was discovered that there were also file/submodule conflicts and submodule/directory conflicts, we needed to copy the special submodule handling code to all the special cases throughout the codebase.

And then it was discovered that our handling of directory/file conflicts was suboptimal because it would create untracked files to store the contents of the conflicting file, which would not be cleaned up if someone were to run a 'git merge --abort'(man) or 'git rebase --abort'(man).

It was also difficult or scary to try to add or remove the index entries corresponding to these files given the directory/file conflict in the index.
But changing merge-recursive.c to handle these correctly was a royal pain because there were so many sites in the code with similar but not identical code for handling directory/file/submodule conflicts that would all need to be updated.

I have worked hard to push all directory/file/submodule conflict handling in merge-ort through a single codepath, and avoid creating untracked files for storing tracked content (it does record things at alternate paths, but makes sure they have higher-order stages in the index).


With Git 2.31 (Q1 2021), the merge backend "done right" starts to emerge.
Example:

See commit 6d37ca2 (11 Nov 2020) by Junio C Hamano (gitster).
See commit 89422d2, commit ef2b369, commit 70912f6, commit 6681ce5, commit 9fefce6, commit bb470f4, commit ee4012d, commit a9945bb, commit 8adffaa, commit 6a02dd9, commit 291f29c, commit 98bf984, commit 34e557a, commit 885f006, commit d2bc199, commit 0c0d705, commit c801717, commit e4171b1, commit 231e2dd, commit 5b59c3d (13 Dec 2020) by Elijah Newren (newren).
(Merged by Junio C Hamano -- gitster -- in commit f9d29da, 06 Jan 2021)

merge-ort: add implementation of record_conflicted_index_entries()

Signed-off-by: Elijah Newren

After checkout(), the working tree has the appropriate contents, and the index matches the working copy.
That means that all unmodified and cleanly merged files have correct index entries, but conflicted entries need to be updated.

We do this by looping over the conflicted entries, marking the existing index entry for the path with CE_REMOVE, adding new higher order staged for the path at the end of the index (ignoring normal index sort order), and then at the end of the loop removing the CE_REMOVED-marked cache entries and sorting the index.


With Git 2.31 (Q1 2021), rename detection is added to the "ORT" merge strategy.

See commit 6fcccbd, commit f1665e6, commit 35e47e3, commit 2e91ddd, commit 53e88a0, commit af1e56c (15 Dec 2020), and commit c2d267d, commit 965a7bc, commit f39d05c, commit e1a124e, commit 864075e (14 Dec 2020) by Elijah Newren (newren).
(Merged by Junio C Hamano -- gitster -- in commit 2856089, 25 Jan 2021)

Example:

merge-ort: add implementation of normal rename handling

Signed-off-by: Elijah Newren

Implement handling of normal renames.
This code replaces the following from merge-recurisve.c:

  • the code relevant to RENAME_NORMAL in process_renames()
  • the RENAME_NORMAL case of process_entry()

Also, there is some shared code from merge-recursive.c for multiple different rename cases which we will no longer need for this case (or other rename cases):

  • handle_rename_normal()
  • setup_rename_conflict_info()

The consolidation of four separate codepaths into one is made possible by a change in design: process_renames() tweaks the conflict_info entries within opt->priv->paths such that process_entry() can then handle all the non-rename conflict types (directory/file, modify/delete, etc.) orthogonally.

This means we're much less likely to miss special implementation of some kind of combination of conflict types (see commits brought in by 66c62ea ("Merge branch 'en/merge-tests'", 2020-11-18, Git v2.30.0-rc0 -- merge listed in batch #6), especially commit ef52778 ("merge tests: expect improved directory/file conflict handling in ort", 2020-10-26, Git v2.30.0-rc0 -- merge listed in batch #6) for more details).

That, together with letting worktree/index updating be handled orthogonally in the merge_switch_to_result() function, dramatically simplifies the code for various special rename cases.

(To be fair, the code for handling normal renames wasn't all that complicated beforehand, but it's still much simpler now.)

And, still with Git 2.31 (Q1 2021), With Git 2.31 (Q1 2021), oRT merge strategy learns more support for merge conflicts.

See commit 4ef88fc, commit 4204cd5, commit 70f19c7, commit c73cda7, commit f591c47, commit 62fdec1, commit 991bbdc, commit 5a1a1e8, commit 23366d2, commit 0ccfa4e (01 Jan 2021) by Elijah Newren (newren).
(Merged by Junio C Hamano -- gitster -- in commit b65b9ff, 05 Feb 2021)

merge-ort: add handling for different types of files at same path

Signed-off-by: Elijah Newren

Add some handling that explicitly considers collisions of the following types:

  • file/submodule
  • file/symlink
  • submodule/symlink> Leaving them as conflicts at the same path are hard for users to resolve, so move one or both of them aside so that they each get their own path.

Note that in the case of recursive handling (i.e.
call_depth > 0), we can just use the merge base of the two merge bases as the merge result much like we do with modify/delete conflicts, binary files, conflicting submodule values, and so on.

How can I preview a merge in git?

Pull Request - I've used most of the already submitted ideas but one that I also often use is ( especially if its from another dev ) doing a Pull Request which gives a handy way to review all of the changes in a merge before it takes place. I know that is GitHub not git but it sure is handy.

Why does git perform fast-forward merges by default?

Let me expand a bit on a VonC's very comprehensive answer:


First, if I remember it correctly, the fact that Git by default doesn't create merge commits in the fast-forward case has come from considering single-branch "equal repositories", where mutual pull is used to sync those two repositories (a workflow you can find as first example in most user's documentation, including "The Git User's Manual" and "Version Control by Example"). In this case you don't use pull to merge fully realized branch, you use it to keep up with other work. You don't want to have ephemeral and unimportant fact when you happen to do a sync saved and stored in repository, saved for the future.

Note that usefulness of feature branches and of having multiple branches in single repository came only later, with more widespread usage of VCS with good merging support, and with trying various merge-based workflows. That is why for example Mercurial originally supported only one branch per repository (plus anonymous tips for tracking remote branches), as seen in older revisions of "Mercurial: The Definitive Guide".


Second, when following best practices of using feature branches, namely that feature branches should all start from stable version (usually from last release), to be able to cherry-pick and select which features to include by selecting which feature branches to merge, you are usually not in fast-forward situation... which makes this issue moot. You need to worry about creating a true merge and not fast-forward when merging a very first branch (assuming that you don't put single-commit changes directly on 'master'); all other later merges are of course in non fast-forward situation.

HTH

Git pull - Please move or remove them before you can merge

If there are too many files to delete, which is actually a case for me. You can also try the following solution:

1) fetch

2) merge with a strategy. For instance this one works for me:

git.exe merge --strategy=ours master

How to cherry pick a range of commits and merge into another branch?

git cherry-pick FIRST^..LAST works only for simple scenarios.

To achieve a decent "merge it into the integration branch" while having the usal comfort with things like auto-skipping of already integrated picks, transplanting diamond-merges, interactive control ...) better use a rebase. One answer here pointed to that, however the protocol included a dicey git branch -f and a juggling with a temp branch. Here a straight robust method:

git rebase -i FIRST LAST~0 --onto integration
git rebase @ integration

The -i allows for interactive control. The ~0 ensures a detached rebase (not moving the / another branch) in case LAST is a branch name. It can be omitted otherwise. The second rebase command just moves the integration branch ref in safe manner forward to the intermediate detached head - it doesn't introduce new commits. To rebase a complex structure with merge diamonds etc. consider --rebase-merges or --rebase-merges=rebase-cousins in the first rebase.

The following untracked working tree files would be overwritten by merge, but I don't care

If this is a one-time operation, you could just remove all untracked files from the working directory before doing the pull. Read How to remove local (untracked) files from the current Git working tree? for information on how to remove all untracked files.

Be sure to not accidentally remove untracked file that you still need ;)

Undo git pull, how to bring repos to old state

If you have gitk (try running "gitk --all from your git command line"), it's simple. Just run it, select the commit you want to rollback to (right-click), and select "Reset master branch to here". If you have no uncommited changes, chose the "hard" option.

What's the simplest way to list conflicted files in Git?

Assuming you know where your git root directory, ${GIT_ROOT}, is, you can do,

 cat ${GIT_ROOT}/.git/MERGE_MSG | sed '1,/Conflicts/d'

Get changes from master into branch in Git

First check out to master:

git checkout master

Do all changes, hotfix and commits and push your master.

Go back to your branch, 'aq', and merge master in it:

git checkout aq
git merge master

Your branch will be up-to-date with master. A good and basic example of merge is 3.2 Git Branching - Basic Branching and Merging.

How Do I 'git fetch' and 'git merge' from a Remote Tracking Branch (like 'git pull')

Selecting just one branch: fetch/merge vs. pull

People often advise you to separate "fetching" from "merging". They say instead of this:

    git pull remoteR branchB

do this:

    git fetch remoteR
    git merge remoteR branchB

What they don't mention is that such a fetch command will actually fetch all branches from the remote repo, which is not what that pull command does. If you have thousands of branches in the remote repo, but you do not want to see all of them, you can run this obscure command:

    git fetch remoteR refs/heads/branchB:refs/remotes/remoteR/branchB
    git branch -a  # to verify
    git branch -t branchB remoteR/branchB

Of course, that's ridiculously hard to remember, so if you really want to avoid fetching all branches, it is better to alter your .git/config as described in ProGit.

Huh?

The best explanation of all this is in Chapter 9-5 of ProGit, Git Internals - The Refspec (or via github). That is amazingly hard to find via Google.

First, we need to clear up some terminology. For remote-branch-tracking, there are typically 3 different branches to be aware of:

  1. The branch on the remote repo: refs/heads/branchB inside the other repo
  2. Your remote-tracking branch: refs/remotes/remoteR/branchB in your repo
  3. Your own branch: refs/heads/branchB inside your repo

Remote-tracking branches (in refs/remotes) are read-only. You do not modify those directly. You modify your own branch, and then you push to the corresponding branch at the remote repo. The result is not reflected in your refs/remotes until after an appropriate pull or fetch. That distinction was difficult for me to understand from the git man-pages, mainly because the local branch (refs/heads/branchB) is said to "track" the remote-tracking branch when .git/config defines branch.branchB.remote = remoteR.

Think of 'refs' as C++ pointers. Physically, they are files containing SHA-digests, but basically they are just pointers into the commit tree. git fetch will add many nodes to your commit-tree, but how git decides what pointers to move is a bit complicated.

As mentioned in another answer, neither

    git pull remoteR branchB

nor

    git fetch remoteR branchB

would move refs/remotes/branches/branchB, and the latter certainly cannot move refs/heads/branchB. However, both move FETCH_HEAD. (You can cat any of these files inside .git/ to see when they change.) And git merge will refer to FETCH_HEAD, while setting MERGE_ORIG, etc.

How to resolve merge conflicts in Git repository?

For Emacs users which want to resolve merge conflicts semi-manually:

git diff --name-status --diff-filter=U

shows all files which require conflict resolution.

Open each of those files one by one, or all at once by:

emacs $(git diff --name-only --diff-filter=U)

When visiting a buffer requiring edits in Emacs, type

ALT+x vc-resolve-conflicts

This will open three buffers (mine, theirs, and the output buffer). Navigate by pressing 'n' (next region), 'p' (prevision region). Press 'a' and 'b' to copy mine or theirs region to the output buffer, respectively. And/or edit the output buffer directly.

When finished: Press 'q'. Emacs asks you if you want to save this buffer: yes. After finishing a buffer mark it as resolved by running from the teriminal:

git add FILENAME

When finished with all buffers type

git commit

to finish the merge.

.gitignore and "The following untracked working tree files would be overwritten by checkout"

In my case git rm --cached didn't work. But i got it with a git rebase

Merge development branch with master

If you are using gerrit, the following commands work perfectly.

git checkout master
git merge --no-ff development

You can save with the default commit message. Make sure, the change id has been generated. You can use the following command to make sure.

git commit --amend

Then push with the following command.

git push origin HEAD:refs/for/refs/heads/master

You might encounter an error message like the below.

! [remote rejected] HEAD -> refs/for/refs/heads/master (you are not allowed to upload merges)

To resolve this, the gerrit project admin has to create another reference in gerrit named 'refs/for/refs/heads/master' or 'refs/for/refs/heads/*' (which will cover all branches in future). Then grant 'Push Merge Commit' permission to this reference and 'Submit' permission if required to Submit the GCR.

Now, try the above push command again, and it should work.

Credits:

https://github.com/ReviewAssistant/reviewassistant/wiki/Merging-branches-in-Gerrit

https://stackoverflow.com/a/21199818/3877642

How to import existing Git repository into another?

Adding another answer as I think this is a bit simpler. A pull of repo_dest is done into repo_to_import and then a push --set-upstream url:repo_dest master is done.

This method has worked for me importing several smaller repos into a bigger one.

How to import: repo1_to_import to repo_dest

# checkout your repo1_to_import if you don't have it already 
git clone url:repo1_to_import repo1_to_import
cd repo1_to_import

# now. pull all of repo_dest
git pull url:repo_dest
ls 
git status # shows Your branch is ahead of 'origin/master' by xx commits.
# now push to repo_dest
git push --set-upstream url:repo_dest master

# repeat for other repositories you want to import

Rename or move files and dirs into desired position in original repo before you do the import. e.g.

cd repo1_to_import
mkdir topDir
git add topDir
git mv this that and the other topDir/
git commit -m"move things into topDir in preparation for exporting into new repo"
# now do the pull and push to import

The method described at the following link inspired this answer. I liked it as it seemed more simple. BUT Beware! There be dragons! https://help.github.com/articles/importing-an-external-git-repository git push --mirror url:repo_dest pushes your local repo history and state to remote (url:repo_dest). BUT it deletes the old history and state of the remote. Fun ensues! :-E

Git: How configure KDiff3 as merge tool and diff tool

To amend kris' answer, starting with Git 2.20 (Q4 2018), the proper command for git mergetool will be

git config --global merge.guitool kdiff3 

That is because "git mergetool" learned to take the "--[no-]gui" option, just like "git difftool" does.

See commit c217b93, commit 57ba181, commit 063f2bd (24 Oct 2018) by Denton Liu (Denton-L).
(Merged by Junio C Hamano -- gitster -- in commit 87c15d1, 30 Oct 2018)

mergetool: accept -g/--[no-]gui as arguments

In line with how difftool accepts a -g/--[no-]gui option, make mergetool accept the same option in order to use the merge.guitool variable to find the default mergetool instead of merge.tool.

Git merge errors

I had the same issue when switching from a dev branch to master branch. What I did was commit my changes and switch to the master branch. You might have uncommitted changes.

When do you use Git rebase instead of Git merge?

To complement my own answer mentioned by TSamper,

  • a rebase is quite often a good idea to do before a merge, because the idea is that you integrate in your branch Y the work of the branch B upon which you will merge.
    But again, before merging, you resolve any conflict in your branch (i.e.: "rebase", as in "replay my work in my branch starting from a recent point from the branch B).
    If done correctly, the subsequent merge from your branch to branch B can be fast-forward.

  • a merge directly impacts the destination branch B, which means the merges better be trivial, otherwise that branch B can be long to get back to a stable state (time for you solve all the conflicts)


the point of merging after a rebase?

In the case that I describe, I rebase B onto my branch, just to have the opportunity to replay my work from a more recent point from B, but while staying into my branch.
In this case, a merge is still needed to bring my "replayed" work onto B.

The other scenario (described in Git Ready for instance), is to bring your work directly in B through a rebase (which does conserve all your nice commits, or even give you the opportunity to re-order them through an interactive rebase).
In that case (where you rebase while being in the B branch), you are right: no further merge is needed:

A Git tree at default when we have not merged nor rebased

rebase1

we get by rebasing:

rebase3

That second scenario is all about: how do I get new-feature back into master.

My point, by describing the first rebase scenario, is to remind everyone that a rebase can also be used as a preliminary step to that (that being "get new-feature back into master").
You can use rebase to first bring master "in" the new-feature branch: the rebase will replay new-feature commits from the HEAD master, but still in the new-feature branch, effectively moving your branch starting point from an old master commit to HEAD-master.
That allows you to resolve any conflicts in your branch (meaning, in isolation, while allowing master to continue to evolve in parallel if your conflict resolution stage takes too long).
Then you can switch to master and merge new-feature (or rebase new-feature onto master if you want to preserve commits done in your new-feature branch).

So:

  • "rebase vs. merge" can be viewed as two ways to import a work on, say, master.
  • But "rebase then merge" can be a valid workflow to first resolve conflict in isolation, then bring back your work.

Is there a git-merge --dry-run option?

My solution is to merge backwards.

Instead of merging your branch into the remote "target" branch, merge that branch into yours.

git checkout my-branch
git merge origin/target-branch

You will see if there are any conflicts and can plan on how to solve them.

After that you can either abort the merge via git merge --abort, or (if there weren't any conflicts and merge has happened) roll back to previous commit via git reset --hard HEAD~1

How can I merge two commits into one if I already started rebase?

If you want to combine the two most recent commits and just use the older commit's message, you can automate the process using expect.

I assume:

  • You're using vi as your editor
  • Your commits are one-line each

I tested with git version 2.14.3 (Apple Git-98).


#!/usr/bin/env expect
spawn git rebase -i HEAD~2

# change the second "pick" to "squash"
# down, delete word, insert 's' (for squash), Escape, save and quit
send "jdwis \033:wq\r"

expect "# This is a"

# skip past first commit message (assumed to be one line), delete rest of file
# down 4, delete remaining lines, save and quit
send "4jdG\r:wq\r"

interact

git stash -> merge stashed change with current changes

you can easily

  1. Commit your current changes
  2. Unstash your stash and resolve conflicts
  3. Commit changes from stash
  4. Soft reset to commit you are comming from (last correct commit)

Is it possible to pull just one file in Git?

git checkout master -- myplugin.js

master = branch name

myplugin.js = file name

Merge, update, and pull Git branches without using checkouts

just to pull the master without checking out the master I use

git fetch origin master:master

Git workflow and rebase vs merge questions

Anyway, I was following my workflow on a recent branch, and when I tried to merge it back to master, it all went to hell. There were tons of conflicts with things that should have not mattered. The conflicts just made no sense to me. It took me a day to sort everything out, and eventually culminated in a forced push to the remote master, since my local master has all conflicts resolved, but the remote one still wasn't happy.

In neither your partner's nor your suggested workflows should you have come across conflicts that didn't make sense. Even if you had, if you are following the suggested workflows then after resolution a 'forced' push should not be required. It suggests that you haven't actually merged the branch to which you were pushing, but have had to push a branch that wasn't a descendent of the remote tip.

I think you need to look carefully at what happened. Could someone else have (deliberately or not) rewound the remote master branch between your creation of the local branch and the point at which you attempted to merge it back into the local branch?

Compared to many other version control systems I've found that using Git involves less fighting the tool and allows you to get to work on the problems that are fundamental to your source streams. Git doesn't perform magic, so conflicting changes cause conflicts, but it should make it easy to do the write thing by its tracking of commit parentage.

Resolve Git merge conflicts in favor of their changes during a pull

You can use the recursive "theirs" strategy option:

git merge --strategy-option theirs

From the man:

ours
    This option forces conflicting hunks to be auto-resolved cleanly by 
    favoring our version. Changes from the other tree that do not 
    conflict with our side are reflected to the merge result.

    This should not be confused with the ours merge strategy, which does 
    not even look at what the other tree contains at all. It discards 
    everything the other tree did, declaring our history contains all that
    happened in it.

theirs
    This is opposite of ours.

Note: as the man page says, the "ours" merge strategy-option is very different from the "ours" merge strategy.

How to use git merge --squash?

If you have already git merge bugfix on main, you can squash your merge commit into one with:

git reset --soft HEAD^1
git commit

I ran into a merge conflict. How can I abort the merge?

For git >= 1.6.1:

git merge --abort

For older versions of git, this will do the job:

git reset --merge

or

git reset --hard

How do I fix a merge conflict due to removal of a file in a branch?

If you are using Git Gui on windows,

  1. Abort the merge
  2. Make sure you are on your target branch
  3. Delete the conflicting file from explorer
  4. Rescan for changes in Git Gui (F5)
  5. Notice that conflicting file is deleted
  6. Select Stage Changed Files To Commit (Ctrl-I) from Commit menu
  7. Enter a commit comment like "deleted conflicting file"
  8. Commit (ctrl-enter)
  9. Now if you restart the merge it will (hopefully) work.

Input type "number" won't resize

For <input type=number>, by the HTML5 CR, the size attribute is not allowed. However, in Obsolete features it says: “Authors should not, but may despite requirements to the contrary elsewhere in this specification, specify the maxlength and size attributes on input elements whose type attributes are in the Number state. One valid reason for using these attributes regardless is to help legacy user agents that do not support input elements with type="number" to still render the text field with a useful width.”

Thus, the size attribute can be used, but it only affects older browsers that do not support type=number, so that the element falls back to a simple text control, <input type=text>.

The rationale behind this is that the browser is expected to provide a user interface that takes the other attributes into account, for good usability. As the implementations may vary, any size imposed by an author might mess things up. (This also applies to setting the width of the control in CSS.)

The conclusion is that you should use <input type=number> in a more or less fluid setup that does not make any assumptions about the dimensions of the element.

R: invalid multibyte string

If you want an R solution, here's a small convenience function I sometimes use to find where the offending (multiByte) character is lurking. Note that it is the next character to what gets printed. This works because print will work fine, but substr throws an error when multibyte characters are present.

find_offending_character <- function(x, maxStringLength=256){  
  print(x)
  for (c in 1:maxStringLength){
    offendingChar <- substr(x,c,c)
    #print(offendingChar) #uncomment if you want the indiv characters printed
    #the next character is the offending multibyte Character
  }    
}

string_vector <- c("test", "Se\x96ora", "works fine")

lapply(string_vector, find_offending_character)

I fix that character and run this again. Hope that helps someone who encounters the invalid multibyte string error.

Button inside of anchor link works in Firefox but not in Internet Explorer?

You can't have a <button> inside an <a> element. As W3's content model description for the <a> element states:

"there must be no interactive content descendant."

(a <button> is considered interactive content)

To get the effect you're looking for, you can ditch the <a> tags and add a simple event handler to each button which navigates the browser to the desired location, e.g.

<input type="button" value="stackoverflow.com" onClick="javascript:location.href = 'http://stackoverflow.com';" />

Please consider not doing this, however; there's a reason regular links work as they do:

  • Users can instantly recognize links and understand that they navigate to other pages
  • Search engines can identify them as links and follow them
  • Screen readers can identify them as links and advise their users appropriately

You also add a completely unnecessary requirement to have JavaScript enabled just to perform a basic navigation; this is such a fundamental aspect of the web that I would consider such a dependency as unacceptable.

You can style your links, if desired, using a background image or background color, border and other techniques, so that they look like buttons, but under the covers, they should be ordinary links.

How to find the kafka version in linux

When you install Kafka in Centos7 with confluent :

yum install confluent-platform-oss-2.11

You can see the version of Kafka with :

yum deplist confluent-platform-oss-2.11

You can read : confluent-kafka-2.11 >= 0.10.2.1

Global Events in Angular

I have created a pub-sub sample here:

http://www.syntaxsuccess.com/viewarticle/pub-sub-in-angular-2.0

The idea is to use RxJs Subjects to wire up an Observer and and Observables as a generic solution for emitting and subscribing to custom events. In my sample I use a customer object for demo purposes

this.pubSubService.Stream.emit(customer);

this.pubSubService.Stream.subscribe(customer => this.processCustomer(customer));

Here is a live demo as well: http://www.syntaxsuccess.com/angular-2-samples/#/demo/pub-sub

server error:405 - HTTP verb used to access this page is not allowed

I fixed mine by adding these lines on my IIS webconfig.

<httpErrors>
    <remove statusCode="405" subStatusCode="-1" />
    <error statusCode="405" prefixLanguageFilePath="" path="/my-page.htm" responseMode="ExecuteURL" />
</httpErrors>

How to get the current date without the time?

You can use DateTime.Now.ToShortDateString() like so:

var test = $"<b>Date of this report:</b> {DateTime.Now.ToShortDateString()}";

Best way to combine two or more byte arrays in C#

For primitive types (including bytes), use System.Buffer.BlockCopy instead of System.Array.Copy. It's faster.

I timed each of the suggested methods in a loop executed 1 million times using 3 arrays of 10 bytes each. Here are the results:

  1. New Byte Array using System.Array.Copy - 0.2187556 seconds
  2. New Byte Array using System.Buffer.BlockCopy - 0.1406286 seconds
  3. IEnumerable<byte> using C# yield operator - 0.0781270 seconds
  4. IEnumerable<byte> using LINQ's Concat<> - 0.0781270 seconds

I increased the size of each array to 100 elements and re-ran the test:

  1. New Byte Array using System.Array.Copy - 0.2812554 seconds
  2. New Byte Array using System.Buffer.BlockCopy - 0.2500048 seconds
  3. IEnumerable<byte> using C# yield operator - 0.0625012 seconds
  4. IEnumerable<byte> using LINQ's Concat<> - 0.0781265 seconds

I increased the size of each array to 1000 elements and re-ran the test:

  1. New Byte Array using System.Array.Copy - 1.0781457 seconds
  2. New Byte Array using System.Buffer.BlockCopy - 1.0156445 seconds
  3. IEnumerable<byte> using C# yield operator - 0.0625012 seconds
  4. IEnumerable<byte> using LINQ's Concat<> - 0.0781265 seconds

Finally, I increased the size of each array to 1 million elements and re-ran the test, executing each loop only 4000 times:

  1. New Byte Array using System.Array.Copy - 13.4533833 seconds
  2. New Byte Array using System.Buffer.BlockCopy - 13.1096267 seconds
  3. IEnumerable<byte> using C# yield operator - 0 seconds
  4. IEnumerable<byte> using LINQ's Concat<> - 0 seconds

So, if you need a new byte array, use

byte[] rv = new byte[a1.Length + a2.Length + a3.Length];
System.Buffer.BlockCopy(a1, 0, rv, 0, a1.Length);
System.Buffer.BlockCopy(a2, 0, rv, a1.Length, a2.Length);
System.Buffer.BlockCopy(a3, 0, rv, a1.Length + a2.Length, a3.Length);

But, if you can use an IEnumerable<byte>, DEFINITELY prefer LINQ's Concat<> method. It's only slightly slower than the C# yield operator, but is more concise and more elegant.

IEnumerable<byte> rv = a1.Concat(a2).Concat(a3);

If you have an arbitrary number of arrays and are using .NET 3.5, you can make the System.Buffer.BlockCopy solution more generic like this:

private byte[] Combine(params byte[][] arrays)
{
    byte[] rv = new byte[arrays.Sum(a => a.Length)];
    int offset = 0;
    foreach (byte[] array in arrays) {
        System.Buffer.BlockCopy(array, 0, rv, offset, array.Length);
        offset += array.Length;
    }
    return rv;
}

*Note: The above block requires you adding the following namespace at the the top for it to work.

using System.Linq;

To Jon Skeet's point regarding iteration of the subsequent data structures (byte array vs. IEnumerable<byte>), I re-ran the last timing test (1 million elements, 4000 iterations), adding a loop that iterates over the full array with each pass:

  1. New Byte Array using System.Array.Copy - 78.20550510 seconds
  2. New Byte Array using System.Buffer.BlockCopy - 77.89261900 seconds
  3. IEnumerable<byte> using C# yield operator - 551.7150161 seconds
  4. IEnumerable<byte> using LINQ's Concat<> - 448.1804799 seconds

The point is, it is VERY important to understand the efficiency of both the creation and the usage of the resulting data structure. Simply focusing on the efficiency of the creation may overlook the inefficiency associated with the usage. Kudos, Jon.

How to pause / sleep thread or process in Android?

Or you could use:

android.os.SystemClock.sleep(checkEvery)

which has the advantage of not requiring a wrapping try ... catch.

Initializing a static std::map<int, int> in C++

Just wanted to share a pure C++ 98 work around:

#include <map>

std::map<std::string, std::string> aka;

struct akaInit
{
    akaInit()
    {
        aka[ "George" ] = "John";
        aka[ "Joe" ] = "Al";
        aka[ "Phil" ] = "Sue";
        aka[ "Smitty" ] = "Yando";
    }
} AkaInit;

How to access the contents of a vector from a pointer to the vector in C++?

Do you have a pointer to a vector because that's how you've coded it? You may want to reconsider this and use a (possibly const) reference. For example:

#include <iostream>
#include <vector>

using namespace std;

void foo(vector<int>* a)
{
    cout << a->at(0) << a->at(1) << a->at(2) << endl;
    // expected result is "123"
}

int main()
{
    vector<int> a;
    a.push_back(1);
    a.push_back(2);
    a.push_back(3);

    foo(&a);
}

While this is a valid program, the general C++ style is to pass a vector by reference rather than by pointer. This will be just as efficient, but then you don't have to deal with possibly null pointers and memory allocation/cleanup, etc. Use a const reference if you aren't going to modify the vector, and a non-const reference if you do need to make modifications.

Here's the references version of the above program:

#include <iostream>
#include <vector>

using namespace std;

void foo(const vector<int>& a)
{
    cout << a[0] << a[1] << a[2] << endl;
    // expected result is "123"
}

int main()
{
    vector<int> a;
    a.push_back(1);
    a.push_back(2);
    a.push_back(3);

    foo(a);
}

As you can see, all of the information contained within a will be passed to the function foo, but it will not copy an entirely new value, since it is being passed by reference. It is therefore just as efficient as passing by pointer, and you can use it as a normal value rather than having to figure out how to use it as a pointer or having to dereference it.

Gulp command not found after install

I had this problem with getting "command not found" after install but I was installed into /usr/local as described in the solution above.

My problem seemed to be caused by me running the install with sudo. I did the following.

  1. Removing gulp again with sudo
  2. Changing the owner of /usr/local/lib/node_modules to my user
  3. Installing gulp again without sudo. "npm install gulp -g"

How do you make a deep copy of an object?

import com.thoughtworks.xstream.XStream;

public class deepCopy {
    private static  XStream xstream = new XStream();

    //serialize with Xstream them deserialize ...
    public static Object deepCopy(Object obj){
        return xstream.fromXML(xstream.toXML(obj));
    }
}

The name 'controlname' does not exist in the current context

Check your code behind file name and Inherits property on the @Page directive, make sure they both match.

How update the _id of one MongoDB Document?

You can also create a new document from MongoDB compass or using command and set the specific _id value that you want.

Android Studio is slow (how to speed up)?

I followed this post and it worked great for me.

EDIT:

Following tips have been mentioned in the above post.

In gradle.properties, put this:

org.gradle.daemon=true
org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
org.gradle.parallel=true
org.gradle.configureondemand=true

And in build.gradle, put this (Note this will disable lint check):

tasks.whenTaskAdded { task ->
    if (task.name.equals("lint")) {
        task.enabled = false
    }
}

How to get current domain name in ASP.NET

Here is a quick easy way to just get the name of the url.

            var urlHost = HttpContext.Current.Request.Url.Host;

            var xUrlHost = urlHost.Split('.');
            foreach(var thing in xUrlHost)
            {
                if(thing != "www" && thing != "com")
                {
                    urlHost = thing;
                }
            }

How do I unload (reload) a Python module?

The following code allows you Python 2/3 compatibility:

try:
    reload
except NameError:
    # Python 3
    from imp import reload

The you can use it as reload() in both versions which makes things simpler.

React: how to update state.item[1] in state using setState?

Mutation free:

// given a state
state = {items: [{name: 'Fred', value: 1}, {name: 'Wilma', value: 2}]}

// This will work without mutation as it clones the modified item in the map:
this.state.items
   .map(item => item.name === 'Fred' ? {...item, ...{value: 3}} : item)

this.setState(newItems)

Taking inputs with BufferedReader in Java

You can't read individual integers in a single line separately using BufferedReader as you do using Scannerclass. Although, you can do something like this in regard to your query :

import java.io.*;
class Test
{
   public static void main(String args[])throws IOException
    {
       BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
       int t=Integer.parseInt(br.readLine());
       for(int i=0;i<t;i++)
       {
         String str=br.readLine();
         String num[]=br.readLine().split(" ");
         int num1=Integer.parseInt(num[0]);
         int num2=Integer.parseInt(num[1]);
         //rest of your code
       }
    }
}

I hope this will help you.

How to create a global variable?

From the official Swift programming guide:

Global variables are variables that are defined outside of any function, method, closure, or type context. Global constants and variables are always computed lazily.

You can define it in any file and can access it in current module anywhere. So you can define it somewhere in the file outside of any scope. There is no need for static and all global variables are computed lazily.

 var yourVariable = "someString"

You can access this from anywhere in the current module.

However you should avoid this as Global variables are not good for application state and mainly reason of bugs.

As shown in this answer, in Swift you can encapsulate them in struct and can access anywhere. You can define static variables or constant in Swift also. Encapsulate in struct

struct MyVariables {
    static var yourVariable = "someString"
}

You can use this variable in any class or anywhere

let string = MyVariables.yourVariable
println("Global variable:\(string)")

//Changing value of it
MyVariables.yourVariable = "anotherString"

javac not working in windows command prompt

The path will only be set for the administrator account. Therefore it is important to launch command prompt as administrator, if you are not already.

how to open *.sdf files?

In addition to the methods described by @ctacke, you can also open SQL Server Compact Edition databases with SQL Server Management Studio. You'll need SQL Server 2008 to open SQL CE 3.5 databases.

Convert string to Boolean in javascript

Unfortunately, I didn't find function something like Boolean.ParseBool('true') which returns true as Boolean type like in C#. So workaround is

var setActive = 'true'; 
setActive = setActive == "true";

if(setActive)
// statements
else
// statements.

How to test if JSON object is empty in Java

Try:

if (record.has("problemkey") && !record.isNull("problemkey")) {
    // Do something with object.
}

Print a variable in hexadecimal in Python

A way that will fail if your input string isn't valid pairs of hex characters...:

>>> import binascii
>>> ' '.join(hex(ord(i)) for i in binascii.unhexlify('deadbeef'))
'0xde 0xad 0xbe 0xef'

Executing multiple SQL queries in one statement with PHP

You can just add the word JOIN or add a ; after each line(as @pictchubbate said). Better this way because of readability and also you should not meddle DELETE with INSERT; it is easy to go south.

The last question is a matter of debate, but as far as I know yes you should close after a set of queries. This applies mostly to old plain mysql/php and not PDO, mysqli. Things get more complicated(and heated in debates) in these cases.

Finally, I would suggest either using PDO or some other method.

Print to the same line and not a new line?

From python 3.x you can do:

print('bla bla', end='')

(which can also be used in Python 2.6 or 2.7 by putting from __future__ import print_function at the top of your script/module)

Python console progressbar example:

import time

# status generator
def range_with_status(total):
    """ iterate from 0 to total and show progress in console """
    n=0
    while n<total:
        done = '#'*(n+1)
        todo = '-'*(total-n-1)
        s = '<{0}>'.format(done+todo)
        if not todo:
            s+='\n'        
        if n>0:
            s = '\r'+s
        print(s, end='')
        yield n
        n+=1

# example for use of status generator
for i in range_with_status(10):
    time.sleep(0.1)

Jinja2 shorthand conditional

Alternative way (but it's not python style. It's JS style)

{{ files and 'Update' or 'Continue' }}

ggplot2 plot without axes, legends, etc

'opts' is deprecated.

in ggplot2 >= 0.9.2 use

p + theme(legend.position = "none") 

Convert an integer to a float number

Type Conversions T() where T is the desired datatype of the result are quite simple in GoLang.

In my program, I scan an integer i from the user input, perform a type conversion on it and store it in the variable f. The output prints the float64 equivalent of the int input. float32 datatype is also available in GoLang

Code:

package main
import "fmt"
func main() {
    var i int
    fmt.Println("Enter an Integer input: ")
    fmt.Scanf("%d", &i)
    f := float64(i)
    fmt.Printf("The float64 representation of %d is %f\n", i, f)
}

Solution:

>>> Enter an Integer input:
>>> 232332
>>> The float64 representation of 232332 is 232332.000000

How to define two angular apps / modules in one page?

Only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application. To run multiple applications in an HTML document you must manually bootstrap them using angular.bootstrap instead. AngularJS applications cannot be nested within each other. -- http://docs.angularjs.org/api/ng.directive:ngApp

See also

How to make a jquery function call after "X" seconds

If you could show the actual page, we, possibly, could help you better.

If you want to trigger the button only after the iframe is loaded, you might want to check if it has been loaded or use the iframe.onload:

<iframe .... onload='buttonWhatever(); '></iframe>


<script type="text/javascript">

    function buttonWhatever() {
        $("#<%=Button1.ClientID%>").click(function (event) {
            $('#<%=TextBox1.ClientID%>').change(function () {
                $('#various3').attr('href', $(this).val());
            });
            $("#<%=Button2.ClientID%>").click();
        });

        function showStickySuccessToast() {
            $().toastmessage('showToast', {
                text: 'Finished Processing!',
                sticky: false,
                position: 'middle-center',
                type: 'success',
                closeText: '',
                close: function () { }
            });
        }
    }

</script>

How to convert .pfx file to keystore with private key?

Justin(above) is accurate. However, keep in mind that depending on who you get the certificate from (intermediate CA, root CA involved or not) or how the pfx is created/exported, sometimes they could be missing the certificate chain. After Import, You would have a certificate of PrivateKeyEntry type, but with a chain of length of 1.

To fix this, there are several options. The easier option in my mind is to import and export the pfx file in IE(choosing the option of Including all the certificates in the chain). The import and export process of certificates in IE should be very easy and well documented elsewhere.

Once exported, import the keystore as Justin pointed above. Now, you would have a keystore with certificate of type PrivateKeyEntry and with a certificate chain length of more than 1.

Certain .Net based Web service clients error out(unable to establish trust relationship), if you don't do the above.

How do I generate random number for each row in a TSQL Select?

select ABS(CAST(CAST(NEWID() AS VARBINARY) AS INT)) as [Randomizer]

has always worked for me

JPanel vs JFrame in Java

You should not extend the JFrame class unnecessarily (only if you are adding extra functionality to the JFrame class)

JFrame:

JFrame extends Component and Container.

It is a top level container used to represent the minimum requirements for a window. This includes Borders, resizability (is the JFrame resizeable?), title bar, controls (minimize/maximize allowed?), and event handlers for various Events like windowClose, windowOpened etc.

JPanel:

JPanel extends Component, Container and JComponent

It is a generic class used to group other Components together.

  • It is useful when working with LayoutManagers e.g. GridLayout f.i adding components to different JPanels which will then be added to the JFrame to create the gui. It will be more manageable in terms of Layout and re-usability.

  • It is also useful for when painting/drawing in Swing, you would override paintComponent(..) and of course have the full joys of double buffering.

A Swing GUI cannot exist without a top level container like (JWindow, Window, JFrame Frame or Applet), while it may exist without JPanels.

How to resolve "Input string was not in a correct format." error?

If using TextBox2.Text as the source for a numeric value, it must first be checked to see if a value exists, and then converted to integer.

If the text box is blank when Convert.ToInt32 is called, you will receive the System.FormatException. Suggest trying:

protected void SetImageWidth()
{
   try{
      Image1.Width = Convert.ToInt32(TextBox1.Text);
   }
   catch(System.FormatException)
   {
      Image1.Width = 100; // or other default value as appropriate in context.
   }
}

How to find all links / pages on a website

If you have the developer console (JavaScript) in your browser, you can type this code in:

urls = document.querySelectorAll('a'); for (url in urls) console.log(urls[url].href);

Shortened:

n=$$('a');for(u in n)console.log(n[u].href)

How to create a new object instance from a Type

Just as an extra to anyone using the above answers that implement:

ObjectType instance = (ObjectType)Activator.CreateInstance(objectType);

Be careful - if your Constructor isn't "Public" then you will get the following error:

"System.MissingMethodException: 'No parameterless constructor defined for this object."

Your class can be Internal/Friend, or whatever you need but the constructor must be public.

Fetch API with Cookie

In addition to @Khanetor's answer, for those who are working with cross-origin requests: credentials: 'include'

Sample JSON fetch request:

fetch(url, {
  method: 'GET',
  credentials: 'include'
})
  .then((response) => response.json())
  .then((json) => {
    console.log('Gotcha');
  }).catch((err) => {
    console.log(err);
});

https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials

Uses of content-disposition in an HTTP response header

For asp.net users, the .NET framework provides a class to create a content disposition header: System.Net.Mime.ContentDisposition

Basic usage:

var cd = new System.Net.Mime.ContentDisposition();
cd.FileName = "myFile.txt";
cd.ModificationDate = DateTime.UtcNow;
cd.Size = 100;
Response.AppendHeader("content-disposition", cd.ToString());

How to send email to multiple recipients with addresses stored in Excel?

You have to loop through every cell in the range "D3:D6" and construct your To string. Simply assigning it to a variant will not solve the purpose. EmailTo becomes an array if you assign the range directly to it. You can do this as well but then you will have to loop through the array to create your To string

Is this what you are trying? (TRIED AND TESTED)

Option Explicit

Sub Mail_workbook_Outlook_1()
     'Working in 2000-2010
     'This example send the last saved version of the Activeworkbook
    Dim OutApp As Object
    Dim OutMail As Object
    Dim emailRng As Range, cl As Range
    Dim sTo As String

    Set emailRng = Worksheets("Selections").Range("D3:D6")

    For Each cl In emailRng 
        sTo = sTo & ";" & cl.Value
    Next

    sTo = Mid(sTo, 2)

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    On Error Resume Next
    With OutMail
        .To = sTo
        .CC = "[email protected];[email protected]"
        .BCC = ""
        .Subject = "RMA #" & Worksheets("RMA").Range("E1")
        .Body = "Attached to this email is RMA #" & _
        Worksheets("RMA").Range("E1") & _
        ". Please follow the instructions for your department included in this form."
        .Attachments.Add ActiveWorkbook.FullName
         'You can add other files also like this
         '.Attachments.Add ("C:\test.txt")

        .Display
    End With
    On Error GoTo 0

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

How to determine the Schemas inside an Oracle Data Pump Export file

Assuming that you do not have the log file from the expdp job that generated the file in the first place, the easiest option would probably be to use the SQLFILE parameter to have impdp generate a file of DDL (based on a full import). Then you can grab the schema names from that file. Not ideal, of course, since impdp has to read the entire dump file to extract the DDL and then again to get to the schema you're interested in, and you have to do a bit of text file searching for the various CREATE USER statements, but it should be doable.

How to convert Blob to String and String to Blob in java

And here is my solution, that always works for me

StringBuffer buf = new StringBuffer();
String temp;
BufferedReader bufReader = new BufferedReader(new InputStreamReader(myBlob.getBinaryStream()));
    while ((temp=bufReader.readLine())!=null) {
        bufappend(temp);
    }

phpMyAdmin is throwing a #2002 cannot log in to the mysql server phpmyadmin

For those who get this error when working with WAMP/XAMP on a windows machine.

This may help you.

Your solution is to

  • net stop mysql
  • Erase binary logs (and the binary log index file)
  • IF you do not know where they are, locate my.ini on your PC
  • Open my.ini in Notepad look for the option log-bin or log_bin
  • Look for the option datadir
  • If log-bin only has a filename, look inside the folder specified by datadir
  • If log-bin includes a path and a filename, look inside the folder specified by log-bin
  • Open the desired folder in Windows Explorer
  • Remove the binary logs There should be a file whose file extension is .index. Delete this as well net start mysql

Please DO NOT ERASE ib_logfile0 or ib_logfile1 when you have binary log issues.

Answer is on dba.stackexchange

Making an API call in Python with an API that requires a bearer token

The token has to be placed in an Authorization header according to the following format:

Authorization: Bearer [Token_Value]

Code below:

import urllib2
import json

def get_auth_token():
    """
    get an auth token
    """
    req=urllib2.Request("https://xforce-api.mybluemix.net/auth/anonymousToken")
    response=urllib2.urlopen(req)
    html=response.read()
    json_obj=json.loads(html)
    token_string=json_obj["token"].encode("ascii","ignore")
    return token_string

def get_response_json_object(url, auth_token):
    """
    returns json object with info
    """
    auth_token=get_auth_token()
    req=urllib2.Request(url, None, {"Authorization": "Bearer %s" %auth_token})
    response=urllib2.urlopen(req)
    html=response.read()
    json_obj=json.loads(html)
    return json_obj

Set selected option of select box

I know this has an accepted answer, but in reading the replies on the answer, I see some things that I can clear up that might help other people having issues with events not triggering after a value change.

This will select the value in the drop-down:

$("#gate").val("gateway_2")

If this select element is using JQueryUI or other JQuery wrapper, use the refresh method of the wrapper to update the UI to show that the value has been selected. The below example is for JQueryUI, but you will have to look at the documentation for the wrapper you are using to determine the correct method for the refresh:

$("#gate").selectmenu("refresh");

If there is an event that needs to be triggered such as a change event, you will have to trigger that manually as changing the value does not fire the event. The event you need to fire depends on how the event was created:

If the event was created with JQuery i.e. $("#gate").on("change",function(){}) then trigger the event using the below method:

$("#gate").change();

If the event was created using a standard JavaScript event i.e. then trigger the event using the below method:

var JSElem = $("#gate")[0];
if ("createEvent" in document) {
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("change", false, true);
    JSElem.dispatchEvent(evt);
} else {
    JSElem.fireEvent("onchange");
}

What method in the String class returns only the first N characters?

string truncatedToNLength = new string(s.Take(n).ToArray());  

This solution has a tiny bonus in that if n is greater than s.Length, it still does the right thing.

How find out which process is using a file in Linux?

@jim's answer is correct -- fuser is what you want.

Additionally (or alternately), you can use lsof to get more information including the username, in case you need permission (without having to run an additional command) to kill the process. (THough of course, if killing the process is what you want, fuser can do that with its -k option. You can have fuser use other signals with the -s option -- check the man page for details.)

For example, with a tail -F /etc/passwd running in one window:

ghoti@pc:~$ lsof | grep passwd
tail      12470    ghoti    3r      REG  251,0     2037 51515911 /etc/passwd

Note that you can also use lsof to find out what processes are using particular sockets. An excellent tool to have in your arsenal.

How can we run a test method with multiple parameters in MSTest?

This feature is in pre-release now and works with Visual Studio 2015.

For example:

[TestClass]
public class UnitTest1
{
    [TestMethod]
    [DataRow(1, 2, 2)]
    [DataRow(2, 3, 5)]
    [DataRow(3, 5, 8)]
    public void AdditionTest(int a, int b, int result)
    {
        Assert.AreEqual(result, a + b);
    }
}

How to make code wait while calling asynchronous calls like Ajax

Use callbacks. Something like this should work based on your sample code.

function someFunc() {

callAjaxfunc(function() {
    console.log('Pass2');
});

}

function callAjaxfunc(callback) {
    //All ajax calls called here
    onAjaxSuccess: function() {
        callback();
    };
    console.log('Pass1');    
}

This will print Pass1 immediately (assuming ajax request takes atleast a few microseconds), then print Pass2 when the onAjaxSuccess is executed.

7-Zip command to create and extract a password-protected ZIP file on Windows?

To fully script-automate:

Create:

7z -mhc=on -mhe=on -pPasswordHere a %ZipDest% %WhatYouWantToZip%

Unzip:

7z x %ZipFile% -pPasswordHere

(Depending, you might need to: Set Path=C:\Program Files\7-Zip;%Path% )

Selecting Multiple Values from a Dropdown List in Google Spreadsheet

I have found solution at https://www.youtube.com/watch?v=dm4z9l26O0I

You would need to use Tools > Script Editor. Create .gs and .html files there. See example at http://goo.gl/LxGXfU (link can be also found under Youtube video). Just copy

Once you have .gs and .html files in place save them and reload your spreadsheet. You will see "Custom menu" as the last item of your top menu. Select cell you would like to manage and click on this menu item.

During the first time it will ask you to authorize application - go ahead and do this.

Note (1): make sure that your cell has "Data validation" defined before you click on "Custom menu".

Note (2): it appeared that solution works with "List from a range" criteria for Data validation (it does not work with "List of items")

How do I get the picture size with PIL?

This is a complete example loading image from URL, creating with PIL, printing the size and resizing...

import requests
h = { 'User-Agent': 'Neo'}
r = requests.get("https://images.freeimages.com/images/large-previews/85c/football-1442407.jpg", headers=h)

from PIL import Image
from io import BytesIO
# create image from binary content
i = Image.open(BytesIO(r.content))


width, height = i.size
print(width, height)
i = i.resize((100,100))
display(i)

How to add property to object in PHP >= 5.3 strict mode without generating error

Yes, is possible to dynamically add properties to a PHP object.

This is useful when a partial object is received from javascript.

JAVASCRIPT side:

var myObject = { name = "myName" };
$.ajax({ type: "POST", url: "index.php",
    data: myObject, dataType: "json",
    contentType: "application/json;charset=utf-8"
}).success(function(datareceived){
    if(datareceived.id >= 0 ) { /* the id property has dynamically added on server side via PHP */ }
});

PHP side:

$requestString = file_get_contents('php://input');
$myObject = json_decode($requestString); // same object as was sent in the ajax call
$myObject->id = 30; // This will dynamicaly add the id property to the myObject object

OR JUST SEND A DUMMY PROPERTY from javascript that you will fill in PHP.

How to make the 'cut' command treat same sequental delimiters as one?

This Perl one-liner shows how closely Perl is related to awk:

perl -lane 'print $F[3]' text.txt

However, the @F autosplit array starts at index $F[0] while awk fields start with $1

Configuring RollingFileAppender in log4j

Toolbear74 is right log4j.XML is required. In order to get the XML to validate the <param> tags need to be BEFORE the <rollingPolicy> I suggest setting a logging threshold <param name="threshold" value="info"/>

When Creating a Log4j.xml file don't forget to to copy the log4j.dtd into the same location.

Here is an example:

<?xml version="1.0" encoding="windows-1252"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration>
<!-- Daily Rolling File Appender that compresses old files -->
  <appender name="file" class="org.apache.log4j.rolling.RollingFileAppender" >
     <param name="threshold" value="info"/>
     <rollingPolicy name="file"  
                      class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
        <param name="FileNamePattern" 
               value="${catalina.base}/logs/myapp.log.%d{yyyy-MM-dd}.gz"/>
        <param name="ActiveFileName" value="${catalina.base}/logs/myapp.log"/>
     </rollingPolicy>
     <layout class="org.apache.log4j.EnhancedPatternLayout" >
        <param name="ConversionPattern" 
               value="%d{ISO8601} %-5p - %-26.26c{1} - %m%n" />
    </layout>
  </appender>

  <root>
    <priority value="debug"></priority>
    <appender-ref ref="file" />
  </root>
</log4j:configuration>

Considering that your setting a FileNamePattern and an ActiveFileName I think that setting a File property is redundant and possibly even erroneous

Try renaming your log4j.properties and dropping in a log4j.xml similar to my example and see what happens.

phpMyAdmin Error: The mbstring extension is missing. Please check your PHP configuration

It could raise the concern if you're either:

Case 1: Downgrading/ upgrading any PHP version.
Case 2: Enabling/Disabling (Switching) between PHP versions.

Here are some recommended commands I found helpful to fix these concerns:

Message 1: The mbstring extension is missing.......

sudo apt-get install php7.1-mbstring  

Message 2: The mysqli extension is missing.......

sudo apt-get install php7.1-mysqli

Note: Tested with PHP version 7.1. Change PHP version as per requirement.

how to set font size based on container size?

I've given a more detailed answer of using vw with respect to specific container sizing in this answer, so I won't just repeat my answer here.

In summary, however, it is essentially a matter of factoring (or controlling) what the container size is going to be with respect to viewport, and then working out the proper vw sizing based on that for the container, taking mind of what needs to happen if something is dynamically resized.

So if you wanted a 5vw size at a container at 100% of the viewport width, then one at 75% of the viewport width you would probably want to be (5vw * .75) = 3.75vw.

What's the -practical- difference between a Bare and non-Bare repository?

A non-bare repository simply has a checked-out working tree. The working tree does not store any information about the state of the repository (branches, tags, etc.); rather, the working tree is just a representation of the actual files in the repo, which allows you to work on (edit, etc.) the files.

Style bottom Line in Android

This does the trick...

<item >
    <shape android:shape="rectangle">
        <solid android:color="#YOUR_BOTTOM_LINE_COLOR"/>
    </shape>
</item>

<item android:bottom="1.5dp">
    <shape android:shape="rectangle">
        <solid android:color="#YOUR_BG_COLOR"/>
    </shape>
</item>

Appending pandas dataframes generated in a for loop

Use pd.concat to merge a list of DataFrame into a single big DataFrame.

appended_data = []
for infile in glob.glob("*.xlsx"):
    data = pandas.read_excel(infile)
    # store DataFrame in list
    appended_data.append(data)
# see pd.concat documentation for more info
appended_data = pd.concat(appended_data)
# write DataFrame to an excel sheet 
appended_data.to_excel('appended.xlsx')

How to test the `Mosquitto` server?

In separate terminal windows do the following:

  1. Start the broker:

    mosquitto
    
  2. Start the command line subscriber:

    mosquitto_sub -v -t 'test/topic'
    
  3. Publish test message with the command line publisher:

    mosquitto_pub -t 'test/topic' -m 'helloWorld'
    

As well as seeing both the subscriber and publisher connection messages in the broker terminal the following should be printed in the subscriber terminal:

test/topic helloWorld

How to find files recursively by file type and copy them to a directory while in ssh?

Try this:

find . -name "*.pdf" -type f -exec cp {} ./pdfsfolder \;

error: expected class-name before ‘{’ token

Replace

#include "Landing.h"

with

class Landing;

If you still get errors, also post Item.h, Flight.h and common.h

EDIT: In response to comment.

You will need to e.g. #include "Landing.h" from Event.cpp in order to actually use the class. You just cannot include it from Event.h

Uncaught syntaxerror: unexpected identifier?

There are errors here :

var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");

The code must change to:

var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");

By the way, there is another error at line 129 :

var createLi.appendChild(createSubList);

Replace it with:

createLi.appendChild(createSubList);

AngularJS : How to watch service variables?

In a scenario like this, where multiple/unkown objects might be interested in changes, use $rootScope.$broadcast from the item being changed.

Rather than creating your own registry of listeners (which have to be cleaned up on various $destroys), you should be able to $broadcast from the service in question.

You must still code the $on handlers in each listener but the pattern is decoupled from multiple calls to $digest and thus avoids the risk of long-running watchers.

This way, also, listeners can come and go from the DOM and/or different child scopes without the service changing its behavior.

** update: examples **

Broadcasts would make the most sense in "global" services that could impact countless other things in your app. A good example is a User service where there are a number of events that could take place such as login, logout, update, idle, etc. I believe this is where broadcasts make the most sense because any scope can listen for an event, without even injecting the service, and it doesn't need to evaluate any expressions or cache results to inspect for changes. It just fires and forgets (so make sure it's a fire-and-forget notification, not something that requires action)

.factory('UserService', [ '$rootScope', function($rootScope) {
   var service = <whatever you do for the object>

   service.save = function(data) {
     .. validate data and update model ..
     // notify listeners and provide the data that changed [optional]
     $rootScope.$broadcast('user:updated',data);
   }

   // alternatively, create a callback function and $broadcast from there if making an ajax call

   return service;
}]);

The service above would broadcast a message to every scope when the save() function completed and the data was valid. Alternatively, if it's a $resource or an ajax submission, move the broadcast call into the callback so it fires when the server has responded. Broadcasts suit that pattern particularly well because every listener just waits for the event without the need to inspect the scope on every single $digest. The listener would look like:

.controller('UserCtrl', [ 'UserService', '$scope', function(UserService, $scope) {

  var user = UserService.getUser();

  // if you don't want to expose the actual object in your scope you could expose just the values, or derive a value for your purposes
   $scope.name = user.firstname + ' ' +user.lastname;

   $scope.$on('user:updated', function(event,data) {
     // you could inspect the data to see if what you care about changed, or just update your own scope
     $scope.name = user.firstname + ' ' + user.lastname;
   });

   // different event names let you group your code and logic by what happened
   $scope.$on('user:logout', function(event,data) {
     .. do something differently entirely ..
   });

 }]);

One of the benefits of this is the elimination of multiple watches. If you were combining fields or deriving values like the example above, you'd have to watch both the firstname and lastname properties. Watching the getUser() function would only work if the user object was replaced on updates, it would not fire if the user object merely had its properties updated. In which case you'd have to do a deep watch and that is more intensive.

$broadcast sends the message from the scope it's called on down into any child scopes. So calling it from $rootScope will fire on every scope. If you were to $broadcast from your controller's scope, for example, it would fire only in the scopes that inherit from your controller scope. $emit goes the opposite direction and behaves similarly to a DOM event in that it bubbles up the scope chain.

Keep in mind that there are scenarios where $broadcast makes a lot of sense, and there are scenarios where $watch is a better option - especially if in an isolate scope with a very specific watch expression.

How do I set GIT_SSL_NO_VERIFY for specific repos only?

There is an easy way of configuring GIT to handle your server the right way. Just add an specific http section for your git server and specify which certificate (Base64 encoded) to trust:

~/.gitconfig

[http "https://repo.your-server.com"]
# windows path use double back slashes
#  sslCaInfo = C:\\Users\\<user>\\repo.your-server.com.cer
# unix path to certificate (Base64 encoded)
sslCaInfo = /home/<user>/repo.your-server.com.cer

This way you will have no more SSL errors and validate the (usually) self-signed certificate. This is the best way to go, as it protects you from man-in-the-middle attacks. When you just disable ssl verification you are vulnerable to these kind of attacks.

https://git-scm.com/docs/git-config#git-config-httplturlgt

What are the differences between using the terminal on a mac vs linux?

If you did a new or clean install of OS X version 10.3 or more recent, the default user terminal shell is bash.

Bash is essentially an enhanced and GNU freeware version of the original Bourne shell, sh. If you have previous experience with bash (often the default on GNU/Linux installations), this makes the OS X command-line experience familiar, otherwise consider switching your shell either to tcsh or to zsh, as some find these more user-friendly.

If you upgraded from or use OS X version 10.2.x, 10.1.x or 10.0.x, the default user shell is tcsh, an enhanced version of csh('c-shell'). Early implementations were a bit buggy and the programming syntax a bit weird so it developed a bad rap.

There are still some fundamental differences between mac and linux as Gordon Davisson so aptly lists, for example no useradd on Mac and ifconfig works differently.

The following table is useful for knowing the various unix shells.

sh      The original Bourne shell   Present on every unix system 
ksh     Original Korn shell         Richer shell programming environment than sh 
csh     Original C-shell            C-like syntax; early versions buggy 
tcsh    Enhanced C-shell            User-friendly and less buggy csh implementation 
bash    GNU Bourne-again shell      Enhanced and free sh implementation 
zsh     Z shell                     Enhanced, user-friendly ksh-like shell

You may also find these guides helpful:

http://homepage.mac.com/rgriff/files/TerminalBasics.pdf

http://guides.macrumors.com/Terminal
http://www.ofb.biz/safari/article/476.html

On a final note, I am on Linux (Ubuntu 11) and Mac osX so I use bash and the thing I like the most is customizing the .bashrc (source'd from .bash_profile on OSX) file with aliases, some examples below. I now placed all my aliases in a separate .bash_aliases file and include it with:

if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

in the .bashrc or .bash_profile file.

Note that this is an example of a mac-linux difference because on a Mac you can't have the --color=auto. The first time I did this (without knowing) I redefined ls to be invalid which was a bit alarming until I removed --auto-color !

You may also find https://unix.stackexchange.com/q/127799/10043 useful

# ~/.bash_aliases
# ls variants
#alias l='ls -CF' 
alias la='ls -A' 
alias l='ls -alFtr' 
alias lsd='ls -d .*' 
# Various
alias h='history | tail'
alias hg='history | grep'
alias mv='mv -i' 
alias zap='rm -i'
# One letter quickies:
alias p='pwd'
alias x='exit'
alias {ack,ak}='ack-grep'
# Directories
alias s='cd ..'
alias play='cd ~/play/'
# Rails
alias src='script/rails console'
alias srs='script/rails server'
alias raked='rake db:drop db:create db:migrate db:seed' 
alias rvm-restart='source '\''/home/durrantm/.rvm/scripts/rvm'\'''
alias rrg='rake routes | grep '
alias rspecd='rspec --drb '
#
# DropBox - syncd
WORKBASE="~/Dropbox/97_2012/work"
alias work="cd $WORKBASE"
alias code="cd $WORKBASE/ror/code"
#
# DropNot - NOT syncd !
WORKBASE_GIT="~/Dropnot"
alias {dropnot,not}="cd $WORKBASE_GIT"
alias {webs,ww}="cd $WORKBASE_GIT/webs"
alias {setups,docs}="cd $WORKBASE_GIT/setups_and_docs"
alias {linker,lnk}="cd $WORKBASE_GIT/webs/rails_v3/linker"
#
# git
alias {gsta,gst}='git status' 
# Warning: gst conflicts with gnu-smalltalk (when used).
alias {gbra,gb}='git branch'
alias {gco,go}='git checkout'
alias {gcob,gob}='git checkout -b '
alias {gadd,ga}='git add '
alias {gcom,gc}='git commit'
alias {gpul,gl}='git pull '
alias {gpus,gh}='git push '
alias glom='git pull origin master'
alias ghom='git push origin master'
alias gg='git grep '
#
# vim
alias v='vim'
#
# tmux
alias {ton,tn}='tmux set -g mode-mouse on'
alias {tof,tf}='tmux set -g mode-mouse off'
#
# dmc
alias {dmc,dm}='cd ~/Dropnot/webs/rails_v3/dmc/'
alias wf='cd ~/Dropnot/webs/rails_v3/dmc/dmWorkflow'
alias ws='cd ~/Dropnot/webs/rails_v3/dmc/dmStaffing'

How do I import the javax.servlet API in my Eclipse project?

For maven projects add following dependancy :

<!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
</dependency>

Reference

For gradle projects:

dependencies {
providedCompile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.0.1'
}

or download javax.servlet.jar and add to your project.

Live video streaming using Java?

You can do this today in Java with the Red5 media server from Flash. If you want to also decode and encode video in Java, you can use the Xuggler project.

asp.net: Invalid postback or callback argument

If you look at the first lines of text you can glean what your error is.

this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them

You're dynamically editing the lstProblems dropdown, so when you post back ASP.NET says "Warning! Invalid entries in the dropdown!" and freaks out throwing that error. You have to determine if turning off event validation is an OK solution, but I would research it before doing it, since the idea behind it is to make your site more secure for free.

Here's another stackoverflow answer that does a much better job explaining what to do than me: Invalid postback or callback argument. Event validation is enabled using '<pages enableEventValidation="true"/>'

Excel VBA Run Time Error '424' object required

You have two options,

-If you want the value:

Dim MyValue as Variant ' or string/date/long/...
MyValue = ThisWorkbook.Sheets(1).Range("A1").Value

-if you want the cell object:

Dim oCell as Range  ' or object (but then you'll miss out on intellisense), and both can also contain more than one cell.
Set oCell = ThisWorkbook.Sheets(1).Range("A1")

Execution failed for task 'app:mergeDebugResources' Crunching Cruncher....png failed

If you're running Linux, try this:

sudo apt-get install lib32stdc++6 lib32z1

It is from here.

JavaScript by reference vs. by value

Javascript always passes by value. However, if you pass an object to a function, the "value" is really a reference to that object, so the function can modify that object's properties but not cause the variable outside the function to point to some other object.

An example:

function changeParam(x, y, z) {
  x = 3;
  y = "new string";
  z["key2"] = "new";
  z["key3"] = "newer";

  z = {"new" : "object"};
}

var a = 1,
    b = "something",
    c = {"key1" : "whatever", "key2" : "original value"};

changeParam(a, b, c);

// at this point a is still 1
// b is still "something"
// c still points to the same object but its properties have been updated
// so it is now {"key1" : "whatever", "key2" : "new", "key3" : "newer"}
// c definitely doesn't point to the new object created as the last line
// of the function with z = ...

Show a message box from a class in c#?

Try this:

System.Windows.Forms.MessageBox.Show("Here's a message!");

Checking Value of Radio Button Group via JavaScript?

If you are using a javascript library like jQuery, it's very easy:

alert($('input[name=gender]:checked').val());

This code will select the checked input with gender name, and gets it's value. Simple isn't it?

Live demo

Meaning of 'const' last in a function declaration of a class?

These const mean that compiler will Error if the method 'with const' changes internal data.

class A
{
public:
    A():member_()
    {
    }

    int hashGetter() const
    {
        state_ = 1;
        return member_;
    }
    int goodGetter() const
    {
        return member_;
    }
    int getter() const
    {
        //member_ = 2; // error
        return member_;
    }
    int badGetter()
    {
        return member_;
    }
private:
    mutable int state_;
    int member_;
};

The test

int main()
{
    const A a1;
    a1.badGetter(); // doesn't work
    a1.goodGetter(); // works
    a1.hashGetter(); // works

    A a2;
    a2.badGetter(); // works
    a2.goodGetter(); // works
    a2.hashGetter(); // works
}

Read this for more information

TypeError: sequence item 0: expected string, int found

you can convert the integer dataframe into string first and then do the operation e.g.

df3['nID']=df3['nID'].astype(str)
grp = df3.groupby('userID')['nID'].aggregate(lambda x: '->'.join(tuple(x)))

formGroup expects a FormGroup instance

I was using reactive forms and ran into similar problems. What helped me was to make sure that I set up a corresponding FormGroup in the class. Something like this:

myFormGroup: FormGroup = this.builder.group({
    dob: ['', Validators.required]
});

Print page numbers on pages when printing html

   **@page {
            margin-top:21% !important; 
            @top-left{
            content: element(header);

            }

            @bottom-left {
            content: element(footer
 }
 div.header {

            position: running(header);

            }
            div.footer {

            position: running(footer);
            border-bottom: 2px solid black;


            }
           .pagenumber:before {
            content: counter(page);
            }
            .pagecount:before {
            content: counter(pages);
            }      
 <div class="footer" style="font-size:12pt; font-family: Arial; font-family: Arial;">
                <span>Page <span class="pagenumber"/> of <span class="pagecount"/></span>
            </div >**

SHA1 vs md5 vs SHA256: which to use for a PHP login?

MD5 is bad because of collision problems - two different passwords possibly generating the same md-5.

Sha-1 would be plenty secure for this. The reason you store the salted sha-1 version of the password is so that you the swerver do not keep the user's apassword on file, that they may be using with other people's servers. Otherwise, what difference does it make?

If the hacker steals your entire unencrypted database some how, the only thing a hashed salted password does is prevent him from impersonating the user for future signons - the hacker already has the data.

What good does it do the attacker to have the hashed value, if what your user inputs is a plain password?

And even if the hacker with future technology could generate a million sha-1 keys a second for a brute force attack, would your server handle a million logons a second for the hacker to test his keys? That's if you are letting the hacker try to logon with the salted sha-1 instead of a password like a normal logon.

The best bet is to limit bad logon attempts to some reasonable number - 25 for example, and then time the user out for a minute or two. And if the cumulative bady logon attempts hits 250 within 24 hours, shut the account access down and email the owner.

How to do SVN Update on my project using the command line

If you want to update your project using SVN then first of all:

  1. Go to the path on which your project is stored through command prompt.

  2. Use the command SVN update

That's it.

iPhone hide Navigation Bar only on first page

After multiple trials here is how I got it working for what I wanted. This is what I was trying. - I have a view with a image. and I wanted to have the image go full screen. - I have a navigation controller with a tabBar too. So i need to hide that too. - Also, my main requirement was not just hiding, but having a fading effect too while showing and hiding.

This is how I got it working.

Step 1 - I have a image and user taps on that image once. I capture that gesture and push it into the new imageViewController, its in the imageViewController, I want to have full screen image.

- (void)handleSingleTap:(UIGestureRecognizer *)gestureRecognizer {  
NSLog(@"Single tap");
ImageViewController *imageViewController =
[[ImageViewController alloc] initWithNibName:@"ImageViewController" bundle:nil];

godImageViewController.imgName  = // pass the image.
godImageViewController.hidesBottomBarWhenPushed=YES;// This is important to note. 

[self.navigationController pushViewController:godImageViewController animated:YES];
// If I remove the line below, then I get this error. [CALayer retain]: message sent to deallocated instance . 
// [godImageViewController release];
} 

Step 2 - All these steps below are in the ImageViewController

Step 2.1 - In ViewDidLoad, show the navBar

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
NSLog(@"viewDidLoad");
[[self navigationController] setNavigationBarHidden:NO animated:YES];
}

Step 2.2 - In viewDidAppear, set up a timer task with delay ( I have it set for 1 sec delay). And after the delay, add fading effect. I am using alpha to use fading.

- (void)viewDidAppear:(BOOL)animated
{
NSLog(@"viewDidAppear");

myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self     selector:@selector(fadeScreen) userInfo:nil repeats:NO];
}

- (void)fadeScreen
{
[UIView beginAnimations:nil context:nil]; // begins animation block
[UIView setAnimationDuration:1.95];        // sets animation duration
self.navigationController.navigationBar.alpha = 0.0;       // Fades the alpha channel of   this view to "0.0" over the animationDuration of "0.75" seconds
[UIView commitAnimations];   // commits the animation block.  This Block is done.
}

step 2.3 - Under viewWillAppear, add singleTap gesture to the image and make the navBar translucent.

- (void) viewWillAppear:(BOOL)animated
{

NSLog(@"viewWillAppear");


NSString *path = [[NSBundle mainBundle] pathForResource:self.imgName ofType:@"png"];

UIImage *theImage = [UIImage imageWithContentsOfFile:path];

self.imgView.image = theImage;

// add tap gestures 
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];  
[self.imgView addGestureRecognizer:singleTap];  
[singleTap release];  

// to make the image go full screen
self.navigationController.navigationBar.translucent=YES;
}

- (void)handleTap:(UIGestureRecognizer *)gestureRecognizer 
{ 
 NSLog(@"Handle Single tap");
 [self finishedFading];
  // fade again. You can choose to skip this can add a bool, if you want to fade again when user taps again. 
 myTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self  selector:@selector(fadeScreen) userInfo:nil repeats:NO];
 }

Step 3 - Finally in viewWillDisappear, make sure to put all the stuff back

- (void)viewWillDisappear: (BOOL)animated 
{ 
self.hidesBottomBarWhenPushed = NO; 
self.navigationController.navigationBar.translucent=NO;

if (self.navigationController.topViewController != self)
{
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

[super viewWillDisappear:animated];
}

How to validate email id in angularJs using ng-pattern

If you want to validate email then use input with type="email" instead of type="text". AngularJS has email validation out of the box, so no need to use ng-pattern for this.

Here is the example from original documentation:

<script>
function Ctrl($scope) {
  $scope.text = '[email protected]';
}
</script>
<form name="myForm" ng-controller="Ctrl">
  Email: <input type="email" name="input" ng-model="text" required>
  <br/>
  <span class="error" ng-show="myForm.input.$error.required">
    Required!</span>
  <span class="error" ng-show="myForm.input.$error.email">
    Not valid email!</span>
  <br>
  <tt>text = {{text}}</tt><br/>
  <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
</form>

For more details read this doc: https://docs.angularjs.org/api/ng/input/input%5Bemail%5D

Live example: http://plnkr.co/edit/T2X02OhKSLBHskdS2uIM?p=info

UPD:

If you are not satisfied with built-in email validator and you want to use your custom RegExp pattern validation then ng-pattern directive can be applied and according to the documentation the error message can be displayed like this:

The validator sets the pattern error key if the ngModel.$viewValue does not match a RegExp

<script>
function Ctrl($scope) {
  $scope.text = '[email protected]';
  $scope.emailFormat = /^[a-z]+[a-z0-9._]+@[a-z]+\.[a-z.]{2,5}$/;
}
</script>
<form name="myForm" ng-controller="Ctrl">
  Email: <input type="email" name="input" ng-model="text" ng-pattern="emailFormat" required>
  <br/><br/>
  <span class="error" ng-show="myForm.input.$error.required">
    Required!
  </span><br/>
  <span class="error" ng-show="myForm.input.$error.pattern">
    Not valid email!
  </span>
  <br><br>
  <tt>text = {{text}}</tt><br/>
  <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  <tt>myForm.$error.pattern = {{!!myForm.$error.pattern}}</tt><br/>
</form>

Plunker: https://plnkr.co/edit/e4imaxX6rTF6jfWbp7mQ?p=preview

Disable Input fields in reactive form

If you want to disable first(formcontrol) then you can use below statement.

this.form.first.disable();

How do I find all the files that were created today in Unix/Linux?

Just keep in mind there are 2 spaces between Aug and 26. Other wise your find command will not work.

find . -type f -exec ls -l {} \; |  egrep "Aug 26";

What are the differences between type() and isinstance()?

Differences between isinstance() and type() in Python?

Type-checking with

isinstance(obj, Base)

allows for instances of subclasses and multiple possible bases:

isinstance(obj, (Base1, Base2))

whereas type-checking with

type(obj) is Base

only supports the type referenced.


As a sidenote, is is likely more appropriate than

type(obj) == Base

because classes are singletons.

Avoid type-checking - use Polymorphism (duck-typing)

In Python, usually you want to allow any type for your arguments, treat it as expected, and if the object doesn't behave as expected, it will raise an appropriate error. This is known as polymorphism, also known as duck-typing.

def function_of_duck(duck):
    duck.quack()
    duck.swim()

If the code above works, we can presume our argument is a duck. Thus we can pass in other things are actual sub-types of duck:

function_of_duck(mallard)

or that work like a duck:

function_of_duck(object_that_quacks_and_swims_like_a_duck)

and our code still works.

However, there are some cases where it is desirable to explicitly type-check. Perhaps you have sensible things to do with different object types. For example, the Pandas Dataframe object can be constructed from dicts or records. In such a case, your code needs to know what type of argument it is getting so that it can properly handle it.

So, to answer the question:

Differences between isinstance() and type() in Python?

Allow me to demonstrate the difference:

type

Say you need to ensure a certain behavior if your function gets a certain kind of argument (a common use-case for constructors). If you check for type like this:

def foo(data):
    '''accepts a dict to construct something, string support in future'''
    if type(data) is not dict:
        # we're only going to test for dicts for now
        raise ValueError('only dicts are supported for now')

If we try to pass in a dict that is a subclass of dict (as we should be able to, if we're expecting our code to follow the principle of Liskov Substitution, that subtypes can be substituted for types) our code breaks!:

from collections import OrderedDict

foo(OrderedDict([('foo', 'bar'), ('fizz', 'buzz')]))

raises an error!

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in foo
ValueError: argument must be a dict

isinstance

But if we use isinstance, we can support Liskov Substitution!:

def foo(a_dict):
    if not isinstance(a_dict, dict):
        raise ValueError('argument must be a dict')
    return a_dict

foo(OrderedDict([('foo', 'bar'), ('fizz', 'buzz')]))

returns OrderedDict([('foo', 'bar'), ('fizz', 'buzz')])

Abstract Base Classes

In fact, we can do even better. collections provides Abstract Base Classes that enforce minimal protocols for various types. In our case, if we only expect the Mapping protocol, we can do the following, and our code becomes even more flexible:

from collections import Mapping

def foo(a_dict):
    if not isinstance(a_dict, Mapping):
        raise ValueError('argument must be a dict')
    return a_dict

Response to comment:

It should be noted that type can be used to check against multiple classes using type(obj) in (A, B, C)

Yes, you can test for equality of types, but instead of the above, use the multiple bases for control flow, unless you are specifically only allowing those types:

isinstance(obj, (A, B, C))

The difference, again, is that isinstance supports subclasses that can be substituted for the parent without otherwise breaking the program, a property known as Liskov substitution.

Even better, though, invert your dependencies and don't check for specific types at all.

Conclusion

So since we want to support substituting subclasses, in most cases, we want to avoid type-checking with type and prefer type-checking with isinstance - unless you really need to know the precise class of an instance.

Angular ng-repeat Error "Duplicates in a repeater are not allowed."

Just in case this happens to someone else, I'm documenting this here, I was getting this error because I mistakenly set the ng-model the same as the ng-repeat array:

 <select ng-model="list_views">
     <option ng-selected="{{view == config.list_view}}"
         ng-repeat="view in list_views"
         value="{{view}}">
         {{view}}
     </option>
 </select>

Instead of:

<select ng-model="config.list_view">
     <option ng-selected="{{view == config.list_view}}"
         ng-repeat="view in list_views"
         value="{{view}}">
         {{view}}
     </option>
 </select>

I checked the array and didn't have any duplicates, just double check your variables.

What's the difference between an argument and a parameter?

Parameters and Arguments

All the different terms that have to do with parameters and arguments can be confusing. However, if you keep a few simple points in mind, you will be able to easily handle these terms.

  1. The formal parameters for a function are listed in the function declaration and are used in the body of the function definition. A formal parameter (of any sort) is a kind of blank or placeholder that is filled in with something when the function is called.
  2. An argument is something that is used to fill in a formal parameter. When you write down a function call, the arguments are listed in parentheses after the function name. When the function call is executed, the arguments are plugged in for the formal parameters.
  3. The terms call-by-value and call-by-reference refer to the mechanism that is used in the plugging-in process. In the call-by-value method only the value of the argument is used. In this call-by-value mechanism, the formal parameter is a local variable that is initialized to the value of the corresponding argument. In the call-by-reference mechanism the argument is a variable and the entire variable is used. In the call- by-reference mechanism the argument variable is substituted for the formal parameter so that any change that is made to the formal parameter is actually made to the argument variable.

Source: Absolute C++, Walter Savitch

That is,

enter image description here

Handling InterruptedException in Java

I just wanted to add one last option to what most people and articles mention. As mR_fr0g has stated, it's important to handle the interrupt correctly either by:

  • Propagating the InterruptException

  • Restore Interrupt state on Thread

Or additionally:

  • Custom handling of Interrupt

There is nothing wrong with handling the interrupt in a custom way depending on your circumstances. As an interrupt is a request for termination, as opposed to a forceful command, it is perfectly valid to complete additional work to allow the application to handle the request gracefully. For example, if a Thread is Sleeping, waiting on IO or a hardware response, when it receives the Interrupt, then it is perfectly valid to gracefully close any connections before terminating the thread.

I highly recommend understanding the topic, but this article is a good source of information: http://www.ibm.com/developerworks/java/library/j-jtp05236/

What is the correct syntax for 'else if'?

def function(a):
    if a == '1':
        print ('1a')
    else if a == '2'
        print ('2a')
    else print ('3a')

Should be corrected to:

def function(a):
    if a == '1':
        print('1a')
    elif a == '2':
        print('2a')
    else:
        print('3a')

As you can see, else if should be changed to elif, there should be colons after '2' and else, there should be a new line after the else statement, and close the space between print and the parentheses.

NULL value for int in Update statement

By using NULL without any quotes.

UPDATE `tablename` SET `fieldName` = NULL;

MySQL: Insert record if not exists in table

This query works well:

INSERT INTO `user` ( `username` , `password` )
    SELECT * FROM (SELECT 'ersks', md5( 'Nepal' )) AS tmp
    WHERE NOT EXISTS (SELECT `username` FROM `user` WHERE `username` = 'ersks' 
    AND `password` = md5( 'Nepal' )) LIMIT 1

And you can create the table using following query:

CREATE TABLE IF NOT EXISTS `user` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `username` varchar(30) NOT NULL,
    `password` varchar(32) NOT NULL,
    `status` tinyint(1) DEFAULT '0',
    PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Note: Create table using second query before trying to use first query.

How to calculate a mod b in Python?

There's the % sign. It's not just for the remainder, it is the modulo operation.

Getting hold of the outer class object from the inner class object

OuterClass.this references the outer class.

set the iframe height automatically

If you a framework like Bootstrap you can make any iframe video responsive by using this snippet:

<div class="embed-responsive embed-responsive-16by9">
    <iframe class="embed-responsive-item" src="vid.mp4" allowfullscreen></iframe>
</div>

PHP float with 2 decimal places: .00

You can use this simple function. number_format ()

    $num = 2214.56;

    // default english notation
    $english_format = number_format($num);
    // 2,215

    // French notation
    $format_francais = number_format($num, 2, ',', ' ');
    // 2 214,56

    $num1 = 2234.5688;

   // English notation with thousands separator
    $english_format_number = number_format($num1,2);
    // 2,234.57

    // english notation without thousands separator
    $english_format_number2 = number_format($num1, 2, '.', '');
    // 2234.57

How to determine CPU and memory consumption from inside a process?

Linux

In Linux, this information is available in the /proc file system. I'm not a big fan of the text file format used, as each Linux distribution seems to customize at least one important file. A quick look as the source to 'ps' reveals the mess.

But here is where to find the information you seek:

/proc/meminfo contains the majority of the system-wide information you seek. Here it looks like on my system; I think you are interested in MemTotal, MemFree, SwapTotal, and SwapFree:

Anderson cxc # more /proc/meminfo
MemTotal:      4083948 kB
MemFree:       2198520 kB
Buffers:         82080 kB
Cached:        1141460 kB
SwapCached:          0 kB
Active:        1137960 kB
Inactive:       608588 kB
HighTotal:     3276672 kB
HighFree:      1607744 kB
LowTotal:       807276 kB
LowFree:        590776 kB
SwapTotal:     2096440 kB
SwapFree:      2096440 kB
Dirty:              32 kB
Writeback:           0 kB
AnonPages:      523252 kB
Mapped:          93560 kB
Slab:            52880 kB
SReclaimable:    24652 kB
SUnreclaim:      28228 kB
PageTables:       2284 kB
NFS_Unstable:        0 kB
Bounce:              0 kB
CommitLimit:   4138412 kB
Committed_AS:  1845072 kB
VmallocTotal:   118776 kB
VmallocUsed:      3964 kB
VmallocChunk:   112860 kB
HugePages_Total:     0
HugePages_Free:      0
HugePages_Rsvd:      0
Hugepagesize:     2048 kB

For CPU utilization, you have to do a little work. Linux makes available overall CPU utilization since system start; this probably isn't what you are interested in. If you want to know what the CPU utilization was for the last second, or 10 seconds, then you need to query the information and calculate it yourself.

The information is available in /proc/stat, which is documented pretty well at http://www.linuxhowtos.org/System/procstat.htm; here is what it looks like on my 4-core box:

Anderson cxc #  more /proc/stat
cpu  2329889 0 2364567 1063530460 9034 9463 96111 0
cpu0 572526 0 636532 265864398 2928 1621 6899 0
cpu1 590441 0 531079 265949732 4763 351 8522 0
cpu2 562983 0 645163 265796890 682 7490 71650 0
cpu3 603938 0 551790 265919440 660 0 9040 0
intr 37124247
ctxt 50795173133
btime 1218807985
processes 116889
procs_running 1
procs_blocked 0

First, you need to determine how many CPUs (or processors, or processing cores) are available in the system. To do this, count the number of 'cpuN' entries, where N starts at 0 and increments. Don't count the 'cpu' line, which is a combination of the cpuN lines. In my example, you can see cpu0 through cpu3, for a total of 4 processors. From now on, you can ignore cpu0..cpu3, and focus only on the 'cpu' line.

Next, you need to know that the fourth number in these lines is a measure of idle time, and thus the fourth number on the 'cpu' line is the total idle time for all processors since boot time. This time is measured in Linux "jiffies", which are 1/100 of a second each.

But you don't care about the total idle time; you care about the idle time in a given period, e.g., the last second. Do calculate that, you need to read this file twice, 1 second apart.Then you can do a diff of the fourth value of the line. For example, if you take a sample and get:

cpu  2330047 0 2365006 1063853632 9035 9463 96114 0

Then one second later you get this sample:

cpu  2330047 0 2365007 1063854028 9035 9463 96114 0

Subtract the two numbers, and you get a diff of 396, which means that your CPU had been idle for 3.96 seconds out of the last 1.00 second. The trick, of course, is that you need to divide by the number of processors. 3.96 / 4 = 0.99, and there is your idle percentage; 99% idle, and 1% busy.

In my code, I have a ring buffer of 360 entries, and I read this file every second. That lets me quickly calculate the CPU utilization for 1 second, 10 seconds, etc., all the way up to 1 hour.

For the process-specific information, you have to look in /proc/pid; if you don't care abut your pid, you can look in /proc/self.

CPU used by your process is available in /proc/self/stat. This is an odd-looking file consisting of a single line; for example:

19340 (whatever) S 19115 19115 3084 34816 19115 4202752 118200 607 0 0 770 384 2
 7 20 0 77 0 266764385 692477952 105074 4294967295 134512640 146462952 321468364
8 3214683328 4294960144 0 2147221247 268439552 1276 4294967295 0 0 17 0 0 0 0

The important data here are the 13th and 14th tokens (0 and 770 here). The 13th token is the number of jiffies that the process has executed in user mode, and the 14th is the number of jiffies that the process has executed in kernel mode. Add the two together, and you have its total CPU utilization.

Again, you will have to sample this file periodically, and calculate the diff, in order to determine the process's CPU usage over time.

Edit: remember that when you calculate your process's CPU utilization, you have to take into account 1) the number of threads in your process, and 2) the number of processors in the system. For example, if your single-threaded process is using only 25% of the CPU, that could be good or bad. Good on a single-processor system, but bad on a 4-processor system; this means that your process is running constantly, and using 100% of the CPU cycles available to it.

For the process-specific memory information, you ahve to look at /proc/self/status, which looks like this:

Name:   whatever
State:  S (sleeping)
Tgid:   19340
Pid:    19340
PPid:   19115
TracerPid:      0
Uid:    0       0       0       0
Gid:    0       0       0       0
FDSize: 256
Groups: 0 1 2 3 4 6 10 11 20 26 27
VmPeak:   676252 kB
VmSize:   651352 kB
VmLck:         0 kB
VmHWM:    420300 kB
VmRSS:    420296 kB
VmData:   581028 kB
VmStk:       112 kB
VmExe:     11672 kB
VmLib:     76608 kB
VmPTE:      1244 kB
Threads:        77
SigQ:   0/36864
SigPnd: 0000000000000000
ShdPnd: 0000000000000000
SigBlk: fffffffe7ffbfeff
SigIgn: 0000000010001000
SigCgt: 20000001800004fc
CapInh: 0000000000000000
CapPrm: 00000000ffffffff
CapEff: 00000000fffffeff
Cpus_allowed:   0f
Mems_allowed:   1
voluntary_ctxt_switches:        6518
nonvoluntary_ctxt_switches:     6598

The entries that start with 'Vm' are the interesting ones:

  • VmPeak is the maximum virtual memory space used by the process, in kB (1024 bytes).
  • VmSize is the current virtual memory space used by the process, in kB. In my example, it's pretty large: 651,352 kB, or about 636 megabytes.
  • VmRss is the amount of memory that have been mapped into the process' address space, or its resident set size. This is substantially smaller (420,296 kB, or about 410 megabytes). The difference: my program has mapped 636 MB via mmap(), but has only accessed 410 MB of it, and thus only 410 MB of pages have been assigned to it.

The only item I'm not sure about is Swapspace currently used by my process. I don't know if this is available.

What is the difference between smoke testing and sanity testing?

THERE IS NO DIFFERENCE BETWEEN smoke and sanity as per ISTQB.

sanity is synonym of smoke.

Check it here : https://glossary.istqb.org/en/search/sanity

Adding a stylesheet to asp.net (using Visual Studio 2010)

Several things here.

First off, you're defining your CSS in 3 places!

In line, in the head and externally. I suggest you only choose one. I'm going to suggest externally.

I suggest you update your code in your ASP form from

<td style="background-color: #A3A3A3; color: #FFFFFF; font-family: 'Arial Black'; font-size: large; font-weight: bold;" 
        class="style6">

to this:

<td  class="style6">

And then update your css too

.style6
    {
        height: 79px; background-color: #A3A3A3; color: #FFFFFF; font-family: 'Arial Black'; font-size: large; font-weight: bold;
    }

This removes the inline.

Now, to move it from the head of the webForm.

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>AR Toolbox</title>
    <link rel="Stylesheet" href="css/master.css" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<table class="style1">
    <tr>
        <td class="style6">
            <asp:Menu ID="Menu1" runat="server">
                <Items>
                    <asp:MenuItem Text="Home" Value="Home"></asp:MenuItem>
                    <asp:MenuItem Text="About" Value="About"></asp:MenuItem>
                    <asp:MenuItem Text="Compliance" Value="Compliance">
                        <asp:MenuItem Text="Item 1" Value="Item 1"></asp:MenuItem>
                        <asp:MenuItem Text="Item 2" Value="Item 2"></asp:MenuItem>
                    </asp:MenuItem>
                    <asp:MenuItem Text="Tools" Value="Tools"></asp:MenuItem>
                    <asp:MenuItem Text="Contact" Value="Contact"></asp:MenuItem>
                </Items>
            </asp:Menu>
        </td>
    </tr>
    <tr>
        <td class="style6">
            <img alt="South University'" class="style7" 
                src="file:///C:/Users/jnewnam/Documents/Visual%20Studio%202010/WebSites/WebSite1/img/suo_n_seal_hor_pantone.png" /></td>
    </tr>
    <tr>
        <td class="style2">
            <table class="style3">
                <tr>
                    <td>
                        &nbsp;</td>
                </tr>
            </table>
        </td>
    </tr>
    <tr>
        <td style="color: #FFFFFF; background-color: #A3A3A3">
            This is the footer.</td>
    </tr>
</table>
</form>
</body>
</html>

Now, in a new file called master.css (in your css folder) add

ul {
list-style-type:none;
margin:0;
padding:0;
}

li {
display:inline;
padding:20px;
}
.style1
{
    width: 100%;
}
.style2
{
    height: 459px;
}
.style3
{
    width: 100%;
    height: 100%;
}
.style6
{
    height: 79px; background-color: #A3A3A3; color: #FFFFFF; font-family: 'Arial Black'; font-size: large; font-weight: bold;
}
.style7
{
    width: 345px;
    height: 73px;
}

How to get the query string by javascript?

If you're referring to the URL in the address bar, then

window.location.search

will give you just the query string part. Note that this includes the question mark at the beginning.

If you're referring to any random URL stored in (e.g.) a string, you can get at the query string by taking a substring beginning at the index of the first question mark by doing something like:

url.substring(url.indexOf("?"))

That assumes that any question marks in the fragment part of the URL have been properly encoded. If there's a target at the end (i.e., a # followed by the id of a DOM element) it'll include that too.

Instagram how to get my user id from username?

Working solution ~2018

I've found that, providing you have an access token, you can perform the following request in your browser:

https://api.instagram.com/v1/users/self?access_token=[VALUE]

In fact, access token contain the User ID (the first segment of the token):

<user-id>.1677aaa.aaa042540a2345d29d11110545e2499

You can get an access token by using this tool provided by Pixel Union.

How to print variables in Perl

You should always include all relevant code when asking a question. In this case, the print statement that is the center of your question. The print statement is probably the most crucial piece of information. The second most crucial piece of information is the error, which you also did not include. Next time, include both of those.

print $ids should be a fairly hard statement to mess up, but it is possible. Possible reasons:

  1. $ids is undefined. Gives the warning undefined value in print
  2. $ids is out of scope. With use strict, gives fatal warning Global variable $ids needs explicit package name, and otherwise the undefined warning from above.
  3. You forgot a semi-colon at the end of the line.
  4. You tried to do print $ids $nIds, in which case perl thinks that $ids is supposed to be a filehandle, and you get an error such as print to unopened filehandle.

Explanations

1: Should not happen. It might happen if you do something like this (assuming you are not using strict):

my $var;
while (<>) {
    $Var .= $_;
}
print $var;

Gives the warning for undefined value, because $Var and $var are two different variables.

2: Might happen, if you do something like this:

if ($something) {
    my $var = "something happened!";
}
print $var;

my declares the variable inside the current block. Outside the block, it is out of scope.

3: Simple enough, common mistake, easily fixed. Easier to spot with use warnings.

4: Also a common mistake. There are a number of ways to correctly print two variables in the same print statement:

print "$var1 $var2";  # concatenation inside a double quoted string
print $var1 . $var2;  # concatenation
print $var1, $var2;   # supplying print with a list of args

Lastly, some perl magic tips for you:

use strict;
use warnings;

# open with explicit direction '<', check the return value
# to make sure open succeeded. Using a lexical filehandle.
open my $fh, '<', 'file.txt' or die $!;

# read the whole file into an array and
# chomp all the lines at once
chomp(my @file = <$fh>);
close $fh;

my $ids  = join(' ', @file);
my $nIds = scalar @file;
print "Number of lines: $nIds\n";
print "Text:\n$ids\n";

Reading the whole file into an array is suitable for small files only, otherwise it uses a lot of memory. Usually, line-by-line is preferred.

Variations:

  • print "@file" is equivalent to $ids = join(' ',@file); print $ids;
  • $#file will return the last index in @file. Since arrays usually start at 0, $#file + 1 is equivalent to scalar @file.

You can also do:

my $ids;
do {
    local $/;
    $ids = <$fh>;
}

By temporarily "turning off" $/, the input record separator, i.e. newline, you will make <$fh> return the entire file. What <$fh> really does is read until it finds $/, then return that string. Note that this will preserve the newlines in $ids.

Line-by-line solution:

open my $fh, '<', 'file.txt' or die $!; # btw, $! contains the most recent error
my $ids;
while (<$fh>) {
    chomp;
    $ids .= "$_ "; # concatenate with string
}
my $nIds = $.; # $. is Current line number for the last filehandle accessed.

How to find and replace string?

// replaced text will be in buffer.
void Replace(char* buffer, const char* source, const char* oldStr,  const char* newStr)
{
    if(buffer==NULL || source == NULL || oldStr == NULL || newStr == NULL) return; 

    int slen = strlen(source);
    int olen = strlen(oldStr);
    int nlen = strlen(newStr);

    if(olen>slen) return;
    int ix=0;

    for(int i=0;i<slen;i++)
    {
        if(oldStr[0] == source[i])
        {
            bool found = true;
            for(int j=1;j<olen;j++)
            {
                if(source[i+j]!=oldStr[j])
                {
                    found = false;
                    break;
                }
            }

            if(found)
            {
                for(int j=0;j<nlen;j++)
                    buffer[ix++] = newStr[j];

                i+=(olen-1);
            }
            else
            {
                buffer[ix++] = source[i];
            }
        }
        else
        {
            buffer[ix++] = source[i];
        }
    }
}

How do I run a Python script from C#?

Execute Python script from C

Create a C# project and write the following code.

using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            run_cmd();
        }

        private void run_cmd()
        {

            string fileName = @"C:\sample_script.py";

            Process p = new Process();
            p.StartInfo = new ProcessStartInfo(@"C:\Python27\python.exe", fileName)
            {
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };
            p.Start();

            string output = p.StandardOutput.ReadToEnd();
            p.WaitForExit();

            Console.WriteLine(output);

            Console.ReadLine();

        }
    }
}

Python sample_script

print "Python C# Test"

You will see the 'Python C# Test' in the console of C#.

Can I add color to bootstrap icons only using CSS?

Another possible way to have bootstrap icons in a different color is to create a new .png in the desired color, (eg. magenta) and save it as /path-to-bootstrap-css/img/glyphicons-halflings-magenta.png

In your variables.less find

// Sprite icons path
// -------------------------
@iconSpritePath:          "../img/glyphicons-halflings.png";
@iconWhiteSpritePath:     "../img/glyphicons-halflings-white.png";

and add this line

@iconMagentaSpritePath:     "../img/glyphicons-halflings-magenta.png";

In your sprites.less add

/* Magenta icons with optional class, or on hover/active states of certain elements */
.icon-magenta,
.nav-pills > .active > a > [class^="icon-"],
.nav-pills > .active > a > [class*=" icon-"],
.nav-list > .active > a > [class^="icon-"],
.nav-list > .active > a > [class*=" icon-"],
.navbar-inverse .nav > .active > a > [class^="icon-"],
.navbar-inverse .nav > .active > a > [class*=" icon-"],
.dropdown-menu > li > a:hover > [class^="icon-"],
.dropdown-menu > li > a:hover > [class*=" icon-"],
.dropdown-menu > .active > a > [class^="icon-"],
.dropdown-menu > .active > a > [class*=" icon-"],
.dropdown-submenu:hover > a > [class^="icon-"],
.dropdown-submenu:hover > a > [class*=" icon-"] {
  background-image: url("@{iconMagentaSpritePath}");
}

And use it like this:

<i class='icon-chevron-down icon-magenta'></i>

Hope it helps someone.

php implode (101) with quotes

If you want to avoid the fopen/fputcsv sub-systems here's a snippet that builds an escaped CSV string from an associative array....

$output = '';
foreach ($list as $row) {
  $output .= '"' . implode('", "', array_values($row)) . '"' . "\r\n";
}

Or from a list of objects...

foreach ($list as $obj) {
  $output .= '"' . implode('", "', array_values((array) $obj)) . '"' . "\r\n";
}

Then you can output the string as desired.

Call JavaScript function from C#

This may be helpful to you:

<script type="text/javascript">
    function Showalert() {
        alert('Profile not parsed!!');
        window.parent.parent.parent.location.reload();
    }
    function ImportingDone() {
        alert('Importing done successfull.!');
        window.parent.parent.parent.location.reload();
    }
</script>

if (SelectedRowCount == 0)
{
    ScriptManager.RegisterStartupScript(this, GetType(), "displayalertmessage", "Showalert();", true);
}
else
{
    ScriptManager.RegisterStartupScript(this, GetType(), "importingdone", "ImportingDone();", true);
}

T-test in Pandas

EDIT: I had not realized this was about the data format. You could use

import pandas as pd
import scipy
two_data = pd.DataFrame(data, index=data['Category'])

Then accessing the categories is as simple as

scipy.stats.ttest_ind(two_data.loc['cat'], two_data.loc['cat2'], equal_var=False)

The loc operator accesses rows by label.


As @G Garcia said

one sided or two sided dependent or independent

If you have two independent samples but you do not know that they have equal variance, you can use Welch's t-test. It is as simple as

scipy.stats.ttest_ind(cat1['values'], cat2['values'], equal_var=False)

For reasons to prefer Welch's test, see https://stats.stackexchange.com/questions/305/when-conducting-a-t-test-why-would-one-prefer-to-assume-or-test-for-equal-vari.

For two dependent samples, you can use

scipy.stats.ttest_rel(cat1['values'], cat2['values'])

How do I add a newline to a windows-forms TextBox?

Took this from JeffK and made it a little more compact.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    Dim Newline As String = System.Environment.NewLine

    TextBox1.Text = "This is a test"
    TextBox1.Text += Newline + "This is another test"

End Sub

JSON.NET Error Self referencing loop detected for type

To serialize usin NEWTONSOFTJSON when you have loop issue, in my case I did not need modify global.asax or either apiconfig. I just use JsonSerializesSettings ignoring Looping handling.

JsonSerializerSettings jss = new JsonSerializerSettings();
jss.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
var lst = db.shCards.Where(m => m.CardID == id).ToList();
string json = JsonConvert.SerializeObject(lst, jss);

how to realize countifs function (excel) in R

Table is the obvious choice, but it returns an object of class table which takes a few annoying steps to transform back into a data.frame So, if you're OK using dplyr, you use the command tally:

    library(dplyr)
    df = data.frame(sex=sample(c("M", "F"), 100000, replace=T), occupation=sample(c('Analyst', 'Student'), 100000, replace=T)
    df %>% group_by_all() %>% tally()


# A tibble: 4 x 3
# Groups:   sex [2]
  sex   occupation `n()`
  <fct> <fct>      <int>
1 F     Analyst    25105
2 F     Student    24933
3 M     Analyst    24769
4 M     Student    25193

how much memory can be accessed by a 32 bit machine?

Going back to a really basic idea, we have 32 bits for our memory addresses. That works out to 2^32 unique combinations of addresses. By convention, each address points to 1 byte of data. Therefore, we can access up to a total 2^32 bytes of data.

In a 32 bit OS, each register stores 32 bits or 4 bytes. 32 bits (1 word) of information are processed per clock cycle. If you want to access a particular 1 byte, conceptually, we can "extract" the individual bytes (e.g. byte 0, byte 1, byte 2, byte 3 etc.) by doing bitwise logical operations.

E.g. to get "dddddddd", take "aaaaaaaabbbbbbbbccccccccdddddddd" and logical AND with "00000000000000000000000011111111".

How to set button click effect in Android?

Step: set a button in XML with onClick Action:

 <Button
android:id="@+id/btnEditUserInfo"
style="?android:borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="@dimen/txt_height"
android:layout_gravity="center"
android:background="@drawable/round_btn"
android:contentDescription="@string/image_view"
android:onClick="edit_user_info"
android:text="Edit"
android:textColor="#000"
android:textSize="@dimen/login_textSize" />

Step: on button clicked show animation point
//pgrm mark ---- ---- ----- ---- ---- ----- ---- ---- -----  ---- ---- -----

    public void edit_user_info(View view) {

        // show click effect on button pressed
        final AlphaAnimation buttonClick = new AlphaAnimation(1F, 0.8F);
        view.startAnimation(buttonClick);

        Intent intent = new Intent(getApplicationContext(),  EditUserInfo.class);
        startActivity(intent);

    }// end edit_user_info

java.lang.IllegalArgumentException: contains a path separator

openFileInput() doesn't accept paths, only a file name if you want to access a path, use File file = new File(path) and corresponding FileInputStream

Get day of week using NSDate

What you are looking for (if I understand the question correctly) is NSCalendarUnit.CalendarUnitWeekday. The corresponding property of NSDateComponents is weekday.

Note also that your date format is wrong (the full specification can be found here: http://unicode.org/reports/tr35/tr35-6.html).

The function can be simplified slightly, using automatic type inference, also you use variables a lot where constants are sufficient. In addition, the function should return an optional which is nil for an invalid input string.

Updated code for Swift 3 and later:

func getDayOfWeek(_ today:String) -> Int? {
    let formatter  = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd"
    guard let todayDate = formatter.date(from: today) else { return nil }
    let myCalendar = Calendar(identifier: .gregorian)
    let weekDay = myCalendar.component(.weekday, from: todayDate)
    return weekDay
}

Example:

if let weekday = getDayOfWeek("2014-08-27") {
    print(weekday)
} else {
    print("bad input")
}

Original answer for Swift 2:

func getDayOfWeek(today:String)->Int? {

    let formatter  = NSDateFormatter()
    formatter.dateFormat = "yyyy-MM-dd"
    if let todayDate = formatter.dateFromString(today) {
        let myCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
        let myComponents = myCalendar.components(.Weekday, fromDate: todayDate)
        let weekDay = myComponents.weekday
        return weekDay
    } else {
        return nil
    }
}

How to leave a message for a github.com user

Github said on April 3rd 2012 :

Today we're removing two features. They've been gathering dust for a while and it's time to throw them out : Fork Queue & Private Messaging

Source

J2ME/Android/BlackBerry - driving directions, route between two locations

J2ME Map Route Provider

maps.google.com has a navigation service which can provide you route information in KML format.

To get kml file we need to form url with start and destination locations:

public static String getUrl(double fromLat, double fromLon,
                            double toLat, double toLon) {// connect to map web service
    StringBuffer urlString = new StringBuffer();
    urlString.append("http://maps.google.com/maps?f=d&hl=en");
    urlString.append("&saddr=");// from
    urlString.append(Double.toString(fromLat));
    urlString.append(",");
    urlString.append(Double.toString(fromLon));
    urlString.append("&daddr=");// to
    urlString.append(Double.toString(toLat));
    urlString.append(",");
    urlString.append(Double.toString(toLon));
    urlString.append("&ie=UTF8&0&om=0&output=kml");
    return urlString.toString();
}

Next you will need to parse xml (implemented with SAXParser) and fill data structures:

public class Point {
    String mName;
    String mDescription;
    String mIconUrl;
    double mLatitude;
    double mLongitude;
}

public class Road {
    public String mName;
    public String mDescription;
    public int mColor;
    public int mWidth;
    public double[][] mRoute = new double[][] {};
    public Point[] mPoints = new Point[] {};
}

Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:

 public static String getUrl(double fromLat, double fromLon,
     double toLat, double toLon)

then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:

 public static Road getRoute(InputStream is) 

Full source code RoadProvider.java

BlackBerry

class MapPathScreen extends MainScreen {
    MapControl map;
    Road mRoad = new Road();
    public MapPathScreen() {
        double fromLat = 49.85, fromLon = 24.016667;
        double toLat = 50.45, toLon = 30.523333;
        String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
        InputStream is = getConnection(url);
        mRoad = RoadProvider.getRoute(is);
        map = new MapControl();
        add(new LabelField(mRoad.mName));
        add(new LabelField(mRoad.mDescription));
        add(map);
    }
    protected void onUiEngineAttached(boolean attached) {
        super.onUiEngineAttached(attached);
        if (attached) {
            map.drawPath(mRoad);
        }
    }
    private InputStream getConnection(String url) {
        HttpConnection urlConnection = null;
        InputStream is = null;
        try {
            urlConnection = (HttpConnection) Connector.open(url);
            urlConnection.setRequestMethod("GET");
            is = urlConnection.openInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
}

See full code on J2MEMapRouteBlackBerryEx on Google Code

Android

Android G1 screenshot

public class MapRouteActivity extends MapActivity {
    LinearLayout linearLayout;
    MapView mapView;
    private Road mRoad;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        new Thread() {
            @Override
            public void run() {
                double fromLat = 49.85, fromLon = 24.016667;
                double toLat = 50.45, toLon = 30.523333;
                String url = RoadProvider
                        .getUrl(fromLat, fromLon, toLat, toLon);
                InputStream is = getConnection(url);
                mRoad = RoadProvider.getRoute(is);
                mHandler.sendEmptyMessage(0);
            }
        }.start();
    }

    Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            TextView textView = (TextView) findViewById(R.id.description);
            textView.setText(mRoad.mName + " " + mRoad.mDescription);
            MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
            List<Overlay> listOfOverlays = mapView.getOverlays();
            listOfOverlays.clear();
            listOfOverlays.add(mapOverlay);
            mapView.invalidate();
        };
    };

    private InputStream getConnection(String url) {
        InputStream is = null;
        try {
            URLConnection conn = new URL(url).openConnection();
            is = conn.getInputStream();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
}

See full code on J2MEMapRouteAndroidEx on Google Code

Java java.sql.SQLException: Invalid column index on preparing statement

Everywhere inside the query string, the wildcard should be ? instead of '?'. That should solve the problem.

EDIT :

To add to that, you need to change date '?' to to_date(?, 'yyyy-mm-dd'). Please try that and let me know.

How to align the checkbox and label in same line in html?

Another approach here:

.checkbox-wrapper {
  white-space: nowrap
}
.checkbox {
  vertical-align: top;
  display:inline-block
}
.checkbox-label {
  white-space: normal
  display:inline-block
}

<div class="text-left checkbox-wrapper">
  <input type="checkbox" id="terms" class="checkbox">
  <label class="checkbox-label" for="terms">I accept whatever you want!</label>
</div>

How to run an application as "run as administrator" from the command prompt?

It looks like psexec -h is the way to do this:

 -h         If the target system is Windows Vista or higher, has the process
            run with the account's elevated token, if available.

Which... doesn't seem to be listed in the online documentation in Sysinternals - PsExec.

But it works on my machine.

How to display custom view in ActionBar?

There is a trick for this. All you have to do is to use RelativeLayout instead of LinearLayout as the main container. It's important to have android:layout_gravity="fill_horizontal" set for it. That should do it.

Comparing the contents of two files in Sublime Text

The Diff Option only appears if the files are in a folder that is part of a Project.

Than you can actually compare files natively right in Sublime Text.

Navigate to the folder containing them through Open Folder... or in a project Select the two files (ie, by holding Ctrl on Windows or ? on macOS) you want to compare in the sidebar Right click and select the Diff files... option.

Laravel 5 – Remove Public from URL

Firstly you can use this steps

For Laravel 5:

1. Rename server.php in your Laravel root folder to index.php

2. Copy the .htaccess file from /public directory to your Laravel root folder.

source: https://stackoverflow.com/a/28735930

after you follow these steps then you need to change all css and script path, but this will be tiring.

Solution Proposal :simply you can make minor change the helpers::asset function.

For this:

  1. open vendor\laravel\framework\src\Illuminate\Foundation\helpers.php

  2. goto line 130

  3. write "public/".$path instead of $path,

    function asset($path, $secure = null){
       return app('url')->asset("public/".$path, $secure);
    }
    

Can not find the tag library descriptor of springframework

add external jar of jstl-standard.jar as the external jar by right click on JRE system libraries under configure build path -> build path. it worked for me!!

Reference - What does this regex mean?

The Stack Overflow Regular Expressions FAQ

See also a lot of general hints and useful links at the tag details page.


Online tutorials

Quantifiers

Character Classes

Escape Sequences

Anchors

(Also see "Flavor-Specific Information ? Java ? The functions in Matcher")

Groups

Lookarounds

Modifiers

Other:

Common Tasks

Advanced Regex-Fu

Flavor-Specific Information

(Except for those marked with *, this section contains non-Stack Overflow links.)

General information

(Links marked with * are non-Stack Overflow links.)

Examples of regex that can cause regex engine to fail

Tools: Testers and Explainers

(This section contains non-Stack Overflow links.)

Error :The remote server returned an error: (401) Unauthorized

I add credentials for HttpWebRequest.

myReq.UseDefaultCredentials = true;
myReq.PreAuthenticate = true;
myReq.Credentials = CredentialCache.DefaultCredentials;

How to "log in" to a website using Python's Requests module?

The requests.Session() solution assisted with logging into a form with CSRF Protection (as used in Flask-WTF forms). Check if a csrf_token is required as a hidden field and add it to the payload with the username and password:

import requests
from bs4 import BeautifulSoup

payload = {
    'email': '[email protected]',
    'password': 'passw0rd'
}     

with requests.Session() as sess:
    res = sess.get(server_name + '/signin')
    signin = BeautifulSoup(res._content, 'html.parser')
    payload['csrf_token'] = signin.find('input', id='csrf_token')['value']
    res = sess.post(server_name + '/auth/login', data=payload)

MySQL Error 1093 - Can't specify target table for update in FROM clause

You could insert the desired rows' ids into a temp table and then delete all the rows that are found in that table.

which may be what @Cheekysoft meant by doing it in two steps.

How to check if iframe is loaded or it has a content?

I had the same issue and added to this, i needed to check if iframe is loaded irrespective of cross-domain policy. I was developing a chrome extension which injects certain script on a webpage and displays some content from the parent page in an iframe. I tried following approach and this worked perfect for me.
P.S.: In my case, i do have control over content in iframe but not on the parent site. (Iframe is hosted on my own server)

First:
Create an iframe with a data- attribute in it like (this part was in injected script in my case)
<iframe id="myiframe" src="http://anyurl.com" data-isloaded="0"></iframe>

Now in the iframe code, use :

var sourceURL = document.referrer;
window.parent.postMessage('1',sourceURL);



Now back to the injected script as per my case:

setTimeout(function(){
  var myIframe = document.getElementById('myiframe');
  var isLoaded = myIframe.prop('data-isloaded');
  if(isLoaded != '1')
  {
    console.log('iframe failed to load');
  } else {
    console.log('iframe loaded');
  }
},3000);


and,

window.addEventListener("message", receiveMessage, false);
function receiveMessage(event)
{
    if(event.origin !== 'https://someWebsite.com') //check origin of message for security reasons
    {
        console.log('URL issues');
        return;
    }
    else {
        var myMsg = event.data;
        if(myMsg == '1'){
            //8-12-18 changed from 'data-isload' to 'data-isloaded
            $("#myiframe").prop('data-isloaded', '1');
        }
    }           
}



It may not exactly answer the question but it indeed is a possible case of this question which i solved by this method.

overlay a smaller image on a larger image python OpenCv

Here it is:

def put4ChannelImageOn4ChannelImage(back, fore, x, y):
    rows, cols, channels = fore.shape    
    trans_indices = fore[...,3] != 0 # Where not transparent
    overlay_copy = back[y:y+rows, x:x+cols] 
    overlay_copy[trans_indices] = fore[trans_indices]
    back[y:y+rows, x:x+cols] = overlay_copy

#test
background = np.zeros((1000, 1000, 4), np.uint8)
background[:] = (127, 127, 127, 1)
overlay = cv2.imread('imagee.png', cv2.IMREAD_UNCHANGED)
put4ChannelImageOn4ChannelImage(background, overlay, 5, 5)

Split string into string array of single characters

Simple!!
one line:

 var res = test.Select(x => new string(x, 1)).ToArray();

How to find my realm file?

To get the DB path for iOS, the simplest way is to:

  1. Launch your app in a simulator
  2. Pause it at any time in the debugger
  3. Go to the console (where you have (lldb)) and type: po RLMRealm.defaultRealmPath

Tada...you have the path to your realm database

Rename all files in a folder with a prefix in a single command

I think this is just what you'er looking for:

ls | xargs -I {} mv {} Unix_{}

Yes, it is simple yet elegant and powerful, and also one-liner. You can get more detailed intro from me on the page:Rename Files and Directories (Add Prefix)

Is there a math nCr function in python?

Do you want iteration? itertools.combinations. Common usage:

>>> import itertools
>>> itertools.combinations('abcd',2)
<itertools.combinations object at 0x01348F30>
>>> list(itertools.combinations('abcd',2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
>>> [''.join(x) for x in itertools.combinations('abcd',2)]
['ab', 'ac', 'ad', 'bc', 'bd', 'cd']

If you just need to compute the formula, use math.factorial:

import math

def nCr(n,r):
    f = math.factorial
    return f(n) / f(r) / f(n-r)

if __name__ == '__main__':
    print nCr(4,2)

In Python 3, use the integer division // instead of / to avoid overflows:

return f(n) // f(r) // f(n-r)

Output

6

Is there a way to make numbers in an ordered list bold?

If you are using Bootstrap 4:

<ol class="font-weight-bold">
    <li><span class="font-weight-light">Curabitur aliquet quam id dui posuere blandit.</span></li>
    <li><span class="font-weight-light">Curabitur aliquet quam id dui posuere blandit.</span></li>
</ol>

Is there an equivalent of lsusb for OS X

system_profiler SPUSBDataType

it your need command on macos

How to include a font .ttf using CSS?

Only providing .ttf file for webfont won't be good enough for cross-browser support. The best possible combination at present is using the combination as :

@font-face {
  font-family: 'MyWebFont';
  src: url('webfont.eot'); /* IE9 Compat Modes */
  src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
       url('webfont.woff') format('woff'), /* Modern Browsers */
       url('webfont.ttf')  format('truetype'), /* Safari, Android, iOS */
       url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */
}

This code assumes you have .eot , .woff , .ttf and svg format for you webfont. To automate all this process , you can use : Transfonter.org.

Also , modern browsers are shifting towards .woff font , so you can probably do this too : :

@font-face {
  font-family: 'MyWebFont';
  src: url('myfont.woff') format('woff'), /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
   url('myfont.ttf') format('truetype'); /* Chrome 4+, Firefox 3.5, Opera 10+, Safari 3—5 */
}  

Read more here : http://css-tricks.com/snippets/css/using-font-face/


Look for browser support : Can I Use fontface

View list of all JavaScript variables in Google Chrome Console

To view any variable in chrome, go to "Sources", and then "Watch" and add it. If you add the "window" variable here then you can expand it and explore.

Most useful NLog configurations

Configure NLog via XML, but Programmatically

What? Did you know that you can specify the NLog XML directly to NLog from your app, as opposed to having NLog read it from the config file? Well, you can. Let's say that you have a distributed app and you want to use the same configuration everywhere. You could keep a config file in each location and maintain it separately, you could maintain one in a central location and push it out to the satellite locations, or you could probably do a lot of other things. Or, you could store your XML in a database, get it at app startup, and configure NLog directly with that XML (maybe checking back periodically to see if it had changed).

  string xml = @"<nlog>
                   <targets>
                     <target name='console' type='Console' layout='${message}' />
                   </targets>

                   <rules>
                     <logger name='*' minlevel='Error' writeTo='console' />
                   </rules>
                 </nlog>";

  StringReader sr = new StringReader(xml);
  XmlReader xr = XmlReader.Create(sr);
  XmlLoggingConfiguration config = new XmlLoggingConfiguration(xr, null);
  LogManager.Configuration = config;
  //NLog is now configured just as if the XML above had been in NLog.config or app.config

  logger.Trace("Hello - Trace"); //Won't log
  logger.Debug("Hello - Debug"); //Won't log
  logger.Info("Hello - Info");   //Won't log
  logger.Warn("Hello - Warn");   //Won't log
  logger.Error("Hello - Error"); //Will log
  logger.Fatal("Hello - Fatal"); //Will log

  //Now let's change the config (the root logging level) ...
  string xml2 = @"<nlog>
                  <targets>
                     <target name='console' type='Console' layout='${message}' />
                   </targets>

                   <rules>
                     <logger name='*' minlevel='Trace' writeTo='console' />
                   </rules>
                 </nlog>";

  StringReader sr2 = new StringReader(xml2);
  XmlReader xr2 = XmlReader.Create(sr2);
  XmlLoggingConfiguration config2 = new XmlLoggingConfiguration(xr2, null);
  LogManager.Configuration = config2;

  logger.Trace("Hello - Trace"); //Will log
  logger.Debug("Hello - Debug"); //Will log
  logger.Info("Hello - Info");   //Will log
  logger.Warn("Hello - Warn");   //Will log
  logger.Error("Hello - Error"); //Will log
  logger.Fatal("Hello - Fatal"); //Will log

I'm not sure how robust this is, but this example provides a useful starting point for people that might want to try configuring like this.

How to change a nullable column to not nullable in a Rails migration?

Rails 4 (other Rails 4 answers have problems):

def change
  change_column_null(:users, :admin, false, <put a default value here> )
  # change_column(:users, :admin, :string, :default => "")
end

Changing a column with NULL values in it to not allow NULL will cause problems. This is exactly the type of code that will work fine in your development setup and then crash when you try to deploy it to your LIVE production. You should first change NULL values to something valid and then disallow NULLs. The 4th value in change_column_null does exactly that. See documentation for more details.

Also, I generally prefer to set a default value for the field so I won't need to specify the field's value every time I create a new object. I included the commented out code to do that as well.

Proper way to restrict text input values (e.g. only numbers)

The inputmask plugin does the best job of this. Its extremely flexible in that you can supply whatever regex you like to restrict input. It also does not require JQuery.

Step 1: Install the plugin:

npm install --save inputmask

Step2: create a directive to wrap the input mask:

import {Directive, ElementRef, Input} from '@angular/core';
import * as Inputmask from 'inputmask';


@Directive({
  selector: '[app-restrict-input]',
})
export class RestrictInputDirective {

  // map of some of the regex strings I'm using (TODO: add your own)
  private regexMap = {
    integer: '^[0-9]*$',
    float: '^[+-]?([0-9]*[.])?[0-9]+$',
    words: '([A-z]*\\s)*',
    point25: '^\-?[0-9]*(?:\\.25|\\.50|\\.75|)$'
  };

  constructor(private el: ElementRef) {}

  @Input('app-restrict-input')
  public set defineInputType(type: string) {
    Inputmask({regex: this.regexMap[type], placeholder: ''})
      .mask(this.el.nativeElement);
  }

}

Step 3:

<input type="text" app-restrict-input="integer">

Check out their github docs for more information.

Print new output on same line

>>> for i in range(1, 11):
...     print(i, end=' ')
...     if i==len(range(1, 11)): print()
... 
1 2 3 4 5 6 7 8 9 10 
>>> 

This is how to do it so that the printing does not run behind the prompt on the next line.

Read properties file outside JAR file

So, you want to treat your .properties file on the same folder as the main/runnable jar as a file rather than as a resource of the main/runnable jar. In that case, my own solution is as follows:

First thing first: your program file architecture shall be like this (assuming your main program is main.jar and its main properties file is main.properties):

./ - the root of your program
 |__ main.jar
 |__ main.properties

With this architecture, you can modify any property in the main.properties file using any text editor before or while your main.jar is running (depending on the current state of the program) since it is just a text-based file. For example, your main.properties file may contain:

app.version=1.0.0.0
app.name=Hello

So, when you run your main program from its root/base folder, normally you will run it like this:

java -jar ./main.jar

or, straight away:

java -jar main.jar

In your main.jar, you need to create a few utility methods for every property found in your main.properties file; let say the app.version property will have getAppVersion() method as follows:

/**
 * Gets the app.version property value from
 * the ./main.properties file of the base folder
 *
 * @return app.version string
 * @throws IOException
 */

import java.util.Properties;

public static String getAppVersion() throws IOException{

    String versionString = null;

    //to load application's properties, we use this class
    Properties mainProperties = new Properties();

    FileInputStream file;

    //the base folder is ./, the root of the main.properties file  
    String path = "./main.properties";

    //load the file handle for main.properties
    file = new FileInputStream(path);

    //load all the properties from this file
    mainProperties.load(file);

    //we have loaded the properties, so close the file handle
    file.close();

    //retrieve the property we are intrested, the app.version
    versionString = mainProperties.getProperty("app.version");

    return versionString;
}

In any part of the main program that needs the app.version value, we call its method as follows:

String version = null;
try{
     version = getAppVersion();
}
catch (IOException ioe){
    ioe.printStackTrace();
}

How to scroll to bottom in react?

Working Example:

You can use the DOM scrollIntoView method to make a component visible in the view.

For this, while rendering the component just give a reference ID for the DOM element using ref attribute. Then use the method scrollIntoView on componentDidMount life cycle. I am just putting a working sample code for this solution. The following is a component rendering each time a message received. You should write code/methods for rendering this component.

class ChatMessage extends Component {
    scrollToBottom = (ref) => {
        this.refs[ref].scrollIntoView({ behavior: "smooth" });
    }

    componentDidMount() {
        this.scrollToBottom(this.props.message.MessageId);
    }

    render() {
        return(
            <div ref={this.props.message.MessageId}>
                <div>Message content here...</div>
            </div>
        );
    }
}

Here this.props.message.MessageId is the unique ID of the particular chat message passed as props

How to convert a byte array to Stream

Easy, simply wrap a MemoryStream around it:

Stream stream = new MemoryStream(buffer);

How do you round a floating point number in Perl?

Whilst not disagreeing with the complex answers about half-way marks and so on, for the more common (and possibly trivial) use-case:

my $rounded = int($float + 0.5);

UPDATE

If it's possible for your $float to be negative, the following variation will produce the correct result:

my $rounded = int($float + $float/abs($float*2 || 1));

With this calculation -1.4 is rounded to -1, and -1.6 to -2, and zero won't explode.

Pass array to mvc Action via AJAX

Set the traditional property to true before making the get call. i.e.:

jQuery.ajaxSettings.traditional = true

$.get('/controller/MyAction', { vals: arrayOfValues }, function (data) {... 

How does Tomcat find the HOME PAGE of my Web App?

In any web application, there will be a web.xml in the WEB-INF/ folder.

If you dont have one in your web app, as it seems to be the case in your folder structure, the default Tomcat web.xml is under TOMCAT_HOME/conf/web.xml

Either way, the relevant lines of the web.xml are

<welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

so any file matching this pattern when found will be shown as the home page.

In Tomcat, a web.xml setting within your web app will override the default, if present.

Further Reading

How do I override the default home page loaded by Tomcat?

How to install all required PHP extensions for Laravel?

Laravel Server Requirements mention that BCMath, Ctype, JSON, Mbstring, OpenSSL, PDO, Tokenizer, and XML extensions are required. Most of the extensions are installed and enabled by default.

You can run the following command in Ubuntu to make sure the extensions are installed.

sudo apt install openssl php-common php-curl php-json php-mbstring php-mysql php-xml php-zip

PHP version specific installation (if PHP 7.4 installed)

sudo apt install php7.4-common php7.4-bcmath openssl php7.4-json php7.4-mbstring

You may need other PHP extensions for your composer packages. Find from links below.

PHP extensions for Ubuntu 20.04 LTS (Focal Fossa)

PHP extensions for Ubuntu 18.04 LTS (Bionic)

PHP extensions for Ubuntu 16.04 LTS (Xenial)

Laravel 5 error SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES)

I was facing the same issue. Everything was fine but in

bootstrap/cache/config.php

always had the incomplete password. Upon digging further, realized that the password had '#' character in it and that was getting dropped. As '#' is used to mark a line as a comment.

How can I view the source code for a function?

View(function_name) - eg. View(mean) Make sure to use uppercase [V]. The read-only code will open in the editor.

How to check if that data already exist in the database during update (Mongoose And Express)

There is a more simpler way using the mongoose exists function

router.post("/groups/members", async (ctx) => {
    const group_name = ctx.request.body.group_membership.group_name;
    const member_name = ctx.request.body.group_membership.group_members;
    const GroupMembership = GroupModels.GroupsMembers;
    console.log("group_name : ", group_name, "member : ", member_name);
    try {
        if (
            (await GroupMembership.exists({
                "group_membership.group_name": group_name,
            })) === false
        ) {
            console.log("new function");
            const newGroupMembership = await GroupMembership.insertMany({
                group_membership: [
                    { group_name: group_name, group_members: [member_name] },
                ],
            });
            await newGroupMembership.save();
        } else {
            const UpdateGroupMembership = await GroupMembership.updateOne(
                { "group_membership.group_name": group_name },
                { $push: { "group_membership.$.group_members": member_name } },
            );
            console.log("update function");
            await UpdateGroupMembership.save();
        }
        ctx.response.status = 201;
        ctx.response.message = "A member added to group successfully";
    } catch (error) {
        ctx.body = {
            message: "Some validations failed for Group Member Creation",
            error: error.message,
        };
        console.log(error);
        ctx.throw(400, error);
    }
});

git: 'credential-cache' is not a git command

I fixed this issue by removing the credential section from the config of specific project:

  • Just typed: git config -e
  • Inside the editor I removed the whole section [credential] helper = cache.

This removed the annoying message :

git: 'credential-cache' is not a git command. See 'git --help'.

git submodule tracking latest

Edit (2020.12.28): GitHub change default master branch to main branch since October 2020. See https://github.com/github/renaming


Update March 2013

Git 1.8.2 added the possibility to track branches.

"git submodule" started learning a new mode to integrate with the tip of the remote branch (as opposed to integrating with the commit recorded in the superproject's gitlink).

# add submodule to track master branch
git submodule add -b master [URL to Git repo];

# update your submodule
git submodule update --remote 

If you had a submodule already present you now wish would track a branch, see "how to make an existing submodule track a branch".

Also see Vogella's tutorial on submodules for general information on submodules.

Note:

git submodule add -b . [URL to Git repo];
                    ^^^

See git submodule man page:

A special value of . is used to indicate that the name of the branch in the submodule should be the same name as the current branch in the current repository.


See commit b928922727d6691a3bdc28160f93f25712c565f6:

submodule add: If --branch is given, record it in .gitmodules

This allows you to easily record a submodule.<name>.branch option in .gitmodules when you add a new submodule. With this patch,

$ git submodule add -b <branch> <repository> [<path>]
$ git config -f .gitmodules submodule.<path>.branch <branch>

reduces to

$ git submodule add -b <branch> <repository> [<path>]

This means that future calls to

$ git submodule update --remote ...

will get updates from the same branch that you used to initialize the submodule, which is usually what you want.

Signed-off-by: W. Trevor King [email protected]


Original answer (February 2012):

A submodule is a single commit referenced by a parent repo.
Since it is a Git repo on its own, the "history of all commits" is accessible through a git log within that submodule.

So for a parent to track automatically the latest commit of a given branch of a submodule, it would need to:

  • cd in the submodule
  • git fetch/pull to make sure it has the latest commits on the right branch
  • cd back in the parent repo
  • add and commit in order to record the new commit of the submodule.

gitslave (that you already looked at) seems to be the best fit, including for the commit operation.

It is a little annoying to make changes to the submodule due to the requirement to check out onto the correct submodule branch, make the change, commit, and then go into the superproject and commit the commit (or at least record the new location of the submodule).

Other alternatives are detailed here.

Counting DISTINCT over multiple columns

How about something like:

select count(*)
from
  (select count(*) cnt
   from DocumentOutputItems
   group by DocumentId, DocumentSessionId) t1

Probably just does the same as you are already though but it avoids the DISTINCT.

Best way to load module/class from lib folder in Rails 3?

I had the same problem. Here is how I solved it. The solution loads the lib directory and all the subdirectories (not only the direct). Of course you can use this for all directories.

# application.rb
config.autoload_paths += %W(#{config.root}/lib)
config.autoload_paths += Dir["#{config.root}/lib/**/"]

How should I import data from CSV into a Postgres table using pgAdmin 3?

pgAdmin has GUI for data import since 1.16. You have to create your table first and then you can import data easily - just right-click on the table name and click on Import.

enter image description here

enter image description here

Is there a simple way to remove multiple spaces in a string?

I have my simple method which I have used in college.

line = "I     have            a       nice    day."

end = 1000
while end != 0:
    line.replace("  ", " ")
    end -= 1

This will replace every double space with a single space and will do it 1000 times. It means you can have 2000 extra spaces and will still work. :)

How to convert WebResponse.GetResponseStream return into a string?

You can use StreamReader.ReadToEnd(),

using (Stream stream = response.GetResponseStream())
{
   StreamReader reader = new StreamReader(stream, Encoding.UTF8);
   String responseString = reader.ReadToEnd();
}

MySQL Nested Select Query?

You just need to write the first query as a subquery (derived table), inside parentheses, pick an alias for it (t below) and alias the columns as well.

The DISTINCT can also be safely removed as the internal GROUP BY makes it redundant:

SELECT DATE(`date`) AS `date` , COUNT(`player_name`) AS `player_count`
FROM (
    SELECT MIN(`date`) AS `date`, `player_name`
    FROM `player_playtime`
    GROUP BY `player_name`
) AS t
GROUP BY DATE( `date`) DESC LIMIT 60 ;

Since the COUNT is now obvious that is only counting rows of the derived table, you can replace it with COUNT(*) and further simplify the query:

SELECT t.date , COUNT(*) AS player_count
FROM (
    SELECT DATE(MIN(`date`)) AS date
    FROM player_playtime
    GROUP BY player_name
) AS t
GROUP BY t.date DESC LIMIT 60 ;

org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]A child container failed during start

If you are using the following stack: Server Version: Apache Tomcat/9.0.21 Servlet Version: 4.0 JSP Version: 2.3

Then try adding <absolute-ordering /> to your web.xml file. So your file looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>spring-mvc-crud-demo</display-name>

  <absolute-ordering />

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>

  ......

How to test for $null array in PowerShell

How do you want things to behave?

If you want arrays with no elements to be treated the same as unassigned arrays, use:

[array]$foo = @() #example where we'd want TRUE to be returned
@($foo).Count -eq 0

If you want a blank array to be seen as having a value (albeit an empty one), use:

[array]$foo = @() #example where we'd want FALSE to be returned
$foo.PSObject -eq $null

If you want an array which is populated with only null values to be treated as null:

[array]$foo = $null,$null
@($foo | ?{$_.PSObject}).Count -eq 0 

NB: In the above I use $_.PSObject over $_ to avoid [bool]$false, [int]0, [string]'', etc from being filtered out; since here we're focussed solely on nulls.

How to copy text to the client's clipboard using jQuery?

Copying to the clipboard is a tricky task to do in Javascript in terms of browser compatibility. The best way to do it is using a small flash. It will work on every browser. You can check it in this article.

Here's how to do it for Internet Explorer:

function copy (str)
{
    //for IE ONLY!
    window.clipboardData.setData('Text',str);
}

How to properly create an SVN tag from trunk?

Another option to tag a Subversion repository is to add the tag to the svn:log property like this:

   echo "TAG: your_tag_text" > newlog
   svn propget $REPO --revprop -r $tagged_revision >> newlog
   svn propset $REPO --revprop -r $tagged_revision -F newlog
   rm newlog

I recently started thinking that this is the most "right" way to tag. This way you don't create extra revisions (as you do with "svn cp") and still can easily extract all tags by using grep on "svn log" output:

   svn log | awk '/----/ {
                      expect_rev=1;
                      expect_tag=0;
                  }
                  /^r[[:digit:]]+/ {
                      if(expect_rev) {
                          rev=$1;
                          expect_tag=1;
                          expect_rev=0;
                      }
                  }
                  /^TAG:/ {
                      if(expect_tag) {
                          print "Revision "rev", Tag: "$2;
                      }
                      expect_tag=0;
                  }'

Also, this way you may seamlessly delete tags if you need to. So the tags become a complete meta-information, and I like it.

Java ArrayList copy

Another convenient way to copy the values from src ArrayList to dest Arraylist is as follows:

ArrayList<String> src = new ArrayList<String>();
src.add("test string1");
src.add("test string2");
ArrayList<String> dest= new ArrayList<String>();
dest.addAll(src);

This is actual copying of values and not just copying of reference.

Git keeps asking me for my ssh key passphrase

I had a similar issue, but the other answers didn't fix my problem. I thought I'd go ahead and post this just in case someone else has a screwy setup like me.

It turns out I had multiple keys and Git was using the wrong one first. It would prompt me for my passphrase, and I would enter it, then Git would use a different key that would work (that I didn't need to enter the passphrase on).

I just deleted the key that it was using to prompt me for a passphrase and now it works!

How to get the groups of a user in Active Directory? (c#, asp.net)

In my case the only way I could keep using GetGroups() without any expcetion was adding the user (USER_WITH_PERMISSION) to the group which has permission to read the AD (Active Directory). It's extremely essential to construct the PrincipalContext passing this user and password.

var pc = new PrincipalContext(ContextType.Domain, domain, "USER_WITH_PERMISSION", "PASS");
var user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, userName);
var groups = user.GetGroups();

Steps you may follow inside Active Directory to get it working:

  1. Into Active Directory create a group (or take one) and under secutiry tab add "Windows Authorization Access Group"
  2. Click on "Advanced" button
  3. Select "Windows Authorization Access Group" and click on "View"
  4. Check "Read tokenGroupsGlobalAndUniversal"
  5. Locate the desired user and add to the group you created (taken) from the first step

rand() between 0 and 1

My guess is that RAND_MAX is equal to INT_MAX and so you're overflowing it to a negative.

Just do this:

r = ((double) rand() / (RAND_MAX)) + 1;

Or even better, use C++11's random number generators.

Add st, nd, rd and th (ordinal) suffix to a number

Strongly recommend the excellent date-fns library. Fast, modular, immutable, works with standard dates.

import * as DateFns from 'date-fns';

const ordinalInt = DateFns.format(someInt, 'do');

See date-fns docs: https://date-fns.org/v2.0.0-alpha.9/docs/format

Python read in string from file and split it into values

Use open(file, mode) for files. The mode is a variant of 'r' for read, 'w' for write, and possibly 'b' appended (e.g., 'rb') to open binary files. See the link below.

Use open with readline() or readlines(). The former will return a line at a time, while the latter returns a list of the lines.

Use split(delimiter) to split on the comma.

Lastly, you need to cast each item to an integer: int(foo). You'll probably want to surround your cast with a try block followed by except ValueError as in the link below.

You can also use 'multiple assignment' to assign a and b at once:

>>>a, b = map(int, "2342342,2234234".split(","))  
>>>print a  
2342342
>>>type(a)  
<type 'int'>

python io docs

python casting

Can a local variable's memory be accessed outside its scope?

In C++, you can access any address, but it doesn't mean you should. The address you are accessing is no longer valid. It works because nothing else scrambled the memory after foo returned, but it could crash under many circumstances. Try analyzing your program with Valgrind, or even just compiling it optimized, and see...

How to count the NaN values in a column in pandas DataFrame

Based on the most voted answer we can easily define a function that gives us a dataframe to preview the missing values and the % of missing values in each column:

def missing_values_table(df):
    mis_val = df.isnull().sum()
    mis_val_percent = 100 * df.isnull().sum() / len(df)
    mis_val_table = pd.concat([mis_val, mis_val_percent], axis=1)
    mis_val_table_ren_columns = mis_val_table.rename(
    columns = {0 : 'Missing Values', 1 : '% of Total Values'})
    mis_val_table_ren_columns = mis_val_table_ren_columns[
        mis_val_table_ren_columns.iloc[:,1] != 0].sort_values(
    '% of Total Values', ascending=False).round(1)
    print ("Your selected dataframe has " + str(df.shape[1]) + " columns.\n"      
        "There are " + str(mis_val_table_ren_columns.shape[0]) +
            " columns that have missing values.")
    return mis_val_table_ren_columns

How to style HTML5 range input to have different color before and after slider?

Yes, it is possible. Though I wouldn't recommend it because input range is not really supported properly by all browsers because is an new element added in HTML5 and HTML5 is only a draft (and will be for long) so going as far as to styling it is perhaps not the best choice.

Also, you'll need a bit of JavaScript too. I took the liberty of using jQuery library for this, for simplicity purposes.

Here you go: http://jsfiddle.net/JnrvG/1/.

Callback after all asynchronous forEach callbacks are completed

Hope this will fix your problem, i usually work with this when i need to execute forEach with asynchronous tasks inside.

foo = [a,b,c,d];
waiting = foo.length;
foo.forEach(function(entry){
      doAsynchronousFunction(entry,finish) //call finish after each entry
}
function finish(){
      waiting--;
      if (waiting==0) {
          //do your Job intended to be done after forEach is completed
      } 
}

with

function doAsynchronousFunction(entry,callback){
       //asynchronousjob with entry
       callback();
}

String field value length in mongoDB

For MongoDB 3.6 and newer:

The $expr operator allows the use of aggregation expressions within the query language, thus you can leverage the use of $strLenCP operator to check the length of the string as follows:

db.usercollection.find({ 
    "name": { "$exists": true },
    "$expr": { "$gt": [ { "$strLenCP": "$name" }, 40 ] } 
})

For MongoDB 3.4 and newer:

You can also use the aggregation framework with the $redact pipeline operator that allows you to proccess the logical condition with the $cond operator and uses the special operations $$KEEP to "keep" the document where the logical condition is true or $$PRUNE to "remove" the document where the condition was false.

This operation is similar to having a $project pipeline that selects the fields in the collection and creates a new field that holds the result from the logical condition query and then a subsequent $match, except that $redact uses a single pipeline stage which is more efficient.

As for the logical condition, there are String Aggregation Operators that you can use $strLenCP operator to check the length of the string. If the length is $gt a specified value, then this is a true match and the document is "kept". Otherwise it is "pruned" and discarded.


Consider running the following aggregate operation which demonstrates the above concept:

db.usercollection.aggregate([
    { "$match": { "name": { "$exists": true } } },
    {
        "$redact": {
            "$cond": [
                { "$gt": [ { "$strLenCP": "$name" }, 40] },
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    },
    { "$limit": 2 }
])

If using $where, try your query without the enclosing brackets:

db.usercollection.find({$where: "this.name.length > 40"}).limit(2);

A better query would be to to check for the field's existence and then check the length:

db.usercollection.find({name: {$type: 2}, $where: "this.name.length > 40"}).limit(2); 

or:

db.usercollection.find({name: {$exists: true}, $where: "this.name.length > 
40"}).limit(2); 

MongoDB evaluates non-$where query operations before $where expressions and non-$where query statements may use an index. A much better performance is to store the length of the string as another field and then you can index or search on it; applying $where will be much slower compared to that. It's recommended to use JavaScript expressions and the $where operator as a last resort when you can't structure the data in any other way, or when you are dealing with a small subset of data.


A different and faster approach that avoids the use of the $where operator is the $regex operator. Consider the following pattern which searches for

db.usercollection.find({"name": {"$type": 2, "$regex": /^.{41,}$/}}).limit(2); 

Note - From the docs:

If an index exists for the field, then MongoDB matches the regular expression against the values in the index, which can be faster than a collection scan. Further optimization can occur if the regular expression is a “prefix expression”, which means that all potential matches start with the same string. This allows MongoDB to construct a “range” from that prefix and only match against those values from the index that fall within that range.

A regular expression is a “prefix expression” if it starts with a caret (^) or a left anchor (\A), followed by a string of simple symbols. For example, the regex /^abc.*/ will be optimized by matching only against the values from the index that start with abc.

Additionally, while /^a/, /^a.*/, and /^a.*$/ match equivalent strings, they have different performance characteristics. All of these expressions use an index if an appropriate index exists; however, /^a.*/, and /^a.*$/ are slower. /^a/ can stop scanning after matching the prefix.

How do I fit an image (img) inside a div and keep the aspect ratio?

Try CSS:

img {
  object-fit: cover;
  height: 48px;
}

fatal: The current branch master has no upstream branch

I had the same problem

enter image description here

I resolved it that used below command

$ git branch --set-upstream develop origin/develop

and it will add a config in the config file in the .git folder.

enter image description here

What is the difference between Class.getResource() and ClassLoader.getResource()?

Class.getResource can take a "relative" resource name, which is treated relative to the class's package. Alternatively you can specify an "absolute" resource name by using a leading slash. Classloader resource paths are always deemed to be absolute.

So the following are basically equivalent:

foo.bar.Baz.class.getResource("xyz.txt");
foo.bar.Baz.class.getClassLoader().getResource("foo/bar/xyz.txt");

And so are these (but they're different from the above):

foo.bar.Baz.class.getResource("/data/xyz.txt");
foo.bar.Baz.class.getClassLoader().getResource("data/xyz.txt");

Create a temporary table in MySQL with an index from a select

I wrestled quite a while with the proper syntax for CREATE TEMPORARY TABLE SELECT. Having figured out a few things, I wanted to share the answers with the rest of the community.

Basic information about the statement is available at the following MySQL links:

CREATE TABLE SELECT and CREATE TABLE.

At times it can be daunting to interpret the spec. Since most people learn best from examples, I will share how I have created a working statement, and how you can modify it to work for you.

  1. Add multiple indexes

    This statement shows how to add multiple indexes (note that index names - in lower case - are optional):

    CREATE TEMPORARY TABLE core.my_tmp_table 
    (INDEX my_index_name (tag, time), UNIQUE my_unique_index_name (order_number))
    SELECT * FROM core.my_big_table
    WHERE my_val = 1
    
  2. Add a new primary key:

    CREATE TEMPORARY TABLE core.my_tmp_table 
    (PRIMARY KEY my_pkey (order_number),
    INDEX cmpd_key (user_id, time))
    SELECT * FROM core.my_big_table
    
  3. Create additional columns

    You can create a new table with more columns than are specified in the SELECT statement. Specify the additional column in the table definition. Columns specified in the table definition and not found in select will be first columns in the new table, followed by the columns inserted by the SELECT statement.

    CREATE TEMPORARY TABLE core.my_tmp_table 
    (my_new_id BIGINT NOT NULL AUTO_INCREMENT,  
    PRIMARY KEY my_pkey (my_new_id), INDEX my_unique_index_name (invoice_number))
    SELECT * FROM core.my_big_table
    
  4. Redefining data types for the columns from SELECT

    You can redefine the data type of a column being SELECTed. In the example below, column tag is a MEDIUMINT in core.my_big_table and I am redefining it to a BIGINT in core.my_tmp_table.

    CREATE TEMPORARY TABLE core.my_tmp_table 
    (tag BIGINT,
    my_time DATETIME,  
    INDEX my_unique_index_name (tag) )
    SELECT * FROM core.my_big_table
    
  5. Advanced field definitions during create

    All the usual column definitions are available as when you create a normal table. Example:

    CREATE TEMPORARY TABLE core.my_tmp_table 
    (id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    value BIGINT UNSIGNED NOT NULL DEFAULT 0 UNIQUE,
    location VARCHAR(20) DEFAULT "NEEDS TO BE SET",
    country CHAR(2) DEFAULT "XX" COMMENT "Two-letter country code",  
    INDEX my_index_name (location))
    ENGINE=MyISAM 
    SELECT * FROM core.my_big_table
    

How do you implement a class in C?

C isn't an OOP language, as your rightly point out, so there's no built-in way to write a true class. You're best bet is to look at structs, and function pointers, these will let you build an approximation of a class. However, as C is procedural you might want to consider writing more C-like code (i.e. without trying to use classes).

Also, if you can use C, you can probally use C++ and get classes.

git pull error "The requested URL returned error: 503 while accessing"

here you can see the latest updated status form their website

bitbucket site status

if Git via HTTPS status is Major Outage, you will not be able to pull/push, let this status to get green

HTTP Error 503 - Service unavailable

GitHub relative link in Markdown file

GitHub could make this a lot better with minimal work. Here is a work-around.

I think you want something more like

[Your Title](your-project-name/tree/master/your-subfolder)

or to point to the README itself

[README](your-project-name/blob/master/your-subfolder/README.md)

Move textfield when keyboard appears swift

Easiest way that doesn't require any code:

  1. Download KeyboardLayoutConstraint.swift and add (drag & drop) the file into your project, if you're not using the Spring animation framework already.
  2. In your storyboard, create a bottom constraint for the object/view/textfield, select the constraint (double-click it) and in the Identity Inspector, change its class from NSLayoutConstraint to KeyboardLayoutConstraint.
  3. Done!

The object will auto-move up with the keyboard, in sync.

Insert data into table with result from another select query

Below is an example of such a query:

INSERT INTO [93275].[93276].[93277].[93278] ( [Mobile Number], [Mobile Series], [Full Name], [Full Address], [Active Date], company ) IN 'I:\For Test\90-Mobile Series.accdb
SELECT [1].[Mobile Number], [1].[Mobile Series], [1].[Full Name], [1].[Full Address], [1].[Active Date], [1].[Company Name]
FROM 1
WHERE ((([1].[Mobile Series])="93275" Or ([1].[Mobile Series])="93276")) OR ((([1].[Mobile Series])="93277"));OR ((([1].[Mobile Series])="93278"));

Difference between HashMap, LinkedHashMap and TreeMap

All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map interface, and represents mapping from unique key to values.

HashMap

  1. A HashMap contains values based on the key.

  2. It contains only unique elements.

  3. It may have one null key and multiple null values.

  4. It maintains no order.

    public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable

LinkedHashMap

  1. A LinkedHashMap contains values based on the key.
  2. It contains only unique elements.
  3. It may have one null key and multiple null values.
  4. It is same as HashMap instead maintains insertion order. //See class deceleration below

    public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>

TreeMap

  1. A TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.
  2. It contains only unique elements.
  3. It cannot have null key but can have multiple null values.
  4. It is same as HashMap instead maintains ascending order(Sorted using the natural order of its key.).

    public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>, Cloneable, Serializable

Hashtable

  1. A Hashtable is an array of list. Each list is known as a bucket. The position of bucket is identified by calling the hashcode() method. A Hashtable contains values based on the key.
  2. It contains only unique elements.
  3. It may have not have any null key or value.
  4. It is synchronized.
  5. It is a legacy class.

    public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable, Serializable

Ref: http://javarevisited.blogspot.in/2015/08/difference-between-HashMap-vs-TreeMap-vs-LinkedHashMap-Java.html

Why Python 3.6.1 throws AttributeError: module 'enum' has no attribute 'IntFlag'?

I had this problem in ubuntu20.04 in jupyterlab in my virtual env kernel with python3.8 and tensorflow 2.2.0. Error message was

 Traceback (most recent call last):
  File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/home/hu-mka/.local/lib/python2.7/site-packages/ipykernel_launcher.py", line 15, in <module>
    from ipykernel import kernelapp as app
  File "/home/hu-mka/.local/lib/python2.7/site-packages/ipykernel/__init__.py", line 2, in <module>
    from .connect import *
  File "/home/hu-mka/.local/lib/python2.7/site-packages/ipykernel/connect.py", line 13, in <module>
    from IPython.core.profiledir import ProfileDir
  File "/home/hu-mka/.local/lib/python2.7/site-packages/IPython/__init__.py", line 48, in <module>
    from .core.application import Application
  File "/home/hu-mka/.local/lib/python2.7/site-packages/IPython/core/application.py", line 23, in <module>
    from traitlets.config.application import Application, catch_config_error
  File "/home/hu-mka/.local/lib/python2.7/site-packages/traitlets/__init__.py", line 1, in <module>
    from .traitlets import *
  File "/home/hu-mka/.local/lib/python2.7/site-packages/traitlets/traitlets.py", line 49, in <module>
    import enum
ImportError: No module named enum

problem was that in symbolic link in /usr/bin/python was pointing to python2. Solution:

cd /usr/bin/
sudo ln -sf python3 python

Hopefully Python 2 usage will drop off completely soon.

How to remove files that are listed in the .gitignore but still on the repository?

I did a very straightforward solution by manipulating the output of the .gitignore statement with sed:

cat .gitignore | sed '/^#.*/ d' | sed '/^\s*$/ d' | sed 's/^/git rm -r /' | bash

Explanation:

  1. print the .gitignore file
  2. remove all comments from the print
  3. delete all empty lines
  4. add 'git rm -r ' to the start of the line
  5. execute every line.

How do I run Python script using arguments in windows command line

I found this thread looking for information about dealing with parameters; this easy guide was so cool:

import argparse

parser = argparse.ArgumentParser(description='Script so useful.')
parser.add_argument("--opt1", type=int, default=1)
parser.add_argument("--opt2")

args = parser.parse_args()

opt1_value = args.opt1
opt2_value = args.opt2

run like:

python myScript.py --opt2 = 'hi'

Python urllib2, basic HTTP authentication, and tr.im

I would suggest that the current solution is to use my package urllib2_prior_auth which solves this pretty nicely (I work on inclusion to the standard lib.

Webclient / HttpWebRequest with Basic Authentication returns 404 not found for valid URL

Try changing the Web Client request authentication part to:

NetworkCredential myCreds = new NetworkCredential(userName, passWord);
client.Credentials = myCreds;

Then make your call, seems to work fine for me.

Insert HTML from CSS

This can be done. For example with Firefox

CSS

#hlinks {
  -moz-binding: url(stackexchange.xml#hlinks);
}

stackexchange.xml

<bindings xmlns="http://www.mozilla.org/xbl"
  xmlns:html="http://www.w3.org/1999/xhtml">
  <binding id="hlinks">
    <content>
      <children/>
      <html:a href="/privileges">privileges</html:a>
      <html:span class="lsep"> | </html:span>
      <html:a href="/users/logout">log out</html:a>
    </content>
  </binding>
</bindings>

ref 1

ref 2

Eclipse Build Path Nesting Errors

I had the same problem even when I created a fresh project. I was creating the Java project within Eclipse, then mavenize it, then going into java build path properties removing src/ and adding src/main/java and src/test/java. When I run Maven update it used to give nested path error.
Then I finally realized -because I had not seen that entry before- there is a <sourceDirectory>src</sourceDirectory> line in pom file written when I mavenize it. It was resolved after removing it.

How Big can a Python List Get?

According to the source code, the maximum size of a list is PY_SSIZE_T_MAX/sizeof(PyObject*).

PY_SSIZE_T_MAX is defined in pyport.h to be ((size_t) -1)>>1

On a regular 32bit system, this is (4294967295 / 2) / 4 or 536870912.

Therefore the maximum size of a python list on a 32 bit system is 536,870,912 elements.

As long as the number of elements you have is equal or below this, all list functions should operate correctly.

add controls vertically instead of horizontally using flow layout

JPanel testPanel = new JPanel();
testPanel.setLayout(new BoxLayout(testPanel, BoxLayout.Y_AXIS));
/*add variables here and add them to testPanel
        e,g`enter code here`
        testPanel.add(nameLabel);
        testPanel.add(textName);
*/
testPanel.setVisible(true);

What is the difference between :focus and :active?

:active       Adds a style to an element that is activated
:focus        Adds a style to an element that has keyboard input focus
:hover        Adds a style to an element when you mouse over it
:lang         Adds a style to an element with a specific lang attribute
:link         Adds a style to an unvisited link
:visited      Adds a style to a visited link

Source: CSS Pseudo-classes