Programs & Examples On #Anonymous function

Anonymous functions use a block of code as a value, defining it as an inline function without a name.

How can I write an anonymous function in Java?

Yes if you are using latest java which is version 8. Java8 make it possible to define anonymous functions which was impossible in previous versions.

Lets take example from java docs to get know how we can declare anonymous functions, classes

The following example, HelloWorldAnonymousClasses, uses anonymous classes in the initialization statements of the local variables frenchGreeting and spanishGreeting, but uses a local class for the initialization of the variable englishGreeting:

public class HelloWorldAnonymousClasses {

    interface HelloWorld {
        public void greet();
        public void greetSomeone(String someone);
    }

    public void sayHello() {

        class EnglishGreeting implements HelloWorld {
            String name = "world";
            public void greet() {
                greetSomeone("world");
            }
            public void greetSomeone(String someone) {
                name = someone;
                System.out.println("Hello " + name);
            }
        }

        HelloWorld englishGreeting = new EnglishGreeting();

        HelloWorld frenchGreeting = new HelloWorld() {
            String name = "tout le monde";
            public void greet() {
                greetSomeone("tout le monde");
            }
            public void greetSomeone(String someone) {
                name = someone;
                System.out.println("Salut " + name);
            }
        };

        HelloWorld spanishGreeting = new HelloWorld() {
            String name = "mundo";
            public void greet() {
                greetSomeone("mundo");
            }
            public void greetSomeone(String someone) {
                name = someone;
                System.out.println("Hola, " + name);
            }
        };
        englishGreeting.greet();
        frenchGreeting.greetSomeone("Fred");
        spanishGreeting.greet();
    }

    public static void main(String... args) {
        HelloWorldAnonymousClasses myApp =
            new HelloWorldAnonymousClasses();
        myApp.sayHello();
    }            
}

Syntax of Anonymous Classes

Consider the instantiation of the frenchGreeting object:

    HelloWorld frenchGreeting = new HelloWorld() {
        String name = "tout le monde";
        public void greet() {
            greetSomeone("tout le monde");
        }
        public void greetSomeone(String someone) {
            name = someone;
            System.out.println("Salut " + name);
        }
    };

The anonymous class expression consists of the following:

  • The new operator
  • The name of an interface to implement or a class to extend. In this example, the anonymous class is implementing the interface HelloWorld.

  • Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression. Note: When you implement an interface, there is no constructor, so you use an empty pair of parentheses, as in this example.

  • A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not.

How to sort with lambda in Python

Use

a = sorted(a, key=lambda x: x.modified, reverse=True)
#             ^^^^

On Python 2.x, the sorted function takes its arguments in this order:

sorted(iterable, cmp=None, key=None, reverse=False)

so without the key=, the function you pass in will be considered a cmp function which takes 2 arguments.

Is it valid to define functions in JSON results?

Via using NodeJS (commonJS syntax) I was able to get this type of functionality working, I originally had just a JSON structure inside some external JS file, but I wanted that structure to be more of a Class, with methods that could be decided at run time.

The declaration of 'Executor' in myJSON is not required.

var myJSON = {
    "Hello": "World",
    "Executor": ""
}

module.exports = {
    init: () => { return { ...myJSON, "Executor": (first, last) => { return first + last } } }
}

How can I pass a reference to a function, with parameters?

You can also overload the Function prototype:

// partially applies the specified arguments to a function, returning a new function
Function.prototype.curry = function( ) {
    var func = this;
    var slice = Array.prototype.slice;
    var appliedArgs = slice.call( arguments, 0 );

    return function( ) {
        var leftoverArgs = slice.call( arguments, 0 );
        return func.apply( this, appliedArgs.concat( leftoverArgs ) );
    };
};

// can do other fancy things:

// flips the first two arguments of a function
Function.prototype.flip = function( ) {
    var func = this;
    return function( ) {
        var first = arguments[0];
        var second = arguments[1];
        var rest = Array.prototype.slice.call( arguments, 2 );
        var newArgs = [second, first].concat( rest );

        return func.apply( this, newArgs );
    };
};

/*
e.g.

var foo = function( a, b, c, d ) { console.log( a, b, c, d ); }
var iAmA = foo.curry( "I", "am", "a" );
iAmA( "Donkey" );
-> I am a Donkey

var bah = foo.flip( );
bah( 1, 2, 3, 4 );
-> 2 1 3 4
*/

Why do you need to invoke an anonymous function on the same line?

The IIFE simply compartmentalizes the function and hides the msg variable so as to not "pollute" the global namespace. In reality, just keep it simple and do like below unless you are building a billion dollar website.

var msg = "later dude";
window.onunload = function(msg){
  alert( msg );
};

You could namespace your msg property using a Revealing Module Pattern like:

var myScript = (function() {
    var pub = {};
    //myscript.msg
    pub.msg = "later dude";
    window.onunload = function(msg) {
        alert(msg);
    };
    //API
    return pub;
}());

removeEventListener on anonymous functions in JavaScript

window.document.removeEventListener("keydown", getEventListeners(window.document.keydown[0].listener));  

May be several anonymous functions, keydown1

Warning: only works in Chrome Dev Tools & cannot be used in code: link

The opposite of Intersect()

/// <summary>
/// Given two list, compare and extract differences
/// http://stackoverflow.com/questions/5620266/the-opposite-of-intersect
/// </summary>
public class CompareList
{
    /// <summary>
    /// Returns list of items that are in initial but not in final list.
    /// </summary>
    /// <param name="listA"></param>
    /// <param name="listB"></param>
    /// <returns></returns>
    public static IEnumerable<string> NonIntersect(
        List<string> initial, List<string> final)
    {
        //subtracts the content of initial from final
        //assumes that final.length < initial.length
        return initial.Except(final);
    }

    /// <summary>
    /// Returns the symmetric difference between the two list.
    /// http://en.wikipedia.org/wiki/Symmetric_difference
    /// </summary>
    /// <param name="initial"></param>
    /// <param name="final"></param>
    /// <returns></returns>
    public static IEnumerable<string> SymmetricDifference(
        List<string> initial, List<string> final)
    {
        IEnumerable<string> setA = NonIntersect(final, initial);
        IEnumerable<string> setB = NonIntersect(initial, final);
        // sum and return the two set.
        return setA.Concat(setB);
    }
}

Why is "cursor:pointer" effect in CSS not working

I found a solution: use :hover with cursor: pointer if nothing else helps.

Index was outside the bounds of the Array. (Microsoft.SqlServer.smo)

The suggested causes are now proven to be mostly impossible. I'm running SSMS V17.9.2 against SS 2014 and still have the problem. Memory problems have existed with this tool since at least 2006 when I started using SSMS.

Yes, MS 'wants' to get rid of diagramming but users won't let them. I have a feeling they will never fix any of these issues because they want users to be so fed up with the tool that enough of them quit using it and they can abandon it entirely.

Restarting is still a workaround if you can stand doing so numerous times per day.

grep output to show only matching file

You can use the Unix-style -l switch – typically terse and cryptic – or the equivalent --files-with-matches – longer and more readable.

The output of grep --help is not easy to read, but it's there:

-l, --files-with-matches  print only names of FILEs containing matches

Is there a way to add a gif to a Markdown file?

just upload the .gif file into your base folder of GitHub and edit README.md just use this code

![](name-of-giphy.gif)

How do I clear my Jenkins/Hudson build history?

Using Script Console.

In case the jobs are grouped it's possible to either give it a full name with forward slashes:

getItemByFullName("folder_name/job_name") 
job.getBuilds().each { it.delete() }
job.nextBuildNumber = 1
job.save()

or traverse the hierarchy like this:

def folder = Jenkins.instance.getItem("folder_name")
def job = folder.getItem("job_name")
job.getBuilds().each { it.delete() }
job.nextBuildNumber = 1
job.save()

Laravel Eloquent - Get one Row

Using Laravel Eloquent you can get one row using first() method,

it returns first row of table if where() condition is not found otherwise it gives the first matched row of given criteria.

Syntax:

Model::where('fieldname',$value)->first();

Example:

$user = User::where('email',$email)->first(); 
//OR
//$user = User::whereEmail($email)->first();

Visual studio code CSS indentation and formatting

Beautify (Github) & Prettier (Github) are the best plugin for web development in Visual Studio Code.

How to play or open *.mp3 or *.wav sound file in c++ program?

First of all, write the following code:

#include <Mmsystem.h>
#include <mciapi.h>
//these two headers are already included in the <Windows.h> header
#pragma comment(lib, "Winmm.lib")

To open *.mp3:

mciSendString("open \"*.mp3\" type mpegvideo alias mp3", NULL, 0, NULL);

To play *.mp3:

mciSendString("play mp3", NULL, 0, NULL);

To play and wait until the *.mp3 has finished playing:

mciSendString("play mp3 wait", NULL, 0, NULL);

To replay (play again from start) the *.mp3:

mciSendString("play mp3 from 0", NULL, 0, NULL);

To replay and wait until the *.mp3 has finished playing:

mciSendString("play mp3 from 0 wait", NULL, 0, NULL);

To play the *.mp3 and replay it every time it ends like a loop:

mciSendString("play mp3 repeat", NULL, 0, NULL);

If you want to do something when the *.mp3 has finished playing, then you need to RegisterClassEx by the WNDCLASSEX structure, CreateWindowEx and process it's messages with the GetMessage, TranslateMessage and DispatchMessage functions in a while loop and call:

mciSendString("play mp3 notify", NULL, 0, hwnd); //hwnd is an handle to the window returned from CreateWindowEx. If this doesn't work, then replace the hwnd with MAKELONG(hwnd, 0).

In the window procedure, add the case MM_MCINOTIFY: The code in there will be executed when the mp3 has finished playing.

But if you program a Console Application and you don't deal with windows, then you can CreateThread in suspend state by specifying the CREATE_SUSPENDED flag in the dwCreationFlags parameter and keep the return value in a static variable and call it whatever you want. For instance, I call it mp3. The type of this static variable is HANDLE of course.

Here is the ThreadProc for the lpStartAddress of this thread:

DWORD WINAPI MP3Proc(_In_ LPVOID lpParameter) //lpParameter can be a pointer to a structure that store data that you cannot access outside of this function. You can prepare this structure before `CreateThread` and give it's address in the `lpParameter`
{
    Data *data = (Data*)lpParameter; //If you call this structure Data, but you can call it whatever you want.
    while (true)
    {
        mciSendString("play mp3 from 0 wait", NULL, 0, NULL);
        //Do here what you want to do when the mp3 playback is over
        SuspendThread(GetCurrentThread()); //or the handle of this thread that you keep in a static variable instead
    }
}

All what you have to do now is to ResumeThread(mp3); every time you want to replay your mp3 and something will happen every time it finishes.

You can #define play_my_mp3 ResumeThread(mp3); to make your code more readable.

Of course you can remove the while (true), SuspendThread and the from 0 codes, if you want to play your mp3 file only once and do whatever you want when it is over.

If you only remove the SuspendThread call, then the sound will play over and over again and do something whenever it is over. This is equivalent to:

mciSendString("play mp3 repeat notify", NULL, 0, hwnd); //or MAKELONG(hwnd, 0) instead

in windows.

To pause the *.mp3 in middle:

mciSendString("pause mp3", NULL, 0, NULL);

and to resume it:

mciSendString("resume mp3", NULL, 0, NULL);

To stop it in middle:

mciSendString("stop mp3", NULL, 0, NULL);

Note that you cannot resume a sound that has been stopped, but only paused, but you can replay it by carrying out the play command. When you're done playing this *.mp3, don't forget to:

mciSendString("close mp3", NULL, 0, NULL);

All these actions also apply to (work with) wave files too, but with wave files, you can use "waveaudio" instead of "mpegvideo". Also you can just play them directly without opening them:

PlaySound("*.wav", GetModuleHandle(NULL), SND_FILENAME);

If you don't want to specify an handle to a module:

sndPlaySound("*.wav", SND_FILENAME);

If you don't want to wait until the playback is over:

PlaySound("*.wav", GetModuleHandle(NULL), SND_FILENAME | SND_ASYNC);
//or
sndPlaySound("*.wav", SND_FILENAME | SND_ASYNC);

To play the wave file over and over again:

PlaySound("*.wav", GetModuleHandle(NULL), SND_FILENAME | SND_ASYNC | SND_LOOP);
//or
sndPlaySound("*.wav", SND_FILENAME | SND_ASYNC | SND_LOOP);

Note that you must specify both the SND_ASYNC and SND_LOOP flags, because you never going to wait until a sound, that repeats itself countless times, is over!

Also you can fopen the wave file and copy all it's bytes to a buffer (an enormous/huge (very big) array of bytes) with the fread function and then:

PlaySound(buffer, GetModuleHandle(NULL), SND_MEMORY);
//or
PlaySound(buffer, GetModuleHandle(NULL), SND_MEMORY | SND_ASYNC);
//or
PlaySound(buffer, GetModuleHandle(NULL), SND_MEMORY | SND_ASYNC | SND_LOOP);
//or
sndPlaySound(buffer, SND_MEMORY);
//or
sndPlaySound(buffer, SND_MEMORY | SND_ASYNC);
//or
sndPlaySound(buffer, SND_MEMORY | SND_ASYNC | SND_LOOP);

Either OpenFile or CreateFile or CreateFile2 and either ReadFile or ReadFileEx functions can be used instead of fopen and fread functions.

Hope this fully answers perfectly your question.

Maven error: Not authorized, ReasonPhrase:Unauthorized

The issue may happen while fetching dependencies from a remote repository. In my case, the repository did not need any authentication and it has been resolved by removing the servers section in the settings.xml file:

<servers>
    <server>
      <id>SomeRepo</id>
      <username>SomeUN</username>
      <password>SomePW</password>
    </server>
</servers>

ps: I guess your target is mvn clean install instead of maven install clean

Confirm postback OnClientClick button ASP.NET

The code is like this:

In Aspx:

<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" CausesValidation=true />

in Cs:

protected void Page_Load(object sender, System.EventArgs e)
{
     if (!IsPostBack)
     {
         btnSave.Attributes["Onclick"] = "return confirm('Do you really want to save?')";          
     }
}

protected void btnSave_Click(object sender, EventArgs e){
    Page.Validate();
    if (Page.IsValid)
    {
       //Update the database
         lblMessage.Text = "Saved Successfully";
    }
}

How to get a list of current open windows/process with Java?

_x000D_
_x000D_
    String line;_x000D_
    Process process = Runtime.getRuntime().exec("ps -e");_x000D_
    process.getOutputStream().close();_x000D_
    BufferedReader input =_x000D_
            new BufferedReader(new InputStreamReader(process.getInputStream()));_x000D_
    while ((line = input.readLine()) != null) {_x000D_
        System.out.println(line); //<-- Parse data here._x000D_
    }_x000D_
    input.close();
_x000D_
_x000D_
_x000D_

We have to use process.getOutputStream.close() otherwise it will get locked in while loop.

How to compute the similarity between two text documents?

You might want to try this online service for cosine document similarity http://www.scurtu.it/documentSimilarity.html

import urllib,urllib2
import json
API_URL="http://www.scurtu.it/apis/documentSimilarity"
inputDict={}
inputDict['doc1']='Document with some text'
inputDict['doc2']='Other document with some text'
params = urllib.urlencode(inputDict)    
f = urllib2.urlopen(API_URL, params)
response= f.read()
responseObject=json.loads(response)  
print responseObject

Index of duplicates items in a python list

I think I found a simple solution after a lot of irritation :

if elem in string_list:
    counter = 0
    elem_pos = []
    for i in string_list:
        if i == elem:
            elem_pos.append(counter)
        counter = counter + 1
    print(elem_pos)

This prints a list giving you the indexes of a specific element ("elem")

How to get option text value using AngularJS?

Instead of ng-options="product as product.label for product in products"> in the select element, you can even use this:

<option ng-repeat="product in products" value="{{product.label}}">{{product.label}}

which works just fine as well.

.toLowerCase not working, replacement function?

It is a number, not a string. Numbers don't have a toLowerCase() function because numbers do not have case in the first place.

To make the function run without error, run it on a string.

var ans = "334";

Of course, the output will be the same as the input since, as mentioned, numbers don't have case in the first place.

mysql: SOURCE error 2?

Remove spaces in the folder names of the path, It worked for my mac path.

(Eg: change the folder name MySQL Server 5.1 to MySQLServer5.1)

Spring Boot REST API - request timeout?

if you are using RestTemplate than you should use following code to implement timeouts

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate(clientHttpRequestFactory());
}

private ClientHttpRequestFactory clientHttpRequestFactory() {
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    factory.setReadTimeout(2000);
    factory.setConnectTimeout(2000);
    return factory;
}}

The xml configuration

<bean class="org.springframework.web.client.RestTemplate">
<constructor-arg>
    <bean class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory"
        p:readTimeout="2000"
        p:connectTimeout="2000" />
</constructor-arg>

How do I check if a SQL Server text column is empty?

I know there are plenty answers with alternatives to this problem, but I just would like to put together what I found as the best solution by @Eric Z Beard & @Tim Cooper with @Enrique Garcia & @Uli Köhler.

If needed to deal with the fact that space-only could be the same as empty in your use-case scenario, because the query below will return 1, not 0.

SELECT datalength(' ')

Therefore, I would go for something like:

SELECT datalength(RTRIM(LTRIM(ISNULL([TextColumn], ''))))

How to generate serial version UID in Intellij

with in the code editor, Open the class you want to create the UID for , Right click -> Generate -> SerialVersionUID. You may need to have the GenerateSerialVersionUID plugin installed for this to work.

How to set margin with jquery?

Set it with a px value. Changing the code like below should work

el.css('marginLeft', mrg + 'px');

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.

How to detect incoming calls, in an Android device?

You need a BroadcastReceiver for ACTION_PHONE_STATE_CHANGED This will call your received whenever the phone-state changes from idle, ringing, offhook so from the previous value and the new value you can detect if this is an incoming/outgoing call.

Required permission would be:

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

But if you also want to receive the EXTRA_INCOMING_NUMBER in that broadcast, you'll need another permission: "android.permission.READ_CALL_LOG"

And the code something like this:

val receiver: BroadcastReceiver = object : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        Log.d(TAG, "onReceive")
    }
}

override fun onResume() {
    val filter = IntentFilter()
    filter.addAction("android.intent.action.PHONE_STATE")
    registerReceiver(receiver, filter)
    super.onResume()
}

override fun onPause() {
    unregisterReceiver(receiver)
    super.onPause()
}

and in receiver class, we can get current state by reading intent like this:

intent.extras["state"]

the result of extras could be:

RINGING -> If your phone is ringing

OFFHOOK -> If you are talking with someone (Incoming or Outcoming call)

IDLE -> if call ended (Incoming or Outcoming call)

With PHONE_STATE broadcast we don't need to use PROCESS_OUTGOING_CALLS permission or deprecated NEW_OUTGOING_CALL action.

How to click or tap on a TextView text

This may not be quite what you are looking for but this is what worked for what I'm doing. All of this is after my onCreate:

boilingpointK = (TextView) findViewById(R.id.boilingpointK);

boilingpointK.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if ("Boiling Point K".equals(boilingpointK.getText().toString()))
            boilingpointK.setText("2792");
        else if ("2792".equals(boilingpointK.getText().toString()))
            boilingpointK.setText("Boiling Point K");
    }
});

Can I safely delete contents of Xcode Derived data folder?

 $ du -h -d=1 ~/Library/Developer/Xcode/*

shows at least two folders are huge:

 1.5G   /Users/horace/Library/Developer/Xcode/DerivedData
 9.4G   /Users/horace/Library/Developer/Xcode/iOS DeviceSupport

Feel free to remove stuff in the folders:

 rm -rf ~/Library/Developer/Xcode/DerivedData/*

and some in:

 open ~/Library/Developer/Xcode/iOS\ DeviceSupport/

Get UTC time in seconds

I bet this is what was intended as a result.

$ date -u --date=@1404372514
Thu Jul  3 07:28:34 UTC 2014

How to define an enum with string value?

For people arriving here looking for an answer to a more generic question, you can extend the static class concept if you want your code to look like an enum.

The following approach works when you haven't finalised the enum names you want and the enum values are the string representation of the enam name; use nameof() to make your refactoring simpler.

public static class Colours
{
    public static string Red => nameof(Red);
    public static string Green => nameof(Green);
    public static string Blue => nameof(Blue);
}

This achieves the intention of an enum that has string values (such as the following pseudocode):

public enum Colours
{
    "Red",
    "Green",
    "Blue"
}

Detect Scroll Up & Scroll down in ListView

I have encountered problems using some example where the cell size of ListView is great. So I have found a solution to my problem which detects the slightest movement of your finger . I've simplified to the minimum possible and is as follows:

private int oldScrolly;


@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {

}

@Override
public void onScroll(AbsListView view, int firstVisibleItem, int    visibleItemCount, int totalItemCount) {

            View view = absListView.getChildAt(0);
            int scrolly = (view == null) ? 0 : -view.getTop() + absListView.getFirstVisiblePosition() * view.getHeight();
            int margin = 10;

            Log.e(TAG, "Scroll y: " + scrolly + " - Item: " + firstVisibleItem);


            if (scrolly > oldScrolly + margin) {
                Log.d(TAG, "SCROLL_UP");
                oldScrolly = scrolly;
            } else if (scrolly < oldScrolly - margin) {
                Log.d(TAG, "SCROLL_DOWN");
                oldScrolly = scrolly;
            }
        }
    });

PD: I use the MARGIN to not detect the scroll until you meet that margin . This avoids problems when I show or hide views and avoid blinking of them.

Is there a Google Keep API?

No there's not and developers still don't know why google doesn't pay attention to this request!

As you can see in this link it's one of the most popular issues with many stars in google code but still no response from google! You can also add stars to this issue, maybe google hears that!

mysql query: SELECT DISTINCT column1, GROUP BY column2

Try the following:

SELECT DISTINCT(ip), name, COUNT(name) nameCnt, 
time, price, SUM(price) priceSum
FROM tablename 
WHERE time >= $yesterday AND time <$today 
GROUP BY ip, name

How to open a web page from my application?

The old school way ;)

public static void openit(string x) {
   System.Diagnostics.Process.Start("cmd", "/C start" + " " + x); 
}

Use: openit("www.google.com");

How do I pass multiple parameters into a function in PowerShell?

If you're a C# / Java / C++ / Ruby / Python / Pick-A-Language-From-This-Century developer and you want to call your function with commas, because that's what you've always done, then you need something like this:

$myModule = New-Module -ascustomobject { 
    function test($arg1, $arg2) { 
        echo "arg1 = $arg1, and arg2 = $arg2"
    }
}

Now call:

$myModule.test("ABC", "DEF")

and you'll see

arg1 = ABC, and arg2 = DEF

How to delete object?

It sounds like you need to create a wrapper around an instance you can invalidate:

public class Ref<T> where T : class
{
    private T instance;
    public Ref(T instance)
    {
        this.instance = instance;
    }

    public static implicit operator Ref<T>(T inner)
    {
        return new Ref<T>(inner);
    }

    public void Delete()
    {
        this.instance = null;
    }

    public T Instance
    {
        get { return this.instance; }
    }
}

and you can use it like:

Ref<Car> carRef = new Car();
carRef.Delete();
var car = carRef.Instance;     //car is null

Be aware however that if any code saves the inner value in a variable, this will not be invalidated by calling Delete.

jQuery Mobile: document ready vs. page events

jQuery Mobile 1.4 Update:

My original article was intended for old way of page handling, basically everything before jQuery Mobile 1.4. Old way of handling is now deprecated and it will stay active until (including) jQuery Mobile 1.5, so you can still use everything mentioned below, at least until next year and jQuery Mobile 1.6.

Old events, including pageinit don't exist any more, they are replaced with pagecontainer widget. Pageinit is erased completely and you can use pagecreate instead, that event stayed the same and its not going to be changed.

If you are interested in new way of page event handling take a look here, in any other case feel free to continue with this article. You should read this answer even if you are using jQuery Mobile 1.4 +, it goes beyond page events so you will probably find a lot of useful information.

Older content:

This article can also be found as a part of my blog HERE.

$(document).on('pageinit') vs $(document).ready()

The first thing you learn in jQuery is to call code inside the $(document).ready() function so everything will execute as soon as the DOM is loaded. However, in jQuery Mobile, Ajax is used to load the contents of each page into the DOM as you navigate. Because of this $(document).ready() will trigger before your first page is loaded and every code intended for page manipulation will be executed after a page refresh. This can be a very subtle bug. On some systems it may appear that it works fine, but on others it may cause erratic, difficult to repeat weirdness to occur.

Classic jQuery syntax:

$(document).ready(function() {

});

To solve this problem (and trust me this is a problem) jQuery Mobile developers created page events. In a nutshell page events are events triggered in a particular point of page execution. One of those page events is a pageinit event and we can use it like this:

$(document).on('pageinit', function() {

});

We can go even further and use a page id instead of document selector. Let's say we have jQuery Mobile page with an id index:

<div data-role="page" id="index">
    <div data-theme="a" data-role="header">
        <h3>
            First Page
        </h3>
        <a href="#second" class="ui-btn-right">Next</a>
    </div>

    <div data-role="content">
        <a href="#" data-role="button" id="test-button">Test button</a>
    </div>

    <div data-theme="a" data-role="footer" data-position="fixed">

    </div>
</div>

To execute code that will only available to the index page we could use this syntax:

$('#index').on('pageinit', function() {

});

Pageinit event will be executed every time page is about be be loaded and shown for the first time. It will not trigger again unless page is manually refreshed or Ajax page loading is turned off. In case you want code to execute every time you visit a page it is better to use pagebeforeshow event.

Here's a working example: http://jsfiddle.net/Gajotres/Q3Usv/ to demonstrate this problem.

Few more notes on this question. No matter if you are using 1 html multiple pages or multiple HTML files paradigm it is advised to separate all of your custom JavaScript page handling into a single separate JavaScript file. This will note make your code any better but you will have much better code overview, especially while creating a jQuery Mobile application.

There's also another special jQuery Mobile event and it is called mobileinit. When jQuery Mobile starts, it triggers a mobileinit event on the document object. To override default settings, bind them to mobileinit. One of a good examples of mobileinit usage is turning off Ajax page loading, or changing default Ajax loader behavior.

$(document).on("mobileinit", function(){
  //apply overrides here
});

Page events transition order

First all events can be found here: http://api.jquerymobile.com/category/events/

Lets say we have a page A and a page B, this is a unload/load order:

  1. page B - event pagebeforecreate

  2. page B - event pagecreate

  3. page B - event pageinit

  4. page A - event pagebeforehide

  5. page A - event pageremove

  6. page A - event pagehide

  7. page B - event pagebeforeshow

  8. page B - event pageshow

For better page events understanding read this:

  • pagebeforeload, pageload and pageloadfailed are fired when an external page is loaded
  • pagebeforechange, pagechange and pagechangefailed are page change events. These events are fired when a user is navigating between pages in the applications.
  • pagebeforeshow, pagebeforehide, pageshow and pagehide are page transition events. These events are fired before, during and after a transition and are named.
  • pagebeforecreate, pagecreate and pageinit are for page initialization.
  • pageremove can be fired and then handled when a page is removed from the DOM

Page loading jsFiddle example: http://jsfiddle.net/Gajotres/QGnft/

If AJAX is not enabled, some events may not fire.

Prevent page transition

If for some reason page transition needs to be prevented on some condition it can be done with this code:

$(document).on('pagebeforechange', function(e, data){
    var to = data.toPage,
        from = data.options.fromPage;

    if (typeof to  === 'string') {
        var u = $.mobile.path.parseUrl(to);
        to = u.hash || '#' + u.pathname.substring(1);
        if (from) from = '#' + from.attr('id');

        if (from === '#index' && to === '#second') {
            alert('Can not transition from #index to #second!');
            e.preventDefault();
            e.stopPropagation();

            // remove active status on a button, if transition was triggered with a button
            $.mobile.activePage.find('.ui-btn-active').removeClass('ui-btn-active ui-focus ui-btn');;
        }
    }
});

This example will work in any case because it will trigger at a begging of every page transition and what is most important it will prevent page change before page transition can occur.

Here's a working example:

Prevent multiple event binding/triggering

jQuery Mobile works in a different way than classic web applications. Depending on how you managed to bind your events each time you visit some page it will bind events over and over. This is not an error, it is simply how jQuery Mobile handles its pages. For example, take a look at this code snippet:

$(document).on('pagebeforeshow','#index' ,function(e,data){
    $(document).on('click', '#test-button',function(e) {
        alert('Button click');
    });
});

Working jsFiddle example: http://jsfiddle.net/Gajotres/CCfL4/

Each time you visit page #index click event will is going to be bound to button #test-button. Test it by moving from page 1 to page 2 and back several times. There are few ways to prevent this problem:

Solution 1

Best solution would be to use pageinit to bind events. If you take a look at an official documentation you will find out that pageinit will trigger ONLY once, just like document ready, so there's no way events will be bound again. This is best solution because you don't have processing overhead like when removing events with off method.

Working jsFiddle example: http://jsfiddle.net/Gajotres/AAFH8/

This working solution is made on a basis of a previous problematic example.

Solution 2

Remove event before you bind it:

$(document).on('pagebeforeshow', '#index', function(){
    $(document).off('click', '#test-button').on('click', '#test-button',function(e) {
        alert('Button click');
    });
});

Working jsFiddle example: http://jsfiddle.net/Gajotres/K8YmG/

Solution 3

Use a jQuery Filter selector, like this:

$('#carousel div:Event(!click)').each(function(){
    //If click is not bind to #carousel div do something
});

Because event filter is not a part of official jQuery framework it can be found here: http://www.codenothing.com/archives/2009/event-filter/

In a nutshell, if speed is your main concern then Solution 2 is much better than Solution 1.

Solution 4

A new one, probably an easiest of them all.

$(document).on('pagebeforeshow', '#index', function(){
    $(document).on('click', '#test-button',function(e) {
        if(e.handled !== true) // This will prevent event triggering more than once
        {
            alert('Clicked');
            e.handled = true;
        }
    });
});

Working jsFiddle example: http://jsfiddle.net/Gajotres/Yerv9/

Tnx to the sholsinger for this solution: http://sholsinger.com/archive/2011/08/prevent-jquery-live-handlers-from-firing-multiple-times/

pageChange event quirks - triggering twice

Sometimes pagechange event can trigger twice and it does not have anything to do with the problem mentioned before.

The reason the pagebeforechange event occurs twice is due to the recursive call in changePage when toPage is not a jQuery enhanced DOM object. This recursion is dangerous, as the developer is allowed to change the toPage within the event. If the developer consistently sets toPage to a string, within the pagebeforechange event handler, regardless of whether or not it was an object an infinite recursive loop will result. The pageload event passes the new page as the page property of the data object (This should be added to the documentation, it's not listed currently). The pageload event could therefore be used to access the loaded page.

In few words this is happening because you are sending additional parameters through pageChange.

Example:

<a data-role="button" data-icon="arrow-r" data-iconpos="right" href="#care-plan-view?id=9e273f31-2672-47fd-9baa-6c35f093a800&amp;name=Sat"><h3>Sat</h3></a>

To fix this problem use any page event listed in Page events transition order.

Page Change Times

As mentioned, when you change from one jQuery Mobile page to another, typically either through clicking on a link to another jQuery Mobile page that already exists in the DOM, or by manually calling $.mobile.changePage, several events and subsequent actions occur. At a high level the following actions occur:

  • A page change process is begun
  • A new page is loaded
  • The content for that page is “enhanced” (styled)
  • A transition (slide/pop/etc) from the existing page to the new page occurs

This is a average page transition benchmark:

Page load and processing: 3 ms

Page enhance: 45 ms

Transition: 604 ms

Total time: 670 ms

*These values are in milliseconds.

So as you can see a transition event is eating almost 90% of execution time.

Data/Parameters manipulation between page transitions

It is possible to send a parameter/s from one page to another during page transition. It can be done in few ways.

Reference: https://stackoverflow.com/a/13932240/1848600

Solution 1:

You can pass values with changePage:

$.mobile.changePage('page2.html', { dataUrl : "page2.html?paremeter=123", data : { 'paremeter' : '123' }, reloadPage : true, changeHash : true });

And read them like this:

$(document).on('pagebeforeshow', "#index", function (event, data) {
    var parameters = $(this).data("url").split("?")[1];;
    parameter = parameters.replace("parameter=","");
    alert(parameter);
});

Example:

index.html

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
  <html>_x000D_
    <head>_x000D_
    <meta charset="utf-8" />_x000D_
    <meta name="viewport" content="widdiv=device-widdiv, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />_x000D_
    <meta name="apple-mobile-web-app-capable" content="yes" />_x000D_
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />_x000D_
    <title>_x000D_
    </title>_x000D_
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />_x000D_
    <script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js">_x000D_
    </script>_x000D_
    <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>_x000D_
    <script>_x000D_
        $(document).on('pagebeforeshow', "#index",function () {_x000D_
            $(document).on('click', "#changePage",function () {_x000D_
                $.mobile.changePage('second.html', { dataUrl : "second.html?paremeter=123", data : { 'paremeter' : '123' }, reloadPage : false, changeHash : true });_x000D_
            });_x000D_
        });_x000D_
_x000D_
        $(document).on('pagebeforeshow', "#second",function () {_x000D_
            var parameters = $(this).data("url").split("?")[1];;_x000D_
            parameter = parameters.replace("parameter=","");_x000D_
            alert(parameter);_x000D_
        });_x000D_
    </script>_x000D_
   </head>_x000D_
   <body>_x000D_
    <!-- Home -->_x000D_
    <div data-role="page" id="index">_x000D_
        <div data-role="header">_x000D_
            <h3>_x000D_
                First Page_x000D_
            </h3>_x000D_
        </div>_x000D_
        <div data-role="content">_x000D_
          <a data-role="button" id="changePage">Test</a>_x000D_
        </div> <!--content-->_x000D_
    </div><!--page-->_x000D_
_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

second.html

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
  <html>_x000D_
    <head>_x000D_
    <meta charset="utf-8" />_x000D_
    <meta name="viewport" content="widdiv=device-widdiv, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />_x000D_
    <meta name="apple-mobile-web-app-capable" content="yes" />_x000D_
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />_x000D_
    <title>_x000D_
    </title>_x000D_
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />_x000D_
    <script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js">_x000D_
    </script>_x000D_
    <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>_x000D_
   </head>_x000D_
   <body>_x000D_
    <!-- Home -->_x000D_
    <div data-role="page" id="second">_x000D_
        <div data-role="header">_x000D_
            <h3>_x000D_
                Second Page_x000D_
            </h3>_x000D_
        </div>_x000D_
        <div data-role="content">_x000D_
_x000D_
        </div> <!--content-->_x000D_
    </div><!--page-->_x000D_
_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Solution 2:

Or you can create a persistent JavaScript object for a storage purpose. As long Ajax is used for page loading (and page is not reloaded in any way) that object will stay active.

var storeObject = {
    firstname : '',
    lastname : ''
}

Example: http://jsfiddle.net/Gajotres/9KKbx/

Solution 3:

You can also access data from the previous page like this:

$(document).on('pagebeforeshow', '#index',function (e, data) {
    alert(data.prevPage.attr('id'));
});

prevPage object holds a complete previous page.

Solution 4:

As a last solution we have a nifty HTML implementation of localStorage. It only works with HTML5 browsers (including Android and iOS browsers) but all stored data is persistent through page refresh.

if(typeof(Storage)!=="undefined") {
    localStorage.firstname="Dragan";
    localStorage.lastname="Gaic";
}

Example: http://jsfiddle.net/Gajotres/J9NTr/

Probably best solution but it will fail in some versions of iOS 5.X. It is a well know error.

Don’t Use .live() / .bind() / .delegate()

I forgot to mention (and tnx andleer for reminding me) use on/off for event binding/unbinding, live/die and bind/unbind are deprecated.

The .live() method of jQuery was seen as a godsend when it was introduced to the API in version 1.3. In a typical jQuery app there can be a lot of DOM manipulation and it can become very tedious to hook and unhook as elements come and go. The .live() method made it possible to hook an event for the life of the app based on its selector. Great right? Wrong, the .live() method is extremely slow. The .live() method actually hooks its events to the document object, which means that the event must bubble up from the element that generated the event until it reaches the document. This can be amazingly time consuming.

It is now deprecated. The folks on the jQuery team no longer recommend its use and neither do I. Even though it can be tedious to hook and unhook events, your code will be much faster without the .live() method than with it.

Instead of .live() you should use .on(). .on() is about 2-3x faster than .live(). Take a look at this event binding benchmark: http://jsperf.com/jquery-live-vs-delegate-vs-on/34, everything will be clear from there.

Benchmarking:

There's an excellent script made for jQuery Mobile page events benchmarking. It can be found here: https://github.com/jquery/jquery-mobile/blob/master/tools/page-change-time.js. But before you do anything with it I advise you to remove its alert notification system (each “change page” is going to show you this data by halting the app) and change it to console.log function.

Basically this script will log all your page events and if you read this article carefully (page events descriptions) you will know how much time jQm spent of page enhancements, page transitions ....

Final notes

Always, and I mean always read official jQuery Mobile documentation. It will usually provide you with needed information, and unlike some other documentation this one is rather good, with enough explanations and code examples.

Changes:

  • 30.01.2013 - Added a new method of multiple event triggering prevention
  • 31.01.2013 - Added a better clarification for chapter Data/Parameters manipulation between page transitions
  • 03.02.2013 - Added new content/examples to the chapter Data/Parameters manipulation between page transitions
  • 22.05.2013 - Added a solution for page transition/change prevention and added links to the official page events API documentation
  • 18.05.2013 - Added another solution against multiple event binding

Using Excel as front end to Access database (with VBA)

Unless there is a strong advantage to running your user form in Excel then I would go with a 100% Access solution that would export the reports and data to Excel on an ad-hoc basis.

From what you describe, Access seems the stronger contender as it is built for working with data:
you would have a lot more tools at your disposal to solve any data problems than have to go around the limitations of Excel and shoehorn it into becoming Access...

As for your questions:

  1. Very easy. There have been some other questions on SO on that subject.
    See for instance this one and that one.

  2. Don't know, but I would guess that there could be a small penalty.
    The biggest difficulty I see is trying to get all the functionalities that Access gives you and re-creating some of these in Excel.

  3. Yes, you can have multiple Excel users and a single Access database.
    Here again, using Access as a front-end and keeping the data in a linked Access database on your network would make more sense and it's easy as pie, there's even a wizard in Access to help you do that: it's just 1 click away.

Really, as most other people have said, take a tiny bit of time to get acquainted with Access, it will save you a lot of time and trouble.
You may know Excel better but if you've gone 80% of the way already if you know VBA and are familiar with the Office object model.

Other advantages of doing it in Access: the Access 2007 runtime is free, meaning that if you were to deploy to app to 1 or 30 PC it would cost you the same: nothing.
You only need one full version of Access for your development work (the Runtime doesn't have the designers).

MySQLDump one INSERT statement for each data row

Use:

mysqldump --extended-insert=FALSE 

Be aware that multiple inserts will be slower than one big insert.

Suppress console output in PowerShell

Try redirecting the output to Out-Null. Like so,

$key = & 'gpg' --decrypt "secret.gpg" --quiet --no-verbose | out-null

Combining (concatenating) date and time into a datetime

This works in SQL 2008 and 2012 to produce datetime2:

declare @date date = current_timestamp;
declare @time time = current_timestamp;

select 
@date as date
,@time as time
,cast(@date as datetime) + cast(@time as datetime) as datetime
,cast(@time as datetime2) as timeAsDateTime2
,dateadd(dayofyear,datepart(dayofyear,@date) - 1,dateadd(year,datepart(year,@date) - 1900,cast(@time as datetime2))) as datetime2;

Why does the program give "illegal start of type" error?

You have a misplaced closing brace before the return statement.

Are strongly-typed functions as parameters possible in TypeScript?

If you define function type first then it would be looked like

type Callback = (n: number) => void;

class Foo {
    save(callback: Callback) : void {        
        callback(42);
    }
}

var foo = new Foo();
var stringCallback = (result: string) : void => {
    console.log(result);
}

var numberCallback = (result: number) : void => {
    console.log(result);
}

foo.save(stringCallback); //--will be showing error
foo.save(numberCallback);

Without function type by using plain property syntax it would be:

class Foo {
    save(callback: (n: number) => void) : void {        
        callback(42);
    }
}

var foo = new Foo();
var stringCallback = (result: string) : void => {
    console.log(result);
}

var numberCallback = (result: number) : void => {
    console.log(result);
}

foo.save(stringCallback); //--will be showing error
foo.save(numberCallback);

If you want by using an interface function like c# generic delegates it would be:

interface CallBackFunc<T, U>
{
    (input:T): U;
};

class Foo {
    save(callback: CallBackFunc<number,void>) : void {        
        callback(42);
    }
}

var foo = new Foo();
var stringCallback = (result: string) : void => {
    console.log(result);
}

var numberCallback = (result: number) : void => {
    console.log(result);
}

let strCBObj:CallBackFunc<string,void> = stringCallback;
let numberCBObj:CallBackFunc<number,void> = numberCallback;

foo.save(strCBObj); //--will be showing error
foo.save(numberCBObj);

test if display = none

If you want to get the visible tbody elements, you could do this:

$('tbody:visible').highlight(myArray[i]);

It looks similar to the answer that Agent_9191 gave, but this one removes the space from the selector, which makes it selects the visible tbody elements instead of the visible descendants.


EDIT:

If you specifically wanted to use a test on the display CSS property of the tbody elements, you could do this:

$('tbody').filter(function() {
     return $(this).css('display') != 'none';
}).highlight(myArray[i]);

MVC which submit button has been pressed

This post is not going to answer to Coppermill, because he have been answered long time ago. My post will be helpful for who will seeking for solution like this. First of all , I have to say " WDuffy's solution is totally correct" and it works fine, but my solution (not actually mine) will be used in other elements and it makes the presentation layer more independent from controller (because your controller depend on "value" which is used for showing label of the button, this feature is important for other languages.).

Here is my solution, give them different names:

<input type="submit" name="buttonSave" value="Save"/>
<input type="submit" name="buttonProcess" value="Process"/>
<input type="submit" name="buttonCancel" value="Cancel"/>

And you must specify the names of buttons as arguments in the action like below:

public ActionResult Register(string buttonSave, string buttonProcess, string buttonCancel)
{
    if (buttonSave!= null)
    {
        //save is pressed
    }
    if (buttonProcess!= null)
    {
        //Process is pressed
    }
    if (buttonCancel!= null)
    {
        //Cancel is pressed
    }
}

when user submits the page using one of the buttons, only one of the arguments will have value. I guess this will be helpful for others.

Update

This answer is quite old and I actually reconsider my opinion . maybe above solution is good for situation which passing parameter to model's properties. don't bother yourselves and take best solution for your project.

BarCode Image Generator in Java

There is also this free API that you can use to make free barcodes in java.

Barbecue

SQL Server FOR EACH Loop

You could use a variable table, like this:

declare @num int

set @num = 1

declare @results table ( val int )

while (@num < 6)
begin
  insert into @results ( val ) values ( @num )
  set @num = @num + 1
end

select val from @results

How to load all modules in a folder?

This is the best way i've found so far:

from os.path import dirname, join, isdir, abspath, basename
from glob import glob
pwd = dirname(__file__)
for x in glob(join(pwd, '*.py')):
    if not x.startswith('__'):
        __import__(basename(x)[:-3], globals(), locals())

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

If you are using pyhton version 3.4 or above. you have to install

sudo apt-get install python3-dev libmysqlclient-dev 

in terminal. then install pip install mysqlclient on your virtual env or where you installed pip.

android TextView: setting the background color dynamically doesn't work

Try this:

TextView c1 = new TextView(activity);
c1.setTextColor(getResources().getColor(R.color.solid_red));
c1.setText("My Text");

I agree that a color and a resource have the same type, but I also spend a few hours to find this solution.

Replace invalid values with None in Pandas DataFrame

Actually in later versions of pandas this will give a TypeError:

df.replace('-', None)
TypeError: If "to_replace" and "value" are both None then regex must be a mapping

You can do it by passing either a list or a dictionary:

In [11]: df.replace('-', df.replace(['-'], [None]) # or .replace('-', {0: None})
Out[11]:
      0
0  None
1     3
2     2
3     5
4     1
5    -5
6    -1
7  None
8     9

But I recommend using NaNs rather than None:

In [12]: df.replace('-', np.nan)
Out[12]:
     0
0  NaN
1    3
2    2
3    5
4    1
5   -5
6   -1
7  NaN
8    9

Show spinner GIF during an $http request in AngularJS?

If you're wrapping your api calls within a service/factory, then you can track the loading counter there (per answer and excellent simultaneous suggestion by @JMaylin), and reference the loading counter via a directive. Or any combination thereof.

API WRAPPER

yourModule
    .factory('yourApi', ['$http', function ($http) {
        var api = {}

        //#region ------------ spinner -------------

        // ajax loading counter
        api._loading = 0;

        /**
         * Toggle check
         */
        api.isOn = function () { return api._loading > 0; }

        /**
         * Based on a configuration setting to ignore the loading spinner, update the loading counter
         * (for multiple ajax calls at one time)
         */
        api.spinner = function(delta, config) {
            // if we haven't been told to ignore the spinner, change the loading counter
            // so we can show/hide the spinner

            if (NG.isUndefined(config.spin) || config.spin) api._loading += delta;

            // don't let runaway triggers break stuff...
            if (api._loading < 0) api._loading = 0;

            console.log('spinner:', api._loading, delta);
        }
        /**
         * Track an ajax load begin, if not specifically disallowed by request configuration
         */
        api.loadBegin = function(config) {
            api.spinner(1, config);
        }
        /**
         * Track an ajax load end, if not specifically disallowed by request configuration
         */
        api.loadEnd = function (config) {
            api.spinner(-1, config);
        }

        //#endregion ------------ spinner -------------

        var baseConfig = {
            method: 'post'
            // don't need to declare `spin` here
        }

        /**
         * $http wrapper to standardize all api calls
         * @param args stuff sent to request
         * @param config $http configuration, such as url, methods, etc
         */
        var callWrapper = function(args, config) {
            var p = angular.extend(baseConfig, config); // override defaults

            // fix for 'get' vs 'post' param attachment
            if (!angular.isUndefined(args)) p[p.method == 'get' ? 'params' : 'data'] = args;

            // trigger the spinner
            api.loadBegin(p);

            // make the call, and turn of the spinner on completion
            // note: may want to use `then`/`catch` instead since `finally` has delayed completion if down-chain returns more promises
            return $http(p)['finally'](function(response) {
                api.loadEnd(response.config);
                return response;
            });
        }

        api.DoSomething = function(args) {
            // yes spinner
            return callWrapper(args, { cache: true });
        }
        api.DoSomethingInBackground = function(args) {
            // no spinner
            return callWrapper(args, { cache: true, spin: false });
        }

        // expose
        return api;
    });

SPINNER DIRECTIVE

(function (NG) {
    var loaderTemplate = '<div class="ui active dimmer" data-ng-show="hasSpinner()"><div class="ui large loader"></div></div>';

    /**
     * Show/Hide spinner with ajax
     */
    function spinnerDirective($compile, api) {
        return {
            restrict: 'EA',
            link: function (scope, element) {
                // listen for api trigger
                scope.hasSpinner = api.isOn;

                // attach spinner html
                var spin = NG.element(loaderTemplate);
                $compile(spin)(scope); // bind+parse
                element.append(spin);
            }
        }
    }

    NG.module('yourModule')
        .directive('yourApiSpinner', ['$compile', 'yourApi', spinnerDirective]);
})(angular);

USAGE

<div ng-controller="myCtrl" your-api-spinner> ... </div>

json parsing error syntax error unexpected end of input

Don't Return Empty Json

In My Case I was returning Empty Json String in .Net Core Web API Project.

So I Changed My Code

From

 return Ok();

To

 return Ok("Done");

It seems you have to return some string or object.

Hope this helps.

C# using streams

I wouldn't call those different kind of streams. The Stream class have CanRead and CanWrite properties that tell you if the particular stream can be read from and written to.

The major difference between different stream classes (such as MemoryStream vs FileStream) is the backing store - where the data is read from or where it's written to. It's kind of obvious from the name. A MemoryStream stores the data in memory only, a FileStream is backed by a file on disk, a NetworkStream reads data from the network and so on.

How can I redirect a php page to another php page?

can use this to redirect

echo '<meta http-equiv="refresh" content="1; URL=index.php" />';

the content=1 can be change to different value to increase the delay before redirection

How to restart a rails server on Heroku?

If you have several heroku apps, you must type heroku restart --app app_name or heroku restart -a app_name

Rails get index of "each" loop

<% @images.each_with_index do |page, index| %>

<% end %>

Does --disable-web-security Work In Chrome Anymore?

Check if you have Chrome App Launcher. You can usually see it in your toolbar. It runs as a second instance of chrome, but unlike the browser, it auto-runs so is going to be running whenever you start your PC. Even though it isn't a browser view, it is a chrome instance which is enough to prevent your arguments from taking effect. Go to your task manager and you will probably have to kill 2 chrome processes.

How to properly import a selfsigned certificate into Java keystore that is available to all Java applications by default?

Might want to try

keytool -import -trustcacerts -noprompt -keystore <full path to cacerts> -storepass changeit -alias $REMHOST -file $REMHOST.pem

i honestly have no idea where it puts your certificate if you just write cacerts just give it a full path

Loop through columns and add string lengths as new columns

You need to use [[, the programmatic equivalent of $. Otherwise, for example, when i is col1, R will look for df$i instead of df$col1.

for(i in names(df)){
  df[[paste(i, 'length', sep="_")]] <- str_length(df[[i]])
}

Test credit card numbers for use with PayPal sandbox

A bit late in the game but just in case it helps anyone.

If you are testing using the Sandbox and on the payment page you want to test payments NOT using a PayPal account but using the "Pay with Debit or Credit Card option" (i.e. when a regular Joe/Jane, NOT PayPal users, want to buy your stuff) and want to save yourself some time: just go to a site like http://www.getcreditcardnumbers.com/ and get numbers from there. You can use any Expiry date (in the future) and any numeric CCV (123 works).

The "test credit card numbers" in the PayPal documentation are just another brick in their infuriating wall of convoluted stuff.

I got the url above from PayPal's tech support.

Tested using a simple Hosted button and IPN. Good luck.

Passing string parameter in JavaScript function

Use this:

document.write('<td width="74"><button id="button" type="button" onclick="myfunction('" + name + "')">click</button></td>')

Using the "With Clause" SQL Server 2008

Try the sp_foreachdb procedure.

Error: Generic Array Creation

You can't create arrays with a generic component type.

Create an array of an explicit type, like Object[], instead. You can then cast this to PCB[] if you want, but I don't recommend it in most cases.

PCB[] res = (PCB[]) new Object[list.size()]; /* Not type-safe. */

If you want type safety, use a collection like java.util.List<PCB> instead of an array.

By the way, if list is already a java.util.List, you should use one of its toArray() methods, instead of duplicating them in your code. This doesn't get your around the type-safety problem though.

Leap year calculation

PHP:

// is number of days in the year 366?  (php days of year is 0 based)
return ((int)date('z', strtotime('Dec 31')) === 365);

C# string reference type?

"A picture is worth a thousand words".

I have a simple example here, it's similar to your case.

string s1 = "abc";
string s2 = s1;
s1 = "def";
Console.WriteLine(s2);
// Output: abc

This is what happened:

enter image description here

  • Line 1 and 2: s1 and s2 variables reference to the same "abc" string object.
  • Line 3: Because strings are immutable, so the "abc" string object do not modify itself (to "def"), but a new "def" string object is created instead, and then s1 references to it.
  • Line 4: s2 still references to "abc" string object, so that's the output.

Merge DLL into EXE?

Here is the official documentation. This is also automatically downloaded at step 2.

Below is a really simple way to do it and I've successfully built my app using .NET framework 4.6.1

  1. Install ILMerge nuget package either via gui or commandline:

    Install-Package ilmerge
    
  2. Verify you have downloaded it. Now Install (not sure the command for this, but just go to your nuget packages): enter image description here Note: You probably only need to install it for one of your solutions if you have multiple

  3. Navigate to your solution folder and in the packages folder you should see 'ILMerge' with an executable:

    \FindMyiPhone-master\FindMyiPhone-master\packages\ILMerge.2.14.1208\tools
    

    enter image description here

  4. Now here is the executable which you could copy over to your \bin\Debug (or whereever your app is built) and then in commandline/powershell do something like below:

    ILMerge.exe myExecutable.exe myDll1.dll myDll2.dll myDlln.dll myNEWExecutable.exe
    

You will now have a new executable with all your libraries in one!

.NET HttpClient. How to POST string value?

There is an article about your question on asp.net's website. I hope it can help you.

How to call an api with asp net

http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client

Here is a small part from the POST section of the article

The following code sends a POST request that contains a Product instance in JSON format:

// HTTP POST
var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };
response = await client.PostAsJsonAsync("api/products", gizmo);
if (response.IsSuccessStatusCode)
{
    // Get the URI of the created resource.
    Uri gizmoUrl = response.Headers.Location;
}

How do I get the computer name in .NET

You can have access of the machine name using Environment.MachineName.

How can I sort a std::map first by value, then by key?

You can use std::set instead of std::map.

You can store both key and value in std::pair and the type of container will look like this:

std::set< std::pair<int, std::string> > items;

std::set will sort it's values both by original keys and values that were stored in std::map.

SQL recursive query on self referencing table (Oracle)

Do you want to do this?

SELECT id, parent_id, name, 
 (select Name from tbl where id = t.parent_id) parent_name
FROM tbl t start with id = 1 CONNECT BY PRIOR id = parent_id

Edit Another option based on OMG's one (but I think that will perform equally):

select 
           t1.id, 
           t1.parent_id, 
           t1.name,
           t2.name AS parent_name,
           t2.id AS parent_id
from 
    (select id, parent_id, name
    from tbl
    start with id = 1 
    connect by prior id = parent_id) t1
    left join
    tbl t2 on t2.id = t1.parent_id

How to make a vertical line in HTML

HTML5 custom elements (or pure CSS)

enter image description here

1. javascript

Register your element.

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

*The - is mandatory in all custom elements.

2. css

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

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

3. instantiate

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

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

usage

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

enter image description here

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


Don't want to mess with javascript?

Simply apply this CSS class to your designated element.

css

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

*See notes above.

How do I find what Java version Tomcat6 is using?

Once you have started tomcat simply run the following command at a terminal prompt:

ps -ef | grep tomcat

This will show the process details and indicate which JVM (by folder location) is running tomcat.

Failed to resolve: com.android.support:appcompat-v7:27.+ (Dependency Error)

Find root build.gradle file and add google maven repo inside allprojects tag

repositories {
        mavenLocal()
        mavenCentral()
        maven {                                  // <-- Add this
            url 'https://maven.google.com/' 
            name 'Google'
        }
    } 

It's better to use specific version instead of variable version

compile 'com.android.support:appcompat-v7:27.0.0'

If you're using Android Plugin for Gradle 3.0.0 or latter version

repositories {
      mavenLocal()
      mavenCentral()
      google()        //---> Add this
} 

and inject dependency in this way :

implementation 'com.android.support:appcompat-v7:27.0.0'

How do I increment a DOS variable in a FOR /F loop?

I would like to add that in case in you create local variables within the loop, they need to be expanded using the bang(!) notation as well. Extending the example at https://stackoverflow.com/a/2919699 above, if we want to create counter-based output filenames

set TEXT_T="myfile.txt"

set /a c=1

setlocal ENABLEDELAYEDEXPANSION

FOR /F "tokens=1 usebackq" %%i in (%TEXT_T%) do (
    set /a c=c+1
    set OUTPUT_FILE_NAME=output_!c!.txt
    echo Output file is !OUTPUT_FILE_NAME!
    echo %%i, !c!
)

endlocal

Convert ArrayList to String array in Android

String[] array = new String[items2.size()];
items2.toArray(array);

Apache gives me 403 Access Forbidden when DocumentRoot points to two different drives

Solved 403: Forbidden when visiting localhost. Using ports 80,443,3308 (the later to handle conflict with MySQL Server installation) Windows 10, XAMPP 7.4.1, Apache 2.4.x My web files are in a separate folder.

httpd.conf - look for these lines and set it up where you have your files, mine is web folder.

DocumentRoot "C:/web"
<Directory "C:/web">

Changed these 2 lines.

<VirtualHost *:80>
 ServerAdmin [email protected]
 DocumentRoot "C:/web/project1"
 ServerName project1.localhost
 <Directory "C:/web/project1">
  Order allow,deny
  allow from all
 </Directory>
</VirtualHost>

to this

<VirtualHost *:80>
 ServerAdmin [email protected]
 DocumentRoot "C:/web/project1"
 ServerName project1.localhost
 <Directory "C:/web/project1">
  Require all granted
 </Directory>
</VirtualHost>

Add your details in your hosts file C:\Windows\System32\drivers\etc\hosts file

127.0.0.1 localhost
127.0.0.1 project1.localhost

Stop start XAMPP, and click Apache admin (or localhost) and the wonderful XAMPP dashboard now displays! And visit your project at project1.localhost

CardView Corner Radius

If you're setting the card background programmatically, make use you use cardView.setCardBackgroundColor() and not cardView.setBackgroundColor() and make sure use using app:cardPreventCornerOverlap="true" on the cardView.xml. That fixed it for me.

Btw, the above code (in quotations) is in Kotlin and not Java. Use the java equivalent if you're using Java.

Get a worksheet name using Excel VBA

You can use below code to get the Active Sheet name and change it to yours preferred name.

Sub ChangeSheetName()

Dim shName As String
Dim currentName As String
currentName = ActiveSheet.Name
shName = InputBox("What name you want to give for your sheet")
ThisWorkbook.Sheets(currentName).Name = shName

End Sub

Handling very large numbers in Python

The python interpreter will handle it for you, you just have to do your operations (+, -, *, /), and it will work as normal.

The int value is unlimited.

Careful when doing division, by default the quotient is turned into float, but float does not support such large numbers. If you get an error message saying float does not support such large numbers, then it means the quotient is too large to be stored in float you’ll have to use floor division (//).

It ignores any decimal that comes after the decimal point, this way, the result will be int, so you can have a large number result.

>>>10//3
3

>>>10//4
2

mysqli or PDO - what are the pros and cons?

PDO will make it a lot easier to scale if your site/web app gets really being as you can daily set up Master and slave connections to distribute the load across the database, plus PHP is heading towards moving to PDO as a standard.

PDO Info

Scaling a Web Application

Swift: Display HTML data in a label or textView

Swift 5

extension UIColor {
    var hexString: String {
        let components = cgColor.components
        let r: CGFloat = components?[0] ?? 0.0
        let g: CGFloat = components?[1] ?? 0.0
        let b: CGFloat = components?[2] ?? 0.0

        let hexString = String(format: "#%02lX%02lX%02lX", lroundf(Float(r * 255)), lroundf(Float(g * 255)),
                               lroundf(Float(b * 255)))

        return hexString
    }
}
extension String {
    func htmlAttributed(family: String?, size: CGFloat, color: UIColor) -> NSAttributedString? {
        do {
            let htmlCSSString = "<style>" +
                "html *" +
                "{" +
                "font-size: \(size)pt !important;" +
                "color: #\(color.hexString) !important;" +
                "font-family: \(family ?? "Helvetica"), Helvetica !important;" +
            "}</style> \(self)"

            guard let data = htmlCSSString.data(using: String.Encoding.utf8) else {
                return nil
            }

            return try NSAttributedString(data: data,
                                          options: [.documentType: NSAttributedString.DocumentType.html,
                                                    .characterEncoding: String.Encoding.utf8.rawValue],
                                          documentAttributes: nil)
        } catch {
            print("error: ", error)
            return nil
        }
    }
}

And final you can create UILabel:

func createHtmlLabel(with html: String) -> UILabel {
    let htmlMock = """
    <b>hello</b>, <i>world</i>
    """

    let descriprionLabel = UILabel()
    descriprionLabel.attributedText = htmlMock.htmlAttributed(family: "YourFontFamily", size: 15, color: .red)

    return descriprionLabel
}

Result:

enter image description here

See tutorial:

https://medium.com/@valv0/a-swift-extension-for-string-and-html-8cfb7477a510

Creating the checkbox dynamically using JavaScript?

   /* worked for me  */
     <div id="divid"> </div>
     <script type="text/javascript">
         var hold = document.getElementById("divid");
         var checkbox = document.createElement('input');
         checkbox.type = "checkbox";
         checkbox.name = "chkbox1";
         checkbox.id = "cbid";
         var label = document.createElement('label');
         var tn = document.createTextNode("Not A RoBot");
         label.htmlFor="cbid";
         label.appendChild(tn); 
         hold.appendChild(label);
         hold.appendChild(checkbox);
      </script>  

ModelState.IsValid == false, why?

About "can it be that 0 errors and IsValid == false": here's MVC source code from https://github.com/Microsoft/referencesource/blob/master/System.Web/ModelBinding/ModelStateDictionary.cs#L37-L41

public bool IsValid {
    get {
        return Values.All(modelState => modelState.Errors.Count == 0);
    }
}

Now, it looks like it can't be. Well, that's for ASP.NET MVC v1.

Passing enum or object through an intent (the best solution)

I think your best bet is going to be to convert those lists into something parcelable such as a string (or map?) to get it to the Activity. Then the Activity will have to convert it back to an array.

Implementing custom parcelables is a pain in the neck IMHO so I would avoid it if possible.

How to extract 1 screenshot for a video with ffmpeg at a given time?

Use the -ss option:

ffmpeg -ss 01:23:45 -i input -vframes 1 -q:v 2 output.jpg
  • For JPEG output use -q:v to control output quality. Full range is a linear scale of 1-31 where a lower value results in a higher quality. 2-5 is a good range to try.

  • The select filter provides an alternative method for more complex needs such as selecting only certain frame types, or 1 per 100, etc.

  • Placing -ss before the input will be faster. See FFmpeg Wiki: Seeking and this excerpt from the ffmpeg cli tool documentation:

-ss position (input/output)

When used as an input option (before -i), seeks in this input file to position. Note the in most formats it is not possible to seek exactly, so ffmpeg will seek to the closest seek point before position. When transcoding and -accurate_seek is enabled (the default), this extra segment between the seek point and position will be decoded and discarded. When doing stream copy or when -noaccurate_seek is used, it will be preserved.

When used as an output option (before an output filename), decodes but discards input until the timestamps reach position.

position may be either in seconds or in hh:mm:ss[.xxx] form.

How to generate the JPA entity Metamodel?

For Hibernate as provider which is most common IMHO:

In case of build tools like Gradle, Maven you need to have Hibernate JPA 2 Metamodel Generator jar in the classpath and compiler level>=1.6 that is all you need build the project and metamodel will be generated automatically.

In case of IDE Eclipse 1. goto Project->Properties->Java Compiler->Annotation Processing and enable it. 2. Expand Annotation Processing->Factory Path-> Add External Jar add Hibernate JPA 2 Metamodel Generator jar check the newly added jar and say OK. Clean and Build done!

Link Hibernate JPA 2 Metamodel Generator jar link from maven repo https://mvnrepository.com/artifact/org.hibernate/hibernate-jpamodelgen

HTML code for INR

How about using fontawesome icon for Indian Rupee (INR).

Add font awesome CSS from CDN in the Head section of your HTML page:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

And then using the font like this:

<i class="fa fa-inr" aria-hidden="true"></i>

Method to find string inside of the text file. Then getting the following lines up to a certain limit

You can do something like this:

File file = new File("Student.txt");

try {
    Scanner scanner = new Scanner(file);

    //now read the file line by line...
    int lineNum = 0;
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        lineNum++;
        if(<some condition is met for the line>) { 
            System.out.println("ho hum, i found it on line " +lineNum);
        }
    }
} catch(FileNotFoundException e) { 
    //handle this
}

Syntax error "syntax error, unexpected end-of-input, expecting keyword_end (SyntaxError)"

$ rails server -b $IP -p $PORT - that solved the same problem for me

twitter bootstrap 3.0 typeahead ajax example

<input id="typeahead-input" type="text" data-provide="typeahead" />

<script type="text/javascript">
var data = ["Aamir", "Amol", "Ayesh", "Sameera", "Sumera", "Kajol", "Kamal",
  "Akash", "Robin", "Roshan", "Aryan"];
$(function() {
    $('#typeahead-input').typeahead({
        source: function (query, process) {
               process(data);
            });
        }
    });
});
</script>

Script to kill all connections to a database (More than RESTRICTED_USER ROLLBACK)

Little known: the GO sql statement can take an integer for the number of times to repeat previous command.

So if you:

ALTER DATABASE [DATABASENAME] SET SINGLE_USER
GO

Then:

USE [DATABASENAME]
GO 2000

This will repeat the USE command 2000 times, force deadlock on all other connections, and take ownership of the single connection. (Giving your query window sole access to do as you wish.)

How to grep a text file which contains some binary data?

Here's what I used in a system that didn't have "strings" command installed

cat yourfilename | tr -cd "[:print:]"

This prints the text and removes unprintable characters in one fell swoop, unlike "cat -v filename" which requires some postprocessing to remove unwanted stuff. Note that some of the binary data may be printable so you'll still get some gibberish between the good stuff. I think strings removes this gibberish too if you can use that.

Node.js version on the command line? (not the REPL)

Node:

node --version or node -v

npm:

npm --version or npm -v

V8 engine version:

node -p process.versions.v8

How could I put a border on my grid control in WPF?

This is a later answer that works for me, if it may be of use to anyone in the future. I wanted a simple border around all four sides of the grid and I achieved it like so...

<DataGrid x:Name="dgDisplay" Margin="5" BorderBrush="#1266a7" BorderThickness="1"...

Download the Android SDK components for offline install

There is an open source offline package deployer for Windows which I wrote:

http://siddharthbarman.com/apd/

You can try this out to see if it meets your needs.

Grid of responsive squares

You can make responsive grid of squares with verticaly and horizontaly centered content only with CSS. I will explain how in a step by step process but first here are 2 demos of what you can achieve :

Responsive 3x3 square grid Responsive square images in a 3x3 grid

Now let's see how to make these fancy responsive squares!



1. Making the responsive squares :

The trick for keeping elements square (or whatever other aspect ratio) is to use percent padding-bottom.
Side note: you can use top padding too or top/bottom margin but the background of the element won't display.

As top padding is calculated according to the width of the parent element (See MDN for reference), the height of the element will change according to its width. You can now Keep its aspect ratio according to its width.
At this point you can code :

HTML :

 <div></div>

CSS

div {
    width: 30%;
    padding-bottom: 30%; /* = width for a square aspect ratio */
}

Here is a simple layout example of 3*3 squares grid using the code above.

With this technique, you can make any other aspect ratio, here is a table giving the values of bottom padding according to the aspect ratio and a 30% width.

 Aspect ratio  |  padding-bottom  |  for 30% width
------------------------------------------------
    1:1        |  = width         |    30%
    1:2        |  width x 2       |    60%
    2:1        |  width x 0.5     |    15%
    4:3        |  width x 0.75    |    22.5%
    16:9       |  width x 0.5625  |    16.875%




2. Adding content inside the squares

As you can't add content directly inside the squares (it would expand their height and squares wouldn't be squares anymore) you need to create child elements (for this example I am using divs) inside them with position: absolute; and put the content inside them. This will take the content out of the flow and keep the size of the square.

Don't forget to add position:relative; on the parent divs so the absolute children are positioned/sized relatively to their parent.

Let's add some content to our 3x3 grid of squares :

HTML :

<div class="square">
    <div class="content">
        .. CONTENT HERE ..
    </div>
</div>
... and so on 9 times for 9 squares ...

CSS :

.square {
    float:left;
    position: relative;
    width: 30%;
    padding-bottom: 30%; /* = width for a 1:1 aspect ratio */
    margin:1.66%;
    overflow:hidden;
}

.content {
    position:absolute;
    height:80%; /* = 100% - 2*10% padding */
    width:90%; /* = 100% - 2*5% padding */
    padding: 10% 5%;
}

RESULT <-- with some formatting to make it pretty!



3.Centering the content

Horizontally :

This is pretty easy, you just need to add text-align:center to .content.
RESULT

Vertical alignment

This becomes serious! The trick is to use

display:table;
/* and */
display:table-cell;
vertical-align:middle;

but we can't use display:table; on .square or .content divs because it conflicts with position:absolute; so we need to create two children inside .content divs. Our code will be updated as follow :

HTML :

<div class="square">
    <div class="content">
        <div class="table">
            <div class="table-cell">
                ... CONTENT HERE ...
            </div>
        </div>
    </div>
</div>
... and so on 9 times for 9 squares ...

CSS :

.square {
    float:left;
    position: relative;
    width: 30%;
    padding-bottom : 30%; /* = width for a 1:1 aspect ratio */
    margin:1.66%;
    overflow:hidden;
}

.content {
    position:absolute;
    height:80%; /* = 100% - 2*10% padding */
    width:90%; /* = 100% - 2*5% padding */
    padding: 10% 5%;
}
.table{
    display:table;
    height:100%;
    width:100%;
}
.table-cell{
    display:table-cell;
    vertical-align:middle;
    height:100%;
    width:100%;
}




We have now finished and we can take a look at the result here :

LIVE FULLSCREEN RESULT

editable fiddle here


Can I use CASE statement in a JOIN condition?

I think you need two case statements:

SELECT  *
FROM    sys.indexes i
    JOIN sys.partitions p
        ON i.index_id = p.index_id 
    JOIN sys.allocation_units a
        ON 
        -- left side of join on statement
            CASE
               WHEN a.type IN (1, 3)
                   THEN a.container_id
               WHEN a.type IN (2)
                   THEN a.container_id
            END 
        = 
        -- right side of join on statement
            CASE
               WHEN a.type IN (1, 3)
                   THEN p.hobt_id
               WHEN a.type IN (2)
                   THEN p.partition_id
            END             

This is because:

  • the CASE statement returns a single value at the END
  • the ON statement compares two values
  • your CASE statement was doing the comparison inside of the CASE statement. I would guess that if you put your CASE statement in your SELECT you would get a boolean '1' or '0' indicating whether the CASE statement evaluated to True or False

Jquery Ajax beforeSend and success,error & complete

It's actually much easier with jQuery's promise API:

$.ajax(
            type: "GET",
            url: requestURL,
        ).then((success) =>
            console.dir(success)
        ).failure((failureResponse) =>
            console.dir(failureResponse)
        )

Alternatively, you can pass in of bind functions to each result callback; the order of parameters is: (success, failure). So long as you specify a function with at least 1 parameter, you get access to the response. So, for example, if you wanted to check the response text, you could simply do:

$.ajax(
            type: "GET",
            url: @get("url") + "logout",
            beforeSend: (xhr) -> xhr.setRequestHeader("token", currentToken)
        ).failure((response) -> console.log "Request was unauthorized" if response.status is 401

Delete everything in a MongoDB database

Simplest way to delete a database say blog:

> use blog
switched to db blog
> db.dropDatabase();
{ "dropped" : "blog", "ok" : 1 }

How do I tell if a variable has a numeric value in Perl?

Not perfect, but you can use a regex:

sub isnumber 
{
    shift =~ /^-?\d+\.?\d*$/;
}

AngularJS passing data to $http.get request

You can even simply add the parameters to the end of the url:

$http.get('path/to/script.php?param=hello').success(function(data) {
    alert(data);
});

Paired with script.php:

<? var_dump($_GET); ?>

Resulting in the following javascript alert:

array(1) {  
    ["param"]=>  
    string(4) "hello"
}

Python Pandas User Warning: Sorting because non-concatenation axis is not aligned

jezrael's answer is good, but did not answer a question I had: Will getting the "sort" flag wrong mess up my data in any way? The answer is apparently "no", you are fine either way.

from pandas import DataFrame, concat

a = DataFrame([{'a':1,      'c':2,'d':3      }])
b = DataFrame([{'a':4,'b':5,      'd':6,'e':7}])

>>> concat([a,b],sort=False)
   a    c  d    b    e
0  1  2.0  3  NaN  NaN
0  4  NaN  6  5.0  7.0

>>> concat([a,b],sort=True)
   a    b    c  d    e
0  1  NaN  2.0  3  NaN
0  4  5.0  NaN  6  7.0

Most efficient way to create a zero filled JavaScript array?

I've tested all combinations of pre-allocating/not pre-allocating, counting up/down, and for/while loops in IE 6/7/8, Firefox 3.5, Chrome, and Opera.

The functions below was consistently the fastest or extremely close in Firefox, Chrome, and IE8, and not much slower than the fastest in Opera and IE 6. It's also the simplest and clearest in my opinion. I've found several browsers where the while loop version is slightly faster, so I'm including it too for reference.

function newFilledArray(length, val) {
    var array = [];
    for (var i = 0; i < length; i++) {
        array[i] = val;
    }
    return array;
}

or

function newFilledArray(length, val) {
    var array = [];
    var i = 0;
    while (i < length) {
        array[i++] = val;
    }
    return array;
}

Tomcat: LifecycleException when deploying

Might be super trivial but worth a check prior to waste some time.

At my case the mysql service was down.

When you have a java app including JPA / Hibernate it is checking the database connection on startup. Just found out by looking into the looks where it had an entity manager error.

How can I validate a string to only allow alphanumeric characters in it?

While there are many ways to skin this cat, I prefer to wrap such code into reusable extension methods that make it trivial to do going forward. When using extension methods, you can also avoid RegEx as it is slower than a direct character check. I like using the extensions in the Extensions.cs NuGet package. It makes this check as simple as:

  1. Add the https://www.nuget.org/packages/Extensions.cs package to your project.
  2. Add "using Extensions;" to the top of your code.
  3. "smith23".IsAlphaNumeric() will return True whereas "smith 23".IsAlphaNumeric(false) will return False. By default the .IsAlphaNumeric() method ignores spaces, but it can also be overridden as shown above. If you want to allow spaces such that "smith 23".IsAlphaNumeric() will return True, simple default the arg.
  4. Every other check in the rest of the code is simply MyString.IsAlphaNumeric().

Angular HTTP GET with TypeScript error http.get(...).map is not a function in [null]

Angular version 6 "0.6.8" rxjs version 6 "^6.0.0"

this solution is for :

  "@angular-devkit/core": "0.6.8",
  "rxjs": "^6.0.0"

as we all know angular is being developed every day so there are lots of changes every day and this solution is for angular 6 and rxjs 6
first to work with http yo should import it from : after all you have to declare the HttpModule in app.module.ts

import { Http } from '@angular/http';

and you have to add HttpModule to Ngmodule -> imports

  imports: [
    HttpModule,
    BrowserModule,
    FormsModule,
    RouterModule.forRoot(appRoutes)
  ],

second to work with map you should first import pipe :

import { pipe } from 'rxjs';

third you need the map function import from :

import { map } from 'rxjs/operators';

you have to use map inside pipe like this exemple :

 constructor(public http:Http){  }

    getusersGET(){
        return this.http.get('http://jsonplaceholder.typicode.com/users').pipe(
         map(res => res.json()  )  );
    }

that works perfectly good luck !

How to control the line spacing in UILabel

Here is a subclass of UILabel that sets lineHeightMultiple and makes sure the intrinsic height is large enough to not cut off text.

@IBDesignable
class Label: UILabel {
    override var intrinsicContentSize: CGSize {
        var size = super.intrinsicContentSize
        let padding = (1.0 - lineHeightMultiple) * font.pointSize
        size.height += padding
        return size
    }

    override var text: String? {
        didSet {
            updateAttributedText()
        }
    }

    @IBInspectable var lineHeightMultiple: CGFloat = 1.0 {
        didSet {
            updateAttributedText()
        }
    }

    private func updateAttributedText() {
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineHeightMultiple = lineHeightMultiple
        attributedText = NSAttributedString(string: text ?? "", attributes: [
            .font: font,
            .paragraphStyle: paragraphStyle,
            .foregroundColor: textColor
        ])
        invalidateIntrinsicContentSize()
    }
}

How can I declare and define multiple variables in one line using C++?

template <typename ...A>
constexpr auto assign(A& ...a) noexcept
{
  return [&](auto&& ...v) noexcept(noexcept(
    ((a = std::forward<decltype(v)>(v)), ...)))
    {
      ((a = std::forward<decltype(v)>(v)), ...);
    };
}

int column, row, index;

assign(column, row, index)(0, 0, 0);

ubuntu "No space left on device" but there is tons of space

It's possible that you've run out of memory or some space elsewhere and it prompted the system to mount an overflow filesystem, and for whatever reason, it's not going away.

Try unmounting the overflow partition:

umount /tmp

or

umount overflow

Function names in C++: Capitalize or not?

Personally, I prefer thisStyle to ThisStyle for functions. This is really for personal taste, probably Java-influenced, but I quite like functions and classes to look different.

If I had to argue for it, though, I'd say that the distinction is slightly more than just aesthetic. It saves a tiny bit of thought when you come across function-style construction of a temporary. Against that, you can argue that it doesn't actually matter whether Foo(1,2,3) is a function call or not - if it is a constructor, then it acts exactly like a function returning a Foo by value anyway.

The convention also avoids the function-with-same-name-as-a-class-is-not-an-error fiasco that C++ inherits because C has a separate tag namespace:

#include <iostream>

struct Bar {
    int a;
    Bar() : a(0) {}
    Bar(int a) : a(a) {}
};

struct Foo {
    Bar b;
};

int Bar() {
    return 23;
}

int main() {
    Foo f;
    f.b = Bar();
    // outputs 23
    std::cout << f.b.a << "\n";
    // This line doesn't compile. The function has hidden the class.
    // Bar b;
}

Bar is, after all, both a noun and a verb, so could reasonably be defined as a class in one place and a function in another. Obviously there are better ways to avoid the clash, such as proper use of namespaces. So as I say, really it's just because I prefer the look of functions with lower-case initials rather than because it's actually necessary to distinguish them from from classes.

PowerShell - Start-Process and Cmdline Switches

you are going to want to separate your arguments into separate parameter

$msbuild = "C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe"
$arguments = "/v:q /nologo"
start-process $msbuild $arguments 

Python Function to test ping

This is my version of check ping function. May be if well be usefull for someone:

def check_ping(host):
if platform.system().lower() == "windows":
response = os.system("ping -n 1 -w 500 " + host + " > nul")
if response == 0:
return "alive"
else:
return "not alive"
else:
response = os.system("ping -c 1 -W 0.5" + host + "> /dev/null")
if response == 1:
return "alive"
else:
return "not alive"

Classes residing in App_Code is not accessible

In my case, I couldn't get a project to build with classes defined in the App_Code folder.

Can't replicate the scenario precisely to comment, but had to close and re-open visual studio for intellisense to co-operate agree...

I noticed that when a class in the App_Code folder is set to 'Compile' instead of 'Content' (right-click it) that the errors were coming from a second version of the class... Look to the left-most of the 3 of the 3 fields between the code pane and the tab. The 'other' one was called something along the lines of 10_App_Code or similar.

To rectify the issue, I renamed the folder from App_Code to Code, explicitly set namespaces on the classes and set all of the classes to 'Compile'

Debugging JavaScript in IE7

IE8 Developer Tools are able to switch to IE7 modeenter image description here

How to find the Target *.exe file of *.appref-ms

I know this question is old, but the way I found the executable file for a similar application was to first open the application, then open Windows Task Manager, and in the "Processes" list right-click on it and choose "Open File Location".

I couldn't seem to find the location in the application reference file in my case...

Increment value in mysql update query

Remove the ' around the point:

mysql_query("UPDATE member_profile SET points=".$points."+1 WHERE user_id = '".$userid."'");

You are "casting" an integer value to string in your original query...

How to access site through IP address when website is on a shared host?

According with the HTTP/1.1 standard, the shared IP hosted site can be accessed by a GET request with the IP as URL and a header of the host.

Here there are two examples(wget and curl): $ wget --header 'Host:somerandomservice.com' http://67.225.235.59 $ curl --header 'Host:somerandomservice.com' http://67.225.235.59

Resources:

https://en.wikipedia.org/wiki/Shared_web_hosting_service

http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.23

Setting Java heap space under Maven 2 on Windows

It worked - To change in Eclipse, go to Window -> Preferences -> Java -> Installed JREs. Select the checked JRE/JDK and click edit.

Default VM Arguments = -Xms128m -Xmx1024m

SyntaxError: multiple statements found while compiling a single statement

A (partial) practical work-around is to put things into a throw-away function.

Pasting

x = 1
x += 1
print(x)

results in

>>> x = 1
x += 1
print(x)
  File "<stdin>", line 1
    x += 1
print(x)

    ^
SyntaxError: multiple statements found while compiling a single statement
>>>

However, pasting

def abc():
  x = 1
  x += 1
  print(x)

works:

>>> def abc():
  x = 1
  x += 1
  print(x)
>>> abc()
2
>>>

Of course, this is OK for a quick one-off, won't work for everything you might want to do, etc. But then, going to ipython / jupyter qtconsole is probably the next simplest option.

How to search a specific value in all tables (PostgreSQL)?

There is a way to achieve this without creating a function or using an external tool. By using Postgres' query_to_xml() function that can dynamically run a query inside another query, it's possible to search a text across many tables. This is based on my answer to retrieve the rowcount for all tables:

To search for the string foo across all tables in a schema, the following can be used:

with found_rows as (
  select format('%I.%I', table_schema, table_name) as table_name,
         query_to_xml(format('select to_jsonb(t) as table_row 
                              from %I.%I as t 
                              where t::text like ''%%foo%%'' ', table_schema, table_name), 
                      true, false, '') as table_rows
  from information_schema.tables 
  where table_schema = 'public'
)
select table_name, x.table_row
from found_rows f
  left join xmltable('//table/row' 
                     passing table_rows
                       columns
                         table_row text path 'table_row') as x on true

Note that the use of xmltable requires Postgres 10 or newer. For older Postgres version, this can be also done using xpath().

with found_rows as (
  select format('%I.%I', table_schema, table_name) as table_name,
         query_to_xml(format('select to_jsonb(t) as table_row 
                              from %I.%I as t 
                              where t::text like ''%%foo%%'' ', table_schema, table_name), 
                      true, false, '') as table_rows
  from information_schema.tables 
  where table_schema = 'public'
)
select table_name, x.table_row
from found_rows f
   cross join unnest(xpath('/table/row/table_row/text()', table_rows)) as r(data)

The common table expression (WITH ...) is only used for convenience. It loops through all tables in the public schema. For each table the following query is run through the query_to_xml() function:

select to_jsonb(t)
from some_table t
where t::text like '%foo%';

The where clause is used to make sure the expensive generation of XML content is only done for rows that contain the search string. This might return something like this:

<table xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<row>
  <table_row>{"id": 42, "some_column": "foobar"}</table_row>
</row>
</table>

The conversion of the complete row to jsonb is done, so that in the result one could see which value belongs to which column.

The above might return something like this:

table_name   |   table_row
-------------+----------------------------------------
public.foo   |  {"id": 1, "some_column": "foobar"}
public.bar   |  {"id": 42, "another_column": "barfoo"}

Online example for Postgres 10+

Online example for older Postgres versions

How to label each equation in align environment?

Within the environment align from the package amsmath it is possible to combine the use of \label and \tag for each equation or line. For example, the code:

\documentclass{article}
\usepackage{amsmath}

\begin{document}
Write
\begin{align}
x+y\label{eq:eq1}\tag{Aa}\\
x+z\label{eq:eq2}\tag{Bb}\\
y-z\label{eq:eq3}\tag{Cc}\\
y-2z\nonumber
\end{align}
then cite \eqref{eq:eq1} and \eqref{eq:eq2} or \eqref{eq:eq3} separately.
\end{document}

produces:

screenshot of output

C++ error : terminate called after throwing an instance of 'std::bad_alloc'

The problem in your code is that you can't store the memory address of a local variable (local to a function, for example) in a globlar variable:

RectInvoice rect(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(&rect);

There, &rect is a temporary address (stored in the function's activation registry) and will be destroyed when that function end.

The code should create a dynamic variable:

RectInvoice *rect =  new RectInvoice(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(rect);

There you are using a heap address that will not be destroyed in the end of the function's execution. Tell me if it worked for you.

Cheers

Passing a String by Reference in Java?

String is immutable in java. you cannot modify/change, an existing string literal/object.

String s="Hello"; s=s+"hi";

Here the previous reference s is replaced by the new refernce s pointing to value "HelloHi".

However, for bringing mutability we have StringBuilder and StringBuffer.

StringBuilder s=new StringBuilder(); s.append("Hi");

this appends the new value "Hi" to the same refernce s. //

in python how do I convert a single digit number into a double digits string?

If you are an analyst and not a full stack guy, this might be more intuitive:

[(str('00000') + str(i))[-5:] for i in arange(100)]

breaking that down, you:

  • start by creating a list that repeats 0's or X's, in this case, 100 long, i.e., arange(100)

  • add the numbers you want to the string, in this case, numbers 0-99, i.e., 'i'

  • keep only the right hand 5 digits, i.e., '[-5:]' for subsetting

  • output is numbered list, all with 5 digits

How to list files in a directory in a C program?

One tiny addition to JB Jansen's answer - in the main readdir() loop I'd add this:

  if (dir->d_type == DT_REG)
  {
     printf("%s\n", dir->d_name);
  }

Just checking if it's really file, not (sym)link, directory, or whatever.

NOTE: more about struct dirent in libc documentation.

Monitoring the Full Disclosure mailinglist

Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.

You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.

But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.

You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.

How does "make" app know default target to build if no target is specified?

By default, it begins by processing the first target that does not begin with a . aka the default goal; to do that, it may have to process other targets - specifically, ones the first target depends on.

The GNU Make Manual covers all this stuff, and is a surprisingly easy and informative read.

How to convert datetime to integer in python

It depends on what the integer is supposed to encode. You could convert the date to a number of milliseconds from some previous time. People often do this affixed to 12:00 am January 1 1970, or 1900, etc., and measure time as an integer number of milliseconds from that point. The datetime module (or others like it) will have functions that do this for you: for example, you can use int(datetime.datetime.utcnow().timestamp()).

If you want to semantically encode the year, month, and day, one way to do it is to multiply those components by order-of-magnitude values large enough to juxtapose them within the integer digits:

2012-06-13 --> 20120613 = 10,000 * (2012) + 100 * (6) + 1*(13)

def to_integer(dt_time):
    return 10000*dt_time.year + 100*dt_time.month + dt_time.day

E.g.

In [1]: import datetime

In [2]: %cpaste
Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
:def to_integer(dt_time):
:    return 10000*dt_time.year + 100*dt_time.month + dt_time.day
:    # Or take the appropriate chars from a string date representation.
:--

In [3]: to_integer(datetime.date(2012, 6, 13))
Out[3]: 20120613

If you also want minutes and seconds, then just include further orders of magnitude as needed to display the digits.

I've encountered this second method very often in legacy systems, especially systems that pull date-based data out of legacy SQL databases.

It is very bad. You end up writing a lot of hacky code for aligning dates, computing month or day offsets as they would appear in the integer format (e.g. resetting the month back to 1 as you pass December, then incrementing the year value), and boiler plate for converting to and from the integer format all over.

Unless such a convention lives in a deep, low-level, and thoroughly tested section of the API you're working on, such that everyone who ever consumes the data really can count on this integer representation and all of its helper functions, then you end up with lots of people re-writing basic date-handling routines all over the place.

It's generally much better to leave the value in a date context, like datetime.date, for as long as you possibly can, so that the operations upon it are expressed in a natural, date-based context, and not some lone developer's personal hack into an integer.

Storing SHA1 hash values in MySQL

You may still want to use VARCHAR in cases where you don't always store a hash for the user (i.e. authenticating accounts/forgot login url). Once a user has authenticated/changed their login info they shouldn't be able to use the hash and should have no reason to. You could create a separate table to store temporary hash -> user associations that could be deleted but I don't think most people bother to do this.

How can VBA connect to MySQL database in Excel?

This piece of vba worked for me:

Sub connect()
    Dim Password As String
    Dim SQLStr As String
    'OMIT Dim Cn statement
    Dim Server_Name As String
    Dim User_ID As String
    Dim Database_Name As String
    'OMIT Dim rs statement

    Set rs = CreateObject("ADODB.Recordset") 'EBGen-Daily
    Server_Name = Range("b2").Value
    Database_name = Range("b3").Value ' Name of database
    User_ID = Range("b4").Value 'id user or username
    Password = Range("b5").Value 'Password

    SQLStr = "SELECT * FROM ComputingNotesTable"

    Set Cn = CreateObject("ADODB.Connection") 'NEW STATEMENT
    Cn.Open "Driver={MySQL ODBC 5.2.2 Driver};Server=" & _ 
            Server_Name & ";Database=" & Database_Name & _
            ";Uid=" & User_ID & ";Pwd=" & Password & ";"

    rs.Open SQLStr, Cn, adOpenStatic

    Dim myArray()

    myArray = rs.GetRows()

    kolumner = UBound(myArray, 1)
    rader = UBound(myArray, 2)

    For K = 0 To kolumner ' Using For loop data are displayed
        Range("a5").Offset(0, K).Value = rs.Fields(K).Name
        For R = 0 To rader
           Range("A5").Offset(R + 1, K).Value = myArray(K, R)
        Next
    Next

    rs.Close
    Set rs = Nothing
    Cn.Close
    Set Cn = Nothing
End Sub

android activity has leaked window com.android.internal.policy.impl.phonewindow$decorview Issue

Thank you Guys to give me many suggestions. Finally I got a solution. That is i have started the NetErrorPage intent two times. One time, i have checked the net connection availability and started the intent in page started event. second time, if the page has error, then i have started the intent in OnReceivedError event. So the first time dialog is not closed, before that the second dialog is called. So that i got a error.

Reason for the Error: I have called the showInfoMessageDialog method two times before closing the first one.

Now I have removed the second call and Cleared error :-).

Creating a "Hello World" WebSocket example

WebSockets is protocol that relies on TCP streamed connection. Although WebSockets is Message based protocol.

If you want to implement your own protocol then I recommend to use latest and stable specification (for 18/04/12) RFC 6455. This specification contains all necessary information regarding handshake and framing. As well most of description on scenarios of behaving from browser side as well as from server side. It is highly recommended to follow what recommendations tells regarding server side during implementing of your code.

In few words, I would describe working with WebSockets like this:

  1. Create server Socket (System.Net.Sockets) bind it to specific port, and keep listening with asynchronous accepting of connections. Something like that:

    Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
    serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8080));
    serverSocket.Listen(128);
    serverSocket.BeginAccept(null, 0, OnAccept, null);
  2. You should have accepting function "OnAccept" that will implement handshake. In future it has to be in another thread if system is meant to handle huge amount of connections per second.

    private void OnAccept(IAsyncResult result) {
    try {
        Socket client = null;
        if (serverSocket != null && serverSocket.IsBound) {
            client = serverSocket.EndAccept(result);
        }
        if (client != null) {
            /* Handshaking and managing ClientSocket */
        }
    } catch(SocketException exception) {
    
    } finally {
        if (serverSocket != null && serverSocket.IsBound) {
            serverSocket.BeginAccept(null, 0, OnAccept, null);
        }
    }
    }
  3. After connection established, you have to do handshake. Based on specification 1.3 Opening Handshake, after connection established you will receive basic HTTP request with some information. Example:

    GET /chat HTTP/1.1
    Host: server.example.com
    Upgrade: websocket
    Connection: Upgrade
    Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
    Origin: http://example.com
    Sec-WebSocket-Protocol: chat, superchat
    Sec-WebSocket-Version: 13

    This example is based on version of protocol 13. Bear in mind that older versions have some differences but mostly latest versions are cross-compatible. Different browsers may send you some additional data. For example Browser and OS details, cache and others.

    Based on provided handshake details, you have to generate answer lines, they are mostly same, but will contain Accpet-Key, that is based on provided Sec-WebSocket-Key. In specification 1.3 it is described clearly how to generate response key. Here is my function I've been using for V13:

    static private string guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
    private string AcceptKey(ref string key) {
        string longKey = key + guid;
        SHA1 sha1 = SHA1CryptoServiceProvider.Create();
        byte[] hashBytes = sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(longKey));
        return Convert.ToBase64String(hashBytes);
    }
    

    Handshake answer looks like that:

    HTTP/1.1 101 Switching Protocols
    Upgrade: websocket
    Connection: Upgrade
    Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

    But accept key have to be the generated one based on provided key from client and method AcceptKey I provided before. As well, make sure after last character of accept key you put two new lines "\r\n\r\n".

  4. After handshake answer is sent from server, client should trigger "onopen" function, that means you can send messages after.
  5. Messages are not sent in raw format, but they have Data Framing. And from client to server as well implement masking for data based on provided 4 bytes in message header. Although from server to client you don't need to apply masking over data. Read section 5. Data Framing in specification. Here is copy-paste from my own implementation. It is not ready-to-use code, and have to be modified, I am posting it just to give an idea and overall logic of read/write with WebSocket framing. Go to this link.
  6. After framing is implemented, make sure that you receive data right way using sockets. For example to prevent that some messages get merged into one, because TCP is still stream based protocol. That means you have to read ONLY specific amount of bytes. Length of message is always based on header and provided data length details in header it self. So when you receiving data from Socket, first receive 2 bytes, get details from header based on Framing specification, then if mask provided another 4 bytes, and then length that might be 1, 4 or 8 bytes based on length of data. And after data it self. After you read it, apply demasking and your message data is ready to use.
  7. You might want to use some Data Protocol, I recommend to use JSON due traffic economy and easy to use on client side in JavaScript. For server side you might want to check some of parsers. There is lots of them, google can be really helpful.

Implementing own WebSockets protocol definitely have some benefits and great experience you get as well as control over protocol it self. But you have to spend some time doing it, and make sure that implementation is highly reliable.

In same time you might have a look in ready to use solutions that google (again) have enough.

Displaying files (e.g. images) stored in Google Drive on a website

If you want to view the file in the browser, it's also possible using a similar method to the one provided by rufo and Torxed:

https://drive.google.com/uc?export=view&id={fileId}

What is the difference between null and undefined in JavaScript?

The best way to understand the difference is to first clear your mind of the inner workings of JavaScript and just understand the differences in meaning between:

let supervisor = "None"
    // I have a supervisor named "None"

let supervisor = null
    // I do NOT have a supervisor. It is a FACT that I do not.

let supervisor = undefined
    // I may or may not have a supervisor. I either don't know
    // if I do or not, or I am choosing not to tell you. It is
    // irrelevant or none of your business.

There is a difference in meaning between these three cases, and JavaScript distinguishes the latter two cases with two different values, null and undefined. You are free to use those values explicitly to convey those meanings.

So what are some of the JavaScript-specific issues that arise due to this philosophical basis?

  1. A declared variable without an initializer gets the value undefined because you never said anything about the what the intended value was.

    let supervisor;
    assert(supervisor === undefined);
    
  2. A property of an object that has never been set evaluates to undefined because no one ever said anything about that property.

    const dog = { name: 'Sparky', age: 2 };
    assert(dog.breed === undefined);
    
  3. null and undefined are "similar" to each other because Brendan Eich said so. But they are emphatically not equal to each other.

    assert(null == undefined);
    assert(null !== undefined);
    
  4. null and undefined thankfully have different types. null belongs to the type Null and undefined to the type Undefined. This is in the spec, but you would never know this because of the typeof weirdness which I will not repeat here.

  5. A function reaching the end of its body without an explicit return statement returns undefined since you don't know anything about what it returned.

By the way, there are other forms of "nothingness" in JavaScript (it's good to have studied Philosophy....)

  • NaN
  • Using a variable that has never been declared and receiving a ReferenceError
  • Using a let or const defined local variable in its temporal dead zone and receiving a ReferenceError
  • Empty cells in sparse arrays. Yes these are not even undefined although they compare === to undefined.

    $ node
    > const a = [1, undefined, 2]
    > const b = [1, , 2]
    > a
    [ 1, undefined, 2 ]
    > b
    [ 1, <1 empty item>, 2 ]
    

mysql_config not found when installing mysqldb python interface

I fixed it by installing libmysqlclient:

sudo apt-get install libmysqlclient16-dev

A server with the specified hostname could not be found

I faced the same problem, it turned out to be VPN related. If you are testing on a device against a corporate network, chances are your Mac has proper VPN set up, but your phone does not. Connect phone to the corporate VPN for your apps deployed to device to see corporate servers.

PHP float with 2 decimal places: .00

try this

$result = number_format($FloatNumber, 2);

Android global variable

Try Like This:

Create a shared data class:

SharedData.java

import android.app.Application;

/**
 * Created by kundan on 6/23/2015.
 */
public class Globals {


    private static Globals instance = new Globals();

    // Getter-Setters
    public static Globals getInstance() {
        return instance;
    }

    public static void setInstance(Globals instance) {
        Globals.instance = instance;
    }

    private String notification_index;


    private Globals() {

    }


    public String getValue() {
        return notification_index;
    }


    public void setValue(String notification_index) {
        this.notification_index = notification_index;
    }



}

Declared/Initiaze an instance of class globally in those classes where you want to set/get data (using this code before onCreate() method):-

Globals sharedData = Globals.getInstance();

Set data:

sharedData.setValue("kundan");

Get data:

String n = sharedData.getValue();

How to convert string date to Timestamp in java?

Use capital HH to get hour of day format, instead of am/pm hours

Decimal to Hexadecimal Converter in Java

One possible solution:

import java.lang.StringBuilder;

class Test {
  private static final int sizeOfIntInHalfBytes = 8;
  private static final int numberOfBitsInAHalfByte = 4;
  private static final int halfByte = 0x0F;
  private static final char[] hexDigits = { 
    '0', '1', '2', '3', '4', '5', '6', '7', 
    '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  };

  public static String decToHex(int dec) {
    StringBuilder hexBuilder = new StringBuilder(sizeOfIntInHalfBytes);
    hexBuilder.setLength(sizeOfIntInHalfBytes);
    for (int i = sizeOfIntInHalfBytes - 1; i >= 0; --i)
    {
      int j = dec & halfByte;
      hexBuilder.setCharAt(i, hexDigits[j]);
      dec >>= numberOfBitsInAHalfByte;
    }
    return hexBuilder.toString(); 
  }

  public static void main(String[] args) {
     int dec = 305445566;
     String hex = decToHex(dec);
     System.out.println(hex);       
  }
}

Output:

1234BABE

Anyway, there is a library method for this:

String hex = Integer.toHexString(dec);

jquery .html() vs .append()

Whenever you pass a string of HTML to any of jQuery's methods, this is what happens:

A temporary element is created, let's call it x. x's innerHTML is set to the string of HTML that you've passed. Then jQuery will transfer each of the produced nodes (that is, x's childNodes) over to a newly created document fragment, which it will then cache for next time. It will then return the fragment's childNodes as a fresh DOM collection.

Note that it's actually a lot more complicated than that, as jQuery does a bunch of cross-browser checks and various other optimisations. E.g. if you pass just <div></div> to jQuery(), jQuery will take a shortcut and simply do document.createElement('div').

EDIT: To see the sheer quantity of checks that jQuery performs, have a look here, here and here.


innerHTML is generally the faster approach, although don't let that govern what you do all the time. jQuery's approach isn't quite as simple as element.innerHTML = ... -- as I mentioned, there are a bunch of checks and optimisations occurring.


The correct technique depends heavily on the situation. If you want to create a large number of identical elements, then the last thing you want to do is create a massive loop, creating a new jQuery object on every iteration. E.g. the quickest way to create 100 divs with jQuery:

jQuery(Array(101).join('<div></div>'));

There are also issues of readability and maintenance to take into account.

This:

$('<div id="' + someID + '" class="foobar">' + content + '</div>');

... is a lot harder to maintain than this:

$('<div/>', {
    id: someID,
    className: 'foobar',
    html: content
});

Unable to start Service Intent

In my case the 1 MB maximum cap for data transport by Intent. I'll just use Cache or Storage.

Difference between "\n" and Environment.NewLine

Environment.NewLine will give "\r\n" when run on Windows. If you are generating strings for Unix based environments, you don't want the "\r".

Uncaught SyntaxError: Unexpected token :

This happened to because I have a rule setup in my express server to route any 404 back to /# plus whatever the original request was. Allowing the angular router/js to handle the request. If there's no js route to handle that path, a request to /#/whatever is made to the server, which is just a request for /, the entire webpage.

So for example if I wanted to make a request for /correct/somejsfile.js but I miss typed it to /wrong/somejsfile.js the request is made to the server. That location/file does not exist, so the server responds with a 302 location: /#/wrong/somejsfile.js. The browser happily follows the redirect and the entire webpage is returned. The browser parses the page as js and you get

Uncaught SyntaxError: Unexpected token <

So to help find the offending path/request look for 302 requests.

Hope that helps someone.

Open CSV file via VBA (performance)

Sometimes all the solutions with Workbooks.open is not working no matter how many parameters are set. For me, the fastest solution was to change the List separator in Region & language settings. Region window / Additional settings... / List separator.

If csv is not opening in proper way You probly have set ',' as a list separator. Just change it to ';' and everything is solved. Just the easiest way when "everything is against You" :P

PostgreSQL error: Fatal: role "username" does not exist

Use the operating system user postgres to create your database - as long as you haven't set up a database role with the necessary privileges that corresponds to your operating system user of the same name (h9uest in your case):

sudo -u postgres -i

As recommended here or here.

Then try again. Type exit when done with operating as system user postgres.

Or execute the single command createuser as postgres with sudo, like demonstrated by drees in another answer.

The point is to use the operating system user matching the database role of the same name to be granted access via ident authentication. postgres is the default operating system user to have initialized the database cluster. The manual:

In order to bootstrap the database system, a freshly initialized system always contains one predefined role. This role is always a “superuser”, and by default (unless altered when running initdb) it will have the same name as the operating system user that initialized the database cluster. Customarily, this role will be named postgres. In order to create more roles you first have to connect as this initial role.

I have heard of odd setups with non-standard user names or where the operating system user does not exist. You'd need to adapt your strategy there.

Read about database roles and client authentication in the manual.

Count lines in large files

If your computer has python, you can try this from the shell:

python -c "print len(open('test.txt').read().split('\n'))"

This uses python -c to pass in a command, which is basically reading the file, and splitting by the "newline", to get the count of newlines, or the overall length of the file.

@BlueMoon's:

bash-3.2$ sed -n '$=' test.txt
519

Using the above:

bash-3.2$ python -c "print len(open('test.txt').read().split('\n'))"
519

varbinary to string on SQL Server

For a VARBINARY(MAX) column, I had to use NVARCHAR(MAX):

cast(Content as nvarchar(max))

Or

CONVERT(NVARCHAR(MAX), Content, 0)
VARCHAR(MAX) didn't show the entire value

Create a nonclustered non-unique index within the CREATE TABLE statement with SQL Server

As of SQL 2014, this can be accomplished via inline index creation:

CREATE TABLE MyTable(
    a int NOT NULL
    ,b smallint NOT NULL
    ,c smallint NOT NULL
    ,d smallint NOT NULL
    ,e smallint NOT NULL

    -- This creates a primary key
    ,CONSTRAINT PK_MyTable PRIMARY KEY CLUSTERED (a)

    -- This creates a unique nonclustered index on columns b and c
    ,CONSTRAINT IX_MyTable1 UNIQUE (b, c)

    -- This creates a standard non-clustered index on (d, e)
    ,INDEX IX_MyTable4 NONCLUSTERED (d, e)
);
GO

Prior to SQL 2014, CREATE/ALTER TABLE only accepted CONSTRAINTs to be added, not indexes. The fact that primary key and unique constraints are implemented in terms of an index is a side effect.

How to display a content in two-column layout in LaTeX?

Load the multicol package, like this \usepackage{multicol}. Then use:

\begin{multicols}{2}
Column 1
\columnbreak
Column 2
\end{multicols}

If you omit the \columnbreak, the columns will balance automatically.

Is gcc's __attribute__((packed)) / #pragma pack unsafe?

As ams said above, don't take a pointer to a member of a struct that's packed. This is simply playing with fire. When you say __attribute__((__packed__)) or #pragma pack(1), what you're really saying is "Hey gcc, I really know what I'm doing." When it turns out that you do not, you can't rightly blame the compiler.

Perhaps we can blame the compiler for it's complacency though. While gcc does have a -Wcast-align option, it isn't enabled by default nor with -Wall or -Wextra. This is apparently due to gcc developers considering this type of code to be a brain-dead "abomination" unworthy of addressing -- understandable disdain, but it doesn't help when an inexperienced programmer bumbles into it.

Consider the following:

struct  __attribute__((__packed__)) my_struct {
    char c;
    int i;
};

struct my_struct a = {'a', 123};
struct my_struct *b = &a;
int c = a.i;
int d = b->i;
int *e __attribute__((aligned(1))) = &a.i;
int *f = &a.i;

Here, the type of a is a packed struct (as defined above). Similarly, b is a pointer to a packed struct. The type of of the expression a.i is (basically) an int l-value with 1 byte alignment. c and d are both normal ints. When reading a.i, the compiler generates code for unaligned access. When you read b->i, b's type still knows it's packed, so no problem their either. e is a pointer to a one-byte-aligned int, so the compiler knows how to dereference that correctly as well. But when you make the assignment f = &a.i, you are storing the value of an unaligned int pointer in an aligned int pointer variable -- that's where you went wrong. And I agree, gcc should have this warning enabled by default (not even in -Wall or -Wextra).

displaying a string on the textview when clicking a button in android

public void onCreate(Bundle savedInstanceState) 
{
    setContentView(R.layout.main);
    super.onCreate(savedInstanceState);

    mybtn = (Button)findViewById(R.id.mybtn);
    txtView=(TextView)findViewById(R.id.txtView);

    mybtn .setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            txtView.SetText("Your Message");
        }
    });
}

mysqli_real_connect(): (HY000/2002): No such file or directory

mysqli_connect(): (HY000/2002): No such file or directory

Background:

I was just wanted to run some PHPUnit tests on my Mac, using Terminal. Some of the classes I wanna test was having to connect MySQL DB which was created and managed by PHPMyAdmin, and the web app I was working was working fine in the localhost. So when I ran that testcases I got the following error on my terminal:

mysqli_connect(): (HY000/2002): No such file or directory

Solution:

So with the itchiness I had to resolve it and run my test I searched in few SO Q&A threads and tried out. And a combination of changes worked for me.

  1. Locate your config.inc.php file which relates to PHPMyAdmin.
  2. Locate the line $cfg['Servers'][$i]['host'] mostly this line might have been commented out by default, if so please uncomment it.
  3. And replace that line with following:

$cfg['Servers'][$i]['host'] = '127.0.0.1';

  1. Save it and restart the MySQL Database from your XAMPP control panel (manager-osx).
  2. Change your $host parameter value in the mysqli_connect() method to following:

$_connection = mysqli_connect(**"localhost: 3306"**, $_mysql_username, $_mysql_password, $_database);

Note: This 3306 is my MySQL port number which is its default. You should better check what's your actual MySQL Port number before going to follow these steps.

And that's all. For me only these set of steps worked and nothing else. I ran my Unit Tests and it's working fine and the DB data were also updated properly according to the tests.

Why this works:

The closest reason I could have found is that it works because sometimes the mysqli_connect method requires a working socket(IP Address of the DB Host along with the Port number) of the database. So if you have commented out the $cfg['Servers'][$i]['host'] = '127.0.0.1'; line or have set 'localhost' as the value in it, it ignores the port number. But if you wanna use a socket, then you have to use '127.0.0.1' or the real hostname. (for me it appears to be regardless of the default port number we really have, we have to do the above steps.) Read the following link of PHPMyAdmin for further details.

Hope this might be helpful to somebody else out there.

Cheers!

Remove end of line characters from Java string

public static void main(final String[] argv) 
{
    String str;

    str = "hello\r\n\tjava\r\nbook";
    str = str.replaceAll("(\\r|\\n|\\t)", "");
    System.out.println(str);
}

It would be useful to add the tabulation in regex too.

What's the point of the X-Requested-With header?

Make sure you read SilverlightFox's answer. It highlights a more important reason.

The reason is mostly that if you know the source of a request you may want to customize it a little bit.

For instance lets say you have a website which has many recipes. And you use a custom jQuery framework to slide recipes into a container based on a link they click. The link may be www.example.com/recipe/apple_pie

Now normally that returns a full page, header, footer, recipe content and ads. But if someone is browsing your website some of those parts are already loaded. So you can use an AJAX to get the recipe the user has selected but to save time and bandwidth don't load the header/footer/ads.

Now you can just write a secondary endpoint for the data like www.example.com/recipe_only/apple_pie but that's harder to maintain and share to other people.

But it's easier to just detect that it is an ajax request making the request and then returning only a part of the data. That way the user wastes less bandwidth and the site appears more responsive.

The frameworks just add the header because some may find it useful to keep track of which requests are ajax and which are not. But it's entirely dependent on the developer to use such techniques.

It's actually kind of similar to the Accept-Language header. A browser can request a website please show me a Russian version of this website without having to insert /ru/ or similar in the URL.

Replace \n with actual new line in Sublime Text

None of the above worked for me in Sublime Text 2 on Windows.

I did this:

  • click on an empty line;
  • drag to the following empty line (selecting the invisible character after the line);
  • press ctrl+H for replace;
  • input desired replacement character/string or leave it empty;
  • click "Replace all";

By selecting before hitting ctrl+H it uses that as the character to be replaced.

QByteArray to QString

You can use QTextCodec to convert the bytearray to a string:

QString DataAsString = QTextCodec::codecForMib(1015)->toUnicode(Data);

(1015 is UTF-16, 1014 UTF-16LE, 1013 UTF-16BE, 106 UTF-8)

From your example we can see that the string "test" is encoded as "t\0 e\0 s\0 t\0 \0 \0" in your encoding, i.e. every ascii character is followed by a \0-byte, or resp. every ascii character is encoded as 2 bytes. The only unicode encoding in which ascii letters are encoded in this way, are UTF-16 or UCS-2 (which is a restricted version of UTF-16), so in your case the 1015 mib is needed (assuming your local endianess is the same as the input endianess).

ORA-00904: invalid identifier

Your problem is those pernicious double quotes.

SQL> CREATE TABLE "APC"."PS_TBL_DEPARTMENT_DETAILS"
  2  (
  3    "Company Code" VARCHAR2(255),
  4    "Company Name" VARCHAR2(255),
  5    "Sector_Code" VARCHAR2(255),
  6    "Sector_Name" VARCHAR2(255),
  7    "Business_Unit_Code" VARCHAR2(255),
  8    "Business_Unit_Name" VARCHAR2(255),
  9    "Department_Code" VARCHAR2(255),
 10    "Department_Name" VARCHAR2(255),
 11    "HR_ORG_ID" VARCHAR2(255),
 12    "HR_ORG_Name" VARCHAR2(255),
 13    "Cost_Center_Number" VARCHAR2(255),
 14    " " VARCHAR2(255)
 15  )
 16  /

Table created.

SQL>

Oracle SQL allows us to ignore the case of database object names provided we either create them with names all in upper case, or without using double quotes. If we use mixed case or lower case in the script and wrapped the identifiers in double quotes we are condemned to using double quotes and the precise case whenever we refer to the object or its attributes:

SQL> select count(*) from PS_TBL_DEPARTMENT_DETAILS
  2  where Department_Code = 'BAH'
  3  /
where Department_Code = 'BAH'
      *
ERROR at line 2:
ORA-00904: "DEPARTMENT_CODE": invalid identifier


SQL> select count(*) from PS_TBL_DEPARTMENT_DETAILS
  2  where "Department_Code" = 'BAH'
  3  /

  COUNT(*)
----------
         0

SQL>

tl;dr

don't use double quotes in DDL scripts

(I know most third party code generators do, but they are disciplined enough to put all their object names in UPPER CASE.)


The reverse is also true. If we create the table without using double-quotes …

create table PS_TBL_DEPARTMENT_DETAILS
( company_code VARCHAR2(255),
  company_name VARCHAR2(255),
  Cost_Center_Number VARCHAR2(255))
;

… we can reference it and its columns in whatever case takes our fancy:

select * from ps_tbl_department_details

… or

select * from PS_TBL_DEPARTMENT_DETAILS;

… or

select * from PS_Tbl_Department_Details
where COMAPNY_CODE = 'ORCL'
and cost_center_number = '0980'

Count the number of occurrences of a character in a string in Javascript

Simply, use the split to find out the number of occurrences of a character in a string.

mainStr.split(',').length // gives 4 which is the number of strings after splitting using delimiter comma

mainStr.split(',').length - 1 // gives 3 which is the count of comma

MySQL Nested Select Query?

You just need to write the first query as a subquery (derived table), inside parentheses, pick an alias for it (t below) and alias the columns as well.

The DISTINCT can also be safely removed as the internal GROUP BY makes it redundant:

SELECT DATE(`date`) AS `date` , COUNT(`player_name`) AS `player_count`
FROM (
    SELECT MIN(`date`) AS `date`, `player_name`
    FROM `player_playtime`
    GROUP BY `player_name`
) AS t
GROUP BY DATE( `date`) DESC LIMIT 60 ;

Since the COUNT is now obvious that is only counting rows of the derived table, you can replace it with COUNT(*) and further simplify the query:

SELECT t.date , COUNT(*) AS player_count
FROM (
    SELECT DATE(MIN(`date`)) AS date
    FROM player_playtime
    GROUP BY player_name
) AS t
GROUP BY t.date DESC LIMIT 60 ;

How to check if a class inherits another class without instantiating it?

To check for assignability, you can use the Type.IsAssignableFrom method:

typeof(SomeType).IsAssignableFrom(typeof(Derived))

This will work as you expect for type-equality, inheritance-relationships and interface-implementations but not when you are looking for 'assignability' across explicit / implicit conversion operators.

To check for strict inheritance, you can use Type.IsSubclassOf:

typeof(Derived).IsSubclassOf(typeof(SomeType))

Git On Custom SSH Port

When you want a relative path from your home directory (on any UNIX) you use this strange syntax:

ssh://[user@]host.xz[:port]/~[user]/path/to/repo

For Example, if the repo is in /home/jack/projects/jillweb on the server jill.com and you are logging in as jack with sshd listening on port 4242:

ssh://[email protected]:4242/~/projects/jillweb

And when logging in as jill (presuming you have file permissions):

ssh://[email protected]:4242/~jack/projects/jillweb

How the single threaded non blocking IO model works in Node.js

Node.js uses libuv behind the scenes. libuv has a thread pool (of size 4 by default). Therefore Node.js does use threads to achieve concurrency.

However, your code runs on a single thread (i.e., all of the callbacks of Node.js functions will be called on the same thread, the so called loop-thread or event-loop). When people say "Node.js runs on a single thread" they are really saying "the callbacks of Node.js run on a single thread".

Getting Database connection in pure JPA setup

if you use EclipseLink: You should be in a JPA transaction to access the Connection

entityManager.getTransaction().begin();
java.sql.Connection connection = entityManager.unwrap(java.sql.Connection.class);
...
entityManager.getTransaction().commit();

What is this date format? 2011-08-12T20:17:46.384Z

This technique translates java.util.Date to UTC format (or any other) and back again.

Define a class like so:

import java.util.Date;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class UtcUtility {

public static DateTimeFormatter UTC = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZoneUTC();


public static Date parse(DateTimeFormatter dateTimeFormatter, String date) {
    return dateTimeFormatter.parseDateTime(date).toDate();
}

public static String format(DateTimeFormatter dateTimeFormatter, Date date) {
    return format(dateTimeFormatter, date.getTime());
}

private static String format(DateTimeFormatter dateTimeFormatter, long timeInMillis) {
    DateTime dateTime = new DateTime(timeInMillis);
    String formattedString = dateTimeFormatter.print(dateTime);
    return formattedString;
}

}

Then use it like this:

Date date = format(UTC, "2020-04-19T00:30:07.000Z")

or

String date = parse(UTC, new Date())

You can also define other date formats if you require (not just UTC)

how to get the first and last days of a given month

cal_days_in_month() should give you the total number of days in the month, and therefore, the last one.

Java "?" Operator for checking null - What is it? (Not Ternary!)

One way to workaround the lack of "?" operator using Java 8 without the overhead of try-catch (which could also hide a NullPointerException originated elsewhere, as mentioned) is to create a class to "pipe" methods in a Java-8-Stream style.

public class Pipe<T> {
    private T object;

    private Pipe(T t) {
        object = t;
    }

    public static<T> Pipe<T> of(T t) {
        return new Pipe<>(t);
    }

    public <S> Pipe<S> after(Function<? super T, ? extends S> plumber) {
        return new Pipe<>(object == null ? null : plumber.apply(object));
    }

    public T get() {
        return object;
    }

    public T orElse(T other) {
        return object == null ? other : object;
    }
}

Then, the given example would become:

public String getFirstName(Person person) {
    return Pipe.of(person).after(Person::getName).after(Name::getGivenName).get();
}

[EDIT]

Upon further thought, I figured out that it is actually possible to achieve the same only using standard Java 8 classes:

public String getFirstName(Person person) {
    return Optional.ofNullable(person).map(Person::getName).map(Name::getGivenName).orElse(null);
}

In this case, it is even possible to choose a default value (like "<no first name>") instead of null by passing it as parameter of orElse.

Headers and client library minor version mismatch

The same works for MySQL:

sudo apt-get install php5-mysqlnd

I've read this thread trying to find the solution for MySQL, and I've also seen ken's answer, but I ignored the solution for MariaDB, wasting a few hours that way. It wasn't clear for me that the same may apply to MySQL. This post is just to spare you the few hours I lost.

How add unique key to existing table (with non uniques rows)

I am providing my solution with the assumption on your business logic. Basicall in my design i will allow the table to store only one record for a user-game combination. So I will add a composite key to the table.

PRIMARY KEY (`user_id`,`game_id`)

python - find index position in list based of partial string

Your idea to use enumerate() was correct.

indices = []
for i, elem in enumerate(mylist):
    if 'aa' in elem:
        indices.append(i)

Alternatively, as a list comprehension:

indices = [i for i, elem in enumerate(mylist) if 'aa' in elem]

Passing properties by reference in C#

Just a little expansion to Nathan's Linq Expression solution. Use multi generic param so that the property doesn't limited to string.

void GetString<TClass, TProperty>(string input, TClass outObj, Expression<Func<TClass, TProperty>> outExpr)
{
    if (!string.IsNullOrEmpty(input))
    {
        var expr = (MemberExpression) outExpr.Body;
        var prop = (PropertyInfo) expr.Member;
        if (!prop.GetValue(outObj).Equals(input))
        {
            prop.SetValue(outObj, input, null);
        }
    }
}

SQL Server Profiler - How to filter trace to only display events from one database?

In the Trace properties, click the Events Selection tab at the top next to General. Then click Column Filters... at the bottom right. You can then select what to filter, such as TextData or DatabaseName.

Expand the Like node and enter your filter with the percentage % signs like %MyDatabaseName% or %TextDataToFilter%. Without the %% signs the filter will not work.

Also, make sure to check the checkbox Exclude rows that do not contain values' If you cannot find the field you are looking to filter such as DatabaseName go to the General tab and change your Template, blank one should contain all the fields.

Updating a local repository with changes from a GitHub repository

This question is very general and there are a couple of assumptions I'll make to simplify it a bit. We'll assume that you want to update your master branch.

If you haven't made any changes locally, you can use git pull to bring down any new commits and add them to your master.

git pull origin master

If you have made changes, and you want to avoid adding a new merge commit, use git pull --rebase.

git pull --rebase origin master

git pull --rebase will work even if you haven't made changes and is probably your best call.

WARNING in budgets, maximum exceeded for initial

Open angular.json file and find budgets keyword.

It should look like:

    "budgets": [
       {
          "type": "initial",
          "maximumWarning": "2mb",
          "maximumError": "5mb"
       }
    ]

As you’ve probably guessed you can increase the maximumWarning value to prevent this warning, i.e.:

    "budgets": [
       {
          "type": "initial",
          "maximumWarning": "4mb", <===
          "maximumError": "5mb"
       }
    ]

What does budgets mean?

A performance budget is a group of limits to certain values that affect site performance, that may not be exceeded in the design and development of any web project.

In our case budget is the limit for bundle sizes.

See also:

Multi-dimensional arrays in Bash

I do this using associative arrays since bash 4 and setting IFS to a value that can be defined manually.

The purpose of this approach is to have arrays as values of associative array keys.

In order to set IFS back to default just unset it.

  • unset IFS

This is an example:

#!/bin/bash

set -euo pipefail

# used as value in asscciative array
test=(
  "x3:x4:x5"
)
# associative array
declare -A wow=(
  ["1"]=$test
  ["2"]=$test
)
echo "default IFS"
for w in ${wow[@]}; do
  echo "  $w"
done

IFS=:
echo "IFS=:"
for w in ${wow[@]}; do
  for t in $w; do
    echo "  $t"
  done
done
echo -e "\n or\n"
for w in ${!wow[@]}
do
  echo "  $w"
  for t in ${wow[$w]}
  do
    echo "    $t"
  done
done

unset IFS
unset w
unset t
unset wow
unset test

The output of the script below is:

default IFS
  x3:x4:x5
  x3:x4:x5
IFS=:
  x3
  x4
  x5
  x3
  x4
  x5

 or

  1
    x3
    x4
    x5
  2
    x3
    x4
    x5

How to check if object property exists with a variable holding the property name?

A much more secure way to check if property exists on the object is to use empty object or object prototype to call hasOwnProperty()

var foo = {
  hasOwnProperty: function() {
    return false;
  },
  bar: 'Here be dragons'
};

foo.hasOwnProperty('bar'); // always returns false

// Use another Object's hasOwnProperty and call it with 'this' set to foo
({}).hasOwnProperty.call(foo, 'bar'); // true

// It's also possible to use the hasOwnProperty property from the Object
// prototype for this purpose
Object.prototype.hasOwnProperty.call(foo, 'bar'); // true

Reference from MDN Web Docs - Object.prototype.hasOwnProperty()

Bad Request - Invalid Hostname IIS7

I'm not sure if this was your problem but for anyone that's trying to access his web application from his machine and having this problem:

Make sure you're connecting to 127.0.0.1 (a.k.a localhost) and not to your external IP address.

Your URL should be something like http://localhost:8181/ or http://127.0.0.1:8181 and not http://YourExternalIPaddress:8181/.


Additional information:
The reason this works is because your firewall may block your own request. It can be a firewall on your OS and it can be (the usual) your router.

When you connect to your external IP address, you connect to you from the internet, as if you were a stranger (or a hacker).
However when you connect to your localhost, you connect locally as yourself and the block is obviously not needed (& avoided altogether).

jQuery multiselect drop down menu

I was also looking for a simple multi select for my company. I wanted something simple, highly customizable and with no big dependencies others than jQuery.

I didn't found one fitting my needs so I decided to code my own.
I use it in production.

Here's some demos and documentation: loudev.com

If you want to contribute, check the github repository

Does WGET timeout?

Since in your question you said it's a PHP script, maybe the best solution could be to simply add in your script:

ignore_user_abort(TRUE);

In this way even if wget terminates, the PHP script goes on being processed at least until it does not exceeds max_execution_time limit (ini directive: 30 seconds by default).

As per wget anyay you should not change its timeout, according to the UNIX manual the default wget timeout is 900 seconds (15 minutes), whis is much larger that the 5-6 minutes you need.

How do I save and restore multiple variables in python?

The following approach seems simple and can be used with variables of different size:

import hickle as hkl
# write variables to filename [a,b,c can be of any size]
hkl.dump([a,b,c], filename)

# load variables from filename
a,b,c = hkl.load(filename)

jQuery SVG, why can't I addClass?

Inspired by the answers above, especially by Sagar Gala, I've created this API. You may use it if you don't want or can't upgrade your jquery version.

RESTful URL design for search

Though I like Justin's response, I feel it more accurately represents a filter rather than a search. What if I want to know about cars with names that start with cam?

The way I see it, you could build it into the way you handle specific resources:
/cars/cam*

Or, you could simply add it into the filter:
/cars/doors/4/name/cam*/colors/red,blue,green

Personally, I prefer the latter, however I am by no means an expert on REST (having first heard of it only 2 or so weeks ago...)

Retrieve list of tasks in a queue in Celery

EDIT: See other answers for getting a list of tasks in the queue.

You should look here: Celery Guide - Inspecting Workers

Basically this:

from celery.app.control import Inspect

# Inspect all nodes.
i = Inspect()

# Show the items that have an ETA or are scheduled for later processing
i.scheduled()

# Show tasks that are currently active.
i.active()

# Show tasks that have been claimed by workers
i.reserved()

Depending on what you want

How to add minutes to current time in swift

I think the simplest will be

let minutes = Date(timeIntervalSinceNow:(minutes * 60.0))

MySQL : ERROR 1215 (HY000): Cannot add foreign key constraint

I don't meet the problem as you. But I get the same ERROR Message. So I mark it down here for others' convience.

Check the charset of two table if the column type is char or varchar. I use a charset=gbk, but I create a new table whose default charset=utf8. So the charset is not the same.

ERROR 1215 (HY000): Cannot add foreign key constraint

To solve it is to use the same charset. For example utf8.

How to prompt for user input and read command-line arguments

As of Python 3.2 2.7, there is now argparse for processing command line arguments.

How do I find out what type each object is in a ArrayList<Object>?

Just call .getClass() on each Object in a loop.

Unfortunately, Java doesn't have map(). :)

If a DOM Element is removed, are its listeners also removed from memory?

Just extending other answers...

Delegated events handlers will not be removed upon element removal.

$('body').on('click', '#someEl', function (event){
  console.log(event);
});

$('#someEL').remove(); // removing the element from DOM

Now check:

$._data(document.body, 'events');

How to merge two sorted arrays into a sorted array?

Here is my java implementation that remove duplicate.

public static int[] mergesort(int[] a, int[] b) {
    int[] c = new int[a.length + b.length];
    int i = 0, j = 0, k = 0, duplicateCount = 0;

    while (i < a.length || j < b.length) {
        if (i < a.length && j < b.length) {
            if (a[i] == b[j]) {
                c[k] = a[i];
                i++;j++;duplicateCount++;
            } else {
                c[k] = a[i] < b[j] ? a[i++] : b[j++];
            }
        } else if (i < a.length) {
            c[k] = a[i++];
        } else if (j < a.length) {
            c[k] = b[j++];
        }
        k++;
    }

    return Arrays.copyOf(c, c.length - duplicateCount);
}

Set IDENTITY_INSERT ON is not working

Here's Microsoft's write up on using SET IDENTITY_INSERT, which might be helpful to others seeing this post if they, like me, found this post when trying to recreate deleted records while maintaining the original identity column value.

to recreate deleted records with original identity column value: http://msdn.microsoft.com/en-us/library/aa259221(v=sql.80).aspx

IE7 Z-Index Layering Issues

http://www.vancelucas.com/blog/fixing-ie7-z-index-issues-with-jquery/

$(function() {
var zIndexNumber = 1000;
$('div').each(function() {
    $(this).css('zIndex', zIndexNumber);
    zIndexNumber -= 10;
});
});

Finding median of list in Python

I posted my solution at Python implementation of "median of medians" algorithm , which is a little bit faster than using sort(). My solution uses 15 numbers per column, for a speed ~5N which is faster than the speed ~10N of using 5 numbers per column. The optimal speed is ~4N, but I could be wrong about it.

Per Tom's request in his comment, I added my code here, for reference. I believe the critical part for speed is using 15 numbers per column, instead of 5.

#!/bin/pypy
#
# TH @stackoverflow, 2016-01-20, linear time "median of medians" algorithm
#
import sys, random


items_per_column = 15


def find_i_th_smallest( A, i ):
    t = len(A)
    if(t <= items_per_column):
        # if A is a small list with less than items_per_column items, then:
        #
        # 1. do sort on A
        # 2. find i-th smallest item of A
        #
        return sorted(A)[i]
    else:
        # 1. partition A into columns of k items each. k is odd, say 5.
        # 2. find the median of every column
        # 3. put all medians in a new list, say, B
        #
        B = [ find_i_th_smallest(k, (len(k) - 1)/2) for k in [A[j:(j + items_per_column)] for j in range(0,len(A),items_per_column)]]

        # 4. find M, the median of B
        #
        M = find_i_th_smallest(B, (len(B) - 1)/2)


        # 5. split A into 3 parts by M, { < M }, { == M }, and { > M }
        # 6. find which above set has A's i-th smallest, recursively.
        #
        P1 = [ j for j in A if j < M ]
        if(i < len(P1)):
            return find_i_th_smallest( P1, i)
        P3 = [ j for j in A if j > M ]
        L3 = len(P3)
        if(i < (t - L3)):
            return M
        return find_i_th_smallest( P3, i - (t - L3))


# How many numbers should be randomly generated for testing?
#
number_of_numbers = int(sys.argv[1])


# create a list of random positive integers
#
L = [ random.randint(0, number_of_numbers) for i in range(0, number_of_numbers) ]


# Show the original list
#
# print L


# This is for validation
#
# print sorted(L)[int((len(L) - 1)/2)]


# This is the result of the "median of medians" function.
# Its result should be the same as the above.
#
print find_i_th_smallest( L, (len(L) - 1) / 2)

How to fix symbol lookup error: undefined symbol errors in a cluster environment

After two dozens of comments to understand the situation, it was found that the libhdf5.so.7 was actually a symlink (with several levels of indirection) to a file that was not shared between the queued processes and the interactive processes. This means even though the symlink itself lies on a shared filesystem, the contents of the file do not and as a result the process was seeing different versions of the library.

For future reference: other than checking LD_LIBRARY_PATH, it's always a good idea to check a library with nm -D to see if the symbols actually exist. In this case it was found that they do exist in interactive mode but not when run in the queue. A quick md5sum revealed that the files were actually different.

Convert an image to grayscale in HTML/CSS

You can use one of the functions of jFunc - use the function "jFunc_CanvasFilterGrayscale" http://jfunc.com/jFunc-functions.aspx

How to make RatingBar to show five stars

Another possibility is you are using the Rating in Adapter of list view

View android.view.LayoutInflater.inflate(int resource, ViewGroup root, boolean attachToRoot)

Below params are necessary for all the attributes to work properly:

  1. Set the root to parent
  2. boolean attachToRoot as false

Ex: convertView = inflater.inflate(R.layout.myId, parent, false);

Using SimpleXML to create an XML object from scratch

Sure you can. Eg.

<?php
$newsXML = new SimpleXMLElement("<news></news>");
$newsXML->addAttribute('newsPagePrefix', 'value goes here');
$newsIntro = $newsXML->addChild('content');
$newsIntro->addAttribute('type', 'latest');
Header('Content-type: text/xml');
echo $newsXML->asXML();
?>

Output

<?xml version="1.0"?>
<news newsPagePrefix="value goes here">
    <content type="latest"/>
</news>

Have fun.

Shrinking navigation bar when scrolling down (bootstrap3)

For those not willing to use jQuery here is a Vanilla Javascript way of doing the same using classList:

function runOnScroll() {
    var element = document.getElementsByTagName('nav')  ;
    if(document.body.scrollTop >= 50) {
        element[0].classList.add('shrink')
    } else {
        element[0].classList.remove('shrink')
    }
    console.log(topMenu[0].classList)

};

There might be a nicer way of doing it using toggle, but the above works fine in Chrome

Mocking Extension Methods with Moq

I have used a Wrapper to get around this problem. Create a wrapper object and pass your mocked method.

See Mocking Static Methods for Unit Testing by Paul Irwin, it has nice examples.

How to specify multiple conditions in an if statement in javascript

Wrap them in an extra pair of parens and you're good to go.

if((Type == 2 && PageCount == 0) || (Type == 2 && PageCount == ''))
    PageCount= document.getElementById('<%=hfPageCount.ClientID %>').value;
}