Programs & Examples On #Winlogon

How to check if a registry value exists using C#?

  RegistryKey rkSubKey = Registry.CurrentUser.OpenSubKey(" Your Registry Key Location", false);
        if (rkSubKey == null)
        {
           // It doesn't exist
        }
        else
        {
           // It exists and do something if you want to
         }

Stop a youtube video with jquery?

I've had this problem before and the conclusion I've come to is that the only way to stop a video in IE is to remove it from the DOM.

How can I catch an error caused by mail()?

This is about the best you can do:

if (!mail(...)) {
   // Reschedule for later try or panic appropriately!
}

http://php.net/manual/en/function.mail.php

mail() returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise.

It is important to note that just because the mail was accepted for delivery, it does NOT mean the mail will actually reach the intended destination.

If you need to suppress warnings, you can use:

if (!@mail(...))

Be careful though about using the @ operator without appropriate checks as to whether something succeed or not.


If mail() errors are not suppressible (weird, but can't test it right now), you could:

a) turn off errors temporarily:

$errLevel = error_reporting(E_ALL ^ E_NOTICE);  // suppress NOTICEs
mail(...);
error_reporting($errLevel);  // restore old error levels

b) use a different mailer, as suggested by fire and Mike.

If mail() turns out to be too flaky and inflexible, I'd look into b). Turning off errors is making debugging harder and is generally ungood.

Easy way to write contents of a Java InputStream to an OutputStream

Use Commons Net's Util class:

import org.apache.commons.net.io.Util;
...
Util.copyStream(in, out);

Find a line in a file and remove it

Here you go. This solution uses a DataInputStream to scan for the position of the string you want replaced and uses a FileChannel to replace the text at that exact position. It only replaces the first occurrence of the string that it finds. This solution doesn't store a copy of the entire file somewhere, (either the RAM or a temp file), it just edits the portion of the file that it finds.

public static long scanForString(String text, File file) throws IOException {
    if (text.isEmpty())
        return file.exists() ? 0 : -1;
    // First of all, get a byte array off of this string:
    byte[] bytes = text.getBytes(/* StandardCharsets.your_charset */);

    // Next, search the file for the byte array.
    try (DataInputStream dis = new DataInputStream(new FileInputStream(file))) {

        List<Integer> matches = new LinkedList<>();

        for (long pos = 0; pos < file.length(); pos++) {
            byte bite = dis.readByte();

            for (int i = 0; i < matches.size(); i++) {
                Integer m = matches.get(i);
                if (bytes[m] != bite)
                    matches.remove(i--);
                else if (++m == bytes.length)
                    return pos - m + 1;
                else
                    matches.set(i, m);
            }

            if (bytes[0] == bite)
                matches.add(1);
        }
    }
    return -1;
}

public static void replaceText(String text, String replacement, File file) throws IOException {
    // Open a FileChannel with writing ability. You don't really need the read
    // ability for this specific case, but there it is in case you need it for
    // something else.
    try (FileChannel channel = FileChannel.open(file.toPath(), StandardOpenOption.WRITE, StandardOpenOption.READ)) {
        long scanForString = scanForString(text, file);
        if (scanForString == -1) {
            System.out.println("String not found.");
            return;
        }
        channel.position(scanForString);
        channel.write(ByteBuffer.wrap(replacement.getBytes(/* StandardCharsets.your_charset */)));
    }
}

Example

Input: ABCDEFGHIJKLMNOPQRSTUVWXYZ

Method Call:

replaceText("QRS", "000", new File("path/to/file");

Resulting File: ABCDEFGHIJKLMNOP000TUVWXYZ

How can I reset or revert a file to a specific revision?

If you know how many commits you need to go back, you can use:

git checkout master~5 image.png

This assumes that you're on the master branch, and the version you want is 5 commits back.

Pandas read_csv low_memory and dtype options

Sometimes, when all else fails, you just want to tell pandas to shut up about it:

# Ignore DtypeWarnings from pandas' read_csv                                                                                                                                                                                            
warnings.filterwarnings('ignore', message="^Columns.*")

Check if a Python list item contains a string inside another string

Use filter to get at the elements that have abc.

>>> lst = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
>>> print filter(lambda x: 'abc' in x, lst)
['abc-123', 'abc-456']

You can also use a list comprehension.

>>> [x for x in lst if 'abc' in x]

By the way, don't use the word list as a variable name since it is already used for the list type.

What is the difference between HTML tags and elements?

<p>Here is a quote from WWF's website:</p>.

In this part <p> is a tag.

<blockquote cite="www.facebook.com">facebook is the world's largest socialsite..</blockquote>

in this part <blockquote> is an element.

How to Compare a long value is equal to Long value

    public static void main(String[] args) {
        long a = 1111;
        Long b = 1113L;
        if(a == b.longValue())
    {
        System.out.println("Equals");
    }else{
        System.out.println("not equals");
    }
  }

or:

    public static void main(String[] args) {
        long a = 1111;
        Long b = 1113L;
        if(a == b)
    {
        System.out.println("Equals");
    }else{
        System.out.println("not equals");
    }
  }

SQL Error: ORA-00942 table or view does not exist

Here is an answer: http://www.dba-oracle.com/concepts/synonyms.htm

An Oracle synonym basically allows you to create a pointer to an object that exists somewhere else. You need Oracle synonyms because when you are logged into Oracle, it looks for all objects you are querying in your schema (account). If they are not there, it will give you an error telling you that they do not exist.

Pass multiple parameters to rest API - Spring

Yes its possible to pass JSON object in URL

queryString = "{\"left\":\"" + params.get("left") + "}";
 httpRestTemplate.exchange(
                    Endpoint + "/A/B?query={queryString}",
                    HttpMethod.GET, entity, z.class, queryString);

Java HttpRequest JSON & Response Handling

The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc

A set of simple examples:

Using Gson:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class Gson {

    public static void main(String[] args) {
    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);
            String json = EntityUtils.toString(result.getEntity(), "UTF-8");

            com.google.gson.Gson gson = new com.google.gson.Gson();
            Response respuesta = gson.fromJson(json, Response.class);

            System.out.println(respuesta.getExample());
            System.out.println(respuesta.getFr());

        } catch (IOException ex) {
        }
        return null;
    }

    public class Response{

        private String example;
        private String fr;

        public String getExample() {
            return example;
        }
        public void setExample(String example) {
            this.example = example;
        }
        public String getFr() {
            return fr;
        }
        public void setFr(String fr) {
            this.fr = fr;
        }
    }
}

Using json-simple:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class JsonSimple {

    public static void main(String[] args) {

    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);

            String json = EntityUtils.toString(result.getEntity(), "UTF-8");
            try {
                JSONParser parser = new JSONParser();
                Object resultObject = parser.parse(json);

                if (resultObject instanceof JSONArray) {
                    JSONArray array=(JSONArray)resultObject;
                    for (Object object : array) {
                        JSONObject obj =(JSONObject)object;
                        System.out.println(obj.get("example"));
                        System.out.println(obj.get("fr"));
                    }

                }else if (resultObject instanceof JSONObject) {
                    JSONObject obj =(JSONObject)resultObject;
                    System.out.println(obj.get("example"));
                    System.out.println(obj.get("fr"));
                }

            } catch (Exception e) {
                // TODO: handle exception
            }

        } catch (IOException ex) {
        }
        return null;
    }
}

etc...

How do I make a splash screen?

Further reading:

Old answer:

HOW TO: Simple splash screen

This answers shows you how to display a splash screen for a fixed amount of time when your app starts for e.g. branding reasons. E.g. you might choose to show the splash screen for 3 seconds. However if you want to show the spash screen for a variable amount of time (e.g. app startup time) you should check out Abdullah's answer https://stackoverflow.com/a/15832037/401025. However be aware that app startup might be very fast on new devices so the user will just see a flash which is bad UX.

First you need to define the spash screen in your layout.xml file

  <?xml version="1.0" encoding="utf-8"?>
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical" android:layout_width="fill_parent"
          android:layout_height="fill_parent">

          <ImageView android:id="@+id/splashscreen" android:layout_width="wrap_content"
                  android:layout_height="fill_parent"
                  android:src="@drawable/splash"
                  android:layout_gravity="center"/>

          <TextView android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:text="Hello World, splash"/>

  </LinearLayout>

And your activity:

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;

public class Splash extends Activity {

    /** Duration of wait **/
    private final int SPLASH_DISPLAY_LENGTH = 1000;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.splashscreen);

        /* New Handler to start the Menu-Activity 
         * and close this Splash-Screen after some seconds.*/
        new Handler().postDelayed(new Runnable(){
            @Override
            public void run() {
                /* Create an Intent that will start the Menu-Activity. */
                Intent mainIntent = new Intent(Splash.this,Menu.class);
                Splash.this.startActivity(mainIntent);
                Splash.this.finish();
            }
        }, SPLASH_DISPLAY_LENGTH);
    }
}

Thats all ;)

jQuery Screen Resolution Height Adjustment

var space = $(window).height();
var diff = space - HEIGHT;
var margin = (diff > 0) ? (space - HEIGHT)/2 : 0;
$('#container').css({'margin-top': margin});

Purpose of #!/usr/bin/python3 shebang

#!/usr/bin/python3 is a shebang line.

A shebang line defines where the interpreter is located. In this case, the python3 interpreter is located in /usr/bin/python3. A shebang line could also be a bash, ruby, perl or any other scripting languages' interpreter, for example: #!/bin/bash.

Without the shebang line, the operating system does not know it's a python script, even if you set the execution flag (chmod +x script.py) on the script and run it like ./script.py. To make the script run by default in python3, either invoke it as python3 script.py or set the shebang line.

You can use #!/usr/bin/env python3 for portability across different systems in case they have the language interpreter installed in different locations.

Colon (:) in Python list index

: is the delimiter of the slice syntax to 'slice out' sub-parts in sequences , [start:end]

[1:5] is equivalent to "from 1 to 5" (5 not included)
[1:] is equivalent to "1 to end"
[len(a):] is equivalent to "from length of a to end"

Watch https://youtu.be/tKTZoB2Vjuk?t=41m40s at around 40:00 he starts explaining that.

Works with tuples and strings, too.

COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'

In my case I created a database and gave the collation 'utf8_general_ci' but the required collation was 'latin1'. After changing my collation type to latin1_bin the error was gone.

How to change a dataframe column from String type to Double type in PySpark?

There is no need for an UDF here. Column already provides cast method with DataType instance :

from pyspark.sql.types import DoubleType

changedTypedf = joindf.withColumn("label", joindf["show"].cast(DoubleType()))

or short string:

changedTypedf = joindf.withColumn("label", joindf["show"].cast("double"))

where canonical string names (other variations can be supported as well) correspond to simpleString value. So for atomic types:

from pyspark.sql import types 

for t in ['BinaryType', 'BooleanType', 'ByteType', 'DateType', 
          'DecimalType', 'DoubleType', 'FloatType', 'IntegerType', 
           'LongType', 'ShortType', 'StringType', 'TimestampType']:
    print(f"{t}: {getattr(types, t)().simpleString()}")
BinaryType: binary
BooleanType: boolean
ByteType: tinyint
DateType: date
DecimalType: decimal(10,0)
DoubleType: double
FloatType: float
IntegerType: int
LongType: bigint
ShortType: smallint
StringType: string
TimestampType: timestamp

and for example complex types

types.ArrayType(types.IntegerType()).simpleString()   
'array<int>'
types.MapType(types.StringType(), types.IntegerType()).simpleString()
'map<string,int>'

IOPub data rate exceeded in Jupyter notebook (when viewing image)

I ran into this using networkx and bokeh

This works for me in Windows 7 (taken from here):

  1. To create a jupyter_notebook_config.py file, with all the defaults commented out, you can use the following command line:

    $ jupyter notebook --generate-config

  2. Open the file and search for c.NotebookApp.iopub_data_rate_limit

  3. Comment out the line c.NotebookApp.iopub_data_rate_limit = 1000000 and change it to a higher default rate. l used c.NotebookApp.iopub_data_rate_limit = 10000000

This unforgiving default config is popping up in a lot of places. See git issues:

It looks like it might get resolved with the 5.1 release

Update:

Jupyter notebook is now on release 5.2.2. This problem should have been resolved. Upgrade using conda or pip.

VBA paste range

This is what I came up to when trying to copy-paste excel ranges with it's sizes and cell groups. It might be a little too specific for my problem but...:

'** 'Copies a table from one place to another 'TargetRange: where to put the new LayoutTable 'typee: If it is an Instalation Layout table(1) or Package Layout table(2) '**

Sub CopyLayout(TargetRange As Range, typee As Integer)
    Application.ScreenUpdating = False
        Dim ncolumn As Integer
        Dim nrow As Integer

        SheetLayout.Activate
    If (typee = 1) Then 'is installation
        Range("installationlayout").Copy Destination:=TargetRange '@SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
    ElseIf (typee = 2) Then 'is package
        Range("PackageLayout").Copy Destination:=TargetRange '@SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
    End If

    Sheet2.Select 'SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@

    If typee = 1 Then
       nrow = SheetLayout.Range("installationlayout").Rows.Count
       ncolumn = SheetLayout.Range("installationlayout").Columns.Count

       Call RowHeightCorrector(SheetLayout.Range("installationlayout"), TargetRange.CurrentRegion, typee, nrow, ncolumn)
    ElseIf typee = 2 Then
       nrow = SheetLayout.Range("PackageLayout").Rows.Count
       ncolumn = SheetLayout.Range("PackageLayout").Columns.Count
       Call RowHeightCorrector(SheetLayout.Range("PackageLayout"), TargetRange.CurrentRegion, typee, nrow, ncolumn)
    End If
    Range("A1").Select 'Deselect the created table

    Application.CutCopyMode = False
    Application.ScreenUpdating = True
End Sub

'** 'Receives the Pasted Table Range and rearranjes it's properties 'accordingly to the original CopiedTable 'typee: If it is an Instalation Layout table(1) or Package Layout table(2) '**

Function RowHeightCorrector(CopiedTable As Range, PastedTable As Range, typee As Integer, RowCount As Integer, ColumnCount As Integer)
    Dim R As Long, C As Long

    For R = 1 To RowCount
        PastedTable.Rows(R).RowHeight = CopiedTable.CurrentRegion.Rows(R).RowHeight
        If R >= 2 And R < RowCount Then
            PastedTable.Rows(R).Group 'Main group of the table
        End If
        If R = 2 Then
            PastedTable.Rows(R).Group 'both type of tables have a grouped section at relative position "2" of Rows
        ElseIf (R = 4 And typee = 1) Then
            PastedTable.Rows(R).Group 'If it is an installation materials table, it has two grouped sections...
        End If
    Next R

    For C = 1 To ColumnCount
        PastedTable.Columns(C).ColumnWidth = CopiedTable.CurrentRegion.Columns(C).ColumnWidth
    Next C
End Function



Sub test ()
    Call CopyLayout(Sheet2.Range("A18"), 2)
end sub

What is a callback?

Dedication to LightStriker:
Sample Code:

class CallBackExample
{
    public delegate void MyNumber();
    public static void CallMeBack()
    {
        Console.WriteLine("He/She is calling you.  Pick your phone!:)");
        Console.Read();
    }
    public static void MetYourCrush(MyNumber number)
    {
        int j;
        Console.WriteLine("is she/he interested 0/1?:");
        var i = Console.ReadLine();
        if (int.TryParse(i, out j))
        {
            var interested = (j == 0) ? false : true;
            if (interested)//event
            {
                //call his/her number
                number();
            }
            else
            {
                Console.WriteLine("Nothing happened! :(");
                Console.Read();
            }
        }
    }
    static void Main(string[] args)
    {
        MyNumber number = Program.CallMeBack;
        Console.WriteLine("You have just met your crush and given your number");
        MetYourCrush(number);
        Console.Read();
        Console.Read();
    }       
}

Code Explanation:

I created the code to implement the funny explanation provided by LightStriker in the above one of the replies. We are passing delegate (number) to a method (MetYourCrush). If the Interested (event) occurs in the method (MetYourCrush) then it will call the delegate (number) which was holding the reference of CallMeBack method. So, the CallMeBack method will be called. Basically, we are passing delegate to call the callback method.

Please let me know if you have any questions.

Manifest merger failed : uses-sdk:minSdkVersion 14

For me the issue like this is solved by changing the

minSdkVersion 14

In the build.gladdle file and use the one that is specified in the error message

but the issue was

Manifest merger failed : uses-sdk:minSdkVersion 14 cannot be smaller than version 15 declared in library

So I changed from 14 to 15 in the build.gladdle file and it works

give it a try.

Postman: sending nested JSON object

I got it working using the Raw data option in postman, as you can see in the screen shot

enter image description here

Using BeautifulSoup to extract text without tags

Just loop through all the <strong> tags and use next_sibling to get what you want. Like this:

for strong_tag in soup.find_all('strong'):
    print(strong_tag.text, strong_tag.next_sibling)

Demo:

from bs4 import BeautifulSoup

html = '''
<p>
  <strong class="offender">YOB:</strong> 1987<br />
  <strong class="offender">RACE:</strong> WHITE<br />
  <strong class="offender">GENDER:</strong> FEMALE<br />
  <strong class="offender">HEIGHT:</strong> 5'05''<br />
  <strong class="offender">WEIGHT:</strong> 118<br />
  <strong class="offender">EYE COLOR:</strong> GREEN<br />
  <strong class="offender">HAIR COLOR:</strong> BROWN<br />
</p>
'''

soup = BeautifulSoup(html)

for strong_tag in soup.find_all('strong'):
    print(strong_tag.text, strong_tag.next_sibling)

This gives you:

YOB:  1987
RACE:  WHITE
GENDER:  FEMALE
HEIGHT:  5'05''
WEIGHT:  118
EYE COLOR:  GREEN
HAIR COLOR:  BROWN

Quickest way to find missing number in an array of numbers

On a similar scenario, where the array is already sorted, it does not include duplicates and only one number is missing, it is possible to find this missing number in log(n) time, using binary search.

public static int getMissingInt(int[] intArray, int left, int right) {
    if (right == left + 1) return intArray[right] - 1;
    int pivot = left + (right - left) / 2;
    if (intArray[pivot] == intArray[left] + (intArray[right] - intArray[left]) / 2 - (right - left) % 2)
        return getMissingInt(intArray, pivot, right);
    else 
        return getMissingInt(intArray, left, pivot);
}

public static void main(String args[]) {
    int[] array = new int[]{3, 4, 5, 6, 7, 8, 10};
    int missingInt = getMissingInt(array, 0, array.length-1);
    System.out.println(missingInt); //it prints 9
}

prevent iphone default keyboard when focusing an <input>

@rene-pot is correct. You will however have a not-allowed sign on the desktop version of the website. Way around this, apply the readonly="true" to a div that will show up on the mobile view only and not on desktop. See what we did here http://www.naivashahotels.com/naivasha-hotels/lake-naivasha-country-club/

How to scroll to an element inside a div?

Here's a simple pure JavaScript solution that works for a target Number (value for scrollTop), target DOM element, or some special String cases:

/**
 * target - target to scroll to (DOM element, scrollTop Number, 'top', or 'bottom'
 * containerEl - DOM element for the container with scrollbars
 */
var scrollToTarget = function(target, containerEl) {
    // Moved up here for readability:
    var isElement = target && target.nodeType === 1,
        isNumber = Object.prototype.toString.call(target) === '[object Number]';

    if (isElement) {
        containerEl.scrollTop = target.offsetTop;
    } else if (isNumber) {
        containerEl.scrollTop = target;
    } else if (target === 'bottom') {
        containerEl.scrollTop = containerEl.scrollHeight - containerEl.offsetHeight;
    } else if (target === 'top') {
        containerEl.scrollTop = 0;
    }
};

And here are some examples of usage:

// Scroll to the top
var scrollableDiv = document.getElementById('scrollable_div');
scrollToTarget('top', scrollableDiv);

or

// Scroll to 200px from the top
var scrollableDiv = document.getElementById('scrollable_div');
scrollToTarget(200, scrollableDiv);

or

// Scroll to targetElement
var scrollableDiv = document.getElementById('scrollable_div');
var targetElement= document.getElementById('target_element');
scrollToTarget(targetElement, scrollableDiv);

Asp.Net MVC with Drop Down List, and SelectListItem Assistance

You have a view model to which your view is strongly typed => use strongly typed helpers:

<%= Html.DropDownListFor(
    x => x.SelectedAccountId, 
    new SelectList(Model.Accounts, "Value", "Text")
) %>

Also notice that I use a SelectList for the second argument.

And in your controller action you were returning the view model passed as argument and not the one you constructed inside the action which had the Accounts property correctly setup so this could be problematic. I've cleaned it a bit:

public ActionResult AccountTransaction()
{
    var accounts = Services.AccountServices.GetAccounts(false);
    var viewModel = new AccountTransactionView
    {
        Accounts = accounts.Select(a => new SelectListItem
        {
            Text = a.Description,
            Value = a.AccountId.ToString()
        })
    };
    return View(viewModel);
}

How to send password using sftp batch file

You mention batch files, am I correct then assuming that you're talking about a Windows system? If so you cannot use sshpass, and you will have to switch to a different option.

Two of such options, that follow diametrically opposite philosophies are:

  • psftp: command-line tool that you can call from within your batch scripts; psftp is part of the PuTTY package and you can find it here http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html
  • Syncplify.me FTP Script: a scriptable FTP/S and SFTP client for Windows that allows you to store your password in encrypted "profile files"; check it out here http://www.syncplify.me/products/ftp-script/

Either way, switching from password to PKI authentication is strongly recommended.

[Vue warn]: Cannot find element

I think sometimes stupid mistakes can give us this error.

<div id="#main"> <--- id with hashtag
    <div id="mainActivity" v-component="{{currentActivity}}" class="activity"></div>
</div>

To

<div id="main"> <--- id without hashtag
    <div id="mainActivity" v-component="{{currentActivity}}" class="activity"></div>
</div>

Escape quote in web.config connection string

Use &quot; That should work.

how to send multiple data with $.ajax() jquery

I would recommend using a hash instead of a param string:

data = {id: id, name: name}

How do you create a daemon in Python?

I am afraid the daemon module mentioned by @Dustin didn't work for me. Instead I installed python-daemon and used the following code:

# filename myDaemon.py
import sys
import daemon
sys.path.append('/home/ubuntu/samplemodule') # till __init__.py
from samplemodule import moduleclass 

with daemon.DaemonContext():
    moduleclass.do_running() # I have do_running() function and whatever I was doing in __main__() in module.py I copied in it.

Running is easy

> python myDaemon.py

just for completeness here is samplemodule directory content

>ls samplemodule
__init__.py __init__.pyc moduleclass.py

The content of moduleclass.py can be

class moduleclass():
    ...

def do_running():
    m = moduleclass()
    # do whatever daemon is required to do.

How to increment a datetime by one day?

You can also import timedelta so the code is cleaner.

from datetime import datetime, timedelta
date = datetime.now() + timedelta(seconds=[delta_value])

Then convert to date to string

date = date.strftime('%Y-%m-%d %H:%M:%S')

Python one liner is

date = (datetime.now() + timedelta(seconds=[delta_value])).strftime('%Y-%m-%d %H:%M:%S')

javaw.exe cannot find path

Make sure to download these from here:

enter image description here

Also create PATH enviroment variable on you computer like this (if it doesn't exist already):

  1. Right click on My Computer/Computer
  2. Properties
  3. Advanced system settings (or just Advanced)
  4. Enviroment variables
  5. If PATH variable doesn't exist among "User variables" click New (Variable name: PATH, Variable value : C:\Program Files\Java\jdk1.8.0\bin; <-- please check out the right version, this may differ as Oracle keeps updating Java). ; in the end enables assignment of multiple values to PATH variable.
  6. Click OK! Done

enter image description here

To be sure that everything works, open CMD Prompt and type: java -version to check for Java version and javac to be sure that compiler responds.

enter image description here

I hope this helps. Good luck!

Can two or more people edit an Excel document at the same time?

No, sadly:

The Excel 2010 client application does not support co-authoring workbooks in SharePoint Server 2010. However, the Excel client application does support non-real-time co-authoring workbooks stored locally or on network (UNC) paths by using the Shared Workbook feature. Co-authoring workbooks in SharePoint is supported by using the Microsoft Excel Web App, included with Office Web Apps

From Co-authoring overview (SharePoint Server 2010)

...and not for SharePoint 2013 either. Though it works for pretty much all other Office documents. Go figure.

How to see docker image contents

You should not start a container just to see the image contents. For instance, you might want to look for malicious content, not run it. Use "create" instead of "run";

docker create --name="tmp_$$" image:tag
docker export tmp_$$ | tar t
docker rm tmp_$$

jQuery if div contains this text, replace that part of the text

Very simple just use this code, it will preserve the HTML, while removing unwrapped text only:

jQuery(function($){

    // Replace 'td' with your html tag
    $("td").html(function() { 

    // Replace 'ok' with string you want to change, you can delete 'hello everyone' to remove the text
          return $(this).html().replace("ok", "hello everyone");  

    });
});

Here is full example: https://blog.hfarazm.com/remove-unwrapped-text-jquery/

drag drop files into standard html file input

_x000D_
_x000D_
//----------App.js---------------------//_x000D_
$(document).ready(function() {_x000D_
    var holder = document.getElementById('holder');_x000D_
    holder.ondragover = function () { this.className = 'hover'; return false; };_x000D_
    holder.ondrop = function (e) {_x000D_
      this.className = 'hidden';_x000D_
      e.preventDefault();_x000D_
      var file = e.dataTransfer.files[0];_x000D_
      var reader = new FileReader();_x000D_
      reader.onload = function (event) {_x000D_
          document.getElementById('image_droped').className='visible'_x000D_
          $('#image_droped').attr('src', event.target.result);_x000D_
      }_x000D_
      reader.readAsDataURL(file);_x000D_
    };_x000D_
});
_x000D_
.holder_default {_x000D_
    width:500px; _x000D_
    height:150px; _x000D_
    border: 3px dashed #ccc;_x000D_
}_x000D_
_x000D_
#holder.hover { _x000D_
    width:400px; _x000D_
    height:150px; _x000D_
    border: 3px dashed #0c0 !important; _x000D_
}_x000D_
_x000D_
.hidden {_x000D_
    visibility: hidden;_x000D_
}_x000D_
_x000D_
.visible {_x000D_
    visibility: visible;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
_x000D_
<html>_x000D_
    <head>_x000D_
        <title> HTML 5 </title>_x000D_
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.js"></script>_x000D_
    </head>_x000D_
    <body>_x000D_
      <form method="post" action="http://example.com/">_x000D_
        <div id="holder" style="" id="holder" class="holder_default">_x000D_
          <img src="" id="image_droped" width="200" style="border: 3px dashed #7A97FC;" class=" hidden"/>_x000D_
        </div>_x000D_
      </form>_x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Unable to run Java code with Intellij IDEA

If you are just opened a new java project then create a new folder src/ in the man project location.

Then cut and paste all your package in that folder.

Then Right click on src directory and select option Mark Directory As > Sources Root.

how to end ng serve or firebase serve

On macOS Mojave 10.14.4, you can also try Command ? + Q in a terminal.

Server Document Root Path in PHP

$files = glob($_SERVER["DOCUMENT_ROOT"]."/myFolder/*");

How to get a URL parameter in Express?

This will work if your route looks like this: localhost:8888/p?tagid=1234

var tagId = req.query.tagid;
console.log(tagId); // outputs: 1234
console.log(req.query.tagid); // outputs: 1234

Otherwise use the following code if your route looks like this: localhost:8888/p/1234

var tagId = req.params.tagid;
console.log(tagId); // outputs: 1234
console.log(req.params.tagid); // outputs: 1234

How to insert newline in string literal?

If you want a const string that contains Environment.NewLine in it you can do something like this:

const string stringWithNewLine =
@"first line
second line
third line";

EDIT

Since this is in a const string it is done in compile time therefore it is the compiler's interpretation of a newline. I can't seem to find a reference explaining this behavior but, I can prove it works as intended. I compiled this code on both Windows and Ubuntu (with Mono) then disassembled and these are the results:

Disassemble on Windows Disassemble on Ubuntu

As you can see, in Windows newlines are interpreted as \r\n and on Ubuntu as \n

Increment a database field by 1

Updating an entry:

A simple increment should do the trick.

UPDATE mytable 
  SET logins = logins + 1 
  WHERE id = 12

Insert new row, or Update if already present:

If you would like to update a previously existing row, or insert it if it doesn't already exist, you can use the REPLACE syntax or the INSERT...ON DUPLICATE KEY UPDATE option (As Rob Van Dam demonstrated in his answer).

Inserting a new entry:

Or perhaps you're looking for something like INSERT...MAX(logins)+1? Essentially you'd run a query much like the following - perhaps a bit more complex depending on your specific needs:

INSERT into mytable (logins) 
  SELECT max(logins) + 1 
  FROM mytable

Lost connection to MySQL server at 'reading initial communication packet', system error: 0

In my case it was the university wifi blocking port 3306. I was able to connect by using a mobile hotspot.

Change to a mobile hotspot or another network, and if it works there, then you know that original network is blocking port 3306. If you get the same error on more than 1 network, then you know it's specific to your machine.

What's the best way to calculate the size of a directory in .NET?

Multi thread example to calculate directory size from Microsoft Docs, which would be faster

using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      long totalSize = 0;

      String[] args = Environment.GetCommandLineArgs();
      if (args.Length == 1) {
         Console.WriteLine("There are no command line arguments.");
         return;
      }
      if (! Directory.Exists(args[1])) {
         Console.WriteLine("The directory does not exist.");
         return;
      }

      String[] files = Directory.GetFiles(args[1]);
      Parallel.For(0, files.Length,
                   index => { FileInfo fi = new FileInfo(files[index]);
                              long size = fi.Length;
                              Interlocked.Add(ref totalSize, size);
                   } );
      Console.WriteLine("Directory '{0}':", args[1]);
      Console.WriteLine("{0:N0} files, {1:N0} bytes", files.Length, totalSize);
   }
}
// The example displaysoutput like the following:
//       Directory 'c:\windows\':
//       32 files, 6,587,222 bytes

This example only calculate the files in current folder, so if you want to calculate all the files recursively, you can change the

String[] files = Directory.GetFiles(args[1]);

to

String[] files = Directory.GetFiles(args[1], "*", SearchOption.AllDirectories);

How to wrap text using CSS?

The better option if you cannot control user input, it is to establish the css property, overflow:hidden, so if the string is superior to the width, it will not deform the design.

Edited:

I like the answer: "word-wrap: break-word", and for those browsers that do not support it, for example, IE6 or IE7, I would use my solution.

How do you debug PHP scripts?

Manual debugging is generally quicker for me - var_dump() and debug_print_backtrace() are all the tools you need to arm your logic with.

Java ArrayList for integers

Actually what u did is also not wrong your declaration is right . With your declaration JVM will create a ArrayList of integer arrays i.e each entry in arraylist correspond to an integer array hence your add function should pass a integer array as a parameter.

For Ex:

list.add(new Integer[3]);

In this way first entry of ArrayList is an integer array which can hold at max 3 values.

Python match a string with regex

One Liner implementation:

a=[1,3]
b=[1,2,3,4]
all(i in b for i in a)

C# Telnet Library

Another one, it is an older project but shares the complete source code: http://telnetcsharp.codeplex.com/

Exception in thread "main" java.util.NoSuchElementException

simply don't close in

remove in.close() from your code.

Unit Testing C Code

other than my obvious bias

http://code.google.com/p/seatest/

is a nice simple way to unit test C code. mimics xUnit

Best Practice: Initialize JUnit class fields in setUp() or at declaration?

In addition to Alex B's answer.

It is even required to use the setUp method to instantiate resources in a certain state. Doing this in the constructor is not only a matter of timings, but because of the way JUnit runs the tests, each test state would be erased after running one.

JUnit first creates instances of the testClass for each test method and starts running the tests after each instance is created. Before running the test method, its setup method is ran, in which some state can be prepared.

If the database state would be created in the constructor, all instances would instantiate the db state right after each other, before running each tests. As of the second test, tests would run with a dirty state.

JUnits lifecycle:

  1. Create a different testclass instance for each test method
  2. Repeat for each testclass instance: call setup + call the testmethod

With some loggings in a test with two test methods you get: (number is the hashcode)

  • Creating new instance: 5718203
  • Creating new instance: 5947506
  • Setup: 5718203
  • TestOne: 5718203
  • Setup: 5947506
  • TestTwo: 5947506

How can I open a URL in Android's web browser from my application?

Kotlin

startActivity(Intent(Intent.ACTION_VIEW).apply {
            data = Uri.parse(your_link)
        })

RHEL 6 - how to install 'GLIBC_2.14' or 'GLIBC_2.15'?

For another instance of Glibc, download gcc 4.7.2, for instance from this github repo (although an official source would be better) and extract it to some folder, then update LD_LIBRARY_PATH with the path where you have extracted glib.

export LD_LIBRARY_PATH=$glibpath/glib-2.49.4-kgesagxmtbemim2denf65on4iixy3miy/lib:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=$glibpath/libffi-3.2.1-wk2luzhfdpbievnqqtu24pi774esyqye/lib64:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=$glibpath/pcre-8.39-itdbuzevbtzqeqrvna47wstwczud67wx/lib:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=$glibpath/gettext-0.19.8.1-aoweyaoufujdlobl7dphb2gdrhuhikil/lib:$LD_LIBRARY_PATH

This should keep you safe from bricking your CentOS*.

*Disclaimer: I just completed the thought it looks like the OP was trying to express, but I don't fully agree.

How do I find files with a path length greater than 260 characters in Windows?

you can redirect stderr.

more explanation here, but having a command like:

MyCommand >log.txt 2>errors.txt

should grab the data you are looking for.

Also, as a trick, Windows bypasses that limitation if the path is prefixed with \\?\ (msdn)

Another trick if you have a root or destination that starts with a long path, perhaps SUBST will help:

SUBST Q: "C:\Documents and Settings\MyLoginName\My Documents\MyStuffToBeCopied"
Xcopy Q:\ "d:\Where it needs to go" /s /e
SUBST Q: /D

if A vs if A is not None:

The former is more Pythonic (better ideomatic code), but will not execute the block if A is False (not None).

Correct way to push into state array

This Code work for me :

fetch('http://localhost:8080')
  .then(response => response.json())
  .then(json => {
  this.setState({mystate: this.state.mystate.push.apply(this.state.mystate, json)})
})

How does the FetchMode work in Spring Data JPA

I think that Spring Data ignores the FetchMode. I always use the @NamedEntityGraph and @EntityGraph annotations when working with Spring Data

@Entity
@NamedEntityGraph(name = "GroupInfo.detail",
  attributeNodes = @NamedAttributeNode("members"))
public class GroupInfo {

  // default fetch mode is lazy.
  @ManyToMany
  List<GroupMember> members = new ArrayList<GroupMember>();

  …
}

@Repository
public interface GroupRepository extends CrudRepository<GroupInfo, String> {

  @EntityGraph(value = "GroupInfo.detail", type = EntityGraphType.LOAD)
  GroupInfo getByGroupName(String name);

}

Check the documentation here

How/when to use ng-click to call a route?

just do it as follows in your html write:

<button ng-click="going()">goto</button>

And in your controller, add $state as follows:

.controller('homeCTRL', function($scope, **$state**) {

$scope.going = function(){

$state.go('your route');

}

})

How to center horizontal table-cell

Sometimes you have things other than text inside a table cell that you'd like to be horizontally centered. In order to do this, first set up some css...

<style>
    div.centered {
        margin: auto;
        width: 100%;
        display: flex;
        justify-content: center;
    }
</style>

Then declare a div with class="centered" inside each table cell you want centered.

<td>
    <div class="centered">
        Anything: text, controls, etc... will be horizontally centered.
    </div>
</td>

In excel how do I reference the current row but a specific column?

If you dont want to hard-code the cell addresses you can use the ROW() function.

eg: =AVERAGE(INDIRECT("A" & ROW()), INDIRECT("C" & ROW()))

Its probably not the best way to do it though! Using Auto-Fill and static columns like @JaiGovindani suggests would be much better.

How can I remove a commit on GitHub?

In case you like to keep the commit changes after deletion:

Note that this solution works if the commit to be removed is the last committed one.


1 - Copy the commit reference you like to go back to from the log:

git log

2 - Reset git to the commit reference:

 git reset <commit_ref>

3 - Stash/store the local changes from the wrong commit to use later after pushing to remote:

 git stash

4 - Push the changes to remote repository, (-f or --force):

git push -f

5 - Get back the stored changes to local repository:

git stash apply

7 - In case you have untracked/new files in the changes, you need to add them to git before committing:

git add .

6 - Add whatever extra changes you need, then commit the needed files, (or use a dot '.' instead of stating each file name, to commit all files in the local repository:

git commit -m "<new_commit_message>" <file1> <file2> ...

or

git commit -m "<new_commit_message>" .

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

Here's a pl/pgsql function that locates records where any column contains a specific value. It takes as arguments the value to search in text format, an array of table names to search into (defaults to all tables) and an array of schema names (defaults all schema names).

It returns a table structure with schema, name of table, name of column and pseudo-column ctid (non-durable physical location of the row in the table, see System Columns)

CREATE OR REPLACE FUNCTION search_columns(
    needle text,
    haystack_tables name[] default '{}',
    haystack_schema name[] default '{}'
)
RETURNS table(schemaname text, tablename text, columnname text, rowctid text)
AS $$
begin
  FOR schemaname,tablename,columnname IN
      SELECT c.table_schema,c.table_name,c.column_name
      FROM information_schema.columns c
        JOIN information_schema.tables t ON
          (t.table_name=c.table_name AND t.table_schema=c.table_schema)
        JOIN information_schema.table_privileges p ON
          (t.table_name=p.table_name AND t.table_schema=p.table_schema
              AND p.privilege_type='SELECT')
        JOIN information_schema.schemata s ON
          (s.schema_name=t.table_schema)
      WHERE (c.table_name=ANY(haystack_tables) OR haystack_tables='{}')
        AND (c.table_schema=ANY(haystack_schema) OR haystack_schema='{}')
        AND t.table_type='BASE TABLE'
  LOOP
    FOR rowctid IN
      EXECUTE format('SELECT ctid FROM %I.%I WHERE cast(%I as text)=%L',
       schemaname,
       tablename,
       columnname,
       needle
      )
    LOOP
      -- uncomment next line to get some progress report
      -- RAISE NOTICE 'hit in %.%', schemaname, tablename;
      RETURN NEXT;
    END LOOP;
 END LOOP;
END;
$$ language plpgsql;

See also the version on github based on the same principle but adding some speed and reporting improvements.

Examples of use in a test database:

  • Search in all tables within public schema:
select * from search_columns('foobar');
 schemaname | tablename | columnname | rowctid 
------------+-----------+------------+---------
 public     | s3        | usename    | (0,11)
 public     | s2        | relname    | (7,29)
 public     | w         | body       | (0,2)
(3 rows)
  • Search in a specific table:
 select * from search_columns('foobar','{w}');
 schemaname | tablename | columnname | rowctid 
------------+-----------+------------+---------
 public     | w         | body       | (0,2)
(1 row)
  • Search in a subset of tables obtained from a select:
select * from search_columns('foobar', array(select table_name::name from information_schema.tables where table_name like 's%'), array['public']);
 schemaname | tablename | columnname | rowctid 
------------+-----------+------------+---------
 public     | s2        | relname    | (7,29)
 public     | s3        | usename    | (0,11)
(2 rows)
  • Get a result row with the corresponding base table and and ctid:
select * from public.w where ctid='(0,2)';
 title |  body  |         tsv         
-------+--------+---------------------
 toto  | foobar | 'foobar':2 'toto':1

Variants

  • To test against a regular expression instead of strict equality, like grep, this part of the query:

    SELECT ctid FROM %I.%I WHERE cast(%I as text)=%L

    may be changed to:

    SELECT ctid FROM %I.%I WHERE cast(%I as text) ~ %L

  • For case insensitive comparisons, you could write:

    SELECT ctid FROM %I.%I WHERE lower(cast(%I as text)) = lower(%L)

"Retrieving the COM class factory for component.... error: 80070005 Access is denied." (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

If you are trying to configure this on 64bit, you have to do your DCOMconfig configuration (see other answers above) in:

C:\WINDOWS\SysWOW64>mmc comexp.msc /32

according to Setting Process-Wide Security Using DCOMCNFG.

After this, I was able to configure this for IIS_IUSRS without administrator privileges.

SQL: How do I SELECT only the rows with a unique value on certain column?

Modified!

SELECT distinct contract, activity from @t a
WHERE (SELECT COUNT(DISTINCT activity) FROM @t b WHERE b.contract = a.contract) = 1

And here's another one -- shorter/cleaner without subquery

select contract, max(activity) from @t
group by contract
having count(distinct activity) = 1

How to filter rows containing a string pattern from a Pandas dataframe

In [3]: df[df['ids'].str.contains("ball")]
Out[3]:
     ids  vals
0  aball     1
1  bball     2
3  fball     4

How to hide navigation bar permanently in android activity?

It's my solution:

First, define boolean that indicate if navigation bar is visible or not.

boolean navigationBarVisibility = true //because it's visible when activity is created

Second create method that hide navigation bar.

private void setNavigationBarVisibility(boolean visibility){
    if(visibility){
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN;
        decorView.setSystemUiVisibility(uiOptions);
        navigationBarVisibility = false;
    }

    else
        navigationBarVisibility = true;
}

By default, if you click to activity after hide navigation bar, navigation bar will be visible. So we got it's state if it visible we will hide it.

Now set OnClickListener to your view. I use a surfaceview so for me:

    playerSurface.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setNavigationBarVisibility(navigationBarVisibility);
        }
    });

Also, we must call this method when activity is launched. Because we want hide it at the beginning.

        setNavigationBarVisibility(navigationBarVisibility);

Install php-mcrypt on CentOS 6

For php 7 to install mcrypt run:

Centos: sudo yum install php7.0-mcrypt to install

On Ubuntu: sudo apt-get install php7.0-mcrypt

Returning value from called function in a shell script

If it's just a true/false test, have your function return 0 for success, and return 1 for failure. The test would then be:

if function_name; then
  do something
else
  error condition
fi

JavaScript Extending Class

Summary:

There are multiple ways which can solve the problem of extending a constructor function with a prototype in Javascript. Which of these methods is the 'best' solution is opinion based. However, here are two frequently used methods in order to extend a constructor's function prototype.

ES 2015 Classes:

_x000D_
_x000D_
class Monster {_x000D_
  constructor(health) {_x000D_
    this.health = health_x000D_
  }_x000D_
  _x000D_
  growl () {_x000D_
  console.log("Grr!");_x000D_
  }_x000D_
  _x000D_
}_x000D_
_x000D_
_x000D_
class Monkey extends Monster {_x000D_
  constructor (health) {_x000D_
    super(health) // call super to execute the constructor function of Monster _x000D_
    this.bananaCount = 5;_x000D_
  }_x000D_
}_x000D_
_x000D_
const monkey = new Monkey(50);_x000D_
_x000D_
console.log(typeof Monster);_x000D_
console.log(monkey);
_x000D_
_x000D_
_x000D_

The above approach of using ES 2015 classes is nothing more than syntactic sugar over the prototypal inheritance pattern in javascript. Here the first log where we evaluate typeof Monster we can observe that this is function. This is because classes are just constructor functions under the hood. Nonetheless you may like this way of implementing prototypal inheritance and definitively should learn it. It is used in major frameworks such as ReactJS and Angular2+.

Factory function using Object.create():

_x000D_
_x000D_
function makeMonkey (bananaCount) {_x000D_
  _x000D_
  // here we define the prototype_x000D_
  const Monster = {_x000D_
  health: 100,_x000D_
  growl: function() {_x000D_
  console.log("Grr!");}_x000D_
  }_x000D_
  _x000D_
  const monkey = Object.create(Monster);_x000D_
  monkey.bananaCount = bananaCount;_x000D_
_x000D_
  return monkey;_x000D_
}_x000D_
_x000D_
_x000D_
const chimp = makeMonkey(30);_x000D_
_x000D_
chimp.growl();_x000D_
console.log(chimp.bananaCount);
_x000D_
_x000D_
_x000D_

This method uses the Object.create() method which takes an object which will be the prototype of the newly created object it returns. Therefore we first create the prototype object in this function and then call Object.create() which returns an empty object with the __proto__ property set to the Monster object. After this we can initialize all the properties of the object, in this example we assign the bananacount to the newly created object.

How to open CSV file in R when R says "no such file or directory"?

Another way of reading Excel including the new format xlsx could be the package speedR (https://r-forge.r-project.org/projects/speedr/). It is an interactive and visual data importer. Besides importing you can filter(subset) the existing objects from the R workspace.

How to upload multiple files using PHP, jQuery and AJAX

My solution

  • Assuming that form id = "my_form_id"
  • It detects the form method and form action from HTML

jQuery code

$('#my_form_id').on('submit', function(e) {
    e.preventDefault();
    var formData = new FormData($(this)[0]);
    var msg_error = 'An error has occured. Please try again later.';
    var msg_timeout = 'The server is not responding';
    var message = '';
    var form = $('#my_form_id');
    $.ajax({
        data: formData,
        async: false,
        cache: false,
        processData: false,
        contentType: false,
        url: form.attr('action'),
        type: form.attr('method'),
        error: function(xhr, status, error) {
            if (status==="timeout") {
                alert(msg_timeout);
            } else {
                alert(msg_error);
            }
        },
        success: function(response) {
            alert(response);
        },
        timeout: 7000
    });
});

How to install a .ipa file into my iPhone?

You need to install the provisioning profile (drag and drop it into iTunes). Then drag and drop the .ipa. Ensure you device is set to sync apps, and try again.

height: calc(100%) not working correctly in CSS

If you are styling calc in a GWT project, its parser might not parse calc for you as it did not for me... the solution is to wrap it in a css literal like this:

height: literal("-moz-calc(100% - (20px + 30px))");
height: literal("-webkit-calc(100% - (20px + 30px))");
height: literal("calc(100% - (20px + 30px))");

Fastest way to get the first n elements of a List into an Array

It mostly depends on how big n is.

If n==0, nothing beats option#1 :)

If n is very large, toArray(new String[n]) is faster.

Handling the TAB character in Java

Yes the tab character is one character. You can match it in java with "\t".

"A referral was returned from the server" exception when accessing AD from C#

A referral is sent by an AD server when it doesn't have the information requested itself, but know that another server have the info. It usually appears in trust environment where a DC can refer to a DC in trusted domain.

In your case you are only specifying a domain, relying on automatic lookup of what domain controller to use. I think that you should try to find out what domain controller is used for the query and look if that one really holds the requested information.

If you provide more information on your AD setup, including any trusts/subdomains, global catalogues and the DNS resource records for the domain controllers it will be easier to help you.

How do you use $sce.trustAsHtml(string) to replicate ng-bind-html-unsafe in Angular 1.2+

Personally I sanitize all my data with some PHP libraries before going into the database so there's no need for another XSS filter for me.

From AngularJS 1.0.8

directives.directive('ngBindHtmlUnsafe', [function() {
    return function(scope, element, attr) {
        element.addClass('ng-binding').data('$binding', attr.ngBindHtmlUnsafe);
        scope.$watch(attr.ngBindHtmlUnsafe, function ngBindHtmlUnsafeWatchAction(value) {
            element.html(value || '');
        });
    }
}]);

To use:

<div ng-bind-html-unsafe="group.description"></div>

To disable $sce:

app.config(['$sceProvider', function($sceProvider) {
    $sceProvider.enabled(false);
}]);

What are the differences between Abstract Factory and Factory design patterns?

abstract factory design pattern with realtime example: what is an abstract factory design pattern? It is similar to the factory method design pattern. we need to use this pattern when we have multiple factories. there will be a grouping of factories defined in this pattern. factory method pattern is a subset of abstract factory design pattern. They have the same advantages as factory patterns. abstract factory relies on object composition whereas the factory method deals with inheritance. factory design pattern in java with a realtime example: what is the factory design pattern? it is mostly used design in object-oriented programming. It is one of the creational patterns. it is all about creating instances. Clients will create the object without exposed to object creational logic. it is widely used in different frameworks ex: the spring framework. we use this pattern when the class doesn’t know the objects of another it must create. Realtime example: when our car breaks down on the road. We need to inform the repairman about what type of vehicle we are using so that repairman will carry tools to fix the repair. as per our input, the repairman will fix the issue and make it ready for us to travel again. There are a few built-in methods that use these patterns. example getInstance() method in JavaUtilcalendar class. With help of getInstance(), we can get objects whenever we execute this method. Javautilcalendar : getInstance() is method return object. https://trendydevx.com/factory-design-pattern-in-java-with-realtime-example/

Newline in JLabel

Surround the string with <html></html> and break the lines with <br/>.

JLabel l = new JLabel("<html>Hello World!<br/>blahblahblah</html>", SwingConstants.CENTER);

JOIN two SELECT statement results

SELECT t1.ks, t1.[# Tasks], COALESCE(t2.[# Late], 0) AS [# Late]
FROM 
    (SELECT ks, COUNT(*) AS '# Tasks' FROM Table GROUP BY ks) t1
LEFT JOIN
    (SELECT ks, COUNT(*) AS '# Late' FROM Table WHERE Age > Palt GROUP BY ks) t2
ON (t1.ks = t2.ks);

Get my phone number in android

Method 1:

TelephonyManager tMgr = (TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();

With below permission

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

Method 2:

There is another way you will be able to get your phone number, I haven't tested this on multiple devices but above code is not working every time.

Try below code:

String main_data[] = {"data1", "is_primary", "data3", "data2", "data1", "is_primary", "photo_uri", "mimetype"};
Object object = getContentResolver().query(Uri.withAppendedPath(android.provider.ContactsContract.Profile.CONTENT_URI, "data"),
        main_data, "mimetype=?",
        new String[]{"vnd.android.cursor.item/phone_v2"},
        "is_primary DESC");
if (object != null) {
    do {
        if (!((Cursor) (object)).moveToNext())
            break;
        String s1 = ((Cursor) (object)).getString(4);
    } while (true);
    ((Cursor) (object)).close();
}

You will need to add these two permissions.

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

Hope this helps, Thanks!

Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?

I found this question serval years ago.

recently I tried to "rewrite" the submit method. below is my code

window.onload= function (){
for(var i= 0;i<document.forms.length;i++){
    (function (p){
        var form= document.forms[i];
        var originFn= form.submit;
        form.submit=function (){
            //do something you like
            alert("submitting "+form.id+" using submit method !");
            originFn();
        }
        form.onsubmit= function (){
            alert("submitting "+form.id+" with onsubmit event !");
        }
    })(i);


}

}

<form method="get" action="" id="form1">
<input type="submit" value="??form1" />
<input type="button" name="" id="" value="button????1" onclick="document.forms[0].submit();" /></form>

It did in IE,but failed in other browsers for the same reason as "cletus"

Writing MemoryStream to Response Object

The problem for me was that my stream was not set to the origin before download.

Response.Clear();
Response.ContentType = "Application/msword";
Response.AddHeader("Content-Disposition", "attachment; filename=myfile.docx");

//ADDED THIS LINE
myMemoryStream.Seek(0,SeekOrigin.Begin);

myMemoryStream.WriteTo(Response.OutputStream); 
Response.Flush();
Response.Close();

How to disable margin-collapsing?

overflow:hidden prevents collapsing margins but it's not free of side effects - namely it... hides overflow.

Apart form this and what you've mentioned you just have to learn live with it and learn for this day when they are actually useful (comes every 3 to 5 years).

css with background image without repeating the image

body {
    background: url(images/image_name.jpg) no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

Here is a good solution to get your image to cover the full area of the web app perfectly

sorting and paging with gridview asp.net

<asp:GridView 
    ID="GridView1" runat="server" AutoGenerateColumns="false" AllowSorting="True" onsorting="GridView1_Sorting" EnableViewState="true"> 
    <Columns>
        <asp:BoundField DataField="bookid" HeaderText="BOOK ID"SortExpression="bookid"  />
        <asp:BoundField DataField="bookname" HeaderText="BOOK NAME" />
        <asp:BoundField DataField="writer" HeaderText="WRITER" />
        <asp:BoundField DataField="totalbook" HeaderText="TOTALBOOK" SortExpression="totalbook"  />
        <asp:BoundField DataField="availablebook" HeaderText="AVAILABLE BOOK" />
    </Columns>
</asp:GridView>

Code behind:

protected void Page_Load(object sender, EventArgs e) {
        if (!IsPostBack) {
            string query = "SELECT * FROM book";
            DataTable DT = new DataTable();
            SqlDataAdapter DA = new SqlDataAdapter(query, sqlCon);
            DA.Fill(DT);

            GridView1.DataSource = DT;
            GridView1.DataBind();
        }
    }

    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) {

        string query = "SELECT * FROM book";
        DataTable DT = new DataTable();
        SqlDataAdapter DA = new SqlDataAdapter(query, sqlCon);
        DA.Fill(DT);

        GridView1.DataSource = DT;
        GridView1.DataBind();

        if (DT != null) {
            DataView dataView = new DataView(DT);
            dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);

            GridView1.DataSource = dataView;
            GridView1.DataBind();
        }
    }

    private string GridViewSortDirection {
        get { return ViewState["SortDirection"] as string ?? "DESC"; }
        set { ViewState["SortDirection"] = value; }
    }

    private string ConvertSortDirectionToSql(SortDirection sortDirection) {
        switch (GridViewSortDirection) {
            case "ASC":
                GridViewSortDirection = "DESC";
                break;

            case "DESC":
                GridViewSortDirection = "ASC";
                break;
        }

        return GridViewSortDirection;
    }
}

How to save a list as numpy array in python?

import numpy as np 

... ## other code

some list comprehension

t=[nodel[ nodenext[i][j] ] for j in idx]
            #for each link, find the node lables 
            #t is the list of node labels 

Convert the list to a numpy array using the array method specified in the numpy library.

t=np.array(t)

This may be helpful: https://numpy.org/devdocs/user/basics.creation.html

How to change 1 char in the string?

I usually approach it like this:

   char[] c = text.ToCharArray();
   for (i=0; i<c.Length; i++)
   {
    if (c[i]>'9' || c[i]<'0') // use any rules of your choice
    {
     c[i]=' '; // put in any character you like
    }
   }
   // the new string can have the same name, or a new variable       
   String text=new string(c); 

How do I get the row count of a Pandas DataFrame?

Either of this can do it (df is the name of the DataFrame):

Method 1: Using the len function:

len(df) will give the number of rows in a DataFrame named df.

Method 2: using count function:

df[col].count() will count the number of rows in a given column col.

df.count() will give the number of rows for all the columns.

How are SSL certificate server names resolved/Can I add alternative names using keytool?

How host name verification should be done is defined in RFC 6125, which is quite recent and generalises the practice to all protocols, and replaces RFC 2818, which was specific to HTTPS. (I'm not even sure Java 7 uses RFC 6125, which might be too recent for this.)

From RFC 2818 (Section 3.1):

If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.

[...]

In some cases, the URI is specified as an IP address rather than a hostname. In this case, the iPAddress subjectAltName must be present in the certificate and must exactly match the IP in the URI.

Essentially, the specific problem you have comes from the fact that you're using IP addresses in your CN and not a host name. Some browsers might work because not all tools follow this specification strictly, in particular because "most specific" in RFC 2818 isn't clearly defined (see discussions in RFC 6215).

If you're using keytool, as of Java 7, keytool has an option to include a Subject Alternative Name (see the table in the documentation for -ext): you could use -ext san=dns:www.example.com or -ext san=ip:10.0.0.1.

EDIT:

You can request a SAN in OpenSSL by changing openssl.cnf (it will pick the copy in the current directory if you don't want to edit the global configuration, as far as I remember, or you can choose an explicit location using the OPENSSL_CONF environment variable).

Set the following options (find the appropriate sections within brackets first):

[req]
req_extensions = v3_req

[ v3_req ]
subjectAltName=IP:10.0.0.1
# or subjectAltName=DNS:www.example.com

There's also a nice trick to use an environment variable for this (rather in than fixing it in a configuration file) here: http://www.crsr.net/Notes/SSL.html

How to increase application heap size in Eclipse?

Open eclipse.ini

Search for -Xmx512m or maybe more size it is.

Just change it to a required size such as I changed it to -Xmx1024m

Which is faster: Stack allocation or Heap allocation

It has been mentioned before that stack allocation is simply moving the stack pointer, that is, a single instruction on most architectures. Compare that to what generally happens in the case of heap allocation.

The operating system maintains portions of free memory as a linked list with the payload data consisting of the pointer to the starting address of the free portion and the size of the free portion. To allocate X bytes of memory, the link list is traversed and each note is visited in sequence, checking to see if its size is at least X. When a portion with size P >= X is found, P is split into two parts with sizes X and P-X. The linked list is updated and the pointer to the first part is returned.

As you can see, heap allocation depends on may factors like how much memory you are requesting, how fragmented the memory is and so on.

Change :hover CSS properties with JavaScript

If it fits your purpose you can add the hover functionality without using css and using the onmouseover event in javascript

Here is a code snippet

<div id="mydiv">foo</div>

<script>
document.getElementById("mydiv").onmouseover = function() 
{
    this.style.backgroundColor = "blue";
}
</script>

Where should I put the log4j.properties file?

I don't know this is correct way.But it solved my problem. put log4j.properties file in "project folder"/config and use PropertyConfigurator.configure("config//log4j.properties");

it will works with IDE but not when run the jar file yourself. when you run the jar file by yourself just copy the log4j.properties file in to the folder that jar file is in.when the jar and property file in same directory it runs well.

Why is my JQuery selector returning a n.fn.init[0], and what is it?

Another approach(Inside of $function to asure that the each is executed on document ready):

var ids = [1,2];
$(function(){
  $('.checkbox-wrapper>input[type="checkbox"]').each(function(i,item){
    if(ids.indexOf($(item).data('id')) > -1){
       $(item).prop("checked", "checked");
    }
  });
});

Working fiddle: https://jsfiddle.net/robertrozas/w5uda72v/

What is the n.fn.init[0], and why it is returned? Why are my two seemingly identical JQuery functions returning different things?

Answer: It seems that your elements are not in the DOM yet, when you are trying to find them. As @Rory McCrossan pointed out, the length:0 means that it doesn't find any element based on your search criteria.

About n.fn.init[0], lets look at the core of the Jquery Library:

var jQuery = function( selector, context ) {
   return new jQuery.fn.init( selector, context );
};

Looks familiar, right?, now in a minified version of jquery, this should looks like:

var n = function( selector, context ) {
   return new n.fn.init( selector, context );
};

So when you use a selector you are creating an instance of the jquery function; when found an element based on the selector criteria it returns the matched elements; when the criteria does not match anything it returns the prototype object of the function.

How to get the current loop index when using Iterator?

I had the same question and found using a ListIterator worked. Similar to the test above:

List<String> list = Arrays.asList("zero", "one", "two");

ListIterator iter = list.listIterator();
    
while (iter.hasNext()) {
    System.out.println("index: " + iter.nextIndex() + " value: " + iter.next());
}

Make sure you call the nextIndex() before you actually get the next().

Open firewall port on CentOS 7

Firewalld is a bit non-intuitive for the iptables veteran. For those who prefer an iptables-driven firewall with iptables-like syntax in an easy configurable tree, try replacing firewalld with fwtree: https://www.linuxglobal.com/fwtree-flexible-linux-tree-based-firewall/ and then do the following:

 echo '-p tcp --dport 80 -m conntrack --cstate NEW -j ACCEPT' > /etc/fwtree.d/filter/INPUT/80-allow.rule
 systemctl reload fwtree 

How to set a single, main title above all the subplots with Pyplot?

Use pyplot.suptitle or Figure.suptitle:

import matplotlib.pyplot as plt
import numpy as np

fig=plt.figure()
data=np.arange(900).reshape((30,30))
for i in range(1,5):
    ax=fig.add_subplot(2,2,i)        
    ax.imshow(data)

fig.suptitle('Main title') # or plt.suptitle('Main title')
plt.show()

enter image description here

Using reflection in Java to create a new instance with the reference variable type set to the new instance class name?

This line seems to sum up the crux of your problem:

The issue with this is that now you can't call any new methods (only overrides) on the implementing class, as your object reference variable has the interface type.

You are pretty stuck in your current implementation, as not only do you have to attempt a cast, you also need the definition of the method(s) that you want to call on this subclass. I see two options:

1. As stated elsewhere, you cannot use the String representation of the Class name to cast your reflected instance to a known type. You can, however, use a String equals() test to determine whether your class is of the type that you want, and then perform a hard-coded cast:

try {
   String className = "com.path.to.ImplementationType";// really passed in from config
   Class c = Class.forName(className);
   InterfaceType interfaceType = (InterfaceType)c.newInstance();
   if (className.equals("com.path.to.ImplementationType") {
      ((ImplementationType)interfaceType).doSomethingOnlyICanDo();
   } 
} catch (Exception e) {
   e.printStackTrace();
}

This looks pretty ugly, and it ruins the nice config-driven process that you have. I dont suggest you do this, it is just an example.

2. Another option you have is to extend your reflection from just Class/Object creation to include Method reflection. If you can create the Class from a String passed in from a config file, you can also pass in a method name from that config file and, via reflection, get an instance of the Method itself from your Class object. You can then call invoke(http://java.sun.com/javase/6/docs/api/java/lang/reflect/Method.html#invoke(java.lang.Object, java.lang.Object...)) on the Method, passing in the instance of your class that you created. I think this will help you get what you are after.

Here is some code to serve as an example. Note that I have taken the liberty of hard coding the params for the methods. You could specify them in a config as well, and would need to reflect on their class names to define their Class obejcts and instances.

public class Foo {

    public void printAMessage() {
    System.out.println(toString()+":a message");
    }
    public void printAnotherMessage(String theString) {
        System.out.println(toString()+":another message:" + theString);
    }

    public static void main(String[] args) {
        Class c = null;
        try {
            c = Class.forName("Foo");
            Method method1 = c.getDeclaredMethod("printAMessage", new Class[]{});
            Method method2 = c.getDeclaredMethod("printAnotherMessage", new Class[]{String.class});
            Object o = c.newInstance();
            System.out.println("this is my instance:" + o.toString());
            method1.invoke(o);
            method2.invoke(o, "this is my message, from a config file, of course");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException nsme){
            nsme.printStackTrace();
        } catch (IllegalAccessException iae) {
            iae.printStackTrace();
        } catch (InstantiationException ie) {
            ie.printStackTrace();
        } catch (InvocationTargetException ite) {
            ite.printStackTrace();
        }
    }
}

and my output:

this is my instance:Foo@e0cf70
Foo@e0cf70:a message
Foo@e0cf70:another message:this is my message, from a config file, of course

#1130 - Host ‘localhost’ is not allowed to connect to this MySQL server

Use this in your my.ini under

[mysqldump]
    user=root
    password=anything

"Object doesn't support property or method 'find'" in IE

Here is a work around. You can use filter instead of find; but filter returns an array of matching objects. find only returns the first match inside an array. So, why not use filter as following;

data.filter(function (x) {
         return x.Id === e
    })[0];

Android new Bottom Navigation bar or BottomNavigationView

There is a new official BottomNavigationView in version 25 of the Design Support Library

https://developer.android.com/reference/android/support/design/widget/BottomNavigationView.html add in gradle compile 'com.android.support:design:25.0.0'

XML

<android.support.design.widget.BottomNavigationView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:design="http://schema.android.com/apk/res/android.support.design"
    android:id="@+id/navigation"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    design:menu="@menu/my_navigation_items" />

How to hide collapsible Bootstrap 4 navbar on click

I am using Angular 5 with Boostrap 4. It works for me in this way.

_x000D_
_x000D_
 $(document).on('click', '.navbar-nav>li>a, .navbar-brand, .dropdown-menu>a', function (e) {_x000D_
      if ( $(e.target).is('a') && $(e.target).attr('class') != 'nav-link dropdown-toggle' ) {_x000D_
        $('.navbar-collapse').collapse('hide');_x000D_
      }_x000D_
    });_x000D_
   }
_x000D_
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">_x000D_
  <a class="navbar-brand" [routerLink]="['/home']">FbShareTool</a>_x000D_
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor01" aria-controls="navbarColor01" aria-expanded="false" aria-label="Toggle navigation" style="">_x000D_
    <span class="navbar-toggler-icon"></span>_x000D_
  </button>_x000D_
_x000D_
  <div class="collapse navbar-collapse" id="navbarColor01">_x000D_
    <ul class="navbar-nav mr-auto">_x000D_
      <li class="nav-item active" *ngIf="_myAuthService.isAuthenticated()">_x000D_
        <a class="nav-link" [routerLink]="['/dashboard']">Dashboard <span class="sr-only">(current)</span></a>_x000D_
      </li>_x000D_
      <li class="nav-item dropdown" *ngIf="_myAuthService.isAuthenticated()">_x000D_
          <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">_x000D_
            Manage_x000D_
          </a>_x000D_
          <div class="dropdown-menu" aria-labelledby="navbarDropdown">_x000D_
            <a class="dropdown-item" [routerLink]="['/fbgroup']">Facebook Group</a>_x000D_
            <div class="dropdown-divider"></div>_x000D_
            <a class="dropdown-item" href="#">Fetch Data</a>_x000D_
          </div>_x000D_
      </li>_x000D_
    </ul>_x000D_
_x000D_
    <ul class="navbar-nav navbar-right navbar-right-link">_x000D_
        <li class="nav-item" *ngIf="!_myAuthService.isAuthenticated()" >_x000D_
            <a class="nav-link" (click)="logIn()">Login</a>_x000D_
        </li>_x000D_
        <li class="nav-item" *ngIf="_myAuthService.isAuthenticated()">_x000D_
           <a class="nav-link">{{ _myAuthService.userDetails.displayName }}</a>_x000D_
        </li>_x000D_
        <li class="nav-item" *ngIf="_myAuthService.isAuthenticated() && _myAuthService.userDetails.photoURL">_x000D_
            <a>_x000D_
              <img [src]="_myAuthService.userDetails.photoURL" alt="profile-photo" class="img-fluid rounded" width="40px;">_x000D_
            </a>_x000D_
        </li>_x000D_
        <li class="nav-item" *ngIf="_myAuthService.isAuthenticated()">_x000D_
            <a class="nav-link" (click)="logOut()">Logout</a>_x000D_
        </li>_x000D_
    </ul>_x000D_
_x000D_
  </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

What is the 'open' keyword in Swift?

Read open as

open for inheritance in other modules

I repeat open for inheritance in other modules. So an open class is open for subclassing in other modules that include the defining module. Open vars and functions are open for overriding in other modules. Its the least restrictive access level. It is as good as public access except that something that is public is closed for inheritance in other modules.

From Apple Docs:

Open access applies only to classes and class members, and it differs from public access as follows:

  1. Classes with public access, or any more restrictive access level, can be subclassed only within the module where they’re defined.

  2. Class members with public access, or any more restrictive access level, can be overridden by subclasses only within the module where they’re defined.

  3. Open classes can be subclassed within the module where they’re defined, and within any module that imports the module where they’re defined.

  4. Open class members can be overridden by subclasses within the module where they’re defined, and within any module that imports the module where they’re defined.

Removing html5 required attribute with jQuery

Using Javascript:

document.querySelector('#edit-submitted-first-name').required = false;

Using jQuery:

$('#edit-submitted-first-name').removeAttr('required');

Integrating Dropzone.js into existing HTML form with other fields

You can modify the formData by catching the 'sending' event from your dropzone.

dropZone.on('sending', function(data, xhr, formData){
        formData.append('fieldname', 'value');
});

Regular expression search replace in Sublime Text 2

Important: Use the ( ) parentheses in your search string

While the previous answer is correct there is an important thing to emphasize! All the matched segments in your search string that you want to use in your replacement string must be enclosed by ( ) parentheses, otherwise these matched segments won't be accessible to defined variables such as $1, $2 or \1, \2 etc.

For example we want to replace 'em' with 'px' but preserve the digit values:

    margin: 10em;  /* Expected: margin: 10px */
    margin: 2em;   /* Expected: margin: 2px */
  • Replacement string: margin: $1px or margin: \1px
  • Search string (CORRECT): margin: ([0-9]*)em // with parentheses
  • Search string (INCORRECT): margin: [0-9]*em

CORRECT CASE EXAMPLE: Using margin: ([0-9]*)em search string (with parentheses). Enclose the desired matched segment (e.g. $1 or \1) by ( ) parentheses as following:

  • Find: margin: ([0-9]*)em (with parentheses)
  • Replace to: margin: $1px or margin: \1px
  • Result:
    margin: 10px;
    margin: 2px;

INCORRECT CASE EXAMPLE: Using margin: [0-9]*em search string (without parentheses). The following regex pattern will match the desired lines but matched segments will not be available in replaced string as variables such as $1 or \1:

  • Find: margin: [0-9]*em (without parentheses)
  • Replace to: margin: $1px or margin: \1px
  • Result:
    margin: px; /* `$1` is undefined */
    margin: px; /* `$1` is undefined */

How to use zIndex in react-native

Use elevation instead of zIndex for android devices

elevatedElement: {
  zIndex: 3, // works on ios
  elevation: 3, // works on android
}

This worked fine for me!

How to detect when facebook's FB.init is complete

The Facebook API watches for the FB._apiKey so you can watch for this before calling your own application of the API with something like:

window.fbAsyncInit = function() {
  FB.init({
    //...your init object
  });
  function myUseOfFB(){
    //...your FB API calls
  };
  function FBreadyState(){
    if(FB._apiKey) return myUseOfFB();
    setTimeout(FBreadyState, 100); // adjust time as-desired
  };
  FBreadyState();
}; 

Not sure this makes a difference but in my case--because I wanted to be sure the UI was ready--I've wrapped the initialization with jQuery's document ready (last bit above):

  $(document).ready(FBreadyState);

Note too that I'm NOT using async = true to load Facebook's all.js, which in my case seems to be helping with signing into the UI and driving features more reliably.

MySQL convert date string to Unix timestamp

From http://www.epochconverter.com/

SELECT DATEDIFF(s, '1970-01-01 00:00:00', GETUTCDATE())

My bad, SELECT unix_timestamp(time) Time format: YYYY-MM-DD HH:MM:SS or YYMMDD or YYYYMMDD. More on using timestamps with MySQL:

http://www.epochconverter.com/programming/mysql-from-unixtime.php

How to replace comma with a dot in the number (or any replacement)

This will need new var ttfixed

Then this under the tt value slot and replace all pointers down below that are tt to ttfixed

ttfixed = (tt.replace(",", "."));

Origin <origin> is not allowed by Access-Control-Allow-Origin

I finally got the answer for apache Tomcat8

You have to edit the tomcat web.xml file.

probabily it will be inside webapps folder,

sudo gedit /opt/tomcat/webapps/your_directory/WEB-INF/web.xml

find it and edit it

<web-app>


<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
  <init-param>
    <param-name>cors.allowed.origins</param-name>
    <param-value>*</param-value>
  </init-param>
  <init-param>
    <param-name>cors.allowed.methods</param-name>
    <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
  </init-param>
  <init-param>
    <param-name>cors.allowed.headers</param-name>
    <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
  </init-param>
  <init-param>
    <param-name>cors.exposed.headers</param-name>
    <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
  </init-param>
  <init-param>
    <param-name>cors.support.credentials</param-name>
    <param-value>true</param-value>
  </init-param>
  <init-param>
    <param-name>cors.preflight.maxage</param-name>
    <param-value>10</param-value>
  </init-param>
</filter>


<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>



</web-app>

This will allow Access-Control-Allow-Origin all hosts. If you need to change it from all hosts to only your host you can edit the

<param-name>cors.allowed.origins</param-name>
<param-value>http://localhost:3000</param-value>

above code from * to your http://your_public_IP or http://www.example.com

you can refer here Tomcat filter documentation

Thanks

How can labels/legends be added for all chart types in chart.js (chartjs.org)?

  1. The legend is part of the default options of the ChartJs library. So you do not need to explicitly add it as an option.

  2. The library generates the HTML. It is merely a matter of adding that to the your page. For example, add it to the innerHTML of a given DIV. (Edit the default options if you are editing the colors, etc)


<div>
    <canvas id="chartDiv" height="400" width="600"></canvas>
    <div id="legendDiv"></div>
</div>

<script>
   var data = {
        labels: ["January", "February", "March", "April", "May", "June", "July"],
        datasets: [
            {
                label: "The Flash's Speed",
                fillColor: "rgba(220,220,220,0.2)",
                strokeColor: "rgba(220,220,220,1)",
                pointColor: "rgba(220,220,220,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(220,220,220,1)",
                data: [65, 59, 80, 81, 56, 55, 40]
            },
            {
                label: "Superman's Speed",
                fillColor: "rgba(151,187,205,0.2)",
                strokeColor: "rgba(151,187,205,1)",
                pointColor: "rgba(151,187,205,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(151,187,205,1)",
                data: [28, 48, 40, 19, 86, 27, 90]
            }
        ]
    };

    var myLineChart = new Chart(document.getElementById("chartDiv").getContext("2d")).Line(data);
    document.getElementById("legendDiv").innerHTML = myLineChart.generateLegend();
</script>

How to install JSON.NET using NuGet?

You can do this a couple of ways.

Via the "Solution Explorer"

  1. Simply right-click the "References" folder and select "Manage NuGet Packages..."
  2. Once that window comes up click on the option labeled "Online" in the left most part of the dialog.
  3. Then in the search bar in the upper right type "json.net"
  4. Click "Install" and you're done.

Via the "Package Manager Console"

  1. Open the console. "View" > "Other Windows" > "Package Manager Console"
  2. Then type the following:
    Install-Package Newtonsoft.Json

For more info on how to use the "Package Manager Console" check out the nuget docs.

Transpose list of lists

One way to do it is with NumPy transpose. For a list, a:

>>> import numpy as np
>>> np.array(a).T.tolist()
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Or another one without zip:

>>> map(list,map(None,*a))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Calculating sum of repeated elements in AngularJS ng-repeat

After reading all the answers here - how to summarize grouped information, i decided to skip it all and just loaded one of the SQL javascript libraries. I'm using alasql, yeah it takes a few secs longer on load time but saves countless time in coding and debugging, Now to group and sum() I just use,

$scope.bySchool = alasql('SELECT School, SUM(Cost) AS Cost from ? GROUP BY School',[restResults]);

I know this sounds like a bit of a rant on angular/js but really SQL solved this 30+ years ago and we shouldn't have to re-invent it within a browser.

SVN how to resolve new tree conflicts when file is added on two branches

As was mentioned in an older version (2009) of the "Tree Conflict" design document:

XFAIL conflict from merge of add over versioned file

This test does a merge which brings a file addition without history onto an existing versioned file.
This should be a tree conflict on the file of the 'local obstruction, incoming add upon merge' variety. Fixed expectations in r35341.

(This is also called "evil twins" in ClearCase by the way):
a file is created twice (here "added" twice) in two different branches, creating two different histories for two different elements, but with the same name.

The theoretical solution is to manually merge those files (with an external diff tool) in the destination branch 'B2'.

If you still are working on the source branch, the ideal scenario would be to remove that file from the source branch B1, merge back from B2 to B1 in order to make that file visible on B1 (you will then work on the same element).
If a merge back is not possible because merges only occurs from B1 to B2, then a manual merge will be necessary for each B1->B2 merges.

what does Error "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" mean?

Mine was about

dispatch_group_leave(group)

was inside if closure in block. I just moved it out of closure.

Set the table column width constant regardless of the amount of text in its cells?

KAsun has the right idea. Here is the correct code...

<style type="text/css">
  th.first-col > div, 
  td.first-col > div {
    overflow:hidden;
    white-space:nowrap;
    width:100px
  }
</style>

<table>
  <thead><tr><th class="first-col"><div>really long header</div></th></tr></thead>
  <tbody><tr><td class="first-col"><div>really long text</div></td></tr></tbody>
</table>

How to split a string with angularJS

You can try something like this:

$scope.test = "test1,test2";
{{test.split(',')[0]}}

now you will get "test1" while you try {{test.split(',')[0]}}

and you will get "test2" while you try {{test.split(',')[1]}}

here is my plnkr:

http://plnkr.co/edit/jaXOrZX9UO9kmdRMImdN?p=preview

How to export SQL Server database to MySQL?

As mentioned above, if your data contains tab characters, commas, or newlines in your data then it's going to be very hard to export and import it with CSV. Values will overflow out of the fields and you will get errors. This problem is even worse if any of your long fields contain multi-line text with newline characters in them.

My method in these cases is to use the BCP command-line utility to export the data from SQL server, then use LOAD DATA INFILE .. INTO TABLE command in MySQL to read the data file back in. BCP is one of the oldest SQL Server command line utilities (dating back to the birth of SQL server - v6.5) but it is still around and still one of the easiest and most reliable ways to get data out.

To use this technique you need to create each destination table with the same or equivalent schema in MySQL. I do that by right clicking the Database in SQL enterprise manager, then Tasks->Generate Scripts... and create a SQL script for all the tables. You must then convert the script to MySQL compatible SQL by hand (definitely the worst part of the job) and finally run the CREATE TABLE commands on the MySQL database so you have matching tables to the SQL server versions column-wise, empty and ready for data.

Then, export the data from the MS-SQL side as follows.

bcp DatabaseName..TableName out TableName.dat -q -c -T -S ServerName -r \0 -t !\t!

(If you're using SQL Server Express, use a -S value like so: -S "ComputerName\SQLExpress")

That will create a file named TableName.dat, with fields delimited by ![tab]! and rows delimited by \0 NUL characters.

Now copy the .dat files into /tmp on the MySQL server and load on the MySQL side like so:

LOAD DATA INFILE '/tmp/TableName.dat' INTO TABLE TableName FIELDS TERMINATED BY '!\t!' LINES TERMINATED BY '\0';

Don't forget that the tables (TableName in this example) must be created already on the MySQL side.

This procedure is painfully manual when it comes to converting the SQL schema over, however it works for even the most difficult of data and because it uses flat files you never need to persuade SQL Server to talk to MySQL, or vice versa.

docker command not found even though installed with apt-get

The Ubuntu package docker actually refers to a GUI application, not the beloved DevOps tool we've come out to look for.

The instructions for docker can be followed per instructions on the docker page here: https://docs.docker.com/engine/install/ubuntu/

=== UPDATED (thanks @Scott Stensland) ===

You now run the following install script to get docker:

`sudo curl -sSL https://get.docker.com/ | sh`
  • Note: review the script on the website and make sure you have the right link before continuing since you are running this as sudo.

This will run a script that installs docker. Note the last part of the script:

If you would like to use Docker as a non-root user, you should now consider
adding your user to the "docker" group with something like:

  `sudo usermod -aG docker stens`

Remember that you will have to log out and back in for this to take effect!

To update Docker run:

`sudo apt-get update && sudo apt-get upgrade`

For more details on what's going on, See the docker install documentation or @Scott Stensland's answer below

.

=== UPDATE: For those uncomfortable w/ sudo | sh ===

Some in the comments have mentioned that it a risk to run an arbitrary script as sudo. The above option is a convenience script from docker to make the task simple. However, for those that are security-focused but don't want to read the script you can do the following:

  1. Add Dependencies
sudo apt-get update; \
sudo apt-get install \
 apt-transport-https \
 ca-certificates \
 curl \
 gnupg-agent \
 software-properties-common
  1. Add docker gpg key

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

(Security check, verify key fingerprint 9DC8 5822 9FC7 DD38 854A E2D8 8D81 803C 0EBF CD88

$ sudo apt-key fingerprint 0EBFCD88

pub   rsa4096 2017-02-22 [SCEA]
      9DC8 5822 9FC7 DD38 854A  E2D8 8D81 803C 0EBF CD88
uid           [ unknown] Docker Release (CE deb) <[email protected]>
sub   rsa4096 2017-02-22 [S]

)

  1. Setup Repository
sudo add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"
  1. Install Docker
sudo apt-get update; \
sudo apt-get install docker-ce docker-ce-cli containerd.io

If you want to verify that it worked run: sudo docker run hello-world


The following explains why it is named like this: Why install docker on ubuntu should be `sudo apt-get install docker.io`?

How do I change button size in Python?

Configuring a button (or any widget) in Tkinter is done by calling a configure method "config"

To change the size of a button called button1 you simple call

button1.config( height = WHATEVER, width = WHATEVER2 )

If you know what size you want at initialization these options can be added to the constructor.

button1 = Button(self, text = "Send", command = self.response1, height = 100, width = 100) 

Pretty printing XML in Python

I found this question while looking for "how to pretty print html"

Using some of the ideas in this thread I adapted the XML solutions to work for XML or HTML:

from xml.dom.minidom import parseString as string_to_dom

def prettify(string, html=True):
    dom = string_to_dom(string)
    ugly = dom.toprettyxml(indent="  ")
    split = list(filter(lambda x: len(x.strip()), ugly.split('\n')))
    if html:
        split = split[1:]
    pretty = '\n'.join(split)
    return pretty

def pretty_print(html):
    print(prettify(html))

When used this is what it looks like:

html = """\
<div class="foo" id="bar"><p>'IDK!'</p><br/><div class='baz'><div>
<span>Hi</span></div></div><p id='blarg'>Try for 2</p>
<div class='baz'>Oh No!</div></div>
"""

pretty_print(html)

Which returns:

<div class="foo" id="bar">
  <p>'IDK!'</p>
  <br/>
  <div class="baz">
    <div>
      <span>Hi</span>
    </div>
  </div>
  <p id="blarg">Try for 2</p>
  <div class="baz">Oh No!</div>
</div>

Set the maximum character length of a UITextField in Swift

Simply just check with the number of characters in the string

  1. Add a delegate to view controller ans asign delegate
    class YorsClassName : UITextFieldDelegate {

    }
  1. check the number of chars allowed for textfield
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField.text?.count == 1 {
        return false
    }
    return true
}

Note: Here I checked for only char allowed in textField

Can I use tcpdump to get HTTP requests, response header and response body?

I would recommend using Wireshark, which has a "Follow TCP Stream" option that makes it very easy to see the full requests and responses for a particular TCP connection. If you would prefer to use the command line, you can try tcpflow, a tool dedicated to capturing and reconstructing the contents of TCP streams.

Other options would be using an HTTP debugging proxy, like Charles or Fiddler as EricLaw suggests. These have the advantage of having specific support for HTTP to make it easier to deal with various sorts of encodings, and other features like saving requests to replay them or editing requests.

You could also use a tool like Firebug (Firefox), Web Inspector (Safari, Chrome, and other WebKit-based browsers), or Opera Dragonfly, all of which provide some ability to view the request and response headers and bodies (though most of them don't allow you to see the exact byte stream, but instead how the browsers parsed the requests).

And finally, you can always construct requests by hand, using something like telnet, netcat, or socat to connect to port 80 and type the request in manually, or a tool like htty to help easily construct a request and inspect the response.

How to compile or convert sass / scss to css with node-sass (no Ruby)?

The installation of these tools may vary on different OS.

Under Windows, node-sass currently supports VS2015 by default, if you only have VS2013 in your box and meet any error while running the command, you can define the version of VS by adding: --msvs_version=2013. This is noted on the node-sass npm page.

So, the safe command line that works on Windows with VS2013 is: npm install --msvs_version=2013 gulp node-sass gulp-sass

prevent refresh of page when button inside form clicked

I was facing the same problem. The problem is with the onclick function. There should not be any problem with the function getData. It worked by making the onclick function return false.

<form method="POST">
    <button name="data" onclick="getData(); return false">Click</button>
</form>

src absolute path problem

You should be referencing it as localhost. Like this:

<img src="http:\\localhost\site\img\mypicture.jpg"/>

Why can't variables be declared in a switch statement?

This question is was originally tagged as [C] and [C++] at the same time. The original code is indeed invalid in both C and C++, but for completely different unrelated reasons.

  • In C++ this code is invalid because the case ANOTHER_VAL: label jumps into the scope of variable newVal bypassing its initialization. Jumps that bypass initialization of automatic objects are illegal in C++. This side of the issue is correctly addressed by most answers.

  • However, in C language bypassing variable initialization is not an error. Jumping into the scope of a variable over its initialization is legal in C. It simply means that the variable is left uninitialized. The original code does not compile in C for a completely different reason. Label case VAL: in the original code is attached to the declaration of variable newVal. In C language declarations are not statements. They cannot be labeled. And this is what causes the error when this code is interpreted as C code.

    switch (val)  
    {  
    case VAL:             /* <- C error is here */
      int newVal = 42;  
      break;
    case ANOTHER_VAL:     /* <- C++ error is here */
      ...
      break;
    }
    

Adding an extra {} block fixes both C++ and C problems, even though these problems happen to be very different. On the C++ side it restricts the scope of newVal, making sure that case ANOTHER_VAL: no longer jumps into that scope, which eliminates the C++ issue. On the C side that extra {} introduces a compound statement, thus making the case VAL: label to apply to a statement, which eliminates the C issue.

  • In C case the problem can be easily solved without the {}. Just add an empty statement after the case VAL: label and the code will become valid

    switch (val)  
    {  
    case VAL:;            /* Now it works in C! */
      int newVal = 42;  
      break;
    case ANOTHER_VAL:  
      ...
      break;
    }
    

    Note that even though it is now valid from C point of view, it remains invalid from C++ point of view.

  • Symmetrically, in C++ case the the problem can be easily solved without the {}. Just remove the initializer from variable declaration and the code will become valid

    switch (val)  
    {  
    case VAL: 
      int newVal;
      newVal = 42;  
      break;
    case ANOTHER_VAL:     /* Now it works in C++! */
      ...
      break;
    }
    

    Note that even though it is now valid from C++ point of view, it remains invalid from C point of view.

Merging two images in C#/.NET

basically i use this in one of our apps: we want to overlay a playicon over a frame of a video:

Image playbutton;
try
{
    playbutton = Image.FromFile(/*somekindofpath*/);
}
catch (Exception ex)
{
    return;
}

Image frame;
try
{
    frame = Image.FromFile(/*somekindofpath*/);
}
catch (Exception ex)
{
    return;
}

using (frame)
{
    using (var bitmap = new Bitmap(width, height))
    {
        using (var canvas = Graphics.FromImage(bitmap))
        {
            canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
            canvas.DrawImage(frame,
                             new Rectangle(0,
                                           0,
                                           width,
                                           height),
                             new Rectangle(0,
                                           0,
                                           frame.Width,
                                           frame.Height),
                             GraphicsUnit.Pixel);
            canvas.DrawImage(playbutton,
                             (bitmap.Width / 2) - (playbutton.Width / 2),
                             (bitmap.Height / 2) - (playbutton.Height / 2));
            canvas.Save();
        }
        try
        {
            bitmap.Save(/*somekindofpath*/,
                        System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        catch (Exception ex) { }
    }
}

How to click a link whose href has a certain substring in Selenium?

use driver.findElement(By.partialLinkText("long")).click();

How can I match on an attribute that contains a certain string?

Here's an example that finds div elements whose className contains atag:

//div[contains(@class, 'atag')]

Here's an example that finds div elements whose className contains atag and btag:

//div[contains(@class, 'atag') and contains(@class ,'btag')]

However, it will also find partial matches like class="catag bobtag".

If you don't want partial matches, see bobince's answer below.

Overriding !important style

If all you are doing is adding css to the page, then I would suggest you use the Stylish addon, and write a user style instead of a user script, because a user style is more efficient and appropriate.

See this page with information on how to create a user style

Finding first and last index of some value in a list in Python

This method can be more optimized than above

def rindex(iterable, value):
    try:
        return len(iterable) - next(i for i, val in enumerate(reversed(iterable)) if val == value) - 1
    except StopIteration:
        raise ValueError

NOT IN vs NOT EXISTS

It depends..

SELECT x.col
FROM big_table x
WHERE x.key IN( SELECT key FROM really_big_table );

would not be relatively slow the isn't much to limit size of what the query check to see if they key is in. EXISTS would be preferable in this case.

But, depending on the DBMS's optimizer, this could be no different.

As an example of when EXISTS is better

SELECT x.col
FROM big_table x
WHERE EXISTS( SELECT key FROM really_big_table WHERE key = x.key);
  AND id = very_limiting_criteria

How to pass table value parameters to stored procedure from .net code

DataTable, DbDataReader, or IEnumerable<SqlDataRecord> objects can be used to populate a table-valued parameter per the MSDN article Table-Valued Parameters in SQL Server 2008 (ADO.NET).

The following example illustrates using either a DataTable or an IEnumerable<SqlDataRecord>:

SQL Code:

CREATE TABLE dbo.PageView
(
    PageViewID BIGINT NOT NULL CONSTRAINT pkPageView PRIMARY KEY CLUSTERED,
    PageViewCount BIGINT NOT NULL
);
CREATE TYPE dbo.PageViewTableType AS TABLE
(
    PageViewID BIGINT NOT NULL
);
CREATE PROCEDURE dbo.procMergePageView
    @Display dbo.PageViewTableType READONLY
AS
BEGIN
    MERGE INTO dbo.PageView AS T
    USING @Display AS S
    ON T.PageViewID = S.PageViewID
    WHEN MATCHED THEN UPDATE SET T.PageViewCount = T.PageViewCount + 1
    WHEN NOT MATCHED THEN INSERT VALUES(S.PageViewID, 1);
END

C# Code:

private static void ExecuteProcedure(bool useDataTable, 
                                     string connectionString, 
                                     IEnumerable<long> ids) 
{
    using (SqlConnection connection = new SqlConnection(connectionString)) 
    {
        connection.Open();
        using (SqlCommand command = connection.CreateCommand()) 
        {
            command.CommandText = "dbo.procMergePageView";
            command.CommandType = CommandType.StoredProcedure;

            SqlParameter parameter;
            if (useDataTable) {
                parameter = command.Parameters
                              .AddWithValue("@Display", CreateDataTable(ids));
            }
            else 
            {
                parameter = command.Parameters
                              .AddWithValue("@Display", CreateSqlDataRecords(ids));
            }
            parameter.SqlDbType = SqlDbType.Structured;
            parameter.TypeName = "dbo.PageViewTableType";

            command.ExecuteNonQuery();
        }
    }
}

private static DataTable CreateDataTable(IEnumerable<long> ids) 
{
    DataTable table = new DataTable();
    table.Columns.Add("ID", typeof(long));
    foreach (long id in ids) 
    {
        table.Rows.Add(id);
    }
    return table;
}

private static IEnumerable<SqlDataRecord> CreateSqlDataRecords(IEnumerable<long> ids) 
{
    SqlMetaData[] metaData = new SqlMetaData[1];
    metaData[0] = new SqlMetaData("ID", SqlDbType.BigInt);
    SqlDataRecord record = new SqlDataRecord(metaData);
    foreach (long id in ids) 
    {
        record.SetInt64(0, id);
        yield return record;
    }
}

How to set background image of a view?

simple way :

   -(void) viewDidLoad {
   self.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage       imageNamed:@"background.png"]];
    [super viewDidLoad];
    }

How do I check in python if an element of a list is empty?

If you want to know if list element at index i is set or not, you can simply check the following:

if len(l)<=i:
    print ("empty")

If you are looking for something like what is a NULL-Pointer or a NULL-Reference in other languages, Python offers you None. That is you can write:

l[0] = None # here, list element at index 0 has to be set already
l.append(None) # here the list can be empty before
# checking
if l[i] == None:
    print ("list has actually an element at position i, which is None")

Gitignore not working

In my case it was a blank space at the beginning of the file which showed up clearly when I opened the file in Notepad, wasn't obvious in Visual Studio Code.

Catch paste input

Hmm... I think you can use e.clipboardData to catch the data being pasted. If it doesn't pan out, have a look here.

$(this).live("paste", function(e) {
    alert(e.clipboardData); // [object Clipboard]
});

Euclidean distance of two vectors

As defined on Wikipedia, this should do it.

euc.dist <- function(x1, x2) sqrt(sum((x1 - x2) ^ 2))

There's also the rdist function in the fields package that may be useful. See here.


EDIT: Changed ** operator to ^. Thanks, Gavin.

Icons missing in jQuery UI

Having the right CSS and JS libraries helps, this solved it for me

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

UTF-8 encoding problem in Spring MVC

Convert the JSON string to UTF-8 on your own.

@RequestMapping(value = "/example.json", method = RequestMethod.GET)
@ResponseBody
public byte[] example() throws Exception {

    return "{ 'text': 'äöüß' } ".getBytes("UTF-8");
}

I'm getting Key error in python

This means your array is missing the key you're looking for. I handle this with a function which either returns the value if it exists or it returns a default value instead.

def keyCheck(key, arr, default):
    if key in arr.keys():
        return arr[key]
    else:
        return default


myarray = {'key1':1, 'key2':2}

print keyCheck('key1', myarray, '#default')
print keyCheck('key2', myarray, '#default')
print keyCheck('key3', myarray, '#default')

Output:

1
2
#default

How to print out all the elements of a List in Java?

Consider a List<String> stringList which can be printed in many ways using Java 8 constructs:

stringList.forEach(System.out::println);                            // 1) Iterable.forEach
stringList.stream().forEach(System.out::println);                   // 2) Stream.forEach (order maintained generally but doc does not guarantee)
stringList.stream().forEachOrdered(System.out::println);            // 3) Stream.forEachOrdered (order maintained always)
stringList.parallelStream().forEach(System.out::println);           // 4) Parallel version of Stream.forEach (order not maintained)
stringList.parallelStream().forEachOrdered(System.out::println);    // 5) Parallel version ofStream.forEachOrdered (order maintained always)

How are these approaches different from each other?

First Approach (Iterable.forEach)- The iterator of the collection is generally used and that is designed to be fail-fast which means it will throw ConcurrentModificationException if the underlying collection is structurally modified during the iteration. As mentioned in the doc for ArrayList:

A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.

So it means for ArrayList.forEach setting the value is allowed without any issue. And in case of concurrent collection e.g. ConcurrentLinkedQueue the iterator would be weakly-consistent which means the actions passed in forEach are allowed to make even structural changes without ConcurrentModificationExceptionexception being thrown. But here the modifications might or might not be visible in that iteration.

Second Approach (Stream.forEach)- The order is undefined. Though it may not occur for sequential streams but the specification does not guarantee it. Also the action is required to be non-interfering in nature. As mentioned in doc:

The behavior of this operation is explicitly nondeterministic. For parallel stream pipelines, this operation does not guarantee to respect the encounter order of the stream, as doing so would sacrifice the benefit of parallelism.

Third Approach (Stream.forEachOrdered)- The action would be performed in the encounter order of the stream. So whenever order matters use forEachOrdered without a second thought. As mentioned in the doc:

Performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order.

While iterating over a synchronized collection the first approach would take the collection's lock once and would hold it across all the calls to action method, but in case of streams they use collection's spliterator, which does not lock and relies on the already established rules of non-interference. In case collection backing the stream is modified during iteration a ConcurrentModificationException would be thrown or inconsistent result may occur.

Fourth Approach (Parallel Stream.forEach)- As already mentioned no guarantee to respect the encounter order as expected in case of parallel streams. It is possible that action is performed in different thread for different elements which can never be the case with forEachOrdered.

Fifth Approach (Parallel Stream.forEachOrdered)- The forEachOrdered will process the elements in the order specified by the source irrespective of the fact whether stream is sequential or parallel. So it makes no sense to use this with parallel streams.

Test for non-zero length string in Bash: [ -n "$var" ] or [ "$var" ]

Use case/esac to test:

case "$var" in
  "") echo "zero length";;
esac

CSS background-image-opacity?

#id {
  position: relative;
  opacity: 0.99;
}

#id::before {
  content: "";
  position: absolute;
  width: 100%;
  height: 100%;
  z-index: -1;
  background: url('image.png');
  opacity: 0.3;
}

Hack with opacity 0.99 (less than 1) creates z-index context so you can not worry about global z-index values. (Try to remove it and see what happens in the next demo where parent wrapper has positive z-index.)
If your element already has z-index, then you don't need this hack.

Demo.

How does ApplicationContextAware work in Spring?

Interface to be implemented by any object that wishes to be notified of the ApplicationContext that it runs in.

above is excerpted from the Spring doc website https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/ApplicationContextAware.html.

So, it seemed to be invoked when Spring container has started, if you want to do something at that time.

It just has one method to set the context, so you will get the context and do something to sth now already in context I think.

Implementing a Custom Error page on an ASP.Net website

Try this way, almost same.. but that's what I did, and working.

<configuration>
    <system.web>
       <customErrors mode="On" defaultRedirect="apperror.aspx">
          <error statusCode="404" redirect="404.aspx" />
          <error statusCode="500" redirect="500.aspx" />
       </customErrors>
    </system.web>
</configuration> 

or try to change the 404 error page from IIS settings, if required urgently.

SQL not a single-group group function

Well the problem simply-put is that the SUM(TIME) for a specific SSN on your query is a single value, so it's objecting to MAX as it makes no sense (The maximum of a single value is meaningless).

Not sure what SQL database server you're using but I suspect you want a query more like this (Written with a MSSQL background - may need some translating to the sql server you're using):

SELECT TOP 1 SSN, SUM(TIME)
FROM downloads
GROUP BY SSN
ORDER BY 2 DESC

This will give you the SSN with the highest total time and the total time for it.

Edit - If you have multiple with an equal time and want them all you would use:

SELECT
SSN, SUM(TIME)
FROM downloads
GROUP BY SSN
HAVING SUM(TIME)=(SELECT MAX(SUM(TIME)) FROM downloads GROUP BY SSN))

Getting index value on razor foreach

All of the above answers require logic in the view. Views should be dumb and contain as little logic as possible. Why not create properties in your view model that correspond to position in the list eg:

public int Position {get; set}

In your view model builder you set the position 1 through 4.

BUT .. there is even a cleaner way. Why not make the CSS class a property of your view model? So instead of the switch statement in your partial, you would just do this:

<div class="@Model.GridCSS">

Move the switch statement to your view model builder and populate the CSS class there.

Update Item to Revision vs Revert to Revision

The files in your working copy might look exactly the same after, but they are still very different actions -- the repository is in a completely different state, and you will have different options available to you after reverting than "updating" to an old revision.

Briefly, "update to" only affects your working copy, but "reverse merge and commit" will affect the repository.

If you "update" to an old revision, then the repository has not changed: in your example, the HEAD revision is still 100. You don't have to commit anything, since you are just messing around with your working copy. If you make modifications to your working copy and try to commit, you will be told that your working copy is out-of-date, and you will need to update before you can commit. If someone else working on the same repository performs an "update", or if you check out a second working copy, it will be r100.

However, if you "reverse merge" to an old revision, then your working copy is still based on the HEAD (assuming you are up-to-date) -- but you are creating a new revision to supersede the unwanted changes. You have to commit these changes, since you are changing the repository. Once done, any updates or new working copies based on the HEAD will show r101, with the contents you just committed.

php how to go one level up on dirname(__FILE__)

dirname(__DIR__,level);
dirname(__DIR__,1);

level is how many times will you go back to the folder

Change select box option background color

enter image description here

Similar to some of the answers, but not really stated, is to add a class to the actual option tag and use css classes...this is currently working for me without issue on IE (see above ss).

<select id="reviewAction">
<option class="greenColor">Accept and Advance Status</option>
<option class="redColor">Return for Modifications</option>
</select>

CSS:

.greenColor{
    background-color: #33CC33;
}
.redColor{
    background-color: #E60000;
}

Android Stop Emulator from Command Line

The other answer didn't work for me (on Windows 7). But this worked:

telnet localhost 5554
kill

Difference between iCalendar (.ics) and the vCalendar (.vcs)

You can try VCS to ICS file converter (Java, works with Windows, Mac, Linux etc.). It has the feature of parsing events and todos. You can convert the VCS generated by your Nokia phone, with bluetooth export or via nbuexplorer.

  • Complete support for UTF-8
  • Quoted-printable encoded strings
  • Completely open source code (GPLv3 and Apache 2.0)
  • Standard iCalendar v2.0 output
  • Encodes multiple files at once (only one event per file)
  • Compatible with Android, iOS, Mozilla Lightning/Sunbird, Google Calendar and others
  • Multiplatform

How does String.Index work in Swift

enter image description here

All of the following examples use

var str = "Hello, playground"

startIndex and endIndex

  • startIndex is the index of the first character
  • endIndex is the index after the last character.

Example

// character
str[str.startIndex] // H
str[str.endIndex]   // error: after last character

// range
let range = str.startIndex..<str.endIndex
str[range]  // "Hello, playground"

With Swift 4's one-sided ranges, the range can be simplified to one of the following forms.

let range = str.startIndex...
let range = ..<str.endIndex

I will use the full form in the follow examples for the sake of clarity, but for the sake of readability, you will probably want to use the one-sided ranges in your code.

after

As in: index(after: String.Index)

  • after refers to the index of the character directly after the given index.

Examples

// character
let index = str.index(after: str.startIndex)
str[index]  // "e"

// range
let range = str.index(after: str.startIndex)..<str.endIndex
str[range]  // "ello, playground"

before

As in: index(before: String.Index)

  • before refers to the index of the character directly before the given index.

Examples

// character
let index = str.index(before: str.endIndex)
str[index]  // d

// range
let range = str.startIndex..<str.index(before: str.endIndex)
str[range]  // Hello, playgroun

offsetBy

As in: index(String.Index, offsetBy: String.IndexDistance)

  • The offsetBy value can be positive or negative and starts from the given index. Although it is of the type String.IndexDistance, you can give it an Int.

Examples

// character
let index = str.index(str.startIndex, offsetBy: 7)
str[index]  // p

// range
let start = str.index(str.startIndex, offsetBy: 7)
let end = str.index(str.endIndex, offsetBy: -6)
let range = start..<end
str[range]  // play

limitedBy

As in: index(String.Index, offsetBy: String.IndexDistance, limitedBy: String.Index)

  • The limitedBy is useful for making sure that the offset does not cause the index to go out of bounds. It is a bounding index. Since it is possible for the offset to exceed the limit, this method returns an Optional. It returns nil if the index is out of bounds.

Example

// character
if let index = str.index(str.startIndex, offsetBy: 7, limitedBy: str.endIndex) {
    str[index]  // p
}

If the offset had been 77 instead of 7, then the if statement would have been skipped.

Why is String.Index needed?

It would be much easier to use an Int index for Strings. The reason that you have to create a new String.Index for every String is that Characters in Swift are not all the same length under the hood. A single Swift Character might be composed of one, two, or even more Unicode code points. Thus each unique String must calculate the indexes of its Characters.

It is possibly to hide this complexity behind an Int index extension, but I am reluctant to do so. It is good to be reminded of what is actually happening.

How do I flush the cin buffer?

#include <stdio_ext.h>

and then use function

__fpurge(stdin)

HTML: Image won't display?

I found that skipping the quotation marks "" around the file and location name displayed the image... I am doing this on MacBook....

ListView with Add and Delete Buttons in each Row in android

on delete button click event

public void delete(View v){                

    ListView listview1;
    ArrayList<E> datalist;

    final int position = listview1.getPositionForView((View) v.getParent());
    datalist.remove(position);
    myAdapter.notifyDataSetChanged();

}

Export data from R to Excel

The WriteXLS function from the WriteXLS package can write data to Excel.

Alternatively, write.xlsx from the xlsx package will also work.

How do I conditionally add attributes to React components?

Here is an example of using Bootstrap's Button via React-Bootstrap (version 0.32.4):

var condition = true;

return (
  <Button {...(condition ? {bsStyle: 'success'} : {})} />
);

Depending on the condition, either {bsStyle: 'success'} or {} will be returned. The spread operator will then spread the properties of the returned object to Button component. In the falsy case, since no properties exist on the returned object, nothing will be passed to the component.


An alternative way based on Andy Polhill's comment:

var condition = true;

return (
  <Button bsStyle={condition ? 'success' : undefined} />
);

The only small difference is that in the second example the inner component <Button/>'s props object will have a key bsStyle with a value of undefined.

How to use a variable in the replacement side of the Perl substitution operator?

On the replacement side, you must use $1, not \1.

And you can only do what you want by making replace an evalable expression that gives the result you want and telling s/// to eval it with the /ee modifier like so:

$find="start (.*) end";
$replace='"foo $1 bar"';

$var = "start middle end";
$var =~ s/$find/$replace/ee;

print "var: $var\n";

To see why the "" and double /e are needed, see the effect of the double eval here:

$ perl
$foo = "middle";
$replace='"foo $foo bar"';
print eval('$replace'), "\n";
print eval(eval('$replace')), "\n";
__END__
"foo $foo bar"
foo middle bar

(Though as ikegami notes, a single /e or the first /e of a double e isn't really an eval(); rather, it tells the compiler that the substitution is code to compile, not a string. Nonetheless, eval(eval(...)) still demonstrates why you need to do what you need to do to get /ee to work as desired.)

How to connect to Oracle 11g database remotely

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

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

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

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

LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
    )
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
    )
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = 172.20.14.13)(PORT = 1521))
    )
  )

ADR_BASE_LISTENER = E:\app\user

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

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

ALINADB =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = alinadb)
    )
  )

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


LOCAL =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = 172.20.14.13)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = alinadb)
    )
  )

ORACLR_CONNECTION_DATA =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
    )
    (CONNECT_DATA =
      (SID = CLRExtProc)
      (PRESENTATION = RO)
    )
  )

ORCL =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = 172.20.14.78)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = orcl)
    )
  )

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

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

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

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

    ADR_BASE_LISTENER = F:\app\alinasoft

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

SERVER-DB =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = 172.20.14.13)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = alinadb)
    )
  )

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

Eight Allow connections for port 1158 (Computer A - (172.20.14.13)) for Oracle Enterprise Manager (https://172.20.14.13:1158/em/console/logon/logon)

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

Tenth In computer B 172.20.14.78 sqlplus /NOLOG CONNECT system/oracle@//172.20.14.13:1521/alinadb

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

MySQL Error 1153 - Got a packet bigger than 'max_allowed_packet' bytes

Set max_allowed_packet to the same (or more) than what it was when you dumped it with mysqldump. If you can't do that, make the dump again with a smaller value.

That is, assuming you dumped it with mysqldump. If you used some other tool, you're on your own.

How to terminate a python subprocess launched with shell=True

I could do it using

from subprocess import Popen

process = Popen(command, shell=True)
Popen("TASKKILL /F /PID {pid} /T".format(pid=process.pid))

it killed the cmd.exe and the program that i gave the command for.

(On Windows)

hash function for string

I've had nice results with djb2 by Dan Bernstein.

unsigned long
hash(unsigned char *str)
{
    unsigned long hash = 5381;
    int c;

    while (c = *str++)
        hash = ((hash << 5) + hash) + c; /* hash * 33 + c */

    return hash;
}

JUnit Eclipse Plugin?

It's built in Eclipse since ages. Which Eclipse version are you using? How were you trying to create a new JUnit test case? It should be File > New > Other > Java - JUnit - JUnit Test Case (you can eventually enter Filter text "junit").

ToggleClass animate jQuery?

You can simply use CSS transitions, see this fiddle

.on {
color:#fff;
transition:all 1s;
}

.off{
color:#000;
transition:all 1s;
}

Good PHP ORM Library?

Try PdoMap. Wikipedia claims that is inspired by Hibernate. Since I never used Hibernate, I cannot judge :), but I would say from my experience that is good and fast ORM that is easy to implement, with a less steep learning curve that other ORMs.

SQL LEFT JOIN Subquery Alias

I recognize that the answer works and has been accepted but there is a much cleaner way to write that query. Tested on mysql and postgres.

SELECT wpoi.order_id As No_Commande
FROM  wp_woocommerce_order_items AS wpoi
LEFT JOIN wp_postmeta AS wpp ON wpoi.order_id = wpp.post_id 
                            AND wpp.meta_key = '_shipping_first_name'
WHERE  wpoi.order_id =2198 

jQuery checkbox checked state changed event

If your intention is to attach event only on checked checkboxes (so it would fire when they are unchecked and checked later again) then this is what you want.

$(function() {
    $("input[type='checkbox']:checked").change(function() {

    })
})

if your intention is to attach event to all checkboxes (checked and unchecked)

$(function() {
    $("input[type='checkbox']").change(function() {

    })
})

if you want it to fire only when they are being checked (from unchecked) then @James Allardice answer above.

BTW input[type='checkbox']:checked is CSS selector.

Gradle - Could not find or load main class

For a project structure like

project_name/src/main/java/Main_File.class

in the file build.gradle, add the following line

mainClassName = 'Main_File'

How to convert JSON to CSV format and store in a variable

A more elegant way to convert json to csv is to use the map function without any framework:

var json = json3.items
var fields = Object.keys(json[0])
var replacer = function(key, value) { return value === null ? '' : value } 
var csv = json.map(function(row){
  return fields.map(function(fieldName){
    return JSON.stringify(row[fieldName], replacer)
  }).join(',')
})
csv.unshift(fields.join(',')) // add header column
 csv = csv.join('\r\n');
console.log(csv)

Output:

title,description,link,timestamp,image,embed,language,user,user_image,user_link,user_id,geo,source,favicon,type,domain,id
"Apple iPhone 4S Sale Cancelled in Beijing Amid Chaos (Design You Trust)","Advertise here with BSA Apple cancelled its scheduled sale of iPhone 4S in one of its stores in China’s capital Beijing on January 13. Crowds outside the store in the Sanlitun district were waiting on queues overnight. There were incidents of scuffle between shoppers and the store’s security staff when shoppers, hundreds of them, were told that the sales [...]Source : Design You TrustExplore : iPhone, iPhone 4, Phone","http://wik.io/info/US/309201303","1326439500","","","","","","","","","wikio","http://wikio.com/favicon.ico","blogs","wik.io","2388575404943858468"
"Apple to halt sales of iPhone 4S in China (Fame Dubai Blog)","SHANGHAI – Apple Inc said on Friday it will stop selling its latest iPhone in its retail stores in Beijing and Shanghai to ensure the safety of its customers and employees. Go to SourceSource : Fame Dubai BlogExplore : iPhone, iPhone 4, Phone","http://wik.io/info/US/309198933","1326439320","","","","","","","","","wikio","http://wikio.com/favicon.ico","blogs","wik.io","16209851193593872066"

Update ES6 (2016)

Use this less dense syntax and also JSON.stringify to add quotes to strings while keeping numbers unquoted:

const items = json3.items
const replacer = (key, value) => value === null ? '' : value // specify how you want to handle null values here
const header = Object.keys(items[0])
const csv = [
  header.join(','), // header row first
  ...items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','))
].join('\r\n')

console.log(csv)

Count with IF condition in MySQL query

Use sum() in place of count()

Try below:

SELECT
    ccc_news . * , 
    SUM(if(ccc_news_comments.id = 'approved', 1, 0)) AS comments
FROM
    ccc_news
    LEFT JOIN
        ccc_news_comments
    ON
        ccc_news_comments.news_id = ccc_news.news_id
WHERE
    `ccc_news`.`category` = 'news_layer2'
    AND `ccc_news`.`status` = 'Active'
GROUP BY
    ccc_news.news_id
ORDER BY
    ccc_news.set_order ASC
LIMIT 20 

Extract public/private key from PKCS12 file for later use in SSH-PK-Authentication

You can use following commands to extract public/private key from a PKCS#12 container:

  • PKCS#1 Private key

    openssl pkcs12 -in yourP12File.pfx -nocerts -out privateKey.pem
    
  • Certificates:

    openssl pkcs12 -in yourP12File.pfx -clcerts -nokeys -out publicCert.pem
    

Combine Multiple child rows into one row MYSQL

The easiest way would be to make use of the GROUP_CONCAT group function here..

select
  ordered_item.id as `Id`,
  ordered_item.Item_Name as `ItemName`,
  GROUP_CONCAT(Ordered_Options.Value) as `Options`
from
  ordered_item,
  ordered_options
where
  ordered_item.id=ordered_options.ordered_item_id
group by
  ordered_item.id

Which would output:

Id              ItemName       Options

1               Pizza          Pepperoni,Extra Cheese

2               Stromboli      Extra Cheese

That way you can have as many options as you want without having to modify your query.

Ah, if you see your results getting cropped, you can increase the size limit of GROUP_CONCAT like this:

SET SESSION group_concat_max_len = 8192;

How can I get npm start at a different directory?

I came here from google so it might be relevant to others: for yarn you could use:

yarn --cwd /path/to/your/app run start 

how to convert date to a format `mm/dd/yyyy`

As your data already in varchar, you have to convert it into date first:

select convert(varchar(10), cast(ts as date), 101) from <your table>

Using Pairs or 2-tuples in Java

Android Tuple Utils

This object provides a sensible implementation of equals(), returning true if equals() is true on each of the contained objects.

How to instantiate a javascript class in another js file?

It depends on what environment you're running in. In a web browser you simply need to make sure that file1.js is loaded before file2.js:

<script src="file1.js"></script>
<script src="file2.js"></script>

In node.js, the recommended way is to make file1 a module then you can load it with the require function:

require('path/to/file1.js');

It's also possible to use node's module style in HTML using the require.js library.

How to define a two-dimensional array?

I read in comma separated files like this:

data=[]
for l in infile:
    l = split(',')
    data.append(l)

The list "data" is then a list of lists with index data[row][col]

How to print the array?

It looks like you have a typo on your array, it should read:

int my_array[3][3] = {...

You don't have the _ or the {.

Also my_array[3][3] is an invalid location. Since computers begin counting at 0, you are accessing position 4. (Arrays are weird like that).

If you want just the last element:

printf("%d\n", my_array[2][2]);

If you want the entire array:

for(int i = 0; i < my_array.length; i++) {
  for(int j = 0; j < my_array[i].length; j++)
    printf("%d ", my_array[i][j]);
  printf("\n");
}

how to remove time from datetime

In mysql at least, you can use DATE(theDate).

What are the proper permissions for an upload folder with PHP/Apache?

I would go with Ryan's answer if you really want to do this.

In general on a *nix environment, you always want to err on giving away as little permissions as possible.

9 times out of 10, 755 is the ideal permission for this - as the only user with the ability to modify the files will be the webserver. Change this to 775 with your ftp user in a group if you REALLY need to change this.

Since you're new to php by your own admission, here's a helpful link for improving the security of your upload service: move_uploaded_file

How to install the Raspberry Pi cross compiler on my Linux host machine?

The initial question has been posted quite some time ago and in the meantime Debian has made huge headway in the area of multiarch support.

Multiarch is a great achievement for cross compilation!

In a nutshell the following steps are required to leverage multiarch for Raspbian Jessie cross compilation:

  • On your Ubuntu host install Debian Jessie amd64 within a chroot or a LXC container.
  • Enable the foreign architecture armhf.
  • Install the cross compiler from the emdebian tools repository.
  • Tweak the cross compiler (it would generate code for ARMv7-A by default) by writing a custom gcc specs file.
  • Install armhf libraries (libstdc++ etc.) from the Raspbian repository.
  • Build your source code.

Since this is a lot of work I have automated the above setup. You can read about it here:

Cross Compiling for Raspbian

How to detect scroll direction

var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$(document).bind(mousewheelevt, 
function(e)
    {
        var evt = window.event || e //equalize event object     
        evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible               
        var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF
        if(delta > 0) 
            {
            scrollup();
            }
        else
            {
            scrolldown();
            }   
    }
);

How to delete specific characters from a string in Ruby?

Do as below using String#tr :

 "((String1))".tr('()', '')
 # => "String1"

Good Linux (Ubuntu) SVN client

To begin with, I will try not to sound flamish here ;)

Sigh.. Why don't people get that file explorer integrated clients is the way to go? It is so much more efficient than opening terminals and typing. Simple math, ~two mouse clicks versus ~10+ key strokes. Though, I must point out that I love command line since I do lot's of administrative work and prefer to automate things as quickly and easy as possible.

Having been spoiled by TortoiseSVN on windows I was amazed by the lack of a tortoisesvn-like integrated client when I moved to ubuntu. For pure programmers an IDE integrated client might be enough but for general purpose use and for say graphics artists or other random office people, the client has to be integrated into the standard file explorer, else most people will not use it, at all, ever.

Some thought's on some clients:

kdesvn, The client I like the best this far, though there is one huge annoyance compared to TortoiseSVN - you have to enter the special subversion layout mode to get overlays indicating file status. Thus I would not call kdesvn integrated.

NautilusSVN, looks promising but as of 0.12 release it has performance problems with big repositories. I work with repositories where working copies can contain ~50 000 files at times, which TortoiseSVN handles but NautilusSVN does not. So I hope NautilusSVN will get a new optimized release soon.

RapidSVN is not integrated, but I gave it a try. It behaved quite weird and crashed a couple of times. It got uninstalled after ~20 minutes..

I really hope the NautilusSVN project will make a new performance optimized release soon.

NaughtySVN seems like it could shape up to be quite nice, but as of now it lacks icon overlays and has not had a release for two years... so I would say NautilusSVN is our only hope.

Most efficient way to concatenate strings?

It really depends on your usage pattern. A detailed benchmark between string.Join, string,Concat and string.Format can be found here: String.Format Isn't Suitable for Intensive Logging

(This is actually the same answer I gave to this question)

How to count number of records per day?

select DateAdded, count(CustID)
from tbl
group by DateAdded

about 7-days interval it's DB-depending question

Mysql - delete from multiple tables with one query

Normally you can't DELETE from multiple tables at once, unless you'll use JOINs as shown in other answers.

However if all yours tables starts with certain name, then this query will generate query which would do that task:

SELECT CONCAT('DELETE FROM ', GROUP_CONCAT(TABLE_NAME SEPARATOR ' WHERE user_id=123;DELETE FROM ') , 'FROM table1;' ) AS statement FROM information_schema.TABLES WHERE TABLE_NAME LIKE 'table%'

then pipe it (in shell) into mysql command for execution.

For example it'll generate something like:

DELETE FROM table1 WHERE user_id=123;
DELETE FROM table2 WHERE user_id=123;
DELETE FROM table3 WHERE user_id=123;

More shell oriented example would be:

echo "SHOW TABLES LIKE 'table%'" | mysql | tail -n +2 | xargs -L1 -I% echo "DELETE FROM % WHERE user_id=123;" | mysql -v

If you want to use only MySQL for that, you can think of more advanced query, such as this:

SET @TABLES = (SELECT GROUP_CONCAT(TABLE_NAME) FROM information_schema.TABLES WHERE TABLE_NAME LIKE 'table%');
PREPARE drop_statement FROM 'DELETE FROM @tables';
EXECUTE drop_statement USING @TABLES;
DEALLOCATE PREPARE drop_statement;

The above example is based on: MySQL – Delete/Drop all tables with specific prefix.

How to load property file from classpath?

final Properties properties = new Properties();
try (final InputStream stream =
           this.getClass().getResourceAsStream("foo.properties")) {
    properties.load(stream);
    /* or properties.loadFromXML(...) */
}