Programs & Examples On #Getaddrinfo a

UTF-8: General? Bin? Unicode?

Accepted answer is outdated.

If you use MySQL 5.5.3+, use utf8mb4_unicode_ci instead of utf8_unicode_ci to ensure the characters typed by your users won't give you errors.

utf8mb4 supports emojis for example, whereas utf8 might give you hundreds of encoding-related bugs like:

Incorrect string value: ‘\xF0\x9F\x98\x81…’ for column ‘data’ at row 1

HTTP POST and GET using cURL in Linux

I think Amith Koujalgi is correct but also, in cases where the webservice responses are in JSON then it might be more useful to see the results in a clean JSON format instead of a very long string. Just add | grep }| python -mjson.tool to the end of curl commands here is two examples:

GET approach with JSON result

curl -i -H "Accept: application/json" http://someHostName/someEndpoint | grep }| python -mjson.tool 

POST approach with JSON result

curl -X POST  -H "Accept: Application/json" -H "Content-Type: application/json" http://someHostName/someEndpoint -d '{"id":"IDVALUE","name":"Mike"}' | grep }| python -mjson.tool

enter image description here

How to declare variable and use it in the same Oracle SQL script?

Just want to add Matas' answer. Maybe it's obvious, but I've searched for a long time to figure out that the variable is accessible only inside the BEGIN-END construction, so if you need to use it in some code later, you need to put this code inside the BEGIN-END block.

Note that these blocks can be nested:

DECLARE x NUMBER;
BEGIN
    SELECT PK INTO x FROM table1 WHERE col1 = 'test';

    DECLARE y NUMBER;
    BEGIN
        SELECT PK INTO y FROM table2 WHERE col2 = x;

        INSERT INTO table2 (col1, col2)
        SELECT y,'text'
        FROM dual
        WHERE exists(SELECT * FROM table2);

        COMMIT;
    END;
END;

How to access the value of a promise?

There are some good answer above and here is the ES6 Arrow function version

var something = async() => {
   let result = await functionThatReturnsPromiseA();
   return result + 1;
}

Importing data from a JSON file into R

import httr package

library(httr)

Get the url

url <- "http://www.omdbapi.com/?apikey=72bc447a&t=Annie+Hall&y=&plot=short&r=json"
resp <- GET(url)

Print content of resp as text

content(resp, as = "text")

Print content of resp

content(resp)

Use content() to get the content of resp, but this time do not specify a second argument. R figures out automatically that you're dealing with a JSON, and converts the JSON to a named R list.

Java optional parameters

VarArgs and overloading have been mentioned. Another option is a Bloch Builder pattern, which would look something like this:

 MyObject my = new MyObjectBuilder().setParam1(value)
                                 .setParam3(otherValue)
                                 .setParam6(thirdValue)
                                 .build();

Although that pattern would be most appropriate for when you need optional parameters in a constructor.

how to change a selections options based on another select option selected?

you can use data-tag in html5 and do this using this code:

_x000D_
_x000D_
<script>_x000D_
 $('#mainCat').on('change', function() {_x000D_
  var selected = $(this).val();_x000D_
  $("#expertCat option").each(function(item){_x000D_
   console.log(selected) ;  _x000D_
   var element =  $(this) ; _x000D_
   console.log(element.data("tag")) ; _x000D_
   if (element.data("tag") != selected){_x000D_
    element.hide() ; _x000D_
   }else{_x000D_
    element.show();_x000D_
   }_x000D_
  }) ; _x000D_
  _x000D_
  $("#expertCat").val($("#expertCat option:visible:first").val());_x000D_
  _x000D_
});_x000D_
</script>
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>_x000D_
<select id="mainCat">_x000D_
   <option value = '1'>navid</option>_x000D_
   <option value = '2'>javad</option>_x000D_
   <option value = '3'>mamal</option>_x000D_
  </select>_x000D_
  _x000D_
  <select id="expertCat">_x000D_
   <option  value = '1' data-tag='2'>UI</option>_x000D_
   <option  value = '2' data-tag='2'>Java Android</option>_x000D_
   <option  value = '3' data-tag='1'>Web</option>_x000D_
   <option  value = '3' data-tag='1'>Server</option>_x000D_
   <option  value = '3' data-tag='3'>Back End</option>_x000D_
   <option  value = '3' data-tag='3'>.net</option>_x000D_
  </select>
_x000D_
_x000D_
_x000D_

How to design RESTful search/filtering?

FYI: I know this is a bit late but for anyone who is interested. Depends on how RESTful you want to be, you will have to implement your own filtering strategies as the HTTP spec is not very clear on this. I'd like to suggest url-encoding all the filter parameters e.g.

GET api/users?filter=param1%3Dvalue1%26param2%3Dvalue2

I know it's ugly but I think it's the most RESTful way to do it and should be easy to parse on the server side :)

Java verify void method calls n times with Mockito

The necessary method is Mockito#verify:

public static <T> T verify(T mock,
                           VerificationMode mode)

mock is your mocked object and mode is the VerificationMode that describes how the mock should be verified. Possible modes are:

verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");

You'll need these static imports from the Mockito class in order to use the verify method and these verification modes:

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

So in your case the correct syntax will be:

Mockito.verify(mock, times(4)).send()

This verifies that the method send was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.


If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode. A simple

verify(mock).someMethod("was called once");

would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");.


It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");, but we can write

verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");

instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.

JavaScript Array splice vs slice

splice & delete Array item by index

index = 2

//splice & will modify the origin array
const arr1 = [1,2,3,4,5];
//slice & won't modify the origin array
const arr2 = [1,2,3,4,5]

console.log("----before-----");
console.log(arr1.splice(2, 1));
console.log(arr2.slice(2, 1));

console.log("----after-----");
console.log(arr1);
console.log(arr2);

_x000D_
_x000D_
let log = console.log;_x000D_
_x000D_
//splice & will modify the origin array_x000D_
const arr1 = [1,2,3,4,5];_x000D_
_x000D_
//slice & won't modify the origin array_x000D_
const arr2 = [1,2,3,4,5]_x000D_
_x000D_
log("----before-----");_x000D_
log(arr1.splice(2, 1));_x000D_
log(arr2.slice(2, 1));_x000D_
_x000D_
log("----after-----");_x000D_
log(arr1);_x000D_
log(arr2);
_x000D_
_x000D_
_x000D_

enter image description here

Converting a UNIX Timestamp to Formatted Date String

You can do like as.....

$originalDate = "1585876500";

echo $newDate = date("Y-m-d h:i:sa", date($originalDate));

Where to declare variable in react js

Using ES6 syntax in React does not bind this to user-defined functions however it will bind this to the component lifecycle methods.

So the function that you declared will not have the same context as the class and trying to access this will not give you what you are expecting.

For getting the context of class you have to bind the context of class to the function or use arrow functions.

Method 1 to bind the context:

class MyContainer extends Component {

    constructor(props) {
        super(props);
        this.onMove = this.onMove.bind(this);
        this.testVarible= "this is a test";
    }

    onMove() {
        console.log(this.testVarible);
    }
}

Method 2 to bind the context:

class MyContainer extends Component {

    constructor(props) {
        super(props);
        this.testVarible= "this is a test";
    }

    onMove = () => {
        console.log(this.testVarible);
    }
}

Method 2 is my preferred way but you are free to choose your own.

Update: You can also create the properties on class without constructor:

class MyContainer extends Component {

    testVarible= "this is a test";

    onMove = () => {
        console.log(this.testVarible);
    }
}

Note If you want to update the view as well, you should use state and setState method when you set or change the value.

Example:

class MyContainer extends Component {

    state = { testVarible: "this is a test" };

    onMove = () => {
        console.log(this.state.testVarible);
        this.setState({ testVarible: "new value" });
    }
}

Warning: mysqli_connect(): (HY000/1045): Access denied for user 'username'@'localhost' (using password: YES)

Do you have two connections at the same time? If so, close every time you don't need it.

django order_by query set, ascending and descending

Reserved.objects.filter(client=client_id).order_by('-check_in')

Notice the - before check_in.

Django Documentation

Class 'App\Http\Controllers\DB' not found and I also cannot use a new Model

I like to do this witch i think is cleaner :

1 - Add the model to namespace:

use App\Employee;

2 - then you can do :

$employees = Employee::get();

or maybe somthing like this:

$employee = Employee::where('name', 'John')->first();

Is there a MySQL option/feature to track history of changes to records?

Just my 2 cents. I would create a solution which records exactly what changed, very similar to transient's solution.

My ChangesTable would simple be:

DateTime | WhoChanged | TableName | Action | ID |FieldName | OldValue

1) When an entire row is changed in the main table, lots of entries will go into this table, BUT that is very unlikely, so not a big problem (people are usually only changing one thing) 2) OldVaue (and NewValue if you want) have to be some sort of epic "anytype" since it could be any data, there might be a way to do this with RAW types or just using JSON strings to convert in and out.

Minimum data usage, stores everything you need and can be used for all tables at once. I'm researching this myself right now, but this might end up being the way I go.

For Create and Delete, just the row ID, no fields needed. On delete a flag on the main table (active?) would be good.

VBA check if object is set

If obj Is Nothing Then
    ' need to initialize obj: '
    Set obj = ...
Else
    ' obj already set / initialized. '
End If

Or, if you prefer it the other way around:

If Not obj Is Nothing Then
    ' obj already set / initialized. '
Else
    ' need to initialize obj: '
    Set obj = ...
End If

Using AngularJS date filter with UTC date

If you are working in .Net then adding following in web.config inside

<system.web>

will solve your issue:

<globalization culture="auto:en-US" uiCulture="auto:en-US" />

Android file chooser

EDIT (02 Jan 2012):

I created a small open source Android Library Project that streamlines this process, while also providing a built-in file explorer (in case the user does not have one present). It's extremely simple to use, requiring only a few lines of code.

You can find it at GitHub: aFileChooser.


ORIGINAL

If you want the user to be able to choose any file in the system, you will need to include your own file manager, or advise the user to download one. I believe the best you can do is look for "openable" content in an Intent.createChooser() like this:

private static final int FILE_SELECT_CODE = 0;

private void showFileChooser() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
    intent.setType("*/*"); 
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {
        startActivityForResult(
                Intent.createChooser(intent, "Select a File to Upload"),
                FILE_SELECT_CODE);
    } catch (android.content.ActivityNotFoundException ex) {
        // Potentially direct the user to the Market with a Dialog
        Toast.makeText(this, "Please install a File Manager.", 
                Toast.LENGTH_SHORT).show();
    }
}

You would then listen for the selected file's Uri in onActivityResult() like so:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case FILE_SELECT_CODE:
        if (resultCode == RESULT_OK) {
            // Get the Uri of the selected file 
            Uri uri = data.getData();
            Log.d(TAG, "File Uri: " + uri.toString());
            // Get the path
            String path = FileUtils.getPath(this, uri);
            Log.d(TAG, "File Path: " + path);
            // Get the file instance
            // File file = new File(path);
            // Initiate the upload
        }
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

The getPath() method in my FileUtils.java is:

public static String getPath(Context context, Uri uri) throws URISyntaxException {
    if ("content".equalsIgnoreCase(uri.getScheme())) {
        String[] projection = { "_data" };
        Cursor cursor = null;

        try {
            cursor = context.getContentResolver().query(uri, projection, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow("_data");
            if (cursor.moveToFirst()) {
                return cursor.getString(column_index);
            }
        } catch (Exception e) {
            // Eat it
        }
    }
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
} 

Visual Studio 2015 is very slow

Try uninstalling either Node.js Tools for Visual Studio (NTVS) or the commercial add-on called ReSharper from JetBrains. Using both NTVS and Resharper causes memory leaks in Visual Studio 2015.

NTVS = Node Tools for Visual Studio

Using Switch Statement to Handle Button Clicks

Just change the class (I suppose it's the main Activity) to implement View.OnClickListener and on the onClick method put the general onClick actions you want to put:

public class MediaPlayer extends Activity implements OnClickListener {

@Override
public void onCreate(Bundle savedInstanceState) {
    Button b1 = (Button) findViewById(R.id.buttonplay);       
    b1.setOnClickListener(this);
    //{YOUR APP}
}


@Override
public void onClick(View v) {
    // Perform action on click
    switch(v.getId()) {
    case R.id.buttonplay:
        //Play voicefile
        MediaPlayer.create(getBaseContext(), R.raw.voicefile).start();
        break;
    case R.id.buttonstop:
        //Stop MediaPlayer
        MediaPlayer.create(getBaseContext(), R.raw.voicefile).stop();
        break;
    }

}}

I took it from this video: http://www.youtube.com/watch?v=rm-hNlTD1H0 . It's good for starters.

How can I have grep not print out 'No such file or directory' errors?

I was getting lots of these errors running "M-x rgrep" from Emacs on Windows with /Git/usr/bin in my PATH. Apparently in that case, M-x rgrep uses "NUL" (the Windows null device) rather than "/dev/null". I fixed the issue by adding this to .emacs:

;; Prevent issues with the Windows null device (NUL)
;; when using cygwin find with rgrep.
(defadvice grep-compute-defaults (around grep-compute-defaults-advice-null-device)
  "Use cygwin's /dev/null as the null-device."
  (let ((null-device "/dev/null"))
    ad-do-it))
(ad-activate 'grep-compute-defaults)

OSX El Capitan: sudo pip install OSError: [Errno: 1] Operation not permitted

pip install --ignore-installed six

This will do the job, then you can try your first command.

Via http://github.com/pypa/pip/issues/3165

Declaring & Setting Variables in a Select Statement

I have tried this and it worked:

define PROPp_START_DT = TO_DATE('01-SEP-1999')

select * from proposal where prop_start_dt = &PROPp_START_DT

 

$lookup on ObjectId's in an array

I have to disagree, we can make $lookup work with IDs array if we preface it with $match stage.

_x000D_
_x000D_
// replace IDs array with lookup results_x000D_
db.products.aggregate([_x000D_
    { $match: { products : { $exists: true } } },_x000D_
    {_x000D_
        $lookup: {_x000D_
            from: "products",_x000D_
            localField: "products",_x000D_
            foreignField: "_id",_x000D_
            as: "productObjects"_x000D_
        }_x000D_
    }_x000D_
])
_x000D_
_x000D_
_x000D_

It becomes more complicated if we want to pass the lookup result to a pipeline. But then again there's a way to do so (already suggested by @user12164):

_x000D_
_x000D_
// replace IDs array with lookup results passed to pipeline_x000D_
db.products.aggregate([_x000D_
    { $match: { products : { $exists: true } } },_x000D_
    {_x000D_
        $lookup: {_x000D_
            from: "products",_x000D_
             let: { products: "$products"},_x000D_
             pipeline: [_x000D_
                 { $match: { $expr: {$in: ["$_id", "$$products"] } } },_x000D_
                 { $project: {_id: 0} } // suppress _id_x000D_
             ],_x000D_
            as: "productObjects"_x000D_
        }_x000D_
    }_x000D_
])
_x000D_
_x000D_
_x000D_

Can we write our own iterator in Java?

Here is the complete answer to the question.

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

class ListIterator implements Iterator<String>{
    List<String> list;
    int pos = 0;

    public ListIterator(List<String> list) {
        this.list = list;
    }

    @Override
    public boolean hasNext() {
        while(pos < list.size()){
            if (list.get(pos).startsWith("a"))
                return true;
            pos++;
        }
        return false;

    }

    @Override
    public String next() {
        if (hasNext())
            return list.get(pos++);
        throw new NoSuchElementException();
    }
}

public class IteratorTest {

    public static void main(String[] args) {
        List<String> list = Arrays.asList("alice", "bob", "abigail", "charlie");
        ListIterator itr = new ListIterator(list);

        while(itr.hasNext())
            System.out.println(itr.next()); // prints alice, abigail
    }
}
  • ListIterator is the iterator for the array which returns the elements that start with 'a'.
  • There is no need for implementing an Iterable interface. But that is a possibility.
  • There is no need to implement this generically.
  • It fully satisfies the contract for hasNext() and next(). ie if hasNext() says there are still elements, next() will return those elements. And if hasNext() says no more elements, it returns a valid NoSuchElementException exception.

Comparing two arrays & get the values which are not common

PS > $c = Compare-Object -ReferenceObject (1..5) -DifferenceObject (1..6) -PassThru
PS > $c
6

CSS Background image not loading

I had the same issue. The problem ended up being the path to the image file. Make sure the image path is relative to the location of the CSS file instead of the HTML.

Programmatically obtain the phone number of the Android phone

Sometimes, below code returns null or blank string.

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

With below permission

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

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;
        // This is the phoneNumber
        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!

How (and why) to use display: table-cell (CSS)

It's even easier to use parent > child selector relationship so the inner div do not need to have their css classes to be defined explicitly:

_x000D_
_x000D_
.display-table {_x000D_
    display: table; _x000D_
}_x000D_
.display-table > div { _x000D_
    display: table-row; _x000D_
}_x000D_
.display-table > div > div { _x000D_
    display: table-cell;_x000D_
    padding: 5px;_x000D_
}
_x000D_
<div class="display-table">_x000D_
    <div>_x000D_
        <div>0, 0</div>_x000D_
        <div>0, 1</div>_x000D_
    </div>_x000D_
    <div>_x000D_
        <div>1, 0</div>_x000D_
        <div>1, 1</div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to extract a value from a string using regex and a shell?

you can use the shell(bash for example)

$ string="12 BBQ ,45 rofl, 89 lol"
$ echo ${string% rofl*}
12 BBQ ,45
$ string=${string% rofl*}
$ echo ${string##*,}
45

Right HTTP status code to wrong input

404 - Not Found - can be used for The URI requested is invalid or the resource requested such as a user, does not exists.

pull out p-values and r-squared from a linear regression

This is the easiest way to pull the p-values:

coef(summary(modelname))[, "Pr(>|t|)"]

how to use free cloud database with android app?

Now there are a lot of cloud providers , providing solutions like MBaaS (Mobile Backend as a Service). Some only give access to cloud database, some will do the user management for you, some let you place code around cloud database and there are facilities of access control, push notifications, analytics, integrated image and file hosting etc.

Here are some providers which have a "free-tier" (may change in future):

  1. Firebase (Google) - https://firebase.google.com/
  2. AWS Mobile (Amazon) - https://aws.amazon.com/mobile/
  3. Azure Mobile (Microsoft) - https://azure.microsoft.com/en-in/services/app-service/mobile/
  4. MongoDB Realm (MongoDB) - https://www.mongodb.com/realm
  5. Back4app (Popular) - https://www.back4app.com/

Open source solutions:

  1. Parse - http://parseplatform.org/
  2. Apache User Grid - https://usergrid.apache.org/
  3. SupaBase (under development) - https://supabase.io/

Convert string date to timestamp in Python

>>> int(datetime.datetime.strptime('01/12/2011', '%d/%m/%Y').strftime("%s"))
1322683200

Open link in new tab or window

It shouldn't be your call to decide whether the link should open in a new tab or a new window, since ultimately this choice should be done by the settings of the user's browser. Some people like tabs; some like new windows.

Using _blank will tell the browser to use a new tab/window, depending on the user's browser configuration and how they click on the link (e.g. middle click, Ctrl+click, or normal click).

Simple Deadlock Examples

Deadlock can occur in a situation when a Girl1 is wanting to flirt with Guy2, who is caught by another Girl2, and Girl2 is wanting to flirt with a Guy1 that is caught by Girl1. Since, both girls are waiting for dumping each other, the condition is called deadlock.

class OuchTheGirls
{
    public static void main(String[] args)
    {
        final String resource1 = "Guy1";
        final String resource2 = "Guy2";

        // Girl1 tries to lock resource1 then resource2
        Thread Girl1 = new Thread(() ->
                                  {
                                      synchronized (resource1)
                                      {
                                          System.out.println("Thread 1: locked Guy1");

                                          try { Thread.sleep(100);} catch (Exception e) {}

                                          synchronized (resource2)
                                          {
                                              System.out.println("Thread 1: locked Guy2");
                                          }
                                      }
                                  });

        // Girl2 tries to lock Guy2 then Guy1
        Thread Girl2 = new Thread(() ->
                                  {
                                      synchronized (resource2)
                                      {
                                          System.out.println("Thread 2: locked Guy2");

                                          try { Thread.sleep(100);} catch (Exception e) {}

                                          synchronized (resource1)
                                          {
                                              System.out.println("Thread 2: locked Guy1");
                                          }
                                      }
                                  });


        Girl1.start();
        Girl2.start();
    }
}

AVD Manager - No system image installed for this target

Open your Android SDK Manager and ensure that you download/install a system image for the API level you are developing with.

Returning JSON from a PHP Script

Try json_encode to encode the data and set the content-type with header('Content-type: application/json');.

How to add files/folders to .gitignore in IntelliJ IDEA?

I'm using intelliJ 15 community edition and I'm able to right click a file and select 'add to .gitignore'

PHP - Copy image to my server direct from URL

This SO thread will solve your problem. Solution in short:

$url = 'http://www.google.co.in/intl/en_com/images/srpr/logo1w.png';
$img = '/my/folder/my_image.gif';
file_put_contents($img, file_get_contents($url));

MongoDB: How To Delete All Records Of A Collection in MongoDB Shell?

db.users.count()
db.users.remove({})
db.users.count()

Insert Multiple Rows Into Temp Table With SQL Server 2012

When using SQLFiddle, make sure that the separator is set to GO. Also the schema build script is executed in a different connection from the run script, so a temp table created in the one is not visible in the other. This fiddle shows that your code is valid and working in SQL 2012:

SQL Fiddle

MS SQL Server 2012 Schema Setup:

Query 1:

CREATE TABLE #Names
  ( 
    Name1 VARCHAR(100),
    Name2 VARCHAR(100)
  ) 

INSERT INTO #Names
  (Name1, Name2)
VALUES
  ('Matt', 'Matthew'),
  ('Matt', 'Marshal'),
  ('Matt', 'Mattison')

SELECT * FROM #NAMES

Results:

| NAME1 |    NAME2 |
--------------------
|  Matt |  Matthew |
|  Matt |  Marshal |
|  Matt | Mattison |

Here a SSMS 2012 screenshot: enter image description here

How to stop the Timer in android?

In java.util.timer one can use .cancel() to stop the timer and clear all pending tasks.

error: could not create '/usr/local/lib/python2.7/dist-packages/virtualenv_support': Permission denied

Use

sudo pip install virtualenv

Apparently you will have powers of administrator when adding "sudo" before the line... just don't forget your password.

Creating a PHP header/footer

Just create the header.php file, and where you want to use it do:

<?php
include('header.php');
?>

Same with the footer. You don't need php tags in these files if you just have html.

See more about include here:

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

Accessing the logged-in user in a template

{{ app.user.username|default('') }}

Just present login username for example, filter function default('') should be nice when user is NOT login by just avoid annoying error message.

Build fails with "Command failed with a nonzero exit code"

In my case, I was clean build folder then restart my mac then it's work.

How can I specify the default JVM arguments for programs I run from eclipse?

As far as I know there is no option to create global configuration for java applications. You always create a duplicate of the configuration.

enter image description here

Also, if you are using PDE (for plugin development), you can create target platform using windows -> Preferences -> Plug-in development -> Target Platform. Edit has options for program/vm arguments.

Hope this helps

CSS Selector "(A or B) and C"?

No. Standard CSS does not provide the kind of thing you're looking for.

However, you might want to look into LESS and SASS.

These are two projects which aim to extend default CSS syntax by introducing additional features, including variables, nested rules, and other enhancements.

They allow you to write much more structured CSS code, and either of them will almost certainly solve your particular use case.

Of course, none of the browsers support their extended syntax (especially since the two projects each have different syntax and features), but what they do is provide a "compiler" which converts your LESS or SASS code into standard CSS, which you can then deploy on your site.

How do I delete everything in Redis?

Its better if you can have RDM (Redis Desktop Manager). You can connect to your redis server by creating a new connection in RDM.

Once its connected you can check the live data, also you can play around with any redis command.

Opening a cli in RDM.

1) Right click on the connection you will see a console option, just click on it a new console window will open at the bottom of RDM.

Coming back to your question FLUSHALL is the command, you can simply type FLUSHALL in the redis cli.

Moreover if you want to know about any redis command and its proper usage, go to link below. https://redis.io/commands.

Check if string has space in between (or anywhere)

Trim() will only remove leading or trailing spaces.

Try .Contains() to check if a string contains white space

"sossjjs sskkk".Contains(" ") // returns true

File path issues in R using Windows ("Hex digits in character string" error)

The best way to deal with this in case of txt file which contains data for text mining (speech, newsletter, etc.) is to replace "\" with "/".

Example:

file<-Corpus(DirSource("C:/Users/PRATEEK/Desktop/training tool/Text Analytics/text_file_main"))

Close/kill the session when the browser or tab is closed

As you said the event window.onbeforeunload fires when the users clicks on a link or refreshes the page, so it would not a good even to end a session.

http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx describes all situations where window.onbeforeonload is triggered. (IE)

However, you can place a JavaScript global variable on your pages to identify actions that should not trigger a logoff (by using an AJAX call from onbeforeonload, for example).

The script below relies on JQuery

/*
* autoLogoff.js
*
* Every valid navigation (form submit, click on links) should
* set this variable to true.
*
* If it is left to false the page will try to invalidate the
* session via an AJAX call
*/
var validNavigation = false;

/*
* Invokes the servlet /endSession to invalidate the session.
* No HTML output is returned
*/
function endSession() {
   $.get("<whatever url will end your session>");
}

function wireUpEvents() {

  /*
  * For a list of events that triggers onbeforeunload on IE
  * check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
  */
  window.onbeforeunload = function() {
      if (!validNavigation) {
         endSession();
      }
  }

  // Attach the event click for all links in the page
  $("a").bind("click", function() {
     validNavigation = true;
  });

  // Attach the event submit for all forms in the page
  $("form").bind("submit", function() {
     validNavigation = true;
  });

}

// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
    wireUpEvents();  
});

This script may be included in all pages

<script type="text/javascript" src="js/autoLogoff.js"></script>

Let's go through this code:

  var validNavigation = false;

  window.onbeforeunload = function() {
      if (!validNavigation) {
         endSession();
      }
  }

  // Attach the event click for all links in the page
  $("a").bind("click", function() {
     validNavigation = true;
  });

  // Attach the event submit for all forms in the page
  $("form").bind("submit", function() {
     validNavigation = true;
  });

A global variable is defined at page level. If this variable is not set to true then the event windows.onbeforeonload will terminate the session.

An event handler is attached to every link and form in the page to set this variable to true, thus preventing the session from being terminated if the user is just submitting a form or clicking on a link.

function endSession() {
   $.get("<whatever url will end your session>");
}

The session is terminated if the user closed the browser/tab or navigated away. In this case the global variable was not set to true and the script will do an AJAX call to whichever URL you want to end the session

This solution is server-side technology agnostic. It was not exaustively tested but it seems to work fine in my tests

Java Byte Array to String to Byte Array

Its simple to convert byte array to string and string back to byte array in java. we need to know when to use 'new' in the right way. It can be done as follows:

byte array to string conversion:

byte[] bytes = initializeByteArray();
String str = new String(bytes);

String to byte array conversion:

String str = "Hello"
byte[] bytes = str.getBytes();

For more details, look at: http://evverythingatonce.blogspot.in/2014/01/tech-talkbyte-array-and-string.html

CSS force image resize and keep aspect ratio

This is mental. Use the scale-down property - it explains itself.

Inline styling:

<img src='/nic-cage.png' style={{ maxWidth: '50%', objectFit: 'scale-down' }} />

This will stop flex from stretching it. In this case, the image would go to 50% of the width of its parent container and the height would scale down to match.

Keep it simple.

WCF change endpoint address at runtime

app.config

<client>
    <endpoint address="" binding="basicHttpBinding" 
    bindingConfiguration="LisansSoap" 
    contract="Lisans.LisansSoap" 
    name="LisansSoap" />
</client>

program

 Lisans.LisansSoapClient test = new LisansSoapClient("LisansSoap",
                         "http://webservis.uzmanevi.com/Lisans/Lisans.asmx");

 MessageBox.Show(test.LisansKontrol("","",""));

Find all files in a directory with extension .txt in Python

Python v3.5+

Fast method using os.scandir in a recursive function. Searches for all files with a specified extension in folder and sub-folders. It is fast, even for finding 10,000s of files.

I have also included a function to convert the output to a Pandas Dataframe.

import os
import re
import pandas as pd
import numpy as np


def findFilesInFolderYield(path,  extension, containsTxt='', subFolders = True, excludeText = ''):
    """  Recursive function to find all files of an extension type in a folder (and optionally in all subfolders too)

    path:               Base directory to find files
    extension:          File extension to find.  e.g. 'txt'.  Regular expression. Or  'ls\d' to match ls1, ls2, ls3 etc
    containsTxt:        List of Strings, only finds file if it contains this text.  Ignore if '' (or blank)
    subFolders:         Bool.  If True, find files in all subfolders under path. If False, only searches files in the specified folder
    excludeText:        Text string.  Ignore if ''. Will exclude if text string is in path.
    """
    if type(containsTxt) == str: # if a string and not in a list
        containsTxt = [containsTxt]
    
    myregexobj = re.compile('\.' + extension + '$')    # Makes sure the file extension is at the end and is preceded by a .
    
    try:   # Trapping a OSError or FileNotFoundError:  File permissions problem I believe
        for entry in os.scandir(path):
            if entry.is_file() and myregexobj.search(entry.path): # 
    
                bools = [True for txt in containsTxt if txt in entry.path and (excludeText == '' or excludeText not in entry.path)]
    
                if len(bools)== len(containsTxt):
                    yield entry.stat().st_size, entry.stat().st_atime_ns, entry.stat().st_mtime_ns, entry.stat().st_ctime_ns, entry.path
    
            elif entry.is_dir() and subFolders:   # if its a directory, then repeat process as a nested function
                yield from findFilesInFolderYield(entry.path,  extension, containsTxt, subFolders)
    except OSError as ose:
        print('Cannot access ' + path +'. Probably a permissions error ', ose)
    except FileNotFoundError as fnf:
        print(path +' not found ', fnf)

def findFilesInFolderYieldandGetDf(path,  extension, containsTxt, subFolders = True, excludeText = ''):
    """  Converts returned data from findFilesInFolderYield and creates and Pandas Dataframe.
    Recursive function to find all files of an extension type in a folder (and optionally in all subfolders too)

    path:               Base directory to find files
    extension:          File extension to find.  e.g. 'txt'.  Regular expression. Or  'ls\d' to match ls1, ls2, ls3 etc
    containsTxt:        List of Strings, only finds file if it contains this text.  Ignore if '' (or blank)
    subFolders:         Bool.  If True, find files in all subfolders under path. If False, only searches files in the specified folder
    excludeText:        Text string.  Ignore if ''. Will exclude if text string is in path.
    """
    
    fileSizes, accessTimes, modificationTimes, creationTimes , paths  = zip(*findFilesInFolderYield(path,  extension, containsTxt, subFolders))
    df = pd.DataFrame({
            'FLS_File_Size':fileSizes,
            'FLS_File_Access_Date':accessTimes,
            'FLS_File_Modification_Date':np.array(modificationTimes).astype('timedelta64[ns]'),
            'FLS_File_Creation_Date':creationTimes,
            'FLS_File_PathName':paths,
                  })
    
    df['FLS_File_Modification_Date'] = pd.to_datetime(df['FLS_File_Modification_Date'],infer_datetime_format=True)
    df['FLS_File_Creation_Date'] = pd.to_datetime(df['FLS_File_Creation_Date'],infer_datetime_format=True)
    df['FLS_File_Access_Date'] = pd.to_datetime(df['FLS_File_Access_Date'],infer_datetime_format=True)

    return df

ext =   'txt'  # regular expression 
containsTxt=[]
path = 'C:\myFolder'
df = findFilesInFolderYieldandGetDf(path,  ext, containsTxt, subFolders = True)

How to show uncommitted changes in Git and some Git diffs in detail

I had a situation of git status showing changes, but git diff printing nothing, although there were changes in several lines. However:

$ git diff data.txt > myfile
$ cat myfile
<prints diff>

Git 2.20.1 on raspbian. Other commands like git checkout, git pull are printing to stdout without problems.

Seaborn Barplot - Displaying Values

A simple way to do so is to add the below code (for Seaborn):

for p in splot.patches:
    splot.annotate(format(p.get_height(), '.1f'), 
                   (p.get_x() + p.get_width() / 2., p.get_height()), 
                   ha = 'center', va = 'center', 
                   xytext = (0, 9), 
                   textcoords = 'offset points') 

Example :

splot = sns.barplot(df['X'], df['Y'])
# Annotate the bars in plot
for p in splot.patches:
    splot.annotate(format(p.get_height(), '.1f'), 
                   (p.get_x() + p.get_width() / 2., p.get_height()), 
                   ha = 'center', va = 'center', 
                   xytext = (0, 9), 
                   textcoords = 'offset points')    
plt.show()

Recursive search and replace in text files on Mac and Linux

OS X uses a mix of BSD and GNU tools, so best always check the documentation (although I had it that less didn't even conform to the OS X manpage):

https://web.archive.org/web/20170808213955/https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man1/sed.1.html

sed takes the argument after -i as the extension for backups. Provide an empty string (-i '') for no backups.

The following should do:

LC_ALL=C find . -type f -name '*.txt' -exec sed -i '' s/this/that/ {} +

The -type f is just good practice; sed will complain if you give it a directory or so. -exec is preferred over xargs; you needn't bother with -print0 or anything. The {} + at the end means that find will append all results as arguments to one instance of the called command, instead of re-running it for each result. (One exception is when the maximal number of command-line arguments allowed by the OS is breached; in that case find will run more than one instance.)

How to create local notifications?

- (void)applicationDidEnterBackground:(UIApplication *)application
{
   UILocalNotification *notification = [[UILocalNotification alloc]init];
   notification.repeatInterval = NSDayCalendarUnit;
   [notification setAlertBody:@"Hello world"];
   [notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]];
   [notification setTimeZone:[NSTimeZone  defaultTimeZone]];
   [application setScheduledLocalNotifications:[NSArray arrayWithObject:notification]];
}

This is worked, but in iOS 8.0 and later, your application must register for user notifications using -[UIApplication registerUserNotificationSettings:] before being able to schedule and present UILocalNotifications, do not forget this.

tomcat - CATALINA_BASE and CATALINA_HOME variables

I can't say I know the best practice, but here's my perspective.

Are you using these variables for anything?

Personally, I haven't needed to change neither, on Linux nor Windows, in environments varying from development to production. Unless you are doing something particular that relies on them, chances are you could leave them alone.

catalina.sh sets the variables that Tomcat needs to work out of the box. It also says that CATALINA_BASE is optional:

#   CATALINA_HOME   May point at your Catalina "build" directory.
#
#   CATALINA_BASE   (Optional) Base directory for resolving dynamic portions
#                   of a Catalina installation.  If not present, resolves to
#                   the same directory that CATALINA_HOME points to.

I'm pretty sure you'll find out whether or not your setup works when you start your server.

How to solve ADB device unauthorized in Android ADB host device?

Check and uncheck the USB Debugging option in the device. If that doesn't work unplug and plug in the USB a couple of times.

At some point, the device should show a message box to ask you to authorize the computer. Click yes and then the device will be authorized.

jQuery How to Get Element's Margin and Padding?

Edit:

use jquery plugin: jquery.sizes.js

$('img').margin() or $('img').padding()

return:

{bottom: 10 ,left: 4 ,top: 0 ,right: 5}

get value:

$('img').margin().top

iptables LOG and DROP in one rule

Although already over a year old, I stumbled across this question a couple of times on other Google search and I believe I can improve on the previous answer for the benefit of others.

Short answer is you cannot combine both action in one line, but you can create a chain that does what you want and then call it in a one liner.

Let's create a chain to log and accept:

iptables -N LOG_ACCEPT

And let's populate its rules:

iptables -A LOG_ACCEPT -j LOG --log-prefix "INPUT:ACCEPT:" --log-level 6
iptables -A LOG_ACCEPT -j ACCEPT

Now let's create a chain to log and drop:

iptables -N LOG_DROP

And let's populate its rules:

iptables -A LOG_DROP -j LOG --log-prefix "INPUT:DROP: " --log-level 6
iptables -A LOG_DROP -j DROP

Now you can do all actions in one go by jumping (-j) to you custom chains instead of the default LOG / ACCEPT / REJECT / DROP:

iptables -A <your_chain_here> <your_conditions_here> -j LOG_ACCEPT
iptables -A <your_chain_here> <your_conditions_here> -j LOG_DROP

MassAssignmentException in Laravel

Use the fillable to tell laravel which fields can be filled using an array. By default, Laravel does not allow database fields to be updated via an array

Protected $fillable=array('Fields you want to fill using array');

The opposite of fillable is guardable.

Throwing multiple exceptions in a method of an interface in java

You need to specify it on the methods that can throw the exceptions. You just seperate them with a ',' if it can throw more than 1 type of exception. e.g.

public interface MyInterface {
  public MyObject find(int x) throws MyExceptionA,MyExceptionB;
}

Serialize and Deserialize Json and Json Array in Unity

You can use Newtonsoft.Json just add Newtonsoft.dll to your project and use below script

using System;
using Newtonsoft.Json;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{

    [Serializable]
    public class Person
    {
        public string id;
        public string name;
    }
    public Person[] person;

    private void Start()
    {
       var myjson = JsonConvert.SerializeObject(person);

        print(myjson);

    }
}

enter image description here

another solution is using JsonHelper

using System;
using Newtonsoft.Json;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{

    [Serializable]
    public class Person
    {
        public string id;
        public string name;
    }
    public Person[] person;

    private void Start()
    {
        var myjson = JsonHelper.ToJson(person);

        print(myjson);

    }
}

enter image description here

how to start stop tomcat server using CMD?

you can use this trick to run tomcat using cmd and directly by tomcat bin folder.

1. set the path of jdk.

2.

To set path. go to Desktop and right click on computer icon. Click the Properties

go to Advance System Settings.

then Click Advance to Environment variables.

Click new and set path AS,

in the column Variable name=JAVA_HOME

Variable Value=C:\Program Files\Java\jdk1.6.0_19

Click ok ok.

now path is stetted.

3.

Go to tomcat folder where you installed the tomcat. go to bin folder. there are two window batch files.

1.Startup

2.Shutdown.

By using cmd if you installed the tomcate in D Drive

type on cmd screen

  1. D:

  2. Cd tomcat\bin then type Startup.

4. By clicking them you can start and stop the tomcat.

5.

Final step.

if you start and want to check it.

open a Browser in URL bar type.

**HTTP://localhost:8080/**

TSQL - Cast string to integer or return default value

As has been mentioned, you may run into several issues if you use ISNUMERIC:

-- Incorrectly gives 0:
SELECT CASE WHEN ISNUMERIC('-') = 1 THEN CAST('-' AS INT) END   

-- Error (conversion failure):
SELECT CASE WHEN ISNUMERIC('$') = 1 THEN CAST('$' AS INT) END
SELECT CASE WHEN ISNUMERIC('4.4') = 1 THEN CAST('4.4' AS INT) END
SELECT CASE WHEN ISNUMERIC('1,300') = 1 THEN CAST('1,300' AS INT) END

-- Error (overflow):
SELECT CASE WHEN ISNUMERIC('9999999999') = 1 THEN CAST('9999999999' AS INT) END

If you want a reliable conversion, you'll need to code one yourself.

Update: My new recommendation would be to use an intermediary test conversion to FLOAT to validate the number. This approach is based on adrianm's comment. The logic can be defined as an inline table-valued function:

CREATE FUNCTION TryConvertInt (@text NVARCHAR(MAX)) 
RETURNS TABLE
AS
RETURN
(
    SELECT
        CASE WHEN ISNUMERIC(@text + '.e0') = 1 THEN 
             CASE WHEN CONVERT(FLOAT, @text) BETWEEN -2147483648 AND 2147483647 
                  THEN CONVERT(INT, @text) 
             END 
         END AS [Result]
)

Some tests:

SELECT [Conversion].[Result]
FROM ( VALUES
     ( '1234'                     )   -- 1234
   , ( '1,234'                    )   -- NULL
   , ( '1234.0'                   )   -- NULL
   , ( '-1234'                    )   -- -1234
   , ( '$1234'                    )   -- NULL
   , ( '1234e10'                  )   -- NULL
   , ( '1234 5678'                )   -- NULL
   , ( '123-456'                  )   -- NULL
   , ( '1234.5'                   )   -- NULL
   , ( '123456789000000'          )   -- NULL
   , ( 'N/A'                      )   -- NULL
   , ( '-'                        )   -- NULL
   , ( '$'                        )   -- NULL
   , ( '4.4'                      )   -- NULL
   , ( '1,300'                    )   -- NULL
   , ( '9999999999'               )   -- NULL
   , ( '00000000000000001234'     )   -- 1234
   , ( '212110090000000235698741' )   -- NULL
) AS [Source] ([Text])
OUTER APPLY TryConvertInt ([Source].[Text]) AS [Conversion]

Results are similar to Joseph Sturtevant's answer, with the following main differences:

  • My logic does not tolerate occurrences of . or , in order to mimic the behaviour of native INT conversions. '1,234' and '1234.0' return NULL.
  • Since it does not use local variables, my function can be defined as an inline table-valued function, allowing for better query optimization.
  • Joseph's answer can lead to incorrect results due to silent truncations of the argument; '00000000000000001234' evaluates to 12. Increasing the parameter length would result in errors on numbers that overflow BIGINT, such as BBANs (basic bank account numbers) like '212110090000000235698741'.

Withdrawn: The approach below is no longer recommended, as is left just for reference.

The snippet below works on non-negative integers. It checks that your string does not contain any non-digit characters, is not empty, and does not overflow (by exceeding the maximum value for the int type). However, it also gives NULL for valid integers whose length exceeds 10 characters due to leading zeros.

SELECT 
    CASE WHEN @text NOT LIKE '%[^0-9]%' THEN
         CASE WHEN LEN(@text) BETWEEN 1 AND 9 
                OR LEN(@text) = 10 AND @text <= '2147483647' 
              THEN CAST (@text AS INT)
         END
    END 

If you want to support any number of leading zeros, use the below. The nested CASE statements, albeit unwieldy, are required to promote short-circuit evaluation and reduce the likelihood of errors (arising, for example, from passing a negative length to LEFT).

SELECT 
    CASE WHEN @text NOT LIKE '%[^0-9]%' THEN
         CASE WHEN LEN(@text) BETWEEN 1 AND 9 THEN CAST (@text AS INT)
              WHEN LEN(@text) >= 10 THEN
              CASE WHEN LEFT(@text, LEN(@text) - 10) NOT LIKE '%[^0]%'
                    AND RIGHT(@text, 10) <= '2147483647'
                   THEN CAST (@text AS INT)
              END
         END
    END

If you want to support positive and negative integers with any number of leading zeros:

SELECT 
         -- Positive integers (or 0):
    CASE WHEN @text NOT LIKE '%[^0-9]%' THEN
         CASE WHEN LEN(@text) BETWEEN 1 AND 9 THEN CAST (@text AS INT)
              WHEN LEN(@text) >= 10 THEN
              CASE WHEN LEFT(@text, LEN(@text) - 10) NOT LIKE '%[^0]%'
                    AND RIGHT(@text, 10) <= '2147483647'
                   THEN CAST (@text AS INT)
              END
         END
         -- Negative integers:
         WHEN LEFT(@text, 1) = '-' THEN
         CASE WHEN RIGHT(@text, LEN(@text) - 1) NOT LIKE '%[^0-9]%' THEN
              CASE WHEN LEN(@text) BETWEEN 2 AND 10 THEN CAST (@text AS INT)
                   WHEN LEN(@text) >= 11 THEN
                   CASE WHEN SUBSTRING(@text, 2, LEN(@text) - 11) NOT LIKE '%[^0]%'
                         AND RIGHT(@text, 10) <= '2147483648'
                        THEN CAST (@text AS INT)
                   END
              END
         END
    END

how to check and set max_allowed_packet mysql variable

max_allowed_packet is set in mysql config, not on php side

[mysqld]
max_allowed_packet=16M 

You can see it's curent value in mysql like this:

SHOW VARIABLES LIKE 'max_allowed_packet';

You can try to change it like this, but it's unlikely this will work on shared hosting:

SET GLOBAL max_allowed_packet=16777216;

You can read about it here http://dev.mysql.com/doc/refman/5.1/en/packet-too-large.html

EDIT

The [mysqld] is necessary to make the max_allowed_packet working since at least mysql version 5.5.

Recently setup an instance on AWS EC2 with Drupal and Solr Search Engine, which required 32M max_allowed_packet. It you set the value under [mysqld_safe] (which is default settings came with the mysql installation) mode in /etc/my.cnf, it did no work. I did not dig into the problem. But after I change it to [mysqld] and restarted the mysqld, it worked.

Remove a string from the beginning of a string

Plain form, without regex:

$prefix = 'bla_';
$str = 'bla_string_bla_bla_bla';

if (substr($str, 0, strlen($prefix)) == $prefix) {
    $str = substr($str, strlen($prefix));
} 

Takes: 0.0369 ms (0.000,036,954 seconds)

And with:

$prefix = 'bla_';
$str = 'bla_string_bla_bla_bla';
$str = preg_replace('/^' . preg_quote($prefix, '/') . '/', '', $str);

Takes: 0.1749 ms (0.000,174,999 seconds) the 1st run (compiling), and 0.0510 ms (0.000,051,021 seconds) after.

Profiled on my server, obviously.

PostgreSQL function for last inserted ID

See the below example

CREATE TABLE users (
    -- make the "id" column a primary key; this also creates
    -- a UNIQUE constraint and a b+-tree index on the column
    id    SERIAL PRIMARY KEY,
    name  TEXT,
    age   INT4
);

INSERT INTO users (name, age) VALUES ('Mozart', 20);

Then for getting last inserted id use this for table "user" seq column name "id"

SELECT currval(pg_get_serial_sequence('users', 'id'));

Can we create an instance of an interface in Java?

Yes we can, "Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name"->>Java Doc

Open an html page in default browser with VBA?

You can use the Windows API function ShellExecute to do so:

Option Explicit

Private Declare Function ShellExecute _
  Lib "shell32.dll" Alias "ShellExecuteA" ( _
  ByVal hWnd As Long, _
  ByVal Operation As String, _
  ByVal Filename As String, _
  Optional ByVal Parameters As String, _
  Optional ByVal Directory As String, _
  Optional ByVal WindowStyle As Long = vbMinimizedFocus _
  ) As Long

Public Sub OpenUrl()

    Dim lSuccess As Long
    lSuccess = ShellExecute(0, "Open", "www.google.com")

End Sub

Just a short remark concerning security: If the URL comes from user input make sure to strictly validate that input as ShellExecute would execute any command with the user's permissions, also a format c: would be executed if the user is an administrator.

How to calculate the number of days between two dates?

Adjusted to allow for daylight saving differences. try this:

  function daysBetween(date1, date2) {

 // adjust diff for for daylight savings
 var hoursToAdjust = Math.abs(date1.getTimezoneOffset() /60) - Math.abs(date2.getTimezoneOffset() /60);
 // apply the tz offset
 date2.addHours(hoursToAdjust); 

    // The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24

    // Convert both dates to milliseconds
    var date1_ms = date1.getTime()
    var date2_ms = date2.getTime()

    // Calculate the difference in milliseconds
    var difference_ms = Math.abs(date1_ms - date2_ms)

    // Convert back to days and return
    return Math.round(difference_ms/ONE_DAY)

}

// you'll want this addHours function too 

Date.prototype.addHours= function(h){
    this.setHours(this.getHours()+h);
    return this;
}

Scrollview vertical and horizontal in android

I use it and works fine:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView android:id="@+id/ScrollView02" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content"
            xmlns:android="http://schemas.android.com/apk/res/android">
<HorizontalScrollView android:id="@+id/HorizontalScrollView01" 
                      android:layout_width="wrap_content" 
                      android:layout_height="wrap_content">
<ImageView android:id="@+id/ImageView01"
           android:src="@drawable/pic" 
           android:isScrollContainer="true" 
           android:layout_height="fill_parent" 
           android:layout_width="fill_parent" 
           android:adjustViewBounds="true">
</ImageView>
</HorizontalScrollView>
</ScrollView>

The source link is here: Android-spa

Join vs. sub-query

If you want to speed up your query using join:

For "inner join/join", Don't use where condition instead use it in "ON" condition. Eg:

     select id,name from table1 a  
   join table2 b on a.name=b.name
   where id='123'

 Try,

    select id,name from table1 a  
   join table2 b on a.name=b.name and a.id='123'

For "Left/Right Join", Don't use in "ON" condition, Because if you use left/right join it will get all rows for any one table.So, No use of using it in "On". So, Try to use "Where" condition

How can I debug what is causing a connection refused or a connection time out?

The problem

The problem is in the network layer. Here are the status codes explained:

  • Connection refused: The peer is not listening on the respective network port you're trying to connect to. This usually means that either a firewall is actively denying the connection or the respective service is not started on the other site or is overloaded.

  • Connection timed out: During the attempt to establish the TCP connection, no response came from the other side within a given time limit. In the context of urllib this may also mean that the HTTP response did not arrive in time. This is sometimes also caused by firewalls, sometimes by network congestion or heavy load on the remote (or even local) site.

In context

That said, it is probably not a problem in your script, but on the remote site. If it's occuring occasionally, it indicates that the other site has load problems or the network path to the other site is unreliable.

Also, as it is a problem with the network, you cannot tell what happened on the other side. It is possible that the packets travel fine in the one direction but get dropped (or misrouted) in the other.

It is also not a (direct) DNS problem, that would cause another error (Name or service not known or something similar). It could however be the case that the DNS is configured to return different IP addresses on each request, which would connect you (DNS caching left aside) to different addresses hosts on each connection attempt. It could in turn be the case that some of these hosts are misconfigured or overloaded and thus cause the aforementioned problems.

Debugging this

As suggested in the another answer, using a packet analyzer can help to debug the issue. You won't see much however except the packets reflecting exactly what the error message says.

To rule out network congestion as a problem you could use a tool like mtr or traceroute or even ping to see if packets get lost to the remote site. Note that, if you see loss in mtr (and any traceroute tool for that matter), you must always consider the first host where loss occurs (in the route from yours to remote) as the one dropping packets, due to the way ICMP works. If the packets get lost only at the last hop over a long time (say, 100 packets), that host definetly has an issue. If you see that this behaviour is persistent (over several days), you might want to contact the administrator.

Loss in a middle of the route usually corresponds to network congestion (possibly due to maintenance), and there's nothing you could do about it (except whining at the ISP about missing redundance).

If network congestion is not a problem (i.e. not more than, say, 5% of the packets get lost), you should contact the remote server administrator to figure out what's wrong. He may be able to see relevant infos in system logs. Running a packet analyzer on the remote site might also be more revealing than on the local site. Checking whether the port is open using netstat -tlp is definetly recommended then.

Aggregate function in SQL WHERE-Clause

UPDATED query:

select id from t where id < (select max(id) from t);

It'll select all but the last row from the table t.

Get current AUTO_INCREMENT value for any table

Even though methai's answer is correct if you manually run the query, a problem occurs when 2 concurrent transaction/connections actually execute this query at runtime in production (for instance).

Just tried manually in MySQL workbench with 2 connections opened simultaneously:

CREATE TABLE translation (
  id BIGINT PRIMARY KEY AUTO_INCREMENT
);
# Suppose we have already 20 entries, we execute 2 new inserts:

Transaction 1:

21 = SELECT `AUTO_INCREMENT` FROM INFORMATION_SCHEMA.TABLES
     WHERE TABLE_SCHEMA = 'DatabaseName' AND TABLE_NAME = 'translation';

insert into translation (id) values (21);

Transaction 2:

21 = SELECT `AUTO_INCREMENT` FROM INFORMATION_SCHEMA.TABLES
     WHERE TABLE_SCHEMA = 'DatabaseName' AND TABLE_NAME = 'translation';

insert into translation (id) values (21);

# commit transaction 1;
# commit transaction 2;

Insert of transaction 1 is ok: Insert of transaction 2 goes in error: Error Code: 1062. Duplicate entry '21' for key 'PRIMARY'.

A good solution would be jvdub's answer because per transaction/connection the 2 inserts will be:

Transaction 1:

insert into translation (id) values (null);
21 = SELECT LAST_INSERT_ID();

Transaction 2:

insert into translation (id) values (null);
22 = SELECT LAST_INSERT_ID();

# commit transaction 1;
# commit transaction 2;

But we have to execute the last_insert_id() just after the insert! And we can reuse that id to be inserted in others tables where a foreign key is expected!

Also, we cannot execute the 2 queries as following:

insert into translation (id) values ((SELECT AUTO_INCREMENT FROM
    information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE()
    AND TABLE_NAME='translation'));

because we actually are interested to grab/reuse that ID in other table or to return!

Examples of good gotos in C or C++

#include <stdio.h>
#include <string.h>

int main()
{
    char name[64];
    char url[80]; /*The final url name with http://www..com*/
    char *pName;
    int x;

    pName = name;

    INPUT:
    printf("\nWrite the name of a web page (Without www, http, .com) ");
    gets(name);

    for(x=0;x<=(strlen(name));x++)
        if(*(pName+0) == '\0' || *(pName+x) == ' ')
        {
            printf("Name blank or with spaces!");
            getch();
            system("cls");
            goto INPUT;
        }

    strcpy(url,"http://www.");
    strcat(url,name);
    strcat(url,".com");

    printf("%s",url);
    return(0);
}

How to check whether the user uploaded a file in PHP?

You can use is_uploaded_file():

if(!file_exists($_FILES['myfile']['tmp_name']) || !is_uploaded_file($_FILES['myfile']['tmp_name'])) {
    echo 'No upload';
}

From the docs:

Returns TRUE if the file named by filename was uploaded via HTTP POST. This is useful to help ensure that a malicious user hasn't tried to trick the script into working on files upon which it should not be working--for instance, /etc/passwd.

This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system.

EDIT: I'm using this in my FileUpload class, in case it helps:

public function fileUploaded()
{
    if(empty($_FILES)) {
        return false;       
    } 
    $this->file = $_FILES[$this->formField];
    if(!file_exists($this->file['tmp_name']) || !is_uploaded_file($this->file['tmp_name'])){
        $this->errors['FileNotExists'] = true;
        return false;
    }   
    return true;
}

Does functional programming replace GoF design patterns?

I would say that when you have a language like Lisp with its support for macros, then you can build you own domain-specific abstractions, abstractions which often are much better than the general idiom solutions.

In vb.net, how to get the column names from a datatable

' i modify the code for Datatable 

For Each c as DataColumn in dt.Columns
 For j=0 To _dataTable.Columns.Count-1
            xlWorksheet.Cells (i+1, j+1) = _dataTable.Columns(j).ColumnName
Next
Next

Hope this could be help!

How to index an element of a list object in R

Indexing a list is done using double bracket, i.e. hypo_list[[1]] (e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table does not return a table but a dataframe (see value section in ?read.table). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.

Note: In R, the index for the first entry is a 1 (not 0 like in some other languages).

Dataframes

l <- list(anscombe, iris)   # put dfs in list
l[[1]]             # returns anscombe dataframe

anscombe[1:2, 2]   # access first two rows and second column of dataset
[1] 10  8

l[[1]][1:2, 2]     # the same but selecting the dataframe from the list first
[1] 10  8

Table objects

tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2)  # put tables in a list

tbl1[1:2]              # access first two elements of table 1 

Now with the list

l[[1]]                 # access first table from the list

1  2  3  4  5 
9 11 12  9  9 

l[[1]][1:2]            # access first two elements in first table

1  2 
9 11 

How can I make my own event in C#?

to do it we have to know the three components

  1. the place responsible for firing the Event
  2. the place responsible for responding to the Event
  3. the Event itself

    a. Event

    b .EventArgs

    c. EventArgs enumeration

now lets create Event that fired when a function is called

but I my order of solving this problem like this: I'm using the class before I create it

  1. the place responsible for responding to the Event

    NetLog.OnMessageFired += delegate(object o, MessageEventArgs args) 
    {
            // when the Event Happened I want to Update the UI
            // this is WPF Window (WPF Project)  
            this.Dispatcher.Invoke(() =>
            {
                LabelFileName.Content = args.ItemUri;
                LabelOperation.Content = args.Operation;
                LabelStatus.Content = args.Status;
            });
    };
    

NetLog is a static class I will Explain it later

the next step is

  1. the place responsible for firing the Event

    //this is the sender object, MessageEventArgs Is a class I want to create it  and Operation and Status are Event enums
    NetLog.FireMessage(this, new MessageEventArgs("File1.txt", Operation.Download, Status.Started));
    downloadFile = service.DownloadFile(item.Uri);
    NetLog.FireMessage(this, new MessageEventArgs("File1.txt", Operation.Download, Status.Finished));
    

the third step

  1. the Event itself

I warped The Event within a class called NetLog

public sealed class NetLog
{
    public delegate void MessageEventHandler(object sender, MessageEventArgs args);

    public static event MessageEventHandler OnMessageFired;
    public static void FireMessage(Object obj,MessageEventArgs eventArgs)
    {
        if (OnMessageFired != null)
        {
            OnMessageFired(obj, eventArgs);
        }
    }
}

public class MessageEventArgs : EventArgs
{
    public string ItemUri { get; private set; }
    public Operation Operation { get; private set; }
    public Status Status { get; private set; }

    public MessageEventArgs(string itemUri, Operation operation, Status status)
    {
        ItemUri = itemUri;
        Operation = operation;
        Status = status;
    }
}

public enum Operation
{
    Upload,Download
}

public enum Status
{
    Started,Finished
}

this class now contain the Event, EventArgs and EventArgs Enums and the function responsible for firing the event

sorry for this long answer

Difference between Activity Context and Application Context

I think when everything need a screen to show ( button, dialog,layout...) we have to use context activity, and everything doesn't need a screen to show or process ( toast, service telelphone,contact...) we could use a application context

Convert output of MySQL query to utf8

Addition:

When using the MySQL client library, then you should prevent a conversion back to your connection's default charset. (see mysql_set_character_set()[1])

In this case, use an additional cast to binary:

SELECT column1, CAST(CONVERT(column2 USING utf8) AS binary)
FROM my_table
WHERE my_condition;

Otherwise, the SELECT statement converts to utf-8, but your client library converts it back to a (potentially different) default connection charset.

fork() child and parent processes

We control fork() process call by if, else statement. See my code below:

int main()
{
   int forkresult, parent_ID;

   forkresult=fork();
   if(forkresult !=0 )
   {
        printf(" I am the parent my ID is = %d" , getpid());
        printf(" and my child ID is = %d\n" , forkresult);
   }
   parent_ID = getpid();

   if(forkresult ==0)
      printf(" I am the  child ID is = %d",getpid());
   else
      printf(" and my parent ID is = %d", parent_ID);
}

How can I get javascript to read from a .json file?

NOTICE: AS OF JULY 12TH, 2018, THE OTHER ANSWERS ARE ALL OUTDATED. JSONP IS NOW CONSIDERED A TERRIBLE IDEA

If you have your JSON as a string, JSON.parse() will work fine. Since you are loading the json from a file, you will need to do a XMLHttpRequest to it. For example (This is w3schools.com example):

_x000D_
_x000D_
var xmlhttp = new XMLHttpRequest();_x000D_
xmlhttp.onreadystatechange = function() {_x000D_
    if (this.readyState == 4 && this.status == 200) {_x000D_
        var myObj = JSON.parse(this.responseText);_x000D_
        document.getElementById("demo").innerHTML = myObj.name;_x000D_
    }_x000D_
};_x000D_
xmlhttp.open("GET", "json_demo.txt", true);_x000D_
xmlhttp.send();
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<h2>Use the XMLHttpRequest to get the content of a file.</h2>_x000D_
<p>The content is written in JSON format, and can easily be converted into a JavaScript object.</p>_x000D_
_x000D_
<p id="demo"></p>_x000D_
_x000D_
_x000D_
<p>Take a look at <a href="json_demo.txt" target="_blank">json_demo.txt</a></p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

It will not work here as that file isn't located here. Go to this w3schools example though: https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax

Here is the documentation for JSON.parse(): https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

Here's a summary:

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

Here's the example used:

_x000D_
_x000D_
var json = '{"result":true, "count":42}';_x000D_
obj = JSON.parse(json);_x000D_
_x000D_
console.log(obj.count);_x000D_
// expected output: 42_x000D_
_x000D_
console.log(obj.result);_x000D_
// expected output: true
_x000D_
_x000D_
_x000D_

Here is a summary on XMLHttpRequests from https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest:

Use XMLHttpRequest (XHR) objects to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in Ajax programming.

If you don't want to use XMLHttpRequests, then a JQUERY way (which I'm not sure why it isn't working for you) is http://api.jquery.com/jQuery.getJSON/

Since it isn't working, I'd try using XMLHttpRequests

You could also try AJAX requests:

$.ajax({
    'async': false,
    'global': false,
    'url': "/jsonfile.json",
    'dataType': "json",
    'success': function (data) {
        // do stuff with data
    }
});

Documentation: http://api.jquery.com/jquery.ajax/

Default value in Go's method

No, the powers that be at Google chose not to support that.

https://groups.google.com/forum/#!topic/golang-nuts/-5MCaivW0qQ

How to add google-services.json in Android?

WINDOWS

  1. Open Terminal window in Android Studio (Alt+F12 or View->Tool Windows->Terminal). Then type

"move file_path/google-services.json app/"

without double quotes.

eg

move C:\Users\siva\Downloads\google-services.json app/

LINUX

  1. Open Android Studio Terminal and type this

scp file_path/google-services.json app/

eg:

scp '/home/developer/Desktop/google-services.json' 'app/'

Python non-greedy regexes

>>> x = "a (b) c (d) e"
>>> re.search(r"\(.*\)", x).group()
'(b) c (d)'
>>> re.search(r"\(.*?\)", x).group()
'(b)'

According to the docs:

The '*', '+', and '?' qualifiers are all greedy; they match as much text as possible. Sometimes this behavior isn’t desired; if the RE <.*> is matched against '<H1>title</H1>', it will match the entire string, and not just '<H1>'. Adding '?' after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using .*? in the previous expression will match only '<H1>'.

OAuth: how to test with local URLs?

Or you can use https://tolocalhost.com/ and configure how it should redirect a callback to your local site. You can specify the hostname (if different from localhost, i.e. yourapp.local and the port number). For development purposes only.

how to check if a datareader is null or empty

First of all, you probably want to check for a DBNull not a regular Null.

Or you could look at the IsDBNull method

How to resolve git error: "Updates were rejected because the tip of your current branch is behind"

I had this issue and I realized that .gitignore file is changed. So, I changed .gitignore and I could pull the changes.

Convert hex string to int in Python

with '0x' prefix, you might also use eval function

For example

>>a='0xff'
>>eval(a)
255

How can I create a "Please Wait, Loading..." animation using jQuery?

Along with what Jonathan and Samir suggested (both excellent answers btw!), jQuery has some built in events that it'll fire for you when making an ajax request.

There's the ajaxStart event

Show a loading message whenever an AJAX request starts (and none is already active).

...and it's brother, the ajaxStop event

Attach a function to be executed whenever all AJAX requests have ended. This is an Ajax Event.

Together, they make a fine way to show a progress message when any ajax activity is happening anywhere on the page.

HTML:

<div id="loading">
  <p><img src="loading.gif" /> Please Wait</p>
</div>

Script:

$(document).ajaxStart(function(){
    $('#loading').show();
 }).ajaxStop(function(){
    $('#loading').hide();
 });

src absolute path problem

Use forward slashes. See explanation here

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

If you still cannot solve your problem have a look at this. This might be the solution you are looking for

There are several php.ini files in C:\wamp\bin\php\php x-y-z folder. You may find production, development and some other php.ini files. No point of editing production and development files. Find the file which is exactly as same as the below image. (You can find it. Just type php.ini in your search bar and do a search). Open the file and remove ; from extension=php_openssl.dll. Save the file and close it. Restart all services in Wampp server. Re-install your composer.

That is it.

enter image description here

Good Hash Function for Strings

This function provided by Nick is good but if you use new String(byte[] bytes) to make the transformation to String, it failed. You can use this function to do that.

private static final char[] hex = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

public static String byteArray2Hex(byte[] bytes) {
    StringBuffer sb = new StringBuffer(bytes.length * 2);
    for(final byte b : bytes) {
        sb.append(hex[(b & 0xF0) >> 4]);
        sb.append(hex[b & 0x0F]);
    }
    return sb.toString();
}

public static String getStringFromSHA256(String stringToEncrypt) throws NoSuchAlgorithmException {
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
    messageDigest.update(stringToEncrypt.getBytes());
    return byteArray2Hex(messageDigest.digest());
}

May be this can help somebody

Should I use typescript? or I can just use ES6?

Decision tree between ES5, ES6 and TypeScript

Do you mind having a build step?

  • Yes - Use ES5
  • No - keep going

Do you want to use types?

  • Yes - Use TypeScript
  • No - Use ES6

More Details

ES5 is the JavaScript you know and use in the browser today it is what it is and does not require a build step to transform it into something that will run in today's browsers

ES6 (also called ES2015) is the next iteration of JavaScript, but it does not run in today's browsers. There are quite a few transpilers that will export ES5 for running in browsers. It is still a dynamic (read: untyped) language.

TypeScript provides an optional typing system while pulling in features from future versions of JavaScript (ES6 and ES7).

Note: a lot of the transpilers out there (i.e. babel, TypeScript) will allow you to use features from future versions of JavaScript today and exporting code that will still run in today's browsers.

Force "portrait" orientation mode

Short answer: Don't do it.

Redesign your app so that it can run in both portrait and landscape mode. There is no such thing as a UI that can't be designed to work in both portrait and landscape; only lazy or unimaginative developers.

The reason why is rather simple. You want your app to be usable by as wide an audience as possible on as many different devices as possible. By forcing a particular screen orientation, you prevent your app from running (usably) on devices that don't support that orientation and you frustrate and alienate potential customers who prefer a different orientation.

Example: You design your app to force portrait mode. A customer downloads the app on a 2-in-1 device which they use predominantly in landscape mode.
Consequence 1: Your app is unusable, or your customer is forced to undock their device, rotate it, and use it in an orientation that is not familiar or comfortable for them.
Consequence 2: The customer gets frustrated by your app's non-intuitive design and finds an alternative or ditches the app entirely.

I'm fighting with this with an app right now and as a consumer and a developer, I hate it. As useful as the app is, as fantastic as the features are that it offers, I absolutely hate the app because it forces me to use an orientation that is counter to every other way that I use my device.

You don't want your customers to hate your app.


I know this doesn't directly answer the question, so I want to explain it in a little more detail for those who are curious.

There is a tendency for developers to be really good at writing code and really terrible at design. This question, though it sounds like a code question and the asker certainly feels like it's a code question, is really a design question.

The question really is "Should I lock the screen orientation in my app?" The asker chose to design the UI to function and look good only in portrait mode. I suspect it was to save development time or because the app's workflow is particularly conducive to a portrait layout (common for mobile games). But those reasons neglect all the real important factors that motivate proper design.

  1. Customer engagement - you want your customers to feel pulled into your app, not pushed out of it. The app should transition smoothly from whatever your customer was doing prior to opening your app. (This is the reason most platforms have consistent design principles, so most apps look more or less alike though they don't have to.)

  2. Customer response - you want your customers to react positively to your app. They should enjoy using it. Even if it's a payroll app for work, it should be a pleasure for them to open it and clock in. The app should save your customers time and reduce frustration over alternatives. (Apps that annoy users build resentment against your app which grows into resentment against your brand.)

  3. Customer conversion - you want your customers to be able to quickly and easily move from browsing to interacting. This is the ultimate goal of any app, to convert impressions into revenue. (Apps that don't generate revenue are a waste of your time to build, from a business perspective.)

A poorly designed UI reduces customer engagement and response which ultimately results in lower revenue. In a mobile-centric world (and particularly on the subject of portrait/landscape display modes), this explains why responsive web design is such a big deal. Walmart Canada introduced responsive design on their website in November 2013 and saw a 20% increase in customer conversion. O'Neill Clothing implemented responsive web design and revenue from customers using iOS devices increased 101.25%, and 591.42% from customers using Android devices.

There is also a tendency for developers to focus intently on implementing a particular solution (such as locking display orientation), and most of the developers on this site will be all too glad to help implement that solution, without questioning whether that is even the best solution to the problem.

Locking your screen orientation is the UI design equivalent of implementing a do-while loop. Are you really sure you want to do it that way, or is there a better alternative?

Don't force your app into a single display mode. Invest the extra time and effort to make it responsive.

Adding event listeners to dynamically added elements using jQuery

You are dynamically generating those elements so any listener applied on page load wont be available. I have edited your fiddle with the correct solution. Basically jQuery holds the event for later binding by attaching it to the parent Element and propagating it downward to the correct dynamically created element.

$('#musics').on('change', '#want',function(e) {
    $(this).closest('.from-group').val(($('#want').is(':checked')) ? "yes" : "no");
    var ans=$(this).val();
    console.log(($('#want').is(':checked')));
});

http://jsfiddle.net/swoogie/1rkhn7ek/39/

Upload files from Java client to a HTTP server

Here is how you would do it with Apache HttpClient (this solution is for those who don't mind using a 3rd party library):

    HttpEntity entity = MultipartEntityBuilder.create()
                       .addPart("file", new FileBody(file))
                       .build();

    HttpPost request = new HttpPost(url);
    request.setEntity(entity);

    HttpClient client = HttpClientBuilder.create().build();
    HttpResponse response = client.execute(request);

How can I access and process nested objects, arrays or JSON?

Objects and arrays has a lot of built-in methods that can help you with processing data.

Note: in many of the examples I'm using arrow functions. They are similar to function expressions, but they bind the this value lexically.

Object.keys(), Object.values() (ES 2017) and Object.entries() (ES 2017)

Object.keys() returns an array of object's keys, Object.values() returns an array of object's values, and Object.entries() returns an array of object's keys and corresponding values in a format [key, value].

_x000D_
_x000D_
const obj = {_x000D_
  a: 1_x000D_
 ,b: 2_x000D_
 ,c: 3_x000D_
}_x000D_
_x000D_
console.log(Object.keys(obj)) // ['a', 'b', 'c']_x000D_
console.log(Object.values(obj)) // [1, 2, 3]_x000D_
console.log(Object.entries(obj)) // [['a', 1], ['b', 2], ['c', 3]]
_x000D_
_x000D_
_x000D_

Object.entries() with a for-of loop and destructuring assignment

_x000D_
_x000D_
const obj = {_x000D_
  a: 1_x000D_
 ,b: 2_x000D_
 ,c: 3_x000D_
}_x000D_
_x000D_
for (const [key, value] of Object.entries(obj)) {_x000D_
  console.log(`key: ${key}, value: ${value}`)_x000D_
}
_x000D_
_x000D_
_x000D_

It's very convenient to iterate the result of Object.entries() with a for-of loop and destructuring assignment.

For-of loop lets you iterate array elements. The syntax is for (const element of array) (we can replace const with var or let, but it's better to use const if we don't intend to modify element).

Destructuring assignment lets you extract values from an array or an object and assign them to variables. In this case const [key, value] means that instead of assigning the [key, value] array to element, we assign the first element of that array to key and the second element to value. It is equivalent to this:

for (const element of Object.entries(obj)) {
  const key = element[0]
       ,value = element[1]
}

As you can see, destructuring makes this a lot simpler.

Array.prototype.every() and Array.prototype.some()

The every() method returns true if the specified callback function returns true for every element of the array. The some() method returns true if the specified callback function returns true for some (at least one) element.

_x000D_
_x000D_
const arr = [1, 2, 3]_x000D_
_x000D_
// true, because every element is greater than 0_x000D_
console.log(arr.every(x => x > 0))_x000D_
// false, because 3^2 is greater than 5_x000D_
console.log(arr.every(x => Math.pow(x, 2) < 5))_x000D_
// true, because 2 is even (the remainder from dividing by 2 is 0)_x000D_
console.log(arr.some(x => x % 2 === 0))_x000D_
// false, because none of the elements is equal to 5_x000D_
console.log(arr.some(x => x === 5))
_x000D_
_x000D_
_x000D_

Array.prototype.find() and Array.prototype.filter()

The find() methods returns the first element which satisfies the provided callback function. The filter() method returns an array of all elements which satisfies the provided callback function.

_x000D_
_x000D_
const arr = [1, 2, 3]_x000D_
_x000D_
// 2, because 2^2 !== 2_x000D_
console.log(arr.find(x => x !== Math.pow(x, 2)))_x000D_
// 1, because it's the first element_x000D_
console.log(arr.find(x => true))_x000D_
// undefined, because none of the elements equals 7_x000D_
console.log(arr.find(x => x === 7))_x000D_
_x000D_
// [2, 3], because these elements are greater than 1_x000D_
console.log(arr.filter(x => x > 1))_x000D_
// [1, 2, 3], because the function returns true for all elements_x000D_
console.log(arr.filter(x => true))_x000D_
// [], because none of the elements equals neither 6 nor 7_x000D_
console.log(arr.filter(x => x === 6 || x === 7))
_x000D_
_x000D_
_x000D_

Array.prototype.map()

The map() method returns an array with the results of calling a provided callback function on the array elements.

_x000D_
_x000D_
const arr = [1, 2, 3]_x000D_
_x000D_
console.log(arr.map(x => x + 1)) // [2, 3, 4]_x000D_
console.log(arr.map(x => String.fromCharCode(96 + x))) // ['a', 'b', 'c']_x000D_
console.log(arr.map(x => x)) // [1, 2, 3] (no-op)_x000D_
console.log(arr.map(x => Math.pow(x, 2))) // [1, 4, 9]_x000D_
console.log(arr.map(String)) // ['1', '2', '3']
_x000D_
_x000D_
_x000D_

Array.prototype.reduce()

The reduce() method reduces an array to a single value by calling the provided callback function with two elements.

_x000D_
_x000D_
const arr = [1, 2, 3]_x000D_
_x000D_
// Sum of array elements._x000D_
console.log(arr.reduce((a, b) => a + b)) // 6_x000D_
// The largest number in the array._x000D_
console.log(arr.reduce((a, b) => a > b ? a : b)) // 3
_x000D_
_x000D_
_x000D_

The reduce() method takes an optional second parameter, which is the initial value. This is useful when the array on which you call reduce() can has zero or one elements. For example, if we wanted to create a function sum() which takes an array as an argument and returns the sum of all elements, we could write it like that:

_x000D_
_x000D_
const sum = arr => arr.reduce((a, b) => a + b, 0)_x000D_
_x000D_
console.log(sum([]))     // 0_x000D_
console.log(sum([4]))    // 4_x000D_
console.log(sum([2, 5])) // 7
_x000D_
_x000D_
_x000D_

Node.js: Gzip compression?

If you're using Express, then you can use its compress method as part of the configuration:

var express = require('express');
var app = express.createServer();
app.use(express.compress());

And you can find more on compress here: http://expressjs.com/api.html#compress

And if you're not using Express... Why not, man?! :)

NOTE: (thanks to @ankitjaininfo) This middleware should be one of the first you "use" to ensure all responses are compressed. Ensure that this is above your routes and static handler (eg. how I have it above).

NOTE: (thanks to @ciro-costa) Since express 4.0, the express.compress middleware is deprecated. It was inherited from connect 3.0 and express no longer includes connect 3.0. Check Express Compression for getting the middleware.

Drop data frame columns by name

Dplyr Solution

I doubt this will get much attention down here, but if you have a list of columns that you want to remove, and you want to do it in a dplyr chain I use one_of() in the select clause:

Here is a simple, reproducable example:

undesired <- c('mpg', 'cyl', 'hp')

mtcars <- mtcars %>%
  select(-one_of(undesired))

Documentation can be found by running ?one_of or here:

http://genomicsclass.github.io/book/pages/dplyr_tutorial.html

How to stop/cancel 'git log' command in terminal?

You can hit the key q (for quit) and it should take you to the prompt.

Please see this link.

Is it possible to have empty RequestParam values use the defaultValue?

You could change the @RequestParam type to an Integer and make it not required. This would allow your request to succeed, but it would then be null. You could explicitly set it to your default value in the controller method:

@RequestMapping(value = "/test", method = RequestMethod.POST)
@ResponseBody
public void test(@RequestParam(value = "i", required=false) Integer i) {
    if(i == null) {
        i = 10;
    }
    // ...
}

I have removed the defaultValue from the example above, but you may want to include it if you expect to receive requests where it isn't set at all:

http://example.com/test

Redis - Connect to Remote Server

I've been stuck with the same issue, and the preceding answer did not help me (albeit well written).

The solution is here : check your /etc/redis/redis.conf, and make sure to change the default

bind 127.0.0.1

to

bind 0.0.0.0

Then restart your service (service redis-server restart)

You can then now check that redis is listening on non-local interface with

redis-cli -h 192.168.x.x ping

(replace 192.168.x.x with your IP adress)

Important note : as several users stated, it is not safe to set this on a server which is exposed to the Internet. You should be certain that you redis is protected with any means that fits your needs.

How can I create a Java method that accepts a variable number of arguments?

The following will create a variable length set of arguments of the type of string:

print(String arg1, String... arg2)

You can then refer to arg2 as an array of Strings. This is a new feature in Java 5.

Read response headers from API response - Angular 5 + TypeScript

Have you exposed the X-Token from server side using access-control-expose-headers? because not all headers are allowed to be accessed from the client side, you need to expose them from the server side

Also in your frontend, you can use new HTTP module to get a full response using {observe: 'response'} like

http
  .get<any>('url', {observe: 'response'})
  .subscribe(resp => {
    console.log(resp.headers.get('X-Token'));
  });

Getting the PublicKeyToken of .Net assemblies

You can add this as an external tool to Visual Studio like so:

Title:

Get PublicKeyToken

Command:

c:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools\sn.exe

(Path may differ between versions)

Arguments:

-T "$(TargetPath)"

And check the "Use Output window" option.

List of standard lengths for database fields

I just queried my database with millions of customers in the USA.

  • The maximum first name length was 46. I go with 50. (Of course, only 500 of those were over 25, and they were all cases where data imports resulted in extra junk winding up in that field.)

  • Last name was similar to first name.

  • Email addresses maxed out at 62 characters. Most of the longer ones were actually lists of email addresses separated by semicolons.

  • Street address maxes out at 95 characters. The long ones were all valid.

  • Max city length was 35.

This should be a decent statistical spread for people in the US. If you have localization to consider, the numbers could vary significantly.

Create a list with initial capacity in Python

def doAppend( size=10000 ):
    result = []
    for i in range(size):
        message= "some unique object %d" % ( i, )
        result.append(message)
    return result

def doAllocate( size=10000 ):
    result=size*[None]
    for i in range(size):
        message= "some unique object %d" % ( i, )
        result[i]= message
    return result

Results. (evaluate each function 144 times and average the duration)

simple append 0.0102
pre-allocate  0.0098

Conclusion. It barely matters.

Premature optimization is the root of all evil.

How to update a single pod without touching other dependencies

pod update POD_NAME will update latest pod but not update Podfile.lock file.

So, you may update your Podfile with specific version of your pod e.g pod 'POD_NAME', '~> 2.9.0' and then use command pod install

Later, you can remove the specific version naming from your Podfile and can again use pod install. This will helps to keep Podfile.lock updated.

Free FTP Library

I've just posted an article that presents both an FTP client class and an FTP user control.

They are simple and aren't very fast, but are very easy to use and all source code is included. Just drop the user control onto a form to allow users to navigate FTP directories from your application.

How do Python's any and all functions work?

list = [1,1,1,0]
print(any(list)) # will return True because there is  1 or True exists
print(all(list)) # will return False because there is a 0 or False exists
return all(a % i for i in range(3, int(a ** 0.5) + 1)) # when number is divisible it will return False else return True but the whole statement is False .

Make multiple-select to adjust its height to fit options without scroll bar

I know the question is old, but how the topic is not closed I'll give my help.

The attribute "size" will resolve your problem.

Example:

<select name="courses" multiple="multiple" size="30">

Create a table without a header in Markdown

Universal Solution

Many of the suggestions unfortunately do not work for all Markdown viewers/editors, for instance, the popular Markdown Viewer Chrome extension, but they do work with iA Writer.

What does seem to work across both of these popular programs (and might work for your particular application) is to use HTML comment blocks ('<!-- -->'):

| <!-- -->    | <!-- -->    |
|-------------|-------------|
| Foo         | Bar         |

Like some of the earlier suggestions stated, this does add an empty header row in your Markdown viewer/editor. In iA Writer, it's aesthetically small enough that it doesn't get in my way too much.

WCFTestClient The HTTP request is unauthorized with client authentication scheme 'Anonymous'

I had the same error today, after deploying our service calling an external service to the staging environment in azure. Local the service called the external service without errors, but after deployment it didn't.

In the end it turned out to be that the external service has a IP validation. The new environment in Azure has another IP and it was rejected.

So if you ever get this error calling external services

It might be an IP restriction.

Running Windows batch file commands asynchronously

Combining a couple of the previous answers, you could try start /b cmd /c foo.exe.

For a trivial example, if you wanted to print out the versions of java/groovy/grails/gradle, you could do this in a batch file:

@start /b cmd /c java -version
@start /b cmd /c gradle -version
@start /b cmd /c groovy -version
@start /b cmd /c grails -version

If you have something like Process Explorer (Sysinternals), you will see a few child cmd.exe processes each with a java process (as per the above commands). The output will print to the screen in whatever order they finish.

start /b :  Start application without creating a new window. The
             application has ^C handling ignored. Unless the application
             enables ^C processing, ^Break is the only way to interrupt
             the application

cmd /c : Carries out the command specified by string and then terminates

How can I change the width and height of slides on Slick Carousel?

I found good solution myself. Since slick slider is still used nowadays i'll post my approach.

@RuivBoas answer is partly correct. - It can change the width of the slide but it can break the slider. Why?

Slick slider may exceed browser width. Actual container width is set to value that can accomodate all it's slides.

The best solution for setting slide width is to use width of the actual browser window. It works best with responsive design.

For example 2 slides with absorbed width

CSS

.slick-slide {
    width: 50vw;
    // for absorbing width from @Ken Wheeler answer
    box-sizing: border-box;
}

JS

$(document).on('ready', function () {
            $("#container").slick({
                variableWidth: true,
                slidesToShow: 2,
                slidesToScroll: 2
            });
        });

HTML markup

<div id="container">
    <div><img/></div>
    <div><img/></div>
    <div><img/></div>
</div>

How to Convert string "07:35" (HH:MM) to TimeSpan

While correct that this will work:

TimeSpan time = TimeSpan.Parse("07:35");

And if you are using it for validation...

TimeSpan time;
if (!TimeSpan.TryParse("07:35", out time))
{
    // handle validation error
}

Consider that TimeSpan is primarily intended to work with elapsed time, rather than time-of-day. It will accept values larger than 24 hours, and will accept negative values also.

If you need to validate that the input string is a valid time-of-day (>= 00:00 and < 24:00), then you should consider this instead:

DateTime dt;
if (!DateTime.TryParseExact("07:35", "HH:mm", CultureInfo.InvariantCulture, 
                                              DateTimeStyles.None, out dt))
{
    // handle validation error
}
TimeSpan time = dt.TimeOfDay;

As an added benefit, this will also parse 12-hour formatted times when an AM or PM is included, as long as you provide the appropriate format string, such as "h:mm tt".

Google Maps API - Get Coordinates of address

A Nuget solved my problem:Geocoding.Google 4.0.0. Install it so not necessary to write extra classes etc.

https://www.nuget.org/packages/Geocoding.Google/

Determine on iPhone if user has enabled push notifications

re:

this is correct

if (types & UIRemoteNotificationTypeAlert)

but following is correct too ! (as UIRemoteNotificationTypeNone is 0 )

if (types == UIRemoteNotificationTypeNone) 

see the following

NSLog(@"log:%d",0 & 0); ///false
NSLog(@"log:%d",1 & 1); ///true
NSLog(@"log:%d",1<<1 & 1<<1); ///true
NSLog(@"log:%d",1<<2 & 1<<2); ///true
NSLog(@"log:%d",(0 & 0) && YES); ///false
NSLog(@"log:%d",(1 & 1) && YES); ///true
NSLog(@"log:%d",(1<<1 & 1<<1) && YES); ///true
NSLog(@"log:%d",(1<<2 & 1<<2) && YES); ///true

Error: No toolchains found in the NDK toolchains folder for ABI with prefix: llvm

Steps I have followed to fix the issue as follows,

Analyze -> Code Cleanup

File -> Project Structures -> Select project from the list and update the gradle version to latest.

Build -> Clean Project

Build -> Make Project

Now the issue related to the build may get reported like using compile instead of implementation etc.

Please fix those and hopefully it should fix the issue.

C# binary literals

You can use 0b000001 since Visual Studio 2017 (C# 7.0)

Firestore Getting documents id from collection

doc.id gets the UID.

Combine with the rest of the data for one object like so:

Object.assign({ uid: doc.id }, doc.data())

java.lang.ClassNotFoundException: org.apache.log4j.Level

In my environment, I just added the two files to class path. And is work fine.

slf4j-jdk14-1.7.25.jar
slf4j-api-1.7.25.jar

Object Required Error in excel VBA

The Set statement is only used for object variables (like Range, Cell or Worksheet in Excel), while the simple equal sign '=' is used for elementary datatypes like Integer. You can find a good explanation for when to use set here.

The other problem is, that your variable g1val isn't actually declared as Integer, but has the type Variant. This is because the Dim statement doesn't work the way you would expect it, here (see example below). The variable has to be followed by its type right away, otherwise its type will default to Variant. You can only shorten your Dim statement this way:

Dim intColumn As Integer, intRow As Integer  'This creates two integers

For this reason, you will see the "Empty" instead of the expected "0" in the Watches window.

Try this example to understand the difference:

Sub Dimming()

  Dim thisBecomesVariant, thisIsAnInteger As Integer
  Dim integerOne As Integer, integerTwo As Integer

  MsgBox TypeName(thisBecomesVariant)  'Will display "Empty"
  MsgBox TypeName(thisIsAnInteger )  'Will display "Integer"
  MsgBox TypeName(integerOne )  'Will display "Integer"
  MsgBox TypeName(integerTwo )  'Will display "Integer"

  'By assigning an Integer value to a Variant it becomes Integer, too
  thisBecomesVariant = 0
  MsgBox TypeName(thisBecomesVariant)  'Will display "Integer"

End Sub

Two further notices on your code:

First remark: Instead of writing

'If g1val is bigger than the value in the current cell
If g1val > Cells(33, i).Value Then
  g1val = g1val   'Don't change g1val
Else
  g1val = Cells(33, i).Value  'Otherwise set g1val to the cell's value
End If

you could simply write

'If g1val is smaller or equal than the value in the current cell
If g1val <= Cells(33, i).Value Then
  g1val = Cells(33, i).Value  'Set g1val to the cell's value 
End If

Since you don't want to change g1val in the other case.

Second remark: I encourage you to use Option Explicit when programming, to prevent typos in your program. You will then have to declare all variables and the compiler will give you a warning if a variable is unknown.

VSCode single to double quote automatic replace

Well for me both options solved the issue:

  1. By adding inside the .prettierrc - "singleQuote": true

  2. Or by adding following inside the package.json -> "prettier": { "singleQuote": true }

Though I tried also adding .prettierrc.js and have following

module.exports = { singleQuote: true };

This didn't worked.

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in

The problem is your query returned false meaning there was an error in your query. After your query you could do the following:

if (!$result) {
    die(mysqli_error($link));
}

Or you could combine it with your query:

$results = mysqli_query($link, $query) or die(mysqli_error($link));

That will print out your error.

Also... you need to sanitize your input. You can't just take user input and put that into a query. Try this:

$query = "SELECT * FROM shopsy_db WHERE name LIKE '%" . mysqli_real_escape_string($link, $searchTerm) . "%'";

In reply to: Table 'sookehhh_shopsy_db.sookehhh_shopsy_db' doesn't exist

Are you sure the table name is sookehhh_shopsy_db? maybe it's really like users or something.

Set Content-Type to application/json in jsp file

Try this piece of code, it should work too

<%
    //response.setContentType("Content-Type", "application/json"); // this will fail compilation
    response.setContentType("application/json"); //fixed
%>

How can I know if Object is String type object?

Its possible you don't need to know depending on what you are doing with it.

String myString = object.toString();

or if object can be null

String myString = String.valueOf(object);

Android Image View Pinch Zooming

Custom zoom view in Kotlin

 import android.content.Context
 import android.graphics.Matrix
 import android.graphics.PointF
 import android.util.AttributeSet
 import android.util.Log
 import android.view.MotionEvent
 import android.view.ScaleGestureDetector
 import android.view.ScaleGestureDetector.SimpleOnScaleGestureListener
 import androidx.appcompat.widget.AppCompatImageView

 class ZoomImageview : AppCompatImageView {
var matri: Matrix? = null
var mode = NONE

// Remember some things for zooming
var last = PointF()
var start = PointF()
var minScale = 1f
var maxScale = 3f
lateinit var m: FloatArray
var viewWidth = 0
var viewHeight = 0
var saveScale = 1f
protected var origWidth = 0f
protected var origHeight = 0f
var oldMeasuredWidth = 0
var oldMeasuredHeight = 0
var mScaleDetector: ScaleGestureDetector? = null
var contex: Context? = null

constructor(context: Context) : super(context) {
    sharedConstructing(context)
}

constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
    sharedConstructing(context)
}

private fun sharedConstructing(context: Context) {
    super.setClickable(true)
    this.contex= context
    mScaleDetector = ScaleGestureDetector(context, ScaleListener())
    matri = Matrix()
    m = FloatArray(9)
    imageMatrix = matri
    scaleType = ScaleType.MATRIX
    setOnTouchListener { v, event ->
        mScaleDetector!!.onTouchEvent(event)
        val curr = PointF(event.x, event.y)
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                last.set(curr)
                start.set(last)
                mode = DRAG
            }
            MotionEvent.ACTION_MOVE -> if (mode == DRAG) {
                val deltaX = curr.x - last.x
                val deltaY = curr.y - last.y
                val fixTransX = getFixDragTrans(deltaX, viewWidth.toFloat(), origWidth * saveScale)
                val fixTransY = getFixDragTrans(deltaY, viewHeight.toFloat(), origHeight * saveScale)
                matri!!.postTranslate(fixTransX, fixTransY)
                fixTrans()
                last[curr.x] = curr.y
            }
            MotionEvent.ACTION_UP -> {
                mode = NONE
                val xDiff = Math.abs(curr.x - start.x).toInt()
                val yDiff = Math.abs(curr.y - start.y).toInt()
                if (xDiff < CLICK && yDiff < CLICK) performClick()
            }
            MotionEvent.ACTION_POINTER_UP -> mode = NONE
        }
        imageMatrix = matri
        invalidate()
        true // indicate event was handled
    }
}

fun setMaxZoom(x: Float) {
    maxScale = x
}

private inner class ScaleListener : SimpleOnScaleGestureListener() {
    override fun onScaleBegin(detector: ScaleGestureDetector): Boolean {
        mode = ZOOM
        return true
    }

    override fun onScale(detector: ScaleGestureDetector): Boolean {
        var mScaleFactor = detector.scaleFactor
        val origScale = saveScale
        saveScale *= mScaleFactor
        if (saveScale > maxScale) {
            saveScale = maxScale
            mScaleFactor = maxScale / origScale
        } else if (saveScale < minScale) {
            saveScale = minScale
            mScaleFactor = minScale / origScale
        }
        if (origWidth * saveScale <= viewWidth || origHeight * saveScale <= viewHeight) matri!!.postScale(mScaleFactor, mScaleFactor, viewWidth / 2.toFloat(), viewHeight / 2.toFloat()) else matri!!.postScale(mScaleFactor, mScaleFactor, detector.focusX, detector.focusY)
        fixTrans()
        return true
    }
}

fun fixTrans() {
    matri!!.getValues(m)
    val transX = m[Matrix.MTRANS_X]
    val transY = m[Matrix.MTRANS_Y]
    val fixTransX = getFixTrans(transX, viewWidth.toFloat(), origWidth * saveScale)
    val fixTransY = getFixTrans(transY, viewHeight.toFloat(), origHeight * saveScale)
    if (fixTransX != 0f || fixTransY != 0f) matri!!.postTranslate(fixTransX, fixTransY)
}

fun getFixTrans(trans: Float, viewSize: Float, contentSize: Float): Float {
    val minTrans: Float
    val maxTrans: Float
    if (contentSize <= viewSize) {
        minTrans = 0f
        maxTrans = viewSize - contentSize
    } else {
        minTrans = viewSize - contentSize
        maxTrans = 0f
    }
    if (trans < minTrans) return -trans + minTrans
    if (trans > maxTrans) return -trans + maxTrans
    return 0f
}

fun getFixDragTrans(delta: Float, viewSize: Float, contentSize: Float): Float {
    if (contentSize <= viewSize) {
        return 0f
    } else {
        return delta
    }
}

override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    viewWidth = MeasureSpec.getSize(widthMeasureSpec)
    viewHeight = MeasureSpec.getSize(heightMeasureSpec)
    //
    // Rescales image on rotation
    //
    if (oldMeasuredHeight == viewWidth && oldMeasuredHeight == viewHeight || viewWidth == 0 || viewHeight == 0) return
    oldMeasuredHeight = viewHeight
    oldMeasuredWidth = viewWidth
    if (saveScale == 1f) {
        //Fit to screen.
        val scale: Float
        val drawable = drawable
        if (drawable == null || drawable.intrinsicWidth == 0 || drawable.intrinsicHeight == 0) return
        val bmWidth = drawable.intrinsicWidth
        val bmHeight = drawable.intrinsicHeight
        Log.d("bmSize", "bmWidth: $bmWidth bmHeight : $bmHeight")
        val scaleX = viewWidth.toFloat() / bmWidth.toFloat()
        val scaleY = viewHeight.toFloat() / bmHeight.toFloat()
        scale = Math.min(scaleX, scaleY)
        matri!!.setScale(scale, scale)
        // Center the image
        var redundantYSpace = viewHeight.toFloat() - scale * bmHeight.toFloat()
        var redundantXSpace = viewWidth.toFloat() - scale * bmWidth.toFloat()
        redundantYSpace /= 2.toFloat()
        redundantXSpace /= 2.toFloat()
        matri!!.postTranslate(redundantXSpace, redundantYSpace)
        origWidth = viewWidth - 2 * redundantXSpace
        origHeight = viewHeight - 2 * redundantYSpace
        imageMatrix = matri
    }
    fixTrans()
}

companion object {
    // We can be in one of these 3 states
    const val NONE = 0
    const val DRAG = 1
    const val ZOOM = 2
    const val CLICK = 3
}
 }

What are the differences between JSON and JSONP?

JSONP is JSON with padding. That is, you put a string at the beginning and a pair of parentheses around it. For example:

//JSON
{"name":"stackoverflow","id":5}
//JSONP
func({"name":"stackoverflow","id":5});

The result is that you can load the JSON as a script file. If you previously set up a function called func, then that function will be called with one argument, which is the JSON data, when the script file is done loading. This is usually used to allow for cross-site AJAX with JSON data. If you know that example.com is serving JSON files that look like the JSONP example given above, then you can use code like this to retrieve it, even if you are not on the example.com domain:

function func(json){
  alert(json.name);
}
var elm = document.createElement("script");
elm.setAttribute("type", "text/javascript");
elm.src = "http://example.com/jsonp";
document.body.appendChild(elm);

Laravel Eloquent ORM Transactions

For some reason it is quite difficult to find this information anywhere, so I decided to post it here, as my issue, while related to Eloquent transactions, was exactly changing this.

After reading THIS stackoverflow answer, I realized my database tables were using MyISAM instead of InnoDB.

For transactions to work on Laravel (or anywhere else as it seems), it is required that your tables are set to use InnoDB

Why?

Quoting MySQL Transactions and Atomic Operations docs (here):

MySQL Server (version 3.23-max and all versions 4.0 and above) supports transactions with the InnoDB and BDB transactional storage engines. InnoDB provides full ACID compliance. See Chapter 14, Storage Engines. For information about InnoDB differences from standard SQL with regard to treatment of transaction errors, see Section 14.2.11, “InnoDB Error Handling”.

The other nontransactional storage engines in MySQL Server (such as MyISAM) follow a different paradigm for data integrity called “atomic operations.” In transactional terms, MyISAM tables effectively always operate in autocommit = 1 mode. Atomic operations often offer comparable integrity with higher performance.

Because MySQL Server supports both paradigms, you can decide whether your applications are best served by the speed of atomic operations or the use of transactional features. This choice can be made on a per-table basis.

Django set default form values

Other solution: Set initial after creating the form:

form.fields['tank'].initial = 123

How to properly stop the Thread in Java?

You should always end threads by checking a flag in the run() loop (if any).

Your thread should look like this:

public class IndexProcessor implements Runnable {

    private static final Logger LOGGER = LoggerFactory.getLogger(IndexProcessor.class);
    private volatile boolean execute;

    @Override
    public void run() {
        this.execute = true;
        while (this.execute) {
            try {
                LOGGER.debug("Sleeping...");
                Thread.sleep((long) 15000);

                LOGGER.debug("Processing");
            } catch (InterruptedException e) {
                LOGGER.error("Exception", e);
                this.execute = false;
            }
        }
    }

    public void stopExecuting() {
        this.execute = false;
    }
}

Then you can end the thread by calling thread.stopExecuting(). That way the thread is ended clean, but this takes up to 15 seconds (due to your sleep). You can still call thread.interrupt() if it's really urgent - but the prefered way should always be checking the flag.

To avoid waiting for 15 seconds, you can split up the sleep like this:

        ...
        try {
            LOGGER.debug("Sleeping...");
            for (int i = 0; (i < 150) && this.execute; i++) {
                Thread.sleep((long) 100);
            }

            LOGGER.debug("Processing");
        } catch (InterruptedException e) {
        ...

Resize external website content to fit iFrame width

Tip for 1 website resizing the height. But you can change to 2 websites.

Here is my code to resize an iframe with an external website. You need insert a code into the parent (with iframe code) page and in the external website as well, so, this won't work with you don't have access to edit the external website.

  • local (iframe) page: just insert a code snippet
  • remote (external) page: you need a "body onload" and a "div" that holds all contents. And body needs to be styled to "margin:0"

Local:

<IFRAME STYLE="width:100%;height:1px" SRC="http://www.remote-site.com/" FRAMEBORDER="no" BORDER="0" SCROLLING="no" ID="estframe"></IFRAME>

<SCRIPT>
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
  if (e.data.substring(0,3)=='frm') document.getElementById('estframe').style.height = e.data.substring(3) + 'px';
},false);
</SCRIPT>

You need this "frm" prefix to avoid problems with other embeded codes like Twitter or Facebook plugins. If you have a plain page, you can remove the "if" and the "frm" prefix on both pages (script and onload).

Remote:

You need jQuery to accomplish about "real" page height. I cannot realize how to do with pure JavaScript since you'll have problem when resize the height down (higher to lower height) using body.scrollHeight or related. For some reason, it will return always the biggest height (pre-redimensioned).

<BODY onload="parent.postMessage('frm'+$('#master').height(),'*')" STYLE="margin:0">
<SCRIPT SRC="path-to-jquery/jquery.min.js"></SCRIPT>
<DIV ID="master">
your content
</DIV>

So, parent page (iframe) has a 1px default height. The script inserts a "wait for message/event" from the iframe. When a message (post message) is received and the first 3 chars are "frm" (to avoid the mentioned problem), will get the number from 4th position and set the iframe height (style), including 'px' unit.

The external site (loaded in the iframe) will "send a message" to the parent (opener) with the "frm" and the height of the main div (in this case id "master"). The "*" in postmessage means "any source".

Hope this helps. Sorry for my english.

What is ".NET Core"?

Microsoft recognized the future web open source paradigm and decided to open .NET to other operating systems. .NET Core is a .NET Framework for Mac and Linux. It is a “lightweight” .NET Framework, so some features/libraries are missing.

On Windows, I would still run .NET Framework and Visual Studio 2015. .NET Core is more friendly with the open source world like Node.js, npm, Yeoman, Docker, etc.

You can develop full-fledged web sites and RESTful APIs on Mac or Linux with Visual Studio Code + .NET Core which wasn't possible before. So if you love Mac or Ubuntu and you are a .NET developer then go ahead and set it up.

For Mono vs. .NET Core, Mono was developed as a .NET Framework for Linux which is now acquired by Microsoft (company called Xamarin) and used in mobile development. Eventually, Microsoft may merge/migrate Mono to .NET Core. I would not worry about Mono right now.

SQL search multiple values in same field

Yes, you can use SQL IN operator to search multiple absolute values:

SELECT name FROM products WHERE name IN ( 'Value1', 'Value2', ... );

If you want to use LIKE you will need to use OR instead:

SELECT name FROM products WHERE name LIKE '%Value1' OR name LIKE '%Value2';

Using AND (as you tried) requires ALL conditions to be true, using OR requires at least one to be true.

String concatenation in MySQL

MySQL is different from most DBMSs use of + or || for concatenation. It uses the CONCAT function:

SELECT CONCAT(first_name, " ", last_name) AS Name FROM test.student

As @eggyal pointed out in comments, you can enable string concatenation with the || operator in MySQL by setting the PIPES_AS_CONCAT SQL mode.

AVD Manager - Cannot Create Android Virtual Device

I actually hit on this problem a week ago. The issue had to do with not using an updated Eclipse version of the Android SDK plugin with the latest version of the SDK. It was a fun problem overall, but it disappeared as soon as I updated it.

I had even updated the AVD images and no luck. Apparently the old plugin cannot see the new image layout or something. This is for version 22.3 of the SDK.

How to specify the current directory as path in VBA?

I thought I had misunderstood but I was right. In this scenario, it will be ActiveWorkbook.Path

But the main issue was not here. The problem was with these 2 lines of code

strFile = Dir(strPath & "*.csv")

Which should have written as

strFile = Dir(strPath & "\*.csv")

and

With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _

Which should have written as

With .QueryTables.Add(Connection:="TEXT;" & strPath & "\" & strFile, _

Attempted to read or write protected memory

I had the same problem after upgrading from .NET 4.5 to .NET 4.5.1. What fixed it for me was running this command:

netsh winsock reset

Convert txt to csv python script

This is how I do it:

 with open(txtfile, 'r') as infile, open(csvfile, 'w') as outfile:
        stripped = (line.strip() for line in infile)
        lines = (line.split(",") for line in stripped if line)
        writer = csv.writer(outfile)
        writer.writerows(lines)

Hope it helps!

What's the difference between a mock & stub?

Stubs are used on methods with an expected return value which you setup in your test. Mocks are used on void methods which are verified in the Assert that they are called.

How can I import a database with MySQL from terminal?

Assuming you're on a Linux or Windows console:

Prompt for password:

mysql -u <username> -p <databasename> < <filename.sql>

Enter password directly (not secure):

mysql -u <username> -p<PlainPassword> <databasename> < <filename.sql>

Example:

mysql -u root -p wp_users < wp_users.sql

mysql -u root -pPassword123 wp_users < wp_users.sql

See also:

4.5.1.5. Executing SQL Statements from a Text File


Note: If you are on windows then you will have to cd (change directory) to your MySQL/bin directory inside the CMD before executing the command.

Upload failed You need to use a different version code for your APK because you already have one with version code 2

In my app/build.gradle file , version code was like this:-

build.gradle(app module) file

In place of versionCode flutterVersionCode.toInteger() , i replaced it with as versionCode 2

Convenient way to parse incoming multipart/form-data parameters in a Servlet

multipart/form-data encoded requests are indeed not by default supported by the Servlet API prior to version 3.0. The Servlet API parses the parameters by default using application/x-www-form-urlencoded encoding. When using a different encoding, the request.getParameter() calls will all return null. When you're already on Servlet 3.0 (Glassfish 3, Tomcat 7, etc), then you can use HttpServletRequest#getParts() instead. Also see this blog for extended examples.

Prior to Servlet 3.0, a de facto standard to parse multipart/form-data requests would be using Apache Commons FileUpload. Just carefully read its User Guide and Frequently Asked Questions sections to learn how to use it. I've posted an answer with a code example before here (it also contains an example targeting Servlet 3.0).

matrix multiplication algorithm time complexity

In matrix multiplication there are 3 for loop, we are using since execution of each for loop requires time complexity O(n). So for three loops it becomes O(n^3)

Update row with data from another row in the same table

Here's my go:

UPDATE test as t1 
    INNER JOIN test as t2 ON 
        t1.NAME = t2.NAME AND 
        t2.value IS NOT NULL 
SET t1.VALUE = t2.VALUE;

EDIT: Removed superfluous t1.id != t2.id condition.

append to url and refresh page

Try this

var url = ApiUrl(`/customers`);
  if(data){
   url += '?search='+data; 
  }
  else
  { 
      url +=  `?page=${page}&per_page=${perpage}`;
  }
  console.log(url);

How to align an indented line in a span that wraps into multiple lines?

try to add display: block; (or replace the <span> by a <div>) (note that this could cause other problems becuase a <span> is inline by default - but you havn't posted the rest of your html)

In Eclipse, what can cause Package Explorer "red-x" error-icon when all Java sources compile without errors?

Subversion is occasionally the culprit for this as well. It might not have anything to do with your environment. But, there might be a discrepancy between the current and local state of the project. In my case, doing an update, and then a commit to the subversion server provided me with the expected clean result without any flags in the project such as the X.

How to uninstall a Windows Service when there is no executable for it left on the system?

Remove Windows Service via Registry

Its very easy to remove a service from registry if you know the right path. Here is how I did that:

  1. Run Regedit or Regedt32

  2. Go to the registry entry "HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services"

  3. Look for the service that you want delete and delete it. You can look at the keys to know what files the service was using and delete them as well (if necessary).

Delete Windows Service via Command Window

Alternatively, you can also use command prompt and delete a service using following command:

sc delete

You can also create service by using following command

sc create "MorganTechService" binpath= "C:\Program Files\MorganTechSPace\myservice.exe"

Note: You may have to reboot the system to get the list updated in service manager.

What's the simplest way to print a Java array?

There's one additional way if your array is of type char[]:

char A[] = {'a', 'b', 'c'}; 

System.out.println(A); // no other arguments

prints

abc

Rewrite URL after redirecting 404 error htaccess

Try adding this rule to the top of your htaccess:

RewriteEngine On
RewriteRule ^404/?$ /pages/errors/404.php [L]

Then under that (or any other rules that you have):

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^ http://domain.com/404/ [L,R]

How to force HTTPS using a web.config file

The excellent NWebsec library can upgrade your requests from HTTP to HTTPS using its upgrade-insecure-requests tag within the Web.config:

<nwebsec>
  <httpHeaderSecurityModule>
    <securityHttpHeaders>
      <content-Security-Policy enabled="true">
        <upgrade-insecure-requests enabled="true"  />
      </content-Security-Policy>
    </securityHttpHeaders>
  </httpHeaderSecurityModule>
</nwebsec>

Merge Cell values with PHPExcel - PHP

Try this

$objPHPExcel->getActiveSheet()->mergeCells('A1:C1');

AngularJS $http-post - convert binary to excel file and download

You could as well take an alternative approach -- you don't have to use $http, you don't need any extra libraries, and it ought to work in any browser.

Just place an invisible form on your page.

<form name="downloadForm" action="/MyApp/MyFiles/Download" method="post" target="_self">
    <input type="hidden" name="value1" value="{{ctrl.value1}}" />
    <input type="hidden" name="value2" value="{{ctrl.value2}}" />
</form>

And place this code in your angular controller.

ctrl.value1 = 'some value 1';  
ctrl.value2 = 'some value 2';  
$timeout(function () {
    $window.document.forms['downloadForm'].submit();
});

This code will post your data to /MyApp/MyFiles/Download and you'll receive a file in your Downloads folder.
It works with Internet Explorer 10.

If a conventional HTML form doesn't let you post your complex object, then you have two options:

1. Stringify your object and put it into one of the form fields as a string.

<input type="hidden" name="myObjJson" value="{{ctrl.myObj | json:0}}" />


2. Consider HTML JSON forms: https://www.w3.org/TR/html-json-forms/

How to resolve symbolic links in a shell script

Common shell scripts often have to find their "home" directory even if they are invoked as a symlink. The script thus have to find their "real" position from just $0.

cat `mvn`

on my system prints a script containing the following, which should be a good hint at what you need.

if [ -z "$M2_HOME" ] ; then
  ## resolve links - $0 may be a link to maven's home
  PRG="$0"

  # need this for relative symlinks
  while [ -h "$PRG" ] ; do
    ls=`ls -ld "$PRG"`
    link=`expr "$ls" : '.*-> \(.*\)$'`
    if expr "$link" : '/.*' > /dev/null; then
      PRG="$link"
    else
      PRG="`dirname "$PRG"`/$link"
    fi
  done

  saveddir=`pwd`

  M2_HOME=`dirname "$PRG"`/..

  # make it fully qualified
  M2_HOME=`cd "$M2_HOME" && pwd`

Jenkins Git Plugin: How to build specific tag?

I set the Advanced->Refspec field to refs/tags/[your tag name]. This seems simpler than the various other suggestions for Refspec, but it worked just fine for me.

UPDATE 23/7/2014 - Actually, after further testing, it turns out this didn't work as expected. It appears that the HEAD version was still being checked out. Please undo this as the accepted answer. I ended up getting a working solution by following the post from gotgenes in this thread (30th March). The issue mentioned in that post of unnecessary triggering of builds was not an issue for me, as my job is triggered from an upstream job, not from polling SCM.

UPDATE APR-2018 - Note in the comments that this does work for one person, and agrees with Jenkins documentation.

What's the difference between SoftReference and WeakReference in Java?

Weak Reference http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ref/WeakReference.html

Principle: weak reference is related to garbage collection. Normally, object having one or more reference will not be eligible for garbage collection.
The above principle is not applicable when it is weak reference. If an object has only weak reference with other objects, then its ready for garbage collection.

Let's look at the below example: We have an Map with Objects where Key is reference a object.

import java.util.HashMap;   
public class Test {

    public static void main(String args[]) {
        HashMap<Employee, EmployeeVal> aMap = new 
                       HashMap<Employee, EmployeeVal>();

        Employee emp = new Employee("Vinoth");
        EmployeeVal val = new EmployeeVal("Programmer");

        aMap.put(emp, val);

        emp = null;

        System.gc();
        System.out.println("Size of Map" + aMap.size());

    }
}

Now, during the execution of the program we have made emp = null. The Map holding the key makes no sense here as it is null. In the above situation, the object is not garbage collected.

WeakHashMap

WeakHashMap is one where the entries (key-to-value mappings) will be removed when it is no longer possible to retrieve them from the Map.

Let me show the above example same with WeakHashMap

import java.util.WeakHashMap;

public class Test {

    public static void main(String args[]) {
        WeakHashMap<Employee, EmployeeVal> aMap = 
                    new WeakHashMap<Employee, EmployeeVal>();

        Employee emp = new Employee("Vinoth");
        EmployeeVal val = new EmployeeVal("Programmer");

        aMap.put(emp, val);

        emp = null;

        System.gc();
        int count = 0;
        while (0 != aMap.size()) {
            ++count;
            System.gc();
        }
        System.out.println("Took " + count
                + " calls to System.gc() to result in weakHashMap size of : "
                + aMap.size());
    }
}

Output: Took 20 calls to System.gc() to result in aMap size of : 0.

WeakHashMap has only weak references to the keys, not strong references like other Map classes. There are situations which you have to take care when the value or key is strongly referenced though you have used WeakHashMap. This can avoided by wrapping the object in a WeakReference.

import java.lang.ref.WeakReference;
import java.util.HashMap;

public class Test {

    public static void main(String args[]) {
        HashMap<Employee, EmployeeVal> map = 
                      new HashMap<Employee, EmployeeVal>();
        WeakReference<HashMap<Employee, EmployeeVal>> aMap = 
                       new WeakReference<HashMap<Employee, EmployeeVal>>(
                map);

        map = null;

        while (null != aMap.get()) {
            aMap.get().put(new Employee("Vinoth"),
                    new EmployeeVal("Programmer"));
            System.out.println("Size of aMap " + aMap.get().size());
            System.gc();
        }
        System.out.println("Its garbage collected");
    }
}

Soft References.

Soft Reference is slightly stronger that weak reference. Soft reference allows for garbage collection, but begs the garbage collector to clear it only if there is no other option.

The garbage collector does not aggressively collect softly reachable objects the way it does with weakly reachable ones -- instead it only collects softly reachable objects if it really "needs" the memory. Soft references are a way of saying to the garbage collector, "As long as memory isn't too tight, I'd like to keep this object around. But if memory gets really tight, go ahead and collect it and I'll deal with that." The garbage collector is required to clear all soft references before it can throw OutOfMemoryError.

How to select all the columns of a table except one column?

In your case, expand columns of that database in the object explorer. Drag the columns in to the query area.

And then just delete one or two columns which you don't want and then run it. I'm open to any suggestions easier than this.

How to concatenate string and int in C?

Look at snprintf or, if GNU extensions are OK, asprintf (which will allocate memory for you).

How do I escape a single quote in SQL Server?

Many of us know that the Popular Method of Escaping Single Quotes is by Doubling them up easily like below.

PRINT 'It''s me, Arul.';

Doubling the Single Quotes Method

we are going to look on some other alternate ways of escaping the single quotes.

1.UNICODE Characters

39 is the UNICODE character of Single Quote. So we can use it like below.

PRINT 'Hi,it'+CHAR(39)+'s Arul.';
PRINT 'Helo,it'+NCHAR(39)+'s Arul.';

UNICODE Characters

2.QUOTED_IDENTIFIER

Another simple and best alternate solution is to use QUOTED_IDENTIFIER. When QUOTED_IDENTIFIER is set to OFF, the strings can be enclosed in double quotes. In this scenario, we don’t need to escape single quotes. So,this way would be very helpful while using lot of string values with single quotes. It will be very much helpful while using so many lines of INSERT/UPDATE scripts where column values having single quotes.

SET QUOTED_IDENTIFIER OFF;
PRINT "It's Arul."
SET QUOTED_IDENTIFIER ON;

QUOTE_IDENTIFIER

CONCLUSION

The above mentioned methods are applicable to both AZURE and On Premises .

Function passed as template argument

In your template

template <void (*T)(int &)>
void doOperation()

The parameter T is a non-type template parameter. This means that the behaviour of the template function changes with the value of the parameter (which must be fixed at compile time, which function pointer constants are).

If you want somthing that works with both function objects and function parameters you need a typed template. When you do this, though, you also need to provide an object instance (either function object instance or a function pointer) to the function at run time.

template <class T>
void doOperation(T t)
{
  int temp=0;
  t(temp);
  std::cout << "Result is " << temp << std::endl;
}

There are some minor performance considerations. This new version may be less efficient with function pointer arguments as the particular function pointer is only derefenced and called at run time whereas your function pointer template can be optimized (possibly the function call inlined) based on the particular function pointer used. Function objects can often be very efficiently expanded with the typed template, though as the particular operator() is completely determined by the type of the function object.

Best way to update an element in a generic List

AllDogs.First(d => d.Id == "2").Name = "some value";

However, a safer version of that might be this:

var dog = AllDogs.FirstOrDefault(d => d.Id == "2");
if (dog != null) { dog.Name = "some value"; }

Cannot insert explicit value for identity column in table 'table' when IDENTITY_INSERT is set to OFF

If you're having this issue while using an sql-server with the sequelize-typescript npm make sure to add @AutoIncrement to ID column:

  @PrimaryKey
  @AutoIncrement
  @Column
  id!: number;

this.getClass().getClassLoader().getResource("...") and NullPointerException

It should be getResource("/install.xml");

The resource names are relative to where the getClass() class resides, e.g. if your test is org/example/foo/MyTest.class then getResource("install.xml") will look in org/example/foo/install.xml.

If your install.xml is in src/test/resources, it's in the root of the classpath, hence you need to prepend the resource name with /.

Also, if it works only sometimes, then it might be because Eclipse has cleaned the output directory (e.g. target/test-classes) and the resource is simply missing from the runtime classpath. Verify that using the Navigator view of Eclipse instead of the Package explorer. If the files is missing, run the mvn package goal.

How to define and use function inside Jenkins Pipeline config?

First off, you shouldn't add $ when you're outside of strings ($class in your first function being an exception), so it should be:

def doCopyMibArtefactsHere(projectName) {
    step ([
        $class: 'CopyArtifact',
        projectName: projectName,
        filter: '**/**.mib',
        fingerprintArtifacts: true, 
        flatten: true
    ]);
}

def BuildAndCopyMibsHere(projectName, params) {
    build job: project, parameters: params
    doCopyMibArtefactsHere(projectName)
}
...

Now, as for your problem; the second function takes two arguments while you're only supplying one argument at the call. Either you have to supply two arguments at the call:

...
node { 
    stage('Prepare Mib'){
        BuildAndCopyMibsHere('project1', null)
    }
}

... or you need to add a default value to the functions' second argument:

def BuildAndCopyMibsHere(projectName, params = null) {
    build job: project, parameters: params
    doCopyMibArtefactsHere($projectName)
}

Manually raising (throwing) an exception in Python

In Python3 there are 4 different syntaxes for rasing exceptions:

1. raise exception 
2. raise exception (args) 
3. raise
4. raise exception (args) from original_exception

1. raise exception vs. 2. raise exception (args)

If you use raise exception (args) to raise an exception then the args will be printed when you print the exception object - as shown in the example below.

  #raise exception (args)
    try:
        raise ValueError("I have raised an Exception")
    except ValueError as exp:
        print ("Error", exp)     # Output -> Error I have raised an Exception 



  #raise execption 
    try:
        raise ValueError
    except ValueError as exp:
        print ("Error", exp)     # Output -> Error 

3.raise

raise statement without any arguments re-raises the last exception. This is useful if you need to perform some actions after catching the exception and then want to re-raise it. But if there was no exception before, raise statement raises TypeError Exception.

def somefunction():
    print("some cleaning")

a=10
b=0 
result=None

try:
    result=a/b
    print(result)

except Exception:            #Output ->
    somefunction()           #some cleaning
    raise                    #Traceback (most recent call last):
                             #File "python", line 8, in <module>
                             #ZeroDivisionError: division by zero

4. raise exception (args) from original_exception

This statement is used to create exception chaining in which an exception that is raised in response to another exception can contain the details of the original exception - as shown in the example below.

class MyCustomException(Exception):
pass

a=10
b=0 
reuslt=None
try:
    try:
        result=a/b

    except ZeroDivisionError as exp:
        print("ZeroDivisionError -- ",exp)
        raise MyCustomException("Zero Division ") from exp

except MyCustomException as exp:
        print("MyException",exp)
        print(exp.__cause__)

Output:

ZeroDivisionError --  division by zero
MyException Zero Division 
division by zero

Getting Date or Time only from a DateTime Object

var currentDateTime = dateTime.Now();
var date=currentDateTime.Date;

Which browsers support <script async="async" />?

There's two parts to this question, really.

  1. Q: Which browsers support the "async" attribute on a script tag in markup?

    A: IE10p2+, Chrome 11+, Safari 5+, Firefox 3.6+

  2. Q: Which browsers support the new spec that defines behavior for the "async" property in JavaScript, on a dynamically created script element?

    A: IE10p2+, Chrome 12+, Safari 5.1+, Firefox 4+

As for Opera, they are very close to releasing a version which will support both types of async. I've been working with them closely on this, and it should come out soon (I hope!).

More info on ordered-async (aka, "async=false") can be found here: http://wiki.whatwg.org/wiki/Dynamic_Script_Execution_Order

Also, to test if a browser supports the new dynamic async property behavior: http://test.getify.com/test-async/

How to determine device screen size category (small, normal, large, xlarge) using code?

Try this function isLayoutSizeAtLeast(int screenSize)

To check small screen, atleast 320x426 dp and above getResources().getConfiguration().isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_SMALL);

To check normal screen, atleast 320x470 dp and above getResources().getConfiguration().isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_NORMAL);

To check large screen, atleast 480x640 dp and above getResources().getConfiguration().isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_LARGE);

To check extra large screen, atleast 720x960 dp and above getResources().getConfiguration().isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_XLARGE);

Doctrine findBy 'does not equal'

I solved this rather easily (without adding a method) so i'll share:

use Doctrine\Common\Collections\Criteria;

$repository->matching( Criteria::create()->where( Criteria::expr()->neq('id', 1) ) );

By the way, i'm using the Doctrine ORM module from within Zend Framework 2 and i'm not sure whether this would be compatible in any other case.

In my case, i was using a form element configuration like this: to show all roles except "guest" in a radio button array.

$this->add(array(
    'type' => 'DoctrineModule\Form\Element\ObjectRadio',
        'name' => 'roles',
        'options' => array(
            'label' => _('Roles'),
            'object_manager' => $this->getEntityManager(),
            'target_class'   => 'Application\Entity\Role',
            'property' => 'roleId',
            'find_method'    => array(
                'name'   => 'matching',
                'params' => array(
                    'criteria' => Criteria::create()->where(
                        Criteria::expr()->neq('roleId', 'guest')
                ),
            ),
        ),
    ),
));

How to detect a textbox's content has changed

Start observing 'input' event instead of 'change'.

jQuery('#some_text_box').on('input', function() {
    // do your stuff
});

...which is nice and clean, but may be extended further to:

jQuery('#some_text_box').on('input propertychange paste', function() {
    // do your stuff
});

How to open specific tab of bootstrap nav tabs on click of a particuler link using jQuery?

May I suggest a php+css solution I used on my site? It's simple and no js problems :)

url to page: <a href="page.php?tab=menu1">link to menu1</a>

<?
$tab = $_GET['tab'];
?>
<ul class="nav nav-tabs">
  <li class="<? if ($tab=='menu1' OR $tab=='menu2') 
{
echo "";
} 
else {
echo "active";
}
?>"><a data-toggle="tab" href="#home">Prodotti</a></li>
  <li class="<? if ($tab=='menu1') 
{
echo "active";
} 
?>"><a data-toggle="tab" href="#menu1">News</a></li>
  <li class="<? if ($tab=='menu2') 
{
echo "active";
} 
?>"><a data-toggle="tab" href="#menu2">Gallery</a></li>
</ul>

<div class="tab-content">
  <div id="home" class="tab-pane fade <? if ($tab=='menu1' OR $tab=='menu2') 
{
echo "";
} 
else {
echo "in active";
}
?>
">
    <h3>Prodotti</h3>
    <p>Contenuto della pagina, zona prodotti</p>
  </div>
  <div id="menu1" class="tab-pane fade <? if ($tab=='menu1') 
{
echo "in active";
} 
?>">
    <h3>News</h3>
    <p>Qui ci saranno le news.</p>
  </div>
  <div id="menu2" class="tab-pane fade <? if ($tab=='menu2') 
{
echo "in active";
} 
?>">
    <h3>Gallery</h3>
    <p>Qui ci sarà la gallery</p>
  </div>
</div>

html5 <input type="file" accept="image/*" capture="camera"> display as image rather than "choose file" button

I know this is an old question but I came across it while trying to solve this same issue. I thought it'd be worth sharing this solution I hadn't found anywhere else.

Basically the solution is to use CSS to hide the <input> element and style a <label> around it to look like a button. Click the 'Run code snippet' button to see the results.

I had used a JavaScript solution before that worked fine too but it is nice to solve a 'presentation' issue with just CSS.

_x000D_
_x000D_
label.cameraButton {_x000D_
  display: inline-block;_x000D_
  margin: 1em 0;_x000D_
_x000D_
  /* Styles to make it look like a button */_x000D_
  padding: 0.5em;_x000D_
  border: 2px solid #666;_x000D_
  border-color: #EEE #CCC #CCC #EEE;_x000D_
  background-color: #DDD;_x000D_
}_x000D_
_x000D_
/* Look like a clicked/depressed button */_x000D_
label.cameraButton:active {_x000D_
  border-color: #CCC #EEE #EEE #CCC;_x000D_
}_x000D_
_x000D_
/* This is the part that actually hides the 'Choose file' text box for camera inputs */_x000D_
label.cameraButton input[accept*="camera"] {_x000D_
  display: none;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <title>Nice image capture button</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <label class="cameraButton">Take a picture_x000D_
    <input type="file" accept="image/*;capture=camera">_x000D_
  </label>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to pass a function as a parameter in Java?

I used the command pattern that @jk. mentioned, adding a return type:

public interface Callable<I, O> {

    public O call(I input);   
}

Parse HTML table to Python list?

Hands down the easiest way to parse a HTML table is to use pandas.read_html() - it accepts both URLs and HTML.

import pandas as pd
url = r'https://en.wikipedia.org/wiki/List_of_S%26P_500_companies'
tables = pd.read_html(url) # Returns list of all tables on page
sp500_table = tables[0] # Select table of interest

Only downside is that read_html() doesn't preserve hyperlinks.

vim - How to delete a large block of text without counting the lines?

You can also enter a very large number, and then press dd if you wish to delete all the lines below the cursor.

How to get the last day of the month?

The simplest way is to use datetime and some date math, e.g. subtract a day from the first day of the next month:

import datetime

def last_day_of_month(d: datetime.date) -> datetime.date:
    return (
        datetime.date(d.year + d.month//12, d.month % 12 + 1, 1) -
        datetime.timedelta(days=1)
    )

Alternatively, you could use calendar.monthrange() to get the number of days in a month (taking leap years into account) and update the date accordingly:

import calendar, datetime

def last_day_of_month(d: datetime.date) -> datetime.date:
    return d.replace(day=calendar.monthrange(d.year, d.month)[1])

A quick benchmark shows that the first version is noticeably faster:

In [14]: today = datetime.date.today()

In [15]: %timeit last_day_of_month_dt(today)
918 ns ± 3.54 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [16]: %timeit last_day_of_month_calendar(today)
1.4 µs ± 17.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Bootstrap: How do I identify the Bootstrap version?

An easy way to do this, without searching files or folders would be:

  • Open your web page on browser
  • press ctrl+U
  • search boostrap.min.js or boostrap.min.css, then click it (it would open source file)
  • at first line(commented) you should see boostrap version

Rounding float in Ruby

Pass an argument to round containing the number of decimal places to round to

>> 2.3465.round
=> 2
>> 2.3465.round(2)
=> 2.35
>> 2.3465.round(3)
=> 2.347

.Net System.Mail.Message adding multiple "To" addresses

You could try putting the e-mails into a comma-delimited string ("[email protected], [email protected]"):

C#:

ArrayList arEmails = new ArrayList();
arEmails.Add("[email protected]");
arEmails.Add("[email protected]");
           
string strEmails = string.Join(", ", arEmails);

VB.NET if you're interested:

Dim arEmails As New ArrayList
arEmails.Add("[email protected]")
arEmails.Add("[email protected]")

Dim strEmails As String = String.Join(", ", arEmails)

Generating a unique machine id

Look up CPUID for one option. There might be some issues with multi-CPU systems.

How do I create a readable diff of two spreadsheets using git diff?

I found an openoffice macro here that will invoke openoffice's compare documents function on two files. Unfortunately, openoffice's spreadsheet compare seems a little flaky; I just had the 'Reject All' button insert a superfluous column in my document.