Programs & Examples On #Rebasing

rebase in progress. Cannot commit. How to proceed or stop (abort)?

Mine was an error that popped up from BitBucket. Ran git am --skip fixed it.

Completely cancel a rebase

Use git rebase --abort. From the official Linux kernel documentation for git rebase:

git rebase --continue | --skip | --abort | --edit-todo

Git push rejected "non-fast-forward"

Well I used the advice here and it screwed me as it merged my local code directly to master. .... so take it all with a grain of salt. My coworker said the following helped resolve the issue, needed to repoint my branch.

 git branch --set-upstream-to=origin/feature/my-current-branch feature/my-current-branch

Choose Git merge strategy for specific files ("ours", "mine", "theirs")

Even though this question is answered, providing an example as to what "theirs" and "ours" means in the case of git rebase vs merge. See this link

Git Rebase
theirs is actually the current branch in the case of rebase. So the below set of commands are actually accepting your current branch changes over the remote branch.

# see current branch
$ git branch
... 
* branch-a
# rebase preferring current branch changes during conflicts
$ git rebase -X theirs branch-b

Git Merge
For merge, the meaning of theirs and ours is reversed. So, to get the same effect during a merge, i.e., keep your current branch changes (ours) over the remote branch being merged (theirs).

# assuming branch-a is our current version
$ git merge -X ours branch-b  # <- ours: branch-a, theirs: branch-b

git rebase merge conflict

Note: with Git 2.14.x/2.15 (Q3 2017), the git rebase message in case of conflicts will be clearer.

See commit 5fdacc1 (16 Jul 2017) by William Duclot (williamdclt).
(Merged by Junio C Hamano -- gitster -- in commit 076eeec, 11 Aug 2017)

rebase: make resolve message clearer for inexperienced users

Before:

When you have resolved this problem, run "git rebase --continue".
If you prefer to skip this patch, run "git rebase --skip" instead.
To check out the original branch and stop rebasing, run "git rebase --abort"

After:

Resolve all conflicts manually, 
mark them as resolved with git add/rm <conflicted_files>
then run "git rebase --continue".

You can instead skip this commit: run "git rebase --skip".
To abort and get back to the state before "git rebase", run "git rebase --abort".')

The git UI can be improved by addressing the error messages to those they help: inexperienced and casual git users.
To this intent, it is helpful to make sure the terms used in those messages can be understood by this segment of users, and that they guide them to resolve the problem.

In particular, failure to apply a patch during a git rebase is a common problem that can be very destabilizing for the inexperienced user.
It is important to lead them toward the resolution of the conflict (which is a 3-steps process, thus complex) and reassure them that they can escape a situation they can't handle with "--abort".
This commit answer those two points by detailing the resolution process and by avoiding cryptic git linguo.

What does 'git remote add upstream' help achieve?

Let's take an example: You want to contribute to django, so you fork its repository. In the while you work on your feature, there is much work done on the original repo by other people. So the code you forked is not the most up to date. setting a remote upstream and fetching it time to time makes sure your forked repo is in sync with the original repo.

Git push rejected after feature branch rebase

As the OP does understand the problem, just looks for a nicer solution...

How about this as a practice ?

  • Have on actual feature-develop branch (where you never rebase and force-push, so your fellow feature developers don't hate you). Here, regularly grab those changes from main with a merge. Messier history, yes, but life is easy and no one get's interupted in his work.

  • Have a second feature-develop branch, where one feature team member regulary pushes all feature commits to, indeed rebased, indeed forced. So almost cleanly based on a fairly recent master commit. Upon feature complete, push that branch on top of master.

There might be a pattern name for this method already.

How to get "their" changes in the middle of conflicting Git rebase?

If you want to pull a particular file from another branch just do

git checkout branch1 -- filenamefoo.txt

This will pull a version of the file from one branch into the current tree

How do you rebase the current branch's changes on top of changes being merged in?

You've got what rebase does backwards. git rebase master does what you're asking for — takes the changes on the current branch (since its divergence from master) and replays them on top of master, then sets the head of the current branch to be the head of that new history. It doesn't replay the changes from master on top of the current branch.

Rebasing remote branches in Git

Nice that you brought this subject up.

This is an important thing/concept in git that a lof of git users would benefit from knowing. git rebase is a very powerful tool and enables you to squash commits together, remove commits etc. But as with any powerful tool, you basically need to know what you're doing or something might go really wrong.

When you are working locally and messing around with your local branches, you can do whatever you like as long as you haven't pushed the changes to the central repository. This means you can rewrite your own history, but not others history. By only messing around with your local stuff, nothing will have any impact on other repositories.

This is why it's important to remember that once you have pushed commits, you should not rebase them later on. The reason why this is important, is that other people might pull in your commits and base their work on your contributions to the code base, and if you later on decide to move that content from one place to another (rebase it) and push those changes, then other people will get problems and have to rebase their code. Now imagine you have 1000 developers :) It just causes a lot of unnecessary rework.

How to squash commits in git after they have been pushed?

Squash commits locally with

git rebase -i origin/master~4 master

and then force push with

git push origin +master

Difference between --force and +

From the documentation of git push:

Note that --force applies to all the refs that are pushed, hence using it with push.default set to matching or with multiple push destinations configured with remote.*.push may overwrite refs other than the current branch (including local refs that are strictly behind their remote counterpart). To force a push to only one branch, use a + in front of the refspec to push (e.g git push origin +master to force a push to the master branch).

Rebasing a Git merge commit

Ok, that's an old question and it already have accepted answer by @siride, but that answer wasn't enough in my case, as --preserve-merges forces you to resolve all conflicts second time. My solution based on the idea by @Tobi B but with exact step-by-step commands

So we'll start on such state based on example in the question:

*   8101fe3 Merge branch 'topic'  [HEAD -> master]
|\  
| * b62cae6 2                     [topic]
| |
| | * f5a7ca8 5                   [origin/master]
| | * e7affba 4
| |/  
|/|   
* | eb3b733 3
|/  
* 38abeae 1

Note that we have 2 commits ahead master, so cherry-pick wouldn't work.

  1. First of all, let's create correct history that we want:

    git checkout -b correct-history # create new branch to save master for future
    git rebase --strategy=ours --preserve-merges origin/master
    

    We use --preserve-merges to save our merge commit in history. We use --strategy=ours to ignore all merge conflicts as we don't care about what contents will be in that merge commit, we only need nice history now.

    History will looks like that (ignoring master):

    *   51984c7 Merge branch 'topic'  [HEAD -> correct-history]
    |\  
    | * b62cae6 2                     [topic]
    * | f5a7ca8 5                     [origin/master]
    * | e7affba 4
    * | eb3b733 3
    |/  
    * 38abeae 1
    
  2. Let's get correct index now.

    git checkout master # return to our master branch
    git merge origin/master # merge origin/master on top of our master
    

    We may get some additional merge conflicts here, but that's would only be conflicts from files changed between 8101fe3 and f5a7ca8, but not includes already resolved conflicts from topic

    History will looks like this (ignoring correct-history):

    *   94f1484 Merge branch 'origin/master'  [HEAD -> master]
    |\  
    * | f5a7ca8 5                   [origin/master]
    * | e7affba 4
    | *   8101fe3 Merge branch 'topic'
    | |\  
    | | * b62cae6 2                     [topic]
    |/ /
    * / eb3b733 3
    |/  
    * 38abeae 1
    
  3. The last stage is to combine our branch with correct history and branch with correct index

    git reset --soft correct-history
    git commit --amend
    

    We use reset --soft to reset our branch (and history) to correct-history, but leave index and working tree as is. Then we use commit --amend to rewrite our merge commit, that used to have incorrect index, with our good index from master.

    In the end we will have such state (note another id of top commit):

    *   13e6d03 Merge branch 'topic'  [HEAD -> master]
    |\  
    | * b62cae6 2                     [topic]
    * | f5a7ca8 5                     [origin/master]
    * | e7affba 4
    * | eb3b733 3
    |/  
    * 38abeae 1
    

Can I get a patch-compatible output from git-diff?

If you want to use patch you need to remove the a/ b/ prefixes that git uses by default. You can do this with the --no-prefix option (you can also do this with patch's -p option):

git diff --no-prefix [<other git-diff arguments>]

Usually though, it is easier to use straight git diff and then use the output to feed to git apply.

Most of the time I try to avoid using textual patches. Usually one or more of temporary commits combined with rebase, git stash and bundles are easier to manage.

For your use case I think that stash is most appropriate.

# save uncommitted changes
git stash

# do a merge or some other operation
git merge some-branch

# re-apply changes, removing stash if successful
# (you may be asked to resolve conflicts).
git stash pop

When should I use git pull --rebase?

I think you should use git pull --rebase when collaborating with others on the same branch. You are in your work ? commit ? work ? commit cycle, and when you decide to push your work your push is rejected, because there's been parallel work on the same branch. At this point I always do a pull --rebase. I do not use squash (to flatten commits), but I rebase to avoid the extra merge commits.

As your Git knowledge increases you find yourself looking a lot more at history than with any other version control systems I've used. If you have a ton of small merge commits, it's easy to lose focus of the bigger picture that's happening in your history.

This is actually the only time I do rebasing(*), and the rest of my workflow is merge based. But as long as your most frequent committers do this, history looks a whole lot better in the end.

(*) While teaching a Git course, I had a student arrest me on this, since I also advocated rebasing feature branches in certain circumstances. And he had read this answer ;) Such rebasing is also possible, but it always has to be according to a pre-arranged/agreed system, and as such should not "always" be applied. And at that time I usually don't do pull --rebase either, which is what the question is about ;)

Pushing an existing Git repository to SVN

If you don't have to use any specific SVN and you are using GitHub you can use their SVN connector.

More information is here: Collaborating on GitHub with Subversion

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.

Git for beginners: The definitive practical guide

WRT good GUIs/frontends, you may also want to check out qgit which is a cross-platform (Linux/Win32) repository viewer for Git and can be also used as high level frontend for the most common Git operations, in fact it can be easily enhanced by so called "custom actions" so that users can provide customized actions.

Regex to validate JSON

Looking at the documentation for JSON, it seems that the regex can simply be three parts if the goal is just to check for fitness:

  1. The string starts and ends with either [] or {}
    • [{\[]{1}...[}\]]{1}
  2. and
    1. The character is an allowed JSON control character (just one)
      • ...[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]...
    2. or The set of characters contained in a ""
      • ...".*?"...

All together: [{\[]{1}([,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]|".*?")+[}\]]{1}

If the JSON string contains newline characters, then you should use the singleline switch on your regex flavor so that . matches newline. Please note that this will not fail on all bad JSON, but it will fail if the basic JSON structure is invalid, which is a straight-forward way to do a basic sanity validation before passing it to a parser.

Please explain about insertable=false and updatable=false in reference to the JPA @Column annotation

You would do that when the responsibility of creating/updating the referenced column isn't in the current entity, but in another entity.

Is there a way to ignore a single FindBugs warning?

Update Gradle

dependencies {
    compile group: 'findbugs', name: 'findbugs', version: '1.0.0'
}

Locate the FindBugs Report

file:///Users/your_user/IdeaProjects/projectname/build/reports/findbugs/main.html

Find the specific message

find bugs

Import the correct version of the annotation

import edu.umd.cs.findbugs.annotations.SuppressWarnings;

Add the annotation directly above the offending code

@SuppressWarnings("OUT_OF_RANGE_ARRAY_INDEX")

See here for more info: findbugs Spring Annotation

Cannot create SSPI context

First thing you should do is go into the logs (Management\SQL Server Logs) and see if SQL Server successfully registered the Service Principal Name (SPN). If you see some sort of error (The SQL Server Network Interface library could not register the Service Principal Name (SPN) for the SQL Server service) then you know where to start.

We saw this happen when we changed the account SQL Server was running under. Resetting it to Local System Account solved the problem. Microsoft also has a guide on manually configuring the SPN.

SQL Server r2 installation error .. update Visual Studio 2008 to SP1

Finally, I solved it. Even though the solution is a bit lengthy, I think its the simplest. The solution is as follows:

  1. Install Visual Studio 2008
  2. Install the service Package 1 (SP1)
  3. Install SQL Server 2008 r2

How to open a new tab using Selenium WebDriver

This line of code will open a new browser tab using Selenium WebDriver:

((JavascriptExecutor)getDriver()).executeScript("window.open()");

Split bash string by newline characters

There is another way if all you want is the text up to the first line feed:

x='some
thing'

y=${x%$'\n'*}

After that y will contain some and nothing else (no line feed).

What is happening here?

We perform a parameter expansion substring removal (${PARAMETER%PATTERN}) for the shortest match up to the first ANSI C line feed ($'\n') and drop everything that follows (*).

How to use Angular2 templates with *ngFor to create a table out of nested arrays?

it's not exact output that you wanted but maybe something like this will do. Parent cmp:

<table>
  <item *ngFor="#i of items" [data]="i"></item>
</table>

Child cmp

import {Component} from 'angular2/core';

@Component({
  selector: `item`,
  inputs: ['data'],
  template: `
    <tr><td>{{data.name}}</td></tr>
    <tr *ngFor="#i of data.items">
      <td><h1>{{i}}</h1></td>
    </tr>
  `
})
export default class Item {


}

Including a groovy script in another groovy

Groovy doesn't have an import keyword like typical scripting languages that will do a literal include of another file's contents (alluded to here: Does groovy provide an include mechanism?).
Because of its object/class oriented nature, you have to "play games" to make things like this work. One possibility is to make all your utility functions static (since you said they don't use objects) and then perform a static import in the context of your executing shell. Then you can call these methods like "global functions".
Another possibility would be using a Binding object (http://groovy.codehaus.org/api/groovy/lang/Binding.html) while creating your Shell and binding all the functions you want to the methods (the downside here would be having to enumerate all methods in the binding but you could perhaps use reflection). Yet another solution would be to override methodMissing(...) in the delegate object assigned to your shell which allows you to basically do dynamic dispatch using a map or whatever method you'd like.

Several of these methods are demonstrated here: http://www.nextinstruction.com/blog/2012/01/08/creating-dsls-with-groovy/. Let me know if you want to see an example of a particular technique.

What is a good practice to check if an environmental variable exists or not?

I'd recommend the following solution.

It prints the env vars you didn't include, which lets you add them all at once. If you go for the for loop, you're going to have to rerun the program to see each missing var.

from os import environ

REQUIRED_ENV_VARS = {"A", "B", "C", "D"}
diff = REQUIRED_ENV_VARS.difference(environ)
if len(diff) > 0:
    raise EnvironmentError(f'Failed because {diff} are not set')

the easiest way to convert matrix to one row vector

You can use the function RESHAPE:

B = reshape(A.',1,[]);

LINQ .Any VS .Exists - What's the difference?

See documentation

List.Exists (Object method - MSDN)

Determines whether the List(T) contains elements that match the conditions defined by the specified predicate.

This exists since .NET 2.0, so before LINQ. Meant to be used with the Predicate delegate, but lambda expressions are backward compatible. Also, just List has this (not even IList)

IEnumerable.Any (Extension method - MSDN)

Determines whether any element of a sequence satisfies a condition.

This is new in .NET 3.5 and uses Func(TSource, bool) as argument, so this was intended to be used with lambda expressions and LINQ.

In behaviour, these are identical.

Android List View Drag and Drop sort

I found DragSortListView worked well, although getting started on it could have been easier. Here's a brief tutorial on using it in Android Studio with an in-memory list:

  1. Add this to the build.gradle dependencies for your app:

    compile 'asia.ivity.android:drag-sort-listview:1.0' // Corresponds to release 0.6.1
    
  2. Create a resource for the drag handle ID by creating or adding to values/ids.xml:

    <resources>
        ... possibly other resources ...
        <item type="id" name="drag_handle" />
    </resources>
    
  3. Create a layout for a list item that includes your favorite drag handle image, and assign its ID to the ID you created in step 2 (e.g. drag_handle).

  4. Create a DragSortListView layout, something like this:

    <com.mobeta.android.dslv.DragSortListView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:dslv="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        dslv:drag_handle_id="@id/drag_handle"
        dslv:float_background_color="@android:color/background_light"/>
    
  5. Set an ArrayAdapter derivative with a getView override that renders your list item view.

        final ArrayAdapter<MyItem> itemAdapter = new ArrayAdapter<MyItem>(this, R.layout.my_item, R.id.my_item_name, items) { // The third parameter works around ugly Android legacy. http://stackoverflow.com/a/18529511/145173
            @Override public View getView(int position, View convertView, ViewGroup parent) {
                View view = super.getView(position, convertView, parent);
                MyItem item = getItem(position);
                ((TextView) view.findViewById(R.id.my_item_name)).setText(item.getName());
                // ... Fill in other views ...
                return view;
            }
        };
    
        dragSortListView.setAdapter(itemAdapter);
    
  6. Set a drop listener that rearranges the items as they are dropped.

        dragSortListView.setDropListener(new DragSortListView.DropListener() {
            @Override public void drop(int from, int to) {
                MyItem movedItem = items.get(from);
                items.remove(from);
                if (from > to) --from;
                items.add(to, movedItem);
                itemAdapter.notifyDataSetChanged();
            }
        });
    

Select first 10 distinct rows in mysql

Try this SELECT DISTINCT 10 * ...

How do I update a model value in JavaScript in a Razor view?

This should work

function updatePostID(val)
{
    document.getElementById('PostID').value = val;

    //and probably call document.forms[0].submit();
}

Then have a hidden field or other control for the PostID

@Html.Hidden("PostID", Model.addcomment.PostID)
//OR
@Html.HiddenFor(model => model.addcomment.PostID)

'npm' is not recognized as internal or external command, operable program or batch file

If you are using VS Code, close VS code and open again.

I tried closing Terminal and then opening new Terminal but it didn't work.

Re-Starting VS Code works!

How good is Java's UUID.randomUUID?

I play at lottery last year, and I've never won .... but it seems that there lottery has winners ...

doc : http://tools.ietf.org/html/rfc4122

Type 1 : not implemented. collision are possible if the uuid is generated at the same moment. impl can be artificially a-synchronize in order to bypass this problem.

Type 2 : never see a implementation.

Type 3 : md5 hash : collision possible (128 bits-2 technical bytes)

Type 4 : random : collision possible (as lottery). note that the jdk6 impl dont use a "true" secure random because the PRNG algorithm is not choose by developer and you can force system to use a "poor" PRNG algo. So your UUID is predictable.

Type 5 : sha1 hash : not implemented : collision possible (160 bit-2 technical bytes)

How do I create a view controller file after creating a new view controller?

Correct, when you drag a view controller object onto your storyboard in order to create a new scene, it doesn't automatically make the new class for you, too.

Having added a new view controller scene to your storyboard, you then have to:

  1. Create a UIViewController subclass. For example, go to your target's folder in the project navigator panel on the left and then control-click and choose "New File...". Choose a "Cocoa Touch Class":

    Cocoa Touch Class

    And then select a unique name for the new view controller subclass:

    UIViewController subclass

  2. Specify this new subclass as the base class for the scene you just added to the storyboard.

    enter image description here

  3. Now hook up any IBOutlet and IBAction references for this new scene with the new view controller subclass.

how to display employee names starting with a and then b in sql

Here what I understood from the question is starting with "a " and then "b" ex:

  • abhay
  • abhishek
  • abhinav

So there should be two conditions and both should be true means you cant use "OR" operator Ordered by is not not compulsory but its good if you use.

Select e_name from emp 
where  e_name like 'a%' AND e_name like '_b%'
Ordered by e_name

How to calculate the difference between two dates using PHP?

<?php
    $today = strtotime("2011-02-03 00:00:00");
    $myBirthDate = strtotime("1964-10-30 00:00:00");
    printf("Days since my birthday: ", ($today - $myBirthDate)/60/60/24);
?>

Using PowerShell credentials without being prompted for a password

There is another way, but...

DO NOT DO THIS IF YOU DO NOT WANT YOUR PASSWORD IN THE SCRIPT FILE (It isn't a good idea to store passwords in scripts, but some of us just like to know how.)

Ok, that was the warning, here's the code:

$username = "John Doe"
$password = "ABCDEF"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr

$cred will have the credentials from John Doe with the password "ABCDEF".

Alternative means to get the password ready for use:

$password = convertto-securestring -String "notverysecretpassword" -AsPlainText -Force

How do I export a project in the Android studio?

Follow the below steps to sign the application in the android studio:-

  1. First Go to Build->Generate Signed APK

    First screenshot

  2. Then Once you click on the Generate Signed APK then there is info dialog message appear.

    Second screenshot

  3. Click on the Create New button if you don't have any keystore file. If you have click on the Choose Existing.

    This screenshot

  4. Once you click on the Create New button then now dialog box appear where you need to enter the keystore file info, other signing authority details.

    Fourth screenshot

  5. Once you fill complete details then click on the Ok button then it redirect to this dialog.

    Fifth screenshot

  6. Click on the Next button then check mark on the Run ProGuard and click on the finish. It generate the signed APK.

    Sixth screenshot

    Seventh screenshot

Use and meaning of "in" in an if statement?

Maybe these examples will help illustrate what in does. It basically translate to Is this item in this other item?

listOfNums = [ 1, 2, 3, 4, 5, 6, 45, 'j' ]

>>> 3 in listOfNums:
>>> True

>>> 'j' in listOfNums:
>>> True

>>> 66 in listOfNums:
>>> False

rails 3.1.0 ActionView::Template::Error (application.css isn't precompiled)

Here's the quick fix:

If you're using capistrano do this add this to your deploy.rb:

after 'deploy:update_code' do
  run "cd #{release_path}; RAILS_ENV=production rake assets:precompile"
end

cap deploy

Alter table to modify default value of column

For Sql Azure the following query works :

ALTER TABLE [TableName] ADD  DEFAULT 'DefaultValue' FOR ColumnName
GO

How do I make WRAP_CONTENT work on a RecyclerView

Here is the refined version of the class which seems to work and lacks problems other solutions have:

package org.solovyev.android.views.llm;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

/**
 * {@link android.support.v7.widget.LinearLayoutManager} which wraps its content. Note that this class will always
 * wrap the content regardless of {@link android.support.v7.widget.RecyclerView} layout parameters.
 *
 * Now it's impossible to run add/remove animations with child views which have arbitrary dimensions (height for
 * VERTICAL orientation and width for HORIZONTAL). However if child views have fixed dimensions
 * {@link #setChildSize(int)} method might be used to let the layout manager know how big they are going to be.
 * If animations are not used at all then a normal measuring procedure will run and child views will be measured during
 * the measure pass.
 */
public class LinearLayoutManager extends android.support.v7.widget.LinearLayoutManager {

    private static final int CHILD_WIDTH = 0;
    private static final int CHILD_HEIGHT = 1;
    private static final int DEFAULT_CHILD_SIZE = 100;

    private final int[] childDimensions = new int[2];

    private int childSize = DEFAULT_CHILD_SIZE;
    private boolean hasChildSize;

    @SuppressWarnings("UnusedDeclaration")
    public LinearLayoutManager(Context context) {
        super(context);
    }

    @SuppressWarnings("UnusedDeclaration")
    public LinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
    }

    public static int makeUnspecifiedSpec() {
        return View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
    }

    @Override
    public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
        final int widthMode = View.MeasureSpec.getMode(widthSpec);
        final int heightMode = View.MeasureSpec.getMode(heightSpec);

        final int widthSize = View.MeasureSpec.getSize(widthSpec);
        final int heightSize = View.MeasureSpec.getSize(heightSpec);

        final boolean exactWidth = widthMode == View.MeasureSpec.EXACTLY;
        final boolean exactHeight = heightMode == View.MeasureSpec.EXACTLY;

        final int unspecified = makeUnspecifiedSpec();

        if (exactWidth && exactHeight) {
            // in case of exact calculations for both dimensions let's use default "onMeasure" implementation
            super.onMeasure(recycler, state, widthSpec, heightSpec);
            return;
        }

        final boolean vertical = getOrientation() == VERTICAL;

        initChildDimensions(widthSize, heightSize, vertical);

        int width = 0;
        int height = 0;

        // it's possible to get scrap views in recycler which are bound to old (invalid) adapter entities. This
        // happens because their invalidation happens after "onMeasure" method. As a workaround let's clear the
        // recycler now (it should not cause any performance issues while scrolling as "onMeasure" is never
        // called whiles scrolling)
        recycler.clear();

        final int stateItemCount = state.getItemCount();
        final int adapterItemCount = getItemCount();
        // adapter always contains actual data while state might contain old data (f.e. data before the animation is
        // done). As we want to measure the view with actual data we must use data from the adapter and not from  the
        // state
        for (int i = 0; i < adapterItemCount; i++) {
            if (vertical) {
                if (!hasChildSize) {
                    if (i < stateItemCount) {
                        // we should not exceed state count, otherwise we'll get IndexOutOfBoundsException. For such items
                        // we will use previously calculated dimensions
                        measureChild(recycler, i, widthSpec, unspecified, childDimensions);
                    } else {
                        logMeasureWarning(i);
                    }
                }
                height += childDimensions[CHILD_HEIGHT];
                if (i == 0) {
                    width = childDimensions[CHILD_WIDTH];
                }
                if (height >= heightSize) {
                    break;
                }
            } else {
                if (!hasChildSize) {
                    if (i < stateItemCount) {
                        // we should not exceed state count, otherwise we'll get IndexOutOfBoundsException. For such items
                        // we will use previously calculated dimensions
                        measureChild(recycler, i, unspecified, heightSpec, childDimensions);
                    } else {
                        logMeasureWarning(i);
                    }
                }
                width += childDimensions[CHILD_WIDTH];
                if (i == 0) {
                    height = childDimensions[CHILD_HEIGHT];
                }
                if (width >= widthSize) {
                    break;
                }
            }
        }

        if ((vertical && height < heightSize) || (!vertical && width < widthSize)) {
            // we really should wrap the contents of the view, let's do it

            if (exactWidth) {
                width = widthSize;
            } else {
                width += getPaddingLeft() + getPaddingRight();
            }

            if (exactHeight) {
                height = heightSize;
            } else {
                height += getPaddingTop() + getPaddingBottom();
            }

            setMeasuredDimension(width, height);
        } else {
            // if calculated height/width exceeds requested height/width let's use default "onMeasure" implementation
            super.onMeasure(recycler, state, widthSpec, heightSpec);
        }
    }

    private void logMeasureWarning(int child) {
        if (BuildConfig.DEBUG) {
            Log.w("LinearLayoutManager", "Can't measure child #" + child + ", previously used dimensions will be reused." +
                    "To remove this message either use #setChildSize() method or don't run RecyclerView animations");
        }
    }

    private void initChildDimensions(int width, int height, boolean vertical) {
        if (childDimensions[CHILD_WIDTH] != 0 || childDimensions[CHILD_HEIGHT] != 0) {
            // already initialized, skipping
            return;
        }
        if (vertical) {
            childDimensions[CHILD_WIDTH] = width;
            childDimensions[CHILD_HEIGHT] = childSize;
        } else {
            childDimensions[CHILD_WIDTH] = childSize;
            childDimensions[CHILD_HEIGHT] = height;
        }
    }

    @Override
    public void setOrientation(int orientation) {
        // might be called before the constructor of this class is called
        //noinspection ConstantConditions
        if (childDimensions != null) {
            if (getOrientation() != orientation) {
                childDimensions[CHILD_WIDTH] = 0;
                childDimensions[CHILD_HEIGHT] = 0;
            }
        }
        super.setOrientation(orientation);
    }

    public void clearChildSize() {
        hasChildSize = false;
        setChildSize(DEFAULT_CHILD_SIZE);
    }

    public void setChildSize(int childSize) {
        hasChildSize = true;
        if (this.childSize != childSize) {
            this.childSize = childSize;
            requestLayout();
        }
    }

    private void measureChild(RecyclerView.Recycler recycler, int position, int widthSpec, int heightSpec, int[] dimensions) {
        final View child = recycler.getViewForPosition(position);

        final RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) child.getLayoutParams();

        final int hPadding = getPaddingLeft() + getPaddingRight();
        final int vPadding = getPaddingTop() + getPaddingBottom();

        final int hMargin = p.leftMargin + p.rightMargin;
        final int vMargin = p.topMargin + p.bottomMargin;

        final int hDecoration = getRightDecorationWidth(child) + getLeftDecorationWidth(child);
        final int vDecoration = getTopDecorationHeight(child) + getBottomDecorationHeight(child);

        final int childWidthSpec = getChildMeasureSpec(widthSpec, hPadding + hMargin + hDecoration, p.width, canScrollHorizontally());
        final int childHeightSpec = getChildMeasureSpec(heightSpec, vPadding + vMargin + vDecoration, p.height, canScrollVertically());

        child.measure(childWidthSpec, childHeightSpec);

        dimensions[CHILD_WIDTH] = getDecoratedMeasuredWidth(child) + p.leftMargin + p.rightMargin;
        dimensions[CHILD_HEIGHT] = getDecoratedMeasuredHeight(child) + p.bottomMargin + p.topMargin;

        recycler.recycleView(child);
    }
}

This is also available as a library. Link to relevant class.

How to use color picker (eye dropper)?

To open the Eye Dropper simply:

  1. Open DevTools F12
  2. Go to Elements tab
  3. Under Styles side bar click on any color preview box

enter image description here

Its main functionality is to inspect pixel color values by clicking them though with its new features you can also see your page's existing colors palette or material design palette by clicking on the two arrows icon at the bottom. It can get quite handy when designing your page.

Twitter Bootstrap 3: How to center a block

center-block can be found in bootstrap 3.0 in utilities.less on line 12 and mixins.less on line 39

DISTINCT for only one column

The reason DISTINCT and GROUP BY work on entire rows is that your query returns entire rows.

To help you understand: Try to write out by hand what the query should return and you will see that it is ambiguous what to put in the non-duplicated columns.

If you literally don't care what is in the other columns, don't return them. Returning a random row for each e-mail address seems a little useless to me.

Creating a div element inside a div element in javascript

Your code works well you just mistyped this line of code:

document.getElementbyId('lc').appendChild(element);

change it with this: (The "B" should be capitalized.)

document.getElementById('lc').appendChild(element);  

HERE IS MY EXAMPLE:

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
_x000D_
<script>_x000D_
_x000D_
function test() {_x000D_
_x000D_
    var element = document.createElement("div");_x000D_
    element.appendChild(document.createTextNode('The man who mistook his wife for a hat'));_x000D_
    document.getElementById('lc').appendChild(element);_x000D_
_x000D_
}_x000D_
_x000D_
</script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<input id="filter" type="text" placeholder="Enter your filter text here.." onkeyup = "test()" />_x000D_
_x000D_
<div id="lc" style="background: blue; height: 150px; width: 150px;_x000D_
}" onclick="test();">  _x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to use npm with ASP.NET Core

Instead of trying to serve the node modules folder, you can also use Gulp to copy what you need to wwwroot.

https://docs.asp.net/en/latest/client-side/using-gulp.html

This might help too

Visual Studio 2015 ASP.NET 5, Gulp task not copying files from node_modules

How to get string objects instead of Unicode from JSON?

This is late to the game, but I built this recursive caster. It works for my needs and I think it's relatively complete. It may help you.

def _parseJSON(self, obj):
    newobj = {}

    for key, value in obj.iteritems():
        key = str(key)

        if isinstance(value, dict):
            newobj[key] = self._parseJSON(value)
        elif isinstance(value, list):
            if key not in newobj:
                newobj[key] = []
                for i in value:
                    newobj[key].append(self._parseJSON(i))
        elif isinstance(value, unicode):
            val = str(value)
            if val.isdigit():
                val = int(val)
            else:
                try:
                    val = float(val)
                except ValueError:
                    val = str(val)
            newobj[key] = val

    return newobj

Just pass it a JSON object like so:

obj = json.loads(content, parse_float=float, parse_int=int)
obj = _parseJSON(obj)

I have it as a private member of a class, but you can repurpose the method as you see fit.

Image resolution for new iPhone 6 and 6+, @3x support added?

I have tested by making a sample project and all simulators seem to use @3x images , this is confusing.

Create different versions of an image in your asset catalog such that the image itself tells you what version it is:

enter image description here

Now run the app on each simulator in turn. You will see that the 3x image is used only on the iPhone 6 Plus.

The same thing is true if the images are drawn from the app bundle using their names (e.g. one.png, [email protected], and [email protected]) by calling imageNamed: and assigning into an image view.

(However, there's a difference if you assign the image to an image view in Interface Builder - the 2x version is ignored on double-resolution devices. This is presumably a bug, apparently a bug in pathForResource:ofType:.)

onclick event pass <li> id or value

<li>s don't have a value - only form inputs do. In fact, you're not supposed to even include the value attribute in the HTML for <li>s.

You can rely on .innerHTML instead:

getPaging(this.innerHTML)

Or maybe the id:

getPaging(this.id);

However, it's easier (and better practice) to add the click handlers from JavaScript code, and not include them in the HTML. Seeing as you're already using jQuery, this can easily be done by changing your HTML to:

<li class="clickMe">1</li>
<li class="clickMe">2</li>

And use the following JavaScript:

$(function () {
    $('.clickMe').click(function () {
        var str = $(this).text();
        $('#loading-content').load('dataSearch.php?' + str, hideLoader);
    });
});

This will add the same click handler to all your <li class="clickMe">s, without requiring you to duplicate your onclick="getPaging(this.value)" code for each of them.

How to create a RelativeLayout programmatically with two buttons one on top of the other?

I have written a quick example to demonstrate how to create a layout programmatically.

public class CodeLayout extends Activity {

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

        // Creating a new RelativeLayout
        RelativeLayout relativeLayout = new RelativeLayout(this);

        // Defining the RelativeLayout layout parameters.
        // In this case I want to fill its parent
        RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.FILL_PARENT,
                RelativeLayout.LayoutParams.FILL_PARENT);

        // Creating a new TextView
        TextView tv = new TextView(this);
        tv.setText("Test");

        // Defining the layout parameters of the TextView
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        lp.addRule(RelativeLayout.CENTER_IN_PARENT);

        // Setting the parameters on the TextView
        tv.setLayoutParams(lp);

        // Adding the TextView to the RelativeLayout as a child
        relativeLayout.addView(tv);

        // Setting the RelativeLayout as our content view
        setContentView(relativeLayout, rlp);
    }
}

In theory everything should be clear as it is commented. If you don't understand something just tell me.

How do I force detach Screen from another SSH session?

Short answer

  1. Reattach without ejecting others: screen -x
  2. Get list of displays: ^A *, select the one to disconnect, press d


Explained answer

Background: When I was looking for the solution with same problem description, I have always landed on this answer. I would like to provide more sensible solution. (For example: the other attached screen has a different size and a I cannot force resize it in my terminal.)

Note: PREFIX is usually ^A = ctrl+a

Note: the display may also be called:

  • "user front-end" (in at command manual in screen)
  • "client" (tmux vocabulary where this functionality is detach-client)
  • "terminal" (as we call the window in our user interface) /depending on

1. Reattach a session: screen -x

-x attach to a not detached screen session without detaching it

2. List displays of this session: PREFIX *

It is the default key binding for: PREFIX :displays. Performing it within the screen, identify the other display we want to disconnect (e.g. smaller size). (Your current display is displayed in brighter color/bold when not selected).

term-type   size         user interface           window       Perms
---------- ------- ---------- ----------------- ----------     -----
 screen     240x60         you@/dev/pts/2      nb  0(zsh)        rwx
 screen      78x40         you@/dev/pts/0      nb  0(zsh)        rwx

Using arrows ? ?, select the targeted display, press d If nothing happens, you tried to detach your own display and screen will not detach it. If it was another one, within a second or two, the entry will disappear.

Press ENTER to quit the listing.

Optionally: in order to make the content fit your screen, reflow: PREFIX F (uppercase F)

Excerpt from man page of screen:

displays

Shows a tabular listing of all currently connected user front-ends (displays). This is most useful for multiuser sessions. The following keys can be used in displays list:

  • mouseclick Move to the selected line. Available when "mousetrack" is set to on.
  • space Refresh the list
  • d Detach that display
  • D Power detach that display
  • C-g, enter, or escape Exit the list

How to speed up insertion performance in PostgreSQL

For optimal Insertion performance disable the index if that's an option for you. Other than that, better hardware (disk, memory) is also helpful

Bootstrap 3 hidden-xs makes row narrower

How does it work if you only are using visible-md at Col4 instead? Do you use the -lg at all? If not this might work.

<div class="container">
    <div class="row">
        <div class="col-xs-4 col-sm-2 col-md-1" align="center">
            Col1
        </div>
        <div class="col-xs-4 col-sm-2" align="center">
            Col2
        </div>
        <div class="hidden-xs col-sm-6 col-md-5" align="center">
            Col3
        </div>
        <div class="visible-md col-md-3 " align="center">
            Col4
        </div>
        <div class="col-xs-4 col-sm-2 col-md-1" align="center">
            Col5
        </div>
    </div>
</div>

What is the string length of a GUID?

The correct thing to do here is to store it as uniqueidentifier - this is then fully indexable, etc. at the database. The next-best option would be a binary(16) column: standard GUIDs are exactly 16 bytes in length.

If you must store it as a string, the length really comes down to how you choose to encode it. As hex (AKA base-16 encoding) without hyphens it would be 32 characters (two hex digits per byte), so char(32).

However, you might want to store the hyphens. If you are short on space, but your database doesn't support blobs / guids natively, you could use Base64 encoding and remove the == padding suffix; that gives you 22 characters, so char(22). There is no need to use Unicode, and no need for variable-length - so nvarchar(max) would be a bad choice, for example.

How to create a file name with the current date & time in Python?

I'm surprised there is not some single formatter that returns a default (and safe) 'for appending in filename' - format of the time, We could simply write FD.write('mybackup'+time.strftime('%(formatter here)') + 'ext'

"%x" instead of "%Y%m%d-%H%M%S"

Reading rather large json files in Python

The issue here is that JSON, as a format, is generally parsed in full and then handled in-memory, which for such a large amount of data is clearly problematic.

The solution to this is to work with the data as a stream - reading part of the file, working with it, and then repeating.

The best option appears to be using something like ijson - a module that will work with JSON as a stream, rather than as a block file.

Edit: Also worth a look - kashif's comment about json-streamer and Henrik Heino's comment about bigjson.

How to count how many values per level in a given factor?

Using plyr package:

library(plyr)

count(mydf$V1)

It will return you a frequency of each value.

Uncaught ReferenceError: $ is not defined

The error will occur in the following two scenarios as well.

  1. @section scripts element is missing from the HTML file
  2. Error in accessing DOM elements. For example accessing of DOM element is mentioned as $("js-toggle") instead of $(".js-toggle"). Actually the period is missing

So 3 things to be followed - check required scripts are added, check if it is added in the required order and third syntax errors in your Java Script.

How do I show a message in the foreach loop?

You are looking to see if a single value is in an array. Use in_array.

However note that case is important, as are any leading or trailing spaces. Use var_dump to find out the length of the strings too, and see if they fit.

How do you handle a "cannot instantiate abstract class" error in C++?

Visual Studio's Error List pane only shows you the first line of the error. Invoke View>Output and I bet you'll see something like:

c:\path\to\your\code.cpp(42): error C2259: 'AmbientOccluder' : cannot instantiate abstract class
          due to following members:
          'ULONG MysteryUnimplementedMethod(void)' : is abstract
          c:\path\to\some\include.h(8) : see declaration of 'MysteryUnimplementedMethod'

How do I match any character across multiple lines in a regular expression?

In the context of use within languages, regular expressions act on strings, not lines. So you should be able to use the regex normally, assuming that the input string has multiple lines.

In this case, the given regex will match the entire string, since "<FooBar>" is present. Depending on the specifics of the regex implementation, the $1 value (obtained from the "(.*)") will either be "fghij" or "abcde\nfghij". As others have said, some implementations allow you to control whether the "." will match the newline, giving you the choice.

Line-based regular expression use is usually for command line things like egrep.

pip cannot install anything

I had that problem too, after I tried to reset my network settings. it solves problem.

figure of imshow() is too small

I'm new to python too. Here is something that looks like will do what you want to

axes([0.08, 0.08, 0.94-0.08, 0.94-0.08]) #[left, bottom, width, height]
axis('scaled')`

I believe this decides the size of the canvas.

Cross origin requests are only supported for HTTP but it's not cross-domain

REM kill all existing instance of chrome 
taskkill /F /IM chrome.exe /T
REM directory path where chrome.exe is located
set chromeLocation="C:\Program Files (x86)\Google\Chrome\Application"
cd %chromeLocation%
cd c:
start chrome.exe --allow-file-access-from-files
  1. change chromeLocation path with yours.

  2. save above as .bat file.

  3. drag drop you file on the batch file you created. (chrome does give restore pages option though so if you have pages open just hit restore and it will work).

How do I get some variable from another class in Java?

The code that you have is correct. To get a variable from another class you need to create an instance of the class if the variable is not static, and just call the explicit method to get access to that variable. If you put get and set method like the above is the same of declaring that variable public.

Put the method setNum private and inside the getNum assign the value that you want, you will have "get" access to the variable in that case

Is generator.next() visible in Python 3?

Try:

next(g)

Check out this neat table that shows the differences in syntax between 2 and 3 when it comes to this.

How can I link to a specific glibc version?

You are correct in that glibc uses symbol versioning. If you are curious, the symbol versioning implementation introduced in glibc 2.1 is described here and is an extension of Sun's symbol versioning scheme described here.

One option is to statically link your binary. This is probably the easiest option.

You could also build your binary in a chroot build environment, or using a glibc-new => glibc-old cross-compiler.

According to the http://www.trevorpounds.com blog post Linking to Older Versioned Symbols (glibc), it is possible to to force any symbol to be linked against an older one so long as it is valid by using the same .symver pseudo-op that is used for defining versioned symbols in the first place. The following example is excerpted from the blog post.

The following example makes use of glibc’s realpath, but makes sure it is linked against an older 2.2.5 version.

#include <limits.h>
#include <stdlib.h>
#include <stdio.h>

__asm__(".symver realpath,realpath@GLIBC_2.2.5");
int main()
{
    const char* unresolved = "/lib64";
    char resolved[PATH_MAX+1];

    if(!realpath(unresolved, resolved))
        { return 1; }

    printf("%s\n", resolved);

    return 0;
}

Using $window or $location to Redirect in AngularJS

Not sure from what version, but I use 1.3.14 and you can just use:

window.location.href = '/employee/1';

No need to inject $location or $window in the controller and no need to get the current host address.

Fastest way to convert a dict's keys & values from `unicode` to `str`?

>>> d = {u"a": u"b", u"c": u"d"}
>>> d
{u'a': u'b', u'c': u'd'}
>>> import json
>>> import yaml
>>> d = {u"a": u"b", u"c": u"d"}
>>> yaml.safe_load(json.dumps(d))
{'a': 'b', 'c': 'd'}

npm behind a proxy fails with status 403

In my case, I read the registry that npm using:

 npm config get registry

and I got

http://registry.npmjs.org/

then I had just changed http to https like this:

npm config set registry https://registry.npmjs.org/

jQuery get the name of a select option

For anyone who comes across this late, like me.

As others have stated, name isn't a valid attribute of an option element. Combining the accepted answer above with the answer from this other question, you get:

$(this).find('option:selected').text();

How to drop all tables from the database with manage.py CLI in Django?

Here's an example Makefile to do some nice things with multiple settings files:

test:
    python manage.py test --settings=my_project.test

db_drop:
    echo 'DROP DATABASE my_project_development;' | ./manage.py dbshell
    echo 'DROP DATABASE my_project_test;' | ./manage.py dbshell

db_create:
    echo 'CREATE DATABASE my_project_development;' | ./manage.py dbshell
    echo 'CREATE DATABASE my_project_test;' | ./manage.py dbshell

db_migrate:
    python manage.py migrate --settings=my_project.base
    python manage.py migrate --settings=my_project.test

db_reset: db_drop db_create db_migrate

.PHONY: test db_drop db_create db_migrate db_reset

Then you can do things like: $ make db_reset

How do I setup the dotenv file in Node.js?

I solved this using:

require('dotenv').config({path: __dirname + '/.env'})

or with an absolute path:

C:\\asd\\auhsd\\.env

If it does not find the .env file, it will return undefined.

GET URL parameter in PHP

The accepted answer is good. But if you have a scenario like this:

http://www.mydomain.me/index.php?state=California.php#Berkeley

You can treat the named anchor as a query string like this:

http://www.mydomain.me/index.php?state=California.php&city=Berkeley

Then, access it like this:

$Url = $_GET['state']."#".$_GET['city'];

Escape sequence \f - form feed - what exactly is it?

Although recently its use is undefined, a common and useful use for the form feed is to separate sections of code vertically, like so: enter image description here (from http://ergoemacs.org/emacs/emacs_form_feed_section_paging.html)

How do I append text to a file?

Follow up to accepted answer.

You need something other than CTRL-D to designate the end if using this in a script. Try this instead:

cat << EOF >> filename
This is text entered via the keyboard or via a script.
EOF

This will append text to the stated file (not including "EOF").

It utilizes a here document (or heredoc).

However if you need sudo to append to the stated file, you will run into trouble utilizing a heredoc due to I/O redirection if you're typing directly on the command line.

This variation will work when you are typing directly on the command line:

sudo sh -c 'cat << EOF >> filename
This is text entered via the keyboard.
EOF'

Or you can use tee instead to avoid the command line sudo issue seen when using the heredoc with cat:

tee -a filename << EOF
This is text entered via the keyboard or via a script.
EOF

How to convert date format to milliseconds?

beginupd.getTime() will give you time in milliseconds since January 1, 1970, 00:00:00 GMT till the time you have specified in Date object

How to deselect a selected UITableView cell?

Swift 4:

tableView.deselectRow(at: indexPath, animated: true)

How to calculate a logistic sigmoid function in Python?

I feel many might be interested in free parameters to alter the shape of the sigmoid function. Second for many applications you want to use a mirrored sigmoid function. Third you might want to do a simple normalization for example the output values are between 0 and 1.

Try:

def normalized_sigmoid_fkt(a, b, x):
   '''
   Returns array of a horizontal mirrored normalized sigmoid function
   output between 0 and 1
   Function parameters a = center; b = width
   '''
   s= 1/(1+np.exp(b*(x-a)))
   return 1*(s-min(s))/(max(s)-min(s)) # normalize function to 0-1

And to draw and compare:

def draw_function_on_2x2_grid(x): 
    fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
    plt.subplots_adjust(wspace=.5)
    plt.subplots_adjust(hspace=.5)

    ax1.plot(x, normalized_sigmoid_fkt( .5, 18, x))
    ax1.set_title('1')

    ax2.plot(x, normalized_sigmoid_fkt(0.518, 10.549, x))
    ax2.set_title('2')

    ax3.plot(x, normalized_sigmoid_fkt( .7, 11, x))
    ax3.set_title('3')

    ax4.plot(x, normalized_sigmoid_fkt( .2, 14, x))
    ax4.set_title('4')
    plt.suptitle('Different normalized (sigmoid) function',size=10 )

    return fig

Finally:

x = np.linspace(0,1,100)
Travel_function = draw_function_on_2x2_grid(x)

Sigmoid functions graph

Using ListView : How to add a header view?

I found out that inflating the header view as:

inflater.inflate(R.layout.listheader, container, false);

being container the Fragment's ViewGroup, inflates the headerview with a LayoutParam that extends from FragmentLayout but ListView expect it to be a AbsListView.LayoutParams instead.

So, my problem was solved solved by inflating the header view passing the list as container:

ListView list = fragmentview.findViewById(R.id.listview);
View headerView = inflater.inflate(R.layout.listheader, list, false);

then

list.addHeaderView(headerView, null, false);

Kinda late answer but I hope this can help someone

python ignore certificate validation urllib2

In the meantime urllib2 seems to verify server certificates by default. The warning, that was shown in the past disappeared for 2.7.9 and I currently ran into this problem in a test environment with a self signed certificate (and Python 2.7.9).

My evil workaround (don't do this in production!):

import urllib2
import ssl

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

urllib2.urlopen("https://your-test-server.local", context=ctx)

According to docs calling SSLContext constructor directly should work, too. I haven't tried that.

How to find and return a duplicate value in array

Alas most of the answers are O(n^2).

Here is an O(n) solution,

a = %w{the quick brown fox jumps over the lazy dog}
h = Hash.new(0)
a.find { |each| (h[each] += 1) == 2 } # => 'the"

What is the complexity of this?

  • Runs in O(n) and breaks on first match
  • Uses O(n) memory, but only the minimal amount

Now, depending on how frequent duplicates are in your array these runtimes might actually become even better. For example if the array of size O(n) has been sampled from a population of k << n different elements only the complexity for both runtime and space becomes O(k), however it is more likely that the original poster is validating input and wants to make sure there are no duplicates. In that case both runtime and memory complexity O(n) since we expect the elements to have no repetitions for the majority of inputs.

Open file dialog box in JavaScript

The only without <input type="file"> is by embedding a transparent flash movie over the div. You can then use a user generated click event (compliant with Flash 10 new security rules) to trigger a call to flash's FileReference.browse.

It offers an added dependency over the quirksmode way but in return you get alot more events (such as built in progress events).

Get integer value of the current year in Java

tl;dr

ZonedDateTime.now(  ZoneId.of( "Africa/Casablanca" )  )
             .getYear()

Time Zone

The answer by Raffi Khatchadourian wisely shows how to use the new java.time package in Java 8. But that answer fails to address the critical issue of time zone in determining a date.

int year = LocalDate.now().getYear();

That code depends on the JVM's current default time zone. The default zone is used in determining what today’s date is. Remember, for example, that in the moment after midnight in Paris the date in Montréal is still 'yesterday'.

So your results may vary by what machine it runs on, a user/admin changing the host OS time zone, or any Java code at any moment changing the JVM's current default. Better to specify the time zone.

By the way, always use proper time zone names as defined by the IANA. Never use the 3-4 letter codes that are neither standardized nor unique.

java.time

Example in java.time of Java 8.

int year = ZonedDateTime.now(  ZoneId.of( "Africa/Casablanca" )  ).getYear() ;

Joda-Time

Some idea as above, but using the Joda-Time 2.7 library.

int year = DateTime.now( DateTimeZone.forID( "Africa/Casablanca" ) ).getYear() ;

Incrementing/Decrementing Year

If your goal is to jump a year at a time, no need to extract the year number. Both Joda-Time and java.time have methods for adding/subtracting a year at a time. And those methods are smart, handling Daylight Saving Time and other anomalies.

Example in java.time.

ZonedDateTime zdt = 
    ZonedDateTime
    .now(  ZoneId.of( "Africa/Casablanca" )  )
    .minusYears( 1 ) 
;

Example in Joda-Time 2.7.

DateTime oneYearAgo = DateTime.now( DateTimeZone.forID( "Africa/Casablanca" ) ).minusYears( 1 ) ;

Add CSS box shadow around the whole DIV

Use this below code

 border:2px soild #eee;

 margin: 15px 15px;
 -webkit-box-shadow: 2px 3px 8px #eee;
-moz-box-shadow: 2px 3px 8px #eee;
box-shadow: 2px 3px 8px #eee;

Explanation:-

box-shadow requires you to set the horizontal & vertical offsets, you can then optionally set the blur and colour, you can also choose to have the shadow inset instead of the default outset. Colour can be defined as hex or rgba.

box-shadow : inset/outset h-offset v-offset blur spread color;

Explanation of the values...

inset/outset -- whether the shadow is inside or outside the box. If not specified it will default to outset.

h-offset -- the horizontal offset of the shadow (required value)

v-offset -- the vertical offset of the shadow (required value)

blur -- as it says, the blur of the shadow

spread -- moves the shadow away from the box equally on all sides. A positive value causes the shadow to expand, negative causes it to contract. Though this value isn't often used, it is useful with multiple shadows.

color -- as it says, the color of the shadow

Usage

box-shadow:2px 3px 8px #eee; a gray shadow with a horizontal outset of 2px, vertical of 3px and a blur of 8px

Docker: How to delete all local Docker images

Use this to delete everything:

docker system prune -a --volumes

Remove all unused containers, volumes, networks and images

WARNING! This will remove:
    - all stopped containers
    - all networks not used by at least one container
    - all volumes not used by at least one container
    - all images without at least one container associated to them
    - all build cache

https://docs.docker.com/engine/reference/commandline/system_prune/#extended-description

How does Git handle symbolic links?

Git just stores the contents of the link (i.e. the path of the file system object that it links to) in a 'blob' just like it would for a normal file. It then stores the name, mode and type (including the fact that it is a symlink) in the tree object that represents its containing directory.

When you checkout a tree containing the link, it restores the object as a symlink regardless of whether the target file system object exists or not.

If you delete the file that the symlink references it doesn't affect the Git-controlled symlink in any way. You will have a dangling reference. It is up to the user to either remove or change the link to point to something valid if needed.

MySQLi prepared statements error reporting

Completeness

You need to check both $mysqli and $statement. If they are false, you need to output $mysqli->error or $statement->error respectively.

Efficiency

For simple scripts that may terminate, I use simple one-liners that trigger a PHP error with the message. For a more complex application, an error warning system should be activated instead, for example by throwing an exception.

Usage example 1: Simple script

# This is in a simple command line script
$mysqli = new mysqli('localhost', 'buzUser', 'buzPassword');
$q = "UPDATE foo SET bar=1";
($statement = $mysqli->prepare($q)) or trigger_error($mysqli->error, E_USER_ERROR);
$statement->execute() or trigger_error($statement->error, E_USER_ERROR);

Usage example 2: Application

# This is part of an application
class FuzDatabaseException extends Exception {
}

class Foo {
  public $mysqli;
  public function __construct(mysqli $mysqli) {
    $this->mysqli = $mysqli;
  }
  public function updateBar() {
    $q = "UPDATE foo SET bar=1";
    $statement = $this->mysqli->prepare($q);
    if (!$statement) {
      throw new FuzDatabaseException($mysqli->error);
    }

    if (!$statement->execute()) {
      throw new FuzDatabaseException($statement->error);
    }
  }
}

$foo = new Foo(new mysqli('localhost','buzUser','buzPassword'));
try {
  $foo->updateBar();
} catch (FuzDatabaseException $e)
  $msg = $e->getMessage();
  // Now send warning emails, write log
}

Python: Find index of minimum item in list of floats

I think it's worth putting a few timings up here for some perspective.

All timings done on OS-X 10.5.8 with python2.7

John Clement's answer:

python -m timeit -s 'my_list = range(1000)[::-1]; from operator import itemgetter' 'min(enumerate(my_list),key=itemgetter(1))'
1000 loops, best of 3: 239 usec per loop    

David Wolever's answer:

python -m timeit -s 'my_list = range(1000)[::-1]' 'min((val, idx) for (idx, val) in enumerate(my_list))
1000 loops, best of 3: 345 usec per loop

OP's answer:

python -m timeit -s 'my_list = range(1000)[::-1]' 'my_list.index(min(my_list))'
10000 loops, best of 3: 96.8 usec per loop

Note that I'm purposefully putting the smallest item last in the list to make .index as slow as it could possibly be. It would be interesting to see at what N the iterate once answers would become competitive with the iterate twice answer we have here.

Of course, speed isn't everything and most of the time, it's not even worth worrying about ... choose the one that is easiest to read unless this is a performance bottleneck in your code (and then profile on your typical real-world data -- preferably on your target machines).

Disable / Check for Mock Location (prevent gps spoofing)

try this code its very simple and usefull

  public boolean isMockLocationEnabled() {
        boolean isMockLocation = false;
        try {
            //if marshmallow
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                AppOpsManager opsManager = (AppOpsManager) getApplicationContext().getSystemService(Context.APP_OPS_SERVICE);
                isMockLocation = (opsManager.checkOp(AppOpsManager.OPSTR_MOCK_LOCATION, android.os.Process.myUid(), BuildConfig.APPLICATION_ID)== AppOpsManager.MODE_ALLOWED);
            } else {
                // in marshmallow this will always return true
                isMockLocation = !android.provider.Settings.Secure.getString(getApplicationContext().getContentResolver(), "mock_location").equals("0");
            }
        } catch (Exception e) {
            return isMockLocation;
        }
        return isMockLocation;
    }

Clear ComboBox selected text

The only way I could get it to work:

comboBox1.Text = "";

For some reason ionden's solution didn't work for me.

keyCode values for numeric keypad?

******************* Don't use KEYCODE !!!! ******************

The problem with keyCode is to avoid the combined keys with the numbers on top of keyboard, we must add a check on the key "Shift" and "Alt" to avoid special characters such as e @ & " { } ...

A simplest solution is to convert e.key to a number and check if the conversion gives NaN!

let key = Number(e.key)
if (isNaN(key) || e.key === null || e.key === ' ') {
  console.log("is not numeric")
}
else {
  console.log("is numeric")
}

Be careful if e.key is null or a space, it gives 0 !

Number(5)         // => 5
Number('5')       // => 5
Number(null)      // => 0 
Number(' ')       // => 0
Number('chars')   // => NaN
Number(undefined) // => NaN

What do Clustered and Non clustered index actually mean?

With a clustered index the rows are stored physically on the disk in the same order as the index. Therefore, there can be only one clustered index.

With a non clustered index there is a second list that has pointers to the physical rows. You can have many non clustered indices, although each new index will increase the time it takes to write new records.

It is generally faster to read from a clustered index if you want to get back all the columns. You do not have to go first to the index and then to the table.

Writing to a table with a clustered index can be slower, if there is a need to rearrange the data.

Creating an array from a text file in Bash

Use mapfile or read -a

Always check your code using shellcheck. It will often give you the correct answer. In this case SC2207 covers reading a file that either has space separated or newline separated values into an array.

Don't do this

array=( $(mycommand) )

Files with values separated by newlines

mapfile -t array < <(mycommand)

Files with values separated by spaces

IFS=" " read -r -a array <<< "$(mycommand)"

The shellcheck page will give you the rationale why this is considered best practice.

How to scanf only integer?

I know how this can be done using fgets and strtol, I would like to know how this can be done using scanf() (if possible).

As the other answers say, scanf isn't really suitable for this, fgets and strtol is an alternative (though fgets has the drawback that it's hard to detect a 0-byte in the input and impossible to tell what has been input after a 0-byte, if any).

For sake of completeness (and assuming valid input is an integer followed by a newline):

while(scanf("%d%1[\n]", &n, (char [2]){ 0 }) < 2)

Alternatively, use %n before and after %*1[\n] with assignment-suppression. Note, however (from the Debian manpage):

This is not a conversion, although it can be suppressed with the * assignment-suppression character. The C standard says: "Execution of a %n directive does not increment the assignment count returned at the completion of execution" but the Corrigendum seems to contradict this. Probably it is wise not to make any assumptions on the effect of %n conversions on the return value.

C# - Making a Process.Start wait until the process has start-up

I used the EventWaitHandle class. On the parent process, create a named EventWaitHandle with initial state of the event set to non-signaled. The parent process blocks until the child process calls the Set method, changing the state of the event to signaled, as shown below.

Parent Process:

using System;
using System.Threading;
using System.Diagnostics;

namespace MyParentProcess
{
    class Program
    {
        static void Main(string[] args)
        {
            EventWaitHandle ewh = null;
            try
            {
                ewh = new EventWaitHandle(false, EventResetMode.AutoReset, "CHILD_PROCESS_READY");

                Process process = Process.Start("MyChildProcess.exe", Process.GetCurrentProcess().Id.ToString());
                if (process != null)
                {
                    if (ewh.WaitOne(10000))
                    {
                        // Child process is ready.
                    }
                }
            }
            catch(Exception exception)
            { }
            finally
            {
                if (ewh != null)
                    ewh.Close();
            }
        }
    }
}

Child Process:

using System;
using System.Threading;
using System.Diagnostics;

namespace MyChildProcess
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // Representing some time consuming work.
                Thread.Sleep(5000);

                EventWaitHandle.OpenExisting("CHILD_PROCESS_READY")
                    .Set();

                Process.GetProcessById(Convert.ToInt32(args[0]))
                    .WaitForExit();
            }
            catch (Exception exception)
            { }
        }
    }
}

Drop shadow on a div container?

CSS3 has a box-shadow property. Vendor prefixes are required at the moment for maximum browser compatibility.

div.box-shadow {
    -webkit-box-shadow: 2px 2px 4px 1px #fff;
    box-shadow: 2px 2px 4px 1px #fff;
}

There is a generator available at css3please.

Modular multiplicative inverse function in Python

Python 3.8+

y = pow(x, -1, p)

Python 3.7 and earlier

Maybe someone will find this useful (from wikibooks):

def egcd(a, b):
    if a == 0:
        return (b, 0, 1)
    else:
        g, y, x = egcd(b % a, a)
        return (g, x - (b // a) * y, y)

def modinv(a, m):
    g, x, y = egcd(a, m)
    if g != 1:
        raise Exception('modular inverse does not exist')
    else:
        return x % m

PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

@OneToMany(mappedBy = "xxxx", cascade={CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REMOVE}) worked for me.

How do I tell Gradle to use specific JDK version?

As seen in Gradle (Eclipse plugin)

http://www.gradle.org/get-started

Gradle uses whichever JDK it finds in your path (to check, use java -version). Alternatively, you can set the JAVA_HOME environment variable to point to the install directory of the desired JDK.


If you are using this Eclipse plugin or Enide Studio 2014, alternative JAVA_HOME to use (set in Preferences) will be in version 0.15, see http://www.nodeclipse.org/history

php error: Class 'Imagick' not found

For MAMP running on Mac OSX

Find out the what version of PHP and install the right version via brew

brew install homebrew/php/php56-imagick

Add the extension by modifying the php.ini template in MAMP

enter image description here

Verify the Imagick

enter image description here

Fetch API request timeout?

Building on Endless' excellent answer, I created a helpful utility function.

const fetchTimeout = (url, ms, { signal, ...options } = {}) => {
    const controller = new AbortController();
    const promise = fetch(url, { signal: controller.signal, ...options });
    if (signal) signal.addEventListener("abort", () => controller.abort());
    const timeout = setTimeout(() => controller.abort(), ms);
    return promise.finally(() => clearTimeout(timeout));
};
  1. If the timeout is reached before the resource is fetched then the fetch is aborted.
  2. If the resource is fetched before the timeout is reached then the timeout is cleared.
  3. If the input signal is aborted then the fetch is aborted and the timeout is cleared.
const controller = new AbortController();

document.querySelector("button.cancel").addEventListener("click", () => controller.abort());

fetchTimeout("example.json", 5000, { signal: controller.signal })
    .then(response => response.json())
    .then(console.log)
    .catch(error => {
        if (error.name === "AbortError") {
            // fetch aborted either due to timeout or due to user clicking the cancel button
        } else {
            // network error or json parsing error
        }
    });

Hope that helps.

Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop

A ListIterator allows you to add or remove items in the list. Suppose you have a list of Car objects:

List<Car> cars = ArrayList<>();
// add cars here...

for (ListIterator<Car> carIterator = cars.listIterator();  carIterator.hasNext(); )
{
   if (<some-condition>)
   { 
      carIterator().remove()
   }
   else if (<some-other-condition>)
   { 
      carIterator().add(aNewCar);
   }
}

SQL Server - Convert date field to UTC

I'm a bit late to the game but I needed to do something like this on SQL 2012, I haven't fully tested it yet but here is what I came up with.

CREATE FUNCTION SMS.fnConvertUTC
(
    @DateCST datetime
)
RETURNS DATETIME
AS
BEGIN
    RETURN 
        CASE 
        WHEN @DateCST 
            BETWEEN 
                CASE WHEN @DateCST > '2007-01-01' 
                THEN CONVERT(DATETIME, CONVERT(VARCHAR,YEAR(@DateCST)) + '-MAR-14 02:00') - DATEPART(DW,CONVERT(VARCHAR,YEAR(@DateCST)) + '-MAR-14 02:00' ) + 1
                ELSE CONVERT(DATETIME, CONVERT(VARCHAR,YEAR(@DateCST)) + '-APR-07 02:00') - DATEPART(DW,CONVERT(VARCHAR,YEAR(@DateCST)) + '-APR-07 02:00' ) + 1 END
            AND
                CASE WHEN @DateCST > '2007-01-01' 
                THEN CONVERT(DATETIME, CONVERT(VARCHAR,YEAR(@DateCST)) + '-NOV-07 02:00') - DATEPART(DW,CONVERT(VARCHAR,YEAR(@DateCST)) + '-NOV-07 02:00' ) + 1
                ELSE CONVERT(DATETIME, CONVERT(VARCHAR,YEAR(@DateCST)) + '-OCT-31 02:00') - DATEPART(DW,CONVERT(VARCHAR,YEAR(@DateCST)) + '-OCT-31 02:00' ) + 1 END
        THEN DATEADD(HOUR,4,@DateCST)
        ELSE DATEADD(HOUR,5,@DateCST) 
        END
END

Above someone posted a static list DST dates so I wrote the below query to compare this code's output to that list... so far it looks correct.

;WITH DT AS 
( 
    SELECT MyDate = GETDATE() 
    UNION ALL 
    SELECT MyDate = DATEADD(YEAR,-1,MyDate) FROM DT
    WHERE DATEADD(YEAR,-1,MyDate) > DATEADD(YEAR, -30, GETDATE())
)
SELECT 
    SpringForward = CASE 
        WHEN MyDate > '2007-01-01' 
        THEN CONVERT(DATETIME, CONVERT(VARCHAR,YEAR(MyDate)) + '-MAR-14 02:00') - DATEPART(DW,CONVERT(VARCHAR,YEAR(MyDate)) + '-MAR-14 02:00' ) + 1
        ELSE CONVERT(DATETIME, CONVERT(VARCHAR,YEAR(MyDate)) + '-APR-07 02:00') - DATEPART(DW,CONVERT(VARCHAR,YEAR(MyDate)) + '-APR-07 02:00' ) + 1 END
,   FallBackward  = CASE 
        WHEN MyDate > '2007-01-01' 
        THEN CONVERT(DATETIME, CONVERT(VARCHAR,YEAR(MyDate)) + '-NOV-07 02:00') - DATEPART(DW,CONVERT(VARCHAR,YEAR(MyDate)) + '-NOV-07 02:00' ) + 1
        ELSE CONVERT(DATETIME, CONVERT(VARCHAR,YEAR(MyDate)) + '-OCT-31 02:00') - DATEPART(DW,CONVERT(VARCHAR,YEAR(MyDate)) + '-OCT-31 02:00' ) + 1 END
FROM DT
ORDER BY 1 DESC
SpringForward      FallBackward
----------------   ----------------
2020-03-08 02:00   2020-11-01 02:00
2019-03-10 02:00   2019-11-03 02:00
2018-03-11 02:00   2018-11-04 02:00
2017-03-12 02:00   2017-11-05 02:00
2016-03-13 02:00   2016-11-06 02:00
2015-03-08 02:00   2015-11-01 02:00
2014-03-09 02:00   2014-11-02 02:00
2013-03-10 02:00   2013-11-03 02:00
2012-03-11 02:00   2012-11-04 02:00
2011-03-13 02:00   2011-11-06 02:00
2010-03-14 02:00   2010-11-07 02:00
2009-03-08 02:00   2009-11-01 02:00
2008-03-09 02:00   2008-11-02 02:00
2007-03-11 02:00   2007-11-04 02:00
2006-04-02 02:00   2006-10-29 02:00
2005-04-03 02:00   2005-10-30 02:00
2004-04-04 02:00   2004-10-31 02:00
2003-04-06 02:00   2003-10-26 02:00
2002-04-07 02:00   2002-10-27 02:00
2001-04-01 02:00   2001-10-28 02:00
2000-04-02 02:00   2000-10-29 02:00
1999-04-04 02:00   1999-10-31 02:00
1998-04-05 02:00   1998-10-25 02:00
1997-04-06 02:00   1997-10-26 02:00
1996-04-07 02:00   1996-10-27 02:00
1995-04-02 02:00   1995-10-29 02:00
1994-04-03 02:00   1994-10-30 02:00
1993-04-04 02:00   1993-10-31 02:00
1992-04-05 02:00   1992-10-25 02:00
1991-04-07 02:00   1991-10-27 02:00

(30 row(s) affected)

C++ Calling a function from another class

    void CallFunction ()
    {   // <----- At this point the compiler knows
        //        nothing about the members of B.
        B b;
        b.bFunction();
    }

This happens for the same reason that functions in C cannot call each other without at least one of them being declared as a function prototype.

To fix this issue we need to make sure both classes are declared before they are used. We separate the declaration from the definition. This MSDN article explains in more detail about the declarations and definitions.

class A
{
public:
    void CallFunction ();
};

class B: public A
{
public:
    virtual void bFunction()
    { ... }
};

void A::CallFunction ()
{
    B b;
    b.bFunction();
}

How much faster is C++ than C#?

We have had to determine if C# was comparable to C++ in performance and I wrote some test programs for that (using Visual Studio 2005 for both languages). It turned out that without garbage collection and only considering the language (not the framework) C# has basically the same performance as C++. Memory allocation is way faster in C# than in C++ and C# has a slight edge in determinism when data sizes are increased beyond cache line boundaries. However, all of this had eventually to be paid for and there is a huge cost in the form of non-deterministic performance hits for C# due to garbage collection.

Anonymous method in Invoke call

For the sake of completeness, this can also be accomplished via an Action method/anonymous method combination:

//Process is a method, invoked as a method group
Dispatcher.Current.BeginInvoke((Action) Process);
//or use an anonymous method
Dispatcher.Current.BeginInvoke((Action)delegate => {
  SomeFunc();
  SomeOtherFunc();
});

AngularJS toggle class using ng-class

As alternate solution, based on javascript logic operator '&&' which returns the last evaluation, you can also do this like so:

<i ng-class="autoScroll && 'icon-autoscroll' || !autoScroll && 'icon-autoscroll-disabled'"></i>

It's only slightly shorter syntax, but for me easier to read.

PHP 5 disable strict standards error

All above solutions are correct. But, when we are talking about a normal PHP application, they have to included in every page, that it requires. A way to solve this, is through .htaccess at root folder. Just to hide the errors. [Put one of the followling lines in the file]

php_flag display_errors off

Or

php_value display_errors 0

Next, to set the error reporting

php_value error_reporting 30719

If you are wondering how the value 30719 came, E_ALL (32767), E_STRICT (2048) are actually constant that hold numeric value and (32767 - 2048 = 30719)

Check file uploaded is in csv format

There are a lot of possible MIME types for CSV files, depending on the user's OS and browser version.

This is how I currently validate the MIME types of my CSV files:

$csv_mimetypes = array(
    'text/csv',
    'text/plain',
    'application/csv',
    'text/comma-separated-values',
    'application/excel',
    'application/vnd.ms-excel',
    'application/vnd.msexcel',
    'text/anytext',
    'application/octet-stream',
    'application/txt',
);

if (in_array($_FILES['upload']['type'], $csv_mimetypes)) {
    // possible CSV file
    // could also check for file content at this point
}

how to add the missing RANDR extension

I had the same problem with Firefox 30 + Selenium 2.49 + Ubuntu 15.04.

It worked fine with Ubuntu 14 but after upgrade to 15.04 I got same RANDR warning and problem at starting Firefox using Xfvb.

After adding +extension RANDR it worked again.

$ vim /etc/init/xvfb.conf

#!upstart
description "Xvfb Server as a daemon"

start on filesystem and started networking
stop on shutdown

respawn

env XVFB=/usr/bin/Xvfb
env XVFBARGS=":10 -screen 1 1024x768x24 -ac +extension GLX +extension RANDR +render -noreset"
env PIDFILE=/var/run/xvfb.pid

exec start-stop-daemon --start --quiet --make-pidfile --pidfile $PIDFILE --exec $XVFB -- $XVFBARGS >> /var/log/xvfb.log 2>&1

How to customize message box

MessageBox::Show uses function from user32.dll, and its style is dependent on Windows, so you cannot change it like that, you have to create your own form

Remove elements from collection while iterating

Are there any reasons to prefer one approach over the other

The first approach will work, but has the obvious overhead of copying the list.

The second approach will not work because many containers don't permit modification during iteration. This includes ArrayList.

If the only modification is to remove the current element, you can make the second approach work by using itr.remove() (that is, use the iterator's remove() method, not the container's). This would be my preferred method for iterators that support remove().

org.glassfish.jersey.servlet.ServletContainer ClassNotFoundException

I had the same problem with eclipse, the WA solution was to copy the libs to WEB-INF/lib

Where/how can I download (and install) the Microsoft.Jet.OLEDB.4.0 for Windows 8, 64 bit?

On modern Windows this driver isn't available by default anymore, but you can download as Microsoft Access Database Engine 2010 Redistributable on the MS site. If your app is 32 bits be sure to download and install the 32 bits variant because to my knowledge the 32 and 64 bit variant cannot coexist.

Depending on how your app locates its db driver, that might be all that's needed. However, if you use an UDL file there's one extra step - you need to edit that file. Unfortunately, on a 64bits machine the wizard used to edit UDL files is 64 bits by default, it won't see the JET driver and just slap whatever driver it finds first in the UDL file. There are 2 ways to solve this issue:

  1. start the 32 bits UDL wizard like this: C:\Windows\syswow64\rundll32.exe "C:\Program Files (x86)\Common Files\System\Ole DB\oledb32.dll",OpenDSLFile C:\path\to\your.udl. Note that I could use this technique on a Win7 64 Pro, but it didn't work on a Server 2008R2 (could be my mistake, just mentioning)
  2. open the UDL file in Notepad or another text editor, it should more or less have this format:

[oledb] ; Everything after this line is an OLE DB initstring Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Path\To\The\database.mdb;Persist Security Info=False

That should allow your app to start correctly.

Count table rows

You have to use count() returns the number of rows that matches a specified criteria

select count(*) from table_name;

How to run python script in webpage

In order for your code to show, you need several things:

Firstly, there needs to be a server that handles HTTP requests. At the moment you are just opening a file with Firefox on your local hard drive. A server like Apache or something similar is required.

Secondly, presuming that you now have a server that serves the files, you will also need something that interprets the code as Python code for the server. For Python users the go to solution is nowadays mod_wsgi. But for simpler cases you could stick with CGI (more info here), but if you want to produce web pages easily, you should go with a existing Python web framework like Django.

Setting this up can be quite the hassle, so be prepared.

Postgresql Select rows where column = array

For dynamic SQL use:

'IN(' ||array_to_string(some_array, ',')||')'

Example

DO LANGUAGE PLPGSQL $$

DECLARE
    some_array bigint[];
    sql_statement text;

BEGIN

    SELECT array[1, 2] INTO some_array;
    RAISE NOTICE '%', some_array;

    sql_statement := 'SELECT * FROM my_table WHERE my_column IN(' ||array_to_string(some_array, ',')||')';
    RAISE NOTICE '%', sql_statement;

END;

$$;

Result: NOTICE: {1,2} NOTICE: SELECT * FROM my_table WHERE my_column IN(1,2)

LINQ Using Max() to select a single row

Addressing the first question, if you need to take several rows grouped by certain criteria with the other column with max value you can do something like this:

var query =
    from u1 in table
    join u2 in (
        from u in table
        group u by u.GroupId into g
        select new { GroupId = g.Key, MaxStatus = g.Max(x => x.Status) }
    ) on new { u1.GroupId, u1.Status } equals new { u2.GroupId, Status = u2.MaxStatus}
    select u1;

Read from file or stdin

You can just read from stdin unless the user supply a filename ?

If not, treat the special "filename" - as meaning "read from stdin". The user would have to start the program like cat file | myprogram - if he wants to pipe data to it, and myprogam file if he wants it to read from a file.

int main(int argc,char *argv[] ) {
  FILE *input;
  if(argc != 2) {
     usage();
     return 1;
   }
   if(!strcmp(argv[1],"-")) {
     input = stdin;
    } else {
      input = fopen(argv[1],"rb");
      //check for errors
    }

If you're on *nix, you can check whether stdin is a fifo:

 struct stat st_info;
 if(fstat(0,&st_info) != 0)
   //error
  }
  if(S_ISFIFO(st_info.st_mode)) {
     //stdin is a pipe
  }

Though that won't handle the user doing myprogram <file

You can also check if stdin is a terminal/console

if(isatty(0)) {
  //stdin is a terminal
}

I want to show all tables that have specified column name

Pretty simple on a per database level

Use DatabaseName
Select * From INFORMATION_SCHEMA.COLUMNS Where column_name = 'ColName'

How to put a jpg or png image into a button in HTML

you can also try something like this as well

<input type="button" value="text" name="text" onClick="{action}; return false" class="fwm_button">

and CSS class

.fwm_button {
   color: white;
   font-weight: bold;
   background-color: #6699cc;
   border: 2px outset;
   border-top-color: #aaccff;
   border-left-color: #aaccff;
   border-right-color: #003366;
   border-bottom-color: #003366;
 }

An example is given here

Cut Corners using CSS

You can use clip-path, as Stewartside and Sviatoslav Oleksiv mentioned. To make things easy, I created a sass mixin:

@mixin cut-corners ($left-top, $right-top: 0px, $right-bottom: 0px, $left-bottom: 0px) {
  clip-path: polygon($left-top 0%, calc(100% - #{$right-top}) 0%, 100% $right-top, 100% calc(100% - #{$right-bottom}), calc(100% - #{$right-bottom}) 100%, $left-bottom 100%, 0% calc(100% - #{$left-bottom}), 0% $left-top);
}

.cut-corners {
  @include cut-corners(10px, 0, 25px, 50px);
}

Test for multiple cases in a switch, like an OR (||)

Forget switch and break, lets play with if. And instead of asserting

if(pageid === "listing-page" || pageid === "home-page")

lets create several arrays with cases and check it with Array.prototype.includes()

var caseA = ["listing-page", "home-page"];
var caseB = ["details-page", "case04", "case05"];

if(caseA.includes(pageid)) {
    alert("hello");
}
else if (caseB.includes(pageid)) {
    alert("goodbye");
}
else {
    alert("there is no else case");
}

Copy values from one column to another in the same table

Following worked for me..

  1. Ensure you are not using Safe-mode in your query editor application. If you are, disable it!
  2. Then run following sql command

for a table say, 'test_update_cmd', source value column col2, target value column col1 and condition column col3: -

UPDATE  test_update_cmd SET col1=col2 WHERE col3='value';

Good Luck!

Warning - Build path specifies execution environment J2SE-1.4

Just change the version in Window-> Preferences-> Java -> Installed JREs. Check the installed JREs list. Then, Right-click on your project -> properties -> Java build path -> libraries. Change the "JRE System Library" to the version in "installed JREs".

The warning will be gone.

what is an illegal reflective access

There is an Oracle article I found regarding Java 9 module system

By default, a type in a module is not accessible to other modules unless it’s a public type and you export its package. You expose only the packages you want to expose. With Java 9, this also applies to reflection.

As pointed out in https://stackoverflow.com/a/50251958/134894, the differences between the AccessibleObject#setAccessible for JDK8 and JDK9 are instructive. Specifically, JDK9 added

This method may be used by a caller in class C to enable access to a member of declaring class D if any of the following hold:

  • C and D are in the same module.
  • The member is public and D is public in a package that the module containing D exports to at least the module containing C.
  • The member is protected static, D is public in a package that the module containing D exports to at least the module containing C, and C is a subclass of D.
  • D is in a package that the module containing D opens to at least the module containing C. All packages in unnamed and open modules are open to all modules and so this method always succeeds when D is in an unnamed or open module.

which highlights the significance of modules and their exports (in Java 9)

Automatic exit from Bash shell script on error

One idiom is:

cd some_dir && ./configure --some-flags && make && make install

I realize that can get long, but for larger scripts you could break it into logical functions.

Broken references in Virtualenvs

I was facing the same issue after upgrading brew on my OSX Catalina.

After trying bunch of stuffs, I find the following is the best and easy solution.

At first, delete the virtual env. (Optional)

find myvirtualenv -type l -delete

then recreate a new virtualenv

virtualenv myvirtualenv

Reference: https://www.jeremycade.com/python/osx/homebrew/2015/03/02/fixing-virtualenv-after-a-python-upgrade/

Are there any style options for the HTML5 Date picker?

found this on Zurb's github

In case you want to do some more custom styling. Here's all the default CSS for webkit rendering of the date components.

input[type="date"] {
     -webkit-align-items: center;
     display: -webkit-inline-flex;
     font-family: monospace;
     overflow: hidden;
     padding: 0;
     -webkit-padding-start: 1px;
}

input::-webkit-datetime-edit {
    -webkit-flex: 1;
    -webkit-user-modify: read-only !important;
    display: inline-block;
    min-width: 0;
    overflow: hidden;
}

input::-webkit-datetime-edit-fields-wrapper {
    -webkit-user-modify: read-only !important;
    display: inline-block;
    padding: 1px 0;
    white-space: pre;
}

How do I format date value as yyyy-mm-dd using SSIS expression builder?

Correct expression is

"source " + (DT_STR,4,1252)DATEPART( "yyyy" , getdate() ) + "-" +
RIGHT("0" + (DT_STR,4,1252)DATEPART( "mm" , getdate() ), 2) + "-" +
RIGHT("0" + (DT_STR,4,1252)DATEPART( "dd" , getdate() ), 2) +".CSV"

PostgreSQL: Drop PostgreSQL database through command line

Try this. Note there's no database specified - it just runs "on the server"

psql -U postgres -c "drop database databasename"

If that doesn't work, I have seen a problem with postgres holding onto orphaned prepared statements.
To clean them up, do this:

SELECT * FROM pg_prepared_xacts;

then for every id you see, run this:

ROLLBACK PREPARED '<id>';

Cross-reference (named anchor) in markdown

For anyone who is looking for a solution to this problem in GitBook. This is how I made it work (in GitBook). You need to tag your header explicitly, like this:

# My Anchored Heading {#my-anchor}

Then link to this anchor like this

[link to my anchored heading](#my-anchor)

Solution, and additional examples, may be found here: https://seadude.gitbooks.io/learn-gitbook/

How to enable support of CPU virtualization on Macbook Pro?

CPU Virtualization is enabled by default on all MacBooks with compatible CPUs (i7 is compatible). You can try to reset PRAM if you think it was disabled somehow, but I doubt it.

I think the issue might be in the old version of OS. If your MacBook is i7, then you better upgrade OS to something newer.

Programmatically go back to previous ViewController in Swift

Try this: for the previous view use this:

navigationController?.popViewController(animated: true)  

pop to root use this code:

navigationController?.popToRootViewController(animated: true) 

Proper way to wait for one function to finish before continuing?

I wonder why no one have mentioned this simple pattern? :

(function(next) {
  //do something
  next()
}(function() {
  //do some more
}))

Using timeouts just for blindly waiting is bad practice; and involving promises just adds more complexity to the code. In OP's case:

(function(next) {
  for(i=0;i<x;i++){
    // do something
    if (i==x-1) next()
  }
}(function() {
  // now wait for firstFunction to finish...
  // do something else
}))

a small demo -> http://jsfiddle.net/5jdeb93r/

How to select Python version in PyCharm?

PyCharm 2019.1+

There is a new feature called Interpreter in status bar (scroll down a little bit). This makes switching between python interpreters and seeing which version you’re using easier.

enter image description here

Enable status bar

In case you cannot see the status bar, you can easily activate it by running the Find Action command (Ctrl+Shift+A or ?+ ?+A on mac). Then type status bar and choose View: Status Bar to see it.

enter image description here

Could not load the Tomcat server configuration

In the Servers tab of eclipse, go to the properties of the server and Switch location to latest downloaded tomcat version.

This resolved the issue for me.

Tomcat Server Properties

How to Truncate a string in PHP to the word closest to a certain number of characters?

This will return the first 200 characters of words:

preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, 201));

How to run wget inside Ubuntu Docker image?

You need to install it first. Create a new Dockerfile, and install wget in it:

FROM ubuntu:14.04
RUN  apt-get update \
  && apt-get install -y wget \
  && rm -rf /var/lib/apt/lists/*

Then, build that image:

docker build -t my-ubuntu .

Finally, run it:

docker run my-ubuntu wget https://downloads-packages.s3.amazonaws.com/ubuntu-14.04/gitlab_7.8.2-omnibus.1-1_amd64.deb

CSS how to make scrollable list

As per your question vertical listing have a scrollbar effect.

CSS / HTML :

_x000D_
_x000D_
nav ul{height:200px; width:18%;}_x000D_
nav ul{overflow:hidden; overflow-y:scroll;}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
    <head>_x000D_
        <meta charset="utf-8">_x000D_
        <title>JS Bin</title>_x000D_
    </head>_x000D_
    <body>_x000D_
        <header>header area</header>_x000D_
        <nav>_x000D_
            <ul>_x000D_
                <li>Link 1</li>_x000D_
                <li>Link 2</li>_x000D_
                <li>Link 3</li>_x000D_
                <li>Link 4</li>_x000D_
                <li>Link 5</li>_x000D_
                <li>Link 6</li> _x000D_
                <li>Link 7</li> _x000D_
                <li>Link 8</li>_x000D_
                <li>Link 9</li>_x000D_
                <li>Link 10</li>_x000D_
                <li>Link 11</li>_x000D_
                <li>Link 13</li>_x000D_
                <li>Link 13</li>_x000D_
_x000D_
            </ul>_x000D_
        </nav>_x000D_
        _x000D_
        <footer>footer area</footer>_x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Error: Cannot invoke an expression whose type lacks a call signature

This error can be caused when you are requesting a value from something and you put parenthesis at the end, as if it is a function call, yet the value is correctly retrieved without ending parenthesis. For example, if what you are accessing is a Property 'get' in Typescript.

private IMadeAMistakeHere(): void {
    let mynumber = this.SuperCoolNumber();
}

private IDidItCorrectly(): void {
    let mynumber = this.SuperCoolNumber;
}

private get SuperCoolNumber(): number {
    let response = 42;
    return response;
};

Change the location of an object programmatically

The Location property has type Point which is a struct.

Instead of trying to modify the existing Point, try assigning a new Point object:

 this.balancePanel.Location = new Point(
     this.optionsPanel.Location.X,
     this.balancePanel.Location.Y
 );

How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?

This may be relevant to a certain subset of people with this issue...perhaps in a different flavor.

I was forcing an https redirect on RELEASE.

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
  filters.Add(new HandleErrorAttribute());
  #if !DEBUG
  filters.Add(new RequireHttpsAttribute());
  #endif    
}

And there wasn't https enabled on my iis express. Working correctly on DEBUG

How to use Git?

Have a look at git for designers for great one page article/high level intro to the topic. (That link is broken: Here is a link to another Git for Designers )

I would start at http://git-scm.com/documentation, there are documents and great video presentations for non-software-developer/cs users. Git for beginners have some basic stuff.

Change arrow colors in Bootstraps carousel

With Font Awesome icons:

<!-- Controls -->
<a class="carousel-control-prev" href="#carousel-example-generic" role="button" data-slide="prev">
  <span class="fa fa-chevron-left fa-lg" style="color:red;"></span>
  <span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carousel-example-generic" role="button" data-slide="next">
  <span class="fa fa-chevron-right fa-lg" style="color:red;"></span>
  <span class="sr-only">Next</span>
</a>

No 'Access-Control-Allow-Origin' header is present on the requested resource- AngularJS

This is a CORS issue. There are some settings you can change in angular - these are the ones I typically set in the Angular .config method (not all are related to CORS):

$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.withCredentials = true;
delete $httpProvider.defaults.headers.common["X-Requested-With"];
$httpProvider.defaults.headers.common["Accept"] = "application/json";
$httpProvider.defaults.headers.common["Content-Type"] = "application/json";

You also need to configure your webservice - the details of this will depend on the server side language you are using. If you use a network monitoring tool you will see it sends an OPTIONS request initially. Your server needs to respond appropriately to allow the CORS request.

The reason it works in your brower is because it isn't make a cross-origin request - whereas your Angular code is.

How to prevent "The play() request was interrupted by a call to pause()" error?

I ran into the same issue and resolved it by dynamically adding the autoplay attribute rather than using play(). That way the browser figured out to play without running into the race condition.

How to check postgres user and password?

You may change the pg_hba.conf and then reload the postgresql. something in the pg_hba.conf may be like below:

# "local" is for Unix domain socket connections only
local   all             all                                     trust
# IPv4 local connections:
host    all             all             127.0.0.1/32            trust

then you change your user to postgresql, you may login successfully.

su postgresql

How to undo 'git reset'?

1.Use git reflog to get all references update.

2.git reset <id_of_commit_to_which_you_want_restore>

jQuery AJAX file upload PHP

You need a script that runs on the server to move the file to the uploads directory. The jQuery ajax method (running in the browser) sends the form data to the server, then a script on the server handles the upload. Here's an example using PHP.

Your HTML is fine, but update your JS jQuery script to look like this:

$('#upload').on('click', function() {
    var file_data = $('#sortpicture').prop('files')[0];   
    var form_data = new FormData();                  
    form_data.append('file', file_data);
    alert(form_data);                             
    $.ajax({
        url: 'upload.php', // point to server-side PHP script 
        dataType: 'text',  // what to expect back from the PHP script, if anything
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,                         
        type: 'post',
        success: function(php_script_response){
            alert(php_script_response); // display response from the PHP script, if any
        }
     });
});

And now for the server-side script, using PHP in this case.

upload.php: a PHP script that runs on the server and directs the file to the uploads directory:

<?php

    if ( 0 < $_FILES['file']['error'] ) {
        echo 'Error: ' . $_FILES['file']['error'] . '<br>';
    }
    else {
        move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
    }

?>

Also, a couple things about the destination directory:

  1. Make sure you have the correct server path, i.e., starting at the PHP script location what is the path to the uploads directory, and
  2. Make sure it's writeable.

And a little bit about the PHP function move_uploaded_file, used in the upload.php script:

move_uploaded_file(

    // this is where the file is temporarily stored on the server when uploaded
    // do not change this
    $_FILES['file']['tmp_name'],

    // this is where you want to put the file and what you want to name it
    // in this case we are putting in a directory called "uploads"
    // and giving it the original filename
    'uploads/' . $_FILES['file']['name']
);

$_FILES['file']['name'] is the name of the file as it is uploaded. You don't have to use that. You can give the file any name (server filesystem compatible) you want:

move_uploaded_file(
    $_FILES['file']['tmp_name'],
    'uploads/my_new_filename.whatever'
);

And finally, be aware of your PHP upload_max_filesize AND post_max_size configuration values, and be sure your test files do not exceed either. Here's some help how you check PHP configuration and how you set max filesize and post settings.

Use Excel VBA to click on a button in Internet Explorer, when the button has no "name" associated

With the kind help from Tim Williams, I finally figured out the last détails that were missing. Here's the final code below.

Private Sub Open_multiple_sub_pages_from_main_page()


Dim i As Long
Dim IE As Object
Dim Doc As Object
Dim objElement As Object
Dim objCollection As Object
Dim buttonCollection As Object
Dim valeur_heure As Object


' Create InternetExplorer Object
Set IE = CreateObject("InternetExplorer.Application")
' You can uncoment Next line To see form results
IE.Visible = True

' Send the form data To URL As POST binary request
IE.navigate "http://webpage.com/"

' Wait while IE loading...
While IE.Busy
        DoEvents
Wend


Set objCollection = IE.Document.getElementsByTagName("input")

i = 0
While i < objCollection.Length
    If objCollection(i).Name = "txtUserName" Then
        ' Set text for search
        objCollection(i).Value = "1234"
    End If
    If objCollection(i).Name = "txtPwd" Then
        ' Set text for search
        objCollection(i).Value = "password"
    End If

    If objCollection(i).Type = "submit" And objCollection(i).Name = "btnSubmit" Then ' submit button if found and set
        Set objElement = objCollection(i)
    End If
    i = i + 1
Wend
objElement.Click    ' click button to load page

' Wait while IE re-loading...
While IE.Busy
        DoEvents
Wend

' Show IE
IE.Visible = True
Set Doc = IE.Document

Dim links, link

Dim j As Integer                                                                    'variable to count items
j = 0
Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")
n = links.Length
While j <= n                                    'loop to go thru all "a" item so it loads next page
    links(j).Click
    While IE.Busy
        DoEvents
    Wend
    '-------------Do stuff here:  copy field value and paste in excel sheet.  Will post another question for this------------------------
    IE.Document.getElementById("DetailToolbar1_lnkBtnSave").Click              'save
    Do While IE.Busy
        Application.Wait DateAdd("s", 1, Now)                                   'wait
    Loop
    IE.Document.getElementById("DetailToolbar1_lnkBtnCancel").Click            'close
    Do While IE.Busy
        Application.Wait DateAdd("s", 1, Now)                                   'wait
    Loop
    Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")
    j = j + 2
Wend    
End Sub

Remove all of x axis labels in ggplot

You have to set to element_blank() in theme() elements you need to remove

ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut))+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())

Casting a variable using a Type variable

Putting boxing and unboxing aside for simplicity, there's no specific runtime action involved in casting along the inheritance hierarchy. It's mostly a compile time thing. Essentially, a cast tells the compiler to treat the value of the variable as another type.

What you could do after the cast? You don't know the type, so you wouldn't be able to call any methods on it. There wouldn't be any special thing you could do. Specifically, it can be useful only if you know the possible types at compile time, cast it manually and handle each case separately with if statements:

if (type == typeof(int)) {
    int x = (int)obj;
    DoSomethingWithInt(x);
} else if (type == typeof(string)) {
    string s = (string)obj;
    DoSomethingWithString(s);
} // ...

What does asterisk * mean in Python?

I only have one thing to add that wasn't clear from the other answers (for completeness's sake).

You may also use the stars when calling the function. For example, say you have code like this:

>>> def foo(*args):
...     print(args)
...
>>> l = [1,2,3,4,5]

You can pass the list l into foo like so...

>>> foo(*l)
(1, 2, 3, 4, 5)

You can do the same for dictionaries...

>>> def foo(**argd):
...     print(argd)
...
>>> d = {'a' : 'b', 'c' : 'd'}
>>> foo(**d)
{'a': 'b', 'c': 'd'}

How to change a css class style through Javascript?

You may also be interested in modifying it using jQuery: http://api.jquery.com/category/css/

Best way to resolve file path too long exception

From my experience, won't recommend my below answer for any public facing Web applications.

If you need it for your inhouse tools or for Testing, I would recommend to share it on your own machine.

-Right click on the root path you need to access
-Choose Properties
-Click on Share button and add your chosen users who can access it

This will then create a shared directory like \\{PCName}\{YourSharedRootDirectory} This could be definitely much less than your full path I hope, for me I could reduce to 30 characters from about 290 characters. :)

REST API - Use the "Accept: application/json" HTTP Header

You guessed right, HTTP Headers are not part of the URL.

And when you type a URL in the browser the request will be issued with standard headers. Anyway REST Apis are not meant to be consumed by typing the endpoint in the address bar of a browser.

The most common scenario is that your server consumes a third party REST Api.

To do so your server-side code forges a proper GET (/PUT/POST/DELETE) request pointing to a given endpoint (URL) setting (when needed, like your case) some headers and finally (maybe) sending some data (as typically occurrs in a POST request for example).

The code to forge the request, send it and finally get the response back depends on your server side language.

If you want to test a REST Api you may use curl tool from the command line.

curl makes a request and outputs the response to stdout (unless otherwise instructed).

In your case the test request would be issued like this:

$curl -H "Accept: application/json" 'http://localhost:8080/otp/routers/default/plan?fromPlace=52.5895,13.2836&toPlace=52.5461,13.3588&date=2017/04/04&time=12:00:00'

The H or --header directive sets a header and its value.

Post-increment and pre-increment within a 'for' loop produce same output

There is a difference if:

int main()
{
  for(int i(0); i<2; printf("i = post increment in loop %d\n", i++))
  {
    cout << "inside post incement = " << i << endl;
  }


  for(int i(0); i<2; printf("i = pre increment in loop %d\n",++i))
  {
    cout << "inside pre incement = " << i << endl;
  }

  return 0;
}

The result:

inside post incement = 0

i = post increment in loop 0

inside post incement = 1

i = post increment in loop 1

The second for loop:

inside pre incement = 0

i = pre increment in loop 1

inside pre incement = 1

i = pre increment in loop 2

open existing java project in eclipse

The typical pattern is to check out the root project folder (=the one containing a file called ".project") from SVN using eclipse's svn integration (SVN repository exploring perspective). The project is then recognized automatically.

How to define a preprocessor symbol in Xcode

You can duplicate the target which has the preprocessing section, rename it to any name you want, and then change your Preprocessor macro value.

Multiple maven repositories in one gradle file

you have to do like this in your project level gradle file

allprojects {
    repositories {
        jcenter()
        maven { url "http://dl.appnext.com/" }
        maven { url "https://maven.google.com" }
    }
}

UIImageView aspect fit and center

[your_imageview setContentMode:UIViewContentModeCenter];

How to remove leading zeros using C#

I just crafted this as I needed a good, simple way.

If it gets to the final digit, and if it is a zero, it will stay.

You could also use a foreach loop instead for super long strings.

I just replace each leading oldChar with the newChar.


This is great for a problem I just solved, after formatting an int into a string.

    /* Like this: */
    int counterMax = 1000;
    int counter = ...;
    string counterString = counter.ToString($"D{counterMax.ToString().Length}");
    counterString = RemoveLeadingChars('0', ' ', counterString);
    string fullCounter = $"({counterString}/{counterMax})";
    // = (   1/1000) ... ( 430/1000) ... (1000/1000)

    static string RemoveLeadingChars(char oldChar, char newChar, char[] chars)
    {
        string result = "";
        bool stop = false;
        for (int i = 0; i < chars.Length; i++)
        {
            if (i == (chars.Length - 1)) stop = true;
            if (!stop && chars[i] == oldChar) chars[i] = newChar;
            else stop = true;
            result += chars[i];
        }
        return result;
    }

    static string RemoveLeadingChars(char oldChar, char newChar, string text)
    {
        return RemoveLeadingChars(oldChar, newChar, text.ToCharArray());
    }

I always tend to make my functions suitable for my own library, so there are options.

Websocket connections with Postman

You can use the tool APIC available here https://chrome.google.com/webstore/detail/apic-complete-api-solutio/ggnhohnkfcpcanfekomdkjffnfcjnjam. This tool allows you to test websocket which use either StompJS or native Websocket. More info here at www.apic.app

What is the closest thing Windows has to fork()?

Well, windows doesn't really have anything quite like it. Especially since fork can be used to conceptually create a thread or a process in *nix.

So, I'd have to say:

CreateProcess()/CreateProcessEx()

and

CreateThread() (I've heard that for C applications, _beginthreadex() is better).

asterisk : Unable to connect to remote asterisk (does /var/run/asterisk.ctl exist?)

Try to use sudo, to run asterisk -r that works for me every time this error comes up.

Use a.empty, a.bool(), a.item(), a.any() or a.all()

solution is easy:

replace

 mask = (50  < df['heart rate'] < 101 &
            140 < df['systolic blood pressure'] < 160 &
            90  < df['dyastolic blood pressure'] < 100 &
            35  < df['temperature'] < 39 &
            11  < df['respiratory rate'] < 19 &
            95  < df['pulse oximetry'] < 100
            , "excellent", "critical")

by

mask = ((50  < df['heart rate'] < 101) &
        (140 < df['systolic blood pressure'] < 160) &
        (90  < df['dyastolic blood pressure'] < 100) &
        (35  < df['temperature'] < 39) &
        (11  < df['respiratory rate'] < 19) &
        (95  < df['pulse oximetry'] < 100)
        , "excellent", "critical")

XML Carriage return encoding

To insert a CR into XML, you need to use its character entity &#13;.

This is because compliant XML parsers must, before parsing, translate CRLF and any CR not followed by a LF to a single LF. This behavior is defined in the End-of-Line handling section of the XML 1.0 specification.

How do I find out what version of Sybase is running

There are two ways to know the about Sybase version,

1) Using this System procedure to get the information about Sybase version

> sp_version
> go

2) Using this command to get Sybase version

> select @@version
> go

Graphviz's executables are not found (Python 3.4)

Please note that I am using windows 10. some of the following may or may not applicable for other versions of windows or operating systems:

** Note 2: **
"the Graphviz bin file address on your system" can be C:\Program Files (x86)\Graphviz2.38\bin or any other path you installed Graphviz there.

We have problem not only with Graphviz but also with other external EXE files we want to use in Jupyter.
The reason is when jupyter wants to import a package it looks in working directory to find it and when it fails to find the package it returns such errors.
What we can do is tackle this is as follows:
1) check if the Graphviz is installed on your system and if not you can download and install it from:

https://graphviz.gitlab.io/_pages/Download/Download_windows.html
and then install it. When you installing Graphviz, keep in mind where (in which folder) you are installing it. If you see the above error when you use

import graphviz

then you have several options:

2) you can call the .exe file in the ipynb via

import os
os.environ["PATH"] += os.pathsep + r'the Graphviz bin file address on your system'

It is my experience that it is only works for the same ipynb that I am working with and every time that I open the notebook I need to call this lines of code.

3) If you want the Jupyter where to find the exe file, you need to set environmenal path.
In windows 10 you can do this going to:
Control Panel > System and Security > System > Advanced System Settings > Environment Variables > Path > Edit > New
and then add the "the Graphviz bin file address on your system" In windows 8 or lower go to :
Control Panel > System and Security > System > Advanced System Settings > Environment Variables
and then add the ;(semicolon) + "the Graphviz bin file address on your system" to the end of path string
Note: remember to restart your machine.

4) and even this does not work, define a variable going to:
Control Panel > System and Security > System > Advanced System Settings > Environment Variables and then:

Start to define an environmental variable

Then define a variable as this: Remember to name the variable Graphviz

Remember to name the variable Graphviz. At last restart your PC and hope it works.

I want to vertical-align text in select box

This has now been fixed in Firefox Nightly and will be in the next firefox build.

Please see this bug for more information https://bugzilla.mozilla.org/show_bug.cgi?id=610733

How can I capture packets in Android?

Option 1 - Android PCAP

Limitation

Android PCAP should work so long as:

Your device runs Android 4.0 or higher (or, in theory, the few devices which run Android 3.2). Earlier versions of Android do not have a USB Host API

Option 2 - TcpDump

Limitation

Phone should be rooted

Option 3 - bitshark (I would prefer this)

Limitation

Phone should be rooted

Reason - the generated PCAP files can be analyzed in WireShark which helps us in doing the analysis.

Other Options without rooting your phone

  1. tPacketCapture

https://play.google.com/store/apps/details?id=jp.co.taosoftware.android.packetcapture&hl=en

Advantages

Using tPacketCapture is very easy, captured packet save into a PCAP file that can be easily analyzed by using a network protocol analyzer application such as Wireshark.

  1. You can route your android mobile traffic to PC and capture the traffic in the desktop using any network sniffing tool.

http://lifehacker.com/5369381/turn-your-windows-7-pc-into-a-wireless-hotspot

efficient way to implement paging

The approach that I am giving is the fastest pagination that SQL server can achieve. I have tested this on 5 million records. This approach is far better than "OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY" provided by SQL Server.

-- The below given code computes the page numbers and the max row of previous page
-- Replace <<>> with the correct table data.
-- Eg. <<IdentityColumn of Table>> can be EmployeeId and <<Table>> will be dbo.Employees

DECLARE @PageNumber int=1; --1st/2nd/nth page. In stored proc take this as input param.
DECLARE @NoOfRecordsPerPage int=1000;

 DECLARE @PageDetails TABLE
       (
        <<IdentityColumn of Table>> int,
        rownum int,
        [PageNumber] int
       )           
       INSERT INTO @PageDetails values(0, 0, 0)
       ;WITH CTE AS
       (
       SELECT <<IdentityColumn of Table>>, ROW_NUMBER() OVER(ORDER BY <<IdentityColumn of Table>>) rownum FROM <<Table>>
       )
       Insert into @PageDetails 
       SELECT <<IdentityColumn of Table>>, CTE.rownum, ROW_NUMBER() OVER (ORDER BY rownum) as [PageNumber] FROM CTE WHERE CTE.rownum%@NoOfRecordsPerPage=0


--SELECT * FROM @PageDetails 

-- Actual pagination
SELECT TOP (@NoOfRecordsPerPage)
FROM <<Table>> AS <<Table>>
WHERE <<IdentityColumn of Table>> > (SELECT <<IdentityColumn of Table>> FROM 
@PageDetails WHERE PageNumber=@PageNumber)
ORDER BY <<Identity Column of Table>>

Object passed as parameter to another class, by value or reference?

In general, an "object" is an instance of a class, which is an "image"/"fingerprint" of a class created in memory (via New keyword).
The variable of object type refers to this memory location, that is, it essentially contains the address in memory.
So a parameter of object type passes a reference/"link" to an object, not a copy of the whole object.

Mongoose's find method with $or condition does not work properly

According to mongoDB documentation: "...That is, for MongoDB to use indexes to evaluate an $or expression, all the clauses in the $or expression must be supported by indexes."

So add indexes for your other fields and it will work. I had a similar problem and this solved it.

You can read more here: https://docs.mongodb.com/manual/reference/operator/query/or/

SQL Server Creating a temp table for this query

If you want to just create a temp table inside the query that will allow you to do something with the results that you deposit into it you can do something like the following:

DECLARE @T1 TABLE (
Item 1 VARCHAR(200)
, Item 2 VARCHAR(200)
, ...
, Item n VARCHAR(500)
)

On the top of your query and then do an

INSERT INTO @T1
SELECT
FROM
(...)

comma separated string of selected values in mysql

Check this

SELECT GROUP_CONCAT(id)  FROM table_level where parent_id=4 group by parent_id;

Replace only some groups with Regex

A good idea could be to encapsulate everything inside groups, no matter if need to identify them or not. That way you can use them in your replacement string. For example:

var pattern = @"(-)(\d+)(-)";
var replaced = Regex.Replace(text, pattern, "$1AA$3"); 

or using a MatchEvaluator:

var replaced = Regex.Replace(text, pattern, m => m.Groups[1].Value + "AA" + m.Groups[3].Value);

Another way, slightly messy, could be using a lookbehind/lookahead:

(?<=-)(\d+)(?=-)

How to perform runtime type checking in Dart?

The instanceof-operator is called is in Dart. The spec isn't exactly friendly to a casual reader, so the best description right now seems to be http://www.dartlang.org/articles/optional-types/.

Here's an example:

class Foo { }

main() {
  var foo = new Foo();
  if (foo is Foo) {
    print("it's a foo!");
  }
}

Check if a string is null or empty in XSLT

From Empty Element:

To test if the value of a certain node is empty

It depends on what you mean by empty.

  • Contains no child nodes: not(node())
  • Contains no text content: not(string(.))
  • Contains no text other than whitespace: not(normalize-space(.))
  • Contains nothing except comments: not(node()[not(self::comment())])

check if a file is open in Python

You could use with open("path") as file: so that it automatically closes, else if it's open in another process you can maybe try as in Tims example you should use except IOError to not ignore any other problem with your code :)

try:
   with open("path", "r") as file: # or just open
       # Code here
except IOError:
   # raise error or print

Reading inputStream using BufferedReader.readLine() is too slow

I have a longer test to try. This takes an average of 160 ns to read each line as add it to a List (Which is likely to be what you intended as dropping the newlines is not very useful.

public static void main(String... args) throws IOException {
    final int runs = 5 * 1000 * 1000;

    final ServerSocket ss = new ServerSocket(0);
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Socket serverConn = ss.accept();
                String line = "Hello World!\n";
                BufferedWriter br = new BufferedWriter(new OutputStreamWriter(serverConn.getOutputStream()));
                for (int count = 0; count < runs; count++)
                    br.write(line);
                serverConn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();

    Socket conn = new Socket("localhost", ss.getLocalPort());

    long start = System.nanoTime();
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;

    List<String> responseData = new ArrayList<String>();
    while ((line = in.readLine()) != null) {
        responseData.add(line);
    }
    long time = System.nanoTime() - start;
    System.out.println("Average time to read a line was " + time / runs + " ns.");
    conn.close();
    ss.close();
}

prints

Average time to read a line was 158 ns.

If you want to build a StringBuilder, keeping newlines I would suggets the following approach.

Reader r = new InputStreamReader(conn.getInputStream());
String line;

StringBuilder sb = new StringBuilder();
char[] chars = new char[4*1024];
int len;
while((len = r.read(chars))>=0) {
    sb.append(chars, 0, len);
}

Still prints

Average time to read a line was 159 ns.

In both cases, the speed is limited by the sender not the receiver. By optimising the sender, I got this timing down to 105 ns per line.

JPQL IN clause: Java-Arrays (or Lists, Sets...)?

The oracle limit is 1000 parameters. The issue has been resolved by hibernate in version 4.1.7 although by splitting the passed parameter list in sets of 500 see JIRA HHH-1123

error C2220: warning treated as error - no 'object' file generated

This error message is very confusing. I just fixed the other 'warnings' in my project and I really had only one (simple one):

warning C4101: 'i': unreferenced local variable

After I commented this unused i, and compiled it, the other error went away.

SQLDataReader Row Count

SQLDataReaders are forward-only. You're essentially doing this:

count++;  // initially 1
.DataBind(); //consuming all the records

//next iteration on
.Read()
//we've now come to end of resultset, thanks to the DataBind()
//count is still 1 

You could do this instead:

if (reader.HasRows)
{
    rep.DataSource = reader;
    rep.DataBind();
}
int count = rep.Items.Count; //somehow count the num rows/items `rep` has.

Editing legend (text) labels in ggplot

The tutorial @Henrik mentioned is an excellent resource for learning how to create plots with the ggplot2 package.

An example with your data:

# transforming the data from wide to long
library(reshape2)
dfm <- melt(df, id = "TY")

# creating a scatterplot
ggplot(data = dfm, aes(x = TY, y = value, color = variable)) + 
  geom_point(size=5) +
  labs(title = "Temperatures\n", x = "TY [°C]", y = "Txxx", color = "Legend Title\n") +
  scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
  theme_bw() +
  theme(axis.text.x = element_text(size = 14), axis.title.x = element_text(size = 16),
        axis.text.y = element_text(size = 14), axis.title.y = element_text(size = 16),
        plot.title = element_text(size = 20, face = "bold", color = "darkgreen"))

this results in:

enter image description here

As mentioned by @user2739472 in the comments: If you only want to change the legend text labels and not the colours from ggplot's default palette, you can use scale_color_hue(labels = c("T999", "T888")) instead of scale_color_manual().

Count the Number of Tables in a SQL Server Database

Try this:

SELECT Count(*)
FROM <DATABASE_NAME>.INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'

How to create a signed APK file using Cordova command line interface?

First Check your version code and version name if you are updating your app. And make sure you have a previous keystore.

If you are updating app then follow step 1,3,4.

Step 1:

Goto your cordova project for generate our release build:

D:\projects\Phonegap\Example> cordova build --release android

Then, we can find our unsigned APK file in platforms/android/ant-build. In our example, the file was

if u used ant-build

yourproject/platforms/android/ant-build/Example-release-unsigned.apk

OR

if u used gradle-build

yourProject/platforms/android/build/outputs/apk/Example-release-unsigned.apk

Step 2:

Key Generation:

Syntax:

keytool -genkey -v -keystore <keystoreName>.keystore -alias <Keystore AliasName> -keyalg <Key algorithm> -keysize <Key size> -validity <Key Validity in Days>

if keytool command not recognize do this step

Check that the directory the keytool executable is in is on your path. (For example, on my Windows 7 machine, it's in C:\Program Files (x86)\Java\jre6\bin.)

Example:

keytool -genkey -v -keystore NAME-mobileapps.keystore -alias NAMEmobileapps -keyalg RSA -keysize 2048 -validity 10000


keystore password? : xxxxxxx
What is your first and last name? :  xxxxxx
What is the name of your organizational unit? :  xxxxxxxx
What is the name of your organization? :  xxxxxxxxx
What is the name of your City or Locality? :  xxxxxxx
What is the name of your State or Province? :  xxxxx
What is the two-letter country code for this unit? :  xxx

Then the Key store has been generated with name as NAME-mobileapps.keystore

Step 3:

Place the generated keystore in D:\projects\Phonegap\Example\platforms\android\ant-build

To sign the unsigned APK, run the jarsigner tool which is also included in the JDK:

Syntax:

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore <keystorename <Unsigned APK file> <Keystore Alias name>

If it doesn't reconize do these steps

(1) Right click on "This PC" > right-click Properties > Advanced system settings > Environment Variables > select PATH then EDIT.

(2) Add your jdk bin folder path to environment variables, it should look like this:

"C:\Program Files\Java\jdk1.8.0_40\bin".

Example:

D:\projects\Phonegap\Example\platforms\android\ant-build> jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore NAME-mobileapps.keystore Example-release-unsigned.apk xxxxxmobileapps

Enter KeyPhrase as 'xxxxxxxx'

This signs the apk in place.

Step 4:

Finally, we need to run the zip align tool to optimize the APK:

if zipalign not recognize then

(1) goto your android sdk path and find zipalign it is usually in android-sdk\build-tools\23.0.3

(2) Copy zipalign file paste into your generate release apk folder usually in below path

yourproject/platforms/android/ant-build/Example-release-unsigned.apk

D:\projects\Phonegap\Example\platforms\android\ant-build> zipalign -v 4 Example-release-unsigned.apk Example.apk 

OR

D:\projects\Phonegap\Example\platforms\android\ant-build> C:\Phonegap\adt-bundle-windows-x86_64-20140624\sdk\build-tools\android-4.4W\zipalign -v 4 Example-release-unsigned.apk Example.apk

Now we have our final release binary called example.apk and we can release this on the Google Play Store.

How do we update URL or query strings using javascript/jQuery without reloading the page?

Yes - document.location = "http://my.new.url.com"

You can also retrieve it the same way eg.

var myURL = document.location;
document.location = myURL + "?a=parameter";

The location object has a number of useful properties too:

hash            Returns the anchor portion of a URL
host            Returns the hostname and port of a URL
hostname        Returns the hostname of a URL
href            Returns the entire URL
pathname        Returns the path name of a URL
port            Returns the port number the server uses for a URL
protocol        Returns the protocol of a URL
search          Returns the query portion of a URL

EDIT: Setting the hash of the document.location shouldn't reload the page, just alter where on the page the focus is. So updating to #myId will scroll to the element with id="myId". If the id doesn't exist I believe nothing will happen? (Need to confirm on various browsers though)

EDIT2: To make it clear, not just in a comment: You can't update the whole URL with javascript without changing the page, this is a security restriction. Otherwise you could click on a link to a random page, crafted to look like gmail, and instantly change the URL to www.gmail.com and steal people's login details.
You can change the part after the domain on some browsers to cope with AJAX style things, but that's already been linked to by Osiris. What's more, you probably shouldn't do this, even if you could. The URL tells the user where he/she is on your site. If you change it without changing the page contents, it's becomes a little confusing.

Push origin master error on new repository

I just encountered this problem, and it seemed to be caused by my not adding a custom commit message above the default commit message (I figured, why write "initial commit", when it clearly says that very same thing in the Git-generated text below it).

The problem resolved when I removed the .git directory, re-initialized the project directory for Git, re-added the GitHub remote, added all files to the new stage, committed with a personal message above the auto-generated message, and pushed to origin/master.

When should I create a destructor?

You don't need one unless your class maintains unmanaged resources like Windows file handles.

How to make ng-repeat filter out duplicate results

You can use 'unique'(aliases: uniq) filter in angular.filter module

usage: colection | uniq: 'property'
you can also filter by nested properties: colection | uniq: 'property.nested_property'

What you can do, is something like that..

function MainController ($scope) {
 $scope.orders = [
  { id:1, customer: { name: 'foo', id: 10 } },
  { id:2, customer: { name: 'bar', id: 20 } },
  { id:3, customer: { name: 'foo', id: 10 } },
  { id:4, customer: { name: 'bar', id: 20 } },
  { id:5, customer: { name: 'baz', id: 30 } },
 ];
}

HTML: We filter by customer id, i.e remove duplicate customers

<th>Customer list: </th>
<tr ng-repeat="order in orders | unique: 'customer.id'" >
   <td> {{ order.customer.name }} , {{ order.customer.id }} </td>
</tr>

result
Customer list:
foo 10
bar 20
baz 30

AngularJS Directive Restrict A vs E

The restrict option is typically set to:

  • 'A' - only matches attribute name
  • 'E' - only matches element name
  • 'C' - only matches class name
  • 'M' - only matches comment

Here is the documentation link.

Cannot redeclare function php

Remove the function and check the output of:

var_dump(function_exists('parseDate'));

In which case, change the name of the function.

If you get false, you're including the file with that function twice, replace :

include

by

include_once

And replace :

require

by

require_once

EDIT : I'm just a little too late, post before beat me to it !

Regex (grep) for multi-line search needed

I am not very good in grep. But your problem can be solved using AWK command. Just see

awk '/select/,/from/' *.sql

The above code will result from first occurence of select till first sequence of from. Now you need to verify whether returned statements are having customername or not. For this you can pipe the result. And can use awk or grep again.

click or change event on radio using jquery

This code worked for me:

$(function(){

    $('input:radio').change(function(){
        alert('changed');   
    });          

});

http://jsfiddle.net/3q29L/

Maven not found in Mac OSX mavericks

This solution could seem very long, but it's not. I just included many examples so that everything was clear. It worked for me in Mavericks OS.

Note: I combined and edited some of the answers shown above, added some examples and format and posted the result, so the credit goes mostly to the creators of the original posts.

  1. Download Maven from here.

  2. Open the Terminal.

  3. Extract the file you just downloaded to the location you want, either manually or by typing the following lines in the Terminal (fill the required data):

    mv [Your file name] [Destination location]/ tar -xvf [Your file name]

    For example, if our file is named "apache-maven-3.2.1-bin.tar" (Maven version 3.2.1) and we want to locate it in the "/Applications" directory, then we should type the following lines in Terminal:

    mv apache-maven-3.2.1-bin.tar /Applications/
    tar -xvf apache-maven-3.2.1-bin.tar
    
  4. If you don't have any JDK (Java Development Kit) installed on your computer, install one.

  5. Type "java -version" in Terminal. You should see something like this:

    java version "1.8.0"
    Java(TM) SE Runtime Environment (build 1.8.0-b132)
    Java HotSpot(TM) 64-Bit Server VM (build 25.0-b70, mixed mode)
    

    Remember your java version (in the example, 1.8.0).

  6. Type "cd ~/" to go to your home folder.

  7. Type "touch .bash_profile".

  8. Type "open -e .bash_profile" to open .bash_profile in TextEdit.

  9. Type the following in TextEdit (copy everything and replace the required data):

    export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk[Your Java version].jdk/Contents/Home export M2_HOME=[Your file location]/apache-maven-[Your Maven version]/ export PATH=$PATH:$M2_HOME/bin alias mvn='$M2_HOME/bin/mvn'

    For example, in our case we would replace "[Your Java version]" with "1.8.0" (value got in step 5), "[Your file location]" with "/Applications" (value used as "Destination Location" in step 3) and "[Your Maven version]" with "3.2.1" (Maven version observed in step 3), resulting in the following code:

    export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0.jdk/Contents/Home
    export M2_HOME=/Applications/apache-maven-3.2.1/
    export PATH=$PATH:$M2_HOME/bin
    alias mvn='$M2_HOME/bin/mvn'
    
  10. Save your changes

  11. Type "source .bash_profile" to reload .bash_profile and update any functions you add.

  12. Type mvn -version. If successful you should see the following:

    Apache Maven [Your Maven version] ([Some weird stuff. Don't worry about this]) Maven home: [Your file location]/apache-maven-[Your Maven version] Java version: [You Java version], vendor: Oracle Corporation Java home: /Library/Java/JavaVirtualMachines/jdk[Your Java version].jdk/Contents/Home/jre [Some other stuff which may vary depending on the configuration and the OS of the computer]

    In our example, the result would be the following:

    Apache Maven 3.2.1 (ea8b2b07643dbb1b84b6d16e1f08391b666bc1e9; 2014-02-14T18:37:52+01:00)
    Maven home: /Applications/apache-maven-3.2.1
    Java version: 1.8.0, vendor: Oracle Corporation
    Java home: /Library/Java/JavaVirtualMachines/jdk1.8.0</b>.jdk/Contents/Home/jre
    Default locale: es_ES, platform encoding: UTF-8
    OS name: "mac os x", version: "10.9.2", arch: "x86_64", family: "mac"
    

How do I simulate a hover with a touch in touch enabled browsers?

Easyest solution I found: I had some < span > tags with :hover css rules in them. I switched for < a href="javascript:void(0)" > and voilà. The hover styles in iOS started working.

How to remove rows with any zero value

I prefer a simple adaptation of csgillespie's method, foregoing the need of a function definition:

d[apply(d!=0, 1, all),]

where d is your data frame.

LaTeX: Prevent line break in a span of text

Define myurl command:


\def\myurl{\hfil\penalty 100 \hfilneg \hbox}

I don't want to cause line overflows, 
I'd just rather LaTeX insert linebreaks before 
\myurl{\tt http://stackoverflow.com/questions/1012799/} 
regions rather than inside them.

Scatter plot and Color mapping in Python

To add to wflynny's answer above, you can find the available colormaps here

Example:

import matplotlib.cm as cm
plt.scatter(x, y, c=t, cmap=cm.jet)

or alternatively,

plt.scatter(x, y, c=t, cmap='jet')

Is there a Google Sheets formula to put the name of the sheet into a cell?

You have 2 options, and I am not sure if I am a fan of either of them, but that is my opinion. You may feel differently:

Option 1: Force the function to run.

A function in a cell does not run unless it references a cell that has changed. Changing a sheet name does not trigger any functions in the spreadsheet. But we can force the function to run by passing a range to it and whenever an item in that range changes, the function will trigger.

You can use the below script to create a custom function which will retrieve the name:

function mySheetName() {
  var key = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
  return key;
}

and in the cell place the following:

=mySheetName(A1:Z)

Now if any value in a cell in that passed range changes the script will run. This takes a second to run the script and sets a message in the cell each time any value is changed so this could become annoying very quickly. As already mentioned, it also requires a change in the range to cause it to trigger, so not really helpful on a fairly static file.

Option 2: Use the OnChange Event

While the run time feels better than the above option, and this does not depend on a value changing in the spreadsheet's cells, I do not like this because it forces where the name goes. You could use a Utilities sheet to define this location in various sheets if you wish. Below is the basic idea and may get you started if you like this option.

The OnChange event is triggered when the sheet name is changed. You can make the code below more sophisticated to check for errors, check the sheet ID to only work on a given sheet, etc. The basic code, however, is:

function setSheetName(e) {
  var key = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
  SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange('K1').setValue(key);
}

Once you have saved the code, in the script editor set the Current Project's On Change Trigger to this function. It will write the sheet name to cell K1 on any change event. To set the trigger, select Current project's triggers under the Edit menu.

Does C# support multiple inheritance?

Sorry, you cannot inherit from multiple classes. You may use interfaces or a combination of one class and interface(s), where interface(s) should follow the class name in the signature.

interface A { }
interface B { }
class Base { }
class AnotherClass { }

Possible ways to inherit:

class SomeClass : A, B { } // from multiple Interface(s)
class SomeClass : Base, B { } // from one Class and Interface(s)

This is not legal:

class SomeClass : Base, AnotherClass { }

Simple PHP form: Attachment to email (code golf)

A combination of this http://www.webcheatsheet.com/PHP/send_email_text_html_attachment.php#attachment

with the php upload file example would work. In the upload file example instead of using move_uploaded_file to move it from the temporary folder you would just open it:

$attachment = chunk_split(base64_encode(file_get_contents($tmp_file))); 

where $tmp_file = $_FILES['userfile']['tmp_name'];

and send it as an attachment like the rest of the example.

All in one file / self contained:

<? if(isset($_POST['submit'])){
//process and email
}else{
//display form
}
?>

I think its a quick exercise to get what you need working based on the above two available examples.

P.S. It needs to get uploaded somewhere before Apache passes it along to PHP to do what it wants with it. That would be your system's temp folder by default unless it was changed in the config file.

Moving all files from one directory to another using Python

def copy_myfile_dirOne_to_dirSec(src, dest, ext): 

    if not os.path.exists(dest):    # if dest dir is not there then we create here
        os.makedirs(dest);
        
    for item in os.listdir(src):
        if item.endswith(ext):
            s = os.path.join(src, item);
            fd = open(s, 'r');
            data = fd.read();
            fd.close();
            
            fname = str(item); #just taking file name to make this name file is destination dir     
            
            d = os.path.join(dest, fname);
            fd = open(d, 'w');
            fd.write(data);
            fd.close();
    
    print("Files are copyed successfully")

New self vs. new static

If the method of this code is not static, you can get a work-around in 5.2 by using get_class($this).

class A {
    public function create1() {
        $class = get_class($this);
        return new $class();
    }
    public function create2() {
        return new static();
    }
}

class B extends A {

}

$b = new B();
var_dump(get_class($b->create1()), get_class($b->create2()));

The results:

string(1) "B"
string(1) "B"

Why does Maven have such a bad rep?

I think one major reason for the bad reputation is that maven2 solves several complex problems (build automation, dependencies, managing repositories) as a one shot solution. Therefore you have to face these tough problems while starting to use maven. So it is a kind of "kill the messenger"-effect.

Other approaches (e.g. ant+ivy) often do not give you the chance to blame one single tool for all the problems you encounter. It is more like "okay ant not really easy to get started, ivy has some issues. But at least we don't have to wrestle with maven!" Saying that one does not recognize that all these problems taken together do not differ too much from the issues you encounter when using maven. It just may be a litte bit easier to tackle one at a time. BTW, I set up a build system based on ant+ivy in the past months. And I am really glad I did not have to use maven2 ;-)

Merge r brings error "'by' must specify uniquely valid columns"

Rather give names of the column on which you want to merge:

exporttab <- merge(x=dwd_nogap, y=dwd_gap, by.x='x1', by.y='x2', fill=-9999)

Scala: what is the best way to append an element to an Array?

The easiest might be:

Array(1, 2, 3) :+ 4

Actually, Array can be implcitly transformed in a WrappedArray

border-radius not working

Your problem is unrelated to how you have set border-radius. Fire up Chrome and hit Ctrl+Shift+j and inspect the element. Uncheck width and the border will have curved corners.

Static nested class in Java, why?

I don't know about performance difference, but as you say, static nested class is not a part of an instance of the enclosing class. Seems just simpler to create a static nested class unless you really need it to be an inner class.

It's a bit like why I always make my variables final in Java - if they're not final, I know there's something funny going on with them. If you use an inner class instead of a static nested class, there should be a good reason.

How to add parameters to an external data query in Excel which can't be displayed graphically?

YES - solution is to save workbook in to XML file (eg. 'XML Spreadsheet 2003') and edit this file as text in notepad! use "SEARCH" function of notepad to find query text and change your data to "?".

save and open in excel, try refresh data and excel will be monit about parameters.

Pandas convert string to int

You need add parameter errors='coerce' to function to_numeric:

ID = pd.to_numeric(ID, errors='coerce')

If ID is column:

df.ID = pd.to_numeric(df.ID, errors='coerce')

but non numeric are converted to NaN, so all values are float.

For int need convert NaN to some value e.g. 0 and then cast to int:

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)

Sample:

df = pd.DataFrame({'ID':['4806105017087','4806105017087','CN414149']})
print (df)
              ID
0  4806105017087
1  4806105017087
2       CN414149

print (pd.to_numeric(df.ID, errors='coerce'))
0    4.806105e+12
1    4.806105e+12
2             NaN
Name: ID, dtype: float64

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)
print (df)
              ID
0  4806105017087
1  4806105017087
2              0

EDIT: If use pandas 0.25+ then is possible use integer_na:

df.ID = pd.to_numeric(df.ID, errors='coerce').astype('Int64')
print (df)
              ID
0  4806105017087
1  4806105017087
2            NaN