Programs & Examples On #Monotone

Monotone is an open-source distributed version control system.

How to concatenate two MP4 files using FFmpeg?

Here is a script I made to concatenate several GoPro mp4's into a 720p mp4. Hope it's of help.

#!/bin/sh
cmd="( "
for i; do
    cmd="${cmd}ffmpeg -i $i -ab 256000 -vb 10000000 -mbd rd -trellis 2 -cmp 2 -subcmp 2 -g 100 -f mpeg -; "
done
cmd="${cmd} ) | ffmpeg -i - -vb 10000000 -ab 256000 -s 1280x720 -y out-`date +%F-%H%M.%S`.mp4"
echo "${cmd}"
eval ${cmd}

How do I compile a Visual Studio project from the command-line?

I know of two ways to do it.

Method 1
The first method (which I prefer) is to use msbuild:

msbuild project.sln /Flags...

Method 2
You can also run:

vcexpress project.sln /build /Flags...

The vcexpress option returns immediately and does not print any output. I suppose that might be what you want for a script.

Note that DevEnv is not distributed with Visual Studio Express 2008 (I spent a lot of time trying to figure that out when I first had a similar issue).

So, the end result might be:

os.system("msbuild project.sln /p:Configuration=Debug")

You'll also want to make sure your environment variables are correct, as msbuild and vcexpress are not by default on the system path. Either start the Visual Studio build environment and run your script from there, or modify the paths in Python (with os.putenv).

makefiles - compile all c files at once

LIBS  = -lkernel32 -luser32 -lgdi32 -lopengl32
CFLAGS = -Wall

# Should be equivalent to your list of C files, if you don't build selectively
SRC=$(wildcard *.c)

test: $(SRC)
    gcc -o $@ $^ $(CFLAGS) $(LIBS)

Get remote registry value

Try the Remote Registry Module, the registry provider cannot operate remotely:

Import-Module PSRemoteRegistry
Get-RegValue -ComputerName $Computer1 -Key SOFTWARE\Veritas\NetBackup\CurrentVersion -Value PackageVersion 

How to define partitioning of DataFrame?

So to start with some kind of answer : ) - You can't

I am not an expert, but as far as I understand DataFrames, they are not equal to rdd and DataFrame has no such thing as Partitioner.

Generally DataFrame's idea is to provide another level of abstraction that handles such problems itself. The queries on DataFrame are translated into logical plan that is further translated to operations on RDDs. The partitioning you suggested will probably be applied automatically or at least should be.

If you don't trust SparkSQL that it will provide some kind of optimal job, you can always transform DataFrame to RDD[Row] as suggested in of the comments.

wildcard * in CSS for classes

If you don't need the unique identifier for further styling of the divs and are using HTML5 you could try and go with custom Data Attributes. Read on here or try a google search for HTML5 Custom Data Attributes

How to generate graphs and charts from mysql database in php

I use Google Chart Tools https://developers.google.com/chart/ It's well documented and the charts look great. Being javascript, you can feed it json data via ajax.

How to get all of the immediate subdirectories in Python

I have to mention the path.py library, which I use very often.

Fetching the immediate subdirectories become as simple as that:

my_dir.dirs()

The full working example is:

from path import Path

my_directory = Path("path/to/my/directory")

subdirs = my_directory.dirs()

NB: my_directory still can be manipulated as a string, since Path is a subclass of string, but providing a bunch of useful methods for manipulating paths

Interface/enum listing standard mime-type constants

Java 7 to the rescue!

You can either pass the file or the file name and it will return the MIME type.

String mimeType = MimetypesFileTypeMap
    .getDefaultFileTypeMap()
    .getContentType(attachment.getFileName());

http://docs.oracle.com/javase/7/docs/api/javax/activation/MimetypesFileTypeMap.html

How to set menu to Toolbar in Android

private Toolbar toolbar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    toolbar = (Toolbar) findViewById(R.id.my_toolbar);
    *// here is where you set it to show on the toolbar*
    setSupportActionBar(toolbar);
}

Well, you need to set support action bar setSupportActionBar(); and pass your variable, like so: setSupportActionBar(toolbar);

JavaScript - Get Browser Height

var winWidth = window.screen.width;
var winHeight = window.screen.height;

document.write(winWidth, winHeight);

Can't import javax.servlet.annotation.WebServlet

Add library 'Server Runtime' to your java build path, and it shall resolve the issue.

Comparing strings, c++

string cat = "cat";
string human = "human";

cout << cat.compare(human) << endl; 

This code will give -1 as a result. This is due to the first non-matching character of the compared string 'h' is lower or appears after 'c' in alphabetical order, even though the compared string, 'human' is longer than 'cat'.

I find the return value described in cplusplus.com is more accurate which are-:

0 : They compare equal

<0 : Either the value of the first character that does not match is lower in the compared string, or all compared characters match but the compared string is shorter.

more than 0 : Either the value of the first character that does not match is greater in the compared string, or all compared characters match but the compared string is longer.

Moreover, IMO cppreference.com's description is simpler and so far best describe to my own experience.

negative value if *this appears before the character sequence specified by the arguments, in lexicographical order

zero if both character sequences compare equivalent

positive value if *this appears after the character sequence specified by the arguments, in lexicographical order

What is the difference between "SMS Push" and "WAP Push"?

SMS Push uses SMS as a carrier, WAP uses download via WAP.

How can I convert a datetime object to milliseconds since epoch (unix time) in Python?

>>> import datetime
>>> # replace datetime.datetime.now() with your datetime object
>>> int(datetime.datetime.now().strftime("%s")) * 1000 
1312908481000

Or the help of the time module (and without date formatting):

>>> import datetime, time
>>> # replace datetime.datetime.now() with your datetime object
>>> time.mktime(datetime.datetime.now().timetuple()) * 1000
1312908681000.0

Answered with help from: http://pleac.sourceforge.net/pleac_python/datesandtimes.html

Documentation:

$(window).scrollTop() vs. $(document).scrollTop()

They are both going to have the same effect.

However, as pointed out in the comments: $(window).scrollTop() is supported by more web browsers than $('html').scrollTop().

how to show progress bar(circle) in an activity having a listview before loading the listview with data

Process Bar:

Dependency:

     implementation 'com.github.castorflex.smoothprogressbar:library:1.0.0'

XML:

     <fr.castorflex.android.smoothprogressbar.SmoothProgressBar
        xmlns:android="http://schemas.android.com/apk/res/android"                
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/myProcessbar"
        android:layout_width="match_parent"
        android:layout_height="10dp"
        android:indeterminate="true" />

In Res->color

      <color name="pocket_color_1">#ff1635</color>
      <integer-array name="pocket_background_colors">
          <item>@color/pocket_color_1</item>
      </integer-array>

      <color name="pocket_color_stop">#00ff00</color>
      <integer-array name="pocket_background_stop">
          <item>@color/pocket_color_stop</item>
      </integer-array>

In Main:

      public class MainActivity extends AppCompatActivity{
        SmoothProgressBar smoothProgressBar;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          smoothProgressBar=findViewById(R.id.myProcessbar);
          showProcessBar();
          stopAnimation();    // call when required to stop process
        }

        public void showProcessBar(){
          smoothProgressBar.setVisibility(View.VISIBLE);
          smoothProgressBar.setIndeterminateDrawable(new SmoothProgressDrawable.Builder(getApplicationContext())
            .interpolator(new AccelerateInterpolator())
            .progressiveStart(true)
            .progressiveStopSpeed(1000)
            .build());
          smoothProgressBar.setSmoothProgressDrawableBackgroundDrawable(
          SmoothProgressBarUtils.generateDrawableWithColors(
                    getResources().getIntArray(R.array.pocket_background_colors),
                    ((SmoothProgressDrawable)  smoothProgressBar.getIndeterminateDrawable()).getStrokeWidth()));
        }

        public void stopAnimation(){
          smoothProgressBar.setSmoothProgressDrawableBackgroundDrawable(
          SmoothProgressBarUtils.generateDrawableWithColors(
                    getResources().getIntArray(R.array.pocket_background_stop),
                    ((SmoothProgressDrawable)  smoothProgressBar.getIndeterminateDrawable()).getStrokeWidth()));
          smoothProgressBar.progressiveStop();
          Handler handler=new Handler();
          handler.postDelayed(new Runnable() {
            @Override
            public void run() {
               smoothProgressBar.animate().alpha(0.0f).setDuration(6000).translationY(1000);
               smoothProgressBar.setVisibility(View.GONE);
            }
          },1000);
}

      }

How to programmatically set style attribute in a view

Generally you can't change styles programmatically; you can set the look of a screen, or part of a layout, or individual button in your XML layout using themes or styles. Themes can, however, be applied programmatically.

There is also such a thing as a StateListDrawable which lets you define different drawables for each state the your Button can be in, whether focused, selected, pressed, disabled and so on.

For example, to get your button to change colour when it's pressed, you could define an XML file called res/drawable/my_button.xml directory like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item
    android:state_pressed="true"
    android:drawable="@drawable/btn_pressed" />
  <item
    android:state_pressed="false"
    android:drawable="@drawable/btn_normal" />
</selector>

You can then apply this selector to a Button by setting the property android:background="@drawable/my_button".

How to recover stashed uncommitted changes

The easy answer to the easy question is git stash apply

Just check out the branch you want your changes on, and then git stash apply. Then use git diff to see the result.

After you're all done with your changes—the apply looks good and you're sure you don't need the stash any more—then use git stash drop to get rid of it.

I always suggest using git stash apply rather than git stash pop. The difference is that apply leaves the stash around for easy re-try of the apply, or for looking at, etc. If pop is able to extract the stash, it will immediately also drop it, and if you the suddenly realize that you wanted to extract it somewhere else (in a different branch), or with --index, or some such, that's not so easy. If you apply, you get to choose when to drop.

It's all pretty minor one way or the other though, and for a newbie to git, it should be about the same. (And you can skip all the rest of this!)


What if you're doing more-advanced or more-complicated stuff?

There are at least three or four different "ways to use git stash", as it were. The above is for "way 1", the "easy way":

  1. You started with a clean branch, were working on some changes, and then realized you were doing them in the wrong branch. You just want to take the changes you have now and "move" them to another branch.

    This is the easy case, described above. Run git stash save (or plain git stash, same thing). Check out the other branch and use git stash apply. This gets git to merge in your earlier changes, using git's rather powerful merge mechanism. Inspect the results carefully (with git diff) to see if you like them, and if you do, use git stash drop to drop the stash. You're done!

  2. You started some changes and stashed them. Then you switched to another branch and started more changes, forgetting that you had the stashed ones.

    Now you want to keep, or even move, these changes, and apply your stash too.

    You can in fact git stash save again, as git stash makes a "stack" of changes. If you do that you have two stashes, one just called stash—but you can also write stash@{0}—and one spelled stash@{1}. Use git stash list (at any time) to see them all. The newest is always the lowest-numbered. When you git stash drop, it drops the newest, and the one that was stash@{1} moves to the top of the stack. If you had even more, the one that was stash@{2} becomes stash@{1}, and so on.

    You can apply and then drop a specific stash, too: git stash apply stash@{2}, and so on. Dropping a specific stash, renumbers only the higher-numbered ones. Again, the one without a number is also stash@{0}.

    If you pile up a lot of stashes, it can get fairly messy (was the stash I wanted stash@{7} or was it stash@{4}? Wait, I just pushed another, now they're 8 and 5?). I personally prefer to transfer these changes to a new branch, because branches have names, and cleanup-attempt-in-December means a lot more to me than stash@{12}. (The git stash command takes an optional save-message, and those can help, but somehow, all my stashes just wind up named WIP on branch.)

  3. (Extra-advanced) You've used git stash save -p, or carefully git add-ed and/or git rm-ed specific bits of your code before running git stash save. You had one version in the stashed index/staging area, and another (different) version in the working tree. You want to preserve all this. So now you use git stash apply --index, and that sometimes fails with:

    Conflicts in index.  Try without --index.
    
  4. You're using git stash save --keep-index in order to test "what will be committed". This one is beyond the scope of this answer; see this other StackOverflow answer instead.

For complicated cases, I recommend starting in a "clean" working directory first, by committing any changes you have now (on a new branch if you like). That way the "somewhere" that you are applying them, has nothing else in it, and you'll just be trying the stashed changes:

git status               # see if there's anything you need to commit
                         # uh oh, there is - let's put it on a new temp branch
git checkout -b temp     # create new temp branch to save stuff
git add ...              # add (and/or remove) stuff as needed
git commit               # save first set of changes

Now you're on a "clean" starting point. Or maybe it goes more like this:

git status               # see if there's anything you need to commit
                         # status says "nothing to commit"
git checkout -b temp     # optional: create new branch for "apply"
git stash apply          # apply stashed changes; see below about --index

The main thing to remember is that the "stash" is a commit, it's just a slightly "funny/weird" commit that's not "on a branch". The apply operation looks at what the commit changed, and tries to repeat it wherever you are now. The stash will still be there (apply keeps it around), so you can look at it more, or decide this was the wrong place to apply it and try again differently, or whatever.


Any time you have a stash, you can use git stash show -p to see a simplified version of what's in the stash. (This simplified version looks only at the "final work tree" changes, not the saved index changes that --index restores separately.) The command git stash apply, without --index, just tries to make those same changes in your work-directory now.

This is true even if you already have some changes. The apply command is happy to apply a stash to a modified working directory (or at least, to try to apply it). You can, for instance, do this:

git stash apply stash      # apply top of stash stack
git stash apply stash@{1}  # and mix in next stash stack entry too

You can choose the "apply" order here, picking out particular stashes to apply in a particular sequence. Note, however, that each time you're basically doing a "git merge", and as the merge documentation warns:

Running git merge with non-trivial uncommitted changes is discouraged: while possible, it may leave you in a state that is hard to back out of in the case of a conflict.

If you start with a clean directory and are just doing several git apply operations, it's easy to back out: use git reset --hard to get back to the clean state, and change your apply operations. (That's why I recommend starting in a clean working directory first, for these complicated cases.)


What about the very worst possible case?

Let's say you're doing Lots Of Advanced Git Stuff, and you've made a stash, and want to git stash apply --index, but it's no longer possible to apply the saved stash with --index, because the branch has diverged too much since the time you saved it.

This is what git stash branch is for.

If you:

  1. check out the exact commit you were on when you did the original stash, then
  2. create a new branch, and finally
  3. git stash apply --index

the attempt to re-create the changes definitely will work. This is what git stash branch newbranch does. (And it then drops the stash since it was successfully applied.)


Some final words about --index (what the heck is it?)

What the --index does is simple to explain, but a bit complicated internally:

  • When you have changes, you have to git add (or "stage") them before commiting.
  • Thus, when you ran git stash, you might have edited both files foo and zorg, but only staged one of those.
  • So when you ask to get the stash back, it might be nice if it git adds the added things and does not git add the non-added things. That is, if you added foo but not zorg back before you did the stash, it might be nice to have that exact same setup. What was staged, should again be staged; what was modified but not staged, should again be modified but not staged.

The --index flag to apply tries to set things up this way. If your work-tree is clean, this usually just works. If your work-tree already has stuff added, though, you can see how there might be some problems here. If you leave out --index, the apply operation does not attempt to preserve the whole staged/unstaged setup. Instead, it just invokes git's merge machinery, using the work-tree commit in the "stash bag". If you don't care about preserving staged/unstaged, leaving out --index makes it a lot easier for git stash apply to do its thing.

Getting content/message from HttpResponseMessage

Try this, you can create an extension method like this:

    public static string ContentToString(this HttpContent httpContent)
    {
        var readAsStringAsync = httpContent.ReadAsStringAsync();
        return readAsStringAsync.Result;
    }

and then, simple call the extension method:

txtBlock.Text = response.Content.ContentToString();

I hope this help you ;-)

Bootstrap4 adding scrollbar to div

Yes, It is possible, Just add a class like anyclass and give some CSS style. Live

.anyClass {
  height:150px;
  overflow-y: scroll;
}

_x000D_
_x000D_
.anyClass {_x000D_
  height:150px;_x000D_
  overflow-y: scroll;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class=" col-md-2">_x000D_
  <ul class="nav nav-pills nav-stacked anyClass">_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link active" href="#">Active</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li><li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li><li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li><li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li><li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link disabled" href="#">Disabled</a>_x000D_
    </li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

LINQ to SQL using GROUP BY and COUNT(DISTINCT)

Linq to sql has no support for Count(Distinct ...). You therefore have to map a .NET method in code onto a Sql server function (thus Count(distinct.. )) and use that.

btw, it doesn't help if you post pseudo code copied from a toolkit in a format that's neither VB.NET nor C#.

How do I remove a comma off the end of a string?

rtrim ($string , ","); is the easiest way.

How do you unit test private methods?

Sometimes, it can be good to test private declarations. Fundamentally, a compiler only has one public method: Compile( string outputFileName, params string[] sourceSFileNames ). I'm sure you understand that would be difficult to test such a method without testing each "hidden" declarations!

That's why we have created Visual T#: to make easier tests. It's a free .NET programming language (C# v2.0 compatible).

We have added '.-' operator. It just behave like '.' operator, except you can also access any hidden declaration from your tests without changing anything in your tested project.

Take a look at our web site: download it for free.

React Native: Getting the position of an element

This seems to have changed in the latest version of React Native when using refs to calculate.

Declare refs this way.

  <View
    ref={(image) => {
    this._image = image
  }}>

And find the value this way.

  _measure = () => {
    this._image._component.measure((width, height, px, py, fx, fy) => {
      const location = {
        fx: fx,
        fy: fy,
        px: px,
        py: py,
        width: width,
        height: height
      }
      console.log(location)
    })
  }

What is a method group in C#?

The ToString function has many overloads - the method group would be the group consisting of all the different overloads for that function.

Center align with table-cell

Here is a good starting point.

HTML:

<div class="containing-table">
    <div class="centre-align">
        <div class="content"></div>
    </div>
</div>

CSS:

.containing-table {
    display: table;
    width: 100%;
    height: 400px; /* for demo only */
    border: 1px dotted blue;
}
.centre-align {
    padding: 10px;
    border: 1px dashed gray;
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
.content {
    width: 50px;
    height: 50px;
    background-color: red;
    display: inline-block;
    vertical-align: top; /* Removes the extra white space below the baseline */
}

See demo at: http://jsfiddle.net/audetwebdesign/jSVyY/

.containing-table establishes the width and height context for .centre-align (the table-cell).

You can apply text-align and vertical-align to alter .centre-align as needed.

Note that .content needs to use display: inline-block if it is to be centered horizontally using the text-align property.

CSS image overlay with color and transparency

Have you given a try to Webkit Filters?

You can manipulate not only opacity, but colour, brightness, luminosity and other properties:

finished with non zero exit value

look through your styles.xml files for a @+id/ I had one in styles.xml in values-v17 which I don't recall creating. This is what I had to change in the end and not build tools 21.1.2 to 22.0.1 as suggested.

In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?

I had this issue and tried both, but had to settle for removing crap like "pageEditState", but not removing user info lest I have to look it up again.

public static void RemoveEverythingButUserInfo()
{
    foreach (String o in HttpContext.Current.Session.Keys)
    {
        if (o != "UserInfoIDontWantToAskForAgain")
            keys.Add(o);
    }
}

Error while retrieving information from the server RPC:s-7:AEC-0 in Google play?

If you are in a country such as Argentina, you should call your bank and verify that your card is authorized for international purchases. Certain credit cards in that country (such as pre-paid credit cards) are ONLY authorized for domestic purchases and purchases in bordering countries. They DO work online, but the purchase must be from a bordering country. What this means is that you may get this message because your card is valid but denied. I know, because this has happened to me today. Hopefully this helps someone else understand what their system is telling them.

Define variable to use with IN operator (T-SQL)

I think you'll have to declare a string and then execute that SQL string.

Have a look at sp_executeSQL

How do I link to Google Maps with a particular longitude and latitude?

Find your location in the Google Earth program, and click the icon "View in Google Maps". The URL bar in your browser will show the URL you need.

Call-time pass-by-reference has been removed

Only call time pass-by-reference is removed. So change:

call_user_func($func, &$this, &$client ...

To this:

call_user_func($func, $this, $client ...

&$this should never be needed after PHP4 anyway period.

If you absolutely need $client to be passed by reference, update the function ($func) signature instead (function func(&$client) {)

Remove HTML Tags in Javascript with Regex

The way I do it is practically a one-liner.

The function creates a Range object and then creates a DocumentFragment in the Range with the string as the child content.

Then it grabs the text of the fragment, removes any "invisible"/zero-width characters, and trims it of any leading/trailing white space.

I realize this question is old, I just thought my solution was unique and wanted to share. :)

function getTextFromString(htmlString) {
    return document
        .createRange()
        // Creates a fragment and turns the supplied string into HTML nodes
        .createContextualFragment(htmlString)
        // Gets the text from the fragment
        .textContent
        // Removes the Zero-Width Space, Zero-Width Joiner, Zero-Width No-Break Space, Left-To-Right Mark, and Right-To-Left Mark characters
        .replace(/[\u200B-\u200D\uFEFF\u200E\u200F]/g, '')
        // Trims off any extra space on either end of the string
        .trim();
}

var cleanString = getTextFromString('<p>Hello world! I <em>love</em> <strong>JavaScript</strong>!!!</p>');

alert(cleanString);

How can I hide an HTML table row <tr> so that it takes up no space?

position: absolute will remove it from the layout flow and should solve your problem - the element will remain in the DOM but won't affect others.

Wait until all jQuery Ajax requests are done?

$.when doesn't work for me, callback(x) instead of return x worked as described here: https://stackoverflow.com/a/13455253/10357604

How to append elements into a dictionary in Swift?

I added Dictionary extension

extension Dictionary {   
  func cloneWith(_ dict: [Key: Value]) -> [Key: Value] {
    var result = self
    dict.forEach { key, value in result[key] = value }
    return result  
  }
}

you can use cloneWith like this

 newDictionary = dict.reduce([3 : "efg"]) { r, e in r.cloneWith(e) }

How to select min and max values of a column in a datatable?

Session["MinDate"] = dtRecord.Compute("Min(AccountLevel)", string.Empty);
Session["MaxDate"] = dtRecord.Compute("Max(AccountLevel)", string.Empty);

How to test if a string contains one of the substrings in a list, in pandas?

You can use str.contains alone with a regex pattern using OR (|):

s[s.str.contains('og|at')]

Or you could add the series to a dataframe then use str.contains:

df = pd.DataFrame(s)
df[s.str.contains('og|at')] 

Output:

0 cat
1 hat
2 dog
3 fog 

Xcode 4 - "Valid signing identity not found" error on provisioning profiles on a new Macintosh install

No one has mentioned this yet, and this may not be a common problem, but I had a similar problem with Xcode 5: Make sure you have a default keychain selected in the Mac's Keychain Access. I trying out a fresh install of Mountain Lion and deleted one keychain, which happened to be the default. After setting another keychain as the default (right-click on the keychain and select Make Keychain "Keychain_name" default"), Xcode was able to set up the valid signing identities.

Undoing a git rebase

What I usually do is git reset #commit_hash

to the last commit where I think rebase had no effect.

then git pull

Now your branch should match exactly like master and rebased commits should not be in it.

Now one can just cherry-pick the commits on this branch.

React Native TextInput that only accepts numeric characters

if (!/^[0-9]+$/.test('123456askm')) {
  consol.log('Enter Only Number');
} else {
    consol.log('Sucess');
}

How to Convert Excel Numeric Cell Value into Words

There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.

  1. press Alt+F11
  2. MENU: (Tool Strip) Insert Module
  3. copy and paste the below code


Option Explicit

Public Numbers As Variant, Tens As Variant

Sub SetNums()
    Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
    Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub

Function WordNum(MyNumber As Double) As String
    Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
    Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
    ' This macro was written by Chris Mead - www.MeadInKent.co.uk
    If Abs(MyNumber) > 999999999 Then
        WordNum = "Value too large"
        Exit Function
    End If
    SetNums
    ' String representation of amount (excl decimals)
    NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
    ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
    For n = 3 To 1 Step -1    'analyse the absolute number as 3 sets of 3 digits
        StrNo = Format(ValNo(n), "000")
        If ValNo(n) > 0 Then
            Temp1 = GetTens(Val(Right(StrNo, 2)))
            If Left(StrNo, 1) <> "0" Then
                Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
                If Temp1 <> "" Then Temp2 = Temp2 & " and "
            Else
                Temp2 = ""
            End If
            If n = 3 Then
                If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
                WordNum = Trim(Temp2 & Temp1)
            End If
            If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
            If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
        End If
    Next n
    NumStr = Trim(Str(Abs(MyNumber)))
    ' Values after the decimal place
    DecimalPosition = InStr(NumStr, ".")
    Numbers(0) = "Zero"
    If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
        Temp1 = " point"
        For n = DecimalPosition + 1 To Len(NumStr)
            Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
        Next n
        WordNum = WordNum & Temp1
    End If
    If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
        WordNum = "Zero" & WordNum
    End If
End Function

Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
    If TensNum <= 19 Then
        GetTens = Numbers(TensNum)
    Else
        Dim MyNo As String
        MyNo = Format(TensNum, "00")
        GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
    End If
End Function

After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)

It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.

Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)

you will see a Words equivalent of the numeric value.

This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel

What is w3wp.exe?

Chris pretty much sums up what w3wp is. In order to disable the warning, go to this registry key:

HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0\Debugger

And set the value DisableAttachSecurityWarning to 1.

Convert ascii value to char

To convert an int ASCII value to character you can also use:

int asciiValue = 65;
char character = char(asciiValue);
cout << character; // output: A
cout << char(90); // output: Z

Serialize an object to string

Code Safety Note

Regarding the accepted answer, it is important to use toSerialize.GetType() instead of typeof(T) in XmlSerializer constructor: if you use the first one the code covers all possible scenarios, while using the latter one fails sometimes.

Here is a link with some example code that motivate this statement, with XmlSerializer throwing an Exception when typeof(T) is used, because you pass an instance of a derived type to a method that calls SerializeObject<T>() that is defined in the derived type's base class: http://ideone.com/1Z5J1. Note that Ideone uses Mono to execute code: the actual Exception you would get using the Microsoft .NET runtime has a different Message than the one shown on Ideone, but it fails just the same.

For the sake of completeness I post the full code sample here for future reference, just in case Ideone (where I posted the code) becomes unavailable in the future:

using System;
using System.Xml.Serialization;
using System.IO;

public class Test
{
    public static void Main()
    {
        Sub subInstance = new Sub();
        Console.WriteLine(subInstance.TestMethod());
    }

    public class Super
    {
        public string TestMethod() {
            return this.SerializeObject();
        }
    }

    public class Sub : Super
    {
    }
}

public static class TestExt {
    public static string SerializeObject<T>(this T toSerialize)
    {
        Console.WriteLine(typeof(T).Name);             // PRINTS: "Super", the base/superclass -- Expected output is "Sub" instead
        Console.WriteLine(toSerialize.GetType().Name); // PRINTS: "Sub", the derived/subclass

        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
        StringWriter textWriter = new StringWriter();

        // And now...this will throw and Exception!
        // Changing new XmlSerializer(typeof(T)) to new XmlSerializer(subInstance.GetType()); 
        // solves the problem
        xmlSerializer.Serialize(textWriter, toSerialize);
        return textWriter.ToString();
    }
}

window.location.href and window.open () methods in JavaScript

window.open () will open a new window, whereas window.location.href will open the new URL in your current window.

How to enable bulk permission in SQL Server

Try this:

USE master;

GO;
 
GRANT ADMINISTER BULK OPERATIONS TO shira;

convert date string to mysql datetime field

First, convert the string into a timestamp:

$timestamp = strtotime($string);

Then do a

date("Y-m-d H:i:s", $timestamp);

Get max and min value from array in JavaScript

To get min/max value in array, you can use:

var _array = [1,3,2];
Math.max.apply(Math,_array); // 3
Math.min.apply(Math,_array); // 1

Aborting a shell script if any command returns a non-zero value

The $? variable is rarely needed. The pseudo-idiom command; if [ $? -eq 0 ]; then X; fi should always be written as if command; then X; fi.

The cases where $? is required is when it needs to be checked against multiple values:

command
case $? in
  (0) X;;
  (1) Y;;
  (2) Z;;
esac

or when $? needs to be reused or otherwise manipulated:

if command; then
  echo "command successful" >&2
else
  ret=$?
  echo "command failed with exit code $ret" >&2
  exit $ret
fi

Setting a max character length in CSS

Pure CSS solution to truncating multi line characters

I had a similar problem and found this excellent css only solution from Hackingui.com. You can read the article for information but below is the main code.

I tested it and it works perfectly. Hopefully someone finds it useful before opting for JS or server side options

  /* styles for '...' */ 
.block-with-text {
  /* hide text if it more than N lines  */
  overflow: hidden;
  /* for set '...' in absolute position */
  position: relative; 
  /* use this value to count block height */
  line-height: 1.2em;
  /* max-height = line-height (1.2) * lines max number (3) */
  max-height: 3.6em; 
  /* fix problem when last visible word doesn't adjoin right side  */
  text-align: justify;  
  /* place for '...' */
  margin-right: -1em;
  padding-right: 1em;
}

/* create the ... */
.block-with-text:before {
  /* points in the end */
  content: '...';
  /* absolute position */
  position: absolute;
  /* set position to right bottom corner of block */
  right: 0;
  bottom: 0;
}

/* hide ... if we have text, which is less than or equal to max lines */
.block-with-text:after {
  /* points in the end */
  content: '';
  /* absolute position */
  position: absolute;
  /* set position to right bottom corner of text */
  right: 0;
  /* set width and height */
  width: 1em;
  height: 1em;
  margin-top: 0.2em;
  /* bg color = bg color under block */
  background: white;
}

Converting SVG to PNG using C#

To add to the response from @Anish, if you are having issues with not seeing the text when exporting the SVG to an image, you can create a recursive function to loop through the children of the SVGDocument, try to cast it to a SvgText if possible (add your own error checking) and set the font family and style.

    foreach(var child in svgDocument.Children)
    {
        SetFont(child);
    }

    public void SetFont(SvgElement element)
    {
        foreach(var child in element.Children)
        {
            SetFont(child); //Call this function again with the child, this will loop
                            //until the element has no more children
        }

        try
        {
            var svgText = (SvgText)parent; //try to cast the element as a SvgText
                                           //if it succeeds you can modify the font

            svgText.Font = new Font("Arial", 12.0f);
            svgText.FontSize = new SvgUnit(12.0f);
        }
        catch
        {

        }
    }

Let me know if there are questions.

What's the pythonic way to use getters and setters?

You can use the magic methods __getattribute__ and __setattr__.

class MyClass:
    def __init__(self, attrvalue):
        self.myattr = attrvalue
    def __getattribute__(self, attr):
        if attr == "myattr":
            #Getter for myattr
    def __setattr__(self, attr):
        if attr == "myattr":
            #Setter for myattr

Be aware that __getattr__ and __getattribute__ are not the same. __getattr__ is only invoked when the attribute is not found.

How to wait until an element exists?

This is a simple solution for those who are used to promises and don't want to use any third party libs or timers.

I have been using it in my projects for a while

function waitForElm(selector) {
    return new Promise(resolve => {
        if (document.querySelector(selector)) {
            return resolve(document.querySelector(selector));
        }

        const observer = new MutationObserver(mutations => {
            if (document.querySelector(selector)) {
                resolve(document.querySelector(selector));
                observer.disconnect();
            }
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    });
}

To use it:

waitForElm('.some-class').then(elm => console.log(elm.textContent));

or with async/await

const elm = await waitForElm('.some-classs')

How to call Oracle MD5 hash function?

To calculate MD5 hash of CLOB content field with my desired encoding without implicitly recoding content to AL32UTF8, I've used this code:

create or replace function clob2blob(AClob CLOB) return BLOB is
  Result BLOB;
  o1 integer;
  o2 integer;
  c integer;
  w integer;
begin
  o1 := 1;
  o2 := 1;
  c := 0;
  w := 0;
  DBMS_LOB.CreateTemporary(Result, true);
  DBMS_LOB.ConvertToBlob(Result, AClob, length(AClob), o1, o2, 0, c, w);
  return(Result);
end clob2blob;
/

update my_table t set t.hash = (rawtohex(DBMS_CRYPTO.Hash(clob2blob(t.content),2)));

VueJS conditionally add an attribute for an element

It's notable to understand that if you'd like to conditionally add attributes you can also add a dynamic declaration:

<input v-bind="attrs" />

where attrs is declared as an object:

data() {
    return {
        attrs: {
            required: true,
            type: "text"
        }
    }
}

Which will result in:

<input required type="text"/>

Ideal in cases with multiple attributes.

What is the yield keyword used for in C#?

Here is a simple way to understand the concept: The basic idea is, if you want a collection that you can use "foreach" on, but gathering the items into the collection is expensive for some reason (like querying them out of a database), AND you will often not need the entire collection, then you create a function that builds the collection one item at a time and yields it back to the consumer (who can then terminate the collection effort early).

Think of it this way: You go to the meat counter and want to buy a pound of sliced ham. The butcher takes a 10-pound ham to the back, puts it on the slicer machine, slices the whole thing, then brings the pile of slices back to you and measures out a pound of it. (OLD way). With yield, the butcher brings the slicer machine to the counter, and starts slicing and "yielding" each slice onto the scale until it measures 1-pound, then wraps it for you and you're done. The Old Way may be better for the butcher (lets him organize his machinery the way he likes), but the New Way is clearly more efficient in most cases for the consumer.

How can I render inline JavaScript with Jade / Pug?

simply use a 'script' tag with a dot after.

script.
  var users = !{JSON.stringify(users).replace(/<\//g, "<\\/")}

https://github.com/pugjs/pug/blob/master/examples/dynamicscript.pug

Email & Phone Validation in Swift

Updated version of iksnae's awesome answer. It's not a regex, but I think it's the best solution to validate all countries' phone numbers as it is smart enough to know if the country's phone extension code is valid as well.

extension String {
    public var validPhoneNumber: Bool {
        let types: NSTextCheckingResult.CheckingType = [.phoneNumber]
        guard let detector = try? NSDataDetector(types: types.rawValue) else { return false }
        if let match = detector.matches(in: self, options: [], range: NSMakeRange(0, self.count)).first?.phoneNumber {
            return match == self
        } else {
            return false
        }
    }
}

print("\("+96 (123) 456-0990".validPhoneNumber)") //returns false, smart enough to know if country phone code is valid as well 
print("\("+994 (123) 456-0990".validPhoneNumber)") //returns true because +994 country code is an actual country phone code
print("\("(123) 456-0990".validPhoneNumber)") //returns true
print("\("123-456-0990".validPhoneNumber)") //returns true
print("\("1234560990".validPhoneNumber)") //returns true

jQuery UI dialog box not positioned center screen

Add this to your dialog declaration

my: "center",
at: "center",
of: window

Example :

$("#dialog").dialog({
       autoOpen: false,
        height: "auto",
        width: "auto",
        modal: true,
        position: {
            my: "center",
            at: "center",
            of: window
        }
})

Trying to git pull with error: cannot open .git/FETCH_HEAD: Permission denied

Simply go to your root folder and run this command:

chmod a+rw .git/FETCH_HEAD

Which comment style should I use in batch files?

A very detailed and analytic discussion on the topic is available on THIS page

It has the example codes and the pros/cons of different options.

How to change xampp localhost to another folder ( outside xampp folder)?

steps :

  1. run your xampp control panel
  2. click the button saying config
  3. select apache( httpd.conf )
  4. find document root

replace

DocumentRoot "C:/xampp/htdocs"
<Directory "C:/xampp/htdocs">

Those 2 lines

| C:/xampp/htdocs == current location for root |

|change C:/xampp/htdocs with any location you want|

  1. save it

DONE: start apache and go to the localhost see in action [ watch video click here ]

Using DateTime in a SqlParameter for Stored Procedure, format error

Here is how I add parameters:

sprocCommand.Parameters.Add(New SqlParameter("@Date_Of_Birth",Data.SqlDbType.DateTime))
sprocCommand.Parameters("@Date_Of_Birth").Value = DOB

I am assuming when you write out DOB there are no quotes.

Are you using a third-party control to get the date? I have had problems with the way the text value is generated from some of them.

Lastly, does it work if you type in the .Value attribute of the parameter without referencing DOB?

Check whether variable is number or string in JavaScript

Best way to do this:

function isNumber(num) {
  return (typeof num == 'string' || typeof num == 'number') && !isNaN(num - 0) && num !== '';
};

This satisfies the following test cases:

assertEquals("ISNUMBER-True: 0", true, isNumber(0));
assertEquals("ISNUMBER-True: 1", true, isNumber(-1));
assertEquals("ISNUMBER-True: 2", true, isNumber(-500));
assertEquals("ISNUMBER-True: 3", true, isNumber(15000));
assertEquals("ISNUMBER-True: 4", true, isNumber(0.35));
assertEquals("ISNUMBER-True: 5", true, isNumber(-10.35));
assertEquals("ISNUMBER-True: 6", true, isNumber(2.534e25));
assertEquals("ISNUMBER-True: 7", true, isNumber('2.534e25'));
assertEquals("ISNUMBER-True: 8", true, isNumber('52334'));
assertEquals("ISNUMBER-True: 9", true, isNumber('-234'));

assertEquals("ISNUMBER-False: 0", false, isNumber(NaN));
assertEquals("ISNUMBER-False: 1", false, isNumber({}));
assertEquals("ISNUMBER-False: 2", false, isNumber([]));
assertEquals("ISNUMBER-False: 3", false, isNumber(''));
assertEquals("ISNUMBER-False: 4", false, isNumber('one'));
assertEquals("ISNUMBER-False: 5", false, isNumber(true));
assertEquals("ISNUMBER-False: 6", false, isNumber(false));
assertEquals("ISNUMBER-False: 7", false, isNumber());
assertEquals("ISNUMBER-False: 8", false, isNumber(undefined));
assertEquals("ISNUMBER-False: 9", false, isNumber(null));

Turn off auto formatting in Visual Studio

Follow TOOLS->OPTIONS->Text Editor->CSS->Formatting Choose "Compact Rules" and uncheck "Hiearerchical indentation"

How can I preview a merge in git?

git log currentbranch..otherbranch will give you the list of commits that will go into the current branch if you do a merge. The usual arguments to log which give details on the commits will give you more information.

git diff currentbranch otherbranch will give you the diff between the two commits that will become one. This will be a diff that gives you everything that will get merged.

Would these help?

php: Get html source code with cURL

I found a tool in Github that could possibly be a solution to this question. https://incarnate.github.io/curl-to-php/ I hope that will be useful

Auto-loading lib files in Rails 4

This might help someone like me that finds this answer when searching for solutions to how Rails handles the class loading ... I found that I had to define a module whose name matched my filename appropriately, rather than just defining a class:

In file lib/development_mail_interceptor.rb (Yes, I'm using code from a Railscast :))

module DevelopmentMailInterceptor
  class DevelopmentMailInterceptor
    def self.delivering_email(message)
      message.subject = "intercepted for: #{message.to} #{message.subject}"
      message.to = "[email protected]"
    end
  end
end

works, but it doesn't load if I hadn't put the class inside a module.

Error handling in C code

I personally prefer the former approach (returning an error indicator).

Where necessary the return result should just indicate that an error occurred, with another function being used to find out the exact error.

In your getSize() example I'd consider that sizes must always be zero or positive, so returning a negative result can indicate an error, much like UNIX system calls do.

I can't think of any library that I've used that goes for the latter approach with an error object passed in as a pointer. stdio, etc all go with a return value.

How to get the sign, mantissa and exponent of a floating point number

See this IEEE_754_types.h header for the union types to extract: float, double and long double, (endianness handled). Here is an extract:

/*
** - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
**  Single Precision (float)  --  Standard IEEE 754 Floating-point Specification
*/

# define IEEE_754_FLOAT_MANTISSA_BITS (23)
# define IEEE_754_FLOAT_EXPONENT_BITS (8)
# define IEEE_754_FLOAT_SIGN_BITS     (1)

.
.
.

# if (IS_BIG_ENDIAN == 1)
    typedef union {
        float value;
        struct {
            __int8_t   sign     : IEEE_754_FLOAT_SIGN_BITS;
            __int8_t   exponent : IEEE_754_FLOAT_EXPONENT_BITS;
            __uint32_t mantissa : IEEE_754_FLOAT_MANTISSA_BITS;
        };
    } IEEE_754_float;
# else
    typedef union {
        float value;
        struct {
            __uint32_t mantissa : IEEE_754_FLOAT_MANTISSA_BITS;
            __int8_t   exponent : IEEE_754_FLOAT_EXPONENT_BITS;
            __int8_t   sign     : IEEE_754_FLOAT_SIGN_BITS;
        };
    } IEEE_754_float;
# endif

And see dtoa_base.c for a demonstration of how to convert a double value to string form.

Furthermore, check out section 1.2.1.1.4.2 - Floating-Point Type Memory Layout of the C/CPP Reference Book, it explains super well and in simple terms the memory representation/layout of all the floating-point types and how to decode them (w/ illustrations) following the actually IEEE 754 Floating-Point specification.

It also has links to really really good ressources that explain even deeper.

SQLAlchemy: how to filter date field?

In fact, your query is right except for the typo: your filter is excluding all records: you should change the <= for >= and vice versa:

qry = DBSession.query(User).filter(
        and_(User.birthday <= '1988-01-17', User.birthday >= '1985-01-17'))
# or same:
qry = DBSession.query(User).filter(User.birthday <= '1988-01-17').\
        filter(User.birthday >= '1985-01-17')

Also you can use between:

qry = DBSession.query(User).filter(User.birthday.between('1985-01-17', '1988-01-17'))

Stop UIWebView from "bouncing" vertically?

for (id subview in webView.subviews)
  if ([[subview class] isSubclassOfClass: [UIScrollView class]])
    ((UIScrollView *)subview).bounces = NO;

...seems to work fine.

It'll be accepted to App Store as well.

Update: in iOS 5.x+ there's an easier way - UIWebView has scrollView property, so your code can look like this:

webView.scrollView.bounces = NO;

Same goes for WKWebView.

do { ... } while (0) — what is it good for?

It's the only construct in C that you can use to #define a multistatement operation, put a semicolon after, and still use within an if statement. An example might help:

#define FOO(x) foo(x); bar(x)

if (condition)
    FOO(x);
else // syntax error here
    ...;

Even using braces doesn't help:

#define FOO(x) { foo(x); bar(x); }

Using this in an if statement would require that you omit the semicolon, which is counterintuitive:

if (condition)
    FOO(x)
else
    ...

If you define FOO like this:

#define FOO(x) do { foo(x); bar(x); } while (0)

then the following is syntactically correct:

if (condition)
    FOO(x);
else
    ....

How to read line by line of a text area HTML tag

Two options: no JQuery required, or JQuery version

No JQuery (or anything else required)

var textArea = document.getElementById('myTextAreaId');
var lines = textArea.value.split('\n');    // lines is an array of strings

// Loop through all lines
for (var j = 0; j < lines.length; j++) {
  console.log('Line ' + j + ' is ' + lines[j])
}

JQuery version

var lines = $('#myTextAreaId').val().split('\n');   // lines is an array of strings

// Loop through all lines
for (var j = 0; j < lines.length; j++) {
  console.log('Line ' + j + ' is ' + lines[j])
}

Side note, if you prefer forEach a sample loop is

lines.forEach(function(line) {
  console.log('Line is ' + line)
})

Intel HAXM installation error - This computer does not support Intel Virtualization Technology (VT-x)

Just follows these steps:

  1. Go to Control Panel ? Program and Feature.
  2. Click on Turn Window Features on and off. A window opens.
  3. Uncheck Hyper-V and Windows Hypervisor Platform options and restart your system.

Now, you can Start HAXM installation without any error.

Archive the artifacts in Jenkins

An artifact can be any result of your build process. The important thing is that it doesn't matter on which client it was built it will be tranfered from the workspace back to the master (server) and stored there with a link to the build. The advantage is that it is versionized this way, you only have to setup backup on your master and that all artifacts are accesible via the web interface even if all build clients are offline.

It is possible to define a regular expression as the artifact name. In my case I zipped all the files I wanted to store in one file with a constant name during the build.

Does Java have a path joining method?

This is a start, I don't think it works exactly as you intend, but it at least produces a consistent result.

import java.io.File;

public class Main
{
    public static void main(final String[] argv)
        throws Exception
    {
        System.out.println(pathJoin());
        System.out.println(pathJoin(""));
        System.out.println(pathJoin("a"));
        System.out.println(pathJoin("a", "b"));
        System.out.println(pathJoin("a", "b", "c"));
        System.out.println(pathJoin("a", "b", "", "def"));
    }

    public static String pathJoin(final String ... pathElements)
    {
        final String path;

        if(pathElements == null || pathElements.length == 0)
        {
            path = File.separator;
        }
        else
        {
            final StringBuilder builder;

            builder = new StringBuilder();

            for(final String pathElement : pathElements)
            {
                final String sanitizedPathElement;

                // the "\\" is for Windows... you will need to come up with the 
                // appropriate regex for this to be portable
                sanitizedPathElement = pathElement.replaceAll("\\" + File.separator, "");

                if(sanitizedPathElement.length() > 0)
                {
                    builder.append(sanitizedPathElement);
                    builder.append(File.separator);
                }
            }

            path = builder.toString();
        }

        return (path);
    }
}

Rendering HTML elements to <canvas>

RasterizeHTML is a very good project, but if you need to access the canvas it wont work on chrome. due to the use of <foreignObject>.

If you need to access the canvas then you can use html2canvas

I am trying to find another project as html2canvas is very slow in performance

How to call a method in another class in Java?

Try this :

public void addTeacherToClassRoom(classroom myClassRoom, String TeacherName)
{
    myClassRoom.setTeacherName(TeacherName);
}

Numpy converting array from float to strings

This is probably slower than what you want, but you can do:

>>> tostring = vectorize(lambda x: str(x))
>>> numpy.where(tostring(phis).astype('float64') != phis)
(array([], dtype=int64),)

It looks like it rounds off the values when it converts to str from float64, but this way you can customize the conversion however you like.

Adding items to end of linked list

loop to the last element of the linked list which have next pointer to null then modify the next pointer to point to a new node which has the data=object and next pointer = null

Get text of the selected option with jQuery

$(document).ready(function() {
    $('select#select_2').change(function() {
        var selectedText = $(this).find('option:selected').text();
        alert(selectedText);
    });
});

Fiddle

grep from tar.gz without extracting [faster one]

If you have zgrep you can use

zgrep -a string file.tar.gz

Jquery Value match Regex

Change it to this:

var email = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;

This is a regular expression literal that is passed the i flag which means to be case insensitive.

Keep in mind that email address validation is hard (there is a 4 or 5 page regular expression at the end of Mastering Regular Expressions demonstrating this) and your expression certainly will not capture all valid e-mail addresses.

Java inner class and static nested class

Here is key differences and similarities between Java inner class and static nested class.

Hope it helps!

Inner class

  • Can access to outer class both instance and static methods and fields
  • Associated with instance of enclosing class so to instantiate it first needs an instance of outer class (note new keyword place):

    Outerclass.InnerClass innerObject = outerObject.new Innerclass();
    
  • Cannot define any static members itself

  • Cannot have Class or Interface declaration

Static nested class

  • Cannot access outer class instance methods or fields

  • Not associated with any instance of enclosing class So to instantiate it:

    OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
    

Similarities

  • Both Inner classes can access even private fields and methods of outer class
  • Also the Outer class have access to private fields and methods of inner classes
  • Both classes can have private, protected or public access modifier

Why Use Nested Classes?

According to Oracle documentation there're several reasons (full documentation):

  • It is a way of logically grouping classes that are only used in one place: If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.

  • It increases encapsulation: Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.

  • It can lead to more readable and maintainable code: Nesting small classes within top-level classes places the code closer to where it is used.

How do I find which transaction is causing a "Waiting for table metadata lock" state?

If you cannot find the process locking the table (cause it is alreay dead), it may be a thread still cleaning up like this

section TRANSACTION of

show engine innodb status;

at the end

---TRANSACTION 1135701157, ACTIVE 6768 sec
MySQL thread id 5208136, OS thread handle 0x7f2982e91700, query id 882213399 xxxIPxxx 82.235.36.49 my_user cleaning up

as mentionned in a comment in Clear transaction deadlock?

you can try killing the transaction thread directly, here with

 KILL 5208136;

worked for me.

What does <? php echo ("<pre>"); ..... echo("</pre>"); ?> mean?

The <prev> tag doesn't exist, but it's probably the <pre> HTML tag to put around debug output, to improve readability. It's not a secret PHP hack. :)

android - listview get item view by position

Listview lv = (ListView) findViewById(R.id.previewlist);

    final BaseAdapter adapter = new PreviewAdapter(this, name, age);

    confirm.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub


            View view = null;

            String value;
            for (int i = 0; i < adapter.getCount(); i++) {

                view = adapter.getView(i, view, lv);

                Textview et = (TextView) view.findViewById(R.id.passfare);


                value=et.getText().toString();

                 Toast.makeText(getApplicationContext(), value,
                 Toast.LENGTH_SHORT).show();
            }



        }
    });

What is lexical scope?

Lexical scope means that a function looks up variables in the context where it was defined, and not in the scope immediately around it.

Look at how lexical scope works in Lisp if you want more detail. The selected answer by Kyle Cronin in Dynamic and Lexical variables in Common Lisp is a lot clearer than the answers here.

Coincidentally I only learned about this in a Lisp class, and it happens to apply in JavaScript as well.

I ran this code in Chrome's console.

// JavaScript               Equivalent Lisp
var x = 5;                //(setf x 5)
console.debug(x);         //(print x)
function print_x(){       //(defun print-x ()
    console.debug(x);     //    (print x)
}                         //)
(function(){              //(let
    var x = 10;           //    ((x 10))
    console.debug(x);     //    (print x)
    print_x();            //    (print-x)
})();                     //)

Output:

5
10
5

Remove trailing spaces automatically or with a shortcut

You can enable whitespace trimming at file save time from settings:

  1. Open Visual Studio Code User Settings (menu FilePreferencesSettingsUser Settings tab).
  2. Click the enter image description here icon in the top-right part of the window. This will open a document.
  3. Add a new "files.trimTrailingWhitespace": true setting to the User Settings document if it's not already there. This is so you aren't editing the Default Setting directly, but instead adding to it.
  4. Save the User Settings file.

We also added a new command to trigger this manually (Trim Trailing Whitespace from the command palette).

Creating a blurring overlay view

Here's a fast implementation in Swift using CIGaussianBlur:

func blur(image image: UIImage) -> UIImage {
    let radius: CGFloat = 20;
    let context = CIContext(options: nil);
    let inputImage = CIImage(CGImage: image.CGImage!);
    let filter = CIFilter(name: "CIGaussianBlur");
    filter?.setValue(inputImage, forKey: kCIInputImageKey);
    filter?.setValue("\(radius)", forKey:kCIInputRadiusKey);
    let result = filter?.valueForKey(kCIOutputImageKey) as! CIImage;
    let rect = CGRectMake(radius * 2, radius * 2, image.size.width - radius * 4, image.size.height - radius * 4)
    let cgImage = context.createCGImage(result, fromRect: rect);
    let returnImage = UIImage(CGImage: cgImage);

    return returnImage;
}

Easy way to concatenate two byte arrays

Here's a nice solution using Guava's com.google.common.primitives.Bytes:

byte[] c = Bytes.concat(a, b);

The great thing about this method is that it has a varargs signature:

public static byte[] concat(byte[]... arrays)

which means that you can concatenate an arbitrary number of arrays in a single method call.

change values in array when doing foreach

The callback is passed the element, the index, and the array itself.

arr.forEach(function(part, index, theArray) {
  theArray[index] = "hello world";
});

edit — as noted in a comment, the .forEach() function can take a second argument, which will be used as the value of this in each call to the callback:

arr.forEach(function(part, index) {
  this[index] = "hello world";
}, arr); // use arr as this

That second example shows arr itself being set up as this in the callback.One might think that the array involved in the .forEach() call might be the default value of this, but for whatever reason it's not; this will be undefined if that second argument is not provided.

(Note: the above stuff about this does not apply if the callback is a => function, because this is never bound to anything when such functions are invoked.)

Also it's important to remember that there is a whole family of similar utilities provided on the Array prototype, and many questions pop up on Stackoverflow about one function or another such that the best solution is to simply pick a different tool. You've got:

  • forEach for doing a thing with or to every entry in an array;
  • filter for producing a new array containing only qualifying entries;
  • map for making a one-to-one new array by transforming an existing array;
  • some to check whether at least one element in an array fits some description;
  • every to check whether all entries in an array match a description;
  • find to look for a value in an array

and so on. MDN link

Add rows to CSV File in powershell

Create a new custom object and add it to the object array that Import-Csv creates.

$fileContent = Import-csv $file -header "Date", "Description"
$newRow = New-Object PsObject -Property @{ Date = 'Text4' ; Description = 'Text5' }
$fileContent += $newRow

Date object to Calendar [Java]

Calendar.setTime()

It's often useful to look at the signature and description of API methods, not just their name :) - Even in the Java standard API, names can sometimes be misleading.

What REST PUT/POST/DELETE calls should return by a convention?

Forgive the flippancy, but if you are doing REST over HTTP then RFC7231 describes exactly what behaviour is expected from GET, PUT, POST and DELETE.

Update (Jul 3 '14):
The HTTP spec intentionally does not define what is returned from POST or DELETE. The spec only defines what needs to be defined. The rest is left up to the implementer to choose.

What causes and what are the differences between NoClassDefFoundError and ClassNotFoundException?

What is the reason for getting each of them and any thought process on how to deal with such errors?

They're closely related. A ClassNotFoundException is thrown when Java went looking for a particular class by name and could not successfully load it. A NoClassDefFoundError is thrown when Java went looking for a class that was linked into some existing code, but couldn't find it for one reason or another (e.g., wrong classpath, wrong version of Java, wrong version of a library) and is thoroughly fatal as it indicates that something has gone Badly Wrong.

If you've got a C background, a CNFE is like a failure to dlopen()/dlsym() and an NCDFE is a problem with the linker; in the second case, the class files concerned should never have been actually compiled in the configuration you're trying to use them.

How To Check If A Key in **kwargs Exists?

DSM's and Tadeck's answers answer your question directly.

In my scripts I often use the convenient dict.pop() to deal with optional, and additional arguments. Here's an example of a simple print() wrapper:

def my_print(*args, **kwargs):
    prefix = kwargs.pop('prefix', '')
    print(prefix, *args, **kwargs)

Then:

>>> my_print('eggs')
 eggs
>>> my_print('eggs', prefix='spam')
spam eggs

As you can see, if prefix is not contained in kwargs, then the default '' (empty string) is being stored in the local prefix variable. If it is given, then its value is being used.

This is generally a compact and readable recipe for writing wrappers for any kind of function: Always just pass-through arguments you don't understand, and don't even know if they exist. If you always pass through *args and **kwargs you make your code slower, and requires a bit more typing, but if interfaces of the called function (in this case print) changes, you don't need to change your code. This approach reduces development time while supporting all interface changes.

How can one display images side by side in a GitHub README.md?

You can place each image side-by-side by writing the markdown for each image on the same line.

![alt-text-1](image1.png "title-1") ![alt-text-2](image2.png "title-2")

As long as the images aren't too large, they will display inline as demonstrated by this screen shot of a README file from GitHub:

inline images

Converting string to byte array in C#

Building off Ali's answer, I would recommend an extension method that allows you to optionally pass in the encoding you want to use:

using System.Text;
public static class StringExtensions
{
    /// <summary>
    /// Creates a byte array from the string, using the 
    /// System.Text.Encoding.Default encoding unless another is specified.
    /// </summary>
    public static byte[] ToByteArray(this string str, Encoding encoding = Encoding.Default)
    {
        return encoding.GetBytes(str);
    }
}

And use it like below:

string foo = "bla bla";

// default encoding
byte[] default = foo.ToByteArray();

// custom encoding
byte[] unicode = foo.ToByteArray(Encoding.Unicode);

Python: How to convert datetime format?

>>> import datetime
>>> d = datetime.datetime.strptime('2011-06-09', '%Y-%m-%d')
>>> d.strftime('%b %d,%Y')
'Jun 09,2011'

In pre-2.5 Python, you can replace datetime.strptime with time.strptime, like so (untested): datetime.datetime(*(time.strptime('2011-06-09', '%Y-%m-%d')[0:6]))

How does one use the onerror attribute of an img element

This works:

<img src="invalid_link"
     onerror="this.onerror=null;this.src='https://placeimg.com/200/300/animals';"
>

Live demo: http://jsfiddle.net/oLqfxjoz/

As Nikola pointed out in the comment below, in case the backup URL is invalid as well, some browsers will trigger the "error" event again which will result in an infinite loop. We can guard against this by simply nullifying the "error" handler via this.onerror=null;.

How do I download a file using VBA (without Internet Explorer)

A modified version of above to make it more dynamic.

Public Function DownloadFileB(ByVal URL As String, ByVal DownloadPath As String, ByRef Username As String, ByRef Password, Optional Overwrite As Boolean = True) As Boolean
    On Error GoTo Failed

    Dim WinHttpReq          As Object: Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")

    WinHttpReq.Open "GET", URL, False, Username, Password
    WinHttpReq.send

    If WinHttpReq.Status = 200 Then
        Dim oStream         As Object: Set oStream = CreateObject("ADODB.Stream")
        oStream.Open
        oStream.Type = 1
        oStream.Write WinHttpReq.responseBody
        oStream.SaveToFile DownloadPath, Abs(CInt(Overwrite)) + 1
        oStream.Close
        DownloadFileB = Len(Dir(DownloadPath)) > 0
        Exit Function
    End If

Failed:
    DownloadFileB = False
End Function

How to redirect to logon page when session State time out is completed in asp.net mvc

There is a generic solution:

Lets say you have a controller named Admin where you put content for authorized users.

Then, you can override the Initialize or OnAuthorization methods of Admin controller and write redirect to login page logic on session timeout in these methods as described:

protected override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
    {
        //lets say you set session value to a positive integer
        AdminLoginType = Convert.ToInt32(filterContext.HttpContext.Session["AdminLoginType"]);
        if (AdminLoginType == 0)
        {
            filterContext.HttpContext.Response.Redirect("~/login");
        }

        base.OnAuthorization(filterContext);
    }

Difference between & and && in Java?

&& == logical AND

& = bitwise AND

How to see remote tags?

Even without cloning or fetching, you can check the list of tags on the upstream repo with git ls-remote:

git ls-remote --tags /url/to/upstream/repo

(as illustrated in "When listing git-ls-remote why there's “^{}” after the tag name?")

xbmono illustrates in the comments that quotes are needed:

git ls-remote --tags /some/url/to/repo "refs/tags/MyTag^{}"

Note that you can always push your commits and tags in one command with (git 1.8.3+, April 2013):

git push --follow-tags

See Push git commits & tags simultaneously.


Regarding Atlassian SourceTree specifically:

Note that, from this thread, SourceTree ONLY shows local tags.

There is an RFE (Request for Enhancement) logged in SRCTREEWIN-4015 since Dec. 2015.

A simple workaround:

see a list of only unpushed tags?

git push --tags

or check the "Push all tags" box on the "Push" dialog box, all tags will be pushed to your remote.

https://community.atlassian.com/tnckb94959/attachments/tnckb94959/sourcetree-questions/10923/1/Screen%20Shot%202015-12-15%20at%208.49.48%20AM.png

That way, you will be "sure that they are present in remote so that other developers can pull them".

How to go back to previous page if back button is pressed in WebView?

You can try this for webview in a fragment:

private lateinit var webView: WebView

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    val root = inflater.inflate(R.layout.fragment_name, container, false)
    webView = root!!.findViewById(R.id.home_web_view)
    var url: String = "http://yoururl.com"
    webView.settings.javaScriptEnabled = true
    webView.webViewClient = WebViewClient()
    webView.loadUrl(url)
    webView.canGoBack()
    webView.setOnKeyListener{ v, keyCode, event ->
        if(keyCode == KeyEvent.KEYCODE_BACK && event.action == MotionEvent.ACTION_UP
            && webView.canGoBack()){
            webView.goBack()
            return@setOnKeyListener true
        }
        false
    }
    return root
}

Safe width in pixels for printing web pages?

A printer doesn't understand pixels, it understand dots (pt in CSS). The best solution is to write an extra CSS for printing, with all of its measures in dots.

Then, in your HTML code, in head section, put:

<link href="style.css" rel="stylesheet" type="text/css" media="screen">
<link href="style_print.css" rel="stylesheet" type="text/css" media="print">

HTML button onclick event

<body>
"button" value="Add Students" onclick="window.location.href='Students.html';"> 
<input type="button" value="Add Courses" onclick="window.location.href='Courses.html';"> 
<input type="button" value="Student Payments" onclick="window.location.href='Payments.html';">
</body>

Swift performSelector:withObject:afterDelay: is unavailable

You could do this:

var timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("someSelector"), userInfo: nil, repeats: false)

func someSelector() {
    // Something after a delay
}

SWIFT 3

let timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(someSelector), userInfo: nil, repeats: false)

func someSelector() {
    // Something after a delay
}

Missing artifact com.oracle:ojdbc6:jar:11.2.0 in pom.xml

oracle driver. `

<dependency>
    <groupId>com.hynnet</groupId>
    <artifactId>jdbc-fo</artifactId>
    <version>12.1.0.2</version>
</dependency>

`

Origin is not allowed by Access-Control-Allow-Origin

if you're under apache, just add an .htaccess file to your directory with this content:

Header set Access-Control-Allow-Origin: *

Header set Access-Control-Allow-Headers: content-type

Header set Access-Control-Allow-Methods: *

WCF named pipe minimal example

I just found this excellent little tutorial. broken link (Cached version)

I also followed Microsoft's tutorial which is nice, but I only needed pipes as well.

As you can see, you don't need configuration files and all that messy stuff.

By the way, he uses both HTTP and pipes. Just remove all code lines related to HTTP, and you'll get a pure pipe example.

Alternate table with new not null Column in existing table in SQL

The easiest way to do this is :

ALTER TABLE db.TABLENAME ADD COLUMN [datatype] NOT NULL DEFAULT 'value'

Ex : Adding a column x (bit datatype) to a table ABC with default value 0

ALTER TABLE db.ABC ADD COLUMN x bit NOT NULL DEFAULT 0

PS : I am not a big fan of using the table designer for this. Its so much easier being conventional / old fashioned sometimes. :). Hope this helps answer

Pointer-to-pointer dynamic two-dimensional array

this can be done this way

  1. I have used Operator Overloading
  2. Overloaded Assignment
  3. Overloaded Copy Constructor

    /*
     * Soumil Nitin SHah
     * Github: https://github.com/soumilshah1995
     */
    
    #include <iostream>
    using namespace std;
            class Matrix{
    
    public:
        /*
         * Declare the Row and Column
         *
         */
        int r_size;
        int c_size;
        int **arr;
    
    public:
        /*
         * Constructor and Destructor
         */
    
        Matrix(int r_size, int c_size):r_size{r_size},c_size{c_size}
        {
            arr = new int*[r_size];
            // This Creates a 2-D Pointers
            for (int i=0 ;i < r_size; i++)
            {
                arr[i] = new int[c_size];
            }
    
            // Initialize all the Vector to 0 initially
            for (int row=0; row<r_size; row ++)
            {
                for (int column=0; column < c_size; column ++)
                {
                    arr[row][column] = 0;
                }
            }
            std::cout << "Constructor -- creating Array Size ::" << r_size << " " << c_size << endl;
        }
    
        ~Matrix()
        {
            std::cout << "Destructpr  -- Deleting  Array Size ::" << r_size <<" " << c_size << endl;
    
        }
    
        Matrix(const Matrix &source):Matrix(source.r_size, source.c_size)
    
        {
            for (int row=0; row<source.r_size; row ++)
            {
                for (int column=0; column < source.c_size; column ++)
                {
                    arr[row][column] = source.arr[row][column];
                }
            }
    
            cout << "Copy Constructor " << endl;
        }
    
    
    public:
        /*
         * Operator Overloading
         */
    
        friend std::ostream &operator<<(std::ostream &os, Matrix & rhs)
        {
            int rowCounter = 0;
            int columnCOUNTER = 0;
            int globalCounter = 0;
    
            for (int row =0; row < rhs.r_size; row ++)
            {
                for (int column=0; column < rhs.c_size ; column++)
                {
                    globalCounter = globalCounter + 1;
                }
                rowCounter = rowCounter + 1;
            }
    
    
            os << "Total There are " << globalCounter << " Elements" << endl;
            os << "Array Elements are as follow -------" << endl;
            os << "\n";
    
            for (int row =0; row < rhs.r_size; row ++)
            {
                for (int column=0; column < rhs.c_size ; column++)
                {
                    os << rhs.arr[row][column] << " ";
                }
            os <<"\n";
            }
            return os;
        }
    
        void operator()(int row, int column , int Data)
        {
            arr[row][column] = Data;
        }
    
        int &operator()(int row, int column)
        {
            return arr[row][column];
        }
    
        Matrix &operator=(Matrix &rhs)
                {
                    cout << "Assingment Operator called " << endl;cout <<"\n";
                    if(this == &rhs)
                    {
                        return *this;
                    } else
                        {
                        delete [] arr;
    
                            arr = new int*[r_size];
                            // This Creates a 2-D Pointers
                            for (int i=0 ;i < r_size; i++)
                            {
                                arr[i] = new int[c_size];
                            }
    
                            // Initialize all the Vector to 0 initially
                            for (int row=0; row<r_size; row ++)
                            {
                                for (int column=0; column < c_size; column ++)
                                {
                                    arr[row][column] = rhs.arr[row][column];
                                }
                            }
    
                            return *this;
                        }
    
                }
    
    };
    
                int main()
    {
    
        Matrix m1(3,3);         // Initialize Matrix 3x3
    
        cout << m1;cout << "\n";
    
        m1(0,0,1);
        m1(0,1,2);
        m1(0,2,3);
    
        m1(1,0,4);
        m1(1,1,5);
        m1(1,2,6);
    
        m1(2,0,7);
        m1(2,1,8);
        m1(2,2,9);
    
        cout << m1;cout <<"\n";             // print Matrix
        cout << "Element at Position (1,2) : " << m1(1,2) << endl;
    
        Matrix m2(3,3);
        m2 = m1;
        cout << m2;cout <<"\n";
    
        print(m2);
    
        return 0;
    }
    

Start / Stop a Windows Service from a non-Administrator user account

There is a free GUI Tool ServiceSecurityEditor

Which allows you to edit Windows Service permissions. I have successfully used it to give a non-Administrator user the rights to start and stop a service.

I had used "sc sdset" before I knew about this tool.

ServiceSecurityEditor feels like cheating, it's that easy :)

Declare variable in SQLite and use it

SQLite doesn't support native variable syntax, but you can achieve virtually the same using an in-memory temp table.

I've used the below approach for large projects and works like a charm.

/* Create in-memory temp table for variables */
BEGIN;

PRAGMA temp_store = 2;
CREATE TEMP TABLE _Variables(Name TEXT PRIMARY KEY, RealValue REAL, IntegerValue INTEGER, BlobValue BLOB, TextValue TEXT);

/* Declaring a variable */
INSERT INTO _Variables (Name) VALUES ('VariableName');

/* Assigning a variable (pick the right storage class) */
UPDATE _Variables SET IntegerValue = ... WHERE Name = 'VariableName';

/* Getting variable value (use within expression) */
... (SELECT coalesce(RealValue, IntegerValue, BlobValue, TextValue) FROM _Variables WHERE Name = 'VariableName' LIMIT 1) ...

DROP TABLE _Variables;
END;

Can't include C++ headers like vector in Android NDK

If you are using Android studio and you are still seeing the message "error: vector: No such file or directory" (or other stl related errors) when you're compiling using ndk, then this might help you.

In your project, open the module's build.gradle file (not your project's build.grade, but the one that is for your module) and add 'stl "stlport_shared"' within the ndk element in defaultConfig.

For eg:

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.domain.app"
        minSdkVersion 15
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"

        ndk {
            moduleName "myModuleName"
            stl "stlport_shared"
        }
    }
}

Android Studio Gradle project "Unable to start the daemon process /initialization of VM"

In the gradle.properties file, change org.gradle.jvmargs to -Xmx1024m:

org.gradle.jvmargs=**-Xmx1024m** -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

What is the non-jQuery equivalent of '$(document).ready()'?

A little thing I put together

domready.js

(function(exports, d) {
  function domReady(fn, context) {

    function onReady(event) {
      d.removeEventListener("DOMContentLoaded", onReady);
      fn.call(context || exports, event);
    }

    function onReadyIe(event) {
      if (d.readyState === "complete") {
        d.detachEvent("onreadystatechange", onReadyIe);
        fn.call(context || exports, event);
      }
    }

    d.addEventListener && d.addEventListener("DOMContentLoaded", onReady) ||
    d.attachEvent      && d.attachEvent("onreadystatechange", onReadyIe);
  }

  exports.domReady = domReady;
})(window, document);

How to use it

<script src="domready.js"></script>
<script>
  domReady(function(event) {
    alert("dom is ready!");
  });
</script>

You can also change the context in which the callback runs by passing a second argument

function init(event) {
  alert("check the console");
  this.log(event);
}

domReady(init, console);

'MOD' is not a recognized built-in function name

In TSQL, the modulo is done with a percent sign.

SELECT 38 % 5 would give you the modulo 3

Restoring database from .mdf and .ldf files of SQL Server 2008

First google search yielded me this answer. So I thought of updating this with newer version of attach, detach.

Create database dbname 
On 
(   
Filename= 'path where you copied files',   
Filename ='path where you copied log'
)
For attach; 

Further,if your database is cleanly shutdown(there are no active transactions while database was shutdown) and you dont have log file,you can use below method,SQL server will create a new transaction log file..

Create database dbname 
    On 
    (   
    Filename= 'path where you copied files'   
    )
    For attach; 

if you don't specify transaction log file,SQL will try to look in the default path and will try to use it irrespective of whether database was cleanly shutdown or not..

Here is what MSDN has to say about this..

If a read-write database has a single log file and you do not specify a new location for the log file, the attach operation looks in the old location for the file. If it is found, the old log file is used, regardless of whether the database was shut down cleanly. However, if the old log file is not found and if the database was shut down cleanly and has no active log chain, the attach operation attempts to build a new log file for the database.

There are some restrictions with this approach and some side affects too..

1.attach-and-detach operations both disable cross-database ownership chaining for the database
2.Database trustworthy is set to off
3.Detaching a read-only database loses information about the differential bases of differential backups.

Most importantly..you can't attach a database with recent versions to an earlier version

References:
https://msdn.microsoft.com/en-in/library/ms190794.aspx

Loop through each cell in a range of cells when given a Range object

Sub LoopRange()

    Dim rCell As Range
    Dim rRng As Range

    Set rRng = Sheet1.Range("A1:A6")

    For Each rCell In rRng.Cells
        Debug.Print rCell.Address, rCell.Value
    Next rCell

End Sub

Tablix: Repeat header rows on each page not working - Report Builder 3.0

Open Advanced Mode in the Groupings pane. (Click the arrow to the right of the Column Groups and select Advanced Mode.)

In the Row Groups area (not Column Groups), click on a Static group, which highlights the corresponding textbox in the tablix.

Click through each Static group until it highlights the leftmost column header. This is generally the first Static group listed.

In the properties grid:

  • set KeepWithGroup to After
  • set RepeatOnNewPage to True for repeating headers
  • set FixedData to True for keeping headers visible

Difference between datetime and timestamp in sqlserver?

Datetime is a datatype.

Timestamp is a method for row versioning. In fact, in sql server 2008 this column type was renamed (i.e. timestamp is deprecated) to rowversion. It basically means that every time a row is changed, this value is increased. This is done with a database counter which automatically increase for every inserted or updated row.

For more information:

http://www.sqlteam.com/article/timestamps-vs-datetime-data-types

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

jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox

I had a similar problem with trying to use the Facebook API.

The only contentType which didn't send the Preflighted request seemed to be just text/plain... not the rest of the parameters mentioned at mozilla here

  • Why is this the only browser which does this?
  • Why doesn't Facebook know and accept the preflight request?

FYI: The aforementioned Moz doc suggests X-Lori headers should trigger a Preflighted request ... it doesn't.

How do I get an OAuth 2.0 authentication token in C#

This example get token thouth HttpWebRequest

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(pathapi);
        request.Method = "POST";
        string postData = "grant_type=password";
        ASCIIEncoding encoding = new ASCIIEncoding();
        byte[] byte1 = encoding.GetBytes(postData);

        request.ContentType = "application/x-www-form-urlencoded";

        request.ContentLength = byte1.Length;
        Stream newStream = request.GetRequestStream();
        newStream.Write(byte1, 0, byte1.Length);

        HttpWebResponse response = request.GetResponse() as HttpWebResponse;            
        using (Stream responseStream = response.GetResponseStream())
        {
            StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
            getreaderjson = reader.ReadToEnd();
        }

Current timestamp as filename in Java

Date, SimpleDateFormat and whatever classes are required on the I/O side of things (there are many possibilities).

The activity must be exported or contain an intent-filter

Just Select App from dropdown menu with Run(green play icon). it will run the whole the App not the specific Activity. if it doesn't help try to use in that activity in ManiFest.xml file. thankyou

how to make a html iframe 100% width and height?

Answering this just in case if someone else like me stumbles upon this post among many that advise use of JavaScripts for changing iframe height to 100%.

I strongly recommend that you see and try this option specified at How do you give iframe 100% height before resorting to a JavaScript based option. The referenced solution works perfectly for me in all of the testing I have done so far. Hope this helps someone.

What is the fastest way to compare two sets in Java?

You have the following solution from https://www.mkyong.com/java/java-how-to-compare-two-sets/

public static boolean equals(Set<?> set1, Set<?> set2){

    if(set1 == null || set2 ==null){
        return false;
    }

    if(set1.size() != set2.size()){
        return false;
    }

    return set1.containsAll(set2);
}

Or if you prefer to use a single return statement:

public static boolean equals(Set<?> set1, Set<?> set2){

  return set1 != null 
    && set2 != null 
    && set1.size() == set2.size() 
    && set1.containsAll(set2);
}

Combine two columns and add into one new column

You don't need to store the column to reference it that way. Try this:

To set up:

CREATE TABLE tbl
  (zipcode text NOT NULL, city text NOT NULL, state text NOT NULL);
INSERT INTO tbl VALUES ('10954', 'Nanuet', 'NY');

We can see we have "the right stuff":

\pset border 2
SELECT * FROM tbl;
+---------+--------+-------+
| zipcode |  city  | state |
+---------+--------+-------+
| 10954   | Nanuet | NY    |
+---------+--------+-------+

Now add a function with the desired "column name" which takes the record type of the table as its only parameter:

CREATE FUNCTION combined(rec tbl)
  RETURNS text
  LANGUAGE SQL
AS $$
  SELECT $1.zipcode || ' - ' || $1.city || ', ' || $1.state;
$$;

This creates a function which can be used as if it were a column of the table, as long as the table name or alias is specified, like this:

SELECT *, tbl.combined FROM tbl;

Which displays like this:

+---------+--------+-------+--------------------+
| zipcode |  city  | state |      combined      |
+---------+--------+-------+--------------------+
| 10954   | Nanuet | NY    | 10954 - Nanuet, NY |
+---------+--------+-------+--------------------+

This works because PostgreSQL checks first for an actual column, but if one is not found, and the identifier is qualified with a relation name or alias, it looks for a function like the above, and runs it with the row as its argument, returning the result as if it were a column. You can even index on such a "generated column" if you want to do so.

Because you're not using extra space in each row for the duplicated data, or firing triggers on all inserts and updates, this can often be faster than the alternatives.

Content Type text/xml; charset=utf-8 was not supported by service

First Google hit says:

this is usually a mismatch in the client/server bindings, where the message version in the service uses SOAP 1.2 (which expects application/soap+xml) and the version in the client uses SOAP 1.1 (which sends text/xml). WSHttpBinding uses SOAP 1.2, BasicHttpBinding uses SOAP 1.1.

It usually seems to be a wsHttpBinding on one side and a basicHttpBinding on the other.

jquery animate background position

You can change the image background position using setInterval method, see demo here: http://jquerydemo.com/demo/animate-background-image.aspx

Find position of a node using xpath

I do a lot of Novell Identity Manager stuff, and XPATH in that context looks a little different.

Assume the value you are looking for is in a string variable, called TARGET, then the XPATH would be:

count(attr/value[.='$TARGET']/preceding-sibling::*)+1

Additionally it was pointed out that to save a few characters of space, the following would work as well:

count(attr/value[.='$TARGET']/preceding::*) + 1

I also posted a prettier version of this at Novell's Cool Solutions: Using XPATH to get the position node

SQL Server: UPDATE a table by using ORDER BY

You can not use ORDER BY as part of the UPDATE statement (you can use in sub-selects that are part of the update).

UPDATE Test 
SET Number = rowNumber 
FROM Test
INNER JOIN 
(SELECT ID, row_number() OVER (ORDER BY ID DESC) as rowNumber
FROM Test) drRowNumbers ON drRowNumbers.ID = Test.ID

Enable Hibernate logging

We have a tomcat-8.5 + restlet-2.3.4 + hibernate-4.2.0 + log4j-1.2.14 java 8 app running on AlpineLinux in docker.

On adding these 2 lines to /usr/local/tomcat/webapps/ROOT/WEB-INF/classes/log4j.properties, I started seeing the HQL queries in the logs:

### log just the SQL
log4j.logger.org.hibernate.SQL=debug

### log JDBC bind parameters ###
log4j.logger.org.hibernate.type=debug

However, the JDBC bind parameters are not being logged.

How to get first and last element in an array in java?

Getting first and last elements in an array in Java

int[] a = new int[]{1, 8, 5, 9, 4};

First Element: a[0]

Last Element: a[a.length-1]

Undefined variable: $_SESSION

You need make sure to start the session at the top of every PHP file where you want to use the $_SESSION superglobal. Like this:

<?php
  session_start();
  echo $_SESSION['youritem'];
?>

You forgot the Session HELPER.

Check this link : book.cakephp.org/2.0/en/core-libraries/helpers/session.html

Correct way to pause a Python program

I think I like this solution:

import getpass
getpass.getpass("Press Enter to Continue")

It hides whatever the user types in, which helps clarify that input is not used here.

But be mindful on the OS X platform. It displays a key which may be confusing.

It shows a key, like I said


Probably the best solution would be to do something similar to the getpass module yourself, without making a read -s call. Maybe making the foreground color match the background?

Pagination on a list using ng-repeat

Here is a demo code where there is pagination + Filtering with AngularJS :

https://codepen.io/lamjaguar/pen/yOrVym

JS :

var app=angular.module('myApp', []);

// alternate - https://github.com/michaelbromley/angularUtils/tree/master/src/directives/pagination
// alternate - http://fdietz.github.io/recipes-with-angular-js/common-user-interface-patterns/paginating-through-client-side-data.html

app.controller('MyCtrl', ['$scope', '$filter', function ($scope, $filter) {
    $scope.currentPage = 0;
    $scope.pageSize = 10;
    $scope.data = [];
    $scope.q = '';

    $scope.getData = function () {
      // needed for the pagination calc
      // https://docs.angularjs.org/api/ng/filter/filter
      return $filter('filter')($scope.data, $scope.q)
     /* 
       // manual filter
       // if u used this, remove the filter from html, remove above line and replace data with getData()

        var arr = [];
        if($scope.q == '') {
            arr = $scope.data;
        } else {
            for(var ea in $scope.data) {
                if($scope.data[ea].indexOf($scope.q) > -1) {
                    arr.push( $scope.data[ea] );
                }
            }
        }
        return arr;
       */
    }

    $scope.numberOfPages=function(){
        return Math.ceil($scope.getData().length/$scope.pageSize);                
    }

    for (var i=0; i<65; i++) {
        $scope.data.push("Item "+i);
    }
  // A watch to bring us back to the 
  // first pagination after each 
  // filtering
$scope.$watch('q', function(newValue,oldValue){             if(oldValue!=newValue){
      $scope.currentPage = 0;
  }
},true);
}]);

//We already have a limitTo filter built-in to angular,
//let's make a startFrom filter
app.filter('startFrom', function() {
    return function(input, start) {
        start = +start; //parse to int
        return input.slice(start);
    }
});

HTML :

<div ng-app="myApp" ng-controller="MyCtrl">
  <input ng-model="q" id="search" class="form-control" placeholder="Filter text">
  <select ng-model="pageSize" id="pageSize" class="form-control">
        <option value="5">5</option>
        <option value="10">10</option>
        <option value="15">15</option>
        <option value="20">20</option>
     </select>
  <ul>
    <li ng-repeat="item in data | filter:q | startFrom:currentPage*pageSize | limitTo:pageSize">
      {{item}}
    </li>
  </ul>
  <button ng-disabled="currentPage == 0" ng-click="currentPage=currentPage-1">
        Previous
    </button> {{currentPage+1}}/{{numberOfPages()}}
  <button ng-disabled="currentPage >= getData().length/pageSize - 1" ng-click="currentPage=currentPage+1">
        Next
    </button>
</div>

How to get the day name from a selected date?

I use this Extension Method:

public static string GetDayName(this DateTime date)
{
    string _ret = string.Empty; //Only for .NET Framework 4++
    var culture = new System.Globalization.CultureInfo("es-419"); //<- 'es-419' = Spanish (Latin America), 'en-US' = English (United States)
    _ret = culture.DateTimeFormat.GetDayName(date.DayOfWeek); //<- Get the Name     
    _ret = culture.TextInfo.ToTitleCase(_ret.ToLower()); //<- Convert to Capital title
    return _ret;
}

How to get values and keys from HashMap?

You have to follow the following sequence of opeartions:

  • Convert Map to MapSet with map.entrySet();
  • Get the iterator with Mapset.iterator();
  • Get Map.Entry with iterator.next();
  • use Entry.getKey() and Entry.getValue()
# define Map
for (Map.Entry entry: map.entrySet)
    System.out.println(entry.getKey() + entry.getValue);

fatal: could not create work tree dir 'kivy'

Assuming that you are using Windows, run the application as Admin.

For that, you have at least two options:

• Open the file location, right click and select "Run as Administrator".

Run Git Bash as Admin

• Using Windows Start menu, search for "Git Bash", and you will find the following:

Git Bash using Windows Start Menu

Then, just press "Run as Administrator".

C++ vector's insert & push_back difference

The functions have different purposes. vector::insert allows you to insert an object at a specified position in the vector, whereas vector::push_back will just stick the object on the end. See the following example:

using namespace std;
vector<int> v = {1, 3, 4};
v.insert(next(begin(v)), 2);
v.push_back(5);
// v now contains {1, 2, 3, 4, 5}

You can use insert to perform the same job as push_back with v.insert(v.end(), value).

Getting the first character of a string with $str[0]

The {} syntax is deprecated as of PHP 5.3.0. Square brackets are recommended.

HTML list-style-type dash

HTML

<ul>
  <li>One</li>
  <li>Very</li>
  <li>Simple</li>
  <li>Approach!</li>
</ul>

CSS

ul {
  list-style-type: none;
}

ul li:before {
  content: '-';
  position: absolute;
  margin-left: -20px;
}`

Do something if screen width is less than 960 px

You might want to combine it with a resize event:

 $(window).resize(function() {
  if ($(window).width() < 960) {
     alert('Less than 960');
  }
 else {
    alert('More than 960');
 }
});

For R.J.:

var eventFired = 0;

if ($(window).width() < 960) {
    alert('Less than 960');

}
else {
    alert('More than 960');
    eventFired = 1;
}

$(window).on('resize', function() {
    if (!eventFired) {
        if ($(window).width() < 960) {
            alert('Less than 960 resize');
        } else {
            alert('More than 960 resize');
        }
    }
});

I tried http://api.jquery.com/off/ with no success so I went with the eventFired flag.

What is %2C in a URL?

It's the ASCII keycode in hexadecimal for a comma (,).

You should use your language's URL encoding methods when placing strings in URLs.

You can see a handy list of characters with man ascii. It has this compact diagram available for mapping hexadecimal codes to the character:

   2 3 4 5 6 7       
 -------------      
0:   0 @ P ` p     
1: ! 1 A Q a q     
2: " 2 B R b r     
3: # 3 C S c s     
4: $ 4 D T d t     
5: % 5 E U e u     
6: & 6 F V f v     
7: ' 7 G W g w     
8: ( 8 H X h x     
9: ) 9 I Y i y     
A: * : J Z j z
B: + ; K [ k {
C: , < L \ l |
D: - = M ] m }
E: . > N ^ n ~
F: / ? O _ o DEL

You can also quickly check a character's hexadecimal equivalent with:

$ echo -n , | xxd -p
2c

Best way to show a loading/progress indicator?

Actually if you are waiting for response from a server it should be done programatically. You may create a progress dialog and dismiss it, but then again that is not "the android way".

Currently the recommended method is to use a DialogFragment :

public class MySpinnerDialog extends DialogFragment {

    public MySpinnerDialog() {
        // use empty constructors. If something is needed use onCreate's
    }

    @Override
    public Dialog onCreateDialog(final Bundle savedInstanceState) {

        _dialog = new ProgressDialog(getActivity());
        this.setStyle(STYLE_NO_TITLE, getTheme()); // You can use styles or inflate a view
        _dialog.setMessage("Spinning.."); // set your messages if not inflated from XML

        _dialog.setCancelable(false);  

        return _dialog;
    }
}

Then in your activity you set your Fragment manager and show the dialog once the wait for the server started:

FragmentManager fm = getSupportFragmentManager();
MySpinnerDialog myInstance = new MySpinnerDialog();
}
myInstance.show(fm, "some_tag");

Once your server has responded complete you will dismiss it:

myInstance.dismiss()

Remember that the progressdialog is a spinner or a progressbar depending on the attributes, read more on the api guide

How to strip HTML tags from a string in SQL Server?

Here's an updated version of this function that incorporates the RedFilter answer (Pinal's original) with the LazyCoders additions and the goodeye typo corrections AND my own addition to handle in-line <STYLE> tags inside the HTML.

ALTER FUNCTION [dbo].[udf_StripHTML]
(
@HTMLText varchar(MAX)
)
RETURNS varchar(MAX)
AS
BEGIN
DECLARE @Start  int
DECLARE @End    int
DECLARE @Length int

-- Replace the HTML entity &amp; with the '&' character (this needs to be done first, as
-- '&' might be double encoded as '&amp;amp;')
SET @Start = CHARINDEX('&amp;', @HTMLText)
SET @End = @Start + 4
SET @Length = (@End - @Start) + 1

WHILE (@Start > 0 AND @End > 0 AND @Length > 0) BEGIN
SET @HTMLText = STUFF(@HTMLText, @Start, @Length, '&')
SET @Start = CHARINDEX('&amp;', @HTMLText)
SET @End = @Start + 4
SET @Length = (@End - @Start) + 1
END

-- Replace the HTML entity &lt; with the '<' character
SET @Start = CHARINDEX('&lt;', @HTMLText)
SET @End = @Start + 3
SET @Length = (@End - @Start) + 1

WHILE (@Start > 0 AND @End > 0 AND @Length > 0) BEGIN
SET @HTMLText = STUFF(@HTMLText, @Start, @Length, '<')
SET @Start = CHARINDEX('&lt;', @HTMLText)
SET @End = @Start + 3
SET @Length = (@End - @Start) + 1
END

-- Replace the HTML entity &gt; with the '>' character
SET @Start = CHARINDEX('&gt;', @HTMLText)
SET @End = @Start + 3
SET @Length = (@End - @Start) + 1

WHILE (@Start > 0 AND @End > 0 AND @Length > 0) BEGIN
SET @HTMLText = STUFF(@HTMLText, @Start, @Length, '>')
SET @Start = CHARINDEX('&gt;', @HTMLText)
SET @End = @Start + 3
SET @Length = (@End - @Start) + 1
END

-- Replace the HTML entity &amp; with the '&' character
SET @Start = CHARINDEX('&amp;amp;', @HTMLText)
SET @End = @Start + 4
SET @Length = (@End - @Start) + 1

WHILE (@Start > 0 AND @End > 0 AND @Length > 0) BEGIN
SET @HTMLText = STUFF(@HTMLText, @Start, @Length, '&')
SET @Start = CHARINDEX('&amp;amp;', @HTMLText)
SET @End = @Start + 4
SET @Length = (@End - @Start) + 1
END

-- Replace the HTML entity &nbsp; with the ' ' character
SET @Start = CHARINDEX('&nbsp;', @HTMLText)
SET @End = @Start + 5
SET @Length = (@End - @Start) + 1

WHILE (@Start > 0 AND @End > 0 AND @Length > 0) BEGIN
SET @HTMLText = STUFF(@HTMLText, @Start, @Length, ' ')
SET @Start = CHARINDEX('&nbsp;', @HTMLText)
SET @End = @Start + 5
SET @Length = (@End - @Start) + 1
END

-- Replace any <br> tags with a newline
SET @Start = CHARINDEX('<br>', @HTMLText)
SET @End = @Start + 3
SET @Length = (@End - @Start) + 1

WHILE (@Start > 0 AND @End > 0 AND @Length > 0) BEGIN
SET @HTMLText = STUFF(@HTMLText, @Start, @Length, CHAR(13) + CHAR(10))
SET @Start = CHARINDEX('<br>', @HTMLText)
SET @End = @Start + 3
SET @Length = (@End - @Start) + 1
END

-- Replace any <br/> tags with a newline
SET @Start = CHARINDEX('<br/>', @HTMLText)
SET @End = @Start + 4
SET @Length = (@End - @Start) + 1

WHILE (@Start > 0 AND @End > 0 AND @Length > 0) BEGIN
SET @HTMLText = STUFF(@HTMLText, @Start, @Length, CHAR(13) + CHAR(10))
SET @Start = CHARINDEX('<br/>', @HTMLText)
SET @End = @Start + 4
SET @Length = (@End - @Start) + 1
END

-- Replace any <br /> tags with a newline
SET @Start = CHARINDEX('<br />', @HTMLText)
SET @End = @Start + 5
SET @Length = (@End - @Start) + 1

WHILE (@Start > 0 AND @End > 0 AND @Length > 0) BEGIN
SET @HTMLText = STUFF(@HTMLText, @Start, @Length, CHAR(13) + CHAR(10))
SET @Start = CHARINDEX('<br />', @HTMLText)
SET @End = @Start + 5
SET @Length = (@End - @Start) + 1
END

-- Remove anything between <STYLE> tags
SET @Start = CHARINDEX('<STYLE', @HTMLText)
SET @End = CHARINDEX('</STYLE>', @HTMLText, CHARINDEX('<', @HTMLText)) + 7
SET @Length = (@End - @Start) + 1

WHILE (@Start > 0 AND @End > 0 AND @Length > 0) BEGIN
SET @HTMLText = STUFF(@HTMLText, @Start, @Length, '')
SET @Start = CHARINDEX('<STYLE', @HTMLText)
SET @End = CHARINDEX('</STYLE>', @HTMLText, CHARINDEX('</STYLE>', @HTMLText)) + 7
SET @Length = (@End - @Start) + 1
END

-- Remove anything between <whatever> tags
SET @Start = CHARINDEX('<', @HTMLText)
SET @End = CHARINDEX('>', @HTMLText, CHARINDEX('<', @HTMLText))
SET @Length = (@End - @Start) + 1

WHILE (@Start > 0 AND @End > 0 AND @Length > 0) BEGIN
SET @HTMLText = STUFF(@HTMLText, @Start, @Length, '')
SET @Start = CHARINDEX('<', @HTMLText)
SET @End = CHARINDEX('>', @HTMLText, CHARINDEX('<', @HTMLText))
SET @Length = (@End - @Start) + 1
END

RETURN LTRIM(RTRIM(@HTMLText))

END

How do I do an initial push to a remote repository with Git?

On server:

mkdir my_project.git
cd my_project.git
git --bare init

On client:

mkdir my_project
cd my_project
touch .gitignore
git init
git add .
git commit -m "Initial commit"
git remote add origin [email protected]:/path/to/my_project.git
git push origin master

Note that when you add the origin, there are several formats and schemas you could use. I recommend you see what your hosting service provides.

How to add a button to UINavigationBar?

Adding custom button to navigation bar ( with image for buttonItem and specifying action method (void)openView{} and).

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0, 0, 32, 32);
[button setImage:[UIImage imageNamed:@"settings_b.png"] forState:UIControlStateNormal];
[button addTarget:self action:@selector(openView) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *barButton=[[UIBarButtonItem alloc] init];
[barButton setCustomView:button];
self.navigationItem.rightBarButtonItem=barButton;

[button release];
[barButton release];

How to cast the size_t to double or int C++

Assuming that the program cannot be redesigned to avoid the cast (ref. Keith Thomson's answer):

To cast from size_t to int you need to ensure that the size_t does not exceed the maximum value of the int. This can be done using std::numeric_limits:

int SizeTToInt(size_t data)
{
    if (data > std::numeric_limits<int>::max())
        throw std::exception("Invalid cast.");
    return std::static_cast<int>(data);
}

If you need to cast from size_t to double, and you need to ensure that you don't lose precision, I think you can use a narrow cast (ref. Stroustrup: The C++ Programming Language, Fourth Edition):

template<class Target, class Source>
Target NarrowCast(Source v)
{
    auto r = static_cast<Target>(v);
    if (static_cast<Source>(r) != v)
        throw RuntimeError("Narrow cast failed.");
    return r;
}

I tested using the narrow cast for size_t-to-double conversions by inspecting the limits of the maximum integers floating-point-representable integers (code uses googletest):

EXPECT_EQ(static_cast<size_t>(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() - 2 })), size_t{ IntegerRepresentableBoundary() - 2 });
EXPECT_EQ(static_cast<size_t>(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() - 1 })), size_t{ IntegerRepresentableBoundary() - 1 });
EXPECT_EQ(static_cast<size_t>(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() })), size_t{ IntegerRepresentableBoundary() });
EXPECT_THROW(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() + 1 }), std::exception);
EXPECT_EQ(static_cast<size_t>(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() + 2 })), size_t{ IntegerRepresentableBoundary() + 2 });
EXPECT_THROW(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() + 3 }), std::exception);
EXPECT_EQ(static_cast<size_t>(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() + 4 })), size_t{ IntegerRepresentableBoundary() + 4 });
EXPECT_THROW(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() + 5 }), std::exception);

where

constexpr size_t IntegerRepresentableBoundary()
{
    static_assert(std::numeric_limits<double>::radix == 2, "Method only valid for binary floating point format.");
    return size_t{2} << (std::numeric_limits<double>::digits - 1);
}

That is, if N is the number of digits in the mantissa, for doubles smaller than or equal to 2^N, integers can be exactly represented. For doubles between 2^N and 2^(N+1), every other integer can be exactly represented. For doubles between 2^(N+1) and 2^(N+2) every fourth integer can be exactly represented, and so on.

How to allocate aligned memory only using the standard library?

Original answer

{
    void *mem = malloc(1024+16);
    void *ptr = ((char *)mem+16) & ~ 0x0F;
    memset_16aligned(ptr, 0, 1024);
    free(mem);
}

Fixed answer

{
    void *mem = malloc(1024+15);
    void *ptr = ((uintptr_t)mem+15) & ~ (uintptr_t)0x0F;
    memset_16aligned(ptr, 0, 1024);
    free(mem);
}

Explanation as requested

The first step is to allocate enough spare space, just in case. Since the memory must be 16-byte aligned (meaning that the leading byte address needs to be a multiple of 16), adding 16 extra bytes guarantees that we have enough space. Somewhere in the first 16 bytes, there is a 16-byte aligned pointer. (Note that malloc() is supposed to return a pointer that is sufficiently well aligned for any purpose. However, the meaning of 'any' is primarily for things like basic types — long, double, long double, long long, and pointers to objects and pointers to functions. When you are doing more specialized things, like playing with graphics systems, they can need more stringent alignment than the rest of the system — hence questions and answers like this.)

The next step is to convert the void pointer to a char pointer; GCC notwithstanding, you are not supposed to do pointer arithmetic on void pointers (and GCC has warning options to tell you when you abuse it). Then add 16 to the start pointer. Suppose malloc() returned you an impossibly badly aligned pointer: 0x800001. Adding the 16 gives 0x800011. Now I want to round down to the 16-byte boundary — so I want to reset the last 4 bits to 0. 0x0F has the last 4 bits set to one; therefore, ~0x0F has all bits set to one except the last four. Anding that with 0x800011 gives 0x800010. You can iterate over the other offsets and see that the same arithmetic works.

The last step, free(), is easy: you always, and only, return to free() a value that one of malloc(), calloc() or realloc() returned to you — anything else is a disaster. You correctly provided mem to hold that value — thank you. The free releases it.

Finally, if you know about the internals of your system's malloc package, you could guess that it might well return 16-byte aligned data (or it might be 8-byte aligned). If it was 16-byte aligned, then you'd not need to dink with the values. However, this is dodgy and non-portable — other malloc packages have different minimum alignments, and therefore assuming one thing when it does something different would lead to core dumps. Within broad limits, this solution is portable.

Someone else mentioned posix_memalign() as another way to get the aligned memory; that isn't available everywhere, but could often be implemented using this as a basis. Note that it was convenient that the alignment was a power of 2; other alignments are messier.

One more comment — this code does not check that the allocation succeeded.

Amendment

Windows Programmer pointed out that you can't do bit mask operations on pointers, and, indeed, GCC (3.4.6 and 4.3.1 tested) does complain like that. So, an amended version of the basic code — converted into a main program, follows. I've also taken the liberty of adding just 15 instead of 16, as has been pointed out. I'm using uintptr_t since C99 has been around long enough to be accessible on most platforms. If it wasn't for the use of PRIXPTR in the printf() statements, it would be sufficient to #include <stdint.h> instead of using #include <inttypes.h>. [This code includes the fix pointed out by C.R., which was reiterating a point first made by Bill K a number of years ago, which I managed to overlook until now.]

#include <assert.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static void memset_16aligned(void *space, char byte, size_t nbytes)
{
    assert((nbytes & 0x0F) == 0);
    assert(((uintptr_t)space & 0x0F) == 0);
    memset(space, byte, nbytes);  // Not a custom implementation of memset()
}

int main(void)
{
    void *mem = malloc(1024+15);
    void *ptr = (void *)(((uintptr_t)mem+15) & ~ (uintptr_t)0x0F);
    printf("0x%08" PRIXPTR ", 0x%08" PRIXPTR "\n", (uintptr_t)mem, (uintptr_t)ptr);
    memset_16aligned(ptr, 0, 1024);
    free(mem);
    return(0);
}

And here is a marginally more generalized version, which will work for sizes which are a power of 2:

#include <assert.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static void memset_16aligned(void *space, char byte, size_t nbytes)
{
    assert((nbytes & 0x0F) == 0);
    assert(((uintptr_t)space & 0x0F) == 0);
    memset(space, byte, nbytes);  // Not a custom implementation of memset()
}

static void test_mask(size_t align)
{
    uintptr_t mask = ~(uintptr_t)(align - 1);
    void *mem = malloc(1024+align-1);
    void *ptr = (void *)(((uintptr_t)mem+align-1) & mask);
    assert((align & (align - 1)) == 0);
    printf("0x%08" PRIXPTR ", 0x%08" PRIXPTR "\n", (uintptr_t)mem, (uintptr_t)ptr);
    memset_16aligned(ptr, 0, 1024);
    free(mem);
}

int main(void)
{
    test_mask(16);
    test_mask(32);
    test_mask(64);
    test_mask(128);
    return(0);
}

To convert test_mask() into a general purpose allocation function, the single return value from the allocator would have to encode the release address, as several people have indicated in their answers.

Problems with interviewers

Uri commented: Maybe I am having [a] reading comprehension problem this morning, but if the interview question specifically says: "How would you allocate 1024 bytes of memory" and you clearly allocate more than that. Wouldn't that be an automatic failure from the interviewer?

My response won't fit into a 300-character comment...

It depends, I suppose. I think most people (including me) took the question to mean "How would you allocate a space in which 1024 bytes of data can be stored, and where the base address is a multiple of 16 bytes". If the interviewer really meant how can you allocate 1024 bytes (only) and have it 16-byte aligned, then the options are more limited.

  • Clearly, one possibility is to allocate 1024 bytes and then give that address the 'alignment treatment'; the problem with that approach is that the actual available space is not properly determinate (the usable space is between 1008 and 1024 bytes, but there wasn't a mechanism available to specify which size), which renders it less than useful.
  • Another possibility is that you are expected to write a full memory allocator and ensure that the 1024-byte block you return is appropriately aligned. If that is the case, you probably end up doing an operation fairly similar to what the proposed solution did, but you hide it inside the allocator.

However, if the interviewer expected either of those responses, I'd expect them to recognize that this solution answers a closely related question, and then to reframe their question to point the conversation in the correct direction. (Further, if the interviewer got really stroppy, then I wouldn't want the job; if the answer to an insufficiently precise requirement is shot down in flames without correction, then the interviewer is not someone for whom it is safe to work.)

The world moves on

The title of the question has changed recently. It was Solve the memory alignment in C interview question that stumped me. The revised title (How to allocate aligned memory only using the standard library?) demands a slightly revised answer — this addendum provides it.

C11 (ISO/IEC 9899:2011) added function aligned_alloc():

7.22.3.1 The aligned_alloc function

Synopsis

#include <stdlib.h>
void *aligned_alloc(size_t alignment, size_t size);

Description
The aligned_alloc function allocates space for an object whose alignment is specified by alignment, whose size is specified by size, and whose value is indeterminate. The value of alignment shall be a valid alignment supported by the implementation and the value of size shall be an integral multiple of alignment.

Returns
The aligned_alloc function returns either a null pointer or a pointer to the allocated space.

And POSIX defines posix_memalign():

#include <stdlib.h>

int posix_memalign(void **memptr, size_t alignment, size_t size);

DESCRIPTION

The posix_memalign() function shall allocate size bytes aligned on a boundary specified by alignment, and shall return a pointer to the allocated memory in memptr. The value of alignment shall be a power of two multiple of sizeof(void *).

Upon successful completion, the value pointed to by memptr shall be a multiple of alignment.

If the size of the space requested is 0, the behavior is implementation-defined; the value returned in memptr shall be either a null pointer or a unique pointer.

The free() function shall deallocate memory that has previously been allocated by posix_memalign().

RETURN VALUE

Upon successful completion, posix_memalign() shall return zero; otherwise, an error number shall be returned to indicate the error.

Either or both of these could be used to answer the question now, but only the POSIX function was an option when the question was originally answered.

Behind the scenes, the new aligned memory function do much the same job as outlined in the question, except they have the ability to force the alignment more easily, and keep track of the start of the aligned memory internally so that the code doesn't have to deal with specially — it just frees the memory returned by the allocation function that was used.

How do you Encrypt and Decrypt a PHP String?

These are compact methods to encrypt / decrypt strings with PHP using AES256 CBC:

function encryptString($plaintext, $password, $encoding = null) {
    $iv = openssl_random_pseudo_bytes(16);
    $ciphertext = openssl_encrypt($plaintext, "AES-256-CBC", hash('sha256', $password, true), OPENSSL_RAW_DATA, $iv);
    $hmac = hash_hmac('sha256', $ciphertext.$iv, hash('sha256', $password, true), true);
    return $encoding == "hex" ? bin2hex($iv.$hmac.$ciphertext) : ($encoding == "base64" ? base64_encode($iv.$hmac.$ciphertext) : $iv.$hmac.$ciphertext);
}

function decryptString($ciphertext, $password, $encoding = null) {
    $ciphertext = $encoding == "hex" ? hex2bin($ciphertext) : ($encoding == "base64" ? base64_decode($ciphertext) : $ciphertext);
    if (!hash_equals(hash_hmac('sha256', substr($ciphertext, 48).substr($ciphertext, 0, 16), hash('sha256', $password, true), true), substr($ciphertext, 16, 32))) return null;
    return openssl_decrypt(substr($ciphertext, 48), "AES-256-CBC", hash('sha256', $password, true), OPENSSL_RAW_DATA, substr($ciphertext, 0, 16));
}

Usage:

$enc = encryptString("mysecretText", "myPassword");
$dec = decryptString($enc, "myPassword");

How to convert all text to lowercase in Vim

If you are running under a flavor of Unix

:0,$!tr "[A-Z]" "[a-z]"

Assigning default value while creating migration file

You would have to first create your migration for the model basics then you create another migration to modify your previous using the change_column ...

def change
    change_column :widgets, :colour, :string, default: 'red'
end

Is it valid to have a html form inside another html form?

A possibility is to have an iframe inside the outer form. The iframe contains the inner form. Make sure to use the <base target="_parent" /> tag inside the head tag of the iframe to make the form behave as part of the main page.

Hashmap does not work with int, char

Generic parameters can only bind to reference types, not primitive types, so you need to use the corresponding wrapper types. Try HashMap<Character, Integer> instead.

However, I'm having trouble figuring out why HashMap fails to be able to deal with primitive data types.

This is due to type erasure. Java didn't have generics from the beginning so a HashMap<Character, Integer> is really a HashMap<Object, Object>. The compiler does a bunch of additional checks and implicit casts to make sure you don't put the wrong type of value in or get the wrong type out, but at runtime there is only one HashMap class and it stores objects.

Other languages "specialize" types so in C++, a vector<bool> is very different from a vector<my_class> internally and they share no common vector<?> super-type. Java defines things though so that a List<T> is a List regardless of what T is for backwards compatibility with pre-generic code. This backwards-compatibility requirement that there has to be a single implementation class for all parameterizations of a generic type prevents the kind of template specialization which would allow generic parameters to bind to primitives.

How to check syslog in Bash on Linux?

If you like Vim, it has built-in syntax highlighting for the syslog file, e.g. it will highlight error messages in red.

vi +'syntax on' /var/log/syslog

REST API Best practice: How to accept list of parameter values as input

First:

I think you can do it 2 ways

http://our.api.com/Product/<id> : if you just want one record

http://our.api.com/Product : if you want all records

http://our.api.com/Product/<id1>,<id2> :as James suggested can be an option since what comes after the Product tag is a parameter

Or the one I like most is:

You can use the the Hypermedia as the engine of application state (HATEOAS) property of a RestFul WS and do a call http://our.api.com/Product that should return the equivalent urls of http://our.api.com/Product/<id> and call them after this.

Second

When you have to do queries on the url calls. I would suggest using HATEOAS again.

1) Do a get call to http://our.api.com/term/pumas/productType/clothing/color/black

2) Do a get call to http://our.api.com/term/pumas/productType/clothing,bags/color/black,red

3) (Using HATEOAS) Do a get call to `http://our.api.com/term/pumas/productType/ -> receive the urls all clothing possible urls -> call the ones you want (clothing and bags) -> receive the possible color urls -> call the ones you want

How do I calculate someone's age in Java?

public int getAge(Date dateOfBirth) 
{
    Calendar now = Calendar.getInstance();
    Calendar dob = Calendar.getInstance();

    dob.setTime(dateOfBirth);

    if (dob.after(now)) 
    {
        throw new IllegalArgumentException("Can't be born in the future");
    }

    int age = now.get(Calendar.YEAR) - dob.get(Calendar.YEAR);

    if (now.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR)) 
    {
        age--;
    }

    return age;
}

Multiple Where clauses in Lambda expressions

Maybe

x=> x.Lists.Include(l => l.Title)
    .Where(l => l.Title != string.Empty)
    .Where(l => l.InternalName != string.Empty)

?

You can probably also put it in the same where clause:

x=> x.Lists.Include(l => l.Title)
    .Where(l => l.Title != string.Empty && l.InternalName != string.Empty)

More Pythonic Way to Run a Process X Times

Personally:

for _ in range(50):
    print "Some thing"

if you don't need i. If you use Python < 3 and you want to repeat the loop a lot of times, use xrange as there is no need to generate the whole list beforehand.

How do I delete multiple rows with different IDs?

  • You can make this.

    CREATE PROC [dbo].[sp_DELETE_MULTI_ROW]
    @CODE XML ,@ERRFLAG CHAR(1) = '0' OUTPUT

AS

SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

DELETE tb_SampleTest WHERE CODE IN( SELECT Item.value('.', 'VARCHAR(20)') FROM @CODE.nodes('RecordList/ID') AS x(Item) )

IF @@ROWCOUNT = 0 SET @ERRFLAG = 200

SET NOCOUNT OFF

  • <'RecordList'><'ID'>1<'/ID'><'ID'>2<'/ID'><'/RecordList'>

Tomcat is web server or application server?

It runs Java compiled code, it can maintain database connection pools, it can log errors of various types. I'd call it an application server, in fact I do. In our environment we have Apache as the webserver fronting a number of different application servers, including Tomcat and Coldfusion, and others.

Something like 'contains any' for Java set?

You can use retainAll method and get the intersection of your two sets.

Creating a list of objects in Python

Create a new instance each time, where each new instance has the correct state, rather than continually modifying the state of the same instance.

Alternately, store an explicitly-made copy of the object (using the hint at this page) at each step, rather than the original.

A potentially dangerous Request.Form value was detected from the client

As long as these are only "<" and ">" (and not the double quote itself) characters and you're using them in context like <input value="this" />, you're safe (while for <textarea>this one</textarea> you would be vulnerable of course). That may simplify your situation, but for anything more use one of other posted solutions.

Django - Static file not found

There could be only two things in settings.py which causes problems for you.

1) STATIC_URL = '/static/'

2)

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)

and your static files should lie under static directory which is in same directory as project's settings file.

Even then if your static files are not loading then reason is , you might have kept

DEBUG = False

change it to True (strictly for development only). In production just change STATICFILES_DIRS to whatever path where static files resides.

PHP passing $_GET in linux command prompt

I just pass them like this:

php5 script.php param1=blabla param2=yadayada

works just fine, the $_GET array is:

array(3) {
  ["script_php"]=>
  string(0) ""
  ["param1"]=>
  string(6) "blabla"
  ["param2"]=>
  string(8) "yadayada"
}

How to Parse a JSON Object In Android

In the end I solved it by using JSONObject.get rather than JSONObject.getString and then cast test to a String.

private void saveData(String result) {
    try {
        JSONObject json= (JSONObject) new JSONTokener(result).nextValue();
        JSONObject json2 = json.getJSONObject("results");
        test = (String) json2.get("name");
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

Resource interpreted as stylesheet but transferred with MIME type text/html (seems not related with web server)

i was facing the same thing, with sort of the same .htaccess file for making pretty urls. after some hours of looking around and experimenting. i found out that the error was because of relatively linking files.

the browser will start fetching the same source html file for all the css, js and image files, when i would browse a few steps deep into the server.

to counter this you can either use the <base> tag on your html source,

<base href="http://localhost/assets/">

and link to files like,

<link rel="stylesheet" type="text/css" href="css/style.css" />
<script src="js/script.js"></script>

or use absolute links for all your files.

<link rel="stylesheet" type="text/css" href="http://localhost/assets/css/style.css" />
<script src="http://localhost/assets/js/script.js"></script>
<img src="http://localhost/assets/images/logo.png" />

How can I change Eclipse theme?

In the eclipse Version: 2019-09 R (4.13.0) on windows Go to Window > preferences > Appearance Select the required theme for dark theme to choose Dark and click on Ok. enter image description here

composer laravel create project

Dont write with stability stable in the command ,
in your composer.json file, put
"minimum-stability": "stable" before the closing curly bracket.

Warning: mysql_connect(): Access denied for user 'root'@'localhost' (using password: YES)

try $conn = mysql_connect("localhost", "root") or $conn = mysql_connect("localhost", "root", "")

REST / SOAP endpoints for a WCF service

This is what i did to make it work. Make sure you put
webHttp automaticFormatSelectionEnabled="true" inside endpoint behaviour.

[ServiceContract]
public interface ITestService
{

    [WebGet(BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/product", ResponseFormat = WebMessageFormat.Json)]
    string GetData();
}

public class TestService : ITestService
{
    public string GetJsonData()
    {
        return "I am good...";
    }
}

Inside service model

   <service name="TechCity.Business.TestService">

    <endpoint address="soap" binding="basicHttpBinding" name="SoapTest"
      bindingName="BasicSoap" contract="TechCity.Interfaces.ITestService" />
    <endpoint address="mex"
              contract="IMetadataExchange" binding="mexHttpBinding"/>
    <endpoint behaviorConfiguration="jsonBehavior" binding="webHttpBinding"
              name="Http" contract="TechCity.Interfaces.ITestService" />
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost:8739/test" />
      </baseAddresses>
    </host>
  </service>

EndPoint Behaviour

  <endpointBehaviors>
    <behavior name="jsonBehavior">
      <webHttp automaticFormatSelectionEnabled="true"  />
      <!-- use JSON serialization -->
    </behavior>
  </endpointBehaviors>

Using NotNull Annotation in method argument

If you are using Spring, you can force validation by annotating the class with @Validated:

import org.springframework.validation.annotation.Validated;

More info available here: Javax validation @NotNull annotation usage

SQL Server 2005 Using CHARINDEX() To split a string

Create FUNCTION [dbo].[fnSplitString] 
( 
    @string NVARCHAR(200), 
    @delimiter CHAR(1) 
) 
RETURNS @output TABLE(splitdata NVARCHAR(10) 
) 
BEGIN 
    DECLARE @start INT, @end INT 
    SELECT @start = 1, @end = CHARINDEX(@delimiter, @string) 
    WHILE @start < LEN(@string) + 1 BEGIN 
        IF @end = 0  
            SET @end = LEN(@string) + 1

        INSERT INTO @output (splitdata)  
        VALUES(SUBSTRING(@string, @start, @end - @start)) 
        SET @start = @end + 1 
        SET @end = CHARINDEX(@delimiter, @string, @start)

    END 
    RETURN 

END**strong text**

Postgresql GROUP_CONCAT equivalent?

Since 9.0 this is even easier:

SELECT id, 
       string_agg(some_column, ',')
FROM the_table
GROUP BY id

How to enable CORS in ASP.NET Core

All the workaround mentioned above may work or may not work, in most cases it will not work. I have given the solution here

Currently I am working on Angular and Web API(.net Core) and came across CORS issue explained below

The solution provided above will always work. With 'OPTIONS' request it is really necessary to enable 'Anonymous Authentication'. With the solution mentioned here you don't have to do all the steps mentioned above, like IIS settings.

Anyways someone marked my above post as duplicate with this post, but I can see that this post is only to enable CORS in ASP.net Core, but my post is related to, Enabling and implementing CORS in ASP.net Core and Angular.

Which Radio button in the group is checked?

If you want to get the index of the selected radio button inside a control you can use this method:

public static int getCheckedRadioButton(Control c)
{
    int i;
    try
    {
        Control.ControlCollection cc = c.Controls;
        for (i = 0; i < cc.Count; i++)
        {
            RadioButton rb = cc[i] as RadioButton;
            if (rb.Checked)
            {
                return i;
            }
        }
    }
    catch
    {
        i = -1;
    }
    return i;
}

Example use:

int index = getCheckedRadioButton(panel1);

The code isn't that well tested, but it seems the index order is from left to right and from top to bottom, as when reading a text. If no radio button is found, the method returns -1.

Update: It turned out my first attempt didn't work if there's no radio button inside the control. I added a try and catch block to fix that, and the method now seems to work.

Dynamically replace img src attribute with jQuery

In my case, I replaced the src taq using:

_x000D_
_x000D_
   $('#gmap_canvas').attr('src', newSrc);
_x000D_
_x000D_
_x000D_

How to get error information when HttpWebRequest.GetResponse() fails

I came across this question when trying to check if a file existed on an FTP site or not. If the file doesn't exist there will be an error when trying to check its timestamp. But I want to make sure the error is not something else, by checking its type.

The Response property on WebException will be of type FtpWebResponse on which you can check its StatusCode property to see which FTP error you have.

Here's the code I ended up with:

    public static bool FileExists(string host, string username, string password, string filename)
    {
        // create FTP request
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + host + "/" + filename);
        request.Credentials = new NetworkCredential(username, password);

        // we want to get date stamp - to see if the file exists
        request.Method = WebRequestMethods.Ftp.GetDateTimestamp;

        try
        {
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            var lastModified = response.LastModified;

            // if we get the last modified date then the file exists
            return true;
        }
        catch (WebException ex)
        {
            var ftpResponse = (FtpWebResponse)ex.Response;

            // if the status code is 'file unavailable' then the file doesn't exist
            // may be different depending upon FTP server software
            if (ftpResponse.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
            {
                return false;
            }

            // some other error - like maybe internet is down
            throw;
        }
    }

How to get HttpClient returning status code and response body?

Don't provide the handler to execute.

Get the HttpResponse object, use the handler to get the body and get the status code from it directly

try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
    final HttpGet httpGet = new HttpGet(GET_URL);

    try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
        StatusLine statusLine = response.getStatusLine();
        System.out.println(statusLine.getStatusCode() + " " + statusLine.getReasonPhrase());
        String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
        System.out.println("Response body: " + responseBody);
    }
}

For quick single calls, the fluent API is useful:

Response response = Request.Get(uri)
        .connectTimeout(MILLIS_ONE_SECOND)
        .socketTimeout(MILLIS_ONE_SECOND)
        .execute();
HttpResponse httpResponse = response.returnResponse();
StatusLine statusLine = httpResponse.getStatusLine();

For older versions of java or httpcomponents, the code might look different.

Is Google Play Store supported in avd emulators?

When you create a virtual device from Android Studio pay attention to the Play Store Column in the device table. The images with the play store icon have google play pre-installed.

?? In system images that come with google play root is not available.

android studio images with playstore

After you've created the AVD you'll also be able to see from the Android Studio AVD Manager which of your images have google play installed:

enter image description here

Centering the pagination in bootstrap

In v4.0.0-alpha.6:

<div class="text-center text-sm-right">
    <ul class="pagination d-inline-flex">...</ul>
</div>

When to use React setState callback

The 1. usecase which comes into my mind, is an api call, which should't go into the render, because it will run for each state change. And the API call should be only performed on special state change, and not on every render.

changeSearchParams = (params) => {
  this.setState({ params }, this.performSearch)
} 

performSearch = () => {
  API.search(this.state.params, (result) => {
    this.setState({ result })
  });
}

Hence for any state change, an action can be performed in the render methods body.

Very bad practice, because the render-method should be pure, it means no actions, state changes, api calls, should be performed, just composite your view and return it. Actions should be performed on some events only. Render is not an event, but componentDidMount for example.

Is there a JSON equivalent of XQuery/XPath?

XQuery can be used to query JSON, provided that the processor offers JSON support. This is a straightforward example how BaseX can be used to find objects with "id" = 1:

json:parse('[
    { "id": 1, "name": "One", "objects": [
        { "id": 1, "name": "Response 1", "objects": [ "etc." ] }
    ]}
]')//value[.//id = 1]

assembly to compare two numbers

This depends entirely on the processor you're talking about but it tends to be of the form:

cmp r1, r2
ble label7

In other words, a compare instruction to set the relevant flags, followed by a conditional branch depending on those flags.

This is generally as low as you need to get for programming. You only need to know the machine language for it if you're writing assemblers and you only need to know the microcode and/or circuit designs if you're building processors.

Firebase cloud messaging notification not received by device

You have placed your service outside the application tag. Change bottom to this.

<service
    android:name=".NotificationGenie">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
</service>

</application>

What is the use of the @Temporal annotation in Hibernate?

We use @Temporal annotation to insert date, time or both in database table.Using TemporalType we can insert data, time or both int table.

@Temporal(TemporalType.DATE) // insert date
@Temporal(TemporalType.TIME) // insert time
@Temporal(TemporalType.TIMESTAMP) // insert  both time and date.

How can I use async/await at the top level?

You can now use top level await in Node v13.3.0

import axios from "axios";

const { data } = await axios.get("https://api.namefake.com/");
console.log(data);

run it with --harmony-top-level-await flag

node --harmony-top-level-await index.js

How to add an image to the emulator gallery in android studio?

Copy a file to the emulator:

Open emulator and File Explorer (Finder in Mac) side by side. Choose the file you want to copy then Drag and Drop the file onto the emulator. The selected file will be copied to the Downloads folder of the emulator.

How to view files in Android Studio:

Android Studio has Device Explorer to explore emulator content (Earlier we used to have DDMS, which is deprecated in Studio 3+). Goto View -> Tools Window -> Device File Explorer and you can see the explorer window. Goto Storage -> emulated -> 0 ->Download, if you don't see the file here, please restart the emulator and that's it.

Note: You don't see Device Explorer if you have opened a Flutter project.

You can also view the image files in Android Studio by double-clicking the file in the emulator.

See image below

Get first and last day of month using threeten, LocalDate

The API was designed to support a solution that matches closely to business requirements

import static java.time.temporal.TemporalAdjusters.*;

LocalDate initial = LocalDate.of(2014, 2, 13);
LocalDate start = initial.with(firstDayOfMonth());
LocalDate end = initial.with(lastDayOfMonth());

However, Jon's solutions are also fine.

format a number with commas and decimals in C# (asp.net MVC3)

Try with

ToString("#,##0.###")

Produces:

1234.55678 => 1,234.556

1234 => 1,234

Failed to decode downloaded font, OTS parsing error: invalid version tag + rails 4

For it is fixed by using below statement in app.web.scss
    $fa-font-path:   "../../node_modules/font-awesome/fonts/" !default;
    @import "../../node_modules/font-awesome/scss/font-awesome";