Programs & Examples On #Yield keyword

The yield keyword is used to pause and resume a generator.

What does yield mean in PHP?

simple example

<?php
echo '#start main# ';
function a(){
    echo '{start[';
    for($i=1; $i<=9; $i++)
        yield $i;
    echo ']end} ';
}
foreach(a() as $v)
    echo $v.',';
echo '#end main#';
?>

output

#start main# {start[1,2,3,4,5,6,7,8,9,]end} #end main#

advanced example

<?php
echo '#start main# ';
function a(){
    echo '{start[';
    for($i=1; $i<=9; $i++)
        yield $i;
    echo ']end} ';
}
foreach(a() as $k => $v){
    if($k === 5)
        break;
    echo $k.'=>'.$v.',';
}
echo '#end main#';
?>

output

#start main# {start[0=>1,1=>2,2=>3,3=>4,4=>5,#end main#

How to wait 5 seconds with jQuery?

setTimeout(function(){


},5000); 

Place your code inside of the { }

300 = 0.3 seconds

700 = 0.7 seconds

1000 = 1 second

2000= 2 seconds

2200 = 2.2 seconds

3500 = 3.5 seconds

10000 = 10 seconds

etc.

TypeError: 'str' object is not callable (Python)

Whenever that happens, just issue the following ( it was also posted above)

>>> del str

That should fix it.

Cannot import the keyfile 'blah.pfx' - error 'The keyfile may be password protected'

I spoke too soon! Rebuild brought the errors back into play...

I found this works - right click in Solution Explorer and exclude it from the project. Click Show all files, right click and now include it in the project again. Now undo pending changes...

For some reason this sorted it out for me and was relatively painless!

Pythonic way to combine FOR loop and IF statement

The following is a simplification/one liner from the accepted answer:

a = [2,3,4,5,6,7,8,9,0]
xyz = [0,12,4,6,242,7,9]

for x in (x for x in xyz if x not in a):
    print(x)

12
242

Notice that the generator was kept inline. This was tested on python2.7 and python3.6 (notice the parens in the print ;) )

Amazon S3 and Cloudfront cache, how to clear cache or synchronize their cache

Cloudfront will cache a file/object until the cache expiry. By default it is 24 hrs. If you have changed this to a large value, then it takes longer.

If you anytime needs to force clear the cache, use the invalidation. It is charged separately.

Another option is to change the URL (object key), so it fetches the new object always.

java.util.MissingResourceException: Can't find bundle for base name 'property_file name', locale en_US

I'd like to share my experience of using Ant in building projects, *.properties files should be copied explicitly. This is because Ant will not compile *.properties files into the build working directory by default (javac just ignore *.properties). For example:

<target name="compile" depends="init">
    <javac destdir="${dst}" srcdir="${src}" debug="on" encoding="utf-8" includeantruntime="false">
        <include name="com/example/**" />
        <classpath refid="libs" />
    </javac>
    <copy todir="${dst}">
        <fileset dir="${src}" includes="**/*.properties" />
    </copy>
</target>

<target name="jars" depends="compile">
    <jar jarfile="${app_jar}" basedir="${dst}" includes="com/example/**/*.*" />
</target>

Please notice that 'copy' section under the 'compile' target, it will replicate *.properties files into the build working directory. Without the 'copy' section the jar file will not contain the properties files, then you may encounter the java.util.MissingResourceException.

Get the second largest number in a list in linear time

The quickselect algorithm, O(n) cousin to quicksort, will do what you want. Quickselect has average performance O(n). Worst case performance is O(n^2) just like quicksort but that's rare, and modifications to quickselect reduce the worst case performance to O(n).

The idea of quickselect is to use the same pivot, lower, higher idea of quicksort, but to then ignore the lower part and to further order just the higher part.

How do I mock an autowired @Value field in Spring with Mockito?

I used the below code and it worked for me:

@InjectMocks
private ClassABC classABC;

@Before
public void setUp() {
    ReflectionTestUtils.setField(classABC, "constantFromConfigFile", 3);
}

Reference: https://www.jeejava.com/mock-an-autowired-value-field-in-spring-with-junit-mockito/

Get Substring between two characters using javascript

I used @tsds way but by only using the split function.

var str = 'one:two;three';    
str.split(':')[1].split(';')[0] // returns 'two'

word of caution: if therre is no ":" in the string accessing '1' index of the array will throw an error! str.split(':')[1]

therefore @tsds way is safer if there is uncertainty

str.split(':').pop().split(';')[0]

How to get names of enum entries?

Based on some answers above I came up with this type-safe function signature:

export function getStringValuesFromEnum<T>(myEnum: T): (keyof T)[] {
  return Object.keys(myEnum).filter(k => typeof (myEnum as any)[k] === 'number') as any;
}

Usage:

enum myEnum { entry1, entry2 };
const stringVals = getStringValuesFromEnum(myEnum);

the type of stringVals is 'entry1' | 'entry2'

See it in action

How to show MessageBox on asp.net?

It's true that Messagebox.show("dd"); is not a part of using System.Web;,

I felt the same situation for most of time. If you want to do this then do the following steps.

  • Right click on project in solution explorer
  • go for add reference, then choose .NET tab

  • And select, System.windows.forms (press 's' to find quickly)

u can get the namespace, now u can use Messagebox.show("dd");

But I recommend to go with javascript alert for this.

How to exit in Node.js

From the official nodejs.org documentation:

process.exit(code)

Ends the process with the specified code. If omitted, exit uses the 'success' code 0.

To exit with a 'failure' code:

process.exit(1);

How to get input text value on click in ReactJS

First of all, you can't pass to alert second argument, use concatenation instead

alert("Input is " + inputValue);

Example

However in order to get values from input better to use states like this

_x000D_
_x000D_
var MyComponent = React.createClass({_x000D_
  getInitialState: function () {_x000D_
    return { input: '' };_x000D_
  },_x000D_
_x000D_
  handleChange: function(e) {_x000D_
    this.setState({ input: e.target.value });_x000D_
  },_x000D_
_x000D_
  handleClick: function() {_x000D_
    console.log(this.state.input);_x000D_
  },_x000D_
_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <input type="text" onChange={ this.handleChange } />_x000D_
        <input_x000D_
          type="button"_x000D_
          value="Alert the text input"_x000D_
          onClick={this.handleClick}_x000D_
        />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
ReactDOM.render(_x000D_
  <MyComponent />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

How to convert time milliseconds to hours, min, sec format in JavaScript?

I had the same problem, this is what I ended up doing:

_x000D_
_x000D_
function parseMillisecondsIntoReadableTime(milliseconds){_x000D_
  //Get hours from milliseconds_x000D_
  var hours = milliseconds / (1000*60*60);_x000D_
  var absoluteHours = Math.floor(hours);_x000D_
  var h = absoluteHours > 9 ? absoluteHours : '0' + absoluteHours;_x000D_
_x000D_
  //Get remainder from hours and convert to minutes_x000D_
  var minutes = (hours - absoluteHours) * 60;_x000D_
  var absoluteMinutes = Math.floor(minutes);_x000D_
  var m = absoluteMinutes > 9 ? absoluteMinutes : '0' +  absoluteMinutes;_x000D_
_x000D_
  //Get remainder from minutes and convert to seconds_x000D_
  var seconds = (minutes - absoluteMinutes) * 60;_x000D_
  var absoluteSeconds = Math.floor(seconds);_x000D_
  var s = absoluteSeconds > 9 ? absoluteSeconds : '0' + absoluteSeconds;_x000D_
_x000D_
_x000D_
  return h + ':' + m + ':' + s;_x000D_
}_x000D_
_x000D_
_x000D_
var time = parseMillisecondsIntoReadableTime(86400000);_x000D_
_x000D_
alert(time);
_x000D_
_x000D_
_x000D_

How to recover Git objects damaged by hard disk failure?

Banengusk was putting me on the right track. For further reference, I want to post the steps I took to fix my repository corruption. I was lucky enough to find all needed objects either in older packs or in repository backups.

# Unpack last non-corrupted pack
$ mv .git/objects/pack .git/objects/pack.old
$ git unpack-objects -r < .git/objects/pack.old/pack-012066c998b2d171913aeb5bf0719fd4655fa7d0.pack
$ git log
fatal: bad object HEAD

$ cat .git/HEAD 
ref: refs/heads/master

$ ls .git/refs/heads/

$ cat .git/packed-refs 
# pack-refs with: peeled 
aa268a069add6d71e162c4e2455c1b690079c8c1 refs/heads/master

$ git fsck --full 
error: HEAD: invalid sha1 pointer aa268a069add6d71e162c4e2455c1b690079c8c1
error: refs/heads/master does not point to a valid object!
missing blob 75405ef0e6f66e48c1ff836786ff110efa33a919
missing blob 27c4611ffbc3c32712a395910a96052a3de67c9b
dangling tree 30473f109d87f4bcde612a2b9a204c3e322cb0dc

# Copy HEAD object from backup of repository
$ cp repobackup/.git/objects/aa/268a069add6d71e162c4e2455c1b690079c8c1 .git/objects/aa
# Now copy all missing objects from backup of repository and run "git fsck --full" afterwards
# Repeat until git fsck --full only reports dangling objects

# Now garbage collect repo
$ git gc
warning: reflog of 'HEAD' references pruned commits
warning: reflog of 'refs/heads/master' references pruned commits
Counting objects: 3992, done.
Delta compression using 2 threads.
fatal: object bf1c4953c0ea4a045bf0975a916b53d247e7ca94 inconsistent object length (6093 vs 415232)
error: failed to run repack

# Check reflogs...
$ git reflog

# ...then clean
$ git reflog expire --expire=0 --all

# Now garbage collect again
$ git gc       
Counting objects: 3992, done.
Delta compression using 2 threads.
Compressing objects: 100% (3970/3970), done.
Writing objects: 100% (3992/3992), done.
Total 3992 (delta 2060), reused 0 (delta 0)
Removing duplicate objects: 100% (256/256), done.
# Done!

What is the difference between Set and List?

List :

  1. List is ordered grouping elements
  2. List provides positional access in the elements of the collections.
  3. We can store duplicate elements in the list.
  4. List implements ArrayList, LinkedList, Vector and Stack.
  5. List can store multiple null elements.

Set :

  1. Unorderd grouping elements.
  2. Set doesn’t provides positional access in the elements of the collections.
  3. We can’t store duplicate elements in the set.
  4. Set implement HashSet and LinkedHashSet interfaces.
  5. Set can store only one null elements.

Clearfix with twitter bootstrap

clearfix should contain the floating elements but in your html you have added clearfix only after floating right that is your pull-right so you should do like this:

<div class="clearfix">
  <div id="sidebar">
    <ul>
      <li>A</li>
      <li>A</li>
      <li>C</li>
      <li>D</li>
      <li>E</li>
      <li>F</li>
      <li>...</li>
      <li>Z</li>
    </ul>
  </div>
  <div id="main">
    <div>
      <div class="pull-right">
        <a>RIGHT</a>
      </div>
    </div>
  <div>MOVED BELOW Z</div>
</div>

see this demo


Happy to know you solved the problem by setting overflow properties. However this is also good idea to clear the float. Where you have floated your elements you could add overflow: hidden; as you have done in your main.

How to resolve 'unrecognized selector sent to instance'?

Mine was something simple/stupid. Newbie mistake, for anyone that has converted their NSManagedObject to a normal NSObject.

I had:

@dynamic order_id;

when i should have had:

@synthesize order_id;

Fling gesture detection on grid layout

I know its too late to answer but Still I am posting Swipe Detection for ListView that How to use Swipe Touch Listener in ListView Item.

Refrence: Exterminator13(one of answer in this page)

Make one ActivitySwipeDetector.class

package com.example.wocketapp;

import android.content.Context;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;

public class ActivitySwipeDetector implements View.OnTouchListener 
{
    static final String logTag = "SwipeDetector";
    private SwipeInterface activity;
    private float downX, downY;
    private long timeDown;
    private final float MIN_DISTANCE;
    private final int VELOCITY;
    private final float MAX_OFF_PATH;

    public ActivitySwipeDetector(Context context, SwipeInterface activity)
    {
        this.activity = activity;
        final ViewConfiguration vc = ViewConfiguration.get(context);
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        MIN_DISTANCE = vc.getScaledPagingTouchSlop() * dm.density;
        VELOCITY = vc.getScaledMinimumFlingVelocity();
        MAX_OFF_PATH = MIN_DISTANCE * 2;
    }

    public void onRightToLeftSwipe(View v) 
    {
        Log.i(logTag, "RightToLeftSwipe!");
        activity.onRightToLeft(v);
    }

    public void onLeftToRightSwipe(View v) 
    {
        Log.i(logTag, "LeftToRightSwipe!");
        activity.onLeftToRight(v);
    }

    public boolean onTouch(View v, MotionEvent event) 
    {
        switch (event.getAction()) 
        {
            case MotionEvent.ACTION_DOWN:
            {
                Log.d("onTouch", "ACTION_DOWN");
                timeDown = System.currentTimeMillis();
                downX = event.getX();
                downY = event.getY();
                v.getParent().requestDisallowInterceptTouchEvent(false);
                return true;
            }

        case MotionEvent.ACTION_MOVE:
            {
                float y_up = event.getY();
                float deltaY = y_up - downY;
                float absDeltaYMove = Math.abs(deltaY);

                if (absDeltaYMove > 60) 
                {
                    v.getParent().requestDisallowInterceptTouchEvent(false);
                } 
                else
                {
                    v.getParent().requestDisallowInterceptTouchEvent(true);
                }
            }

            break;

            case MotionEvent.ACTION_UP: 
            {
                Log.d("onTouch", "ACTION_UP");
                long timeUp = System.currentTimeMillis();
                float upX = event.getX();
                float upY = event.getY();

                float deltaX = downX - upX;
                float absDeltaX = Math.abs(deltaX);
                float deltaY = downY - upY;
                float absDeltaY = Math.abs(deltaY);

                long time = timeUp - timeDown;

                if (absDeltaY > MAX_OFF_PATH) 
                {
                    Log.e(logTag, String.format(
                            "absDeltaY=%.2f, MAX_OFF_PATH=%.2f", absDeltaY,
                            MAX_OFF_PATH));
                    return v.performClick();
                }

                final long M_SEC = 1000;
                if (absDeltaX > MIN_DISTANCE && absDeltaX > time * VELOCITY / M_SEC) 
                {
                     v.getParent().requestDisallowInterceptTouchEvent(true);
                    if (deltaX < 0) 
                    {
                        this.onLeftToRightSwipe(v);
                        return true;
                    }
                    if (deltaX > 0) 
                    {
                        this.onRightToLeftSwipe(v);
                        return true;
                    }
                }
                else 
                {
                    Log.i(logTag,
                            String.format(
                                    "absDeltaX=%.2f, MIN_DISTANCE=%.2f, absDeltaX > MIN_DISTANCE=%b",
                                    absDeltaX, MIN_DISTANCE,
                                    (absDeltaX > MIN_DISTANCE)));
                    Log.i(logTag,
                            String.format(
                                    "absDeltaX=%.2f, time=%d, VELOCITY=%d, time*VELOCITY/M_SEC=%d, absDeltaX > time * VELOCITY / M_SEC=%b",
                                    absDeltaX, time, VELOCITY, time * VELOCITY
                                            / M_SEC, (absDeltaX > time * VELOCITY
                                            / M_SEC)));
                }

                 v.getParent().requestDisallowInterceptTouchEvent(false);

            }
        }
        return false;
    }
    public interface SwipeInterface 
    {

        public void onLeftToRight(View v);

        public void onRightToLeft(View v);
    }

}

Call it from your activity class like this:

yourLayout.setOnTouchListener(new ActivitySwipeDetector(this, your_activity.this));

And Don't forget to implement SwipeInterface which will give you two @override methods:

    @Override
    public void onLeftToRight(View v) 
    {
        Log.e("TAG", "L to R");
    }

    @Override
    public void onRightToLeft(View v) 
    {
        Log.e("TAG", "R to L");
    }

How can I list the contents of a directory in Python?

One way:

import os
os.listdir("/home/username/www/")

Another way:

glob.glob("/home/username/www/*")

Examples found here.

The glob.glob method above will not list hidden files.

Since I originally answered this question years ago, pathlib has been added to Python. My preferred way to list a directory now usually involves the iterdir method on Path objects:

from pathlib import Path
print(*Path("/home/username/www/").iterdir(), sep="\n")

How to use operator '-replace' in PowerShell to replace strings of texts with special characters and replace successfully

If you've got V3, you can take advantage of auto-enumeration, the -Raw switch in Get-Content, and some of the new line contiunation syntax to simply it to this, using the string .replace() method instead of the -replace operator:

(Get-ChildItem "[FILEPATH]" -recurse).FullName |
  Foreach-Object {
   (Get-Content $_ -Raw).
     Replace('abt7d9epp4','w2svuzf54f').
     Replace('AccountName=adtestnego','AccountName=zadtestnego').
     Replace('AccountKey=eKkij32jGEIYIEqAR5RjkKgf4OTiMO6SAyF68HsR/Zd/KXoKvSdjlUiiWyVV2+OUFOrVsd7jrzhldJPmfBBpQA==','AccountKey=DdOegAhDmLdsou6Ms6nPtP37bdw6EcXucuT47lf9kfClA6PjGTe3CfN+WVBJNWzqcQpWtZf10tgFhKrnN48lXA==') |
   Set-Content $_
  }

Using the .replace() method uses literal strings for the replaced text argument (not regex), so you don't need to worry about escaping regex metacharacters in the text-to-replace argument.

Show a message box from a class in c#?

System.Windows.MessageBox.Show("Hello world"); //WPF
System.Windows.Forms.MessageBox.Show("Hello world"); //WinForms

How to style UITextview to like Rounded Rect text field?

One solution is to add a UITextField below the UITextView, make the UITextView background transparent and disable any user interaction on the UITextField. Then in code change the UITextField frame with something like that

self.textField.frame = CGRectInset(self.textView.frame, 0, -2);

You will have exactly the same look as a text field.

And as suggested by Jon, you should put this piece of code inside [UIViewController viewDidLayoutSubviews] on iOS 5.0+.

Python function global variables?

You can directly access a global variable inside a function. If you want to change the value of that global variable, use "global variable_name". See the following example:

var = 1
def global_var_change():
      global var
      var = "value changed"
global_var_change() #call the function for changes
print var

Generally speaking, this is not a good programming practice. By breaking namespace logic, code can become difficult to understand and debug.

What is "406-Not Acceptable Response" in HTTP?

406 Not Acceptable The resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request.

406 happens when the server cannot respond with the accept-header specified in the request. In your case it seems application/json for the response may not be acceptable to the server.

How is the java memory pool divided?

The new keyword allocates memory on the Java heap. The heap is the main pool of memory, accessible to the whole of the application. If there is not enough memory available to allocate for that object, the JVM attempts to reclaim some memory from the heap with a garbage collection. If it still cannot obtain enough memory, an OutOfMemoryError is thrown, and the JVM exits.

The heap is split into several different sections, called generations. As objects survive more garbage collections, they are promoted into different generations. The older generations are not garbage collected as often. Because these objects have already proven to be longer lived, they are less likely to be garbage collected.

When objects are first constructed, they are allocated in the Eden Space. If they survive a garbage collection, they are promoted to Survivor Space, and should they live long enough there, they are allocated to the Tenured Generation. This generation is garbage collected much less frequently.

There is also a fourth generation, called the Permanent Generation, or PermGen. The objects that reside here are not eligible to be garbage collected, and usually contain an immutable state necessary for the JVM to run, such as class definitions and the String constant pool. Note that the PermGen space is planned to be removed from Java 8, and will be replaced with a new space called Metaspace, which will be held in native memory. reference:http://www.programcreek.com/2013/04/jvm-run-time-data-areas/

Diagram of Java memory for several threads Diagram of Java memory distribution

Java, How to specify absolute value and square roots

import java.util.Scanner;
class my{
public static void main(String args[])
{
    Scanner x=new Scanner(System.in);
    double a,b,c=0,d;
    d=1;
    d=d/10;
    int e,z=0;
    System.out.print("Enter no:");
    a=x.nextInt();

    for(b=1;b<=a/2;b++)
    {
        if(b*b==a)
        {
            c=b;
            break;
        }
        else
        {
            if(b*b>a)
            break;
        }
    } 
    b--;
    if(c==0)
    {
       for(e=1;e<=15;e++)
        {
            while(b*b<=a && z==0)
            {
                if(b*b==a){c=b;z=1;}
                else
                {
                    b=b+d;          //*d==0.1 first time*//
                    if(b*b>=a){z=1;b=b-d;}
                }
            }
            d=d/10;
            z=0;
        }
        c=b;
    }

        System.out.println("Squre root="+c);





}    
}    

How can I generate an HTML report for Junit results?

If you could use Ant then you would just use the JUnitReport task as detailed here: http://ant.apache.org/manual/Tasks/junitreport.html, but you mentioned in your question that you're not supposed to use Ant. I believe that task merely transforms the XML report into HTML so it would be feasible to use any XSLT processor to generate a similar report.

Alternatively, you could switch to using TestNG ( http://testng.org/doc/index.html ) which is very similar to JUnit but has a default HTML report as well as several other cool features.

How to restore a SQL Server 2012 database to SQL Server 2008 R2?

You won't be able to restore from 2012 to 2008. You will be able to use a tool like red-gate SQL compare to copy the schema etc (provided nothing 2012 specific is used). If you have data to copy across too, you can use their Data Compare tool, and I think you get a 14 day free trial.

How to remove special characters from a string?

That depends on what you define as special characters, but try replaceAll(...):

String result = yourString.replaceAll("[-+.^:,]","");

Note that the ^ character must not be the first one in the list, since you'd then either have to escape it or it would mean "any but these characters".

Another note: the - character needs to be the first or last one on the list, otherwise you'd have to escape it or it would define a range ( e.g. :-, would mean "all characters in the range : to ,).

So, in order to keep consistency and not depend on character positioning, you might want to escape all those characters that have a special meaning in regular expressions (the following list is not complete, so be aware of other characters like (, {, $ etc.):

String result = yourString.replaceAll("[\\-\\+\\.\\^:,]","");


If you want to get rid of all punctuation and symbols, try this regex: \p{P}\p{S} (keep in mind that in Java strings you'd have to escape back slashes: "\\p{P}\\p{S}").

A third way could be something like this, if you can exactly define what should be left in your string:

String  result = yourString.replaceAll("[^\\w\\s]","");

This means: replace everything that is not a word character (a-z in any case, 0-9 or _) or whitespace.

Edit: please note that there are a couple of other patterns that might prove helpful. However, I can't explain them all, so have a look at the reference section of regular-expressions.info.

Here's less restrictive alternative to the "define allowed characters" approach, as suggested by Ray:

String  result = yourString.replaceAll("[^\\p{L}\\p{Z}]","");

The regex matches everything that is not a letter in any language and not a separator (whitespace, linebreak etc.). Note that you can't use [\P{L}\P{Z}] (upper case P means not having that property), since that would mean "everything that is not a letter or not whitespace", which almost matches everything, since letters are not whitespace and vice versa.

Additional information on Unicode

Some unicode characters seem to cause problems due to different possible ways to encode them (as a single code point or a combination of code points). Please refer to regular-expressions.info for more information.

Easiest way to convert a List to a Set in Java

For Java 8 it's very easy:

List < UserEntity > vList= new ArrayList<>(); 
vList= service(...);
Set<UserEntity> vSet= vList.stream().collect(Collectors.toSet());

JQuery Bootstrap Multiselect plugin - Set a value as selected in the multiselect dropdown

$("#dropDownId").val(["130860","130858"]);
$("#dropDownId").selectmenu('refresh');

Finding the second highest number in array

I have got the simplest logic to find the second largest number may be, it's not. The logic find sum of two number in the array which has the highest value and then check which is greater among two simple............

int ar[]={611,4,556,107,5,55,811};
int sum=ar[0]+ar[1];
int temp=0;
int m=ar[0];
int n=ar[1];
for(int i=0;i<ar.length;i++){
    for(int j=i;j<ar.length;j++){
        if(i!=j){
        temp=ar[i]+ar[j];
        if(temp>sum){
            sum=temp;
            m=ar[i];
            n=ar[j];
        }
        temp=0;

    }
    }
}
if(m>n){
    System.out.println(n);

}
else{
    System.out.println(m);
}

How to send custom headers with requests in Swagger UI?

Here's a simpler answer for the ASP.NET Core Web Api/Swashbuckle combo, that doesn't require you to register any custom filters. Third time's a charm you know :).

Adding the code below to your Swagger config will cause the Authorize button to appear, allowing you to enter a bearer token to be sent for all requests. Don't forget to enter this token as Bearer <your token here> when asked.

Note that the code below will send the token for any and all requests and operations, which may or may not be what you want.


    services.AddSwaggerGen(c =>
    {
        //...

        c.AddSecurityDefinition("Bearer", new ApiKeyScheme()
        {
            Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
            Name = "Authorization",
            In = "header",
            Type = "apiKey"
        });

        c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
        {
            { "Bearer", new string[] { } }
        });

        //...
    }

Via this thread.

Error message "No exports were found that match the constraint contract name"

Remove ComponentModelCache folder content.

 %AppData%..\Local\Microsoft\VisualStudio\11.0\ComponentModelCache

How to find the UpgradeCode and ProductCode of an installed application in Windows 7

To everyone using:

Get-WMIObject win32_product

You should be aware that this will run a self-heal on every single MSI application installed on the PC. If you were to check eventvwr it will say it has finished reconfiguring each product.

In this case i use the following (a mixture of Yan Sklyarenko's method):

$Reg = @( "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*", "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*" )
$InstalledApps = Get-ItemProperty $Reg -EA 0
$WantedApp = $InstalledApps | Where { $_.DisplayName -like "*<part of product>*" }

Now if you were to type:

$WantedApp.PSChildName

You would be given the following:

PS D:\SCCM> $WantedApp.PSChildName
{047904BA-C065-40D5-969A-C7D91CA93D62}

If your organization uses loads of MST's whilst installing applications you would want to avoid running self-heals encase they revert some crucial settings.

  • Note - This will find your product code, then the upgrade can be found as Yan mentioned. I usually, though, just use either 'InstEd It!' or 'Orca' then go to the Property table of the MSI and it lists them right at the top.

Convert List<Object> to String[] in Java

Using Guava

List<Object> lst ...    
List<String> ls = Lists.transform(lst, Functions.toStringFunction());

How to add users to Docker container?

Add this line to your Dockerfile (You can run any linux command this way)

RUN useradd -ms /bin/bash yourNewUserName

Set value of hidden field in a form using jQuery's ".val()" doesn't work

If you're having trouble setting the value of a hidden field because you're passing an ID to it, this is the solution:

Instead of $("#hidden_field_id").val(id) just do $("input[id=hidden_field_id]").val(id). Not sure what the difference is, but it works.

How do I specify "not equals to" when comparing strings in an XSLT <xsl:if>?

As Filburt says; but also note that it's usually better to write

test="not(Count = 'N/A')"

If there's exactly one Count element they mean the same thing, but if there's no Count, or if there are several, then the meanings are different.

6 YEARS LATER

Since this answer seems to have become popular, but may be a little cryptic to some readers, let me expand it.

The "=" and "!=" operator in XPath can compare two sets of values. In general, if A and B are sets of values, then "=" returns true if there is any pair of values from A and B that are equal, while "!=" returns true if there is any pair that are unequal.

In the common case where A selects zero-or-one nodes, and B is a constant (say "NA"), this means that not(A = "NA") returns true if A is either absent, or has a value not equal to "NA". By contrast, A != "NA" returns true if A is present and not equal to "NA". Usually you want the "absent" case to be treated as "not equal", which means that not(A = "NA") is the appropriate formulation.

Including jars in classpath on commandline (javac or apt)

Use the -cp or -classpath switch.

$ java -help  
Usage: java [-options] class [args...]  
           (to execute a class)  
   or  java [-options] -jar jarfile [args...]  
           (to execute a jar file)  

where options include:  
...  
    -cp <class search path of directories and zip/jar files>  
    -classpath <class search path of directories and zip/jar files>  
                  A ; separated list of directories, JAR archives,  
                  and ZIP archives to search for class files.  

(Note that the separator used to separate entries on the classpath differs between OSes, on my Windows machine it is ;, in *nix it is usually :.)

How to copy and paste code without rich text formatting?

From websites, using Firefox, I use the CopyPlainText extension.

How to do a Postgresql subquery in select clause with join in from clause like SQL Server?

select n1.name, n1.author_id, cast(count_1 as numeric)/total_count
  from (select id, name, author_id, count(1) as count_1
          from names
          group by id, name, author_id) n1
inner join (select distinct(author_id), count(1) as total_count
              from names) n2
  on (n2.author_id = n1.author_id)
Where true

used distinct if more inner join, because more join group performance is slow

android splash screen sizes for ldpi,mdpi, hdpi, xhdpi displays ? - eg : 1024X768 pixels for ldpi

Just use this website: http://ticons.fokkezb.nl :)

It makes it easier for you, and generates the correct sizes directly

How do I run a simple bit of code in a new thread?

Quick and dirty, but it will work:

Using at top:

using System.Threading;

simple code:

static void Main( string[] args )
{
    Thread t = new Thread( NewThread );
    t.Start();
}

static void NewThread()
{
    //code goes here
}

I just threw this into a new console application for an exmaple

disable viewport zooming iOS 10+ safari?

I spent about an hour looking for a more robust javascript option, and did not find one. It just so happens that in the past few days I've been fiddling with hammer.js (Hammer.js is a library that lets you manipulate all sorts of touch events easily) and mostly failing at what I was trying to do.

With that caveat, and understanding I am by no means a javascript expert, this is a solution I came up with that basically leverages hammer.js to capture the pinch-zoom and double-tap events and then log and discard them.

Make sure you include hammer.js in your page and then try sticking this javascript in the head somewhere:

_x000D_
_x000D_
< script type = "text/javascript" src="http://hammerjs.github.io/dist/hammer.min.js"> < /script >_x000D_
< script type = "text/javascript" >_x000D_
_x000D_
  // SPORK - block pinch-zoom to force use of tooltip zoom_x000D_
  $(document).ready(function() {_x000D_
_x000D_
    // the element you want to attach to, probably a wrapper for the page_x000D_
    var myElement = document.getElementById('yourwrapperelement');_x000D_
    // create a new hammer object, setting "touchAction" ensures the user can still scroll/pan_x000D_
    var hammertime = new Hammer(myElement, {_x000D_
      prevent_default: false,_x000D_
      touchAction: "pan"_x000D_
    });_x000D_
_x000D_
    // pinch is not enabled by default in hammer_x000D_
    hammertime.get('pinch').set({_x000D_
      enable: true_x000D_
    });_x000D_
_x000D_
    // name the events you want to capture, then call some function if you want and most importantly, add the preventDefault to block the normal pinch action_x000D_
    hammertime.on('pinch pinchend pinchstart doubletap', function(e) {_x000D_
      console.log('captured event:', e.type);_x000D_
      e.preventDefault();_x000D_
    })_x000D_
  });_x000D_
</script>
_x000D_
_x000D_
_x000D_

How to use Elasticsearch with MongoDB?

Here how to do this on mongodb 3.0. I used this nice blog

  1. Install mongodb.
  2. Create data directories:
$ mkdir RANDOM_PATH/node1
$ mkdir RANDOM_PATH/node2> 
$ mkdir RANDOM_PATH/node3
  1. Start Mongod instances
$ mongod --replSet test --port 27021 --dbpath node1
$ mongod --replSet test --port 27022 --dbpath node2
$ mongod --replSet test --port 27023 --dbpath node3
  1. Configure the Replica Set:
$ mongo
config = {_id: 'test', members: [ {_id: 0, host: 'localhost:27021'}, {_id: 1, host: 'localhost:27022'}]};    
rs.initiate(config);
  1. Installing Elasticsearch:
a. Download and unzip the [latest Elasticsearch][2] distribution

b. Run bin/elasticsearch to start the es server.

c. Run curl -XGET http://localhost:9200/ to confirm it is working.
  1. Installing and configuring the MongoDB River:

$ bin/plugin --install com.github.richardwilly98.elasticsearch/elasticsearch-river-mongodb

$ bin/plugin --install elasticsearch/elasticsearch-mapper-attachments

  1. Create the “River” and the Index:

curl -XPUT 'http://localhost:8080/_river/mongodb/_meta' -d '{ "type": "mongodb", "mongodb": { "db": "mydb", "collection": "foo" }, "index": { "name": "name", "type": "random" } }'

  1. Test on browser:

    http://localhost:9200/_search?q=home

Convert LocalDate to LocalDateTime or java.sql.Timestamp

The best way use Java 8 time API:

  LocalDateTime ldt = timeStamp.toLocalDateTime();
  Timestamp ts = Timestamp.valueOf(ldt);

For use with JPA put in with your model (https://weblogs.java.net/blog/montanajava/archive/2014/06/17/using-java-8-datetime-classes-jpa):

@Converter(autoApply = true)
public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, Timestamp> {
    @Override
    public Timestamp convertToDatabaseColumn(LocalDateTime ldt) {
        return Timestamp.valueOf(ldt);
    }

    @Override
    public LocalDateTime convertToEntityAttribute(Timestamp ts) {
        return ts.toLocalDateTime();
    }
}

So now it is relative timezone independent time. Additionally it is easy do:

  LocalDate ld = ldt.toLocalDate();
  LocalTime lt = ldt.toLocalTime();

Formatting:

 DateTimeFormatter DATE_TME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
 String str = ldt.format(DATE_TME_FORMATTER);
 ldt = LocalDateTime.parse(str, DATE_TME_FORMATTER);

UPDATE: postgres 9.4.1208, HSQLDB 2.4.0 etc understand Java 8 Time API without any conversations!

How to change app default theme to a different app theme?

Or try to check your mainActivity.xml you make sure that this one
xmlns:app="http://schemas.android.com/apk/res-auto"hereis included

How to find text in a column and saving the row number where it is first found - Excel VBA

A few comments:

  1. Since the search position is important you should specify where you start the search. I use ws.[a1] and xlNext below so my search starts in A2 of the specified sheet.
  2. Some of Finds arguments - including lookat use the prior search settings. So you should always specify xlWhole or xlPart to match all or part a string respectively.
  3. You can do all you want - including inserting a row, and prompting the user for a new value (my code will suggest 20 if the prior value was 19) without using Select or Activate

suggested code

Sub FindEm()
Dim Wb As Workbook
Dim ws As Worksheet
Dim rng1 As Range
Set Wb = ThisWorkbook
Set ws = Wb.Sheets("ECM Overview")
Set rng1 = ws.Range("A:A").Find("ProjTemp", ws.[a1], xlValues, xlWhole, , xlNext)
If Not rng1 Is Nothing Then
rng1.EntireRow.Insert
rng1.Offset(-1, 0).Value = Application.InputBox("Please enter data", "User Data Entry", rng1.Offset(-2, 0) + 1, , , , , 1)
Else
MsgBox "ProjTemp not found", vbCritical
End If
End Sub

How do I query for all dates greater than a certain date in SQL Server?

select *  
from dbo.March2010 A 
where A.Date >= Convert(datetime, '2010-04-01' )

In your query, 2010-4-01 is treated as a mathematical expression, so in essence it read

select *  
from dbo.March2010 A 
where A.Date >= 2005; 

(2010 minus 4 minus 1 is 2005 Converting it to a proper datetime, and using single quotes will fix this issue.)

Technically, the parser might allow you to get away with

select *  
from dbo.March2010 A 
where A.Date >= '2010-04-01'

it will do the conversion for you, but in my opinion it is less readable than explicitly converting to a DateTime for the maintenance programmer that will come after you.

How to change Elasticsearch max memory size

For anyone looking to do this on Centos 7 or with another system running SystemD, you change it in

/etc/sysconfig/elasticsearch 

Uncomment the ES_HEAP_SIZE line, and set a value, eg:

# Heap Size (defaults to 256m min, 1g max)
ES_HEAP_SIZE=16g

(Ignore the comment about 1g max - that's the default)

All shards failed

If you encounter this apparent index corruption in a running system, you can work around it by deleting all files called segments.gen. It is advisory only, and Lucene can recover correctly without it.

From ElasticSearch Blog

XPath OR operator for different nodes

If you want to select only one of two nodes with union operator, you can use this solution: (//bookstore/book/title | //bookstore/city/zipcode/title)[1]

Checking if a key exists in a JS object

map.has(key) is the latest ECMAScript 2015 way of checking the existance of a key in a map. Refer to this for complete details.

jquery $.each() for objects

You are indeed passing the first data item to the each function.

Pass data.programs to the each function instead. Change the code to as below:

<script>     
    $(document).ready(function() {         
        var data = { "programs": [ { "name":"zonealarm", "price":"500" }, { "name":"kaspersky", "price":"200" } ] };         
        $.each(data.programs, function(key,val) {             
            alert(key+val);         
        });     
    }); 
</script> 

How can I check file size in Python?

The other answers work for real files, but if you need something that works for "file-like objects", try this:

# f is a file-like object. 
f.seek(0, os.SEEK_END)
size = f.tell()

It works for real files and StringIO's, in my limited testing. (Python 2.7.3.) The "file-like object" API isn't really a rigorous interface, of course, but the API documentation suggests that file-like objects should support seek() and tell().

Edit

Another difference between this and os.stat() is that you can stat() a file even if you don't have permission to read it. Obviously the seek/tell approach won't work unless you have read permission.

Edit 2

At Jonathon's suggestion, here's a paranoid version. (The version above leaves the file pointer at the end of the file, so if you were to try to read from the file, you'd get zero bytes back!)

# f is a file-like object. 
old_file_position = f.tell()
f.seek(0, os.SEEK_END)
size = f.tell()
f.seek(old_file_position, os.SEEK_SET)

JavaScript get clipboard data on paste event (Cross browser)

I've written a little proof of concept for Tim Downs proposal here with off-screen textarea. And here goes the code:

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script> 
<script language="JavaScript">
 $(document).ready(function()
{

var ctrlDown = false;
var ctrlKey = 17, vKey = 86, cKey = 67;

$(document).keydown(function(e)
{
    if (e.keyCode == ctrlKey) ctrlDown = true;
}).keyup(function(e)
{
    if (e.keyCode == ctrlKey) ctrlDown = false;
});

$(".capture-paste").keydown(function(e)
{
    if (ctrlDown && (e.keyCode == vKey || e.keyCode == cKey)){
        $("#area").css("display","block");
        $("#area").focus();         
    }
});

$(".capture-paste").keyup(function(e)
{
    if (ctrlDown && (e.keyCode == vKey || e.keyCode == cKey)){                      
        $("#area").blur();
        //do your sanitation check or whatever stuff here
        $("#paste-output").text($("#area").val());
        $("#area").val("");
        $("#area").css("display","none");
    }
});

});
</script>

</head>
<body class="capture-paste">

<div id="paste-output"></div>


    <div>
    <textarea id="area" style="display: none; position: absolute; left: -99em;"></textarea>
    </div>

</body>
</html>

Just copy and paste the whole code into one html file and try to paste (using ctrl-v) text from clipboard anywhere on the document.

I've tested it in IE9 and new versions of Firefox, Chrome and Opera. Works quite well. Also it's good that one can use whatever key combination he prefers to triger this functionality. Of course don't forget to include jQuery sources.

Feel free to use this code and if you come with some improvements or problems please post them back. Also note that I'm no Javascript developer so I may have missed something (=>do your own testign).

Numpy: Checking if a value is NaT

Another way would be to catch the exeption:

def is_nat(npdatetime):
    try:
        npdatetime.strftime('%x')
        return False
    except:
        return True

The type or namespace name 'Objects' does not exist in the namespace 'System.Data'

I added a reference to the .dll file, for System.Data.Linq, the above was not sufficient. You can find .dll in the various directories for the following versions.

System.Data.Linq C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.5\System.Data.Linq.dll 3.5.0.0

System.Data.Linq C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0\Profile\Client\System.Data.Linq.dll 4.0.0.0

Xlib: extension "RANDR" missing on display ":21". - Trying to run headless Google Chrome

jeues answer helped me nothing :-( after hours I finally found the solution for my system and I think this will help other people too. I had to set the LD_LIBRARY_PATH like this:

   export LD_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu/

after that everything worked very well, even without any "-extension RANDR" switch.

VBA: activating/selecting a worksheet/row/cell

This is just a sample code, but it may help you get on your way:

Public Sub testIt()
    Workbooks("Workbook2").Activate
    ActiveWorkbook.Sheets("Sheet2").Activate
    ActiveSheet.Range("B3").Select
    ActiveCell.EntireRow.Insert
End Sub

I am assuming that you can open the book (called Workbook2 in the example).


I think (but I'm not sure) you can squash all this in a single line of code:

    Workbooks("Workbook2").Sheets("Sheet2").Range("B3").EntireRow.Insert

This way you won't need to activate the workbook (or sheet or cell)... Obviously, the book has to be open.

Python way to clone a git repository

Here's a way to print progress while cloning a repo with GitPython

import time
import git
from git import RemoteProgress

class CloneProgress(RemoteProgress):
    def update(self, op_code, cur_count, max_count=None, message=''):
        if message:
            print(message)

print('Cloning into %s' % git_root)
git.Repo.clone_from('https://github.com/your-repo', '/your/repo/dir', 
        branch='master', progress=CloneProgress())

Python int to binary string?

Calculator with all neccessary functions for DEC,BIN,HEX: (made and tested with Python 3.5)

You can change the input test numbers and get the converted ones.

# CONVERTER: DEC / BIN / HEX

def dec2bin(d):
    # dec -> bin
    b = bin(d)
    return b

def dec2hex(d):
    # dec -> hex
    h = hex(d)
    return h

def bin2dec(b):
    # bin -> dec
    bin_numb="{0:b}".format(b)
    d = eval(bin_numb)
    return d,bin_numb

def bin2hex(b):
    # bin -> hex
    h = hex(b)
    return h

def hex2dec(h):
    # hex -> dec
    d = int(h)
    return d

def hex2bin(h):
    # hex -> bin
    b = bin(h)
    return b


## TESTING NUMBERS
numb_dec = 99
numb_bin = 0b0111 
numb_hex = 0xFF


## CALCULATIONS
res_dec2bin = dec2bin(numb_dec)
res_dec2hex = dec2hex(numb_dec)

res_bin2dec,bin_numb = bin2dec(numb_bin)
res_bin2hex = bin2hex(numb_bin)

res_hex2dec = hex2dec(numb_hex)
res_hex2bin = hex2bin(numb_hex)



## PRINTING
print('------- DECIMAL to BIN / HEX -------\n')
print('decimal:',numb_dec,'\nbin:    ',res_dec2bin,'\nhex:    ',res_dec2hex,'\n')

print('------- BINARY to DEC / HEX -------\n')
print('binary: ',bin_numb,'\ndec:    ',numb_bin,'\nhex:    ',res_bin2hex,'\n')

print('----- HEXADECIMAL to BIN / HEX -----\n')
print('hexadec:',hex(numb_hex),'\nbin:    ',res_hex2bin,'\ndec:    ',res_hex2dec,'\n')

Purpose of __repr__ method?

__repr__ should return a printable representation of the object, most likely one of the ways possible to create this object. See official documentation here. __repr__ is more for developers while __str__ is for end users.

A simple example:

>>> class Point:
...   def __init__(self, x, y):
...     self.x, self.y = x, y
...   def __repr__(self):
...     return 'Point(x=%s, y=%s)' % (self.x, self.y)
>>> p = Point(1, 2)
>>> p
Point(x=1, y=2)

how to convert from int to char*?

See this answer https://stackoverflow.com/a/23010605/2760919

For your case, just change the type in snprintf from long ("%ld") to int ("%n").

how to pass value from one php page to another using session

Solution using just POST - no $_SESSION

page1.php

<form action="page2.php" method="post">
    <textarea name="textarea1" id="textarea1"></textarea><br />
    <input type="submit" value="submit" />
</form>

page2.php

<?php
    // this page outputs the contents of the textarea if posted
    $textarea1 = ""; // set var to avoid errors
    if(isset($_POST['textarea1'])){
        $textarea1 = $_POST['textarea1']
    }
?>
<textarea><?php echo $textarea1;?></textarea>

Solution using $_SESSION and POST

page1.php

<?php

    session_start(); // needs to be before anything else on page to use $_SESSION
    $textarea1 = "";
    if(isset($_POST['textarea1'])){
        $_SESSION['textarea1'] = $_POST['textarea1'];
    }

?>


<form action="page1.php" method="post">
    <textarea name="textarea1" id="textarea1"></textarea><br />
    <input type="submit" value="submit" />
</form>
<br /><br />
<a href="page2.php">Go to page2</a>

page2.php

<?php
    session_start(); // needs to be before anything else on page to use $_SESSION
    // this page outputs the textarea1 from the session IF it exists
    $textarea1 = ""; // set var to avoid errors
    if(isset($_SESSION['textarea1'])){
        $textarea1 = $_SESSION['textarea1']
    }
?>
<textarea><?php echo $textarea1;?></textarea>

WARNING!!! - This contains no validation!!!

How to install ADB driver for any android device?

I have found a solution by myself. I use the PDANet tool to find the driver automatically.

http://www.junefabrics.com/android/download.php

How do I do logging in C# without using 3rd party libraries?

public void Logger(string lines)
{
  //Write the string to a file.append mode is enabled so that the log
  //lines get appended to  test.txt than wiping content and writing the log

  using(System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt", true))
  {
    file.WriteLine(lines);
  }
}

For more information MSDN

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

We encountered a very similar situation.

Activity 1 (Opening) -> Activity 2 (Preview) -> Activity 3 (Detail)

Incorrect "on back press" Response

  • Device back press on Activity 3 will also close Activity 2.

I have checked all answers posted above and none of them worked. Java syntax for transition between Activity 2 and Activity 3 was reviewed to be correct.

Fresh from coding on calling out a 3rd party app. by an Activity. We decided to investigate the configuration angle - eventually enabling us to identify the root cause of the problem.

Scope: Configuration of Activity 2 (caller).

Root Cause:

android:launchMode="singleInstance"

Solution:

android:launchMode="singleTask"

Apparently on this "on back press" issue singleInstance considers invoked Activities in one instance with the calling Activity, whereas singleTask will allow for invoked Activities having their own identity enough for the intended on back press to function to work as it should to.

What is the difference between CMD and ENTRYPOINT in a Dockerfile?

Difference between CMD and ENTRYPOINT by intuition:

  • ENTRYPOINT: command to run when container starts.
  • CMD: command to run when container starts or arguments to ENTRYPOINT if specified.

Yes, it's mixing up.

You can override any of them when running docker run.

Difference between CMD and ENTRYPOINT by example:

docker run -it --rm yourcontainer /bin/bash            <-- /bin/bash overrides CMD
                                                       <-- /bin/bash does not override ENTRYPOINT
docker run -it --rm --entrypoint ls yourcontainer      <-- overrides ENTRYPOINT with ls
docker run -it --rm --entrypoint ls yourcontainer  -la  <-- overrides ENTRYPOINT with ls and overrides CMD with -la

More on difference between CMD and ENTRYPOINT:

Argument to docker run such as /bin/bash overrides any CMD command we wrote in Dockerfile.

ENTRYPOINT cannot be overriden at run time with normal commands such as docker run [args]. The args at the end of docker run [args] are provided as arguments to ENTRYPOINT. In this way we can create a container which is like a normal binary such as ls.

So CMD can act as default parameters to ENTRYPOINT and then we can override the CMD args from [args].

ENTRYPOINT can be overriden with --entrypoint.

SQL (MySQL) vs NoSQL (CouchDB)

Seems like only real solutions today revolve around scaling out or sharding. All modern databases (NoSQLs as well as NewSQLs) support horizontal scaling right out of the box, at the database layer, without the need for the application to have sharding code or something.

Unfortunately enough, for the trusted good-old MySQL, sharding is not provided "out of the box". ScaleBase (disclaimer: I work there) is a maker of a complete scale-out solution an "automatic sharding machine" if you like. ScaleBae analyzes your data and SQL stream, splits the data across DB nodes, and aggregates in runtime – so you won’t have to! And it's free download.

Don't get me wrong, NoSQLs are great, they're new, new is more choice and choice is always good!! But choosing NoSQL comes with a price, make sure you can pay it...

You can see here some more data about MySQL, NoSQL...: http://www.scalebase.com/extreme-scalability-with-mongodb-and-mysql-part-1-auto-sharding

Hope that helped.

Best way to define error codes/strings in Java?

I use PropertyResourceBundle to define the error codes in an enterprise application to manage locale error code resources. This is the best way to handle error codes instead of writing code (may be hold good for few error codes) when the number of error codes are huge and structured.

Look at java doc for more information on PropertyResourceBundle

How to add bootstrap in angular 6 project?

npm install --save bootstrap

afterwards, inside angular.json (previously .angular-cli.json) inside the project's root folder, find styles and add the bootstrap css file like this:

for angular 6

"styles": [
          "../node_modules/bootstrap/dist/css/bootstrap.min.css",
          "styles.css"
],

for angular 7

"styles": [
          "node_modules/bootstrap/dist/css/bootstrap.min.css",
          "src/styles.css"
],

Hibernate Group by Criteria Object

GroupBy using in Hibernate

This is the resulting code

public Map getStateCounts(final Collection ids) {
    HibernateSession hibernateSession = new HibernateSession();
    Session session = hibernateSession.getSession();
    Criteria criteria = session.createCriteria(DownloadRequestEntity.class)
            .add(Restrictions.in("id", ids));
    ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.groupProperty("state"));
    projectionList.add(Projections.rowCount());
    criteria.setProjection(projectionList);
    List results = criteria.list();
    Map stateMap = new HashMap();
    for (Object[] obj : results) {
        DownloadState downloadState = (DownloadState) obj[0];
        stateMap.put(downloadState.getDescription().toLowerCase() (Integer) obj[1]);
    }
    hibernateSession.closeSession();
    return stateMap;
}

How to reduce the image size without losing quality in PHP

I'd go for jpeg. Read this post regarding image size reduction and after deciding on the technique, use ImageMagick

Hope this helps

Converting 24 hour time to 12 hour time w/ AM & PM using Javascript

This worked for me!

function main() {
  var time = readLine();
  var formattedTime = time.replace('AM', ' AM').replace('PM', ' PM');
  var separators = [':', ' M'];
  var hms = formattedTime.split(new RegExp('[' + separators.join('') + ']'));
  if (parseInt(hms[0]) < 12 && hms[3] == 'P')
      hms[0] = parseInt(hms[0]) + 12;
  else if (parseInt(hms[0]) == 12 && hms[3] == 'A')
      hms[0] = '00';
  console.log(hms[0] + ':' + hms[1] + ':' + hms[2]);

}

Replace one character with another in Bash

Try this for paths:

echo \"hello world\"|sed 's/ /+/g'|sed 's/+/\/g'|sed 's/\"//g'

It replaces the space inside the double-quoted string with a + sing, then replaces the + sign with a backslash, then removes/replaces the double-quotes.

I had to use this to replace the spaces in one of my paths in Cygwin.

echo \"$(cygpath -u $JAVA_HOME)\"|sed 's/ /+/g'|sed 's/+/\\/g'|sed 's/\"//g'

Angular 2: Get Values of Multiple Checked Checkboxes

I just faced this issue, and decided to make everything work with as less variables as i can, to keep workspace clean. Here is example of my code

<input type="checkbox" (change)="changeModel($event, modelArr, option.value)" [checked]="modelArr.includes(option.value)" />

Method, which called on change is pushing value in model, or removing it.

public changeModel(ev, list, val) {
  if (ev.target.checked) {
    list.push(val);
  } else {
    let i = list.indexOf(val);
    list.splice(i, 1);
  }
}

Is it possible to modify a registry entry via a .bat/.cmd script?

You can use the REG command. From http://www.ss64.com/nt/reg.html:

Syntax:

   REG QUERY [ROOT\]RegKey /v ValueName [/s]
   REG QUERY [ROOT\]RegKey /ve  --This returns the (default) value

   REG ADD [ROOT\]RegKey /v ValueName [/t DataType] [/S Separator] [/d Data] [/f]
   REG ADD [ROOT\]RegKey /ve [/d Data] [/f]  -- Set the (default) value

   REG DELETE [ROOT\]RegKey /v ValueName [/f]
   REG DELETE [ROOT\]RegKey /ve [/f]  -- Remove the (default) value
   REG DELETE [ROOT\]RegKey /va [/f]  -- Delete all values under this key

   REG COPY  [\\SourceMachine\][ROOT\]RegKey [\\DestMachine\][ROOT\]RegKey

   REG EXPORT [ROOT\]RegKey FileName.reg
   REG IMPORT FileName.reg
   REG SAVE [ROOT\]RegKey FileName.hiv
   REG RESTORE \\MachineName\[ROOT]\KeyName FileName.hiv

   REG LOAD FileName KeyName
   REG UNLOAD KeyName

   REG COMPARE [ROOT\]RegKey [ROOT\]RegKey [/v ValueName] [Output] [/s]
   REG COMPARE [ROOT\]RegKey [ROOT\]RegKey [/ve] [Output] [/s]

Key:
   ROOT :
         HKLM = HKey_Local_machine (default)
         HKCU = HKey_current_user
         HKU  = HKey_users
         HKCR = HKey_classes_root

   ValueName : The value, under the selected RegKey, to edit.
               (default is all keys and values)

   /d Data   : The actual data to store as a "String", integer etc

   /f        : Force an update without prompting "Value exists, overwrite Y/N"

   \\Machine : Name of remote machine - omitting defaults to current machine.
                Only HKLM and HKU are available on remote machines.

   FileName  : The filename to save or restore a registry hive.

   KeyName   : A key name to load a hive file into. (Creating a new key)

   /S        : Query all subkeys and values.

   /S Separator : Character to use as the separator in REG_MULTI_SZ values
                  the default is "\0" 

   /t DataType  : REG_SZ (default) | REG_DWORD | REG_EXPAND_SZ | REG_MULTI_SZ

   Output    : /od (only differences) /os (only matches) /oa (all) /on (no output)

Escaping Double Quotes in Batch Script

If the string is already within quotes then use another quote to nullify its action.

echo "Insert tablename(col1) Values('""val1""')" 

Multiple submit buttons on HTML form – designate one button as default

Quick'n'dirty you could create an hidden duplicate of the submit-button, which should be used, when pressing enter.

Example CSS

input.hidden {
    width: 0px;
    height: 0px;
    margin: 0px;
    padding: 0px;
    outline: none;
    border: 0px;
}

Example HTML

<input type="submit" name="next" value="Next" class="hidden" />
<input type="submit" name="prev" value="Previous" />
<input type="submit" name="next" value="Next" />

If someone now hits enter in your form, the (hidden) next-button will be used as submitter.

Tested on IE9, Firefox, Chrome and Opera

Find and extract a number from a string

use regular expression ...

Regex re = new Regex(@"\d+");
Match m = re.Match("test 66");

if (m.Success)
{
    Console.WriteLine(string.Format("RegEx found " + m.Value + " at position " + m.Index.ToString()));
}
else
{
    Console.WriteLine("You didn't enter a string containing a number!");
}

How do I create HTML table using jQuery dynamically?

Here is a full example of what you are looking for:

<html>
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script>
        $( document ).ready(function() {
            $("#providersFormElementsTable").html("<tr><td>Nickname</td><td><input type='text' id='nickname' name='nickname'></td></tr><tr><td>CA Number</td><td><input type='text' id='account' name='account'></td></tr>");
        });
    </script>
</head>

<body>
    <table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'> </table>
</body>

Why does CSV file contain a blank line in between each data line when outputting with Dictwriter in Python

By default, the classes in the csv module use Windows-style line terminators (\r\n) rather than Unix-style (\n). Could this be what’s causing the apparent double line breaks?

If so, you can override it in the DictWriter constructor:

output = csv.DictWriter(open('file3.csv','w'), delimiter=',', lineterminator='\n', fieldnames=headers)

TypeError: sequence item 0: expected string, int found

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

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

Remove items from one list in another

You don't need an index, as the List<T> class allows you to remove items by value rather than index by using the Remove function.

foreach(car item in list1) list2.Remove(item);

How to do INSERT into a table records extracted from another table

Well I think the best way would be (will be?) to define 2 recordsets and use them as an intermediate between the 2 tables.

  1. Open both recordsets
  2. Extract the data from the first table (SELECT blablabla)
  3. Update 2nd recordset with data available in the first recordset (either by adding new records or updating existing records
  4. Close both recordsets

This method is particularly interesting if you plan to update tables from different databases (ie each recordset can have its own connection ...)

CSS media query to target iPad and iPad only?

These days you can use a Media Queries Level 4 feature to check if the device has the ability to 'hover' over elements.

@media (hover: hover) { ... }

Since the ipad has no 'hover' state you can effectively target touch devices like the ipad.

Javascript Array.sort implementation?

After some more research, it appears, for Mozilla/Firefox, that Array.sort() uses mergesort. See the code here.

Func delegate with no return type

A very easy way to invoke return and non return value subroutines. is using Func and Action respectively. (see also https://msdn.microsoft.com/en-us/library/018hxwa8(v=vs.110).aspx)

Try this this example

using System;

public class Program
{
    private Func<string,string> FunctionPTR = null;  
    private Func<string,string, string> FunctionPTR1 = null;  
    private Action<object> ProcedurePTR = null; 



    private string Display(string message)  
    {  
        Console.WriteLine(message);  
        return null;  
    }  

    private string Display(string message1,string message2)  
    {  
        Console.WriteLine(message1);  
        Console.WriteLine(message2);  
        return null;  
    }  

    public void ObjectProcess(object param)
    {
        if (param == null)
        {
            throw new ArgumentNullException("Parameter is null or missing");
        }
        else 
        {
            Console.WriteLine("Object is valid");
        }
    }


    public void Main(string[] args)  
    {  
        FunctionPTR = Display;  
        FunctionPTR1= Display;  
        ProcedurePTR = ObjectProcess;
        FunctionPTR("Welcome to function pointer sample.");  
        FunctionPTR1("Welcome","This is function pointer sample");   
        ProcedurePTR(new object());
    }  
}

SQLite equivalent to ISNULL(), NVL(), IFNULL() or COALESCE()

You can easily define such function and use it then:

ifnull <- function(x,y) {
  if(is.na(x)==TRUE) 
    return (y)
  else 
    return (x);
}

or same minified version:

ifnull <- function(x,y) {if(is.na(x)==TRUE) return (y) else return (x);}

Ruby convert Object to Hash

Recursively convert your objects to hash using 'hashable' gem (https://rubygems.org/gems/hashable) Example

class A
  include Hashable
  attr_accessor :blist
  def initialize
    @blist = [ B.new(1), { 'b' => B.new(2) } ]
  end
end

class B
  include Hashable
  attr_accessor :id
  def initialize(id); @id = id; end
end

a = A.new
a.to_dh # or a.to_deep_hash
# {:blist=>[{:id=>1}, {"b"=>{:id=>2}}]}

How to set a cron job to run every 3 hours

The unix setup should be like the following:

 0 */3 * * * sh cron/update_old_citations.sh

good reference for how to set various settings in cron at: http://www.thegeekstuff.com/2011/07/cron-every-5-minutes/

SQL query for getting data for last 3 months

I'd use datediff, and not care about format conversions:

SELECT *
FROM   mytable
WHERE  DATEDIFF(MONTH, my_date_column, GETDATE()) <= 3

How to change the font on the TextView?

Maybe something a bit simpler:

public class Fonts {
  public static HashSet<String,Typeface> fonts = new HashSet<>();

  public static Typeface get(Context context, String file) {
    if (! fonts.contains(file)) {
      synchronized (this) {
        Typeface typeface = Typeface.createFromAsset(context.getAssets(), name);
        fonts.put(name, typeface);
      }
    }
    return fonts.get(file);
  }
}

// Usage
Typeface myFont = Fonts.get("arial.ttf");

(Note this code is untested, but in general this approach should work well.)

jQuery getJSON save result into variable

$.getJSon expects a callback functions either you pass it to the callback function or in callback function assign it to global variale.

var globalJsonVar;

    $.getJSON("http://127.0.0.1:8080/horizon-update", function(json){
               //do some thing with json  or assign global variable to incoming json. 
                globalJsonVar=json;
          });

IMO best is to call the callback function. which is nicer to eyes, readability aspects.

$.getJSON("http://127.0.0.1:8080/horizon-update", callbackFuncWithData);

function callbackFuncWithData(data)
{
 // do some thing with data 
}

Testing whether a value is odd or even

var isEven = function(number) {
    // Your code goes here!
    if (number % 2 == 0){
       return(true);
    }
    else{
       return(false);    
    }
};

How to make a vertical line in HTML

HTML5 custom elements (or pure CSS)

enter image description here

1. javascript

Register your element.

var vr = document.registerElement('v-r'); // vertical rule please, yes!

*The - is mandatory in all custom elements.

2. css

v-r {
    height: 100%;
    width: 1px;
    border-left: 1px solid gray;
    /*display: inline-block;*/    
    /*margin: 0 auto;*/
}

*You might need to fiddle a bit with display:inline-block|inline because inline won't expand to containing element's height. Use the margin to center the line within a container.

3. instantiate

js: document.body.appendChild(new vr());
or
HTML: <v-r></v-r>

*Unfortunately you can't create custom self-closing tags.

usage

 <h1>THIS<v-r></v-r>WORKS</h1>

enter image description here

example: http://html5.qry.me/vertical-rule


Don't want to mess with javascript?

Simply apply this CSS class to your designated element.

css

.vr {
    height: 100%;
    width: 1px;
    border-left: 1px solid gray;
    /*display: inline-block;*/    
    /*margin: 0 auto;*/
}

*See notes above.

How do I detect if a user is already logged in Firebase?

It is not possible to tell whether a user will be signed when a page starts loading, there is a work around though.

You can memorize last auth state to localStorage to persist it between sessions and between tabs.

Then, when page starts loading, you can optimistically assume the user will be re-signed in automatically and postpone the dialog until you can be sure (ie after onAuthStateChanged fires). Otherwise, if the localStorage key is empty, you can show the dialog right away.

The firebase onAuthStateChanged event will fire roughly 2 seconds after a page load.

// User signed out in previous session, show dialog immediately because there will be no auto-login
if (!localStorage.getItem('myPage.expectSignIn')) showDialog() // or redirect to sign-in page

firebase.auth().onAuthStateChanged(user => {
  if (user) {
    // User just signed in, we should not display dialog next time because of firebase auto-login
    localStorage.setItem('myPage.expectSignIn', '1')
  } else {
    // User just signed-out or auto-login failed, we will show sign-in form immediately the next time he loads the page
    localStorage.removeItem('myPage.expectSignIn')

    // Here implement logic to trigger the login dialog or redirect to sign-in page, if necessary. Don't redirect if dialog is already visible.
    // e.g. showDialog()
  }
})



I am using this with React and react-router. I put the code above into componentDidMount of my App root component. There, in the render, I have some PrivateRoutes

<Router>
  <Switch>
    <PrivateRoute
      exact path={routes.DASHBOARD}
      component={pages.Dashboard}
    />
...

And this is how my PrivateRoute is implemented:

export default function PrivateRoute(props) {
  return firebase.auth().currentUser != null
    ? <Route {...props}/>
    : localStorage.getItem('myPage.expectSignIn')
      // if user is expected to sign in automatically, display Spinner, otherwise redirect to login page.
      ? <Spinner centered size={400}/>
      : (
        <>
          Redirecting to sign in page.
          { location.replace(`/login?from=${props.path}`) }
        </>
      )
}

    // Using router Redirect instead of location.replace
    // <Redirect
    //   from={props.path}
    //   to={{pathname: routes.SIGN_IN, state: {from: props.path}}}
    // />

How to remove part of a string before a ":" in javascript?

There is no need for jQuery here, regular JavaScript will do:

var str = "Abc: Lorem ipsum sit amet";
str = str.substring(str.indexOf(":") + 1);

Or, the .split() and .pop() version:

var str = "Abc: Lorem ipsum sit amet";
str = str.split(":").pop();

Or, the regex version (several variants of this):

var str = "Abc: Lorem ipsum sit amet";
str = /:(.+)/.exec(str)[1];

Use virtualenv with Python with Visual Studio Code in Ubuntu

As of September 2016 (according to the GitHub repository documentation of the extension) you can just execute a command from within Visual Studio Code that will let you select the interpreter from an automatically generated list of known interpreters (including the one in your project's virtual environment).

How can I use this feature?

  • Select the command Python: Select Workspace Interpreter(*) from the command palette (F1).
  • Upon selecting the above command a list of discovered interpreters will be displayed in a quick pick list.
  • Selecting an interpreter from this list will update the settings.json file automatically.

(*) This command has been updated to Python: Select Interpreter in the latest release of Visual Studio Code (thanks @nngeek).

Also, notice that your selected interpreter will be shown at the left side of the statusbar, e.g., Python 3.6 64-bit. This is a button you can click to trigger the Select Interpreter feature.

Run Executable from Powershell script with parameters

Try quoting the argument list:

Start-Process -FilePath "C:\Program Files\MSBuild\test.exe" -ArgumentList "/genmsi/f $MySourceDirectory\src\Deployment\Installations.xml"

You can also provide the argument list as an array (comma separated args) but using a string is usually easier.

JavaFX Location is not set error message

That happened to me an i found the solution. If u build your project with your .fxml files in different packages from the class that has the launch line (Parent root = FXMLLoader.load(getClass().getResource("filenamehere.fxml"));) and use a relative path your windows except from the first one wont launch when your run the jar. To keep it short place the .fxml file in the same package with the class that launches it and set the path like this ("filenamehere.fxml") and it should work fine.

Convert a JSON Object to Buffer and Buffer to JSON Object back

You need to stringify the json, not calling toString

var buf = Buffer.from(JSON.stringify(obj));

And for converting string to json obj :

var temp = JSON.parse(buf.toString());

how to get program files x86 env variable?

On a 64-bit Windows system, the reading of the various environment variables and some Windows Registry keys is redirected to different sources, depending whether the process doing the reading is 32-bit or 64-bit.

The table below lists these data sources:

X = HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion
Y = HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion
Z = HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
     
READING ENVIRONMENT VARIABLES:    Source for 64-bit process               Source for 32-bit process
-------------------------------|----------------------------------------|--------------------------------------------------------------
                %ProgramFiles% :  X\ProgramW6432Dir                       X\ProgramFilesDir (x86)
           %ProgramFiles(x86)% :  X\ProgramFilesDir (x86)                 X\ProgramFilesDir (x86)
                %ProgramW6432% :  X\ProgramW6432Dir                       X\ProgramW6432Dir
     
          %CommonProgramFiles% :  X\CommonW6432Dir                        X\CommonFilesDir (x86)
     %CommonProgramFiles(x86)% :  X\CommonFilesDir (x86)                  X\CommonFilesDir (x86)
          %CommonProgramW6432% :  X\CommonW6432Dir                        X\CommonW6432Dir
     
                 %ProgramData% :  Z\ProgramData                           Z\ProgramData


      READING REGISTRY VALUES:    Source for 64-bit process               Source for 32-bit process
-------------------------------|----------------------------------------|--------------------------------------------------------------
             X\ProgramFilesDir :  X\ProgramFilesDir                       Y\ProgramFilesDir
       X\ProgramFilesDir (x86) :  X\ProgramFilesDir (x86)                 Y\ProgramFilesDir (x86)
            X\ProgramFilesPath :  X\ProgramFilesPath = %ProgramFiles%     Y\ProgramFilesPath = %ProgramFiles(x86)%
             X\ProgramW6432Dir :  X\ProgramW6432Dir                       Y\ProgramW6432Dir
     
              X\CommonFilesDir :  X\CommonFilesDir                        Y\CommonFilesDir
        X\CommonFilesDir (x86) :  X\CommonFilesDir (x86)                  Y\CommonFilesDir (x86)
              X\CommonW6432Dir :  X\CommonW6432Dir                        Y\CommonW6432Dir
     

So for example, for a 32-bit process, the source of the data for the %ProgramFiles% and %ProgramFiles(x86)% environment variables is the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir (x86).

However, for a 64-bit process, the source of the data for the %ProgramFiles% environment variable is the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramW6432Dir ...and the source of the data for the %ProgramFiles(x86)% environment variable is the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir (x86)

Most default Windows installation put a string like C:\Program Files (x86) into the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir (x86) but this (and others) can be changed.

Whatever is entered into these Windows Registry values will be read by Windows Explorer into respective Environment Variables upon login and then copied to any child process that it subsequently spawns.

The registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesPath is especially noteworthy because most Windows installations put the string %ProgramFiles% into it, to be read by 64-bit processes. This string refers to the environment variable %ProgramFiles% which in turn, takes its data from the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramW6432Dir ...unless some program changes the value of this environment variable apriori.

I have written a small utility, which displays these environment variables for 64-bit and 32-bit processes. You can download it here.
The source code for VisualStudio 2017 is included and the compiled 64-bit and 32-bit binary executables are in the directories ..\x64\Release and ..\x86\Release, respectively.

Limiting the number of characters per line with CSS

You could do this:
(Note! This is CSS3 and the browser support = good!! )

   p {
    text-overflow: ellipsis; /* will make [...] at the end */
    width: 370px; /* change to your preferences */
    white-space: nowrap; /* paragraph to one line */
    overflow:hidden; /* older browsers */
    }

Setting Oracle 11g Session Timeout

Adam has already suggested database profiles.

You could check the SQLNET.ORA file. There's an EXPIRE_TIME parameter but this is for detecting lost connections, rather than terminating existing ones.

Given it happens overnight, it sounds more like an idle timeout, which could be down to a firewall between the app server and database server. Setting the EXPIRE_TIME may stop that happening (as there'll be check every 10 minutes to check the client is alive).

Or possibly the database is being shutdown and restarted and that is killing the connections.

Alternatively, you should be able to configure tomcat with a validationQuery so that it will automatically restart the connection without a tomcat restart

Implementing a Custom Error page on an ASP.Net website

<system.webServer>     
<httpErrors errorMode="DetailedLocalOnly">
        <remove statusCode="404" subStatusCode="-1" />
        <error statusCode="404" prefixLanguageFilePath="" path="your page" responseMode="Redirect" />
    </httpErrors>
</system.webServer>

Mapping US zip code to time zone

I just found a free zip database that includes time offset and participation in DST. I do like Erik J's answer, as it would help me choose the actual time zone as opposed to just the offset (because you never can be completely sure on the rules), but I think I might start with this, and have it try to find the best time zone match based on offset/dst configuration. I think I may try to set up a simple version of Development 4.0's answer to check against what I get from the zip info as a sanity test. It's definitely not as simple as I'd hope, but a combination should get me at least 90% sure of a user's time zone.

Android custom dropdown/popup menu

I know this is an old question, but I've found another answer that worked better for me and it doesn't seem to appear in any of the answers.

Create a layout xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="5dip"
    android:paddingBottom="5dip"
    android:paddingStart="10dip"
    android:paddingEnd="10dip">

<ImageView
    android:id="@+id/shoe_select_icon"
    android:layout_width="30dp"
    android:layout_height="30dp"
    android:layout_gravity="center_vertical"
    android:scaleType="fitXY" />

<TextView
    android:id="@+id/shoe_select_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:textSize="20sp"
    android:paddingStart="10dp"
    android:paddingEnd="10dp"/>

</LinearLayout>

Create a ListPopupWindow and a map with the content:

ListPopupWindow popupWindow;
List<HashMap<String, Object>> data = new ArrayList<>();
HashMap<String, Object> map = new HashMap<>();
    map.put(TITLE, getString(R.string.left));
    map.put(ICON, R.drawable.left);
    data.add(map);
    map = new HashMap<>();
    map.put(TITLE, getString(R.string.right));
    map.put(ICON, R.drawable.right);
    data.add(map);

Then on click, display the menu using this function:

private void showListMenu(final View anchor) {
    popupWindow = new ListPopupWindow(this);

    ListAdapter adapter = new SimpleAdapter(
            this,
            data,
            R.layout.shoe_select,
            new String[] {TITLE, ICON}, // These are just the keys that the data uses (constant strings)
            new int[] {R.id.shoe_select_text, R.id.shoe_select_icon}); // The view ids to map the data to

    popupWindow.setAnchorView(anchor);
    popupWindow.setAdapter(adapter);
    popupWindow.setWidth(400);
    popupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switch (position){
                case 0:
                    devicesAdapter.setSelectedLeftPosition(devicesList.getChildAdapterPosition(anchor));
                    break;
                case 1:
                    devicesAdapter.setSelectedRightPosition(devicesList.getChildAdapterPosition(anchor));
                    break;
                default:
                    break;
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    devicesAdapter.notifyDataSetChanged();
                }
            });
            popupWindow.dismiss();
        }
    });
    popupWindow.show();
}

ES6 exporting/importing in index file

Install @babel/plugin-proposal-export-default-from via:

yarn add -D @babel/plugin-proposal-export-default-from

In your .babelrc.json or any of the Configuration File Types

module.exports = {
  //...
  plugins: [
     '@babel/plugin-proposal-export-default-from'
  ]
  //...
}

Now you can export directly from a file-path:

export Foo from './components/Foo'
export Bar from './components/Bar'

Good Luck...

What does a just-in-time (JIT) compiler do?

just-in-time (JIT) compilation, (also dynamic translation or run-time compilation), is a way of executing computer code that involves compilation during execution of a program – at run time – rather than prior to execution.

IT compilation is a combination of the two traditional approaches to translation to machine code – ahead-of-time compilation (AOT), and interpretation – and combines some advantages and drawbacks of both. JIT compilation combines the speed of compiled code with the flexibility of interpretation.

Let's consider JIT used in JVM,

For example, the HotSpot JVM JIT compilers generate dynamic optimizations. In other words, they make optimization decisions while the Java application is running and generate high-performing native machine instructions targeted for the underlying system architecture.

When a method is chosen for compilation, the JVM feeds its bytecode to the Just-In-Time compiler (JIT). The JIT needs to understand the semantics and syntax of the bytecode before it can compile the method correctly. To help the JIT compiler analyze the method, its bytecode are first reformulated in an internal representation called trace trees, which resembles machine code more closely than bytecode. Analysis and optimizations are then performed on the trees of the method. At the end, the trees are translated into native code.

A trace tree is a data structure that is used in the runtime compilation of programming code. Trace trees are used in a type of 'just in time compiler' that traces code executing during hotspots and compiles it. Refer this.

Refer :

How do I add a custom script to my package.json file that runs a javascript file?

Custom Scripts

npm run-script <custom_script_name>

or

npm run <custom_script_name>

In your example, you would want to run npm run-script script1 or npm run script1.

See https://docs.npmjs.com/cli/run-script

Lifecycle Scripts

Node also allows you to run custom scripts for certain lifecycle events, like after npm install is run. These can be found here.

For example:

"scripts": {
    "postinstall": "electron-rebuild",
},

This would run electron-rebuild after a npm install command.

Google Chrome redirecting localhost to https

A simple solution to this is to edit your /etc/hosts file and establish one alias per project.

127.0.0.1   project1 project2 project3

These domainless names will never have the problem with HSTS unless you send the HSTS response mentioned by @bigjump and with the added benefit of maintaining your login session if you change back and forth between projects.

Regex select all text between tags

Try this....

(?<=\<any_tag\>)(\s*.*\s*)(?=\<\/any_tag\>)

Open Bootstrap Modal from code-behind

Maybe this answer is so late, but it's useful.
to do it,we have 3 steps:
1- Create a modal structure in HTML.
2- Create a button to call a function in java script, to open modal and set display:none in CSS .
3- Call this button by function in code behind .
you can see these steps in below snippet :

HTML modal:

<div class="modal fade" id="myModal">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title">
                                Registration done Successfully</h4>
                        </div>
                        <div class="modal-body">
                            <asp:Label ID="lblMessage" runat="server" />
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">
                                Close</button>
                            <button type="button" class="btn btn-primary">
                                Save changes</button>
                        </div>
                    </div>
                    <!-- /.modal-content -->
                </div>
                <!-- /.modal-dialog -->
            </div>
            <!-- /.modal -->  

Hidden Button:

<button type="button" style="display: none;" id="btnShowPopup" class="btn btn-primary btn-lg"
                data-toggle="modal" data-target="#myModal">
                Launch demo modal
            </button>    

Script Code:

<script type="text/javascript">
        function ShowPopup() {
            $("#btnShowPopup").click();
        }
    </script>  

code behind:

protected void Page_Load(object sender, EventArgs e)
{
    ClientScript.RegisterStartupScript(this.GetType(), "alert", "ShowPopup();", true);
    this.lblMessage.Text = "Your Registration is done successfully. Our team will contact you shotly";
}  

this solution is one of any solutions that I used it .

python inserting variable string as file name

Very similar to peixe.
You don't have to mention the number if the variables you add as parameters are in order of appearance

f = open('{}.csv'.format(name), 'wb')

Another option - the f-string formatting (ref):

f = open(f"{name}.csv", 'wb') 

What does Docker add to lxc-tools (the userspace LXC tools)?

Dockers use images which are build in layers. This adds a lot in terms of portability, sharing, versioning and other features. These images are very easy to port or transfer and since they are in layers, changes in subsequent versions are added in form of layers over previous layers. So, while porting many a times you don't need to port the base layers. Dockers have containers which run these images with execution environment contained, they add changes as new layers providing easy version control.

Apart from that Docker Hub is a good registry with thousands of public images, where you can find images which have OS and other softwares installed. So, you can get a pretty good head start for your application.

The property 'Id' is part of the object's key information and cannot be modified

You should add

 db.Entry(contact).State = EntityState.Detached;

After the .SaveChanges();

How can you dynamically create variables via a while loop?

Use the exec() method. For example, say you have a dictionary and you want to turn each key into a variable with its original dictionary value can do the following.

Python 2

>>> c = {"one": 1, "two": 2}
>>> for k,v in c.iteritems():
...    exec("%s=%s" % (k,v))

>>> one
1
>>> two
2

Python 3

>>> c = {"one": 1, "two": 2}
>>> for k,v in c.items():
...    exec("%s=%s" % (k,v))

>>> one
1
>>> two
2

What's a good way to extend Error in JavaScript?

I would take a step back and consider why you want to do that? I think the point is to deal with different errors differently.

For example, in Python, you can restrict the catch statement to only catch MyValidationError, and perhaps you want to be able to do something similar in javascript.

catch (MyValidationError e) {
    ....
}

You can't do this in javascript. There's only going to be one catch block. You're supposed to use an if statement on the error to determine its type.

catch(e) { if(isMyValidationError(e)) { ... } else { // maybe rethrow? throw e; } }

I think I would instead throw a raw object with a type, message, and any other properties you see fit.

throw { type: "validation", message: "Invalid timestamp" }

And when you catch the error:

catch(e) {
    if(e.type === "validation") {
         // handle error
    }
    // re-throw, or whatever else
}

Accessing JSON object keys having spaces

The way to do this is via the bracket notation.

_x000D_
_x000D_
var test = {_x000D_
    "id": "109",_x000D_
    "No. of interfaces": "4"_x000D_
}_x000D_
alert(test["No. of interfaces"]);
_x000D_
_x000D_
_x000D_

For more info read out here:

Not able to change TextField Border Color

enabledBorder: OutlineInputBorder(
  borderRadius: BorderRadius.circular(10.0),
  borderSide: BorderSide(color: Colors.red)
),

Setting a log file name to include current date in Log4j

I'm 99% sure that RollingFileAppender/DailyRollingFileAppender, while it gives you the date-rolling functionality you want, doesn't have any way to specify that the current log file should use the DatePattern as well.

You might just be able to simply subclass RollingFileAppender (or DailyRollingFileAppender, I forget which is which in log4net) and modify the naming logic.

Customize UITableView header section

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    //put your values, this is part of my code
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 30.0f)];
    [view setBackgroundColor:[UIColor redColor]];
    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(20, 5, 150, 20)];
    [lbl setFont:[UIFont systemFontOfSize:18]];
    [lbl setTextColor:[UIColor blueColor]];
    [view addSubview:lbl];

    [lbl setText:[NSString stringWithFormat:@"Section: %ld",(long)section]];

    return view;
}

Updating the list view when the adapter data changes

I found a solution that is more efficient than currently accepted answer, because current answer forces all list elements to be refreshed. My solution will refresh only one element (that was touched) by calling adapters getView and recycling current view which adds even more efficiency.

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
      // Edit object data that is represented in Viewat at list's "position"
      view = mAdapter.getView(position, view, parent);
    }
});

Get Maven artifact version at runtime

To get this running in Eclipse, as well as in a Maven build, you should add the addDefaultImplementationEntries and addDefaultSpecificationEntries pom entries as described in other replies, then use the following code:

public synchronized static final String getVersion() {
    // Try to get version number from pom.xml (available in Eclipse)
    try {
        String className = getClass().getName();
        String classfileName = "/" + className.replace('.', '/') + ".class";
        URL classfileResource = getClass().getResource(classfileName);
        if (classfileResource != null) {
            Path absolutePackagePath = Paths.get(classfileResource.toURI())
                    .getParent();
            int packagePathSegments = className.length()
                    - className.replace(".", "").length();
            // Remove package segments from path, plus two more levels
            // for "target/classes", which is the standard location for
            // classes in Eclipse.
            Path path = absolutePackagePath;
            for (int i = 0, segmentsToRemove = packagePathSegments + 2;
                    i < segmentsToRemove; i++) {
                path = path.getParent();
            }
            Path pom = path.resolve("pom.xml");
            try (InputStream is = Files.newInputStream(pom)) {
                Document doc = DocumentBuilderFactory.newInstance()
                        .newDocumentBuilder().parse(is);
                doc.getDocumentElement().normalize();
                String version = (String) XPathFactory.newInstance()
                        .newXPath().compile("/project/version")
                        .evaluate(doc, XPathConstants.STRING);
                if (version != null) {
                    version = version.trim();
                    if (!version.isEmpty()) {
                        return version;
                    }
                }
            }
        }
    } catch (Exception e) {
        // Ignore
    }

    // Try to get version number from maven properties in jar's META-INF
    try (InputStream is = getClass()
        .getResourceAsStream("/META-INF/maven/" + MAVEN_PACKAGE + "/"
                + MAVEN_ARTIFACT + "/pom.properties")) {
        if (is != null) {
            Properties p = new Properties();
            p.load(is);
            String version = p.getProperty("version", "").trim();
            if (!version.isEmpty()) {
                return version;
            }
        }
    } catch (Exception e) {
        // Ignore
    }

    // Fallback to using Java API to get version from MANIFEST.MF
    String version = null;
    Package pkg = getClass().getPackage();
    if (pkg != null) {
        version = pkg.getImplementationVersion();
        if (version == null) {
            version = pkg.getSpecificationVersion();
        }
    }
    version = version == null ? "" : version.trim();
    return version.isEmpty() ? "unknown" : version;
}

If your Java build puts target classes somewhere other than "target/classes", then you may need to adjust the value of segmentsToRemove.

How to remove decimal values from a value of type 'double' in Java

the simple way to remove

new java.text.DecimalFormat("#").format(value)

React : difference between <Route exact path="/" /> and <Route path="/" />

The shortest answer is

Please try this.

<switch>
   <Route exact path="/" component={Home} />
   <Route path="/about" component={About} />
   <Route path="/shop" component={Shop} />
 </switch>

How to find the logs on android studio?

Hope this helps someone: on Mac OS X, the logs are within /Users/<user>/Library/Logs/AndroidStudio<version>/

CORS: credentials mode is 'include'

If it helps, I was using centrifuge with my reactjs app, and, after checking some comments below, I looked at the centrifuge.js library file, which in my version, had the following code snippet:

if ('withCredentials' in xhr) {
 xhr.withCredentials = true;
}

After I removed these three lines, the app worked fine, as expected.

Hope it helps!

How to insert close button in popover for Bootstrap

<script type="text/javascript"  src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript" src="jquery.popover-1.1.2.js"></script>

<script type="text/javascript">
$(function(){ 
$("#example").popover({
        placement: 'bottom',
        html: 'true',
        title : '<span class="text-info"><strong>title</strong></span> <button     type="button" id="close" class="close">&times;</button></span>',
        content : 'test'
    })


$("#close").click(function(event) {

$("#example").popover('hide');
});
});
</script>

<button type="button" id="example" class="btn btn-primary" >click</button>

'Operation is not valid due to the current state of the object' error during postback

Somebody posted quite a few form fields to your page. The new default max introduced by the recent security update is 1000.

Try adding the following setting in your web.config's <appsettings> block. in this block you are maximizing the MaxHttpCollection values this will override the defaults set by .net Framework. you can change the value accordingly as per your form needs

<appSettings>
    <add key="aspnet:MaxHttpCollectionKeys" value="2001" />
 </appSettings>

For more information please read this post. For more insight into the security patch by microsoft you can read this Knowledge base article

Bash Shell Script - Check for a flag and grab its value

Here is a generalized simple command argument interface you can paste to the top of all your scripts.

#!/bin/bash

declare -A flags
declare -A booleans
args=()

while [ "$1" ];
do
    arg=$1
    if [ "${1:0:1}" == "-" ]
    then
      shift
      rev=$(echo "$arg" | rev)
      if [ -z "$1" ] || [ "${1:0:1}" == "-" ] || [ "${rev:0:1}" == ":" ]
      then
        bool=$(echo ${arg:1} | sed s/://g)
        booleans[$bool]=true
        echo \"$bool\" is boolean
      else
        value=$1
        flags[${arg:1}]=$value
        shift
        echo \"$arg\" is flag with value \"$value\"
      fi
    else
      args+=("$arg")
      shift
      echo \"$arg\" is an arg
    fi
done


echo -e "\n"
echo booleans: ${booleans[@]}
echo flags: ${flags[@]}
echo args: ${args[@]}

echo -e "\nBoolean types:\n\tPrecedes Flag(pf): ${booleans[pf]}\n\tFinal Arg(f): ${booleans[f]}\n\tColon Terminated(Ct): ${booleans[Ct]}\n\tNot Mentioned(nm): ${boolean[nm]}"
echo -e "\nFlag: myFlag => ${flags["myFlag"]}"
echo -e "\nArgs: one: ${args[0]}, two: ${args[1]}, three: ${args[2]}"

By running the command:

bashScript.sh firstArg -pf -myFlag "my flag value" secondArg -Ct: thirdArg -f

The output will be this:

"firstArg" is an arg
"pf" is boolean
"-myFlag" is flag with value "my flag value"
"secondArg" is an arg
"Ct" is boolean
"thirdArg" is an arg
"f" is boolean


booleans: true true true
flags: my flag value
args: firstArg secondArg thirdArg

Boolean types:
    Precedes Flag(pf): true
    Final Arg(f): true
    Colon Terminated(Ct): true
    Not Mentioned(nm): 

Flag: myFlag => my flag value

Args: one => firstArg, two => secondArg, three => thirdArg

Basically, the arguments are divided up into flags booleans and generic arguments. By doing it this way a user can put the flags and booleans anywhere as long as he/she keeps the generic arguments (if there are any) in the specified order.

Allowing me and now you to never deal with bash argument parsing again!

You can view an updated script here

This has been enormously useful over the last year. It can now simulate scope by prefixing the variables with a scope parameter.

Just call the script like

replace() (
  source $FUTIL_REL_DIR/commandParser.sh -scope ${FUNCNAME[0]} "$@"
  echo ${replaceFlags[f]}
  echo ${replaceBooleans[b]}
)

Doesn't look like I implemented argument scope, not sure why I guess I haven't needed it yet.

Trying to handle "back" navigation button action in iOS

Perhaps this answers doesn't fit your explanation but question title. It's useful when you are trying to know when you tapped the back button on an UINavigationBar.

In this case you can use UINavigationBarDelegate protocol and implement one of this methods:

- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item;
- (void)navigationBar:(UINavigationBar *)navigationBar didPopItem:(UINavigationItem *)item;

When didPopItem method is called, it's because you either tapped the back button or you used [UINavigationBar popNavigationItemAnimated:] method and the navigation bar did pop the item.

Now, if you want to know what action triggered the didPopItem method you can use a flag.

With this approach I don't need to manually add a left bar button item with an arrow image in order to make it similar to iOS back button, and be able to set my custom target/action.


Let's see an example:

I have a view controller that has a page view controller, and a custom page indicator view. I'm also using a custom UINavigationBar to display a title to know on what page am I and the back button to go back to the previous page. And I also can swipe to previous/next page on page controller.

#pragma mark - UIPageViewController Delegate Methods
- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed {

    if( completed ) {

        //...

        if( currentIndex > lastIndex ) {

            UINavigationItem *navigationItem = [[UINavigationItem alloc] initWithTitle:@"Some page title"];

            [[_someViewController navigationBar] pushNavigationItem:navigationItem animated:YES];
            [[_someViewController pageControl] setCurrentPage:currentIndex];
        } else {
            _autoPop = YES; //We pop the item automatically from code.
            [[_someViewController navigationBar] popNavigationItemAnimated:YES];
            [[_someViewController pageControl] setCurrentPage:currentIndex];
        }
    }

}

So then I implement UINavigationBar delegate methods:

#pragma mark - UINavigationBar Delegate Methods
- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item {
    if( !_autoPop ) {
        //Pop by back button tap
    } else {
        //Pop from code
    }

    _autoPop = NO;

    return YES;
}

In this case I used shouldPopItem because the pop is animated and I wanted to handle the back button immediately and not to wait until transition is finished.

std::string length() and size() member functions

Ruby's just the same, btw, offering both #length and #size as synonyms for the number of items in arrays and hashes (C++ only does it for strings).

Minimalists and people who believe "there ought to be one, and ideally only one, obvious way to do it" (as the Zen of Python recites) will, I guess, mostly agree with your doubts, @Naveen, while fans of Perl's "There's more than one way to do it" (or SQL's syntax with a bazillion optional "noise words" giving umpteen identically equivalent syntactic forms to express one concept) will no doubt be complaining that Ruby, and especially C++, just don't go far enough in offering such synonymical redundancy;-).

Javascript can't find element by id?

The script is performed before the DOM of the body is built. Put it all into a function and call it from the onload of the body-element.

Is PowerShell ready to replace my Cygwin shell on Windows?

I have only recently started dabbling in PowerShell with any degree of seriousness. Although for the past seven years I've worked in an almost exclusively Windows-based environment, I come from a Unix background and find myself constantly trying to "Unix-fy" my interaction experience on Windows. It's frustrating to say the least.

It's only fair to compare PowerShell to something like Bash, tcsh, or zsh since utilities like grep, sed, awk, find, etc. are not, strictly speaking, part of the shell; they will always, however, be part of any Unix environment. That said, a PowerShell command like Select-String has a very similar function to grep and is bundled as a core module in PowerShell ... so the lines can be a little blurred.

I think the key thing is culture, and the fact that the respective tool-sets will embody their respective cultures:

  • Unix is a file-based, (in general, non Unicode) text-based culture. Configuration files are almost exclusively text files. Windows, on the other hand has always been far more structured in respect of configuration formats--configurations are generally kept in proprietary databases (e.g., the Windows registry) which require specialised tools for their management.
  • The Unix administrative (and, for many years, development) interface has traditionally been the command line and the virtual terminal. Windows started off as a GUI and administrative functions have only recently started moving away from being exclusively GUI-based. We can expect the Unix experience on the command line to be a richer, more mature one given the significant lead it has on PowerShell, and my experience matches this. On this, in my experience:

    • The Unix administrative experience is geared towards making things easy to do in a minimal amount of key strokes; this is probably as a result of the historical situation of having to administer a server over a slow 9600 baud dial-up connection. Now PowerShell does have aliases which go a long way to getting around the rather verbose Verb-Noun standard, but getting to know those aliases is a bit of a pain (anyone know of something better than: alias | where {$_.ResolvedCommandName -eq "<command>"}?).

      An example of the rich way in which history can be manipulated:

      iptables commands are often long-winded and repeating them with slight differences would be a pain if it weren't for just one of many neat features of history manipulation built into Bash, so inserting an iptables rule like the following:

      iptables -I camera-1-internet -s 192.168.0.50 -m state --state NEW -j ACCEPT

      a second time for another camera ("camera-2"), is just a case of issuing:

      !!:s/-1-/-2-/:s/50/51

      which means "perform the previous command, but substitute -1- with -2- and 50 with 51.

    • The Unix experience is optimised for touch-typists; one can pretty much do everything without leaving the "home" position. For example, in Bash, using the Emacs key bindings (yes, Bash also supports vi bindings), cycling through the history is done using Ctrl-P and Ctrl-N whilst moving to the start and end of a line is done using Ctrl-A and Ctrl-E respectively ... and it definitely doesn't end there. Try even the simplest of navigation in the PowerShell console without moving from the home position and you're in trouble.

    • Simple things like versatile paging (a la less) on Unix don't seem to be available out-of-the-box in PowerShell which is a little frustrating, and a rich editor experience doesn't exist either. Of course, one can always download third-party tools that will fill those gaps, but it sure would be nice if these things were just "there" like they are on pretty much any flavour of Unix.
  • The Windows culture, at least in terms of system API's is largely driven by the supporting frameworks, viz., COM and .NET, both of-which are highly structured and object-based. On the other hand, access to Unix APIs has traditionally been through a file interface (/dev and /proc) or (non-object-oriented) C-style library calls. It's no surprise then that the scripting experiences match their respective OS paradigms. PowerShell is by nature structured (everything is an object) and Bash-and-friends file-based. The structured API which is at the disposal of a PowerShell programmer is vast (essentially matching the vastness of the existing set of standard COM and .NET interfaces).

In short, although the scripting capabilities of PowerShell are arguably more powerful than Bash (especially when you consider the availability of the .NET BCL), the interactive experience is significantly weaker, particularly if you're coming at it from an entirely keyboard-driven, console-based perspective (as many Unix-heads are).

How to save username and password in Git?

just use

git config --global credential.helper store

and do the git pull, it will ask for username and password, from now on it will not provide any prompt for username and password it will store the details

How to set initial size of std::vector?

std::vector<CustomClass *> whatever(20000);

or:

std::vector<CustomClass *> whatever;
whatever.reserve(20000);

The former sets the actual size of the array -- i.e., makes it a vector of 20000 pointers. The latter leaves the vector empty, but reserves space for 20000 pointers, so you can insert (up to) that many without it having to reallocate.

At least in my experience, it's fairly unusual for either of these to make a huge difference in performance--but either can affect correctness under some circumstances. In particular, as long as no reallocation takes place, iterators into the vector are guaranteed to remain valid, and once you've set the size/reserved space, you're guaranteed there won't be any reallocations as long as you don't increase the size beyond that.

Border in shape xml

If you want make a border in a shape xml. You need to use:

For the external border,you need to use:

<stroke/>

For the internal background,you need to use:

<solid/>

If you want to set corners,you need to use:

<corners/>

If you want a padding betwen border and the internal elements,you need to use:

<padding/>

Here is a shape xml example using the above items. It works for me

<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
  <stroke android:width="2dp" android:color="#D0CFCC" /> 
  <solid android:color="#F8F7F5" /> 
  <corners android:radius="10dp" />
  <padding android:left="2dp" android:top="2dp" android:right="2dp" android:bottom="2dp" />
</shape>

How to check encoding of a CSV file

If you use Python, just use a print() function to check the encoding of a csv file. For example:

with open('file_name.csv') as f:
    print(f)

The output is something like this:

<_io.TextIOWrapper name='file_name.csv' mode='r' encoding='utf8'>

How to globally replace a forward slash in a JavaScript string?

The following would do but only will replace one occurence:

"string".replace('/', 'ForwardSlash');

For a global replacement, or if you prefer regular expressions, you just have to escape the slash:

"string".replace(/\//g, 'ForwardSlash');

Get GPS location from the web browser

Observable

/*
  function geo_success(position) {
    do_something(position.coords.latitude, position.coords.longitude);
  }

  function geo_error() {
    alert("Sorry, no position available.");
  }

  var geo_options = {
    enableHighAccuracy: true,
    maximumAge        : 30000,
    timeout           : 27000
  };

  var wpid = navigator.geolocation.watchPosition(geo_success, geo_error, geo_options);
  */
  getLocation(): Observable<Position> {
    return Observable.create((observer) => {
      const watchID = navigator.geolocation.watchPosition((position: Position) => {
        observer.next(position);
      });
      return () => {
        navigator.geolocation.clearWatch(watchID);
      };
    });
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }

How to bind Close command to a button

One option that I've found to work is to set this function up as a Behavior.

The Behavior:

    public class WindowCloseBehavior : Behavior<Window>
{
    public bool Close
    {
        get { return (bool) GetValue(CloseTriggerProperty); }
        set { SetValue(CloseTriggerProperty, value); }
    }

    public static readonly DependencyProperty CloseTriggerProperty =
        DependencyProperty.Register("Close", typeof(bool), typeof(WindowCloseBehavior),
            new PropertyMetadata(false, OnCloseTriggerChanged));

    private static void OnCloseTriggerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var behavior = d as WindowCloseBehavior;

        if (behavior != null)
        {
            behavior.OnCloseTriggerChanged();
        }
    }

    private void OnCloseTriggerChanged()
    {
        // when closetrigger is true, close the window
        if (this.Close)
        {
            this.AssociatedObject.Close();
        }
    }
}

On the XAML Window, you set up a reference to it and bind the Behavior's Close property to a Boolean "Close" property on your ViewModel:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
<i:Interaction.Behaviors>
    <behavior:WindowCloseBehavior Close="{Binding Close}" />
</i:Interaction.Behaviors>

So, from the View assign an ICommand to change the Close property on the ViewModel which is bound to the Behavior's Close property. When the PropertyChanged event is fired the Behavior fires the OnCloseTriggerChanged event and closes the AssociatedObject... which is the Window.

Android - border for button

Step 1 : Create file named : my_button_bg.xml

Step 2 : Place this file in res/drawables.xml

Step 3 : Insert below code

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
  android:shape="rectangle">
  <gradient android:startColor="#FFFFFF" 
    android:endColor="#00FF00"
    android:angle="270" />
  <corners android:radius="3dp" />
  <stroke android:width="5px" android:color="#000000" />
</shape>

Step 4: Use code "android:background="@drawable/my_button_bg" where needed eg below:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Your Text"
    android:background="@drawable/my_button_bg"
    />

CSS display:inline property with list-style-image: property on <li> tags

You want the list items to line up next to each other, but not really be inline elements. So float them instead:

ol.widgets li { 
    float: left;
    margin-left: 10px;
}

Check if a file exists with wildcard in shell script

Here's a solution for your specific problem that doesn't require for loops or external commands like ls, find and the like.

if [ "$(echo xorg-x11-fonts*)" != "xorg-x11-fonts*" ]; then
    printf "BLAH"
fi

As you can see, it's just a tad more complicated than what you were hoping for, and relies on the fact that if the shell is not able to expand the glob, it means no files with that glob exist and echo will output the glob as is, which allows us to do a mere string comparison to check whether any of those files exist at all.

If we were to generalize the procedure, though, we should take into account the fact that files might contain spaces within their names and/or paths and that the glob char could rightfully expand to nothing (in your example, that would be the case of a file whose name is exactly xorg-x11-fonts).

This could be achieved by the following function, in bash.

function doesAnyFileExist {
   local arg="$*"
   local files=($arg)
   [ ${#files[@]} -gt 1 ] || [ ${#files[@]} -eq 1 ] && [ -e "${files[0]}" ]
}

Going back to your example, it could be invoked like this.

if doesAnyFileExist "xorg-x11-fonts*"; then
    printf "BLAH"
fi

Glob expansion should happen within the function itself for it to work properly, that's why I put the argument in quotes and that's what the first line in the function body is there for: so that any multiple arguments (which could be the result of a glob expansion outside the function, as well as a spurious parameter) would be coalesced into one. Another approach could be to raise an error if there's more than one argument, yet another could be to ignore all but the 1st argument.

The second line in the function body sets the files var to an array constituted by all the file names that the glob expanded to, one for each array element. It's fine if the file names contain spaces, each array element will contain the names as is, including the spaces.

The third line in the function body does two things:

  1. It first checks whether there's more than one element in the array. If so, it means the glob surely got expanded to something (due to what we did on the 1st line), which in turn implies that at least one file matching the glob exist, which is all we wanted to know.

  2. If at step 1. we discovered that we got less than 2 elements in the array, then we check whether we got one and if so we check whether that one exist, the usual way. We need to do this extra check in order to account for function arguments without glob chars, in which case the array contains only one, unexpanded, element.

Flask-SQLAlchemy how to delete all rows in a single table

DazWorrall's answer is spot on. Here's a variation that might be useful if your code is structured differently than the OP's:

num_rows_deleted = db.session.query(Model).delete()

Also, don't forget that the deletion won't take effect until you commit, as in this snippet:

try:
    num_rows_deleted = db.session.query(Model).delete()
    db.session.commit()
except:
    db.session.rollback()

Firebug like plugin for Safari browser

Firebug is great, but Safari provides its own built-in development tools.

If you haven't already tried Safari's development kit, go to Safari-->Preferences-->Advanced, and check the box next to "Show Develop menu in menu bar".

Once you have the Develop menu enabled, you can use the Web Inspector to get a lot of the same functionality that Firebug provides.

How to solve a timeout error in Laravel 5

I had a similar problem just now. However, this had nothing to do with modifying the php.ini file. It was from a for loop. If you are having nested for loops, make sure you are using the iterator properly. In my case, I was iterating the outer iterator from my inner iterator.

C# adding a character in a string

You can use this:

string alpha = "abcdefghijklmnopqrstuvwxyz";
int length = alpha.Length;

for (int i = length - ((length - 1) % 5 + 1); i > 0; i -= 5)
{
    alpha = alpha.Insert(i, "-");
}

Works perfectly with any string. As always, the size doesn't matter. ;)

Javascript: 'window' is not defined

Trying to access an undefined variable will throw you a ReferenceError.

A solution to this is to use typeof:

if (typeof window === "undefined") {
  console.log("Oops, `window` is not defined")
}

or a try catch:

try { window } catch (err) {
  console.log("Oops, `window` is not defined")
}

While typeof window is probably the cleanest of the two, the try catch can still be useful in some cases.

How do I measure execution time of a command on the Windows command line?

This is a comment/edit to Luke Sampson's nice timecmd.bat and reply to

For some reason this only gives me output in whole seconds... which for me is useless. I mean that I run timecmd pause, and it always results in 1.00 sec, 2.00 sec, 4.00 sec... even 0.00 sec! Windows 7. – Camilo Martin Sep 25 '13 at 16:00 "

On some configurations the delimiters may differ. The following change should cover atleast most western countries.

set options="tokens=1-4 delims=:,." (added comma)

The %time% milliseconds work on my system after adding that ','

(*because site doesn't allow anon comment and doesn't keep good track of identity even though I always use same guest email which combined with ipv6 ip and browser fingerprint should be enough to uniquely identify without password)

Inject service in app.config

Easiest way: $injector = angular.element(document.body).injector()

Then use that to run invoke() or get()

INSERT statement conflicted with the FOREIGN KEY constraint - SQL Server

I also got the same error in my SQL Code, This solution works for me,


Check the data in Primary Table May be you are entering a column value which is not present in the primary key column.

How to access cookies in AngularJS?

Add angular cookie lib : angular-cookies.js

You can use $cookies or $cookieStore parameter to the respective controller

Main controller add this inject 'ngCookies':

angular.module("myApp", ['ngCookies']);

Use Cookies in your controller like this way:

 app.controller('checkoutCtrl', function ($scope, $rootScope, $http, $state, $cookies) { 

//store cookies

 $cookies.putObject('final_total_price', $rootScope.fn_pro_per);

//Get cookies

 $cookies.getObject('final_total_price'); }

How to check whether an object has certain method/property?

It is an old question, but I just ran into it. Type.GetMethod(string name) will throw an AmbiguousMatchException if there is more than one method with that name, so we better handle that case

public static bool HasMethod(this object objectToCheck, string methodName)
{
    try
    {
        var type = objectToCheck.GetType();
        return type.GetMethod(methodName) != null;
    }
    catch(AmbiguousMatchException)
    {
        // ambiguous means there is more than one result,
        // which means: a method with that name does exist
        return true;
    }
} 

Is object empty?

EDIT: Note that you should probably use ES5 solution instead of this since ES5 support is widespread these days. It still works for jQuery though.


Easy and cross-browser way is by using jQuery.isEmptyObject:

if ($.isEmptyObject(obj))
{
    // do something
}

More: http://api.jquery.com/jQuery.isEmptyObject/

You need jquery though.

Comparing two hashmaps for equal values and same key sets?

public boolean compareMap(Map<String, String> map1, Map<String, String> map2) {

    if (map1 == null || map2 == null)
        return false;

    for (String ch1 : map1.keySet()) {
        if (!map1.get(ch1).equalsIgnoreCase(map2.get(ch1)))
            return false;

    }
    for (String ch2 : map2.keySet()) {
        if (!map2.get(ch2).equalsIgnoreCase(map1.get(ch2)))
            return false;

    }

    return true;
}

Get a list of numbers as input from the user

You can use .split()

numbers = raw_input().split(",")
print len(numbers)

This will still give you strings, but it will be a list of strings.

If you need to map them to a type, use list comprehension:

numbers = [int(n, 10) for n in raw_input().split(",")]
print len(numbers)

If you want to be able to enter in any Python type and have it mapped automatically and you trust your users IMPLICITLY then you can use eval

Convert a PHP script into a stand-alone windows executable

The current PHP Nightrain (4.0.0) is written in Python and it uses the wxPython libraries. So far wxPython has been working well to get PHP Nightrain where it is today but in order to push PHP Nightrain to its next level, we are introducing a sibling of PHP Nightrain, the PHPWebkit!

It's an update to PHP Nightrain.

https://github.com/entrypass/nightrain-ep

How to merge many PDF files into a single one?

First, get Pdftk:

sudo apt-get install pdftk

Now, as shown on example page, use

pdftk 1.pdf 2.pdf 3.pdf cat output 123.pdf

for merging pdf files into one.

How can I update my ADT in Eclipse?

I viewed the Eclipse ADT documentation and found out the way to get around this issue. I was able to Update My SDK Tool to 22.0.4 (Latest Version).

Solution is: First Update ADT to 22.0.4 and then Update SDK Tool to 22.0.4

The above link says,

ADT 22.0.4 is designed for use with SDK Tools r22.0.4. If you haven't already installed SDK Tools r22.0.4 into your SDK, use the Android SDK Manager to do so

What I had to do was update my ADT to 22.0.4 (Latest Version) and then I was able to update SDK tool to 22.0.4. I thought only SDK Tool has been updated not ADT, so I was updating the SDK Tool with Older ADT Version (22.0.1).

How to Update your ADT to Latest Version

  1. In Eclipse go to Help

  2. Install New Software ---> Add

  3. inside Add Repository write the Name: ADT (or whatever you want)

  4. Location: https://dl-ssl.google.com/android/eclipse/

  5. after loading you should get Developer Tools and NDK Plugins

  6. check both if you want to use the Native Developer Kit (NDK) in the future or check

  7. Developer Tool only

  8. click Next

  9. Finish

How do I use the CONCAT function in SQL Server 2008 R2?

NULL safe drop in replacement approximations for SQL Server 2012 CONCAT function

SQL Server 2012:

SELECT CONCAT(data1, data2)

PRE SQL 2012 (Two Solutions):

SELECT {fn CONCAT(ISNULL(data1, ''), ISNULL(data2, ''))}

SELECT ISNULL(CAST(data1 AS varchar(MAX)), '') + ISNULL(CAST(data2 AS varchar(MAX)), '')

These two solutions collate several excellent answers and caveats raised by other posters including @Martin Smith, @Svish and @vasin1987.

These options add NULL to '' (empty string) casting for safe NULL handling while accounting for the varying behaviour of the + operator pertaining to specific operands.

Note the ODBC Scaler Function solution is limited to 2 arguments whereas the + operator approach is scalable to many arguments as needed.

Note also the potential issue identified by @Swifty regarding the default varchar size here remedied by varchar(MAX).

npm - how to show the latest version of a package

The npm view <pkg> version prints the last version by release date. That might very well be an hotfix release for a older stable branch at times.

The solution is to list all versions and fetch the last one by version number

$ npm view <pkg> versions --json | jq -r '.[-1]'

Or with awk instead of jq:

$ npm view <pkg> --json  | awk '/"$/{print gensub("[ \"]", "", "G")}'

MySQL error - #1062 - Duplicate entry ' ' for key 2

you can try adding

$db['db_debug'] = FALSE; 

in "your database file".php after that you can modify your database as you like.

How to set up fixed width for <td>?

use fixed table layout css in table, and set a percent of the td.

Shortest way to check for null and assign another value if not

Use the C# coalesce operator: ??

// if Value is not null, newValue = Value else if Value is null newValue is YournullValue
var newValue = Value ?? YourNullReplacement;

When creating a service with sc.exe how to pass in context parameters?

It also important taking in account how you access the Arguments in the code of the application.

In my c# application I used the ServiceBase class:

 class MyService : ServiceBase
{

    protected override void OnStart(string[] args)
    {
       }
 }

I registered my service using

sc create myService binpath= "MeyService.exe arg1 arg2"

But I couldn't access the arguments through the args variable when I run it as a service.

The MSDN documentation suggests not using the Main method to retrieve the binPath or ImagePath arguments. Instead it suggests placing your logic in the OnStart method and then using (C#) Environment.GetCommandLineArgs();.

To access the first arguments arg1 I need to do like this:

class MyService : ServiceBase
 {

    protected override void OnStart(string[] args)
    {

                log.Info("arg1 == "+Environment.GetCommandLineArgs()[1]);

       }
 }

this would print

       arg1 == arg1

How to set the action for a UIBarButtonItem in Swift

Swift 5

if you have created UIBarButtonItem in Interface Builder and you connected outlet to item and want to bind selector programmatically.

Don't forget to set target and selector.

addAppointmentButton.action = #selector(moveToAddAppointment)
addAppointmentButton.target = self

@objc private func moveToAddAppointment() {
     self.presenter.goToCreateNewAppointment()
}

In Postgresql, force unique on combination of two columns

CREATE TABLE someTable (
    id serial PRIMARY KEY,
    col1 int NOT NULL,
    col2 int NOT NULL,
    UNIQUE (col1, col2)
)

autoincrement is not postgresql. You want a serial.

If col1 and col2 make a unique and can't be null then they make a good primary key:

CREATE TABLE someTable (
    col1 int NOT NULL,
    col2 int NOT NULL,
    PRIMARY KEY (col1, col2)
)

Best practices for circular shift (rotate) operations in C++

#define ROTATE_RIGHT(x) ( (x>>1) | (x&1?0x8000:0) )

How to use tick / checkmark symbol (?) instead of bullets in unordered list?

Here are three different checkmark styles you can use:

_x000D_
_x000D_
ul:first-child  li:before { content:"\2713\0020"; }  /* OR */_x000D_
ul:nth-child(2) li:before { content:"\2714\0020"; }  /* OR */_x000D_
ul:last-child   li:before { content:"\2611\0020"; }_x000D_
ul { list-style-type: none; }
_x000D_
<ul>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
</ul>_x000D_
_x000D_
<ul>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
</ul>_x000D_
_x000D_
<ul><!-- not working on Stack snippet; check fiddle demo -->_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

jsFiddle

References:

What are XAND and XOR

First comes the logic, then the name, possibly patterned on previous naming.

Thus 0+0=0; 0+1=1; 1+0=1; 1+1=1 - for some reason this is called OR.

Then 0-0=0; 0-1=1; 1-0=1; 1-1=0 - it looks like OR except ... let's call it XOR.

Also 0*0=0; 0*1=0; 1*0=0; 1*1=1 - for some reason this is called AND.

Then 0~0=0; 0~1=0; 1~0=0; 1~1=0 - it looks like AND except ... let's call it XAND.

Eclipse - Failed to load class "org.slf4j.impl.StaticLoggerBinder"

Eclipse Juno, Indigo and Kepler when using the bundled maven version(m2e), are not suppressing the message SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". This behaviour is present from the m2e version 1.1.0.20120530-0009 and onwards.

Although, this is indicated as an error your logs will be saved normally. The highlighted error will still be present until there is a fix of this bug. More about this in the m2e support site.

The current available solution is to use an external maven version rather than the bundled version of Eclipse. You can find about this solution and more details regarding this bug in the question below which i believe describes the same problem you are facing.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

Property getters and setters

I don't know if it is good practice but you can do something like this:

class test_ancestor {
    var prop: Int = 0
}


class test: test_ancestor {
    override var prop: Int {
        get {
            return super.prop // reaching ancestor prop
        }
        set {
            super.prop = newValue * 2
        }
    }
}

var test_instance = test()
test_instance.prop = 10

print(test_instance.prop) // 20

Read more

How to round up value C# to the nearest integer?

The .NET framework uses banker's rounding in Math.Round by default. You should use this overload:

Math.Round(0.5d, MidpointRounding.AwayFromZero)  //1
Math.Round(0.4d, MidpointRounding.AwayFromZero)  //0

How do I create and read a value from cookie?

The chrome team has proposed a new way of managing cookies asynchronous with the Cookie Storage API (available in Google Chrome starting from version 87): https://wicg.github.io/cookie-store/

Use it already today with a polyfill for the other browsers: https://github.com/mkay581/cookie-store

// load polyfill
import 'cookie-store';

// set a cookie
await cookieStore.set('name', 'value');
// get a cookie
const savedValue = await cookieStore.get('name');

How to change the color of progressbar in C# .NET 3.5?

OK, it took me a while to read all the answers and links. Here's what I got out of them:

Sample Results

The accepted answer disables visual styles, it does allow you to set the color to anything you want, but the result looks plain:

enter image description here

Using the following method, you can get something like this instead:

enter image description here

How To

First, include this if you haven't: using System.Runtime.InteropServices;

Second, you can either create this new class, or put its code into an existing static non-generic class:

public static class ModifyProgressBarColor
{
    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
    static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr w, IntPtr l);
    public static void SetState(this ProgressBar pBar, int state)
    {
        SendMessage(pBar.Handle, 1040, (IntPtr)state, IntPtr.Zero);
    }
}

Now, to use it, simply call:

progressBar1.SetState(2);

Note the second parameter in SetState, 1 = normal (green); 2 = error (red); 3 = warning (yellow).

Hope it helps!

HTML Canvas Full Screen

The newest Chrome and Firefox support a fullscreen API, but setting to fullscreen is like a window resize. Listen to the onresize-Event of the window-object:

$(window).bind("resize", function(){
    var w = $(window).width();
    var h = $(window).height();

    $("#mycanvas").css("width", w + "px");
    $("#mycanvas").css("height", h + "px"); 
});

//using HTML5 for fullscreen (only newest Chrome + FF)
$("#mycanvas")[0].webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT); //Chrome
$("#mycanvas")[0].mozRequestFullScreen(); //Firefox

//...

//now i want to cancel fullscreen
document.webkitCancelFullScreen(); //Chrome
document.mozCancelFullScreen(); //Firefox

This doesn't work in every browser. You should check if the functions exist or it will throw an js-error.

for more info on html5-fullscreen check this: http://updates.html5rocks.com/2011/10/Let-Your-Content-Do-the-Talking-Fullscreen-API

Converting a char to uppercase

Have a look at the java.lang.Character class, it provides a lot of useful methods to convert or test chars.

Custom format for time command

To use the Bash builtin time rather than /bin/time you can set this variable:

TIMEFORMAT='%3R'

which will output the real time that looks like this:

5.009

or

65.233

The number specifies the precision and can range from 0 to 3 (the default).

You can use:

TIMEFORMAT='%3lR'

to get output that looks like:

3m10.022s

The l (ell) gives a long format.

How to use Session attributes in Spring-mvc

SessionAttribute annotation is the simplest and straight forward instead of getting session from request object and setting attribute. Any object can be added to the model in controller and it will stored in session if its name matches with the argument in @SessionAttributes annotation. In below eg, personObj will be available in session.

@Controller
@SessionAttributes("personObj")
public class PersonController {

    @RequestMapping(value="/person-form")
    public ModelAndView personPage() {
        return new ModelAndView("person-page", "person-entity", new Person());
    }

    @RequestMapping(value="/process-person")
    public ModelAndView processPerson(@ModelAttribute Person person) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("person-result-page");

        modelAndView.addObject("pers", person);
        modelAndView.addObject("personObj", person);

        return modelAndView;
    }

}

How to save the output of a console.log(object) to a file?

You can use the Chrome DevTools Utilities API copy() command for copying the string representation of the specified object to the clipboard.

If you have lots of objects then you can actually JSON.stringify() all your objects and keep on appending them to a string. Now use copy() method to copy the complete string to clipboard.

Array initialization in Perl

If I understand you, perhaps you don't need an array of zeroes; rather, you need a hash. The hash keys will be the values in the other array and the hash values will be the number of times the value exists in the other array:

use strict;
use warnings;

my @other_array = (0,0,0,1,2,2,3,3,3,4);
my %tallies;
$tallies{$_} ++ for @other_array;

print "$_ => $tallies{$_}\n" for sort {$a <=> $b} keys %tallies;    

Output:

0 => 3
1 => 1
2 => 2
3 => 3
4 => 1

To answer your specific question more directly, to create an array populated with a bunch of zeroes, you can use the technique in these two examples:

my @zeroes = (0) x 5;            # (0,0,0,0,0)

my @zeroes = (0) x @other_array; # A zero for each item in @other_array.
                                 # This works because in scalar context
                                 # an array evaluates to its size.

Scanner vs. BufferedReader

Scanner is used for parsing tokens from the contents of the stream while BufferedReader just reads the stream and does not do any special parsing.

In fact you can pass a BufferedReader to a scanner as the source of characters to parse.

Android SDK is missing, out of date, or is missing templates. Please ensure you are using SDK version 22 or later

Here's a better approach where you don't have to delete/move anything for Android Studio 3.+.

  1. Open Android Studio and click cancel/ignore for error prompts on missing SDK for each project.
  2. Close all your open projects. You can do this by File > Close Project.
  3. After you do step 1 for all projects, the Welcome screen appears.
  4. The welcome screen will detect you are missing the SDK and give you options to fix the problem, i.e., install the SDKs for you.

Reading a binary file with python

In general, I would recommend that you look into using Python's struct module for this. It's standard with Python, and it should be easy to translate your question's specification into a formatting string suitable for struct.unpack().

Do note that if there's "invisible" padding between/around the fields, you will need to figure that out and include it in the unpack() call, or you will read the wrong bits.

Reading the contents of the file in order to have something to unpack is pretty trivial:

import struct

data = open("from_fortran.bin", "rb").read()

(eight, N) = struct.unpack("@II", data)

This unpacks the first two fields, assuming they start at the very beginning of the file (no padding or extraneous data), and also assuming native byte-order (the @ symbol). The Is in the formatting string mean "unsigned integer, 32 bits".

Write lines of text to a file in R

In newer versions of R, writeLines will preserve returns and spaces in your text, so you don't need to include \n at the end of lines and you can write one big chunk of text to a file. This will work with the example,

txt <- "Hello
World"
fileConn<-file("output.txt")
writeLines(txt, fileConn)
close(fileConn)

But you could also use this setup to simply include text with structure (linebreaks or indents)

txt <- "Hello
   world
 I can 
   indent text!"
fileConn<-file("output.txt")
writeLines(txt, fileConn)
close(fileConn)

How to view hierarchical package structure in Eclipse package explorer

Package Explorer / View Menu / Package Presentation... / Hierarchical

The "View Menu" can be opened with Ctrl + F10, or the small arrow-down icon in the top-right corner of the Package Explorer.

base 64 encode and decode a string in angular (2+)

Use the btoa() function to encode:

_x000D_
_x000D_
console.log(btoa("password")); // cGFzc3dvcmQ=
_x000D_
_x000D_
_x000D_

To decode, you can use the atob() function:

_x000D_
_x000D_
console.log(atob("cGFzc3dvcmQ=")); // password
_x000D_
_x000D_
_x000D_

How do I determine the current operating system with Node.js

With Node.js v6 (and above) there is a dedicated os module, which provides a number of operating system-related utility methods.

On my Windows 10 machine it reports the following:

var os = require('os');

console.log(os.type()); // "Windows_NT"
console.log(os.release()); // "10.0.14393"
console.log(os.platform()); // "win32"

You can read it's full documentation here: https://nodejs.org/api/os.html#os_os_type

Downloading all maven dependencies to a directory NOT in repository?

I found the next command

mvn dependency:copy-dependencies -Dclassifier=sources

here maven.apache.org

Node.js: printing to console without a trailing newline?

In Windows console (Linux, too), you should replace '\r' with its equivalent code \033[0G:

process.stdout.write('ok\033[0G');

This uses a VT220 terminal escape sequence to send the cursor to the first column.

Python SQL query string formatting

Cleanest way I have come across is inspired by the sql style guide.

sql = """
    SELECT field1, field2, field3, field4
      FROM table
     WHERE condition1 = 1
       AND condition2 = 2;
"""

Essentially, the keywords that begin a clause should be right-aligned and the field names etc, should be left aligned. This looks very neat and is easier to debug as well.

To switch from vertical split to horizontal split fast in Vim

When you have two or more windows open horizontally or vertically and want to switch them all to the other orientation, you can use the following:

(switch to horizontal)

:windo wincmd K

(switch to vertical)

:windo wincmd H

It's effectively going to each window individually and using ^WK or ^WH.