Programs & Examples On #Soundtouch

An open-source audio processing library for changing the Tempo, Pitch and Playback Rates of audio streams or audio files

Unable to create Genymotion Virtual Device

  1. If you have installed the Genymotion plugin without VirtualBox then make sure the version of VBox is compatible with the plugin, otherwise the plugin will not deploy the virtual device regardless of the OVA file.Install the latest versions of both if you are unsure
  2. Once you verified the versions, you may need to either:

    a: Give administrative privileges for Genymotion via properties

    OR

    b: Change the location for the deployed devices via Settings/VirtualBox to somewhere more accessbile like D:/GenyMotion VMs/

  3. If both step 1 and 2 doesnt work for you, sadly you will have to clear the cache via Settings/Misc and reinstall the OVA file.Hopefully your efforts will be worth it. Good Luck.

How to update an object in a List<> in C#

Can also try.

 _lstProductDetail.Where(S => S.ProductID == "")
        .Select(S => { S.ProductPcs = "Update Value" ; return S; }).ToList();

Set the space between Elements in Row Flutter

Just add "Container(width: 5, color: Colors.transparent)," between elements

new Container(
      alignment: FractionalOffset.center,
      child: new Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          new FlatButton(
            child: new Text('Don\'t have an account?', style: new TextStyle(color: Color(0xFF2E3233))),
          ),
            Container(width: 5, color: Colors.transparent),
          new FlatButton(
            child: new Text('Register.', style: new TextStyle(color: Color(0xFF84A2AF), fontWeight: FontWeight.bold),),
            onPressed: moveToRegister,
          )
        ],
      ),
    ),  

BACKUP LOG cannot be performed because there is no current database backup

Originally, I created a database and then restored the backup file to my new empty database:

Right click on Databases > Restore Database > General : Device: [the path of back up file] ? OK

This was wrong. I shouldn't have first created the database.

Now, instead, I do this:

Right click on Databases > Restore Database > General : Device: [the path of back up file] ? OK

Enable binary mode while restoring a Database from an SQL dump

The file you are trying to import is a zip file. Unzip the file and then try to import again.

How to set opacity in parent div and not affect in child div?

You can't. Css today simply doesn't allow that.

The logical rendering model is this one :

If the object is a container element, then the effect is as if the contents of the container element were blended against the current background using a mask where the value of each pixel of the mask is .

Reference : css transparency

The solution is to use a different element composition, usually using fixed or computed positions for what is today defined as a child : it may appear logically and visualy for the user as a child but the element doesn't need to be really a child in your code.

A solution using css : fiddle

.parent {
    width:500px;
    height:200px;    
    background-image:url('http://canop.org/blog/wp-content/uploads/2011/11/cropped-bandeau-cr%C3%AAte-011.jpg');
    opacity: 0.2;
}
.child {
    position: fixed;
    top:0;
}

Another solution with javascript : fiddle

MySQL how to join tables on two fields

JOIN t2 ON t1.id=t2.id AND t1.date=t2.date

SQL exclude a column using SELECT * [except columnA] FROM tableA?

If we are talking of Procedures, it works with this trick to generate a new query and EXECUTE IMMEDIATE it:

SELECT LISTAGG((column_name), ', ') WITHIN GROUP (ORDER BY column_id)
INTO var_list_of_columns
FROM ALL_TAB_COLUMNS
WHERE table_name = 'PUT_HERE_YOUR_TABLE'
AND column_name NOT IN ('dont_want_this_column','neither_this_one','etc_column');

Fatal error: "No Target Architecture" in Visual Studio

At the beginning of the file you are compiling, before any include, try to put ONE of these lines

#define _X86_
#define _AMD64_
#define _ARM_

Choose the appropriate, only one, depending on your architecture.

Load an image from a url into a PictureBox

The PictureBox.Load(string url) method "sets the ImageLocation to the specified URL and displays the image indicated."

Format cell if cell contains date less than today

Your first problem was you weren't using your compare symbols correctly.

< less than
> greater than
<= less than or equal to
>= greater than or equal to

To answer your other questions; get the condition to work on every cell in the column and what about blanks?

What about blanks?

Add an extra IF condition to check if the cell is blank or not, if it isn't blank perform the check. =IF(B2="","",B2<=TODAY())

Condition on every cell in column

enter image description here

Allow user to select camera or gallery for image

You can create option dialog

Open Camera:

Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                                MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString());
                        if (cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) {
                            startActivityForResult(cameraIntent, CAMERA_IMAGE);
                        }

Open Gallery:

if (Build.VERSION.SDK_INT <= 19) {
            Intent i = new Intent();
            i.setType("image/*");
            i.setAction(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(i, GALLARY_IMAGE);
        } else if (Build.VERSION.SDK_INT > 19) {
            Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(intent, GALLARY_IMAGE);
        }

To get selection result

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == GALLARY_IMAGE) {
                Uri selectedImageUri = data.getData();
                String selectedImagePath = getRealPathFromURI(selectedImageUri);
            } else if (requestCode == CAMERA_IMAGE) {
                Bundle extras = data.getExtras();
                Bitmap bmp = (Bitmap) extras.get("data");
                SaveImage(bmp);
            }
        }
    }

 public String getRealPathFromURI(Uri uri) {
        if (uri == null) {
            return null;
        }
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = getActivity().getContentResolver().query(uri, projection, null, null, null);
        if (cursor != null) {
            int column_index = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }
        return uri.getPath();
    }

Method to save captured image

 private void SaveImage(final Bitmap finalBitmap) {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                String root = Environment.getExternalStorageDirectory().toString();

                File myDir = new File(root + "/Captured Images/");
                if (!myDir.exists())
                    myDir.mkdirs();

                String fname = "/image-" + System.currentTimeMillis() + ".jpg";
                File file = new File(myDir, fname);
                try {
                    FileOutputStream out = new FileOutputStream(file);
                    finalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                    out.flush();
                    out.close();
                    localImagePath = myDir + fname;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


        });
        t.start();

    }

Eclipse fonts and background color

I just came across this: Eclipse Colour Themes

Install the plugin and choose from a selection of pre-defined themes, or write your own. Just what I needed!

MySql server startup error 'The server quit without updating PID file '

$ open /usr/local/var/mysql

you just remove the folder in finder, and

$ brew install mysql

install again.

I've solved from this solution.

But this solution will be delete your database

How can I lock a file using java (if possible)

If you can use Java NIO (JDK 1.4 or greater), then I think you're looking for java.nio.channels.FileChannel.lock()

FileChannel.lock()

How can I get the last character in a string?

You should look at charAt function and take length of the string.

var b = 'I am a JavaScript hacker.';
console.log(b.charAt(b.length-1));

Apache Prefork vs Worker MPM

Apache has 2 types of MPM (Multi-Processing Modules) defined:

1:Prefork 2: Worker

By default, Apacke is configured in preforked mode i.e. non-threaded pre-forking web server. That means that each Apache child process contains a single thread and handles one request at a time. Because of that, it consumes more resources.

Apache also has the worker MPM that turns Apache into a multi-process, multi-threaded web server. Worker MPM uses multiple child processes with many threads each.

Deleting all pending tasks in celery / rabbitmq

For celery 3.0+:

$ celery purge

To purge a specific queue:

$ celery -Q queue_name purge

Warning: Cannot modify header information - headers already sent by ERROR

Check something with echo, print() or printr() in the include file, header.php.

It might be that this is the problem OR if any MVC file, then check the number of spaces after ?>. This could also make a problem.

Difference between text and varchar (character varying)

On PostgreSQL manual

There is no performance difference among these three types, apart from increased storage space when using the blank-padded type, and a few extra CPU cycles to check the length when storing into a length-constrained column. While character(n) has performance advantages in some other database systems, there is no such advantage in PostgreSQL; in fact character(n) is usually the slowest of the three because of its additional storage costs. In most situations text or character varying should be used instead.

I usually use text

References: http://www.postgresql.org/docs/current/static/datatype-character.html

Java Best Practices to Prevent Cross Site Scripting

Use both. In fact refer a guide like the OWASP XSS Prevention cheat sheet, on the possible cases for usage of output encoding and input validation.

Input validation helps when you cannot rely on output encoding in certain cases. For instance, you're better off validating inputs appearing in URLs rather than encoding the URLs themselves (Apache will not serve a URL that is url-encoded). Or for that matter, validate inputs that appear in JavaScript expressions.

Ultimately, a simple thumb rule will help - if you do not trust user input enough or if you suspect that certain sources can result in XSS attacks despite output encoding, validate it against a whitelist.

Do take a look at the OWASP ESAPI source code on how the output encoders and input validators are written in a security library.

Using Apache httpclient for https

When I used Apache HTTP Client 4.3, I was using the Pooled or Basic Connection Managers to the HTTP Client. I noticed, from using java SSL debugging, that these classes loaded the cacerts trust store and not the one I had specified programmatically.

PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
BasicHttpClientConnectionManager cm = new BasicHttpClientConnectionManager();
builder.setConnectionManager( cm );

I wanted to use them but ended up removing them and creating an HTTP Client without them. Note that builder is an HttpClientBuilder.

I confirmed when running my program with the Java SSL debug flags, and stopped in the debugger. I used -Djavax.net.debug=ssl as a VM argument. I stopped my code in the debugger and when either of the above *ClientConnectionManager were constructed, the cacerts file would be loaded.

HTML how to clear input using javascript?

<script type="text/javascript">
    function clearThis(target){
        if(target.value=='[email protected]'){
        target.value= "";}
    }
    </script>

Is this really what your looking for?

Inserting an item in a Tuple

t = (1,2,3,4,5)

t= t + (6,7)

output :

(1,2,3,4,5,6,7)

How to use greater than operator with date?

In your statement, you are comparing a string called start_date with the time.
If start_date is a column, it should either be

 
  SELECT * FROM `la_schedule` WHERE start_date >'2012-11-18';
 

(no apostrophe) or


SELECT * FROM `la_schedule` WHERE `start_date` >'2012-11-18';

(with backticks).

Hope this helps.

add controls vertically instead of horizontally using flow layout

I used a BoxLayout and set its second parameter as BoxLayout.Y_AXIS and it worked for me:

panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

Get String in YYYYMMDD format from JS date object?

Moment.js could be your friend

var date = new Date();
var formattedDate = moment(date).format('YYYYMMDD');

SQL Server Text type vs. varchar data type

There has been some major changes in ms 2008 -> Might be worth considering the following article when making a decisions on what data type to use. http://msdn.microsoft.com/en-us/library/ms143432.aspx

Bytes per

  1. varchar(max), varbinary(max), xml, text, or image column 2^31-1 2^31-1
  2. nvarchar(max) column 2^30-1 2^30-1

replace \n and \r\n with <br /> in java

It works for me.

public class Program
{
    public static void main(String[] args) {
        String str = "This is a string.\nThis is a long string.";
        str = str.replaceAll("(\r\n|\n)", "<br />");
        System.out.println(str);
    }
}

Result:

This is a string.<br />This is a long string.

Your problem is somewhere else.

How to connect to SQL Server from command prompt with Windows authentication

type sqlplus/"as sysdba" in cmd for connection in cmd prompt

How can I find the latitude and longitude from address?

public GeoPoint getLocationFromAddress(String strAddress){

Geocoder coder = new Geocoder(this);
List<Address> address;
GeoPoint p1 = null;

try {
    address = coder.getFromLocationName(strAddress,5);
    if (address==null) {
       return null;
    }
    Address location=address.get(0);
    location.getLatitude();
    location.getLongitude();

    p1 = new GeoPoint((double) (location.getLatitude() * 1E6),
                      (double) (location.getLongitude() * 1E6));

    return p1;
    }
}

strAddress is a string containing the address. The address variable holds the converted addresses.

How to validate a file upload field using Javascript/jquery

My function will check if the user has selected the file or not and you can also check whether you want to allow that file extension or not.

Try this:

<input type="file" name="fileUpload" onchange="validate_fileupload(this.value);">

function validate_fileupload(fileName)
{
    var allowed_extensions = new Array("jpg","png","gif");
    var file_extension = fileName.split('.').pop().toLowerCase(); // split function will split the filename by dot(.), and pop function will pop the last element from the array which will give you the extension as well. If there will be no extension then it will return the filename.

    for(var i = 0; i <= allowed_extensions.length; i++)
    {
        if(allowed_extensions[i]==file_extension)
        {
            return true; // valid file extension
        }
    }

    return false;
}

how to get list of port which are in use on the server

nmap is a useful tool for this kind of thing

Select NOT IN multiple columns

I use a way that may look stupid but it works for me. I simply concat the columns I want to compare and use NOT IN:

SELECT *
FROM table1 t1
WHERE CONCAT(t1.first_name,t1.last_name) NOT IN (SELECT CONCAT(t2.first_name,t2.last_name) FROM table2 t2)

How to insert strings containing slashes with sed?

sed is the stream editor, in that you can use | (pipe) to send standard streams (STDIN and STDOUT specifically) through sed and alter them programmatically on the fly, making it a handy tool in the Unix philosophy tradition; but can edit files directly, too, using the -i parameter mentioned below.
Consider the following:

sed -i -e 's/few/asd/g' hello.txt

s/ is used to substitute the found expression few with asd:

The few, the brave.


The asd, the brave.

/g stands for "global", meaning to do this for the whole line. If you leave off the /g (with s/few/asd/, there always needs to be three slashes no matter what) and few appears twice on the same line, only the first few is changed to asd:

The few men, the few women, the brave.


The asd men, the few women, the brave.

This is useful in some circumstances, like altering special characters at the beginnings of lines (for instance, replacing the greater-than symbols some people use to quote previous material in email threads with a horizontal tab while leaving a quoted algebraic inequality later in the line untouched), but in your example where you specify that anywhere few occurs it should be replaced, make sure you have that /g.

The following two options (flags) are combined into one, -ie:

-i option is used to edit in place on the file hello.txt.

-e option indicates the expression/command to run, in this case s/.

Note: It's important that you use -i -e to search/replace. If you do -ie, you create a backup of every file with the letter 'e' appended.

typecast string to integer - Postgres

You can even go one further and restrict on this coalesced field such as, for example:-

SELECT CAST(coalesce(<column>, '0') AS integer) as new_field
from <table>
where CAST(coalesce(<column>, '0') AS integer) >= 10; 

How can I simulate mobile devices and debug in Firefox Browser?

You can use the already mentioned built in Responsive Design Mode (via dev tools) for setting customised screen sizes together with the Random Agent Spoofer Plugin to modify your headers to simulate you are using Mobile, Tablet etc. Many websites specify their content according to these identified headers.

As dev tools you can use the built in Developer Tools (Ctrl + Shift + I or Cmd + Shift + I for Mac) which have become quite similar to Chrome dev tools by now.

Create an empty data.frame

If you already have an existent data frame, let's say df that has the columns you want, then you can just create an empty data frame by removing all the rows:

empty_df = df[FALSE,]

Notice that df still contains the data, but empty_df doesn't.

I found this question looking for how to create a new instance with empty rows, so I think it might be helpful for some people.

How can I find an element by CSS class with XPath?

The ONLY right way to do it with XPath :

//div[contains(concat(" ", normalize-space(@class), " "), " Test ")]

The function normalize-space strips leading and trailing whitespace, and also replaces sequences of whitespace characters by a single space.


Note

If not need many of these Xpath queries, you might want to use a library that converts CSS selectors to XPath, as CSS selectors are usually a lot easier to both read and write than XPath queries. For example, in this case, you could use both div[class~="Test"] and div.Test to get the same result.

Some libraries I've been able to find :

Rounding a double value to x number of decimal places in swift

If you want to round Double values, you might want to use Swift Decimal so you don't introduce any errors that can crop up when trying to math with these rounded values. If you use Decimal, it can accurately represent decimal values of that rounded floating point value.

So you can do:

extension Double {
    /// Convert `Double` to `Decimal`, rounding it to `scale` decimal places.
    ///
    /// - Parameters:
    ///   - scale: How many decimal places to round to. Defaults to `0`.
    ///   - mode:  The preferred rounding mode. Defaults to `.plain`.
    /// - Returns: The rounded `Decimal` value.

    func roundedDecimal(to scale: Int = 0, mode: NSDecimalNumber.RoundingMode = .plain) -> Decimal {
        var decimalValue = Decimal(self)
        var result = Decimal()
        NSDecimalRound(&result, &decimalValue, scale, mode)
        return result
    }
}

Then, you can get the rounded Decimal value like so:

let foo = 427.3000000002
let value = foo.roundedDecimal(to: 2) // results in 427.30

And if you want to display it with a specified number of decimal places (as well as localize the string for the user's current locale), you can use a NumberFormatter:

let formatter = NumberFormatter()
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 2

if let string = formatter.string(for: value) {
    print(string)
}

What is git tag, How to create tags & How to checkout git remote tag(s)

(This answer took a while to write, and codeWizard's answer is correct in aim and essence, but not entirely complete, so I'll post this anyway.)


There is no such thing as a "remote Git tag". There are only "tags". I point all this out not to be pedantic,1 but because there is a great deal of confusion about this with casual Git users, and the Git documentation is not very helpful2 to beginners. (It's not clear if the confusion comes because of poor documentation, or the poor documentation comes because this is inherently somewhat confusing, or what.)

There are "remote branches", more properly called "remote-tracking branches", but it's worth noting that these are actually local entities. There are no remote tags, though (unless you (re)invent them). There are only local tags, so you need to get the tag locally in order to use it.

The general form for names for specific commits—which Git calls references—is any string starting with refs/. A string that starts with refs/heads/ names a branch; a string starting with refs/remotes/ names a remote-tracking branch; and a string starting with refs/tags/ names a tag. The name refs/stash is the stash reference (as used by git stash; note the lack of a trailing slash).

There are some unusual special-case names that do not begin with refs/: HEAD, ORIG_HEAD, MERGE_HEAD, and CHERRY_PICK_HEAD in particular are all also names that may refer to specific commits (though HEAD normally contains the name of a branch, i.e., contains ref: refs/heads/branch). But in general, references start with refs/.

One thing Git does to make this confusing is that it allows you to omit the refs/, and often the word after refs/. For instance, you can omit refs/heads/ or refs/tags/ when referring to a local branch or tag—and in fact you must omit refs/heads/ when checking out a local branch! You can do this whenever the result is unambiguous, or—as we just noted—when you must do it (for git checkout branch).

It's true that references exist not only in your own repository, but also in remote repositories. However, Git gives you access to a remote repository's references only at very specific times: namely, during fetch and push operations. You can also use git ls-remote or git remote show to see them, but fetch and push are the more interesting points of contact.

Refspecs

During fetch and push, Git uses strings it calls refspecs to transfer references between the local and remote repository. Thus, it is at these times, and via refspecs, that two Git repositories can get into sync with each other. Once your names are in sync, you can use the same name that someone with the remote uses. There is some special magic here on fetch, though, and it affects both branch names and tag names.

You should think of git fetch as directing your Git to call up (or perhaps text-message) another Git—the "remote"—and have a conversation with it. Early in this conversation, the remote lists all of its references: everything in refs/heads/ and everything in refs/tags/, along with any other references it has. Your Git scans through these and (based on the usual fetch refspec) renames their branches.

Let's take a look at the normal refspec for the remote named origin:

$ git config --get-all remote.origin.fetch
+refs/heads/*:refs/remotes/origin/*
$ 

This refspec instructs your Git to take every name matching refs/heads/*—i.e., every branch on the remote—and change its name to refs/remotes/origin/*, i.e., keep the matched part the same, changing the branch name (refs/heads/) to a remote-tracking branch name (refs/remotes/, specifically, refs/remotes/origin/).

It is through this refspec that origin's branches become your remote-tracking branches for remote origin. Branch name becomes remote-tracking branch name, with the name of the remote, in this case origin, included. The plus sign + at the front of the refspec sets the "force" flag, i.e., your remote-tracking branch will be updated to match the remote's branch name, regardless of what it takes to make it match. (Without the +, branch updates are limited to "fast forward" changes, and tag updates are simply ignored since Git version 1.8.2 or so—before then the same fast-forward rules applied.)

Tags

But what about tags? There's no refspec for them—at least, not by default. You can set one, in which case the form of the refspec is up to you; or you can run git fetch --tags. Using --tags has the effect of adding refs/tags/*:refs/tags/* to the refspec, i.e., it brings over all tags (but does not update your tag if you already have a tag with that name, regardless of what the remote's tag says Edit, Jan 2017: as of Git 2.10, testing shows that --tags forcibly updates your tags from the remote's tags, as if the refspec read +refs/tags/*:refs/tags/*; this may be a difference in behavior from an earlier version of Git).

Note that there is no renaming here: if remote origin has tag xyzzy, and you don't, and you git fetch origin "refs/tags/*:refs/tags/*", you get refs/tags/xyzzy added to your repository (pointing to the same commit as on the remote). If you use +refs/tags/*:refs/tags/* then your tag xyzzy, if you have one, is replaced by the one from origin. That is, the + force flag on a refspec means "replace my reference's value with the one my Git gets from their Git".

Automagic tags during fetch

For historical reasons,3 if you use neither the --tags option nor the --no-tags option, git fetch takes special action. Remember that we said above that the remote starts by displaying to your local Git all of its references, whether your local Git wants to see them or not.4 Your Git takes note of all the tags it sees at this point. Then, as it begins downloading any commit objects it needs to handle whatever it's fetching, if one of those commits has the same ID as any of those tags, git will add that tag—or those tags, if multiple tags have that ID—to your repository.

Edit, Jan 2017: testing shows that the behavior in Git 2.10 is now: If their Git provides a tag named T, and you do not have a tag named T, and the commit ID associated with T is an ancestor of one of their branches that your git fetch is examining, your Git adds T to your tags with or without --tags. Adding --tags causes your Git to obtain all their tags, and also force update.

Bottom line

You may have to use git fetch --tags to get their tags. If their tag names conflict with your existing tag names, you may (depending on Git version) even have to delete (or rename) some of your tags, and then run git fetch --tags, to get their tags. Since tags—unlike remote branches—do not have automatic renaming, your tag names must match their tag names, which is why you can have issues with conflicts.

In most normal cases, though, a simple git fetch will do the job, bringing over their commits and their matching tags, and since they—whoever they are—will tag commits at the time they publish those commits, you will keep up with their tags. If you don't make your own tags, nor mix their repository and other repositories (via multiple remotes), you won't have any tag name collisions either, so you won't have to fuss with deleting or renaming tags in order to obtain their tags.

When you need qualified names

I mentioned above that you can omit refs/ almost always, and refs/heads/ and refs/tags/ and so on most of the time. But when can't you?

The complete (or near-complete anyway) answer is in the gitrevisions documentation. Git will resolve a name to a commit ID using the six-step sequence given in the link. Curiously, tags override branches: if there is a tag xyzzy and a branch xyzzy, and they point to different commits, then:

git rev-parse xyzzy

will give you the ID to which the tag points. However—and this is what's missing from gitrevisionsgit checkout prefers branch names, so git checkout xyzzy will put you on the branch, disregarding the tag.

In case of ambiguity, you can almost always spell out the ref name using its full name, refs/heads/xyzzy or refs/tags/xyzzy. (Note that this does work with git checkout, but in a perhaps unexpected manner: git checkout refs/heads/xyzzy causes a detached-HEAD checkout rather than a branch checkout. This is why you just have to note that git checkout will use the short name as a branch name first: that's how you check out the branch xyzzy even if the tag xyzzy exists. If you want to check out the tag, you can use refs/tags/xyzzy.)

Because (as gitrevisions notes) Git will try refs/name, you can also simply write tags/xyzzy to identify the commit tagged xyzzy. (If someone has managed to write a valid reference named xyzzy into $GIT_DIR, however, this will resolve as $GIT_DIR/xyzzy. But normally only the various *HEAD names should be in $GIT_DIR.)


1Okay, okay, "not just to be pedantic". :-)

2Some would say "very not-helpful", and I would tend to agree, actually.

3Basically, git fetch, and the whole concept of remotes and refspecs, was a bit of a late addition to Git, happening around the time of Git 1.5. Before then there were just some ad-hoc special cases, and tag-fetching was one of them, so it got grandfathered in via special code.

4If it helps, think of the remote Git as a flasher, in the slang meaning.

Is there a C++ decompiler?

Depending on how large and how well-written the original code was, it might be worth starting again in your favourite language (which might still be C++) and learning from any mistakes made in the last version. Didn't someone once say about writing one to throw away?

n.b. Clearly if this is a huge product, then it may not be worth the time.

how to change namespace of entire project?

You can use ReSharper for namespace refactoring. It will give 30 days free trial. It will change namespace as per folder structure.

Steps:

  1. Right click on the project/folder/files you want to refactor.

  2. If you have installed ReSharper then you will get an option Refactor->Adjust Namespaces.... So click on this.

enter image description here

It will automatically change the name spaces of all the selected files.

How to create <input type=“text”/> dynamically

I think the following link will help you. If you want to generate fields dynamically and also want to remove them on the same time you can get the help from here. I had the same question, So i got the answer

$(function() {
        var scntDiv = $('#p_scents');
        var i = $('#p_scents p').size() + 1;

        $('#addScnt').live('click', function() {
                $('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);
                i++;
                return false;
        });

        $('#remScnt').live('click', function() { 
                if( i > 2  ) {
                        $(this).parents('p').remove();
                        i--;
                }
                return false;
        });
});

http://jsfiddle.net/jaredwilli/tZPg4/4/

How to sort ArrayList<Long> in decreasing order?

The following approach will sort the list in descending order and also handles the 'null' values, just in case if you have any null values then Collections.sort() will throw NullPointerException

      Collections.sort(list, new Comparator<Long>() {
          public int compare(Long o1, Long o2) {
                  return o1==null?Integer.MAX_VALUE:o2==null?Integer.MIN_VALUE:o2.compareTo(o1);

        }
    });

NameError: name 'self' is not defined

For cases where you also wish to have the option of setting 'b' to None:

def p(self, **kwargs):
    b = kwargs.get('b', self.a)
    print b

var functionName = function() {} vs function functionName() {}

Expression in JS: Something that returns a value
Example: Try out following in chrome console:

a = 10
output : 10

(1 + 3)
output = 4

Declaration/Statement: Something that does not return a value
Example:

if (1 > 2) {
 // do something. 
}

here (1>2) is an expression but the 'if' statament is not. Its not returning anything.


Similarly, we have Function Declaration/Statement vs Function Expression
Lets take an example:

// test.js

var a = 10;

// function expression
var fun_expression = function() {
   console.log("Running function Expression");
}

// funciton expression

function fun_declaration() {
   console.log("Running function Statement");
}

Important: What happens when JavaScript engines runs the above js file.

  • When this js runs following things will happen:

    1. Memory will be created variable 'a' and 'fun_expression'. And memory will be created for function statement 'fun_declaration'
    2. 'a' will be assigned 'undefined'. 'fun_expression' will be assigned 'undefined'. 'fun_declaration' will be in the memory in its entirety.
      Note: Step 1 and 2 above are called 'Execution Context - Creation Phase'.

Now suppose we update the js to.

// test.js

console.log(a)  //output: udefined (No error)
console.log(fun_expression)  // output: undefined (No error)
console.log(fun_expression()) // output: Error. As we trying to invoke undefined. 
console.log(fun_declaration()) // output: running function statement  (As fun_declaration is already hoisted in the memory). 

var a = 10;

// function expression
var fun_expression = function() {
   console.log('Running function expression')
}

// function declaration

function fun_declaration() {
   console.log('running function declaration')
}

console.log(a)   // output: 10
console.log(fun_expression()) //output: Running function expression
console.log(fun_declaration()) //output: running function declaration

The output mentioned above in the comments, should be useful to understand the different between function expression and function statement/declaration.

Select elements by attribute

Do you mean can you select them? If so, then yes:

$(":checkbox[myattr]")

How do you migrate an IIS 7 site to another server?

I can't comment up thread due to lack of rep. Another commenter stated they couldn't migrate from a lower version to a higher version of IIS. This is true if you don't merge some files, but if you do you can as I just migrated my IIS 7.5 site to IIS 8.0 using the answer posted by chews.

When the export is created (II7.5), there are two key files (administration.config and applicationHost.config) which have references to resources on the IIS7.5 server. For example, a DLL will be referred with a public key and version specific to 7.5. These are NOT the same on the IIS8 server. The feature configuration may differ as well (I ensured mine were identical). There are some new features in 8 which will never exist in 7.5.

If you are brave enough to merge the two files - it will work. I had to uninstall IIS once because I messed it up, but got it the second time.

I used a merge tool (Beyond Compare) and without something equivalent it would be a huge PITA - but was pretty easy with a good diff tool (five minutes).

To do the merge, the 8.0 files need to be diffed against the exported 7.5 files BEFORE an import is attempted. For the most part, the 8.0 files need to overwrite the server specific stuff in the exported 7.5 files, while leaving the site/app pool specific stuff.

I found that administration.config was almost identical, sans the version info of many entries. This one was easy.

The applicationHost.config has a lot more differences. Some entries are ordered differently, but otherwise identical, so you will have to pick through each difference and figure it out.

I put my 7.5 export files in the System32\inetsrv\config\Export folder prior to merging.

I merged FROM folder System32\inetsrv\config to folder System32\inetsrv\config\Export for both files I mentioned above. I pushed over everything in the FROM files except site specific tags/elements (e.g. applicationPools, customMetadata, sites, authentication). Of special note, there were also many site specific "location" tag blocks that I had to keep, but the new server had its own "location" tag block with server specific defaults that has to be kept.

Lastly, do note that if you use service accounts, these cached passwords are junk and will have to be re-entered for your app pools. None of my sites worked initially, but all that was required was re-entering the passwords for all my app pools and I was up and running.

If someone who can comment mention this post down thread - it will probably help someone else like me who has many sites on one server with complicated configurations.

Regards,

Stuart

SQLPLUS error:ORA-12504: TNS:listener was not given the SERVICE_NAME in CONNECT_DATA

I ran into the exact same problem under identical circumstances. I don't have the tnsnames.ora file, and I wanted to use SQL*Plus with Easy Connection Identifier format in command line. I solved this problem as follows.

The SQL*Plus® User's Guide and Reference gives an example:

sqlplus hr@\"sales-server:1521/sales.us.acme.com\"

Pay attention to two important points:

  1. The connection identifier is quoted. You have two options:
    1. You can use SQL*Plus CONNECT command and simply pass quoted string.
    2. If you want to specify connection parameters on the command line then you must add backslashes as shields before quotes. It instructs the bash to pass quotes into SQL*Plus.
  2. The service name must be specified in FQDN-form as it configured by your DBA.

I found these good questions to detect service name via existing connection: 1, 2. Try this query for example:

SELECT value FROM V$SYSTEM_PARAMETER WHERE UPPER(name) = 'SERVICE_NAMES'

iOS 7 App Icons, Launch images And Naming Convention While Keeping iOS 6 Icons

You should use Asset Catalog:

I have investigated, how we can use Asset Catalog; Now it seems to be easy for me. I want to show you steps to add icons and splash in asset catalog.

Note: No need to make any entry in info.plist file :) And no any other configuration.

In below image, at right side, you will see highlighted area, where you can mention which icons you need. In case of mine, i have selected first four checkboxes; As its for my app requirements. You can select choices according to your requirements.

enter image description here

Now, see below image. As you will select any App icon then you will see its detail at right side selected area. It will help you to upload correct resolution icon. enter image description here

If Correct resolution image will not be added then following warning will come. Just upload the image with correct resolution. enter image description here

After uploading all required dimensions, you shouldn't get any warning. enter image description here

How to sort a list of strings?

The proper way to sort strings is:

import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # vary depending on your lang/locale
assert sorted((u'Ab', u'ad', u'aa'), cmp=locale.strcoll) == [u'aa', u'Ab', u'ad']

# Without using locale.strcoll you get:
assert sorted((u'Ab', u'ad', u'aa')) == [u'Ab', u'aa', u'ad']

The previous example of mylist.sort(key=lambda x: x.lower()) will work fine for ASCII-only contexts.

Is there a way to retrieve the view definition from a SQL Server using plain ADO?

For users of SQL 2000, the actual command that will provide this information is:

select c.text
from sysobjects     o
join syscomments    c on c.id = o.id
where o.name = '<view_name_here>'
  and o.type      = 'V'

Properly close mongoose's connection once you're done

Probably you have this:

const db = mongoose.connect('mongodb://localhost:27017/db');

// Do some stuff

db.disconnect();

but you can also have something like this:

mongoose.connect('mongodb://localhost:27017/db');

const model = mongoose.model('Model', ModelSchema);

model.find().then(doc => {
  console.log(doc);
}

you cannot call db.disconnect() but you can close the connection after you use it.

model.find().then(doc => {
  console.log(doc);
}).then(() => {
  mongoose.connection.close();
});

How do I disable log messages from the Requests library?

import logging
urllib3_logger = logging.getLogger('urllib3')
urllib3_logger.setLevel(logging.CRITICAL)

In this way all the messages of level=INFO from urllib3 won't be present in the logfile.

So you can continue to use the level=INFO for your log messages...just modify this for the library you are using.

PHP random string generator

This code will help:

This function will return random string with length between $maxLength and $minLength.

NOTE: Function random_bytes works since PHP 7.

If you need specific length, so $maxLength and $minLength must be same.

function getRandomString($maxLength = 20, $minLength = 10)
{
    $minLength = $maxLength < $minLength ? $maxLength : $minLength;
    $halfMin = ceil($minLength / 2);
    $halfMax = ceil($maxLength / 2);
    $bytes = random_bytes(rand($halfMin, $halfMax));
    $randomString = bin2hex($bytes);
    $randomString = strlen($randomString) > $maxLength ? substr($randomString, 0, -1) : $randomString;
    return $randomString;
}

Changing position of the Dialog on screen android

I used this code to show the dialog at the bottom of the screen:

Dialog dlg = <code to create custom dialog>;

Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();

wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);

This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about


private void showPictureialog() {
    final Dialog dialog = new Dialog(this,
            android.R.style.Theme_Translucent_NoTitleBar);

    // Setting dialogview
    Window window = dialog.getWindow();
    window.setGravity(Gravity.CENTER);

    window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    dialog.setTitle(null);
    dialog.setContentView(R.layout.selectpic_dialog);
    dialog.setCancelable(true);

    dialog.show();
}

you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment

How to view .img files?

you could use either PowerISO or WinRAR

Android SDK folder taking a lot of disk space. Do we need to keep all of the System Images?

I had 20.8 GB in the C:\Users\ggo\AppData\Local\Android\Sdk\system-images folder (6 android images: - android-10 - android-15 - android-21 - android-23 - android-25 - android-26 ).

I have compressed the C:\Users\ggo\AppData\Local\Android\Sdk\system-images folder.

Now it takes only 4.65 GB.

C:\Users\ggo\AppData\Local\Android\Sdk\system-images

I did not encountered any problem up to now...

Compression seems to vary from 2/3 to 6, sometimes much more:

android-10

android-23

android-25

android-26

What is the fastest way to transpose a matrix in C++?

Consider each row as a column, and each column as a row .. use j,i instead of i,j

demo: http://ideone.com/lvsxKZ

#include <iostream> 
using namespace std;

int main ()
{
    char A [3][3] =
    {
        { 'a', 'b', 'c' },
        { 'd', 'e', 'f' },
        { 'g', 'h', 'i' }
    };

    cout << "A = " << endl << endl;

    // print matrix A
    for (int i=0; i<3; i++)
    {
        for (int j=0; j<3; j++) cout << A[i][j];
        cout << endl;
    }

    cout << endl << "A transpose = " << endl << endl;

    // print A transpose
    for (int i=0; i<3; i++)
    {
        for (int j=0; j<3; j++) cout << A[j][i];
        cout << endl;
    }

    return 0;
}

Why is python setup.py saying invalid command 'bdist_wheel' on Travis CI?

I did apt-get install python3-dev in my Ubuntu and added setup_requires=["wheel"] in setup.py

Install NuGet via PowerShell script

Here's a short PowerShell script to do what you probably expect:

$sourceNugetExe = "https://dist.nuget.org/win-x86-commandline/latest/nuget.exe"
$targetNugetExe = "$rootPath\nuget.exe"
Invoke-WebRequest $sourceNugetExe -OutFile $targetNugetExe
Set-Alias nuget $targetNugetExe -Scope Global -Verbose

Note that Invoke-WebRequest cmdlet arrived with PowerShell v3.0. This article gives the idea.

Command-line Git on Windows

These instructions worked for a Windows 8 with a msysgit/TortoiseGit installation, but should be applicable for other types of git installations on Windows.

  • Go to Control Panel\System and Security\System
  • Click on Advanced System Settings on the left which opens System Properties.
  • Click on the Advanced Tab
  • Click on the Environment Variables button at the bottom of the dialog box.
  • Edit the System Variable called PATH.
  • Append these two paths to the list of existing paths already present in the system variable. The tricky part was two paths were required. These paths may vary for your PC. ;C:\msysgit\bin\;C:\msysgit\mingw\bin\
  • Close the CMD prompt window if it is open already. CMD needs to restart to get the updated Path variable.
  • Try typing git in the command line, you should see a list of the git commands scroll down the screen.

How do I list the symbols in a .so file

For Android .so files, the NDK toolchain comes with the required tools mentioned in the other answers: readelf, objdump and nm.

PHP check whether property exists in object or class

If you want to know if a property exists in an instance of a class that you have defined, simply combine property_exists() with isset().

public function hasProperty($property)
{
    return property_exists($this, $property) && isset($this->$property);
}

LINQ Orderby Descending Query

Just to show it in a different format that I prefer to use for some reason: The first way returns your itemList as an System.Linq.IOrderedQueryable

using(var context = new ItemEntities())
{
    var itemList = context.Items.Where(x => !x.Items && x.DeliverySelection)
                                .OrderByDescending(x => x.Delivery.SubmissionDate);
}

That approach is fine, but if you wanted it straight into a List Object:

var itemList = context.Items.Where(x => !x.Items && x.DeliverySelection)
                                .OrderByDescending(x => x.Delivery.SubmissionDate).ToList();

All you have to do is append a .ToList() call to the end of the Query.

Something to note, off the top of my head I can't recall if the !(not) expression is acceptable in the Where() call.

How to get the selected row values of DevExpress XtraGrid?

All you have to do is use the GetFocusedRowCellValue method of the gridView control and put it into the RowClick event.

For example:

private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
{
    if (this.gvCodigoNombres.GetFocusedRowCellValue("EMP_dni") == null)
        return;
    MessageBox.Show(""+this.gvCodigoNombres.GetFocusedRowCellValue("EMP_dni").ToString());            
}

Should a retrieval method return 'null' or throw an exception when it can't produce the return value?

it depends if your language and code promotes: LBYL (look before you leap) or EAFP (easier to ask forgiveness than permission)

LBYL says you should check for values (so return a null)
EAFP says to just try the operation and see if it fails (throw an exception)

though I agree with above.. exceptions should be used for exceptional/error conditions, and returning a null is best when using checks.


EAFP vs. LBYL in Python:
http://mail.python.org/pipermail/python-list/2003-May/205182.html (Web Archive)

Batch script: how to check for admin rights

Issues

blak3r / Rushyo's solution works fine for everything except Windows 8. Running AT on Windows 8 results in:

The AT command has been deprecated. Please use schtasks.exe instead.

The request is not supported.

(see screenshot #1) and will return %errorLevel% 1.

 

Research

So, I went searching for other commands that require elevated permissions. rationallyparanoid.com had a list of a few, so I ran each command on the two opposite extremes of current Windows OSs (XP and 8) in the hopes of finding a command that would be denied access on both OSs when run with standard permissions.

Eventually, I did find one - NET SESSION. A true, clean, universal solution that doesn't involve:

  • the creation of or interaction with data in secure locations
  • analyzing data returned from FOR loops
  • searching strings for "Administrator"
  • using AT (Windows 8 incompatible) or WHOAMI (Windows XP incompatible).

Each of which have their own security, usability, and portability issues.

 

Testing

I've independently confirmed that this works on:

  • Windows XP, x86
  • Windows XP, x64
  • Windows Vista, x86
  • Windows Vista, x64
  • Windows 7, x86
  • Windows 7, x64
  • Windows 8, x86
  • Windows 8, x64
  • Windows 10 v1909, x64

(see screenshot #2)

 

Implementation / Usage

So, to use this solution, simply do something like this:

@echo off
goto check_Permissions

:check_Permissions
    echo Administrative permissions required. Detecting permissions...

    net session >nul 2>&1
    if %errorLevel% == 0 (
        echo Success: Administrative permissions confirmed.
    ) else (
        echo Failure: Current permissions inadequate.
    )

    pause >nul

Available here, if you're lazy: https://dl.dropbox.com/u/27573003/Distribution/Binaries/check_Permissions.bat

 

Explanation

NET SESSION is a standard command used to "manage server computer connections. Used without parameters, [it] displays information about all sessions with the local computer."

So, here's the basic process of my given implementation:

  1. @echo off
    • Disable displaying of commands
  2. goto check_Permissions
    • Jump to the :check_Permissions code block
  3. net session >nul 2>&1
    • Run command
    • Hide visual output of command by
      1. Redirecting the standard output (numeric handle 1 / STDOUT) stream to nul
      2. Redirecting the standard error output stream (numeric handle 2 / STDERR) to the same destination as numeric handle 1
  4. if %errorLevel% == 0
    • If the value of the exit code (%errorLevel%) is 0 then this means that no errors have occurred and, therefore, the immediate previous command ran successfully
  5. else
    • If the value of the exit code (%errorLevel%) is not 0 then this means that errors have occurred and, therefore, the immediate previous command ran unsuccessfully
  6. The code between the respective parenthesis will be executed depending on which criteria is met

 

Screenshots

Windows 8 AT %errorLevel%:

[imgur]

 

NET SESSION on Windows XP x86 - Windows 8 x64:

[imgur]

 

Thank you, @Tilka, for changing your accepted answer to mine. :)

Presenting a UIAlertController properly on an iPad using iOS 8

Swift 4.2 You can use condition like that:

let alert = UIAlertController(title: nil, message: nil, preferredStyle: UIDevice.current.userInterfaceIdiom == .pad ? .alert : .actionSheet)

Boolean vs boolean in Java

Boolean wraps the boolean primitive type. In JDK 5 and upwards, Oracle (or Sun before Oracle bought them) introduced autoboxing/unboxing, which essentially allows you to do this

boolean result = Boolean.TRUE;

or

Boolean result = true; 

Which essentially the compiler does,

Boolean result = Boolean.valueOf(true);

So, for your answer, it's YES.

How do I concatenate a string with a variable?

Another way to do it simpler using jquery.

sample:

function add(product_id){

    // the code to add the product
    //updating the div, here I just change the text inside the div. 
    //You can do anything with jquery, like change style, border etc.
    $("#added_"+product_id).html('the product was added to list');

}

Where product_id is the javascript var and$("#added_"+product_id) is a div id concatenated with product_id, the var from function add.

Best Regards!

How do I use Wget to download all images into a single folder, from a URL?

According to the man page the -P flag is:

-P prefix --directory-prefix=prefix Set directory prefix to prefix. The directory prefix is the directory where all other files and subdirectories will be saved to, i.e. the top of the retrieval tree. The default is . (the current directory).

This mean that it only specifies the destination but where to save the directory tree. It does not flatten the tree into just one directory. As mentioned before the -nd flag actually does that.

@Jon in the future it would be beneficial to describe what the flag does so we understand how something works.

var self = this?

This question is not specific to jQuery, but specific to JavaScript in general. The core problem is how to "channel" a variable in embedded functions. This is the example:

var abc = 1; // we want to use this variable in embedded functions

function xyz(){
  console.log(abc); // it is available here!
  function qwe(){
    console.log(abc); // it is available here too!
  }
  ...
};

This technique relies on using a closure. But it doesn't work with this because this is a pseudo variable that may change from scope to scope dynamically:

// we want to use "this" variable in embedded functions

function xyz(){
  // "this" is different here!
  console.log(this); // not what we wanted!
  function qwe(){
    // "this" is different here too!
    console.log(this); // not what we wanted!
  }
  ...
};

What can we do? Assign it to some variable and use it through the alias:

var abc = this; // we want to use this variable in embedded functions

function xyz(){
  // "this" is different here! --- but we don't care!
  console.log(abc); // now it is the right object!
  function qwe(){
    // "this" is different here too! --- but we don't care!
    console.log(abc); // it is the right object here too!
  }
  ...
};

this is not unique in this respect: arguments is the other pseudo variable that should be treated the same way — by aliasing.

Using PHP variables inside HTML tags?

You can do it a number of ways, depending on the type of quotes you use:

  • echo "<a href='http://www.whatever.com/$param'>Click here</a>";
  • echo "<a href='http://www.whatever.com/{$param}'>Click here</a>";
  • echo '<a href="http://www.whatever.com/' . $param . '">Click here</a>';
  • echo "<a href=\"http://www.whatever.com/$param\">Click here</a>";

Double quotes allow for variables in the middle of the string, where as single quotes are string literals and, as such, interpret everything as a string of characters -- nothing more -- not even \n will be expanded to mean the new line character, it will just be the characters \ and n in sequence.

You need to be careful about your use of whichever type of quoting you decide. You can't use double quotes inside a double quoted string (as in your example) as you'll be ending the string early, which isn't what you want. You can escape the inner double quotes, however, by adding a backslash.

On a separate note, you might need to be careful about XSS attacks when printing unsafe variables (populated by the user) out to the browser.

How to clear a data grid view

For having a Datagrid you must have a method which is formatting your Datagrid. If you want clear the Datagrid you just recall the method.

Here is my method:

    public string[] dgv_Headers = new string[] { "Id","Hotel", "Lunch", "Dinner", "Excursions", "Guide", "Bus" }; // This defined at Public partial class


    private void SetDgvHeader()
    {
        dgv.Rows.Clear();
        dgv.ColumnCount = 7;
        dgv.RowHeadersVisible = false;
        int Nbr = int.Parse(daysBox.Text);  // in my method it's the textbox where i keep the number of rows I have to use
        dgv.Rows.Add(Nbr);
        for(int i =0; i<Nbr;++i)
            dgv.Rows[i].Height = 20;
        for (int i = 0; i < dgv_Headers.Length; ++i)
        {
            if(i==0)
                dgv.Columns[i].Visible = false;  // I need an invisible cells if you don't need you can skip it
            else
                dgv.Columns[i].Width = 78;
            dgv.Columns[i].HeaderText = dgv_Headers[i];
        }
        dgv.Height = (Nbr* dgv.Rows[0].Height) + 35;
        dgv.AllowUserToAddRows = false;
    }

dgv is the name of DataGridView

Why am I getting error for apple-touch-icon-precomposed.png

Simply create zero-sized files called the appropriate names.

The request will be satisfied with no additional data transfer nor further logging lines.

Regular Expression to match valid dates

A slightly different approach that may or may not be useful for you.

I'm in php.

The project this relates to will never have a date prior to the 1st of January 2008. So, I take the 'date' inputed and use strtotime(). If the answer is >= 1199167200 then I have a date that is useful to me. If something that doesn't look like a date is entered -1 is returned. If null is entered it does return today's date number so you do need a check for a non-null entry first.

Works for my situation, perhaps yours too?

How do you convert between 12 hour time and 24 hour time in PHP?

// 24-hour time to 12-hour time 
$time_in_12_hour_format  = date("g:i a", strtotime("13:30"));

// 12-hour time to 24-hour time 
$time_in_24_hour_format  = date("H:i", strtotime("1:30 PM"));

How can I use the apply() function for a single column?

Given a sample dataframe df as:

a,b
1,2
2,3
3,4
4,5

what you want is:

df['a'] = df['a'].apply(lambda x: x + 1)

that returns:

   a  b
0  2  2
1  3  3
2  4  4
3  5  5

How to use in jQuery :not and hasClass() to get a specific element without a class

Use the not function instead:

var lastOpenSite = $(this).siblings().not('.closedTab');

hasClass only tests whether an element has a class, not will remove elements from the selected set matching the provided selector.

Using getline() in C++

If you only have a single newline in the input, just doing

std::cin.ignore();

will work fine. It reads and discards the next character from the input.

But if you have anything else still in the input, besides the newline (for example, you read one word but the user entered two words), then you have to do

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

See e.g. this reference of the ignore function.

To be even more safe, do the second alternative above in a loop until gcount returns zero.

Format a datetime into a string with milliseconds

from datetime import datetime
from time import clock

t = datetime.utcnow()
print 't == %s    %s\n\n' % (t,type(t))

n = 100000

te = clock()
for i in xrange(1):
    t_stripped = t.strftime('%Y%m%d%H%M%S%f')
print clock()-te
print t_stripped," t.strftime('%Y%m%d%H%M%S%f')"

print

te = clock()
for i in xrange(1):
    t_stripped = str(t).replace('-','').replace(':','').replace('.','').replace(' ','')
print clock()-te
print t_stripped," str(t).replace('-','').replace(':','').replace('.','').replace(' ','')"

print

te = clock()
for i in xrange(n):
    t_stripped = str(t).translate(None,' -:.')
print clock()-te
print t_stripped," str(t).translate(None,' -:.')"

print

te = clock()
for i in xrange(n):
    s = str(t)
    t_stripped = s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] + s[20:] 
print clock()-te
print t_stripped," s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] + s[20:] "

result

t == 2011-09-28 21:31:45.562000    <type 'datetime.datetime'>


3.33410112179
20110928212155046000  t.strftime('%Y%m%d%H%M%S%f')

1.17067364707
20110928212130453000 str(t).replace('-','').replace(':','').replace('.','').replace(' ','')

0.658806915404
20110928212130453000 str(t).translate(None,' -:.')

0.645189262881
20110928212130453000 s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] + s[20:]

Use of translate() and slicing method run in same time
translate() presents the advantage to be usable in one line

Comparing the times on the basis of the first one:

1.000 * t.strftime('%Y%m%d%H%M%S%f')

0.351 * str(t).replace('-','').replace(':','').replace('.','').replace(' ','')

0.198 * str(t).translate(None,' -:.')

0.194 * s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] + s[20:]

How to use S_ISREG() and S_ISDIR() POSIX Macros?

[Posted on behalf of fossuser] Thanks to "mu is too short" I was able to fix the bug. Here is my working code has been edited in for those looking for a nice example (since I couldn't find any others online).

#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <dirent.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

void helper(DIR *, struct dirent *, struct stat, char *, int, char **);
void dircheck(DIR *, struct dirent *, struct stat, char *, int, char **);

int main(int argc, char *argv[]){

  DIR *dip;
  struct dirent *dit;
  struct stat statbuf;
  char currentPath[FILENAME_MAX];
  int depth = 0; /*Used to correctly space output*/

  /*Open Current Directory*/
  if((dip = opendir(".")) == NULL)
    return errno;

  /*Store Current Working Directory in currentPath*/
  if((getcwd(currentPath, FILENAME_MAX)) == NULL)
    return errno;

  /*Read all items in directory*/
  while((dit = readdir(dip)) != NULL){

    /*Skips . and ..*/
    if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)
      continue;

    /*Correctly forms the path for stat and then resets it for rest of algorithm*/
    getcwd(currentPath, FILENAME_MAX);
    strcat(currentPath, "/");
    strcat(currentPath, dit->d_name);
    if(stat(currentPath, &statbuf) == -1){
      perror("stat");
      return errno;
    }
    getcwd(currentPath, FILENAME_MAX);


    /*Checks if current item is of the type file (type 8) and no command line arguments*/
    if(S_ISREG(statbuf.st_mode) && argv[1] == NULL)
      printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);

    /*If a command line argument is given, checks for filename match*/
    if(S_ISREG(statbuf.st_mode) && argv[1] != NULL)
      if(strcmp(dit->d_name, argv[1]) == 0)
         printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);

    /*Checks if current item is of the type directory (type 4)*/
    if(S_ISDIR(statbuf.st_mode))
      dircheck(dip, dit, statbuf, currentPath, depth, argv);

  }
  closedir(dip);
  return 0;
}

/*Recursively called helper function*/
void helper(DIR *dip, struct dirent *dit, struct stat statbuf, 
        char currentPath[FILENAME_MAX], int depth, char *argv[]){
  int i = 0;

  if((dip = opendir(currentPath)) == NULL)
    printf("Error: Failed to open Directory ==> %s\n", currentPath);

  while((dit = readdir(dip)) != NULL){

    if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)
      continue;

    strcat(currentPath, "/");
    strcat(currentPath, dit->d_name);
    stat(currentPath, &statbuf);
    getcwd(currentPath, FILENAME_MAX);

    if(S_ISREG(statbuf.st_mode) && argv[1] == NULL){
      for(i = 0; i < depth; i++)
    printf("    ");
      printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
    }

    if(S_ISREG(statbuf.st_mode) && argv[1] != NULL){
      if(strcmp(dit->d_name, argv[1]) == 0){
    for(i = 0; i < depth; i++)
      printf("    ");
    printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
      }
    }

    if(S_ISDIR(statbuf.st_mode))
      dircheck(dip, dit, statbuf, currentPath, depth, argv);
  }
  /*Changing back here is necessary because of how stat is done*/
    chdir("..");
    closedir(dip);
}

void dircheck(DIR *dip, struct dirent *dit, struct stat statbuf, 
          char currentPath[FILENAME_MAX], int depth, char *argv[]){
  int i = 0;

  strcat(currentPath, "/");
  strcat(currentPath, dit->d_name);

  /*If two directories exist at the same level the path
    is built wrong and needs to be corrected*/
  if((chdir(currentPath)) == -1){
    chdir("..");
    getcwd(currentPath, FILENAME_MAX);
    strcat(currentPath, "/");
    strcat(currentPath, dit->d_name);

    for(i = 0; i < depth; i++)
      printf ("    ");
    printf("%s (subdirectory)\n", dit->d_name);
    depth++;
    helper(dip, dit, statbuf, currentPath, depth, argv);
  }

  else{
    for(i =0; i < depth; i++)
      printf("    ");
    printf("%s (subdirectory)\n", dit->d_name);
    chdir(currentPath);
    depth++;
    helper(dip, dit, statbuf, currentPath, depth, argv);
  }
}

Android map v2 zoom to show all the markers

You should use the CameraUpdate class to do (probably) all programmatic map movements.

To do this, first calculate the bounds of all the markers like so:

LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (Marker marker : markers) {
    builder.include(marker.getPosition());
}
LatLngBounds bounds = builder.build();

Then obtain a movement description object by using the factory: CameraUpdateFactory:

int padding = 0; // offset from edges of the map in pixels
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, padding);

Finally move the map:

googleMap.moveCamera(cu);

Or if you want an animation:

googleMap.animateCamera(cu);

That's all :)

Clarification 1

Almost all movement methods require the Map object to have passed the layout process. You can wait for this to happen using the addOnGlobalLayoutListener construct. Details can be found in comments to this answer and remaining answers. You can also find a complete code for setting map extent using addOnGlobalLayoutListener here.

Clarification 2

One comment notes that using this method for only one marker results in map zoom set to a "bizarre" zoom level (which I believe to be maximum zoom level available for given location). I think this is expected because:

  1. The LatLngBounds bounds instance will have northeast property equal to southwest, meaning that the portion of area of the earth covered by this bounds is exactly zero. (This is logical since a single marker has no area.)
  2. By passing bounds to CameraUpdateFactory.newLatLngBounds you essentially request a calculation of such a zoom level that bounds (having zero area) will cover the whole map view.
  3. You can actually perform this calculation on a piece of paper. The theoretical zoom level that is the answer is +∞ (positive infinity). In practice the Map object doesn't support this value so it is clamped to a more reasonable maximum level allowed for given location.

Another way to put it: how can Map object know what zoom level should it choose for a single location? Maybe the optimal value should be 20 (if it represents a specific address). Or maybe 11 (if it represents a town). Or maybe 6 (if it represents a country). API isn't that smart and the decision is up to you.

So, you should simply check if markers has only one location and if so, use one of:

  • CameraUpdate cu = CameraUpdateFactory.newLatLng(marker.getPosition()) - go to marker position, leave current zoom level intact.
  • CameraUpdate cu = CameraUpdateFactory.newLatLngZoom(marker.getPosition(), 12F) - go to marker position, set zoom level to arbitrarily chosen value 12.

Ripple effect on Android Lollipop CardView

If there is a root layout like RelativeLayout or LinearLayout which contain all of the adapter item's component in CardView, you have to set background attribute in that root layout. like:

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="122dp"
android:layout_marginBottom="6dp"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
card_view:cardCornerRadius="4dp">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/touch_bg"/>
</android.support.v7.widget.CardView>

How to split a comma-separated string?

You can use something like this:

String animals = "dog, cat, bear, elephant, giraffe";

List<String> animalList = Arrays.asList(animals.split(","));

Also, you'd include the libs:

import java.util.ArrayList;
import java.util.Arrays; 
import java.util.List;

How do I convert uint to int in C#?

Assuming you want to simply lift the 32bits from one type and dump them as-is into the other type:

uint asUint = unchecked((uint)myInt);
int asInt = unchecked((int)myUint);

The destination type will blindly pick the 32 bits and reinterpret them.

Conversely if you're more interested in keeping the decimal/numerical values within the range of the destination type itself:

uint asUint = checked((uint)myInt);
int asInt = checked((int)myUint);

In this case, you'll get overflow exceptions if:

  • casting a negative int (eg: -1) to an uint
  • casting a positive uint between 2,147,483,648 and 4,294,967,295 to an int

In our case, we wanted the unchecked solution to preserve the 32bits as-is, so here are some examples:

Examples

int => uint

int....: 0000000000 (00-00-00-00)
asUint.: 0000000000 (00-00-00-00)
------------------------------
int....: 0000000001 (01-00-00-00)
asUint.: 0000000001 (01-00-00-00)
------------------------------
int....: -0000000001 (FF-FF-FF-FF)
asUint.: 4294967295 (FF-FF-FF-FF)
------------------------------
int....: 2147483647 (FF-FF-FF-7F)
asUint.: 2147483647 (FF-FF-FF-7F)
------------------------------
int....: -2147483648 (00-00-00-80)
asUint.: 2147483648 (00-00-00-80)

uint => int

uint...: 0000000000 (00-00-00-00)
asInt..: 0000000000 (00-00-00-00)
------------------------------
uint...: 0000000001 (01-00-00-00)
asInt..: 0000000001 (01-00-00-00)
------------------------------
uint...: 2147483647 (FF-FF-FF-7F)
asInt..: 2147483647 (FF-FF-FF-7F)
------------------------------
uint...: 4294967295 (FF-FF-FF-FF)
asInt..: -0000000001 (FF-FF-FF-FF)
------------------------------

Code

int[] testInts = { 0, 1, -1, int.MaxValue, int.MinValue };
uint[] testUints = { uint.MinValue, 1, uint.MaxValue / 2, uint.MaxValue };

foreach (var Int in testInts)
{
    uint asUint = unchecked((uint)Int);
    Console.WriteLine("int....: {0:D10} ({1})", Int, BitConverter.ToString(BitConverter.GetBytes(Int)));
    Console.WriteLine("asUint.: {0:D10} ({1})", asUint, BitConverter.ToString(BitConverter.GetBytes(asUint)));
    Console.WriteLine(new string('-',30));
}
Console.WriteLine(new string('=', 30));
foreach (var Uint in testUints)
{
    int asInt = unchecked((int)Uint);
    Console.WriteLine("uint...: {0:D10} ({1})", Uint, BitConverter.ToString(BitConverter.GetBytes(Uint)));
    Console.WriteLine("asInt..: {0:D10} ({1})", asInt, BitConverter.ToString(BitConverter.GetBytes(asInt)));
    Console.WriteLine(new string('-', 30));
}  

This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint

Follow these steps:
Right click on designing part > Constraint Layout > Infer Constraints

Is it possible in Java to access private fields via reflection

Yes, it absolutely is - assuming you've got the appropriate security permissions. Use Field.setAccessible(true) first if you're accessing it from a different class.

import java.lang.reflect.*;

class Other
{
    private String str;
    public void setStr(String value)
    {
        str = value;
    }
}

class Test
{
    public static void main(String[] args)
        // Just for the ease of a throwaway test. Don't
        // do this normally!
        throws Exception
    {
        Other t = new Other();
        t.setStr("hi");
        Field field = Other.class.getDeclaredField("str");
        field.setAccessible(true);
        Object value = field.get(t);
        System.out.println(value);
    }
}

And no, you shouldn't normally do this... it's subverting the intentions of the original author of the class. For example, there may well be validation applied in any situation where the field can normally be set, or other fields may be changed at the same time. You're effectively violating the intended level of encapsulation.

printing all contents of array in C#

If you do not want to use the Array function.

public class GArray
{
    int[] mainArray;
    int index;
    int i = 0;

    public GArray()
    {
        index = 0;
        mainArray = new int[4];
    }
    public void add(int addValue)
    {

        if (index == mainArray.Length)
        {
            int newSize = index * 2;
            int[] temp = new int[newSize];
            for (int i = 0; i < mainArray.Length; i++)
            {
                temp[i] = mainArray[i];
            }
            mainArray = temp;
        }
        mainArray[index] = addValue;
        index++;

    }
    public void print()
    {
        for (int i = 0; i < index; i++)
        {
            Console.WriteLine(mainArray[i]);
        }
    }
 }
 class Program
{
    static void Main(string[] args)
    {
        GArray myArray = new GArray();
        myArray.add(1);
        myArray.add(2);
        myArray.add(3);
        myArray.add(4);
        myArray.add(5);
        myArray.add(6);
        myArray.print();
        Console.ReadKey();
    }
}

Git diff says subproject is dirty

git submodule foreach --recursive git checkout .

This didn't do the trick for me but it gave me a list of files (in my case only one) that had been changed in the submodule (without me doing anything there).

So I could head over to the submodule and git status showed me that my HEAD was detached -> git checkout master, git status to see the modified file once again, git checkout >filename<, git pull and everything fine again.

import android packages cannot be resolved

What all the others said.

Specifically, I recommend you go to Project > Properties > Java Build Path > Libraries and make sure you have exactly one copy of android.jar referenced. (Sometimes you can get two if you're importing a project.) And that its path is correct.

Sometimes you can get the system to resolve this for you by clicking a different target SDK in Project > Properties > Android, then restoring your original selection.

Android Canvas.drawText

It should be noted that the documentation recommends using a Layout rather than Canvas.drawText directly. My full answer about using a StaticLayout is here, but I will provide a summary below.

String text = "This is some text.";

TextPaint textPaint = new TextPaint();
textPaint.setAntiAlias(true);
textPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
textPaint.setColor(0xFF000000);

int width = (int) textPaint.measureText(text);
StaticLayout staticLayout = new StaticLayout(text, textPaint, (int) width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
staticLayout.draw(canvas);

Here is a fuller example in the context of a custom view:

enter image description here

public class MyView extends View {

    String mText = "This is some text.";
    TextPaint mTextPaint;
    StaticLayout mStaticLayout;

    // use this constructor if creating MyView programmatically
    public MyView(Context context) {
        super(context);
        initLabelView();
    }

    // this constructor is used when created from xml
    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initLabelView();
    }

    private void initLabelView() {
        mTextPaint = new TextPaint();
        mTextPaint.setAntiAlias(true);
        mTextPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
        mTextPaint.setColor(0xFF000000);

        // default to a single line of text
        int width = (int) mTextPaint.measureText(mText);
        mStaticLayout = new StaticLayout(mText, mTextPaint, (int) width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);

        // New API alternate
        //
        // StaticLayout.Builder builder = StaticLayout.Builder.obtain(mText, 0, mText.length(), mTextPaint, width)
        //        .setAlignment(Layout.Alignment.ALIGN_NORMAL)
        //        .setLineSpacing(1, 0) // multiplier, add
        //        .setIncludePad(false);
        // mStaticLayout = builder.build();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // Tell the parent layout how big this view would like to be
        // but still respect any requirements (measure specs) that are passed down.

        // determine the width
        int width;
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthRequirement = MeasureSpec.getSize(widthMeasureSpec);
        if (widthMode == MeasureSpec.EXACTLY) {
            width = widthRequirement;
        } else {
            width = mStaticLayout.getWidth() + getPaddingLeft() + getPaddingRight();
            if (widthMode == MeasureSpec.AT_MOST) {
                if (width > widthRequirement) {
                    width = widthRequirement;
                    // too long for a single line so relayout as multiline
                    mStaticLayout = new StaticLayout(mText, mTextPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
                }
            }
        }

        // determine the height
        int height;
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightRequirement = MeasureSpec.getSize(heightMeasureSpec);
        if (heightMode == MeasureSpec.EXACTLY) {
            height = heightRequirement;
        } else {
            height = mStaticLayout.getHeight() + getPaddingTop() + getPaddingBottom();
            if (heightMode == MeasureSpec.AT_MOST) {
                height = Math.min(height, heightRequirement);
            }
        }

        // Required call: set width and height
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // do as little as possible inside onDraw to improve performance

        // draw the text on the canvas after adjusting for padding
        canvas.save();
        canvas.translate(getPaddingLeft(), getPaddingTop());
        mStaticLayout.draw(canvas);
        canvas.restore();
    }
}

Reporting Services export to Excel with Multiple Worksheets

To late for the original asker of the question, but with SQL Server 2008 R2 this is now possible:

Set the property "Pagebreak" on the tablix or table or other element to force a new tab, and then set the property "Pagename" on both the element before the pagebreak and the element after the pagebreak. These names will appear on the tabs when the report is exported to Excel.

Read about it here: http://technet.microsoft.com/en-us/library/dd255278.aspx

res.sendFile absolute path

I use Node.Js and had the same problem... I solved just adding a '/' in the beggining of every script and link to an css static file.

Before:

<link rel="stylesheet" href="assets/css/bootstrap/bootstrap.min.css">

After:

<link rel="stylesheet" href="/assets/css/bootstrap/bootstrap.min.css">

How to loop through files matching wildcard in batch file

Assuming you have two programs that process the two files, process_in.exe and process_out.exe:

for %%f in (*.in) do (
    echo %%~nf
    process_in "%%~nf.in"
    process_out "%%~nf.out"
)

%%~nf is a substitution modifier, that expands %f to a file name only. See other modifiers in https://technet.microsoft.com/en-us/library/bb490909.aspx (midway down the page) or just in the next answer.

Get index of current item in a PowerShell loop

I am not sure it's possible with an "automatic" variable. You can always declare one for yourself and increment it:

$letters = { 'A', 'B', 'C' }
$letters | % {$counter = 0}{...;$counter++}

Or use a for loop instead...

for ($counter=0; $counter -lt $letters.Length; $counter++){...}

Named colors in matplotlib

To get a full list of colors to use in plots:

import matplotlib.colors as colors
colors_list = list(colors._colors_full_map.values())

So, you can use in that way quickly:

scatter(X,Y, color=colors_list[0])
scatter(X,Y, color=colors_list[1])
scatter(X,Y, color=colors_list[2])
...
scatter(X,Y, color=colors_list[-1])

Concatenating Column Values into a Comma-Separated List

SELECT LEFT(Car, LEN(Car) - 1)
FROM (
    SELECT Car + ', '
    FROM Cars
    FOR XML PATH ('')
  ) c (Car)

Sorting a vector of custom objects

typedef struct Freqamp{
    double freq;
    double amp;
}FREQAMP;

bool struct_cmp_by_freq(FREQAMP a, FREQAMP b)
{
    return a.freq < b.freq;
}

main()
{
    vector <FREQAMP> temp;
    FREQAMP freqAMP;

    freqAMP.freq = 330;
    freqAMP.amp = 117.56;
    temp.push_back(freqAMP);

    freqAMP.freq = 450;
    freqAMP.amp = 99.56;
    temp.push_back(freqAMP);

    freqAMP.freq = 110;
    freqAMP.amp = 106.56;
    temp.push_back(freqAMP);

    sort(temp.begin(),temp.end(), struct_cmp_by_freq);
}

if compare is false, it will do "swap".

serialize/deserialize java 8 java.time with Jackson JSON mapper

This is just an example how to use it in a unit test that I hacked to debug this issue. The key ingredients are

  • mapper.registerModule(new JavaTimeModule());
  • maven dependency of <artifactId>jackson-datatype-jsr310</artifactId>

Code:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.io.IOException;
import java.io.Serializable;
import java.time.Instant;

class Mumu implements Serializable {
    private Instant from;
    private String text;

    Mumu(Instant from, String text) {
        this.from = from;
        this.text = text;
    }

    public Mumu() {
    }

    public Instant getFrom() {
        return from;
    }

    public String getText() {
        return text;
    }

    @Override
    public String toString() {
        return "Mumu{" +
                "from=" + from +
                ", text='" + text + '\'' +
                '}';
    }
}
public class Scratch {


    @Test
    public void JacksonInstant() throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JavaTimeModule());

        Mumu before = new Mumu(Instant.now(), "before");
        String jsonInString = mapper.writeValueAsString(before);


        System.out.println("-- BEFORE --");
        System.out.println(before);
        System.out.println(jsonInString);

        Mumu after = mapper.readValue(jsonInString, Mumu.class);
        System.out.println("-- AFTER --");
        System.out.println(after);

        Assert.assertEquals(after.toString(), before.toString());
    }

}

How to create a link to another PHP page

Easiest:

<a href="page2.php">Link</a>

And if you need to pass a value:

<a href="page2.php?val=1">Link that pass the value 1</a>

To retrive the value put in page2.php this code:

<?php
$val = $_GET["val"];
?>

Now the variable $val has the value 1.

Checking for a null object in C++

A reference can not be NULL. The interface makes you pass a real object into the function.

So there is no need to test for NULL. This is one of the reasons that references were introduced into C++.

Note you can still write a function that takes a pointer. In this situation you still need to test for NULL. If the value is NULL then you return early just like in C. Note: You should not be using exceptions when a pointer is NULL. If a parameter should never be NULL then you create an interface that uses a reference.

How to display request headers with command line curl

If you want more alternatives, You can try installing a Modern command line HTTP client like httpie which is available for most of the Operating Systems with package managers like brew, apt-get, pip, yum etc

eg:- For OSX

brew install httpie

Then you can use it on command line with various options

http GET https://www.google.com

enter image description here

How to set a default value for an existing column

cannot use alter column for that, use add instead

ALTER TABLE Employee 
ADD DEFAULT('SANDNES') FOR CityBorn

How to paste into a terminal?

On windows 7:

Ctrl + Shift + Ins

works for me!

Click a button programmatically

in c# this is working :D

protect void button1_Click(object sender, EventArgs e){
    button2_Click(button2, null);
}

protect void button2_Click(object sender, EventeArgs e){
    //some codes here
}

for vb.net

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)   Handles Button1.Click
    Button2_Click(Sender, e)
End Sub

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs)   Handles Button2.Click
    //some codes here
End Sub

How to implement a secure REST API with node.js

I just finished a sample app that does this in a pretty basic, but clear way. It uses mongoose with mongodb to store users and passport for auth management.

https://github.com/Khelldar/Angular-Express-Train-Seed

What is "with (nolock)" in SQL Server?

NOLOCK is equivalent to READ UNCOMMITTED, however Microsoft says you should not use it for UPDATE or DELETE statements:

For UPDATE or DELETE statements: This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications that currently use this feature.

http://msdn.microsoft.com/en-us/library/ms187373.aspx

This article applies to SQL Server 2005, so the support for NOLOCK exists if you are using that version. In order to future-proof you code (assuming you've decided to use dirty reads) you could use this in your stored procedures:

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

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

J2ME Map Route Provider

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

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

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

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

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

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

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

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

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

 public static Road getRoute(InputStream is) 

Full source code RoadProvider.java

BlackBerry

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

See full code on J2MEMapRouteBlackBerryEx on Google Code

Android

Android G1 screenshot

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

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

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

See full code on J2MEMapRouteAndroidEx on Google Code

SQL Server - find nth occurrence in a string

DECLARE @T AS TABLE(pic_name VARCHAR(100));
INSERT INTO @T VALUES ('abc_1_2_3_4.gif'),('zzz_12_3_3_45.gif');

SELECT A.pic_name, P1.D, P2.D, P3.D, P4.D 
FROM @T A
CROSS APPLY (SELECT NULLIF(CHARINDEX('_', A.pic_name),0) AS D)  P1
CROSS APPLY (SELECT NULLIF(CHARINDEX('_', A.pic_name, P1.D+1), 0) AS D)  P2
CROSS APPLY (SELECT NULLIF(CHARINDEX('_', A.pic_name, P2.D+1),0) AS D)  P3
CROSS APPLY (SELECT NULLIF(CHARINDEX('_', A.pic_name, P3.D+1),0) AS D)  P4

keycloak Invalid parameter: redirect_uri

If you are a .Net Devloper Please Check below Configurations keycloakAuthentication options class set CallbackPath = RedirectUri,//this Property needs to be set other wise it will show invalid redirecturi error

I faced the same error. In my case, the issue was with Valid Redirect URIs was not correct. So these are the steps I followed.

First login to keycloack as an admin user. Then Select your realm(maybe you will auto-direct to the realm). Then you will see below screen

enter image description here

Select Clients from left panel. Then select relevant client which you configured for your app. By default, you will be Setting tab, if not select it. My app was running on port 3000, so my correct setting is like below. let say you have an app runs on localhost:3000, so your setting should be like this

enter image description here

The transaction log for database is full. To find out why space in the log cannot be reused, see the log_reuse_wait_desc column in sys.databases

As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:

WHILE EXISTS (SELECT 1 
              FROM   YourTable 
              WHERE  <yourCondition>) 
  DELETE TOP(10000) FROM YourTable 
  WHERE  <yourCondition>

how to reference a YAML "setting" from elsewhere in the same YAML file?

In some languages, you can use an alternative library, For example, tampax is an implementation of YAML handling variables:

const tampax = require('tampax');

const yamlString = `
dude:
  name: Arthur
weapon:
  favorite: Excalibur
  useless: knife
sentence: "{{dude.name}} use {{weapon.favorite}}. The goal is {{goal}}."`;

const r = tampax.yamlParseString(yamlString, { goal: 'to kill Mordred' });
console.log(r.sentence);

// output : "Arthur use Excalibur. The goal is to kill Mordred."

Editor's Note: poster is also the author of this package.

Angular 2 : No NgModule metadata found

I've encountered this problem twice now. Both times were problems with how I was implementing my lazy loading. In my routing module I had my routes defines as:

  {
    path: "game",
    loadChildren: () => import("./game/game.module").then(m => {m.GameModule})
  }

But this is wrong. After the second => you don't need curly braces. it should look like this:

  {
    path: "game",
    loadChildren: () => import("./game/game.module").then(m => m.GameModule)
 }

CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response

You have to add options also in allowed headers. browser sends a preflight request before original request is sent. See below

 res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS');

From source https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS

In CORS, a preflight request with the OPTIONS method is sent, so that the server can respond whether it is acceptable to send the request with these parameters. The Access-Control-Request-Method header notifies the server as part of a preflight request that when the actual request is sent, it will be sent with a POST request method. The Access-Control-Request-Headers header notifies the server that when the actual request is sent, it will be sent with a X-PINGOTHER and Content-Type custom headers. The server now has an opportunity to determine whether it wishes to accept a request under these circumstances.

EDITED

You can avoid this manual configuration by using npmjs.com/package/cors npm package.I have used this method also, it is clear and easy.

Only numbers. Input number in React

Simply way in React

<input
      onKeyPress={(event) => {
        if (!/[0-9]/.test(event.key)) {
          event.preventDefault();
        }
      }}
    />

Swift - Integer conversion to Hours/Minutes/Seconds

I had answered to the similar question, however you don't need to display milliseconds in the result. Hence my solution requires iOS 10.0, tvOS 10.0, watchOS 3.0 or macOS 10.12.

You should call func convertDurationUnitValueToOtherUnits(durationValue:durationUnit:smallestUnitDuration:) from the answer that I already mentioned here:

let secondsToConvert = 27005
let result: [Int] = convertDurationUnitValueToOtherUnits(
    durationValue: Double(secondsToConvert),
    durationUnit: .seconds,
    smallestUnitDuration: .seconds
)
print("\(result[0]) hours, \(result[1]) minutes, \(result[2]) seconds") // 7 hours, 30 minutes, 5 seconds

How to load GIF image in Swift?

This is working for me

Podfile:

platform :ios, '9.0'
use_frameworks!

target '<Your Target Name>' do
pod 'SwiftGifOrigin', '~> 1.7.0'
end

Usage:

// An animated UIImage
let jeremyGif = UIImage.gif(name: "jeremy")

// A UIImageView with async loading
let imageView = UIImageView()
imageView.loadGif(name: "jeremy")

// A UIImageView with async loading from asset catalog(from iOS9)
let imageView = UIImageView()
imageView.loadGif(asset: "jeremy")

For more information follow this link: https://github.com/swiftgif/SwiftGif

Changing the Status Bar Color for specific ViewControllers using Swift in iOS8

There's a billion answers here so I thought why not add another in the form of an extension (with help from @Cœur)

Swift 3

Extension:

extension UIApplication {
    class var statusBarBackgroundColor: UIColor? {
        get {
            return (shared.value(forKey: "statusBar") as? UIView)?.backgroundColor
        } set {
            (shared.value(forKey: "statusBar") as? UIView)?.backgroundColor = newValue
        }
    }
}

Implementation:

UIApplication.statusBarBackgroundColor = .blue

List Highest Correlation Pairs from a Large Correlation Matrix in Pandas?

I was trying some of the solutions here but then I actually came up with my own one. I hope this might be useful for the next one so I share it here:

def sort_correlation_matrix(correlation_matrix):
    cor = correlation_matrix.abs()
    top_col = cor[cor.columns[0]][1:]
    top_col = top_col.sort_values(ascending=False)
    ordered_columns = [cor.columns[0]] + top_col.index.tolist()
    return correlation_matrix[ordered_columns].reindex(ordered_columns)

How to extract year and month from date in PostgreSQL without using to_char() function?

to_char(timestamp, 'YYYY-MM')

You say that the order is not "right", but I cannot see why it is wrong (at least until year 10000 comes around).

Commenting in a Bash script inside a multiline command

In addition to the examples by DigitalRoss, here's another form that you can use if you prefer $() instead of backticks `

echo abc $(: comment) \
     def $(: comment) \
     xyz

Of course, you can use the colon syntax with backticks as well:

echo abc `: comment` \
     def `: comment` \
     xyz

Additional Notes

The reason $(#comment) doesn't work is because once it sees the #, it treats the rest of the line as comments, including the closing parentheses: comment). So the parentheses is never closed.

Backticks parse differently and will detect the closing backtick even after a #.

Effective method to hide email from spam bots

I don't like JavaScript and HTML to be mixed, that's why I use this solution. It works fine for me, for now.

Idea: you could make it more complicated by providing encrypted information in the data-attributes and decrypt it within the JS. This is simply done by replacing letters or just reversing them.

HTML:

<span class="generate-email" data-part1="john" data-part2="gmail" data-part3="com">placeholder</span>

JS:

$(function() {
    $('.generate-email').each(function() {
        var that = $(this);
        that.html(
            that.data('part1') + '@' + that.data('part2') + '.' + that.data('part3')
        );
    });  
});

Try it: http://jsfiddle.net/x6g9L817/

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 can I commit files with git?

It looks like all of the edits are already a part of the index. So to commit just use the commit command

git commit -m "My Commit Message"

Looking at your messages though my instinct says that you probably don't want the cache files to be included in your depot. Especially if it something that is built on the fly when running your program. If so then you should add the following line to your .gitignore file

httpdocs/newsite/manifest/cache/*

time delayed redirect?

<meta http-equiv="refresh" content="2; url=http://example.com/" />

Here 2 is delay in seconds.

Display date/time in user's locale format and time offset

Here's what I've used in past projects:

var myDate = new Date();
var tzo = (myDate.getTimezoneOffset()/60)*(-1);
//get server date value here, the parseInvariant is from MS Ajax, you would need to do something similar on your own
myDate = new Date.parseInvariant('<%=DataCurrentDate%>', 'yyyyMMdd hh:mm:ss');
myDate.setHours(myDate.getHours() + tzo);
//here you would have to get a handle to your span / div to set.  again, I'm using MS Ajax's $get
var dateSpn = $get('dataDate');
dateSpn.innerHTML = myDate.localeFormat('F');

Differences between TCP sockets and web sockets, one more time

WebSocket is basically an application protocol (with reference to the ISO/OSI network stack), message-oriented, which makes use of TCP as transport layer.

The idea behind the WebSocket protocol consists of reusing the established TCP connection between a Client and Server. After the HTTP handshake the Client and Server start speaking WebSocket protocol by exchanging WebSocket envelopes. HTTP handshaking is used to overcome any barrier (e.g. firewalls) between a Client and a Server offering some services (usually port 80 is accessible from anywhere, by anyone). Client and Server can switch over speaking HTTP in any moment, making use of the same TCP connection (which is never released).

Behind the scenes WebSocket rebuilds the TCP frames in consistent envelopes/messages. The full-duplex channel is used by the Server to push updates towards the Client in an asynchronous way: the channel is open and the Client can call any futures/callbacks/promises to manage any asynchronous WebSocket received message.

To put it simply, WebSocket is a high level protocol (like HTTP itself) built on TCP (reliable transport layer, on per frame basis) that makes possible to build effective real-time application with JS Clients (previously Comet and long-polling techniques were used to pull updates from the Server before WebSockets were implemented. See Stackoverflow post: Differences between websockets and long polling for turn based game server ).

Invalid use side-effecting operator Insert within a function

Functions cannot be used to modify base table information, use a stored procedure.

Create a basic matrix in C (input by user !)

int rows, cols , i, j;
printf("Enter number of rows and cols for the matrix: \n");
scanf("%d %d",&rows, &cols);

int mat[rows][cols];

printf("enter the matrix:");

for(i = 0; i < rows ; i++)
    for(j = 0; j < cols; j++)
        scanf("%d", &mat[i][j]);

printf("\nThe Matrix is:\n");
for(i = 0; i < rows ; i++)
{
    for(j = 0; j < cols; j++)
    {
        printf("%d",mat[i][j]);
        printf("\t");
    }
    printf("\n");
}

}

How to use forEach in vueJs?

The keyword you need is flatten an array. Modern javascript array comes with a flat method. You can use third party libraries like underscorejs in case you need to support older browsers.

Native Ex:

var response=[1,2,3,4[12,15],[20,21]];
var data=response.flat(); //data=[1,2,3,4,12,15,20,21]

Underscore Ex:

var response=[1,2,3,4[12,15],[20,21]];
var data=_.flatten(response);

How to close activity and go back to previous activity in android

 @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if ( id == android.R.id.home ) {
            finish();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

Try this it works both on toolbar back button as hardware back button.

How do you append to a file?

You probably want to pass "a" as the mode argument. See the docs for open().

with open("foo", "a") as f:
    f.write("cool beans...")

There are other permutations of the mode argument for updating (+), truncating (w) and binary (b) mode but starting with just "a" is your best bet.

Python os.path.join() on a list

It's just the method. You're not missing anything. The official documentation shows that you can use list unpacking to supply several paths:

s = "c:/,home,foo,bar,some.txt".split(",")
os.path.join(*s)

Note the *s intead of just s in os.path.join(*s). Using the asterisk will trigger the unpacking of the list, which means that each list argument will be supplied to the function as a separate argument.

MySQL: Error dropping database (errno 13; errno 17; errno 39)

In my case it was due to 'lower_case_table_names' parameter.

The error number 39 thrown out when I tried to drop the databases which consists upper case table names with lower_case_table_names parameter is enabled.

This is fixed by reverting back the lower case parameter changes to the previous state.

Specified argument was out of the range of valid values. Parameter name: site

This occurred to me when I applied the 2017 Fall Creator Update. I was able to resolve by repairing IIS 10.0 Express (I do not have IIS installed on my box.)

Note: As a user pointed out in the comments,

Repair can be found in "Programs and Features" - the "classic" control panel.

How to call a function from another controller in angularjs?

If you would like to execute the parent controller's parentmethod function inside a child controller, call it:

$scope.$parent.parentmethod();

You can try it over here

Change Schema Name Of Table In SQL

Try below

declare @sql varchar(8000), @table varchar(1000), @oldschema varchar(1000), @newschema   varchar(1000)

  set @oldschema = 'dbo'
  set @newschema = 'exe'

 while exists(select * from sys.tables where schema_name(schema_id) = @oldschema)

  begin
      select @table = name from sys.tables 
      where object_id in(select min(object_id) from sys.tables where  schema_name(schema_id)  = @oldschema)

    set @sql = 'alter schema ' + @newschema + ' transfer ' + @oldschema + '.' + @table

   exec(@sql)
 end

How to update two tables in one statement in SQL Server 2005?

For general updating table1 specific colom based on Table2 specific colom, below query works perfectly...

UPDATE table 1  
SET Col 2 = t2.Col2,  
Col 3 = t2.Col3  
FROM table1 t1  
INNER JOIN table 2 t2 ON t1.Col1 = t2.col1 

(How) can I count the items in an enum?

I really do not see any way to really get to the number of values in an enumeration in C++. Any of the before mention solution work as long as you do not define the value of your enumerations if you define you value that you might run into situations where you either create arrays too big or too small

enum example{ test1 = -2, test2 = -1, test3 = 0, test4 = 1, test5 = 2 }

in this about examples the result would create a array of 3 items when you need an array of 5 items

enum example2{ test1 , test2 , test3 , test4 , test5 = 301 }

in this about examples the result would create a array of 301 items when you need an array of 5 items

The best way to solve this problem in the general case would be to iterate through your enumerations but that is not in the standard yet as far as I know

How to use querySelectorAll only for elements that have a specific attribute set?

Extra Tips:

Multiple "nots", input that is NOT hidden and NOT disabled:

:not([type="hidden"]):not([disabled])

Also did you know you can do this:

node.parentNode.querySelectorAll('div');

This is equivelent to jQuery's:

$(node).parent().find('div');

Which will effectively find all divs in "node" and below recursively, HOT DAMN!

How Do I Uninstall Yarn

For Windows:

I need to do these steps to completely remove the yarn from the system.

  1. Go to add or remove programs and then search for yarn and uninstall it(if you installed it with the .msi)
  2. npm uninstall -g yarn (if you installed with npm)
  3. Remove any existing yarn folders from your Program Files (x86) (Program Files (x86)\Yarn).
  4. Also need to delete your Appdata\local\yarn folder ( type %LOCALAPPDATA% in the run dialog box (win+R), it opens a local folder and there you'll find the yarn folder to delete)
  5. Finally,check your user directory and remove all .yarn folder, .yarn.lock file, .yarnrc etc ( from C:\Users\<user>\)

Can I delete a git commit but keep the changes?

There are two ways of handling this. Which is easier depends on your situation

Reset

If the commit you want to get rid of was the last commit, and you have not done any additional work you can simply use git-reset

git reset HEAD^

Takes your branch back to the commit just before your current HEAD. However, it doesn't actually change the files in your working tree. As a result, the changes that were in that commit show up as modified - its like an 'uncommit' command. In fact, I have an alias to do just that.

git config --global alias.uncommit 'reset HEAD^'

Then you can just used git uncommit in the future to back up one commit.

Squashing

Squashing a commit means combining two or more commits into one. I do this quite often. In your case you have a half done feature commited, and then you would finish it off and commit again with the proper, permanent commit message.

git rebase -i <ref>

I say above because I want to make it clear this could be any number of commits back. Run git log and find the commit you want to get rid of, copy its SHA1 and use it in place of <ref>. Git will take you into interactive rebase mode. It will show all the commits between your current state and whatever you put in place of <ref>. So if <ref> is 10 commits ago, it will show you all 10 commits.

In front of each commit, it will have the word pick. Find the commit you want to get rid of and change it from pick to fixup or squash. Using fixup simply discards that commits message and merges the changes into its immediate predecessor in the list. The squash keyword does the same thing, but allows you to edit the commit message of the newly combined commit.

Note that the commits will be re-committed in the order they show up on the list when you exit the editor. So if you made a temporary commit, then did other work on the same branch, and completed the feature in a later commit, then using rebase would allow you to re-sort the commits and squash them.

WARNING:

Rebasing modifies history - DONT do this to any commits you have already shared with other developers.

Stashing

In the future, to avoid this problem consider using git stash to temporarily store uncommitted work.

git stash save 'some message'

This will store your current changes off to the side in your stash list. Above is the most explicit version of the stash command, allowing for a comment to describe what you are stashing. You can also simply run git stash and nothing else, but no message will be stored.

You can browse your stash list with...

git stash list

This will show you all your stashes, what branches they were done on, and the message and at the beginning of each line, and identifier for that stash which looks like this stash@{#} where # is its position in the array of stashes.

To restore a stash (which can be done on any branch, regardless of where the stash was originally created) you simply run...

git stash apply stash@{#}

Again, there # is the position in the array of stashes. If the stash you want to restore is in the 0 position - that is, if it was the most recent stash. Then you can just run the command without specifying the stash position, git will assume you mean the last one: git stash apply.

So, for example, if I find myself working on the wrong branch - I may run the following sequence of commands.

git stash
git checkout <correct_branch>
git stash apply

In your case you moved around branches a bit more, but the same idea still applies.

Hope this helps.

How to use the command update-alternatives --config java

Assuming one has installed a JDK in /opt/java/jdk1.8.0_144 then:

  1. Install the alternative for javac

    $ sudo update-alternatives --install /usr/bin/javac javac /opt/java/jdk1.8.0_144/bin/javac 1
    
  2. Check / update the alternatives config:

    $ sudo update-alternatives --config javac
    

If there is only a single alternative for javac you will get a message saying so, otherwise select the option for the new JDK.

To check everything is setup correctly then:

$ which javac
/usr/bin/javac

$ ls -l /usr/bin/javac
lrwxrwxrwx 1 root root 23 Sep  4 17:10 /usr/bin/javac -> /etc/alternatives/javac

$ ls -l /etc/alternatives/javac
lrwxrwxrwx 1 root root 32 Sep  4 17:10 /etc/alternatives/javac -> /opt/java/jdk1.8.0_144/bin/javac

And finally

$ javac -version
javac 1.8.0_144

Repeat for java, keytool, jar, etc as needed.

Android Get Application's 'Home' Data Directory

Of course, never fails. Found the solution about a minute after posting the above question... solution for those that may have had the same issue:

ContextWrapper.getFilesDir()

Found here.

Difference between "or" and || in Ruby?

The way I use these operators:

||, && are for boolean logic. or, and are for control flow. E.g.

do_smth if may_be || may_be -- we evaluate the condition here

do_smth or do_smth_else -- we define the workflow, which is equivalent to do_smth_else unless do_smth

to give a simple example:

> puts "a" && "b"
b

> puts 'a' and 'b'
a

A well-known idiom in Rails is render and return. It's a shortcut for saying return if render, while render && return won't work. See "Avoiding Double Render Errors" in the Rails documentation for more information.

Is it still valid to use IE=edge,chrome=1?

It's still valid to use IE=edge,chrome=1.

But, since the chrome frame project has been wound down the chrome=1 part is redundant for browsers that don't already have the chrome frame plug in installed.

I use the following for correctness nowadays

<meta http-equiv="X-UA-Compatible" content="IE=edge" />

Getting request payload from POST request in Java servlet

If the contents of the body are a string in Java 8 you can do:

String body = request.getReader().lines().collect(Collectors.joining());

How to delete or add column in SQLITE?

I guess what you are wanting to do is database migration. 'Drop'ping a column does not exist in SQLite. But you can however, add an extra column by using the ALTER table query.

How to express a One-To-Many relationship in Django

To be more clear - there's no OneToMany in Django, only ManyToOne - which is Foreignkey described above. You can describe OneToMany relation using Foreignkey but that is very inexpressively.

A good article about it: https://amir.rachum.com/blog/2013/06/15/a-case-for-a-onetomany-relationship-in-django/

MySQL: View with Subquery in the FROM Clause Limitation

It appears to be a known issue.

http://dev.mysql.com/doc/refman/5.1/en/unnamed-views.html

http://bugs.mysql.com/bug.php?id=16757

Many IN queries can be re-written as (left outer) joins and an IS (NOT) NULL of some sort. for example

SELECT * FROM FOO WHERE ID IN (SELECT ID FROM FOO2)

can be re-written as

SELECT FOO.* FROM FOO JOIN FOO2 ON FOO.ID=FOO2.ID

or

SELECT * FROM FOO WHERE ID NOT IN (SELECT ID FROM FOO2)

can be

SELECT FOO.* FROM FOO 
LEFT OUTER JOIN FOO2 
ON FOO.ID=FOO2.ID WHERE FOO.ID IS NULL

How to get the timezone offset in GMT(Like GMT+7:00) from android device?

TimeZone timeZone = TimeZone.getDefault();
String timeZoneInGMTFormat = timeZone.getDisplayName(false,TimeZone.SHORT);

Output : GMT+5:30

JNI converting jstring to char *

Here's a a couple of useful link that I found when I started with JNI

http://en.wikipedia.org/wiki/Java_Native_Interface
http://download.oracle.com/javase/1.5.0/docs/guide/jni/spec/functions.html

concerning your problem you can use this

JNIEXPORT void JNICALL Java_ClassName_MethodName(JNIEnv *env, jobject obj, jstring javaString)   
{
   const char *nativeString = env->GetStringUTFChars(javaString, 0);

   // use your string

   env->ReleaseStringUTFChars(javaString, nativeString);
}

PUT and POST getting 405 Method Not Allowed Error for Restful Web Services

Well, apparently I had to change my PUT calling function updateUser. I removed the @Consumes, the @RequestMapping and also added a @ResponseBody to the function. So my method looked like this:

@RequestMapping(value="/{id}",method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public void updateUser(@PathVariable int id, @RequestBody User temp){
    Set<User> set1= obj2.getUsers();
    for(User a:set1)
    {
        if(id==a.getId())
        {
            set1.remove(a);
            a.setId(temp.getId());
            a.setName(temp.getName());
            set1.add(a);
        }
    }
    Userlist obj3=new Userlist(set1);
    obj2=obj3;
}

And it worked!!! Thank you all for the response.

XSD - how to allow elements in any order any number of times?

If none of the above is working, you are probably working on EDI trasaction where you need to validate your result against an HIPPA schema or any other complex xsd for that matter. The requirement is that, say there 8 REF segments and any of them have to appear in any order and also not all are required, means to say you may have them in following order 1st REF, 3rd REF , 2nd REF, 9th REF. Under default situation EDI receive will fail, beacause default complex type is

<xs:sequence>
  <xs:element.../>
</xs:sequence>

The situation is even complex when you are calling your element by refrence and then that element in its original spot is quite complex itself. for example:

<xs:element>
<xs:complexType>
<xs:sequence>
<element name="REF1"  ref= "REF1_Mycustomelment" minOccurs="0" maxOccurs="1">
<element name="REF2"  ref= "REF2_Mycustomelment" minOccurs="0" maxOccurs="1">
<element name="REF3"  ref= "REF3_Mycustomelment" minOccurs="0" maxOccurs="1">
</xs:sequence>
</xs:complexType>
</xs:element>

Solution:

Here simply replacing "sequence" with "all" or using "choice" with min/max combinations won't work!

First thing replace "xs:sequence" with "<xs:all>" Now,You need to make some changes where you are Referring the element from, There go to:

<xs:annotation>
  <xs:appinfo>
    <b:recordinfo structure="delimited" field.........Biztalk/2003">

***Now in the above segment add trigger point in the end like this trigger_field="REF01_...complete name.." trigger_value = "38" Do the same for other REF segments where trigger value will be different like say "18", "XX" , "YY" etc..so that your record info now looks like:b:recordinfo structure="delimited" field.........Biztalk/2003" trigger_field="REF01_...complete name.." trigger_value="38">


This will make each element unique, reason being All REF segements (above example) have same structure like REF01, REF02, REF03. And during validation the structure validation is ok but it doesn't let the values repeat because it tries to look for remaining values in first REF itself. Adding triggers will make them all unique and they will pass in any order and situational cases (like use 5 out 9 and not all 9/9).

Hope it helps you, for I spent almost 20 hrs on this.

Good Luck

How can I get LINQ to return the object which has the max value for a given property?

You could use a captured variable.

Item result = items.FirstOrDefault();
items.ForEach(x =>
{
  if(result.ID < x.ID)
    result = x;
});

How can I use NSError in my iPhone App?

Another design pattern that I have seen involves using blocks, which is especially useful when a method is being run asynchronously.

Say we have the following error codes defined:

typedef NS_ENUM(NSInteger, MyErrorCodes) {
    MyErrorCodesEmptyString = 500,
    MyErrorCodesInvalidURL,
    MyErrorCodesUnableToReachHost,
};

You would define your method that can raise an error like so:

- (void)getContentsOfURL:(NSString *)path success:(void(^)(NSString *html))success failure:(void(^)(NSError *error))failure {
    if (path.length == 0) {
        if (failure) {
            failure([NSError errorWithDomain:@"com.example" code:MyErrorCodesEmptyString userInfo:nil]);
        }
        return;
    }

    NSString *htmlContents = @"";

    // Exercise for the reader: get the contents at that URL or raise another error.

    if (success) {
        success(htmlContents);
    }
}

And then when you call it, you don't need to worry about declaring the NSError object (code completion will do it for you), or checking the returning value. You can just supply two blocks: one that will get called when there is an exception, and one that gets called when it succeeds:

[self getContentsOfURL:@"http://google.com" success:^(NSString *html) {
    NSLog(@"Contents: %@", html);
} failure:^(NSError *error) {
    NSLog(@"Failed to get contents: %@", error);
    if (error.code == MyErrorCodesEmptyString) { // make sure to check the domain too
        NSLog(@"You must provide a non-empty string");
    }
}];

TypeScript: Creating an empty typed container array

The existing answers missed an option, so here's a complete list:

// 1. Explicitly declare the type
var arr: Criminal[] = [];

// 2. Via type assertion
var arr = <Criminal[]>[];
var arr = [] as Criminal[];

// 3. Using the Array constructor
var arr = new Array<Criminal>();
  1. Explicitly specifying the type is the general solution for whenever type inference fails for a variable declaration.

  2. The advantage of using a type assertion (sometimes called a cast, but it's not really a cast in TypeScript) works for any expression, so it can be used even when no variable is declared. There are two syntaxes for type assertions, but only the latter will work in combination with JSX if you care about that.

  3. Using the Array constructor is something that will only help you in this specific use case, but which I personally find the most readable. However, there is a slight performance impact at runtime*. Also, if someone were crazy enough to redefine the Array constructor, the meaning could change.

It's a matter of personal preference, but I find the third option the most readable. In the vast majority of cases the mentioned downsides would be negligible and readability is the most important factor.

*: Fun fact; at the time of writing the performance difference was 60% in Chrome, while in Firefox there was no measurable performance difference.

How to sort a dataFrame in python pandas by two or more columns?

As of pandas 0.17.0, DataFrame.sort() is deprecated, and set to be removed in a future version of pandas. The way to sort a dataframe by its values is now is DataFrame.sort_values

As such, the answer to your question would now be

df.sort_values(['b', 'c'], ascending=[True, False], inplace=True)

Trying to SSH into an Amazon Ec2 instance - permission error

By default whenever you download the keyfile it come with 644 permissions.

So you need to change the permission each time you download new keys.

 chmod 400 my_file.pem

Creating all possible k combinations of n items in C++

From Rosetta code

#include <algorithm>
#include <iostream>
#include <string>
 
void comb(int N, int K)
{
    std::string bitmask(K, 1); // K leading 1's
    bitmask.resize(N, 0); // N-K trailing 0's
 
    // print integers and permute bitmask
    do {
        for (int i = 0; i < N; ++i) // [0..N-1] integers
        {
            if (bitmask[i]) std::cout << " " << i;
        }
        std::cout << std::endl;
    } while (std::prev_permutation(bitmask.begin(), bitmask.end()));
}
 
int main()
{
    comb(5, 3);
}

output

 0 1 2
 0 1 3
 0 1 4
 0 2 3
 0 2 4
 0 3 4
 1 2 3
 1 2 4
 1 3 4
 2 3 4

Analysis and idea

The whole point is to play with the binary representation of numbers for example the number 7 in binary is 0111

So this binary representation can also be seen as an assignment list as such:

For each bit i if the bit is set (i.e is 1) means the ith item is assigned else not.

Then by simply computing a list of consecutive binary numbers and exploiting the binary representation (which can be very fast) gives an algorithm to compute all combinations of N over k.

The sorting at the end (of some implementations) is not needed. It is just a way to deterministicaly normalize the result, i.e for same numbers (N, K) and same algorithm same order of combinations is returned

For further reading about number representations and their relation to combinations, permutations, power sets (and other interesting stuff), have a look at Combinatorial number system , Factorial number system

PS: You may want to check out my combinatorics framework Abacus which computes many types of combinatorial objects efficiently and its routines (originaly in JavaScript) can be adapted easily to many other languages.

Hide text within HTML?

<div style="display:none;">CREDITS_HERE</div>

How do I free memory in C?

You have to free() the allocated memory in exact reverse order of how it was allocated using malloc().

Note that You should free the memory only after you are done with your usage of the allocated pointers.

memory allocation for 1D arrays:

    buffer = malloc(num_items*sizeof(double));

memory deallocation for 1D arrays:

    free(buffer);

memory allocation for 2D arrays:

    double **cross_norm=(double**)malloc(150 * sizeof(double *));
    for(i=0; i<150;i++)
    {
        cross_norm[i]=(double*)malloc(num_items*sizeof(double));
    }

memory deallocation for 2D arrays:

    for(i=0; i<150;i++)
    {
        free(cross_norm[i]);
    }

    free(cross_norm);

Adjusting and image Size to fit a div (bootstrap)

Just a heads up that Bootstrap 4 now uses img-fluid instead of img-responsive, so double check which version you're using if you're having problems.

What's the difference between MyISAM and InnoDB?

The main differences between InnoDB and MyISAM ("with respect to designing a table or database" you asked about) are support for "referential integrity" and "transactions".

If you need the database to enforce foreign key constraints, or you need the database to support transactions (i.e. changes made by two or more DML operations handled as single unit of work, with all of the changes either applied, or all the changes reverted) then you would choose the InnoDB engine, since these features are absent from the MyISAM engine.

Those are the two biggest differences. Another big difference is concurrency. With MyISAM, a DML statement will obtain an exclusive lock on the table, and while that lock is held, no other session can perform a SELECT or a DML operation on the table.

Those two specific engines you asked about (InnoDB and MyISAM) have different design goals. MySQL also has other storage engines, with their own design goals.

So, in choosing between InnoDB and MyISAM, the first step is in determining if you need the features provided by InnoDB. If not, then MyISAM is up for consideration.

A more detailed discussion of differences is rather impractical (in this forum) absent a more detailed discussion of the problem space... how the application will use the database, how many tables, size of the tables, the transaction load, volumes of select, insert, updates, concurrency requirements, replication features, etc.


The logical design of the database should be centered around data analysis and user requirements; the choice to use a relational database would come later, and even later would the choice of MySQL as a relational database management system, and then the selection of a storage engine for each table.

How to show all privileges from a user in oracle?

There are various scripts floating around that will do that depending on how crazy you want to get. I would personally use Pete Finnigan's find_all_privs script.

If you want to write it yourself, the query gets rather challenging. Users can be granted system privileges which are visible in DBA_SYS_PRIVS. They can be granted object privileges which are visible in DBA_TAB_PRIVS. And they can be granted roles which are visible in DBA_ROLE_PRIVS (roles can be default or non-default and can require a password as well, so just because a user has been granted a role doesn't mean that the user can necessarily use the privileges he acquired through the role by default). But those roles can, in turn, be granted system privileges, object privileges, and additional roles which can be viewed by looking at ROLE_SYS_PRIVS, ROLE_TAB_PRIVS, and ROLE_ROLE_PRIVS. Pete's script walks through those relationships to show all the privileges that end up flowing to a user.

MySQL select with CONCAT condition

SELECT needefield, CONCAT(firstname, ' ',lastname) as firstlast 
FROM users 
WHERE CONCAT(firstname, ' ', lastname) = "Bob Michael Jones"

Compute row average in pandas

If you are looking to average column wise. Try this,

df.drop('Region', axis=1).apply(lambda x: x.mean())

# it drops the Region column
df.drop('Region', axis=1,inplace=True)

how to loop through rows columns in excel VBA Macro

Here is my sugestion:

Dim i As integer, j as integer

With Worksheets("TimeOut")
    i = 26
    Do Until .Cells(8, i).Value = ""
        For j = 9 to 100 ' I do not know how many rows you will need it.'
            .Cells(j, i).Formula = "YourVolFormulaHere"
            .Cells(j, i + 1).Formula = "YourCapFormulaHere"
        Next j

        i = i + 2
    Loop
 End With

java.lang.IllegalAccessError: tried to access method

If getData is protected then try making it public. The problem could exist in JAVA 1.6 and be absent in 1.5x

I got this for your problem. Illegal access error

Invalid date in safari

Best way to do it is by using the following format:

new Date(year, month, day, hours, minutes, seconds, milliseconds)
var d = new Date(2018, 11, 24, 10, 33, 30, 0);

This is supported in all browsers and will not give you any issues. Please note that the months are written from 0 to 11.

JavaScript check if variable exists (is defined/initialized)

I use two different ways depending on the object.

if( !variable ){
  // variable is either
  // 1. '';
  // 2. 0;
  // 3. undefined;
  // 4. null;
  // 5. false;
}

Sometimes I do not want to evaluate an empty string as falsey, so then I use this case

function invalid( item ){
  return (item === undefined || item === null);
}

if( invalid( variable )){
  // only here if null or undefined;
}

If you need the opposite, then in the first instance !variable becomes !!variable, and in the invalid function === become != and the function names changes to notInvalid.

How can I initialize C++ object member variables in the constructor?

You can specify how to initialize members in the member initializer list:

BigMommaClass {
    BigMommaClass(int, int);

private:
    ThingOne thingOne;
    ThingTwo thingTwo;
};

BigMommaClass::BigMommaClass(int numba1, int numba2)
    : thingOne(numba1 + numba2), thingTwo(numba1, numba2) {}

How can I restore the MySQL root user’s full privileges?

If you've deleted your root user by mistake you can do one thing:

  1. Stop MySQL service
  2. Run mysqld_safe --skip-grant-tables &
  3. Type mysql -u root -p and press enter.
  4. Enter your password
  5. At the mysql command line enter: use mysql;

Then execute this query:

insert into `user` (`Host`, `User`, `Password`, `Select_priv`, `Insert_priv`, `Update_priv`, `Delete_priv`, `Create_priv`, `Drop_priv`, `Reload_priv`, `Shutdown_priv`, `Process_priv`, `File_priv`, `Grant_priv`, `References_priv`, `Index_priv`, `Alter_priv`, `Show_db_priv`, `Super_priv`, `Create_tmp_table_priv`, `Lock_tables_priv`, `Execute_priv`, `Repl_slave_priv`, `Repl_client_priv`, `Create_view_priv`, `Show_view_priv`, `Create_routine_priv`, `Alter_routine_priv`, `Create_user_priv`, `ssl_type`, `ssl_cipher`, `x509_issuer`, `x509_subject`, `max_questions`, `max_updates`, `max_connections`, `max_user_connections`) 
values('localhost','root','','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','','','','','0','0','0','0');

then restart the mysqld

EDIT: October 6, 2018

In case anyone else needs this answer, I tried it today using innodb_version 5.6.36-82.0 and 10.1.24-MariaDB and it works if you REMOVE THE BACKTICKS (no single quotes either, just remove them):

insert into user (Host, User, Password, Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv, Reload_priv, Shutdown_priv, Process_priv, File_priv, Grant_priv, References_priv, Index_priv, Alter_priv, Show_db_priv, Super_priv, Create_tmp_table_priv, Lock_tables_priv, Execute_priv, Repl_slave_priv, Repl_client_priv, Create_view_priv, Show_view_priv, Create_routine_priv, Alter_routine_priv, Create_user_priv, ssl_type, ssl_cipher, x509_issuer, x509_subject, max_questions, max_updates, max_connections, max_user_connections) 
values('localhost','root','','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','','','','','0','0','0','0');

ANTLR: Is there a simple example?

Note: this answer is for ANTLR3! If you're looking for an ANTLR4 example, then this Q&A demonstrates how to create a simple expression parser, and evaluator using ANTLR4.


You first create a grammar. Below is a small grammar that you can use to evaluate expressions that are built using the 4 basic math operators: +, -, * and /. You can also group expressions using parenthesis.

Note that this grammar is just a very basic one: it does not handle unary operators (the minus in: -1+9) or decimals like .99 (without a leading number), to name just two shortcomings. This is just an example you can work on yourself.

Here's the contents of the grammar file Exp.g:

grammar Exp;

/* This will be the entry point of our parser. */
eval
    :    additionExp
    ;

/* Addition and subtraction have the lowest precedence. */
additionExp
    :    multiplyExp 
         ( '+' multiplyExp 
         | '-' multiplyExp
         )* 
    ;

/* Multiplication and division have a higher precedence. */
multiplyExp
    :    atomExp
         ( '*' atomExp 
         | '/' atomExp
         )* 
    ;

/* An expression atom is the smallest part of an expression: a number. Or 
   when we encounter parenthesis, we're making a recursive call back to the
   rule 'additionExp'. As you can see, an 'atomExp' has the highest precedence. */
atomExp
    :    Number
    |    '(' additionExp ')'
    ;

/* A number: can be an integer value, or a decimal value */
Number
    :    ('0'..'9')+ ('.' ('0'..'9')+)?
    ;

/* We're going to ignore all white space characters */
WS  
    :   (' ' | '\t' | '\r'| '\n') {$channel=HIDDEN;}
    ;

(Parser rules start with a lower case letter, and lexer rules start with a capital letter)

After creating the grammar, you'll want to generate a parser and lexer from it. Download the ANTLR jar and store it in the same directory as your grammar file.

Execute the following command on your shell/command prompt:

java -cp antlr-3.2.jar org.antlr.Tool Exp.g

It should not produce any error message, and the files ExpLexer.java, ExpParser.java and Exp.tokens should now be generated.

To see if it all works properly, create this test class:

import org.antlr.runtime.*;

public class ANTLRDemo {
    public static void main(String[] args) throws Exception {
        ANTLRStringStream in = new ANTLRStringStream("12*(5-6)");
        ExpLexer lexer = new ExpLexer(in);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        ExpParser parser = new ExpParser(tokens);
        parser.eval();
    }
}

and compile it:

// *nix/MacOS
javac -cp .:antlr-3.2.jar ANTLRDemo.java

// Windows
javac -cp .;antlr-3.2.jar ANTLRDemo.java

and then run it:

// *nix/MacOS
java -cp .:antlr-3.2.jar ANTLRDemo

// Windows
java -cp .;antlr-3.2.jar ANTLRDemo

If all goes well, nothing is being printed to the console. This means the parser did not find any error. When you change "12*(5-6)" into "12*(5-6" and then recompile and run it, there should be printed the following:

line 0:-1 mismatched input '<EOF>' expecting ')'

Okay, now we want to add a bit of Java code to the grammar so that the parser actually does something useful. Adding code can be done by placing { and } inside your grammar with some plain Java code inside it.

But first: all parser rules in the grammar file should return a primitive double value. You can do that by adding returns [double value] after each rule:

grammar Exp;

eval returns [double value]
    :    additionExp
    ;

additionExp returns [double value]
    :    multiplyExp 
         ( '+' multiplyExp 
         | '-' multiplyExp
         )* 
    ;

// ...

which needs little explanation: every rule is expected to return a double value. Now to "interact" with the return value double value (which is NOT inside a plain Java code block {...}) from inside a code block, you'll need to add a dollar sign in front of value:

grammar Exp;

/* This will be the entry point of our parser. */
eval returns [double value]                                                  
    :    additionExp { /* plain code block! */ System.out.println("value equals: "+$value); }
    ;

// ...

Here's the grammar but now with the Java code added:

grammar Exp;

eval returns [double value]
    :    exp=additionExp {$value = $exp.value;}
    ;

additionExp returns [double value]
    :    m1=multiplyExp       {$value =  $m1.value;} 
         ( '+' m2=multiplyExp {$value += $m2.value;} 
         | '-' m2=multiplyExp {$value -= $m2.value;}
         )* 
    ;

multiplyExp returns [double value]
    :    a1=atomExp       {$value =  $a1.value;}
         ( '*' a2=atomExp {$value *= $a2.value;} 
         | '/' a2=atomExp {$value /= $a2.value;}
         )* 
    ;

atomExp returns [double value]
    :    n=Number                {$value = Double.parseDouble($n.text);}
    |    '(' exp=additionExp ')' {$value = $exp.value;}
    ;

Number
    :    ('0'..'9')+ ('.' ('0'..'9')+)?
    ;

WS  
    :   (' ' | '\t' | '\r'| '\n') {$channel=HIDDEN;}
    ;

and since our eval rule now returns a double, change your ANTLRDemo.java into this:

import org.antlr.runtime.*;

public class ANTLRDemo {
    public static void main(String[] args) throws Exception {
        ANTLRStringStream in = new ANTLRStringStream("12*(5-6)");
        ExpLexer lexer = new ExpLexer(in);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        ExpParser parser = new ExpParser(tokens);
        System.out.println(parser.eval()); // print the value
    }
}

Again (re) generate a fresh lexer and parser from your grammar (1), compile all classes (2) and run ANTLRDemo (3):

// *nix/MacOS
java -cp antlr-3.2.jar org.antlr.Tool Exp.g   // 1
javac -cp .:antlr-3.2.jar ANTLRDemo.java      // 2
java -cp .:antlr-3.2.jar ANTLRDemo            // 3

// Windows
java -cp antlr-3.2.jar org.antlr.Tool Exp.g   // 1
javac -cp .;antlr-3.2.jar ANTLRDemo.java      // 2
java -cp .;antlr-3.2.jar ANTLRDemo            // 3

and you'll now see the outcome of the expression 12*(5-6) printed to your console!

Again: this is a very brief explanation. I encourage you to browse the ANTLR wiki and read some tutorials and/or play a bit with what I just posted.

Good luck!

EDIT:

This post shows how to extend the example above so that a Map<String, Double> can be provided that holds variables in the provided expression.

To get this code working with a current version of Antlr (June 2014) I needed to make a few changes. ANTLRStringStream needed to become ANTLRInputStream, the returned value needed to change from parser.eval() to parser.eval().value, and I needed to remove the WS clause at the end, because attribute values such as $channel are no longer allowed to appear in lexer actions.

How to retrieve form values from HTTPPOST, dictionary or?

The answers are very good but there is another way in the latest release of MVC and .NET that I really like to use, instead of the "old school" FormCollection and Request keys.


Consider a HTML snippet contained within a form tag that either does an AJAX or FORM POST.

<input type="hidden"   name="TrackingID" 
<input type="text"     name="FirstName"  id="firstnametext" />
<input type="checkbox" name="IsLegal"  value="Do you accept terms and conditions?" />

Your controller will actually parse the form data and try to deliver it to you as parameters of the defined type. I included checkbox because it is a tricky one. It returns text "on" if checked and null if not checked. The requirement though is that these defined variables MUST exists (unless nullable(remember though that string is nullable)) otherwise the AJAX or POST back will fail.

[HttpPost]
public ActionResult PostBack(int TrackingID, string FirstName, string IsLegal){
    MyData.SaveRequest(TrackingID,FirstName, IsLegal == null ? false : true);
}

You can also post back a model without using any razor helpers. I have come across that this is needed some times.

public Class HomeModel
{
  public int HouseNumber { get; set; }
  public string StreetAddress { get; set; }
}

The HTML markup will simply be ...

<input type="text" name="variableName.HouseNumber" id="whateverid" >

and your controller(Razor Engine) will intercept the Form Variable "variableName" (name is as you like but keep it consistent) and try to build it up and cast it to MyModel.

[HttpPost]
public ActionResult PostBack(HomeModel variableName){
    postBack.HouseNumber; //The value user entered
    postBack.StreetAddress; //the default value of NULL.
}

When a controller is expecting a Model (in this case HomeModel) you do not have to define ALL the fields as the parser will just leave them at default, usually NULL. The nice thing is you can mix and match various models on the Mark-up and the post back parse will populate as much as possible. You do not need to define a model on the page or use any helpers.

TIP: The name of the parameter in the controller is the name defined in the HTML mark-up "name=" not the name of the Model but the name of the expected variable in the !


Using List<> is bit more complex in its mark-up.

<input type="text" name="variableNameHere[0].HouseNumber" id="id"           value="0">
<input type="text" name="variableNameHere[1].HouseNumber" id="whateverid-x" value="1">
<input type="text" name="variableNameHere[2].HouseNumber"                   value="2">
<input type="text" name="variableNameHere[3].HouseNumber" id="whateverid22" value="3">

Index on List<> MUST always be zero based and sequential. 0,1,2,3.

[HttpPost]
public ActionResult PostBack(List<HomeModel> variableNameHere){
     int counter = MyHomes.Count()
     foreach(var home in MyHomes)
     { ... }
}

Using IEnumerable<> for non zero based and non sequential indices post back. We need to add an extra hidden input to help the binder.

<input type="hidden" name="variableNameHere.Index" value="278">
<input type="text" name="variableNameHere[278].HouseNumber" id="id"      value="3">

<input type="hidden" name="variableNameHere.Index" value="99976">
<input type="text" name="variableNameHere[99976].HouseNumber" id="id3"   value="4">

<input type="hidden" name="variableNameHere.Index" value="777">
<input type="text" name="variableNameHere[777].HouseNumber" id="id23"    value="5">

And the code just needs to use IEnumerable and call ToList()

[HttpPost]
public ActionResult PostBack(IEnumerable<MyModel> variableNameHere){
     int counter = variableNameHere.ToList().Count()
     foreach(var home in variableNameHere)
     { ... }
}

It is recommended to use a single Model or a ViewModel (Model contianing other models to create a complex 'View' Model) per page. Mixing and matching as proposed could be considered bad practice, but as long as it works and is readable its not BAD. It does however, demonstrate the power and flexiblity of the Razor engine.

So if you need to drop in something arbitrary or override another value from a Razor helper, or just do not feel like making your own helpers, for a single form that uses some unusual combination of data, you can quickly use these methods to accept extra data.

Display all dataframe columns in a Jupyter Python Notebook

If you want to show all the rows set like bellow

pd.options.display.max_rows = None

If you want to show all columns set like bellow

pd.options.display.max_columns = None

Syntax behind sorted(key=lambda: ...)

One more example of usage sorted() function with key=lambda. Let's consider you have a list of tuples. In each tuple you have a brand, model and weight of the car and you want to sort this list of tuples by brand, model or weight. You can do it with lambda.

cars = [('citroen', 'xsara', 1100), ('lincoln', 'navigator', 2000), ('bmw', 'x5', 1700)]

print(sorted(cars, key=lambda car: car[0]))
print(sorted(cars, key=lambda car: car[1]))
print(sorted(cars, key=lambda car: car[2]))

Results:

[('bmw', 'x5', '1700'), ('citroen', 'xsara', 1100), ('lincoln', 'navigator', 2000)]
[('lincoln', 'navigator', 2000), ('bmw', 'x5', '1700'), ('citroen', 'xsara', 1100)]
[('citroen', 'xsara', 1100), ('bmw', 'x5', 1700), ('lincoln', 'navigator', 2000)]

Java8: HashMap<X, Y> to HashMap<X, Z> using Stream / Map-Reduce / Collector

An alternative that always exists for learning purpose is to build your custom collector through Collector.of() though toMap() JDK collector here is succinct (+1 here) .

Map<String,Integer> newMap = givenMap.
                entrySet().
                stream().collect(Collector.of
               ( ()-> new HashMap<String,Integer>(),
                       (mutableMap,entryItem)-> mutableMap.put(entryItem.getKey(),Integer.parseInt(entryItem.getValue())),
                       (map1,map2)->{ map1.putAll(map2); return map1;}
               ));

Java AES and using my own Key

Edit:

As written in the comments the old code is not "best practice". You should use a keygeneration algorithm like PBKDF2 with a high iteration count. You also should use at least partly a non static (meaning for each "identity" exclusive) salt. If possible randomly generated and stored together with the ciphertext.

    SecureRandom sr = SecureRandom.getInstanceStrong();
    byte[] salt = new byte[16];
    sr.nextBytes(salt);

    PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 1000, 128 * 8);
    SecretKey key = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(spec);
    Cipher aes = Cipher.getInstance("AES");
    aes.init(Cipher.ENCRYPT_MODE, key);

===========

Old Answer

You should use SHA-1 to generate a hash from your key and trim the result to 128 bit (16 bytes).

Additionally don't generate byte arrays from Strings through getBytes() it uses the platform default Charset. So the password "blaöä" results in different byte array on different platforms.

byte[] key = (SALT2 + username + password).getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16); // use only first 128 bit

SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");

Edit: If you need 256 bit as key sizes you need to download the "Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files" Oracle download link, use SHA-256 as hash and remove the Arrays.copyOf line. "ECB" is the default Cipher Mode and "PKCS5Padding" the default padding. You could use different Cipher Modes and Padding Modes through the Cipher.getInstance string using following format: "Cipher/Mode/Padding"

For AES using CTS and PKCS5Padding the string is: "AES/CTS/PKCS5Padding"

How can one see content of stack with GDB?

info frame to show the stack frame info

To read the memory at given addresses you should take a look at x

x/x $esp for hex x/d $esp for signed x/u $esp for unsigned etc. x uses the format syntax, you could also take a look at the current instruction via x/i $eip etc.

Python Pandas: Get index of rows which column matches certain value

df.iloc[i] returns the ith row of df. i does not refer to the index label, i is a 0-based index.

In contrast, the attribute index returns actual index labels, not numeric row-indices:

df.index[df['BoolCol'] == True].tolist()

or equivalently,

df.index[df['BoolCol']].tolist()

You can see the difference quite clearly by playing with a DataFrame with a non-default index that does not equal to the row's numerical position:

df = pd.DataFrame({'BoolCol': [True, False, False, True, True]},
       index=[10,20,30,40,50])

In [53]: df
Out[53]: 
   BoolCol
10    True
20   False
30   False
40    True
50    True

[5 rows x 1 columns]

In [54]: df.index[df['BoolCol']].tolist()
Out[54]: [10, 40, 50]

If you want to use the index,

In [56]: idx = df.index[df['BoolCol']]

In [57]: idx
Out[57]: Int64Index([10, 40, 50], dtype='int64')

then you can select the rows using loc instead of iloc:

In [58]: df.loc[idx]
Out[58]: 
   BoolCol
10    True
40    True
50    True

[3 rows x 1 columns]

Note that loc can also accept boolean arrays:

In [55]: df.loc[df['BoolCol']]
Out[55]: 
   BoolCol
10    True
40    True
50    True

[3 rows x 1 columns]

If you have a boolean array, mask, and need ordinal index values, you can compute them using np.flatnonzero:

In [110]: np.flatnonzero(df['BoolCol'])
Out[112]: array([0, 3, 4])

Use df.iloc to select rows by ordinal index:

In [113]: df.iloc[np.flatnonzero(df['BoolCol'])]
Out[113]: 
   BoolCol
10    True
40    True
50    True

Setting user agent of a java URLConnection

Just for clarification: setRequestProperty("User-Agent", "Mozilla ...") now works just fine and doesn't append java/xx at the end! At least with Java 1.6.30 and newer.

I listened on my machine with netcat(a port listener):

$ nc -l -p 8080

It simply listens on the port, so you see anything which gets requested, like raw http-headers.

And got the following http-headers without setRequestProperty:

GET /foobar HTTP/1.1
User-Agent: Java/1.6.0_30
Host: localhost:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive

And WITH setRequestProperty:

GET /foobar HTTP/1.1
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2
Host: localhost:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive

As you can see the user agent was properly set.

Full example:

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;


public class TestUrlOpener {

    public static void main(String[] args) throws IOException {
        URL url = new URL("http://localhost:8080/foobar");
        URLConnection hc = url.openConnection();
        hc.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");

        System.out.println(hc.getContentType());
    }

}

How to place a div on the right side with absolute position

I'm assuming that your container element is probably position:relative;. This is will mean that the dialog box will be positioned accordingly to the container, not the page.

Can you change the markup to this?

<html>
<body>
    <!-- Need to place this div at the top right of the page-->
        <div class="ajax-message">
            <div class="row">
                <div class="span9">
                    <div class="alert">
                        <a class="close icon icon-remove"></a>
                        <div class="message-content">
                            Some message goes here
                        </div>
                    </div>
                </div>
            </div>
        </div>
    <div class="container">
        <!-- Page contents starts here. These are dynamic-->
        <div class="row">
            <div class="span12 inner-col">
                <h2>Documents</h2>
            </div>
        </div>
    </div>
</body>
</html>

With the dialog box outside the main container then you can use absolute positioning relative to the page.

Can't install any package with node npm

Following on from LAXIT KUMAR's recommendation, we've found that at times the registry URL can get corrupted, not sure how this is happening, however to cure, just reset it:

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

The 404 disappeared as it was going to the correct location again.

Xcode source automatic formatting

That's Ctrl + i.

Or for low-tech, cut and then paste. It'll reformat on paste.

org.apache.http.conn.HttpHostConnectException: Connection to http://localhost refused in android

I am using PHP for webservice and Android 4.x. device for connecting to the webservice. I had similar problem where, using 10.0.2.2 worked well with emulator but failed to connect from device. The solution that worked for me is: Find IP of your computer ... say 192.168.0.103 Find the port of your apache ... say 8080 Now open httpd.conf and locate following line Listen 127.0.0.1:8080 After this line add following Listen 192.168.0.103:8080 Thats it. Now if you use 192.168.0.103:8080 in your android code, it will connect!!

Bootstrap Modal before form Submit

You can use browser default prompt window. Instead of basic <input type="submit" (...) > try:

<button onClick="if(confirm(\'are you sure ?\')){ this.form.submit() }">Save</button>

When does a cookie with expiration time 'At end of session' expire?

Cookies that 'expire at end of the session' expire unpredictably from the user's perspective!

On iOS with Safari they expire whenever you switch apps!

On Android with Chrome they don't expire when you close the browser.

On Windows desktop running Chrome they expire when you close the browser. That's not when you close your website's tab; its when you close all tabs. Nor do they expire if there are any other browser windows open. If users run web apps as windows they might not even know they are browser windows. So your cookie's life depends on what the user is doing with some apparently unrelated app.

How do I exclude Weekend days in a SQL Server query?

SELECT date_created
FROM your_table
WHERE DATENAME(dw, date_created) NOT IN ('Saturday', 'Sunday')

How do I get total physical memory size using PowerShell without WMI?

This gives you the total amount from another WMI class:

$cs = get-wmiobject -class "Win32_ComputerSystem"
$Mem = [math]::Ceiling($cs.TotalPhysicalMemory / 1024 / 1024 / 1024)

Hope this helps.

Read and write a String from text file

It is recommended to read and write files asynchronously! and it's so easy to do in pure Swift,
here is the protocol:

protocol FileRepository {
    func read(from path: String) throws -> String
    func readAsync(from path: String, completion: @escaping (Result<String, Error>) -> Void)
    func write(_ string: String, to path: String) throws
    func writeAsync(_ string: String, to path: String, completion: @escaping (Result<Void, Error>) -> Void)
}

As you can see it allows you to read and write files synchronously or asynchronously.

Here is my implementation in Swift 5:

class DefaultFileRepository {
    
    // MARK: Properties
    
    let queue: DispatchQueue = .global()
    let fileManager: FileManager = .default
    lazy var baseURL: URL = {
        try! fileManager
            .url(for: .libraryDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
            .appendingPathComponent("MyFiles")
    }()
    
    
    // MARK: Private functions
    
    private func doRead(from path: String) throws -> String {
        let url = baseURL.appendingPathComponent(path)
        
        var isDir: ObjCBool = false
        guard fileManager.fileExists(atPath: url.path, isDirectory: &isDir) && !isDir.boolValue else {
            throw ReadWriteError.doesNotExist
        }
        
        let string: String
        do {
            string = try String(contentsOf: url)
        } catch {
            throw ReadWriteError.readFailed(error)
        }
        
        return string
    }
    
    private func doWrite(_ string: String, to path: String) throws {
        let url = baseURL.appendingPathComponent(path)
        let folderURL = url.deletingLastPathComponent()
        
        var isFolderDir: ObjCBool = false
        if fileManager.fileExists(atPath: folderURL.path, isDirectory: &isFolderDir) {
            if !isFolderDir.boolValue {
                throw ReadWriteError.canNotCreateFolder
            }
        } else {
            do {
                try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
            } catch {
                throw ReadWriteError.canNotCreateFolder
            }
        }
        
        var isDir: ObjCBool = false
        guard !fileManager.fileExists(atPath: url.path, isDirectory: &isDir) || !isDir.boolValue else {
            throw ReadWriteError.canNotCreateFile
        }
        
        guard let data = string.data(using: .utf8) else {
            throw ReadWriteError.encodingFailed
        }
        
        do {
            try data.write(to: url)
        } catch {
            throw ReadWriteError.writeFailed(error)
        }
    }
    
}


extension DefaultFileRepository: FileRepository {
    func read(from path: String) throws -> String {
        try queue.sync { try self.doRead(from: path) }
    }
    
    func readAsync(from path: String, completion: @escaping (Result<String, Error>) -> Void) {
        queue.async {
            do {
                let result = try self.doRead(from: path)
                completion(.success(result))
            } catch {
                completion(.failure(error))
            }
        }
    }
    
    func write(_ string: String, to path: String) throws {
        try queue.sync { try self.doWrite(string, to: path) }
    }
    
    func writeAsync(_ string: String, to path: String, completion: @escaping (Result<Void, Error>) -> Void) {
        queue.async {
            do {
                try self.doWrite(string, to: path)
                completion(.success(Void()))
            } catch {
                completion(.failure(error))
            }
        }
    }
    
}


enum ReadWriteError: LocalizedError {
    
    // MARK: Cases
    
    case doesNotExist
    case readFailed(Error)
    case canNotCreateFolder
    case canNotCreateFile
    case encodingFailed
    case writeFailed(Error)
}

str.startswith with a list of strings to test for

You can also use any(), map() like so:

if any(map(l.startswith, x)):
    pass # Do something

Or alternatively, using a generator expression:

if any(l.startswith(s) for s in x)
    pass # Do something

What are the differences between JSON and JSONP?

JSON

JSON (JavaScript Object Notation) is a convenient way to transport data between applications, especially when the destination is a JavaScript application.

Example:

Here is a minimal example that uses JSON as the transport for the server response. The client makes an Ajax request with the jQuery shorthand function $.getJSON. The server generates a hash, formats it as JSON and returns this to the client. The client formats this and puts it in a page element.

Server:

get '/json' do
 content_type :json
 content = { :response  => 'Sent via JSON',
            :timestamp => Time.now,
            :random    => rand(10000) }
 content.to_json
end

Client:

var url = host_prefix + '/json';
$.getJSON(url, function(json){
  $("#json-response").html(JSON.stringify(json, null, 2));
});

Output:

  {
   "response": "Sent via JSON",
   "timestamp": "2014-06-18 09:49:01 +0000",
   "random": 6074
  }

JSONP (JSON with Padding)

JSONP is a simple way to overcome browser restrictions when sending JSON responses from different domains from the client.

The only change on the client side with JSONP is to add a callback parameter to the URL

Server:

get '/jsonp' do
 callback = params['callback']
 content_type :js
 content = { :response  => 'Sent via JSONP',
            :timestamp => Time.now,
            :random    => rand(10000) }
 "#{callback}(#{content.to_json})"
end

Client:

var url = host_prefix + '/jsonp?callback=?';
$.getJSON(url, function(jsonp){
  $("#jsonp-response").html(JSON.stringify(jsonp, null, 2));
});

Output:

 {
  "response": "Sent via JSONP",
  "timestamp": "2014-06-18 09:50:15 +0000",
  "random": 364
}

Which TensorFlow and CUDA version combinations are compatible?

I had a similar problem after upgrading to TF 2.0. The CUDA version that TF was reporting did not match what Ubuntu 18.04 thought I had installed. It said I was using CUDA 7.5.0, but apt thought I had the right version installed.

What I eventually had to do was grep recursively in /usr/local for CUDNN_MAJOR, and I found that /usr/local/cuda-10.0/targets/x86_64-linux/include/cudnn.h did indeed specify the version as 7.5.0.
/usr/local/cuda-10.1 got it right, and /usr/local/cuda pointed to /usr/local/cuda-10.1, so it was (and remains) a mystery to me why TF was looking at /usr/local/cuda-10.0.

Anyway, I just moved /usr/local/cuda-10.0 to /usr/local/old-cuda-10.0 so TF couldn't find it any more and everything then worked like a charm.

It was all very frustrating, and I still feel like I just did a random hack. But it worked :) and perhaps this will help someone with a similar issue.