Programs & Examples On #Openfeint

A social gaming platform for Android and iOS. It was discontinued in 2012.

Why is there no Constant feature in Java?

There would be two ways to define constants - const and static final, with the exact same semantics. Furthermore static final describes the behaviour better than const

Find out time it took for a python script to complete execution

Use the timeit module. It's very easy. Run your file so it is active in the Python Shell, you should now be able to call your function in the shell. Try it out to check it works


Good, that works, now import timeit and set up a timer

>>>import timeit
>>>t = timeit.Timer('','import example')

Now we have our timer set up we can see how long it takes

some number here

And there we go, it will tell you how many seconds (or less) it took to execute that function. If it's a simple function then you can increase it to t.timeit(number=1000) (or any number!) and then divide the answer by the number to get the average.

I hope this helps.

How to return value from function which has Observable subscription inside?

If you want to pre-subscribe to the same Observable which will be returned, just use


function getValueFromObservable() {
        (data:any) => {
            console.log("Line 1: " +data);

        (data:any) => {
            console.log("Line 2: " +data)

How to install Python packages from the tar.gz file without using pip install

Is it possible for you to use sudo apt-get install python-seaborn instead? Basically tar.gz is just a zip file containing a setup, so what you want to do is to unzip it, cd to the place where it is downloaded and use gunzip -c seaborn-0.7.0.tar.gz | tar xf - for linux. Change dictionary into the new seaborn unzipped file and execute python install

java: ArrayList - how can I check if an index exists?

Regarding your update (which probably should be another question). You should use an array of these objects instead an ArrayList, so you can simply check the value for null:

Object[] array = new Object[MAX_ENTRIES];
if ( array[ 8 ] == null ) {
   // not available
else {
   // do something


If you don't have hundred of entries in your array you should consider organizing it as a class to get rid of the magic numbers 3,8 etc.

Control flow using exception is bad practice.

Add text to textarea - Jquery

That should work. Better if you pass a function to val:

$('#replyBox').val(function(i, text) {
    return text + quote;

This way you avoid searching the element and calling val twice.

What is a good game engine that uses Lua?

I can second the previous posters enthusiasm for the Gideros Lua game engine, whilst focusing currently on Mobile (iOS and Android - Windows phone 8 is in the works), desktop support for Mac, PC (possibly Linux) is also planned for the not too distant future.

Google for "Gideros Mobile"

How to switch to another domain and get-aduser

get-aduser -Server "servername" -Identity %username% -Properties *

get-aduser -Server "" -Identity testuser -Properties *

These work when you have the username. Also less to type than using the -filter property.

EDIT: Formatting.

How to write LaTeX in IPython Notebook?

This came up in a search I was just doing, found a better solution with some more searching, IPython notebooks now have a %%latex magic that makes the whole cell Latex without the $$ wrapper for each line.

Refer notebook tour for Rich Display System

How to check for null in a single statement in scala?

Although I'm sure @Ben Jackson's asnwer with Option(getObject).foreach is the preferred way of doing it, I like to use an AnyRef pimp that allows me to write:

getObject ifNotNull ( QueueManager.add(_) )

I find it reads better.

And, in a more general way, I sometimes write

val returnVal = getObject ifNotNull { obj =>
} otherwise {

... replacing ifNotNull with ifSome if I'm dealing with an Option. I find it clearer than first wrapping in an option and then pattern-matching it.

(For the implementation, see Implementing ifTrue, ifFalse, ifSome, ifNone, etc. in Scala to avoid if(...) and simple pattern matching and the Otherwise0/Otherwise1 classes.)

When using .net MVC RadioButtonFor(), how do you group so only one selection can be made?

In cases where the name attribute is different it is easiest to control the radio group via JQuery. When an option is selected use JQuery to un-select the other options.

HTML Table cell background image alignment

This works in IE9 (Compatibility View and Normal Mode), Firefox 17, and Chrome 23:

        <td style="background-image:url(untitled.png); background-position:right 0px; background-repeat:no-repeat;">
            Hello World

How to find my realm file?

What I did was to use

let realm = Realm(path: "/Users/me/Desktop/TestRealm.realm")

and then it gets created in full view on my desktop and I can double-click to launch the Realm Browser on it. Later, I can remove the parameter and let it use the default location when I'm satisfied that all is working as expected.

What are the most-used vim commands/keypresses?

@Greg Hewgill's cheatsheet is very good. I started my switch from TextMate a few months ago. Now I'm as productive as I was with TM and constantly amazed by Vim's power.

Here is how I switched. Maybe it can be useful to you.

Grosso modo, I don't think it's a good idea to do a radical switch. Vim is very different and it's best to go progressively.

And to answer your subquestion, yes, I use all of iaIAoO everyday to enter insert mode. It certainly seems weird at first but you don't really think about it after a while.

Some commands incredibly useful for any programming related tasks:

  • r and R to replace characters
  • <C-a> and <C-x>to increase and decrease numbers
  • cit to change the content of an HTML tag, and its variants (cat, dit, dat, ci(, etc.)
  • <C-x><C-o> (mapped to ,,) for omnicompletion
  • visual block selection with <C-v>
  • and so on…

Once you are accustomed to the Vim way it becomes really hard to not hit o or x all the time when editing text in some other editor or textfield.

Android Notification Sound

You have to use builder.setSound

Intent notificationIntent = new Intent(MainActivity.this, MainActivity.class);  

                PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.this, 0, notificationIntent,   

                builder.setLights(Color.BLUE, 500, 500);
                long[] pattern = {500,500,500,500,500,500,500,500,500};
                builder.setStyle(new NotificationCompat.InboxStyle());
                 Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
                    if(alarmSound == null){
                        alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
                        if(alarmSound == null){
                            alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

                // Add as notification  
                NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  

Getting the screen resolution using PHP

Easiest way

//-- you can modified it like you want

echo $width = "<script>document.write(screen.width);</script>";
echo $height = "<script>document.write(screen.height);</script>";


Length of the String without using length() method

Even more slower one

public int slowerLength(String myString) {
String[] str = myString.split("");
int lol=0;
for(String s:str){
return (lol-1)

Or even slower,

public int slowerLength(String myString) {
String[] str = myString.split("");
int lol=0;
for(String s:str){
    lol += s.toCharArray().length;
return lol

When to use Interface and Model in TypeScript / Angular

The Interface describes either a contract for a class or a new type. It is a pure Typescript element, so it doesn't affect Javascript.

A model, and namely a class, is an actual JS function which is being used to generate new objects.

I want to load JSON data from a URL and bind to the Interface/Model.

Go for a model, otherwise it will still be JSON in your Javascript.

Connect Bluestacks to Android Studio

For those people with (cannot connect to localhost:5555: No connection could be made because the target machine actively refused it. (10061) :

Blustacks is listening at IPv4-Localhost-TCP-5555 (not IPv6). Most of the time Windows has IPv6 enabled by default and Localhost is solving ::1:

If the client (ADB) tries to connect a server using localhost and IPv6 is enabled on the main network adapter, ADB will not connect to the server.

So, you have two options :

1- Change your ADB client TCP connection string to localhost IPV4 : adb connect

OR :

2-Disable IPV6 protocol from the main network adapter.

XML Document to String

First you need to get rid of all newline characters in all your text nodes. Then you can use an identity transform to output your DOM tree. Look at the javadoc for TransformerFactory#newTransformer().

A table name as a variable

Use sp_executesql to execute any SQL, e.g.

DECLARE @tbl    sysname,
        @sql    nvarchar(4000),
        @params nvarchar(4000),
        @count  int

   SELECT object_name(id) FROM syscolumns WHERE name = 'LastUpdated'
   ORDER  BY 1
OPEN tblcur

WHILE 1 = 1
   FETCH tblcur INTO @tbl
   IF @@fetch_status <> 0

   SELECT @sql =
   N' SELECT @cnt = COUNT(*) FROM dbo.' + quotename(@tbl) +
   N' WHERE LastUpdated BETWEEN @fromdate AND ' +
   N'                           coalesce(@todate, ''99991231'')'
   SELECT @params = N'@fromdate datetime, ' +
                    N'@todate   datetime = NULL, ' +
                    N'@cnt      int      OUTPUT'
   EXEC sp_executesql @sql, @params, '20060101', @cnt = @count OUTPUT

   PRINT @tbl + ': ' + convert(varchar(10), @count) + ' modified rows.'


Convert timestamp long to normal date format

To show leading zeros infront of hours, minutes and seconds use below modified code. The trick here is we are converting (or more accurately formatting) integer into string so that it shows leading zero whenever applicable :

public String convertTimeWithTimeZome(long time) {
        Calendar cal = Calendar.getInstance();
        String curTime = String.format("%02d:%02d:%02d", cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND));
        return curTime;

Result would be like : 00:01:30

How to subtract X days from a date using Java calendar?

Eli Courtwright second solution is wrong, it should be:

Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, -days);

How to order citations by appearance using BibTeX?

The best I came up with is using the unsrt style, which seems to be a tweaked plain style. i.e.


However what if my style is not the default?

What is a PDB file?

Program Debug Database file (pdb) is a file format by Microsoft for storing debugging information.

When you build a project using Visual Studio or command prompt the compiler creates these symbol files.

Check Microsoft Docs

How to set background image of a view?

You can set multiple background image in every view using custom method as below.

make plist for every theam with background image name and other color

#import <Foundation/Foundation.h>
@interface ThemeManager : NSObject
@property (nonatomic,strong) NSDictionary*styles;
+ (ThemeManager *)sharedManager;

             #import "ThemeManager.h"

            @implementation ThemeManager
            @synthesize styles;
            + (ThemeManager *)sharedManager
                static ThemeManager *sharedManager = nil;
                if (sharedManager == nil)
                    sharedManager = [[ThemeManager alloc] init];
                [sharedManager selectTheme];
                return sharedManager;
            - (id)init
                if ((self = [super init]))

                return self;
                NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                NSString *themeName = [defaults objectForKey:@"AppTheme"] ?: @"DefaultTheam";

                NSString *path = [[NSBundle mainBundle] pathForResource:themeName ofType:@"plist"];
                self.styles = [NSDictionary dictionaryWithContentsOfFile:path];

Can use this via

 NSDictionary *styles = [ThemeManager sharedManager].styles;
 NSString *imageName = [styles objectForKey:@"backgroundImage"];
[imgViewBackGround setImage:[UIImage imageNamed:imageName]];

What is the use of join() in Python threading?

In python 3.x join() is used to join a thread with the main thread i.e. when join() is used for a particular thread the main thread will stop executing until the execution of joined thread is complete.

#1 - Without Join():
import threading
import time
def loiter():
    print('You are loitering!')
    print('You are not loitering anymore!')

t1 = threading.Thread(target = loiter)
print('Hey, I do not want to loiter!')
Output without join()--> 
You are loitering!
Hey, I do not want to loiter!
You are not loitering anymore! #After 5 seconds --> This statement will be printed

#2 - With Join():
import threading
import time
def loiter():
    print('You are loitering!')
    print('You are not loitering anymore!')

t1 = threading.Thread(target = loiter)
print('Hey, I do not want to loiter!')

Output with join() -->
You are loitering!
You are not loitering anymore! #After 5 seconds --> This statement will be printed
Hey, I do not want to loiter! 


How to expand 'select' option width after the user wants to select an option

you can try and solve using css only. by adding class to select

select{ width:80px;text-overflow:'...';-ms-text-overflow:ellipsis;position:absolute; z-index:+1;}
select:focus{ width:100%;}

for more reference List Box Style in a particular item (option) HTML

Multi Select List Box

What does "Object reference not set to an instance of an object" mean?

It means you did something like this.

Class myObject = GetObjectFromFunction();

And without doing

if(myObject!=null), you go ahead do myObject.Method();

UIBarButtonItem in navigation bar programmatically?

func viewDidLoad(){
let homeBtn: UIButton = UIButton(type: UIButtonType.custom)

        homeBtn.setImage(UIImage(named: "Home.png"), for: [])

        homeBtn.addTarget(self, action: #selector(homeAction), for: UIControlEvents.touchUpInside)

        homeBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)

        let homeButton = UIBarButtonItem(customView: homeBtn)

        let backBtn: UIButton = UIButton(type: UIButtonType.custom)

        backBtn.setImage(UIImage(named: "back.png"), for: [])

        backBtn.addTarget(self, action: #selector(backAction), for: UIControlEvents.touchUpInside)

        backBtn.frame = CGRect(x: -10, y: 0, width: 30, height: 30)

        let backButton = UIBarButtonItem(customView: backBtn)
        self.navigationItem.setLeftBarButtonItems([backButton,homeButton], animated: true)


How do I call a specific Java method on a click/submit event of a specific button in JSP?

If you have web.xml then


<form action="${pageContext.request.contextPath}/myservlet" method="post">
    <input type="submit" name="button1" value="Button 1" />


        <display-name>Servlet Name</display-name>


public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("Write your code below");

Find kth smallest element in a binary search tree in Optimum way

Here's just an outline of the idea:

In a BST, the left subtree of node T contains only elements smaller than the value stored in T. If k is smaller than the number of elements in the left subtree, the kth smallest element must belong to the left subtree. Otherwise, if k is larger, then the kth smallest element is in the right subtree.

We can augment the BST to have each node in it store the number of elements in its left subtree (assume that the left subtree of a given node includes that node). With this piece of information, it is simple to traverse the tree by repeatedly asking for the number of elements in the left subtree, to decide whether to do recurse into the left or right subtree.

Now, suppose we are at node T:

  1. If k == num_elements(left subtree of T), then the answer we're looking for is the value in node T.
  2. If k > num_elements(left subtree of T), then obviously we can ignore the left subtree, because those elements will also be smaller than the kth smallest. So, we reduce the problem to finding the k - num_elements(left subtree of T) smallest element of the right subtree.
  3. If k < num_elements(left subtree of T), then the kth smallest is somewhere in the left subtree, so we reduce the problem to finding the kth smallest element in the left subtree.

Complexity analysis:

This takes O(depth of node) time, which is O(log n) in the worst case on a balanced BST, or O(log n) on average for a random BST.

A BST requires O(n) storage, and it takes another O(n) to store the information about the number of elements. All BST operations take O(depth of node) time, and it takes O(depth of node) extra time to maintain the "number of elements" information for insertion, deletion or rotation of nodes. Therefore, storing information about the number of elements in the left subtree keeps the space and time complexity of a BST.

How can I get the actual video URL of a YouTube live stream?

This URL return to player actual video_id

Where UCkA21M22vGK9GtAvq3DvSlA is your channel id. You can find it inside YouTube account on "My Channel" link.

How to load/edit/run/save text files (.py) into an IPython notebook cell?

To write/save


  • write/save cell contents into (use -a to append). Another alias: %%file

To run


  • run and output results in the current cell

To load/import


  • load "import" into the current cell

For more magic and help


  • list all the other cool cell magic commands.


  • for help on how to use a certain command. i.e. %run?


Beside the cell magic commands, IPython notebook (now Jupyter notebook) is so cool that it allows you to use any unix command right from the cell (this is also equivalent to using the %%bash cell magic command).

To run a unix command from the cell, just precede your command with ! mark. for example:

  • !python --version see your python version
  • !python run and output results in the current cell, just like %run (see the difference between !python and %run in the comments below).

Also, see this nbviewer for further explanation with examples. Hope this helps.

How to develop a soft keyboard for Android?

first of all you should define an .xml file and make keyboard UI in it:

<?xml version="1.0" encoding="utf-8"?>
<Keyboard xmlns:android=""
NOTE When we add a horizontalGap in pixels, this interferes with keyWidth in percentages adding up to 100%
NOTE When we have a horizontalGap (on Keyboard level) of 0, this make the horizontalGap (on Key level) to move from after the key to before the key... (I consider this a bug) 
    <Key android:codes="-5" android:keyLabel="remove"  android:keyEdgeFlags="left" />
    <Key android:codes="48"    android:keyLabel="0" />
    <Key android:codes="55006" android:keyLabel="clear" />
    <Key android:codes="49"    android:keyLabel="1"  android:keyEdgeFlags="left" />
    <Key android:codes="50"    android:keyLabel="2" />
    <Key android:codes="51"    android:keyLabel="3" />
    <Key android:codes="52"    android:keyLabel="4"  android:keyEdgeFlags="left" />
    <Key android:codes="53"    android:keyLabel="5" />
    <Key android:codes="54"    android:keyLabel="6" />

    <Key android:codes="55"    android:keyLabel="7"  android:keyEdgeFlags="left" />
    <Key android:codes="56"    android:keyLabel="8" />
    <Key android:codes="57"    android:keyLabel="9" />

In this example you have 4 rows and in each row you have 3 keys. also you can put an icon in each key you want.

Then you should add xml tag in your activity UI like this:

        android:visibility="visible" />

Also in your .java activity file you should define the keyboard and assign it to a EditText:

CustomKeyboard mCustomKeyboard1 = new CustomKeyboard(this,
  , R.xml.horizontal_keyboard);

This code asign inputSearch (which is a EditText) to your keyboard.

import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView;
import android.inputmethodservice.KeyboardView.OnKeyboardActionListener;
import android.text.Editable;
import android.text.InputType;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

public class CustomKeyboard {

/** A link to the KeyboardView that is used to render this CustomKeyboard. */
private KeyboardView mKeyboardView;
/** A link to the activity that hosts the {@link #mKeyboardView}. */
private Activity mHostActivity;

/** The key (code) handler. */
private OnKeyboardActionListener mOnKeyboardActionListener = new OnKeyboardActionListener() {

    public final static int CodeDelete = -5; // Keyboard.KEYCODE_DELETE
    public final static int CodeCancel = -3; // Keyboard.KEYCODE_CANCEL
    public final static int CodePrev = 55000;
    public final static int CodeAllLeft = 55001;
    public final static int CodeLeft = 55002;
    public final static int CodeRight = 55003;
    public final static int CodeAllRight = 55004;
    public final static int CodeNext = 55005;
    public final static int CodeClear = 55006;

    public void onKey(int primaryCode, int[] keyCodes) {
        // NOTE We can say '<Key android:codes="49,50" ... >' in the xml
        // file; all codes come in keyCodes, the first in this list in
        // primaryCode
        // Get the EditText and its Editable
        View focusCurrent = mHostActivity.getWindow().getCurrentFocus();
        if (focusCurrent == null
                || focusCurrent.getClass() != EditText.class)
        EditText edittext = (EditText) focusCurrent;
        Editable editable = edittext.getText();
        int start = edittext.getSelectionStart();
        // Apply the key to the edittext
        if (primaryCode == CodeCancel) {
        } else if (primaryCode == CodeDelete) {
            if (editable != null && start > 0)
                editable.delete(start - 1, start);
        } else if (primaryCode == CodeClear) {
            if (editable != null)
        } else if (primaryCode == CodeLeft) {
            if (start > 0)
                edittext.setSelection(start - 1);
        } else if (primaryCode == CodeRight) {
            if (start < edittext.length())
                edittext.setSelection(start + 1);
        } else if (primaryCode == CodeAllLeft) {
        } else if (primaryCode == CodeAllRight) {
        } else if (primaryCode == CodePrev) {
            View focusNew = edittext.focusSearch(View.FOCUS_BACKWARD);
            if (focusNew != null)
        } else if (primaryCode == CodeNext) {
            View focusNew = edittext.focusSearch(View.FOCUS_FORWARD);
            if (focusNew != null)
        } else { // insert character
            editable.insert(start, Character.toString((char) primaryCode));

    public void onPress(int arg0) {

    public void onRelease(int primaryCode) {

    public void onText(CharSequence text) {

    public void swipeDown() {

    public void swipeLeft() {

    public void swipeRight() {

    public void swipeUp() {

 * Create a custom keyboard, that uses the KeyboardView (with resource id
 * <var>viewid</var>) of the <var>host</var> activity, and load the keyboard
 * layout from xml file <var>layoutid</var> (see {@link Keyboard} for
 * description). Note that the <var>host</var> activity must have a
 * <var>KeyboardView</var> in its layout (typically aligned with the bottom
 * of the activity). Note that the keyboard layout xml file may include key
 * codes for navigation; see the constants in this class for their values.
 * Note that to enable EditText's to use this custom keyboard, call the
 * {@link #registerEditText(int)}.
 * @param host
 *            The hosting activity.
 * @param viewid
 *            The id of the KeyboardView.
 * @param layoutid
 *            The id of the xml file containing the keyboard layout.
public CustomKeyboard(Activity host, int viewid, int layoutid) {
    mHostActivity = host;
    mKeyboardView = (KeyboardView) mHostActivity.findViewById(viewid);
    mKeyboardView.setKeyboard(new Keyboard(mHostActivity, layoutid));
    mKeyboardView.setPreviewEnabled(false); // NOTE Do not show the preview
                                            // balloons
    // Hide the standard keyboard initially

/** Returns whether the CustomKeyboard is visible. */
public boolean isCustomKeyboardVisible() {
    return mKeyboardView.getVisibility() == View.VISIBLE;

 * Make the CustomKeyboard visible, and hide the system keyboard for view v.
public void showCustomKeyboard(View v) {
    if (v != null)
        ((InputMethodManager) mHostActivity
                .hideSoftInputFromWindow(v.getWindowToken(), 0);

/** Make the CustomKeyboard invisible. */
public void hideCustomKeyboard() {

 * Register <var>EditText<var> with resource id <var>resid</var> (on the
 * hosting activity) for using this custom keyboard.
 * @param resid
 *            The resource id of the EditText that registers to the custom
 *            keyboard.
public void registerEditText(int resid) {
    // Find the EditText 'resid'
    EditText edittext = (EditText) mHostActivity.findViewById(resid);
    // Make the custom keyboard appear
    edittext.setOnFocusChangeListener(new OnFocusChangeListener() {
        // NOTE By setting the on focus listener, we can show the custom
        // keyboard when the edit box gets focus, but also hide it when the
        // edit box loses focus
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus)
    edittext.setOnClickListener(new OnClickListener() {
        // NOTE By setting the on click listener, we can show the custom
        // keyboard again, by tapping on an edit box that already had focus
        // (but that had the keyboard hidden).
        public void onClick(View v) {
    // Disable standard keyboard hard way
    // NOTE There is also an easy way:
    // 'edittext.setInputType(InputType.TYPE_NULL)' (but you will not have a
    // cursor, and no 'edittext.setCursorVisible(true)' doesn't work )
    edittext.setOnTouchListener(new OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            EditText edittext = (EditText) v;
            int inType = edittext.getInputType(); // Backup the input type
            edittext.setInputType(InputType.TYPE_NULL); // Disable standard
                                                        // keyboard
            edittext.onTouchEvent(event); // Call native handler
            edittext.setInputType(inType); // Restore input type
            return true; // Consume touch event
    // Disable spell check (hex strings look like words to Android)
            | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);


// NOTE How can we change the background color of some keys (like the
// shift/ctrl/alt)?
// NOTE What does android:keyEdgeFlags do/mean

How to use activity indicator view on iPhone?

The documentation on this is pretty clear. It's a UIView subclass so you use it like any other view. To start/stop the animation you use

[activityIndicator startAnimating];
[activityIndicator stopAnimating];

How to test if a DataSet is empty?

It is not a valid answer as it gives following error

Cannot find table 0.

Use the following statement instead

if (ds.Tables.Count == 0)
     //DataSet is empty

How to change the session timeout in PHP?

Just a notice for a sharing hosting server or added on domains =

For your settings to work you must have a different save session dir for added domain by using php_value session.save_path folderA/sessionsA.

So create a folder to your root server, not into the public_html and not to be publicity accessed from outside. For my cpanel/server worked fine the folder permissions 0700. Give a try...

# Session timeout, 2628000 sec = 1 month, 604800 = 1 week, 57600 = 16 hours, 86400 = 1 day
ini_set('session.save_path', '/home/server/.folderA_sessionsA');
ini_set('session.gc_maxlifetime', 57600); 
ini_set('session.cookie_lifetime', 57600);
# session.cache_expire is in minutes unlike the other settings above         
ini_set('session.cache_expire', 960);
ini_set('', 'MyDomainA');

before session_start();

or put this in your .htaccess file.

php_value session.save_path /home/server/.folderA_sessionsA
php_value session.gc_maxlifetime 57600
php_value session.cookie_lifetime 57600
php_value session.cache_expire 57600
php_value MyDomainA

After many researching and testing this worked fine for shared cpanel/php7 server. Many thanks to: NoiS

Equivalent of LIMIT and OFFSET for SQL Server?

For me the use of OFFSET and FETCH together was slow, so I used a combination of TOP and OFFSET like this (which was faster):

SELECT TOP 20 * FROM (SELECT columname1, columname2 FROM tablename
    WHERE <conditions...> ORDER BY columname1 OFFSET 100 ROWS) aliasname

Note: If you use TOP and OFFSET together in the same query like:

SELECT TOP 20 columname1, columname2 FROM tablename
    WHERE <conditions...> ORDER BY columname1 OFFSET 100 ROWS

Then you get an error, so for use TOP and OFFSET together you need to separate it with a sub-query.

And if you need to use SELECT DISTINCT then the query is like:

SELECT TOP 20 FROM (SELECT DISTINCT columname1, columname2
    WHERE <conditions...> ORDER BY columname1 OFFSET 100 ROWS) aliasname

Note: The use of SELECT ROW_NUMBER with DISTINCT did not work for me.

Why is it important to override GetHashCode when Equals method is overridden?

Yes, it is important if your item will be used as a key in a dictionary, or HashSet<T>, etc - since this is used (in the absence of a custom IEqualityComparer<T>) to group items into buckets. If the hash-code for two items does not match, they may never be considered equal (Equals will simply never be called).

The GetHashCode() method should reflect the Equals logic; the rules are:

  • if two things are equal (Equals(...) == true) then they must return the same value for GetHashCode()
  • if the GetHashCode() is equal, it is not necessary for them to be the same; this is a collision, and Equals will be called to see if it is a real equality or not.

In this case, it looks like "return FooId;" is a suitable GetHashCode() implementation. If you are testing multiple properties, it is common to combine them using code like below, to reduce diagonal collisions (i.e. so that new Foo(3,5) has a different hash-code to new Foo(5,3)):

unchecked // only needed if you're compiling with arithmetic checks enabled
{ // (the default compiler behaviour is *disabled*, so most folks won't need this)
    int hash = 13;
    hash = (hash * 7) + field1.GetHashCode();
    hash = (hash * 7) + field2.GetHashCode();
    return hash;

Oh - for convenience, you might also consider providing == and != operators when overriding Equals and GetHashCode.

A demonstration of what happens when you get this wrong is here.

Remove querystring from URL

var path = "path/to/myfile.png?foo=bar#hash";

    path.replace(/(\?.*)|(#.*)/g, "")

How to enable PHP's openssl extension to install Composer?


Browse to the line that reads:


and remove the semicolon preceding the line. Restart your WAMP server services (click in your icon tray > 'Restart All Services'

The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'

Any one can help for me!!!!!!!!!
<?xml  version="1.0" encoding="UTF-8"?>
    <beans xmlns=""
        <context:annotation-config />(ERROR OCCUR)
        <context:component-scan base-package="hiberrSpring" /> (ERROR OCCUR)
        <bean id="jspViewResolver"
            <property name="viewClass"
            <property name="prefix" value="/WEB-INF/"></property>
            <property name="suffix" value=".jsp"></property>
        <bean id="messageSource"
            <property name="basename" value="classpath:messages"></property>
            <property name="defaultEncoding" value="UTF-8"></property>
        <bean id="propertyConfigurer"
        <bean id="dataSource"
            class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
            p:url="${jdbc:mysql://localhost/}" p:username="${root}"
        <bean id="sessionFactory"
            <property name="dataSource" ref="dataSource"></property>
            <property name="configLocation">
            <property name="configurationClass">
            <property name="hibernateProperties">
                    <prop key="hibernate.dialect">${org.hibernate.dialect.MySQLDialect}</prop>
                    <prop key="hibernate.show_sql">true</prop>
        <bean id="employeeDAO" class="hiberrSpring.EmployeeDaoImpl"></bean>
        <bean id="employeeManager" class="hiberrSpring.EmployeeManagerImpl"></bean>
        <tx:annotation-driven /> (ERROR OCCUR)
        <bean id="transactionManager"
            <property name="sessionFactory" ref="sessionFactory"></property>

How to save password when using Subversion from the console

It depends on the protocol you're using. If you're using SVN + SSH, the SVN client can't save your password because it never touches it - the SSH client prompts you for it directly. In this case, you can use an SSH key and ssh-agent to avoid the constant prompts. If you're using the svnserve protocol or HTTP(S), then the SSH client is handling your password and can save it.

List all sequences in a Postgres db 8.1 with SQL

This statement lists the table and column that is associated with each sequence:


    SELECT t.relname as related_table, 
           a.attname as related_column,
           s.relname as sequence_name
    FROM pg_class s 
      JOIN pg_depend d ON d.objid = s.oid 
      JOIN pg_class t ON d.objid = s.oid AND d.refobjid = t.oid 
      JOIN pg_attribute a ON (d.refobjid, d.refobjsubid) = (a.attrelid, a.attnum)
      JOIN pg_namespace n ON n.oid = s.relnamespace 
    WHERE s.relkind     = 'S' 

  AND n.nspname     = 'public'

more see here link to answer

Move to next item using Java 8 foreach loop in stream

Another solution: go through a filter with your inverted conditions : Example :

if(subscribtion.isOnce() && subscribtion.isCalled()){

can be replaced with

.filter(s -> !(s.isOnce() && s.isCalled()))

The most straightforward approach seem to be using "return;" though.

Cmake doesn't find Boost

I had the same problem while trying to run make for a project after installing Boost version 1.66.0 on Ubuntu Trusty64. The error message was similar to (not exactly like) this one:

CMake Error at     
/usr/local/Cellar/cmake/3.3.2/share/cmake/Modules/FindBoost.cmake:1245 (message):
Unable to find the requested Boost libraries.
Boost version: 0.0.0
Boost include path: /usr/include
Detected version of Boost is too old.  Requested version was 1.36 (or newer).
Call Stack (most recent call first):
CMakeLists.txt:10 (FIND_PACKAGE)

Boost was definitely installed, but CMake couldn't detect it. After spending plenty of time tinkering with paths and environmental variables, I eventually ended up checking cmake itself for options and found the following:

--check-system-vars        = Find problems with variable usage in system files

So I ran the following in the directory at issue:

sudo cmake --check-system-vars

which returned:

Also check system files when warning about unused and uninitialized variables.
-- Boost version: 1.66.0
-- Found the following Boost libraries:
--   system
--   filesystem
--   thread
--   date_time
--   chrono
--   regex
--   serialization
--   program_options
-- Found Git: /usr/bin/git
-- Configuring done
-- Generating done
-- Build files have been written to: /home/user/myproject

and resolved the issue.

Unable to open project... cannot be opened because the project file cannot be parsed

Try to find HEAD and _HEAD between the lines and delete this words in project.pbxproj. Backup this file before doing this..

Calling a PHP function from an HTML form in the same file

Use SAJAX or switch to JavaScript

Sajax is an open source tool to make programming websites using the Ajax framework — also known as XMLHTTPRequest or remote scripting — as easy as possible. Sajax makes it easy to call PHP, Perl or Python functions from your webpages via JavaScript without performing a browser refresh.

vue.js 'document.getElementById' shorthand

You can use the directive v-el to save an element and then use it later.

<div v-el:my-div></div>
<!-- this.$els.myDiv --->

Edit: This is deprecated in Vue 2, see ??? answer

Set up DNS based URL forwarding in Amazon Route53

The AWS support pointed a simpler solution. It's basically the same idea proposed by @Vivek M. Chawla, with a more simple implementation.


  1. Create a Bucket named with your full domain, like
  2. On the bucket properties, select Redirect all requests to another host name and enter your URL:

AWS Route53:

  1. Create a record set type A. Change Alias to Yes. Click on Alias Target field and select the S3 bucket you created in the previous step.

Reference: How to redirect domains using Amazon Web Services

AWS official documentation: Is there a way to redirect a domain to another domain using Amazon Route 53?

Is there a way to have printf() properly print out an array (of floats, say)?

To be Honest All Are good but it will be easy if or more efficient if someone use n time numbers and show them in out prefer this will be a good option. Do not predefined array variable let user define and show the result. Like this..

int main()
    int i,j,n,t;
int arry[100];
   for (i=0;i<n;i++)
   { scanf("%d",&t);

return 0;

PhpMyAdmin not working on localhost

did you try 'localhost/phpmyadmin' ? (notice the lowercase)

PHPMyAdmin tends to have inconsistent directory names across its versions/distributions.

Edit: Confirm the URL by checking the name of the root folder!

If the config was the primary issue (and it may still be nthary) you would get a php error, not a http "Object not found" error,

As for the config error, here are some steps to correct it:

  1. Once you have confirmed which case your PHPMyAdmin is in, confirm that your is located in its root directory.

  2. If it is, rename it to something else as a backup. Then copy the (in the same directory) and rename it to

  3. Check if it works.

  4. If its does, then open up both the new (that works) and the backup you took earlier of your old one. Compare them and copy/replace the important parts that you want to carry over, the file (in its default state) isn't that long and it should be relatively easy to do so.

N.B. If the reason that you want your old config is because of security setup that you once had, I would definitely suggest still using the security wizard built into XAMPP so that you can be assured that you have the right configuration for the right version. There is no guarantee that different XAMPP/PHPMyAdmin versions implement security/anything in the same way.

XAMPP Security Wizard


How do I view 'git diff' output with my preferred diff tool/ viewer?

Since Git1.6.3, you can use the git difftool script: see my answer below.

May be this article will help you. Here are the best parts:

There are two different ways to specify an external diff tool.

The first is the method you used, by setting the GIT_EXTERNAL_DIFF variable. However, the variable is supposed to point to the full path of the executable. Moreover, the executable specified by GIT_EXTERNAL_DIFF will be called with a fixed set of 7 arguments:

path old-file old-hex old-mode new-file new-hex new-mode

As most diff tools will require a different order (and only some) of the arguments, you will most likely have to specify a wrapper script instead, which in turn calls the real diff tool.

The second method, which I prefer, is to configure the external diff tool via "git config". Here is what I did:

1) Create a wrapper script "" which contains something like


# diff is called by git with 7 parameters:
# path old-file old-hex old-mode new-file new-hex new-mode

"<path_to_diff_executable>" "$2" "$5" | cat

As you can see, only the second ("old-file") and fifth ("new-file") arguments will be passed to the diff tool.

2) Type

$ git config --global diff.external <path_to_wrapper_script>

at the command prompt, replacing with the path to "", so your ~/.gitconfig contains

    external = <path_to_wrapper_script>

Be sure to use the correct syntax to specify the paths to the wrapper script and diff tool, i.e. use forward slashed instead of backslashes. In my case, I have

    external = \"c:/Documents and Settings/sschuber/\"

in .gitconfig and

"d:/Program Files/Beyond Compare 3/BCompare.exe" "$2" "$5" | cat

in the wrapper script. Mind the trailing "cat"!

(I suppose the '| cat' is needed only for some programs which may not return a proper or consistent return status. You might want to try without the trailing cat if your diff tool has explicit return status)

(Diomidis Spinellis adds in the comments:

The cat command is required, because diff(1), by default exits with an error code if the files differ.
Git expects the external diff program to exit with an error code only if an actual error occurred, e.g. if it run out of memory.
By piping the output of git to cat the non-zero error code is masked.
More efficiently, the program could just run exit with and argument of 0.)

That (the article quoted above) is the theory for external tool defined through config file (not through environment variable).
In practice (still for config file definition of external tool), you can refer to:

How to create streams from string in Node.Js?

Just create a new instance of the stream module and customize it according to your needs:

var Stream = require('stream');
var stream = new Stream();

stream.pipe = function(dest) {
  dest.write('your string');
  return dest;

stream.pipe(process.stdout); // in this case the terminal, change to ya-csv


var Stream = require('stream');
var stream = new Stream();

stream.on('data', function(data) {
  process.stdout.write(data); // change process.stdout to ya-csv

stream.emit('data', 'this is my string');

Changing datagridview cell color based on condition

private void dataMain_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        if (dataMain.Columns[e.ColumnIndex].Name == "colStatus")
            if (int.Parse(e.Value.ToString()) == 2)
                dataMain.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.OrangeRed;
                dataMain.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.White;


SQL MAX of multiple columns?

If you are using SQL Server 2005, you can use the UNPIVOT feature. Here is a complete example:

create table dates 
  number int,
  date1 datetime,
  date2 datetime,
  date3 datetime 

insert into dates values (1, '1/1/2008', '2/4/2008', '3/1/2008')
insert into dates values (1, '1/2/2008', '2/3/2008', '3/3/2008')
insert into dates values (1, '1/3/2008', '2/2/2008', '3/2/2008')
insert into dates values (1, '1/4/2008', '2/1/2008', '3/4/2008')

select max(dateMaxes)
from (
    (select max(date1) from dates) date1max, 
    (select max(date2) from dates) date2max,
    (select max(date3) from dates) date3max
) myTable
unpivot (dateMaxes For fieldName In (date1max, date2max, date3max)) as tblPivot

drop table dates

Web API Routing - api/{controller}/{action}/{id} "dysfunctions" api/{controller}/{id}

The possible reason can also be that you have not inherited Controller from ApiController. Happened with me took a while to understand the same.

How to redirect the output of DBMS_OUTPUT.PUT_LINE to a file?

In addition to Tony's answer, if you are looking to find out where your PL/SQL program is spending it's time, it is also worth checking out this part of the Oracle PL/SQL documentation.

Optional args in MATLAB functions

A simple way of doing this is via nargin (N arguments in). The downside is you have to make sure that your argument list and the nargin checks match.

It is worth remembering that all inputs are optional, but the functions will exit with an error if it calls a variable which is not set. The following example sets defaults for b and c. Will exit if a is not present.

function [ output_args ] = input_example( a, b, c )
if nargin < 1
  error('input_example :  a is a required input')

if nargin < 2
  b = 20

if nargin < 3
  c = 30

How to use java.Set

Did you override equals and hashCode in the Block class?


I assumed you mean it doesn't work at runtime... did you mean that or at compile time? If compile time what is the error message? If it crashes at runtime what is the stack trace? If it compiles and runs but doesn't work right then the equals and hashCode are the likely issue.

How can I switch my signed in user in Visual Studio 2013?

None of the above worked for me - the following did:

devenv /ResetSettings

The nice thing about this option was it didn't wipe out all of my Visual Studio configuration (as /ResetUserData does)

How to print a debug log?

Simply way is trigger_error:

 trigger_error("My error");

but you can't put arrays or Objects therefore use


How does cellForRowAtIndexPath work?

1) The function returns a cell for a table view yes? So, the returned object is of type UITableViewCell. These are the objects that you see in the table's rows. This function basically returns a cell, for a table view. But you might ask, how the function would know what cell to return for what row, which is answered in the 2nd question

2)NSIndexPath is essentially two things-

  • Your Section
  • Your row

Because your table might be divided to many sections and each with its own rows, this NSIndexPath will help you identify precisely which section and which row. They are both integers. If you're a beginner, I would say try with just one section.

It is called if you implement the UITableViewDataSource protocol in your view controller. A simpler way would be to add a UITableViewController class. I strongly recommend this because it Apple has some code written for you to easily implement the functions that can describe a table. Anyway, if you choose to implement this protocol yourself, you need to create a UITableViewCell object and return it for whatever row. Have a look at its class reference to understand re-usablity because the cells that are displayed in the table view are reused again and again(this is a very efficient design btw).

As for when you have two table views, look at the method. The table view is passed to it, so you should not have a problem with respect to that.

Enable IIS7 gzip

Another easy way to test without installing anything, neither is it dependent on IIS version. Paste your url to this link - SEO Checkup

test gzip

To add to web.config:

Doctrine2: Best way to handle many-to-many with extra columns in reference table

From $album->getTrackList() you will alwas get "AlbumTrackReference" entities back, so what about adding methods from the Track and proxy?

class AlbumTrackReference
    public function getTitle()
        return $this->getTrack()->getTitle();

    public function getDuration()
        return $this->getTrack()->getDuration();

This way your loop simplifies considerably, aswell as all other code related to looping the tracks of an album, since all methods are just proxied inside AlbumTrakcReference:

foreach ($album->getTracklist() as $track) {
    echo sprintf("\t#%d - %-20s (%s) %s\n", 
        $track->isPromoted() ? ' - PROMOTED!' : ''

Btw You should rename the AlbumTrackReference (for example "AlbumTrack"). It is clearly not only a reference, but contains additional logic. Since there are probably also Tracks that are not connected to an album but just available through a promo-cd or something this allows for a cleaner separation also.

Can I delete data from the iOS DeviceSupport directory?

Yes, you can delete data from iOS device support by the symbols of the operating system, one for each version for each architecture. It's used for debugging. If you don't need to support those devices any more, you can delete the directory without ill effect

Remove all of x axis labels in ggplot

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

ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut))+

Creating a .dll file in C#.Net

You need to make a class library and not a Console Application. The console application is translated into an .exe whereas the class library will then be compiled into a dll which you can reference in your windows project.

  • Right click on your Console Application -> Properties -> Change the Output type to Class Library

enter image description here

Proper use of the IDisposable interface

If MyCollection is going to be garbage collected anyway, then you shouldn't need to dispose it. Doing so will just churn the CPU more than necessary, and may even invalidate some pre-calculated analysis that the garbage collector has already performed.

I use IDisposable to do things like ensure threads are disposed correctly, along with unmanaged resources.

EDIT In response to Scott's comment:

The only time the GC performance metrics are affected is when a call the [sic] GC.Collect() is made"

Conceptually, the GC maintains a view of the object reference graph, and all references to it from the stack frames of threads. This heap can be quite large and span many pages of memory. As an optimisation, the GC caches its analysis of pages that are unlikely to change very often to avoid rescanning the page unnecessarily. The GC receives notification from the kernel when data in a page changes, so it knows that the page is dirty and requires a rescan. If the collection is in Gen0 then it's likely that other things in the page are changing too, but this is less likely in Gen1 and Gen2. Anecdotally, these hooks were not available in Mac OS X for the team who ported the GC to Mac in order to get the Silverlight plug-in working on that platform.

Another point against unnecessary disposal of resources: imagine a situation where a process is unloading. Imagine also that the process has been running for some time. Chances are that many of that process's memory pages have been swapped to disk. At the very least they're no longer in L1 or L2 cache. In such a situation there is no point for an application that's unloading to swap all those data and code pages back into memory to 'release' resources that are going to be released by the operating system anyway when the process terminates. This applies to managed and even certain unmanaged resources. Only resources that keep non-background threads alive must be disposed, otherwise the process will remain alive.

Now, during normal execution there are ephemeral resources that must be cleaned up correctly (as @fezmonkey points out database connections, sockets, window handles) to avoid unmanaged memory leaks. These are the kinds of things that have to be disposed. If you create some class that owns a thread (and by owns I mean that it created it and therefore is responsible for ensuring it stops, at least by my coding style), then that class most likely must implement IDisposable and tear down the thread during Dispose.

The .NET framework uses the IDisposable interface as a signal, even warning, to developers that the this class must be disposed. I can't think of any types in the framework that implement IDisposable (excluding explicit interface implementations) where disposal is optional.

Create Table from View

If you just want to snag the schema and make an empty table out of it, use a false predicate, like so:

SELECT * INTO myNewTable FROM myView WHERE 1=2

How to detect control+click in Javascript from an onclick div attribute?

Because it's been a several years since this question was first asked, the other answers are outdated or incomplete.

Here's the code for a modern implementation using jQuery:

$( 'div#1' ).on( 'click', function( event ) {
    if ( event.ctrlKey ) {
        //is ctrl + click
    } else {
        //normal click
} );

As for detecting right-clicks, this was correctly provided by another user but I'll list it here just to have everything in one place.

$( 'div#1' ).on( 'contextmenu', function( event ) {
    // right-click handler
} ) ;

Class name does not name a type in C++

Include "B.h" in "A.h". That brings in the declaration of 'B' for the compiler while compiling 'A'.

The first bullet holds in the case of OP.

$3.4.1/7 -

"A name used in the definition of a class X outside of a member function body or nested class definition27) shall be declared in one of the following ways:

before its use in class X or be a member of a base class of X (10.2), or

— if X is a nested class of class Y (9.7), before the definition of X in Y, or shall be a member of a base class of Y (this lookup applies in turn to Y’s enclosing classes, starting with the innermost enclosing class),28) or

— if X is a local class (9.8) or is a nested class of a local class, before the definition of class X in a block enclosing the definition of class X, or

— if X is a member of namespace N, or is a nested class of a class that is a member of N, or is a local class or a nested class within a local class of a function that is a member of N, before the definition of class X in namespace N or in one of N’s enclosing namespaces."

How to get full file path from file name?

You Can use:

string path = Path.GetFullPath(FileName);

it will return the Full path of that mentioned file.

VBA Convert String to Date

Looks like it could be throwing the error on the empty data row, have you tried to just make sure itemDate isn't empty before you run the CDate() function? I think this might be your problem.

Any free WPF themes?

Read this article on how to convert a silverlight theme to WPF... The have a look at the Silverlight toolkit, thy released loads of free silverlight themes!!!

  • Expression Dark
  • Expression Light
  • Rainier Purple
  • Rainier Orange
  • Shiny Blue
  • Shiny Red

Python unittest passing arguments

Even if the test gurus say that we should not do it: I do. In some context it makes a lot of sense to have parameters to drive the test in the right direction, for example:

  • which of the dozen identical USB cards should I use for this test now?
  • which server should I use for this test now?
  • which XXX should I use?

For me, the use of the environment variable is good enough for this puprose because you do not have to write dedicated code to pass your parameters around; it is supported by Python. It is clean and simple.

Of course, I'm not advocating for fully parametrizable tests. But we have to be pragmatic and, as I said, in some context you need a parameter or two. We should not abouse of it :)

import os
import unittest

class MyTest(unittest.TestCase):
    def setUp(self):
        self.var1 = os.environ["VAR1"]
        self.var2 = os.environ["VAR2"]

    def test_01(self):
        print("var1: {}, var2: {}".format(self.var1, self.var2))

Then from the command line (tested on Linux)

$ export VAR1=1
$ export VAR2=2
$ python -m unittest MyTest
var1: 1, var2: 2
Ran 1 test in 0.000s


How to save MySQL query output to excel or .txt file?

You can write following codes to achieve this task:

SELECT ... FROM ... WHERE ... 
INTO OUTFILE 'textfile.csv'

It export the result to CSV and then export it to excel sheet.

Truncating all tables in a Postgres database

In this case it would probably be better to just have an empty database that you use as a template and when you need to refresh, drop the existing database and create a new one from the template.

Open files in 'rt' and 'wt' modes

t refers to the text mode. There is no difference between r and rt or w and wt since text mode is the default.

Documented here:

Character   Meaning
'r'     open for reading (default)
'w'     open for writing, truncating the file first
'x'     open for exclusive creation, failing if the file already exists
'a'     open for writing, appending to the end of the file if it exists
'b'     binary mode
't'     text mode (default)
'+'     open a disk file for updating (reading and writing)
'U'     universal newlines mode (deprecated)

The default mode is 'r' (open for reading text, synonym of 'rt').

Server configuration is missing in Eclipse

If you're not too attached to your current workspace you can create a new workspace, follow BalusC's steps for server creation, and recreate your project in the new workspace.

I got the same error after installing Eclipse Java EE IDE for Web Developers(Juno) but using the workspace of a much older Eclipse installation. When I created a new workspace I was able to get my Tomcat server running without this error.

Change button background color using swift language

Update for xcode 8 and swift 3, specify common colors like:

button.backgroundColor =

the Color() has been removed.

Replace multiple strings at once

There is no way to do this in one method call, you'll have to either chain calls together, or write a function that manually does what you need.

var s = "<>\n";
s = s.replace("<", "&lt;");
s = s.replace(">", "&gt;");
s = s.replace("\n", "<br/>");

Where to find the complete definition of off_t type?

If you are having trouble tracing the definitions, you can use the preprocessed output of the compiler which will tell you all you need to know. E.g.

$ cat test.c
#include <stdio.h>
$ cc -E test.c | grep off_t
typedef long int __off_t;
typedef __off64_t __loff_t;
  __off_t __pos;
  __off_t _old_offset;
typedef __off_t off_t;
extern int fseeko (FILE *__stream, __off_t __off, int __whence);
extern __off_t ftello (FILE *__stream) ;

If you look at the complete output you can even see the exact header file location and line number where it was defined:

# 132 "/usr/include/bits/types.h" 2 3 4

typedef unsigned long int __dev_t;
typedef unsigned int __uid_t;
typedef unsigned int __gid_t;
typedef unsigned long int __ino_t;
typedef unsigned long int __ino64_t;
typedef unsigned int __mode_t;
typedef unsigned long int __nlink_t;
typedef long int __off_t;
typedef long int __off64_t;


# 91 "/usr/include/stdio.h" 3 4
typedef __off_t off_t;

Google Maps API v3: InfoWindow not sizing correctly

I was having the same problem with IE and tried many of the fixes detailed in these responses, but was unable to remove the vertical scrollbars in IE reliably.

What worked best for me was to switch to fixed font sizes inside the infowindow -- 'px'... I was using ems. By fixing the font size I no longer needed to explicitly declare the infowindow width or height and the scrollbars were gone for good.

How to select a record and update it, with a single queryset in Django?

only in a case in serializer things, you can update in very simple way!

my_model_serializer = MyModelSerializer(
    instance=my_model, data=validated_data)
if my_model_serializer.is_valid():

only in a case in form things!

instance = get_object_or_404(MyModel, id=id)
form = MyForm(request.POST or None, instance=instance)
if form.is_valid():

<!--[if !IE]> not working

Thank you Fernando68, I used this:

function isIE () {
     var myNav = navigator.userAgent.toLowerCase();
     return (myNav.indexOf('msie') != -1 || myNav.indexOf('trident') != -1) ? true : false;

     $.getScript('js/script.min.js', function() {
            alert('Load was performed.');

window.history.pushState refreshing the browser

As others have suggested, you are not clearly explaining your problem, what you are trying to do, or what your expectations are as to what this function is actually supposed to do.

If I have understood correctly, then you are expecting this function to refresh the page for you (you actually use the term "reloads the browser").

But this function is not intended to reload the browser.

All the function does, is to add (push) a new "state" onto the browser history, so that in future, the user will be able to return to this state that the web-page is now in.

Normally, this is used in conjunction with AJAX calls (which refresh only a part of the page).

For example, if a user does a search "CATS" in one of your search boxes, and the results of the search (presumably cute pictures of cats) are loaded back via AJAX, into the lower-right of your page -- then your page state will not be changed. In other words, in the near future, when the user decides that he wants to go back to his search for "CATS", he won't be able to, because the state doesn't exist in his history. He will only be able to click back to your blank search box.

Hence the need for the function

history.pushState({},"Results for `Cats`",'url.html?s=cats');

It is intended as a way to allow the programmer to specifically define his search into the user's history trail. That's all it is intended to do.

When the function is working properly, the only thing you should expect to see, is the address in your browser's address-bar change to whatever you specify in your URL.

If you already understand this, then sorry for this long preamble. But it sounds from the way you pose the question, that you have not.

As an aside, I have also found some contradictions between the way that the function is described in the documentation, and the way it works in reality. I find that it is not a good idea to use blank or empty values as parameters.

See my answer to this SO question. So I would recommend putting a description in your second parameter. From memory, this is the description that the user sees in the drop-down, when he clicks-and-holds his mouse over "back" button.

How to add form validation pattern in Angular 2?

You could build your form using FormBuilder as it let you more flexible way to configure form.

export class MyComp {
  form: ControlGroup;

  constructor(@Inject()fb: FormBuilder) {  
    this.form ={  
      foo: ['', MyValidators.regex(/^(?!\s|.*\s$).*$/)]  

Then in your template :

<input type="text" ngControl="foo" />
<div *ngIf="!">Please correct foo entry !</div> 

You can also customize ng-invalid CSS class.

As there is actually no validators for regex, you have to write your own. It is a simple function that takes a control in input, and return null if valid or a StringMap if invalid.

export class MyValidators {
  static regex(pattern: string): Function {
    return (control: Control): {[key: string]: any} => {
      return control.value.match(pattern) ? null : {pattern: true};

Hope that it help you.

CSS3 gradient background set on body doesn't stretch but instead repeats?

I know I'm late to the party, but here's a more solid answer.

All you need to do is use min-height: 100%; rather than height: 100%; and your gradient background will extend the entire height of the viewport without repeating, even if the content is scrollable.

Like this:

html {
    min-height: 100%;

body {
    background: linear-gradient(#ff7241, #ff4a1f);

How to calculate the IP range when the IP address and the netmask is given?

I know this is an older question, but I found this nifty library on nuget that seems to do just the trick for me:

How do I install a Python package with a .whl file?

New Python users on Windows often forget to add Python's \Scripts directory to the PATH variable during the installation. I recommend to use the Python launcher and execute pip as a script with the -m switch. Then you can install the wheels for a specific Python version (if more than one are installed) and the Scripts directory doesn't have to be in the PATH. So open the command line, navigate (with the cd command) to the folder where the .whl file is located and enter:

py -3.6 -m pip install your_whl_file.whl

Replace 3.6 by your Python version or just enter -3 if the desired Python version appears first in the PATH. And with an active virtual environment: py -m pip install your_whl_file.whl.

Of course you can also install packages from PyPI in this way, e.g.

py -3.6 -m pip install pygame

Multiple contexts with the same path error running web service in Eclipse using Tomcat

Go to server.xml and Search for "Context" tag with a property name "docBase".

Remove the duplicate lines here. Then try to restart the server.

How do I create a round cornered UILabel on the iPhone?

Did you try using the UIButton from the Interface builder (that has rounded corners) and experimenting with the settings to make it look like a label. if all you want is to display static text within.

How can I check file size in Python?

#Get file size , print it , process it...
#Os.stat will provide the file size in (.st_size) property. 
#The file size will be shown in bytes.

import os

print('size:' + fsize.st_size.__str__())

#check if the file size is less than 10 MB

if fsize.st_size < 10000000:
    process it ....

Count number of cells with any value (string or number) in a column in Google Docs Spreadsheet

In the cell you want your result to appear, use the following formula:


That will count all cells which have a value and ignore all empty cells in the range of A1 to A200.


SELECT train, dest, time FROM ( 
  SELECT train, dest, time, 
    RANK() OVER (PARTITION BY train ORDER BY time DESC) dest_rank
    FROM traintable
  ) where dest_rank = 1

IOError: [Errno 13] Permission denied

I had a similar problem. I was attempting to have a file written every time a user visits a website.

The problem ended up being twofold.

1: the permissions were not set correctly

2: I attempted to use
f = open(r"newfile.txt","w+") (Wrong)

After changing the file to 777 (all users can read/write)
chmod 777 /var/www/path/to/file
and changing the path to an absolute path, my problem was solved
f = open(r"/var/www/path/to/file/newfile.txt","w+") (Right)

Join/Where with LINQ and Lambda

Your key selectors are incorrect. They should take an object of the type of the table in question and return the key to use in the join. I think you mean this:

var query = database.Posts.Join(database.Post_Metas,
                                post => post.ID,
                                meta => meta.Post_ID,
                                (post, meta) => new { Post = post, Meta = meta });

You can apply the where clause afterwards, not as part of the key selector.

JSON find in JavaScript

If the JSON data in your array is sorted in some way, there are a variety of searches you could implement. However, if you're not dealing with a lot of data then you're probably going to be fine with an O(n) operation here (as you have). Anything else would probably be overkill.

How to log as much information as possible for a Java Exception?

You can also use Apache's ExceptionUtils.


import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.log4j.Logger;

public class Test {

    static Logger logger = Logger.getLogger(Test.class);

    public static void main(String[] args) {

            String[] avengers = null;
            System.out.println("Size: "+avengers.length);
        } catch (NullPointerException e){


Console output:

    at com.aimlessfist.avengers.ironman.Test.main(

What is JSONP, and why was it created?

JSONP works by constructing a “script” element (either in HTML markup or inserted into the DOM via JavaScript), which requests to a remote data service location. The response is a javascript loaded on to your browser with name of the pre-defined function along with parameter being passed that is tht JSON data being requested. When the script executes, the function is called along with JSON data, allowing the requesting page to receive and process the data.

For Further Reading Visit:

client side snippet of code

    <!DOCTYPE html>
    <html lang="en">
     <title>AvLabz - CORS : The Secrets Behind JSONP </title>
     <meta charset="UTF-8" />
      <input type="text" id="username" placeholder="Enter Your Name"/>
      <button type="submit" onclick="sendRequest()"> Send Request to Server </button>
    "use strict";
    //Construct the script tag at Runtime
    function requestServerCall(url) {
      var head = document.head;
      var script = document.createElement("script");

      script.setAttribute("src", url);

    //Predefined callback function    
    function jsonpCallback(data) {
      alert(data.message); // Response data from the server

    //Reference to the input field
    var username = document.getElementById("username");

    //Send Request to Server
    function sendRequest() {
      // Edit with your Web Service URL


Server side piece of PHP code

    header("Content-Type: application/javascript");
    $callback = $_GET["callback"];
    $message = $_GET["message"]." you got a response from server yipeee!!!";
    $jsonResponse = "{\"message\":\"" . $message . "\"}";
    echo $callback . "(" . $jsonResponse . ")";

Install python 2.6 in CentOS

When I've run into similar situations, I generally avoid the package manager, especially if it would be embarrassing to break something, i.e. a production server. Instead, I would go to Activestate and download their binary package:

This is installed by running a script which places everything into a folder and does not touch any system files. In fact, you don't even need root permissions to set it up. Then I change the name of the binary to something like apy26, add that folder to the end of the PATH and start coding. If you install packages with apy26 installor if you use virtualenv and easyinstall, then you have just as flexible a python environment as you need without touching the system standard python.

Edits... Recently I've done some work to build a portable Python binary for Linux that should run on any distro with no external dependencies. This means that any binary shared libraries needed by the portable Python module are part of the build, included in the tarball and installed in Python's private directory structure. This way you can install Python for your application without interfering with the system installed Python.

My github site has a build script which has been thoroughly tested on Ubuntu Lucid 10.04 LTS both 32 and 64 bit installs. I've also built it on Debian Etch but that was a while ago and I can't guarantee that I haven't changed something. The easiest way to do this is you just put your choice of Ubuntu Lucid in a virtual machine, checkout the script with git clone git:// and then run the script.

Once you have it built, use the tarball on any recent Linux distro. There is one little wrinkle with moving it to a directory other than /data1/packages/python272 which is that you have to run the included patchelf to set the interpreter path BEFORE you move the directory. This affects any binaries in /data1/packages/python272/bin

All of this is based on building with RUNPATH and copying the dependent shared libraries. Even though the script is in several files, it is effectively one long shell script arranged in the style of /etc/rc.d directories.

How to find the serial port number on Mac OS X?

I was able to screen using the device's name anyway so that wasn't the issue. I was actually just trying to find the port number, i.e. 5331, 5332 etc. I managed to find this by a trial and error process using an app called TCP2Serial from the app store on Mac OS X. It isn't free but that's fine as long as I know it works!

Worth the 99c :)

How to add a form load event (currently not working)

You got half of the answer! Now that you created the event handler, you need to hook it to the form so that it actually gets called when the form is loading. You can achieve that by doing the following:

 public class ProgramViwer : Form{
  public ProgramViwer()
       Load += new EventHandler(ProgramViwer_Load);
  private void ProgramViwer_Load(object sender, System.EventArgs e)

Storing and Retrieving ArrayList values from hashmap

Our variable:

Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();

To store:

map.put("mango", new ArrayList<Integer>(Arrays.asList(0, 4, 8, 9, 12)));

To add numbers one and one, you can do something like this:

String key = "mango";
int number = 42;
if (map.get(key) == null) {
    map.put(key, new ArrayList<Integer>());

In Java 8 you can use putIfAbsent to add the list if it did not exist already:

map.putIfAbsent(key, new ArrayList<Integer>());

Use the map.entrySet() method to iterate on:

for (Entry<String, List<Integer>> ee : map.entrySet()) {
    String key = ee.getKey();
    List<Integer> values = ee.getValue();
    // TODO: Do something.

How to split a string at the first `/` (slash) and surround part of it in a `<span>`?

You should use html():


    $("#date").html('<span>'+$("#date").text().substring(0, 2) + '</span><br />'+$("#date").text().substring(3));     

How to make a .NET Windows Service start right after the installation?

You can do this all from within your service executable in response to events fired from the InstallUtil process. Override the OnAfterInstall event to use a ServiceController class to start the service.

Is there more to an interface than having the correct methods

If you have CardboardBox and HtmlBox (both of which implement IBox), you can pass both of them to any method that accepts a IBox. Even though they are both very different and not completely interchangable, methods that don't care about "open" or "resize" can still use your classes (perhaps because they care about how many pixels are needed to display something on a screen).

Converting a POSTMAN request to Curl

enter image description here

You can see the button "Code" in the attached screenshot, press it and you can get your code in many different languages including PHP cURL

enter image description here

unresolved external symbol __imp__fprintf and __imp____iob_func, SDL2

I resolve this problem with following function. I use Visual Studio 2019.

FILE* __cdecl __iob_func(void)
    FILE _iob[] = { *stdin, *stdout, *stderr };
    return _iob;

because stdin Macro defined function call, "*stdin" expression is cannot used global array initializer. But local array initialier is possible. sorry, I am poor at english.

How do I convert date/time from 24-hour format to 12-hour AM/PM?

You can use date function to format it by using the code below:

echo date("g:i a", strtotime("13:30:30 UTC"));

output: 1:30 pm

Get the (last part of) current directory name in C#

rather then using the '/' for the call to split, better to use the Path.DirectorySeparatorChar :

like so:


How to exit in Node.js

if you want to exit from node js application then write


in your code

How to prevent Google Colab from disconnecting?

var startColabHandler = function startColabHandler(interval = 60000, enableConnectButton = false) {
    console.log("colabHandler - configure - start: " + new Date());
    var colabClick = function colabClick() {
        console.log("colabHandler - click - start: " + new Date());
        if (enableConnectButton === true) {
            var button1 = document.querySelector("#top-toolbar > colab-connect-button").shadowRoot.querySelector("#connect");
            if (button1) {
        button2 = document.querySelector("html body colab-dialog.yes-no-dialog paper-dialog div.buttons paper-button#ok");
        if (button2) {
        console.log("colabHandler - click - end: " + new Date());

    var intervalId = setInterval(colabClick, interval);

    window.stopColabHandler = function stopColabHandler() {
        console.log("colabHandler - stop - start: " + new Date());
        console.log("colabHandler - stop - start: " + new Date());

    console.log("colabHandler - configure - end: " + new Date());

Git clone without .git directory

Alternatively, if you have Node.js installed, you can use the following command:

npx degit GIT_REPO

npx comes with Node, and it allows you to run binary node-based packages without installing them first (alternatively, you can first install degit globally using npm i -g degit).

Degit is a tool created by Rich Harris, the creator of Svelte and Rollup, which he uses to quickly create a new project by cloning a repository without keeping the git folder. But it can also be used to clone any repo once...

Creating a left-arrow button (like UINavigationBar's "back" style) on a UIToolbar

Here's what I ended up doing after searching through all these solutions and others. It uses a stretchable png's extracted from the UIKit stock images. This way you can set the text to whatever you liek

// Generate the background images
UIImage *stretchableBackButton = [[UIImage imageNamed:@"UINavigationBarDefaultBack.png"] stretchableImageWithLeftCapWidth:14 topCapHeight:0];
UIImage *stretchableBackButtonPressed = [[UIImage imageNamed:@"UINavigationBarDefaultBackPressed.png"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];
// Setup the UIButton
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
[backButton setBackgroundImage:stretchableBackButton forState:UIControlStateNormal];
[backButton setBackgroundImage:stretchableBackButtonPressed forState:UIControlStateSelected];
NSString *buttonTitle = NSLocalizedString(@"Back", @"Back");
[backButton setTitle:buttonTitle forState:UIControlStateNormal];
[backButton setTitle:buttonTitle forState:UIControlStateSelected];
backButton.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 2, 1); // Tweak the text position
NSInteger width = ([backButton.titleLabel.text sizeWithFont:backButton.titleLabel.font].width + backButton.titleEdgeInsets.right +backButton.titleEdgeInsets.left);
[backButton setFrame:CGRectMake(0, 0, width, 29)];
backButton.titleLabel.font = [UIFont boldSystemFontOfSize:13.0f];
[backButton addTarget:self action:@selector(yourSelector:) forControlEvents:UIControlEventTouchDown];
// Now add the button as a custom UIBarButtonItem
UIBarButtonItem *backButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:backButton] autorelease];
self.navigationItem.leftBarButtonItem = backButtonItem;

error: expected primary-expression before ')' token (C)

A function call needs to be performed with objects. You are doing the equivalent of this:

// function declaration/definition
void foo(int) {}

// function call
foo(int); // wat!??

i.e. passing a type where an object is required. This makes no sense in C or C++. You need to be doing

int i = 42;



Get SSID when WIFI is connected

In Android 8.1 it is must to turned Location on to get SSID, if not you can get connection state but not SSID

WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = null;
if (wifiManager != null) 
wifiInfo = wifiManager.getConnectionInfo();
 String ssid = null;
if (wifiInfo != null) 
ssid = wifiInfo.getSSID(); /*you will get SSID <unknown ssid> if location turned off*/

How to get the last N rows of a pandas DataFrame?

This is because of using integer indices (ix selects those by label over -3 rather than position, and this is by design: see integer indexing in pandas "gotchas"*).

*In newer versions of pandas prefer loc or iloc to remove the ambiguity of ix as position or label:


see the docs.

As Wes points out, in this specific case you should just use tail!

jQuery $("#radioButton").change(...) not firing during de-selection

My problem was similar and this worked for me:

$('body').on('change', '.radioClassNameHere', function() { ...

How to connect to Oracle 11g database remotely

First. It is necessary add static IP address for Computer A AND B. For example in my case Computer A ( and B (

Second. In Computer A with Net Manager add for Listener new address ( or manually add new record in listener.ora

# listener.ora Network Configuration File: E:\app\user\product\11.2.0\dbhome_1\NETWORK\ADMIN\listener.ora
# Generated by Oracle configuration tools.

    (SID_DESC =
      (SID_NAME = CLRExtProc)
      (ORACLE_HOME = E:\app\user\product\11.2.0\dbhome_1)
      (PROGRAM = extproc)
      (ENVS = "EXTPROC_DLLS=ONLY:E:\app\user\product\11.2.0\dbhome_1\bin\oraclr11.dll")

      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
      (ADDRESS = (PROTOCOL = TCP)(HOST = = 1521))


Third. With Net Manager create Service Naming with IP address computer B ( or manually add new record in tnsnames.ora

# tnsnames.ora Network Configuration File: E:\app\user\product\11.2.0\dbhome_1\NETWORK\ADMIN\tnsnames.ora
# Generated by Oracle configuration tools.

      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
      (SERVICE_NAME = alinadb)

  (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))

      (ADDRESS = (PROTOCOL = TCP)(HOST = = 1521))
      (SERVICE_NAME = alinadb)

      (SID = CLRExtProc)

      (ADDRESS = (PROTOCOL = TCP)(HOST = = 1521))
      (SERVICE_NAME = orcl)

Fourth. In computer B ( install win64_11gR2_client (For example it is for me in Windows 10 Pro 64 bit )

Five. Create with Net Configuration Assistant listener (localhost) or manually add record in listener.ora

# listener.ora Network Configuration File: F:\app\alinasoft\product\11.2.0\client_1\network\admin\listener.ora
# Generated by Oracle configuration tools.

        (DESCRIPTION =
          (ADDRESS = (PROTOCOL = TCP)(HOST = myserver)(PORT = 1521))
          (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))

    ADR_BASE_LISTENER = F:\app\alinasoft

Six. With Net Manager create Service Naming with IP address computer A ( or manually add new record in tnsnames.ora.

      (ADDRESS = (PROTOCOL = TCP)(HOST = = 1521))
      (SERVICE_NAME = alinadb)

Seven (Computer A - ( for database operations and connectivity from remote clients, the following executables must be added to the Windows Firewall exception list: (see image) Oracle_home\bin\oracle.exe - Oracle Database executable Oracle_home\bin\tnslsnr.exe - Oracle Listener

Eight Allow connections for port 1158 (Computer A - ( for Oracle Enterprise Manager (

Ninth Allow connections for port 1521 ( in and out) (Computer A - (

Tenth In computer B sqlplus /NOLOG CONNECT system/oracle@//

If uses Toad, in my case is enter image description here

Why does Eclipse complain about @Override on interface methods?

Do as follows:

Project -> Properties -> java compiler ->

  • Enable project specific settings - 'yes'
  • Compiler compliance - 1.6
  • generated class files and source compatibility - 1.5

How do you append to an already existing string?

$ string="test"
$ string="${string}test2"
$ echo $string

Angularjs $q.all

In javascript there are no block-level scopes only function-level scopes:

Read this article about javaScript Scoping and Hoisting.

See how I debugged your code:

var deferred = $q.defer();
deferred.count = i;

console.log(deferred.count); // 0,1,2,3,4,5 --< all deferred objects

// some code

   console.log(deferred.count); // 5,5,5,5,5,5 --< only the last deferred object
  • When you write var deferred= $q.defer(); inside a for loop it's hoisted to the top of the function, it means that javascript declares this variable on the function scope outside of the for loop.
  • With each loop, the last deferred is overriding the previous one, there is no block-level scope to save a reference to that object.
  • When asynchronous callbacks (success / error) are invoked, they reference only the last deferred object and only it gets resolved, so $q.all is never resolved because it still waits for other deferred objects.
  • What you need is to create an anonymous function for each item you iterate.
  • Since functions do have scopes, the reference to the deferred objects are preserved in a closure scope even after functions are executed.
  • As #dfsq commented: There is no need to manually construct a new deferred object since $http itself returns a promise.

Solution with angular.forEach:

Here is a demo plunker:

UploadService.uploadQuestion = function(questions){

    var promises = [];

    angular.forEach(questions , function(question) {

        var promise = $http({
            url   : 'upload/question',
            method: 'POST',
            data  : question



    return $q.all(promises);

My favorite way is to use Array#map:

Here is a demo plunker:

UploadService.uploadQuestion = function(questions){

    var promises = {

        return $http({
            url   : 'upload/question',
            method: 'POST',
            data  : question


    return $q.all(promises);

Escaping Double Quotes in Batch Script

The escape character in batch scripts is ^. But for double-quoted strings, double up the quotes:

"string with an embedded "" character"

How to name an object within a PowerPoint slide?

Click Insert ->Object->Create from file ->Browse.

Once the file is selected choose the "Change icon" option and you will be able to rename the file and change the icon if you wish.

Hope this helps!

How to set default value for HTML select?

Note: this is JQuery. See Sébastien answer for Javascript

$(function() {
    var temp="a"; 

<select name="MySelect" id="MySelect">
    <option value="a">a</option>
    <option value="b">b</option>
    <option value="c">c</option>

Spring Boot java.lang.NoClassDefFoundError: javax/servlet/Filter

That looks like you tried to add the libraries servlet.jar or servlet-api.jar into your project /lib/ folder, but Tomcat already should provide you with those libraries. Remove them from your project and classpath. Search for that anywhere in your project or classpath and remove it.

Disable click outside of angular material dialog area to close the dialog (With Angular Version 4.0+)

There are two ways to do it.

  1. In the method that opens the dialog, pass in the following configuration option disableClose as the second parameter in MatDialog#open() and set it to true:

    export class AppComponent {
      constructor(private dialog: MatDialog){}
      openDialog() {, { disableClose: true });
  2. Alternatively, do it in the dialog component itself.

    export class DialogComponent {
      constructor(private dialogRef: MatDialogRef<DialogComponent>){
        dialogRef.disableClose = true;

Here's what you're looking for:

<code>disableClose</code> property in

And here's a Stackblitz demo

Other use cases

Here's some other use cases and code snippets of how to implement them.

Allow esc to close the dialog but disallow clicking on the backdrop to close the dialog

As what @MarcBrazeau said in the comment below my answer, you can allow the esc key to close the modal but still disallow clicking outside the modal. Use this code on your dialog component:

import { Component, OnInit, HostListener } from '@angular/core';
import { MatDialogRef } from '@angular/material';
  selector: 'app-third-dialog',
  templateUrl: './third-dialog.component.html'
export class ThirdDialogComponent {
  constructor(private dialogRef: MatDialogRef<ThirdDialogComponent>) {      
  @HostListener('window:keyup.esc') onKeyUp() {


Prevent esc from closing the dialog but allow clicking on the backdrop to close

P.S. This is an answer which originated from this answer, where the demo was based on this answer.

To prevent the esc key from closing the dialog but allow clicking on the backdrop to close, I've adapted Marc's answer, as well as using MatDialogRef#backdropClick to listen for click events to the backdrop.

Initially, the dialog will have the configuration option disableClose set as true. This ensures that the esc keypress, as well as clicking on the backdrop will not cause the dialog to close.

Afterwards, subscribe to the MatDialogRef#backdropClick method (which emits when the backdrop gets clicked and returns as a MouseEvent).

Anyways, enough technical talk. Here's the code:

openDialog() {
  let dialogRef =, { disableClose: true });
     Subscribe to events emitted when the backdrop is clicked
     NOTE: Since we won't actually be using the `MouseEvent` event, we'll just use an underscore here
     See for more info
  dialogRef.backdropClick().subscribe(() => {
    // Close the dialog

  // ...

Alternatively, this can be done in the dialog component:

export class DialogComponent {
  constructor(private dialogRef: MatDialogRef<DialogComponent>) {
    dialogRef.disableClose = true;
      Subscribe to events emitted when the backdrop is clicked
      NOTE: Since we won't actually be using the `MouseEvent` event, we'll just use an underscore here
      See for more info
    dialogRef.backdropClick().subscribe(() => {
      // Close the dialog

When to use static methods

A static method is one type of method which doesn't need any object to be initialized for it to be called. Have you noticed static is used in the main function in Java? Program execution begins from there without an object being created.

Consider the following example:

 class Languages 
     public static void main(String[] args) 

     static void display() 
         System.out.println("Java is my favorite programming language.");

MVC Return Partial View as JSON

Url.Action("Evil", model)

will generate a get query string but your ajax method is post and it will throw error status of 500(Internal Server Error). – Fereydoon Barikzehy Feb 14 at 9:51

Just Add "JsonRequestBehavior.AllowGet" on your Json object.

Using Server.MapPath() inside a static field in ASP.NET MVC

I think you can try this for calling in from a class


*----------------Sorry I oversight, for static function already answered the question by adrift*



I got exception while using System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");

Ex details : System.ArgumentException: The relative virtual path 'SignatureImages' is not allowed here. at System.Web.VirtualPath.FailIfRelativePath()

Solution (tested in static webmethod)

System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/"); Worked

Combine Regexp?

Doesn't contain @: /(^[^@]*$)/

Combining works if the intended result of combination is that any of them matching results in the whole regexp matching.

What's the meaning of System.out.println in Java?

System.out.println("...") in Java code is translated into JVM. Looking into the JVM gave me better understanding what is going on behind the hood.

From the book Programming form the Java Virtual Machine. This code is copied from

This is the JVM source code.

.class public HelloWorld
.super java/lang/Object

.method public static main([Ljava/lang/String;)V
.limit stack 2
.limit locals 1
  getstatic java/lang/System/out Ljava/io/PrintStream;
  ldc "Hello, world"
  invokevirtual java/io/PrintStream/println

.end method
.end class

As "The JVM doesn't permit byte-level access to memory" the out object in type Ljava/io/PrintSteram; is stored in a stack with getstatic JVM command. Then the argument is pushed on the stack before called a method println of the java/io/PrintStream class from an instance named out. The method's parameter is (Ljava/lang/String;) and output type is void (V).

What does `unsigned` in MySQL mean and when to use it?

MySQL says:

All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.

When do I use it ?

Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED data type.

A common mistake is to use a primary key that is an auto-increment INT starting at zero, yet the type is SIGNED, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.

Rails: update_attribute vs update_attributes

Great answers. notice that as for ruby 1.9 and above you could (and i think should) use the new hash syntax for update_attributes:

Model.update_attributes(column1: "data", column2: "data")

Custom header to HttpClient request

I have found the answer to my question.


That should add a custom header to your request

Remove item from list based on condition

You could use Linq.

var prod = from p in prods
           where p.ID != 1
           select p;

How do I make a checkbox required on an ASP.NET form?

javascript function for client side validation (using jQuery)...

function CheckBoxRequired_ClientValidate(sender, e)
    e.IsValid = jQuery(".AcceptedAgreement input:checkbox").is(':checked');

code-behind for server side validation...

protected void CheckBoxRequired_ServerValidate(object sender, ServerValidateEventArgs e)
    e.IsValid = MyCheckBox.Checked;

ASP.Net code for the checkbox & validator...

<asp:CheckBox runat="server" ID="MyCheckBox" CssClass="AcceptedAgreement" />
<asp:CustomValidator runat="server" ID="CheckBoxRequired" EnableClientScript="true"
    ClientValidationFunction="CheckBoxRequired_ClientValidate">You must select this box to proceed.</asp:CustomValidator>

and finally, in your postback - whether from a button or whatever...

if (Page.IsValid)
    // your code here...

Steps to upload an iPhone application to the AppStore

Xcode 9

If this is your first time to submit an app, I recommend going ahead and reading through the full Apple iTunes Connect documentation or reading one of the following tutorials:

However, those materials are cumbersome when you just want a quick reminder of the steps. My answer to that is below:

Step 1: Create a new app in iTunes Connect

Sign in to iTunes Connect and go to My Apps. Then click the "+" button and choose New App.

enter image description here

Then fill out the basic information for a new app. The app bundle id needs to be the same as the one you are using in your Xcode project. There is probably a better was to name the SKU, but I've never needed it and I just use the bundle id.

enter image description here

Click Create and then go on to Step 2.

Step 2: Archive your app in Xcode

Choose the Generic iOS Device from the active scheme menu.

enter image description here

Then go to Product > Archive.

enter image description here

You may have to wait a little while for Xcode to finish archiving your project. After that you will be shown a dialog with your archived project. You can select Upload to the App Store... and follow the prompts.

I sometimes have to repeat this step a few times because I forgot to include something. Besides the upload wait, it isn't a big deal. Just keep doing it until you don't get any more errors.

Step 3: Finish filling out the iTunes Connect info

Back in iTunes Connect you will need to complete all the required information and resources.

enter image description here

Just go through all the menu options and make sure that you have everything entered that needs to be.

Step 4: Submit

In iTunes Connect, under your app's Prepare for Submission section, click Submit for Review. That's it. Give it about a week to be accepted (or rejected), but it might be faster.

PHPMailer: SMTP Error: Could not connect to SMTP host

In my case in CPANEL i have 'Register mail ids' option where i add my email address and after 30 minutes it works fine with simple php mail function.

Nexus 5 USB driver

Is it your first android connected to your computer? Sometimes windows drivers need to be erased. Refer

How to implement Enums in Ruby?

Recently we released a gem that implements Enums in Ruby. In my post you will find the answers on your questions. Also I described there why our implementation is better than existing ones (actually there are many implementations of this feature in Ruby yet as gems).

What is the difference between a .cpp file and a .h file?

.h files, or header files, are used to list the publicly accessible instance variables and and methods in the class declaration. .cpp files, or implementation files, are used to actually implement those methods and use those instance variables.

The reason they are separate is because .h files aren't compiled into binary code while .cpp files are. Take a library, for example. Say you are the author and you don't want it to be open source. So you distribute the compiled binary library and the header files to your customers. That allows them to easily see all the information about your library's classes they can use without being able to see how you implemented those methods. They are more for the people using your code rather than the compiler. As was said before: it's the convention.

How to install multiple python packages at once using pip

You can install packages listed in a text file called requirements file. For example, if you have a file called req.txt containing the following text:


and you issue at the command line:

pip install -r req.txt

pip will install packages listed in the file at the specific revisions.

How to determine if a String has non-alphanumeric characters?

You have to go through each character in the String and check Character.isDigit(char); or Character.isletter(char);

Alternatively, you can use regex.

Removing a Fragment from the back stack

What happens if the fragment that you want to remove is not on top of the stack?

Then you can use theses functions

popBackStack(int arg0, int arg1);

popBackStack(String arg0, int arg1);

Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe

Try this, it will convert True into 1 and False into 0:

data.frame$  <- as.numeric(data.frame$

Then you can convert into factor if you want:

data.frame$ <- as .factor(data.frame$

python date of the previous month

import pandas as pd

lastmonth = int(pd.to_datetime("today").strftime("%Y%m"))-1



Is there a JavaScript strcmp()?

What about


Calculating days between two dates with Java

In Java 8, you could accomplish this by using LocalDate and DateTimeFormatter. From the Javadoc of LocalDate:

LocalDate is an immutable date-time object that represents a date, often viewed as year-month-day.

And the pattern can be constructed using DateTimeFormatter. Here is the Javadoc, and the relevant pattern characters I used:

Symbol - Meaning - Presentation - Examples

y - year-of-era - year - 2004; 04

M/L - month-of-year - number/text - 7; 07; Jul; July; J

d - day-of-month - number - 10

Here is the example:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class Java8DateExample {
    public static void main(String[] args) throws IOException {
        final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MM yyyy");
        final BufferedReader reader = new BufferedReader(new InputStreamReader(;
        final String firstInput = reader.readLine();
        final String secondInput = reader.readLine();
        final LocalDate firstDate = LocalDate.parse(firstInput, formatter);
        final LocalDate secondDate = LocalDate.parse(secondInput, formatter);
        final long days = ChronoUnit.DAYS.between(firstDate, secondDate);
        System.out.println("Days between: " + days);

Example input/output with more recent last:

23 01 1997
27 04 1997
Days between: 94

With more recent first:

27 04 1997
23 01 1997
Days between: -94

Well, you could do it as a method in a simpler way:

public static long betweenDates(Date firstDate, Date secondDate) throws IOException
    return ChronoUnit.DAYS.between(firstDate.toInstant(), secondDate.toInstant());

How do you scroll up/down on the console of a Linux VM

In some VPS hostings (like linode) you have to click Ctrl+A and then ESC. Exit with double ESC too.

How to implement the ReLU function in Numpy

EDIT As jirassimok has mentioned below my function will change the data in place, after that it runs a lot faster in timeit. This causes the good results. It's some kind of cheating. Sorry for your inconvenience.

I found a faster method for ReLU with numpy. You can use the fancy index feature of numpy as well.

fancy index:

20.3 ms ± 272 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

>>> x = np.random.random((5,5)) - 0.5 
>>> x
array([[-0.21444316, -0.05676216,  0.43956365, -0.30788116, -0.19952038],
       [-0.43062223,  0.12144647, -0.05698369, -0.32187085,  0.24901568],
       [ 0.06785385, -0.43476031, -0.0735933 ,  0.3736868 ,  0.24832288],
       [ 0.47085262, -0.06379623,  0.46904916, -0.29421609, -0.15091168],
       [ 0.08381359, -0.25068492, -0.25733763, -0.1852205 , -0.42816953]])
>>> x[x<0]=0
>>> x
array([[ 0.        ,  0.        ,  0.43956365,  0.        ,  0.        ],
       [ 0.        ,  0.12144647,  0.        ,  0.        ,  0.24901568],
       [ 0.06785385,  0.        ,  0.        ,  0.3736868 ,  0.24832288],
       [ 0.47085262,  0.        ,  0.46904916,  0.        ,  0.        ],
       [ 0.08381359,  0.        ,  0.        ,  0.        ,  0.        ]])

Here is my benchmark:

import numpy as np
x = np.random.random((5000, 5000)) - 0.5
print("max method:")
%timeit -n10 np.maximum(x, 0)
print("max inplace method:")
%timeit -n10 np.maximum(x, 0,x)
print("multiplication method:")
%timeit -n10 x * (x > 0)
print("abs method:")
%timeit -n10 (abs(x) + x) / 2
print("fancy index:")
%timeit -n10 x[x<0] =0

max method:
241 ms ± 3.53 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
max inplace method:
38.5 ms ± 4 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
multiplication method:
162 ms ± 3.1 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
abs method:
181 ms ± 4.18 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
fancy index:
20.3 ms ± 272 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

Loop through all the rows of a temp table and call a stored procedure for each row

you could use a cursor:

DECLARE @id int
DECLARE @pass varchar(100)

OPEN cur

FETCH NEXT FROM cur INTO @id, @pass

    EXEC mysp @id, @pass ... -- call your sp here
    FETCH NEXT FROM cur INTO @id, @pass

CLOSE cur    

How do you run a command for each line of a file?

The logic applies to many other objectives. And how to read .sh_history of each user from /home/ filesystem? What if there are thousand of them?

last |head -10|awk '{print $1}'|
 while IFS= read -r line
su - "$line" -c 'tail .sh_history'

Here is the script

Right way to reverse a pandas DataFrame?

You can reverse the rows in an even simpler way:


argparse module How to add option without any argument?

As @Felix Kling suggested use action='store_true':

>>> from argparse import ArgumentParser
>>> p = ArgumentParser()
>>> _ = p.add_argument('-f', '--foo', action='store_true')
>>> args = p.parse_args()
>>> args = p.parse_args(['-f'])

How to decode a Base64 string?

Base64 encoding converts three 8-bit bytes (0-255) into four 6-bit bytes (0-63 aka base64). Each of the four bytes indexes an ASCII string which represents the final output as four 8-bit ASCII characters. The indexed string is typically 'A-Za-z0-9+/' with '=' used as padding. This is why encoded data is 4/3 longer.

Base64 decoding is the inverse process. And as one would expect, the decoded data is 3/4 as long.

While base64 encoding can encode plain text, its real benefit is encoding non-printable characters which may be interpreted by transmitting systems as control characters.

I suggest the original poster render $z as bytes with each bit having meaning to the application. Rendering non-printable characters as text typically invokes Unicode which produces glyphs based on your system's localization.

Base64decode("the answer to life the universe and everything") = 00101010

Why is there no tuple comprehension in Python?

As another poster macm mentioned, the fastest way to create a tuple from a generator is tuple([generator]).

Performance Comparison

  • List comprehension:

    $ python3 -m timeit "a = [i for i in range(1000)]"
    10000 loops, best of 3: 27.4 usec per loop
  • Tuple from list comprehension:

    $ python3 -m timeit "a = tuple([i for i in range(1000)])"
    10000 loops, best of 3: 30.2 usec per loop
  • Tuple from generator:

    $ python3 -m timeit "a = tuple(i for i in range(1000))"
    10000 loops, best of 3: 50.4 usec per loop
  • Tuple from unpacking:

    $ python3 -m timeit "a = *(i for i in range(1000)),"
    10000 loops, best of 3: 52.7 usec per loop

My version of python:

$ python3 --version
Python 3.6.3

So you should always create a tuple from a list comprehension unless performance is not an issue.

CardView not showing Shadow in Android L

My recyclerview was slow in loading so by reading the I changed hardwareAccelerated to "false" then the elevation is not showing in the device. The I changed back to true. It works for me.

How to split a delimited string in Ruby and convert it to an array?

>> "1,2,3,4".split(",")
=> ["1", "2", "3", "4"]

Or for integers:

>> "1,2,3,4".split(",").map { |s| s.to_i }
=> [1, 2, 3, 4]

Or for later versions of ruby (>= 1.9 - as pointed out by Alex):

>> "1,2,3,4".split(",").map(&:to_i)
=> [1, 2, 3, 4]

Android Volley - BasicNetwork.performRequest: Unexpected response code 400

What I did was append an extra '/' to my url, e.g.:

String url = "" 


String url = ""

How to retrieve SQL result column value using column name in Python?

import pymysql

# Open database connection
db = pymysql.connect("localhost","root","","gkdemo1")

# prepare a cursor object using cursor() method
cursor = db.cursor()

# execute SQL query using execute() method.
cursor.execute("SELECT * from user")

# Get the fields name (only once!)
field_name = [field[0] for field in cursor.description]

# Fetch a single row using fetchone() method.
values = cursor.fetchone()

# create the row dictionary to be able to call row['login']
**row = dict(zip(field_name, values))**

# print the dictionary

# print specific field

# print all field
for key in row:
    print(**key," = ",row[key]**)

# close database connection

Cannot find libcrypto in Ubuntu

I solved this on 12.10 by installing libssl-dev.

sudo apt-get install libssl-dev

Convert Uppercase Letter to Lowercase and First Uppercase in Sentence using CSS

If use this on capitalized text;

p text-transform: lowercase;

Then show the text, it is lowercase but if you copy that lower-cased text, and paste it, it change back to original capitalized.

When would you use the different git merge strategies?

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

git merge -s ort

This comes from this thread from Elijah Newren:

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

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


In the ideal world, we should:

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

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

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

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


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

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

Signed-off-by: Elijah Newren

This is the beginning of a new merge strategy.

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

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

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

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


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

t6423, t6436: note improved ort handling with dirty files

Signed-off-by: Elijah Newren

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

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

t6423: expect improved conflict markers labels in the ort backend

Signed-off-by: Elijah Newren

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

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

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

Signed-off-by: Elijah Newren

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

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

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

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

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

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

Signed-off-by: Elijah Newren

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

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

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

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

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

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

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

merge-ort: add implementation of record_conflicted_index_entries()

Signed-off-by: Elijah Newren

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

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

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

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


merge-ort: add implementation of normal rename handling

Signed-off-by: Elijah Newren

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

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

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

  • handle_rename_normal()
  • setup_rename_conflict_info()

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

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

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

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

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

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

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

Signed-off-by: Elijah Newren

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

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

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

How to remove constraints from my MySQL table?

To add a little to Robert Knight's answer, since the title of the post itself doesn't mention foreign keys (and since his doesn't have complete code samples and since SO's comment code blocks don't show as well as the answers' code blocks), I'll add this for unique constraints. Either of these work to drop the constraint:

ALTER TABLE `table_name` DROP KEY `uc_name`;


ALTER TABLE `table_name` DROP INDEX `uc_name`;

Using variable in SQL LIKE statement

If you are using a Stored Procedure:

    @PartialName VARCHAR(50) = NULL

    FROM <table>
    WHERE Name LIKE '%' + @PartialName + '%'

Best practices for API versioning?

Put your version in the URI. One version of an API will not always support the types from another, so the argument that resources are merely migrated from one version to another is just plain wrong. It's not the same as switching format from XML to JSON. The types may not exist, or they may have changed semantically.

Versions are part of the resource address. You're routing from one API to another. It's not RESTful to hide addressing in the header.

How to cast List<Object> to List<MyClass>

You can create a new List and add the elements to it:

For example:

List<A> a = getListOfA();
List<Object> newList = new ArrayList<>();

python numpy ValueError: operands could not be broadcast together with shapes

We might confuse ourselves that a * b is a dot product.

But in fact, it is broadcast.

Dot Product :


The term broadcasting refers to how numpy treats arrays with different dimensions during arithmetic operations which lead to certain constraints, the smaller array is broadcast across the larger array so that they have compatible shapes.

(m,n) +-/* (1,n) ? (m,n) : the operation will be applied to m rows

How to check if a String contains any of some strings

Well, there's always this:

public static bool ContainsAny(this string haystack, params string[] needles)
    foreach (string needle in needles)
        if (haystack.Contains(needle))
            return true;

    return false;


bool anyLuck = s.ContainsAny("a", "b", "c");

Nothing's going to match the performance of your chain of || comparisons, however.

socket.emit() vs. socket.send()

socket.send // Sends a message event

socket.emit(eventName[, ...args][, ack]) // you can custom eventName

How to read a text file directly from Internet using Java?

What really worked to me: (source: oracle documentation "reading url")


 public class UrlTextfile {
public static void main(String[] args) throws Exception {

    URL oracle = new URL("");
    BufferedReader in = new BufferedReader(
    new InputStreamReader(oracle.openStream()));

    String inputLine;
    while ((inputLine = in.readLine()) != null)

What Scala web-frameworks are available?

One very interesting web framework with commercial deployment is Scalatra, inspired by Ruby's Sinatra. Here's an InfoQ article about it.

Using Excel OleDb to get sheet names IN SHEET ORDER

This is short, fast, safe, and usable...

public static List<string> ToExcelsSheetList(string excelFilePath)
    List<string> sheets = new List<string>();
    using (OleDbConnection connection = 
            new OleDbConnection((excelFilePath.TrimEnd().ToLower().EndsWith("x")) 
            ? "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + excelFilePath + "';" + "Extended Properties='Excel 12.0 Xml;HDR=YES;'"
            : "provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + excelFilePath + "';Extended Properties=Excel 8.0;"))
        DataTable dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
        foreach (DataRow drSheet in dt.Rows)
            if (drSheet["TABLE_NAME"].ToString().Contains("$"))
                string s = drSheet["TABLE_NAME"].ToString();
                sheets.Add(s.StartsWith("'")?s.Substring(1, s.Length - 3): s.Substring(0, s.Length - 1));
    return sheets;

Calling method using JavaScript prototype

Well one way to do it would be saving the base method and then calling it from the overriden method, like so

MyClass.prototype._do_base =; = function(){  

    if ( === 'something'){

        //do something new

        return this._do_base();


How do you sort a dictionary by value?


using System.Linq.Enumerable;
List<KeyValuePair<string, string>> myList = aDictionary.ToList();

    delegate(KeyValuePair<string, string> pair1,
    KeyValuePair<string, string> pair2)
        return pair1.Value.CompareTo(pair2.Value);

Since you're targeting .NET 2.0 or above, you can simplify this into lambda syntax -- it's equivalent, but shorter. If you're targeting .NET 2.0 you can only use this syntax if you're using the compiler from Visual Studio 2008 (or above).

var myList = aDictionary.ToList();

myList.Sort((pair1,pair2) => pair1.Value.CompareTo(pair2.Value));

How to disable Python warnings?

If you know what are the useless warnings you usually encounter, you can filter them by message.

import warnings

#ignore by message
warnings.filterwarnings("ignore", message="divide by zero encountered in divide")

#part of the message is also okay
warnings.filterwarnings("ignore", message="divide by zero encountered") 
warnings.filterwarnings("ignore", message="invalid value encountered")

Method List in Visual Studio Code

CTRL+F12 (CMD+F12 for Mac) - opens for me all methods and members in PHP class.

What is the difference between lower bound and tight bound?

The phrases minimum time and maximum time are a bit misleading here. When we talk about big O notations, it's not the actual time we are interested in, it is how the time increases when our input size gets bigger. And it's usually the average or worst case time we are talking about, not best case, which usually is not meaningful in solving our problems.

Using the array search in the accepted answer to the other question as an example. The time it takes to find a particular number in list of size n is n/2 * some_constant in average. If you treat it as a function f(n) = n/2*some_constant, it increases no faster than g(n) = n, in the sense as given by Charlie. Also, it increases no slower than g(n) either. Hence, g(n) is actually both an upper bound and a lower bound of f(n) in Big-O notation, so the complexity of linear search is exactly n, meaning that it is Theta(n).

In this regard, the explanation in the accepted answer to the other question is not entirely correct, which claims that O(n) is upper bound because the algorithm can run in constant time for some inputs (this is the best case I mentioned above, which is not really what we want to know about the running time).

Logcat not displaying my log calls

I had a problem seeing simple log output in logcat as well. My problem was solved when I installed the latest JDK. I just setup a new development machine and only had the JRE installed and instaling the JDK worked for me.

Could not load file or assembly 'System.Web.WebPages.Razor, Version=

In ASP.NET MVC 4, the namespace is not System.Web.WebPages.Razor, but System.Web.Razor

That worked for me, change your web.config.

Why does my favicon not show up?

Favicons only work when served from a web-server which sets mime-types correctly for served content. Loading from a local file might not work in chromium. Loading from an incorrectly configured web-server will not work.

Web-servers such as lighthttpd must be configured manually to set the mime type correctly.

Because of the likelihood that mimetype assignment will not work in all environments, I would suggest you use an inline base64 encoded ico file instead. This will load faster as well, as it reduces the number of http requests sent to the server.

On POSIX based systems you can base64 encode a file with the base64 command.

To create a base64 encoded ico line use the command:

$ base64 favicon.ico --wrap 0

And insert the output into the line:

<link href="data:image/x-icon;base64,HERE" rel="icon" type="image/x-icon" />

Replacing the word HERE like so:


How to add message box with 'OK' button?

protected Dialog onCreateDialog(int id)
    case 0:
        return new AlertDialog.Builder(this)
        .setMessage("text here")
        .setPositiveButton("OK", new DialogInterface.OnClickListener() 
            public void onClick(DialogInterface arg0, int arg1) 

                }//end try
                catch(Exception e)
                    Toast.makeText(getBaseContext(),  "", Toast.LENGTH_LONG).show();
                }//end catch
            }//end onClick()
    }//end case
  }//end switch
    return null;
}//end onCreateDialog

How to run multiple .BAT files within a .BAT file

using "&"

As you have noticed executing the bat directly without CALL,START, CMD /C causes to enter and execute the first file and then the process to stop as the first file is finished. Though you still can use & which will be the same as using command1 & command2 directly in the console:

)& (
    echo other commands

In a term of machine resources this will be the most efficient way though in the last block you won't be able to use command line GOTO,SHIFT,SETLOCAL.. and its capabilities will almost the same as in executing commands in the command prompt. And you won't be able to execute other command after the last closing bracket

Using CALL

call first.bat
call second.bat
call third.bat

In most of the cases it will be best approach - it does not create a separate process but has almost identical behaviour as calling a :label as subroutine. In MS terminology it creates a new "batch file context and pass control to the statement after the specified label. The first time the end of the batch file is encountered (that is, after jumping to the label), control returns to the statement after the call statement."

You can use variables set in the called files (if they are not set in a SETLOCAL block), you can access directly labels in the called file.

CMD /C, Pipes ,FOR /F

Other native option is to use CMD /C (the /C switch will force the called console to exit and return the control) Something that cmd.exe is doing in non transparent way with using FOR /F against bat file or when pipes are used. This will spawn a child process that will have all the environment ot the calling bat. Less efficient in terms of resources but as the process is separate ,parsing crashes or calling an EXIT command will not stop the calling .bat

@echo off
CMD /c first.bat
CMD /C second.bat

::not so different than the above lines.
:: MORE,FINDSTR,FIND command will be able to read the piped data 
:: passed from the left side



Allows you more flexibility as the capability to start the scripts in separate window , to not wait them to finish, setting a title and so on. By default it starts the .bat and .cmd scripts with CMD /K which means that the spawned scripts will not close automatically.Again passes all the environment to the started scripts and consumes more resources than cmd /c:

:: will be executed in the same console window and will wait to finish
start "" /b /w cmd /c first.bat 

::will start in a separate console window and WONT wait to be finished
:: the second console window wont close automatically so second.bat might need explicit exit command
start "" second.bat

::Will start it in a separate window ,but will wait to finish
:: closing the second window will cause Y/N prompt
:: in the original window 
start "" /w third.cmd

::will start it in the same console window
:: but wont wait to finish. May lead to a little bit confusing output
start "" /b cmd /c fourth.bat


Unlike the other methods from now on the examples will use external of the CMD.exe utilities (still available on Windows by default). WMIC utility will create completely separate process so you wont be able directly to wait to finish. Though the best feature of WMIC is that it returns the id of the spawned process:

:: will create a separate process with cmd.exe /c
WMIC process call create "%cd%\first.bat","%cd%"

::you can get the PID and monitoring it with other tools
for /f "tokens=2 delims=;= " %%# in ('WMIC process call create "%cd%\second.bat"^,"%cd%" ^|find "ProcessId"') do (
    set "PID=%%#"
echo %PID%

You can also use it to start a process on a remote machine , with different user and so on.


Using SCHTASKS provides some features as (obvious) scheduling , running as another user (even the system user) , remote machine start and so on. Again starts it in completely separate environment (i.e. its own variables) and even a hidden process, xml file with command parameters and so on :

SCHTASKS /create /tn BatRunner /tr "%cd%\first.bat" /sc ONCE /sd 01/01/1910 /st 00:00
SCHTASKS /Run /TN BatRunner
SCHTASKS /Delete /TN BatRunner /F

Here the PID also can acquired from the event log.


Offers some timeout between started scripts. Basic transaction capabilities (i.e. rollback on error) and the parameters can be put in a separate XML file.

::if the script is not finished after 15 seconds (i.e. ends with pause) it will be killed
ScriptRunner.exe -appvscript %cd%\first.bat -appvscriptrunnerparameters -wait -timeout=15

::will wait or the first called script before to start the second
:: if any of the scripts exit with errorcode different than 0 will try
:: try to restore the system in the original state
ScriptRunner.exe -appvscript second.cmd arg1 arg2 -appvscriptrunnerparameters -wait -rollbackonerror -appvscript third.bat -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror

What is SuppressWarnings ("unchecked") in Java?

It is an annotation to suppress compile warnings about unchecked generic operations (not exceptions), such as casts. It essentially implies that the programmer did not wish to be notified about these which he is already aware of when compiling a particular bit of code.

You can read more on this specific annotation here:


Additionally, Oracle provides some tutorial documentation on the usage of annotations here:


As they put it,

"The 'unchecked' warning can occur when interfacing with legacy code written before the advent of generics (discussed in the lesson titled Generics)."

Split string into tokens and save them in an array

You can use strtok()

char string[]=  "abc/qwe/jkh";
char *array[10];
int i=0;

array[i] = strtok(string,"/");

   array[++i] = strtok(NULL,"/");

M_PI works with math.h but not with cmath in Visual Studio

Interestingly I checked this on an app of mine and I got the same error.

I spent a while checking through headers to see if there was anything undef'ing the _USE_MATH_DEFINES and found nothing.

So I moved the

#include <cmath>

to be the first thing in my file (I don't use PCHs so if you are you will have to have it after the #include "stdafx.h") and suddenly it compile perfectly.

Try moving it higher up the page. Totally unsure as to why this would cause issues though.

Edit: Figured it out. The #include <math.h> occurs within cmath's header guards. This means that something higher up the list of #includes is including cmath without the #define specified. math.h is specifically designed so that you can include it again with that define now changed to add M_PI etc. This is NOT the case with cmath. So you need to make sure you #define _USE_MATH_DEFINES before you include anything else. Hope that clears it up for you :)

Failing that just include math.h you are using non-standard C/C++ as already pointed out :)

Edit 2: Or as David points out in the comments just make yourself a constant that defines the value and you have something more portable anyway :)

AngularJS resource promise

$q.when(scope.regions).then(function(result) {
var Regions = $resource('mocks/regions.json');
$scope.regions = Regions.query().$promise.then(function(response) {
    return response;

Can Android do peer-to-peer ad-hoc networking?

Here's a bug report on the feature you're requesting.

It's status is "reviewed" but I don't believe it's been implemented yet.

No more data to read from socket error

We were facing same problem, we resolved it by increasing initialSize and maxActive size of connection pool.

You can check this link

Maybe this helps someone.

Loading an image to a <img> from <input file>

var outImage ="imagenFondo";_x000D_
function preview_2(obj)_x000D_
 if (FileReader)_x000D_
  var reader = new FileReader();_x000D_
  reader.onload = function (e) {_x000D_
  var image=new Image();_x000D_;_x000D_
  image.onload = function () {_x000D_
      // Not supported_x000D_
<!doctype html>_x000D_
<meta charset="utf-8">_x000D_
<title>preview photo</title>_x000D_
 <input type="file" onChange="preview_2(this);"><br>_x000D_
 <img id="imagenFondo" style="height: 300px;width: 300px;">_x000D_

jQuery append() - return appended elements

var newElementsAppended = $(newHtml).appendTo("#myDiv");
newElementsAppended.effects("highlight", {}, 2000);

java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0)

You will get this error when you call any of the setXxx() methods on PreparedStatement, while the SQL query string does not have any placeholders ? for this.

For example this is wrong:

String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (val1, val2, val3)";
// ...

preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1); // Fail.
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);

You need to fix the SQL query string accordingly to specify the placeholders.

String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (?, ?, ?)";
// ...

preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1);
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);

Note the parameter index starts with 1 and that you do not need to quote those placeholders like so:

String sql = "INSERT INTO tablename (col1, col2, col3) VALUES ('?', '?', '?')";

Otherwise you will still get the same exception, because the SQL parser will then interpret them as the actual string values and thus can't find the placeholders anymore.

See also:

Simple parse JSON from URL on Android and display in listview

try as:

 // your get json request to server.. 
 HttpResponse response = httpClient.execute(httpPost);
 HttpEntity entity = response.getEntity();

 if(entity != null){
    JSONObject respObject = new JSONObject(EntityUtils.toString(entity));
    String active = respObject.getString("active");   
    String name = respObject.getString("name");  
    String tab1_text = respObject.getString("tab1_text");  
       //Do something here...

see this example for Getting and parsing json response from server :

get current page from url

Try this:


How to get current date in jquery?

var d = new Date();
var month = d.getMonth() + 1;
var day = d.getDate();
var year = d.getYear();
var today = (day<10?'0':'')+ day + '/' +(month<10?'0':'')+ month + '/' + year;