Programs & Examples On #Product development

PHPMailer: SMTP Error: Could not connect to SMTP host

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

Query to list number of records in each table in a database

You could try this:

SELECT  OBJECT_SCHEMA_NAME(ps.object_Id) AS [schemaname],
        OBJECT_NAME(ps.object_id) AS [tablename],
        row_count AS [rows]
FROM sys.dm_db_partition_stats ps
WHERE OBJECT_SCHEMA_NAME(ps.object_Id) <> 'sys' AND ps.index_id < 2
ORDER BY 
        OBJECT_SCHEMA_NAME(ps.object_Id),
        OBJECT_NAME(ps.object_id)

How to convert int[] to Integer[] in Java?

I was wrong in a previous answer. The proper solution is to use this class as a key in the map wrapping the actual int[].

public class IntArrayWrapper {
        int[] data;

        public IntArrayWrapper(int[] data) {
            this.data = data;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            IntArrayWrapper that = (IntArrayWrapper) o;

            if (!Arrays.equals(data, that.data)) return false;

            return true;
        }

        @Override
        public int hashCode() {
            return data != null ? Arrays.hashCode(data) : 0;
        }
    }

and change your code like this:

   Map<IntArrayWrapper, Double > freqs = new HashMap<IntArrayWrapper, Double>();

    for (int[] data : datas) {
        IntArrayWrapper wrapper = new IntArrayWrapper(data);

        if ( freqs.containsKey(wrapper)) {
            freqs.put(wrapper, freqs.get(wrapper) + p);
        }

        freqs.put(wrapper, p);
    }

How do I drop a foreign key in SQL Server?

This will work:

ALTER TABLE [dbo].[company] DROP CONSTRAINT [Company_CountryID_FK]

How can I align all elements to the left in JPanel?

You should use setAlignmentX(..) on components you want to align, not on the container that has them..

JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(c1);
panel.add(c2);

c1.setAlignmentX(Component.LEFT_ALIGNMENT);
c2.setAlignmentX(Component.LEFT_ALIGNMENT);

ProgressDialog is deprecated.What is the alternate one to use?

ProgressBar is very simple and easy to use, i am intending to make this same as simple progress dialog. first step is that you can make xml layout of the dialog that you want to show, let say we name this layout

layout_loading_dialog.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="20dp">
    <ProgressBar
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="4"
        android:gravity="center"
        android:text="Please wait! This may take a moment." />
</LinearLayout>

next step is create AlertDialog which will show this layout with ProgressBar

AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCancelable(false); // if you want user to wait for some process to finish,
builder.setView(R.layout.layout_loading_dialog);
AlertDialog dialog = builder.create();

now all that is left is to show and hide this dialog in our click events like this

dialog.show(); // to show this dialog
dialog.dismiss(); // to hide this dialog

and thats it, it should work, as you can see it is farely simple and easy to implement ProgressBar instead of ProgressDialog. now you can show/dismiss this dialog box in either Handler or ASyncTask, its up to your need

How can I make a clickable link in an NSAttributedString?

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:strSomeTextWithLinks];

NSDictionary *linkAttributes = @{NSForegroundColorAttributeName: [UIColor redColor],   
                                 NSUnderlineColorAttributeName: [UIColor blueColor],
                                 NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)};

customTextView.linkTextAttributes = linkAttributes; // customizes the appearance of links
textView.attributedText = attributedString;

KEY POINTS:

  • Make sure that you enable "Selectable" behavior of the UITextView in XIB.
  • Make sure that you disable "Editable" behavior of the UITextView in XIB.

How to check null objects in jQuery

use $("#selector").get(0) to check with null like that. get returns the dom element, until then you re dealing with an array, where you need to check the length property. I personally don't like length check for null handling, it confuses me for some reason :)

Android Studio Gradle project "Unable to start the daemon process /initialization of VM"

It has to do with how much memory is available for AS to create a VM environment for your app to populate. The thing is that ever since the update to 2.2 I've had the same problem every time I try to create a new project in AS.

How I solve it is by going into Project (on the left hand side) > Gradle Scripts > gradle.properties. When it opens the file go to the line under "(Line 10)# Specifies the JVM arguments used for the daemon process. (Line 11)# The setting is particularly useful for tweaking memory settings." You're looking for the line that starts with "org.gradle.jvmargs". This should be line 12. Change line 12 to this

org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

After changing this line you can either sync the gradle with the project by clicking Try again on the notification telling you the gradle sync failed (it'll be at the top of the file you opened). Or you can simply close and restart the AS and it should sync.

Essentially what this is saying is for AS to allocate more memory to the app initialization. I know it's not a permanent fix but it should get you through actually starting your app.

Python Array with String Indices

Even better, try an OrderedDict (assuming you want something like a list). Closer to a list than a regular dict since the keys have an order just like list elements have an order. With a regular dict, the keys have an arbitrary order.

Note that this is available in Python 3 and 2.7. If you want to use with an earlier version of Python you can find installable modules to do that.

SQLAlchemy IN clause

How about

session.query(MyUserClass).filter(MyUserClass.id.in_((123,456))).all()

edit: Without the ORM, it would be

session.execute(
    select(
        [MyUserTable.c.id, MyUserTable.c.name], 
        MyUserTable.c.id.in_((123, 456))
    )
).fetchall()

select() takes two parameters, the first one is a list of fields to retrieve, the second one is the where condition. You can access all fields on a table object via the c (or columns) property.

Get all rows from SQLite

Update queueAll() method as below:

public Cursor queueAll() {

     String selectQuery = "SELECT * FROM " + MYDATABASE_TABLE;
     Cursor cursor = sqLiteDatabase.rawQuery(selectQuery, null);

     return cursor;
}

Update readFileFromSQLite() method as below:

public ArrayList<String> readFileFromSQLite() {

    fileName = new ArrayList<String>();

    fileSQLiteAdapter = new FileSQLiteAdapter(FileChooser.this);
    fileSQLiteAdapter.openToRead();

    cursor = fileSQLiteAdapter.queueAll();

    if (cursor != null) {
        if (cursor.moveToFirst()) {
            do 
            {
                String name = cursor.getString(cursor.getColumnIndex(FileSQLiteAdapter.KEY_CONTENT1));
                fileName.add(name);
            } while (cursor.moveToNext());
        }
        cursor.close();
    }

    fileSQLiteAdapter.close();

    return fileName;
}

What is mutex and semaphore in Java ? What is the main difference?

Semaphore can be counted, while mutex can only count to 1.

Suppose you have a thread running which accepts client connections. This thread can handle 10 clients simultaneously. Then each new client sets the semaphore until it reaches 10. When the Semaphore has 10 flags, then your thread won't accept new connections

Mutex are usually used for guarding stuff. Suppose your 10 clients can access multiple parts of the system. Then you can protect a part of the system with a mutex so when 1 client is connected to that sub-system, no one else should have access. You can use a Semaphore for this purpose too. A mutex is a "Mutual Exclusion Semaphore".

How to search for a string in text files?

As Jeffrey Said, you are not checking the value of check(). In addition, your check() function is not returning anything. Note the difference:

def check():
    with open('example.txt') as f:
        datafile = f.readlines()
    found = False  # This isn't really necessary
    for line in datafile:
        if blabla in line:
            # found = True # Not necessary
            return True
    return False  # Because you finished the search without finding

Then you can test the output of check():

if check():
    print('True')
else:
    print('False')

Perform .join on value in array of objects

If object and dynamical keys: "applications\":{\"1\":\"Element1\",\"2\":\"Element2\"}

Object.keys(myObject).map(function (key, index) {
    return myObject[key]
}).join(', ')

how to show alternate image if source image is not found? (onerror working in IE but not in mozilla)

I think this is very nice and short

<img src="imagenotfound.gif" alt="Image not found" onerror="this.src='imagefound.gif';" />

But, be careful. The user's browser will be stuck in an endless loop if the onerror image itself generates an error.


EDIT To avoid endless loop, remove the onerror from it at once.

<img src="imagenotfound.gif" alt="Image not found" onerror="this.onerror=null;this.src='imagefound.gif';" />

By calling this.onerror=null it will remove the onerror then try to get the alternate image.


NEW I would like to add a jQuery way, if this can help anyone.

<script>
$(document).ready(function()
{
    $(".backup_picture").on("error", function(){
        $(this).attr('src', './images/nopicture.png');
    });
});
</script>

<img class='backup_picture' src='./images/nonexistent_image_file.png' />

You simply need to add class='backup_picture' to any img tag that you want a backup picture to load if it tries to show a bad image.

Range of values in C Int and Long 32 - 64 bits

In fact, unsigned int on most modern processors (ARM, Intel/AMD, Alpha, SPARC, Itanium ,PowerPC) will have a range of 0 to 2^32 - 1 which is 4,294,967,295 = 0xffffffff because int (both signed and unsigned) will be 32 bits long and the largest one is as stated.

(unsigned short will have maximal value 2^16 - 1 = 65,535 )

(unsigned) long long int will have a length of 64 bits (long int will be enough under most 64 bit Linuxes, etc, but the standard promises 64 bits for long long int). Hence these have the range 0 to 2^64 - 1 = 18446744073709551615

Math operations from string

The asker commented:

I figure that if I understand a problem well enough to write a program that can figure it out, I don't need to do the work manually.

If he's writing a math expression solver as a learning exercise, using eval() isn't going to help. Plus it's terrible design.

You might consider making a calculator using Reverse Polish Notation instead of standard math notation. It simplifies the parsing considerably. It would still be a good exercise

Python lookup hostname from IP with 1 second timeout

What you're trying to accomplish is called Reverse DNS lookup.

socket.gethostbyaddr("IP") 
# => (hostname, alias-list, IP)

http://docs.python.org/library/socket.html?highlight=gethostbyaddr#socket.gethostbyaddr

However, for the timeout part I have read about people running into problems with this. I would check out PyDNS or this solution for more advanced treatment.

How to not wrap contents of a div?

If your div has a fixed-width it shouldn't expand, because you've fixed its width. However, modern browsers support a min-width CSS property.

You can emulate the min-width property in old IE browsers by using CSS expressions or by using auto width and having a spacer object in the container. This solution isn't elegant but may do the trick:

<div id="container" style="float: left">
  <div id="spacer" style="height: 1px; width: 300px"></div>
  <button>Button 1 text</button>
  <button>Button 2 text</button>
</div>

Local and global temporary tables in SQL Server

  • Table variables (DECLARE @t TABLE) are visible only to the connection that creates it, and are deleted when the batch or stored procedure ends.

  • Local temporary tables (CREATE TABLE #t) are visible only to the connection that creates it, and are deleted when the connection is closed.

  • Global temporary tables (CREATE TABLE ##t) are visible to everyone, and are deleted when all connections that have referenced them have closed.

  • Tempdb permanent tables (USE tempdb CREATE TABLE t) are visible to everyone, and are deleted when the server is restarted.

Trim a string in C

This made me want to write my own - I didn't like the ones that had been provided. Seems to me there should be 3 functions.

char *ltrim(char *s)
{
    while(isspace(*s)) s++;
    return s;
}

char *rtrim(char *s)
{
    char* back = s + strlen(s);
    while(isspace(*--back));
    *(back+1) = '\0';
    return s;
}

char *trim(char *s)
{
    return rtrim(ltrim(s)); 
}

HTML - Arabic Support

Won't you need the ensure the area where you display the Arabic is Right-to-Left orientated also?

e.g.

<p dir="rtl">

C++ multiline string literal

You can also do this:

const char *longString = R""""(
This is 
a very 
long 
string
)"""";

How do I make a newline after a twitter bootstrap element?

Like KingCronus mentioned in the comments you can use the row class to make the list or heading on its own line. You could use the row class on either or both elements:

<ul class="nav nav-tabs span2 row">
  <li><a href="./index.html"><i class="icon-black icon-music"></i></a></li>
  <li><a href="./about.html"><i class="icon-black icon-eye-open"></i></a></li>
  <li><a href="./team.html"><i class="icon-black icon-user"></i></a></li>
  <li><a href="./contact.html"><i class="icon-black icon-envelope"></i></a></li>
</ul>

<div class="well span6 row">
  <h3>I wish this appeared on the next line without having to gratuitously use BR!</h3>
</div>

get path for my .exe

System.Reflection.Assembly.GetEntryAssembly().Location;

jquery, selector for class within id

You can use the class selector along with descendant selector

$("#my_id .my_class")

Copy and paste content from one file to another file in vi

The below option works most of time and also for pasting later.

 "xnyy
x - buffer name
n - number of line to Yank - optional

The lines yanked will be stored in the buffer 'x'. It can be used anywhere in the edit.

To paste line(s) in the other file,

:e filename&location

Example: Type the below command in the current edit

:e /u/test/Test2.sh
and paste using "xP
P - before cursor
p - after cursor

Complete operation

open file 1 :

vi Test1.sh

a10yy

-Yanked 10 lines

-now open the second file from the current edit

*:e /u/test/Test2.sh*

-move the cursor to the line where you have to paste

*"ap*

--Lines from the buffer '*a*' will be copied after the current cursor pos

pip not working in Python Installation in Windows 10

I faced a problem upgrading pip from version 9.0.1 to 9.0.3 The upgrade failed middle way(after uninstalling version 9.0.1 and without installing version 9.0.3). This usually creates a broken pip file. Broken pip can be solved by the command-->

easy_install pip

Which usually installs the latest version of pip, and solves the issue. In order to confirm, type

pip --version

Hope this was helpfull...

Get year, month or day from numpy datetime64

There should be an easier way to do this, but, depending on what you're trying to do, the best route might be to convert to a regular Python datetime object:

datetime64Obj = np.datetime64('2002-07-04T02:55:41-0700')
print datetime64Obj.astype(object).year
# 2002
print datetime64Obj.astype(object).day
# 4

Based on comments below, this seems to only work in Python 2.7.x and Python 3.6+

jquery multiple checkboxes array

You can use $.map() (or even the .map() function that operates on a jQuery object) to get an array of checked values. The unary (+) operator will cast the string to a number

var arr = $.map($('input:checkbox:checked'), function(e,i) {
    return +e.value;
});

console.log(arr);

Here's an example

Angular 2 / 4 / 5 not working in IE11

Step 1: Un-comment plyfills in polyfills.ts. Also run all npm install commands mentioned in in polyfills.ts file to install those packages

Step 2: In browserslist file remove not before the line where IE 9-11 support is mentioned

Step 3: In tsconfig.json file change like "target": "es2015" to "target": "es5"

These steps fixed my issue

How to submit http form using C#

Here is a sample script that I recently used in a Gateway POST transaction that receives a GET response. Are you using this in a custom C# form? Whatever your purpose, just replace the String fields (username, password, etc.) with the parameters from your form.

private String readHtmlPage(string url)
   {

    //setup some variables

    String username  = "demo";
    String password  = "password";
    String firstname = "John";
    String lastname  = "Smith";

    //setup some variables end

      String result = "";
      String strPost = "username="+username+"&password="+password+"&firstname="+firstname+"&lastname="+lastname;
      StreamWriter myWriter = null;

      HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
      objRequest.Method = "POST";
      objRequest.ContentLength = strPost.Length;
      objRequest.ContentType = "application/x-www-form-urlencoded";

      try
      {
         myWriter = new StreamWriter(objRequest.GetRequestStream());
         myWriter.Write(strPost);
      }
      catch (Exception e) 
      {
         return e.Message;
      }
      finally {
         myWriter.Close();
      }

      HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
      using (StreamReader sr = 
         new StreamReader(objResponse.GetResponseStream()) )
      {
         result = sr.ReadToEnd();

         // Close and clean up the StreamReader
         sr.Close();
      }
      return result;
   } 

What is function overloading and overriding in php?

Method overloading occurs when two or more methods with same method name but different number of parameters in single class. PHP does not support method overloading. Method overriding means two methods with same method name and same number of parameters in two different classes means parent class and child class.

How to prevent line-break in a column of a table cell (not a single cell)?

Just add

style="white-space:nowrap;"

Example:

<table class="blueTable" style="white-space:nowrap;">
   <tr>
      <td>My name is good</td>
    </tr>
 </table>

npm - how to show the latest version of a package

As of October 2014:

npm view illustration

For latest remote version:

npm view <module_name> version  

Note, version is singular.

If you'd like to see all available (remote) versions, then do:

npm view <module_name> versions

Note, versions is plural. This will give you the full listing of versions to choose from.

To get the version you actually have locally you could use:

npm list --depth=0 | grep <module_name>

Note, even with package.json declaring your versions, the installed version might actually differ slightly - for instance if tilda was used in the version declaration

Should work across NPM versions 1.3.x, 1.4.x, 2.x and 3.x

Set Windows process (or user) memory limit

Use Windows Job Objects. Jobs are like process groups and can limit memory usage and process priority.

How to scan multiple paths using the @ComponentScan annotation?

You use ComponentScan to scan multiple packages using

@ComponentScan({"com.my.package.first","com.my.package.second"})

text-align: right on <select> or <option>

You could try using the "dir" attribute, but I'm not sure that would produce the desired effect?

<select dir="rtl">
    <option>Foo</option>    
    <option>bar</option>
    <option>to the right</option>
</select>

Demo here: http://jsfiddle.net/fparent/YSJU7/

What are the special dollar sign shell variables?

To help understand what do $#, $0 and $1, ..., $n do, I use this script:

#!/bin/bash

for ((i=0; i<=$#; i++)); do
  echo "parameter $i --> ${!i}"
done

Running it returns a representative output:

$ ./myparams.sh "hello" "how are you" "i am fine"
parameter 0 --> myparams.sh
parameter 1 --> hello
parameter 2 --> how are you
parameter 3 --> i am fine

Detect URLs in text with JavaScript

If you want to detect links with http:// OR without http:// OR ftp OR other possible cases like removing trailing punctuation at the end, take a look at this code.

https://jsfiddle.net/AndrewKang/xtfjn8g3/

A simple way to use that is to use NPM

npm install --save url-knife

How to refresh activity after changing language (Locale) inside application

Call this method to change app locale:

public void settingLocale(Context context, String language) {

    Locale locale;

    Configuration config = new Configuration();

     if(language.equals(LANGUAGE_ENGLISH)) {

        locale = new Locale("en");

        Locale.setDefault(locale);

        config.locale = locale;

    }else if(language.equals(LANGUAGE_ARABIC)){

        locale = new Locale("hi");

        Locale.setDefault(locale);

        config.locale = locale;

    }

    context.getResources().updateConfiguration(config, null);

    // Here again set the text on view to reflect locale change

    // and it will pick resource from new locale

    tv1.setText(R.string.one); //tv1 is textview in my activity

}

Note: Put your strings in value and values- folder.

How do I make a JSON object with multiple arrays?

Enclosed in {} represents an object; enclosed in [] represents an array, there can be multiple objects in the array
example object :

{
    "brand": "bwm", 
    "price": 30000
}


{
    "brand": "benz", 
    "price": 50000
}

example array:

[
    {
        "brand": "bwm", 
        "price": 30000
    }, 
    {
        "brand": "benz", 
        "price": 50000
    }
]

In order to use JSON more beautifully, you can go here JSON Viewer do format

How to redirect to previous page in Ruby On Rails?

I like Jaime's method with one exception, it worked better for me to re-store the referer every time:

def edit
    session[:return_to] = request.referer
...

The reason is that if you edit multiple objects, you will always be redirected back to the first URL you stored in the session with Jaime's method. For example, let's say I have objects Apple and Orange. I edit Apple and session[:return_to] gets set to the referer of that action. When I go to edit Oranges using the same code, session[:return_to] will not get set because it is already defined. So when I update the Orange, I will get sent to the referer of the previous Apple#edit action.

Java: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

The source of this error on my Apache 2.4 instance (using a Comodo wildcard certificate) was an incomplete path to the SHA-1 signed root certificate. There were multiple chains in the issued certificate, and the chain leading to a SHA-1 root certificate was missing an intermediate certificate. Modern browsers know how to handle this, but Java 7 doesn't handle it by default (although there are some convoluted ways to accomplish this in code). The result is error messages that look identical to the case of self-signed certificates:

Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:196)
    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:268)
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380)
    ... 22 more

In this case, the "unable to find valid certification path to requested target" message is being produced due to the missing intermediate certificate. You can check which certificate is missing using SSL Labs test against the server. Once you find the appropriate certificate, download it and (if the server is under your control) add it to the certificate bundle. Alternatively, you can import the missing certificate locally. Accommodating this issue on the server is a more general solution to the problem.

Javascript string replace with regex to strip off illegal characters

Put them in brackets []:

var cleanString = dirtyString.replace(/[\|&;\$%@"<>\(\)\+,]/g, "");

How do I display a decimal value to 2 decimal places?

Here is a little Linqpad program to show different formats:

void Main()
{
    FormatDecimal(2345.94742M);
    FormatDecimal(43M);
    FormatDecimal(0M);
    FormatDecimal(0.007M);
}

public void FormatDecimal(decimal val)
{
    Console.WriteLine("ToString: {0}", val);
    Console.WriteLine("c: {0:c}", val);
    Console.WriteLine("0.00: {0:0.00}", val);
    Console.WriteLine("0.##: {0:0.##}", val);
    Console.WriteLine("===================");
}

Here are the results:

ToString: 2345.94742
c: $2,345.95
0.00: 2345.95
0.##: 2345.95
===================
ToString: 43
c: $43.00
0.00: 43.00
0.##: 43
===================
ToString: 0
c: $0.00
0.00: 0.00
0.##: 0
===================
ToString: 0.007
c: $0.01
0.00: 0.01
0.##: 0.01
===================

How to connect to Oracle 11g database remotely

First, make sure the listener on database server (computer A) that receives client connection requests is running. To do so, run lsnrctl status command.

In case, if you get TNS:no listener message (see below image), it means listener service is not running. To start it, run lsnrctl start command.

enter image description here

Second, for database operations and connectivity from remote clients, the following executables must be added to the Windows Firewall exception list: (see image)

Oracle_home\bin\oracle.exe - Oracle Database executable

Oracle_home\bin\tnslsnr.exe - Oracle Listener

enter image description here

Finally, install oracle instant client on client machine (computer B) and run:

sqlplus user/password@computerA:port/XE

Getting around the Max String size in a vba function?

I may have missed something here, but why can't you just declare your string with the desired size? For example, in my VBA code I often use something like:

Dim AString As String * 1024

which provides for a 1k string. Obviously, you can use whatever declaration you like within the larger limits of Excel and available memory etc.

This may be a little inefficient in some cases, and you will probably wish to use Trim(AString) like constructs to obviate any superfluous trailing blanks. Still, it easily exceeds 256 chars.

Is there any way to set environment variables in Visual Studio Code?

For more advanced Go language scenarios, you can load an environment file, like this:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Launch",
      "type": "go",
      "request": "launch", 
      "mode": "debug",
      "remotePath": "",
      "port": 2345,
      "host": "127.0.0.1",
      "program": "${workspaceFolder}",
      "envFile": "${workspaceFolder}/.env",
      "args": [], 
      "showLog": true
    }
  ]
}

Place the .env file in your folder and add vars like this:

KEY1="TEXT_VAL1"
KEY2='{"key1":val1","key2":"val2"}'

Details: https://medium.com/@reuvenharrison/using-visual-studio-code-to-debug-a-go-program-with-environment-variables-523fea268271

Convert an array into an ArrayList

declaring the list (and initializing it with an empty arraylist)

List<Card> cardList = new ArrayList<Card>();

adding an element:

Card card;
cardList.add(card);

iterating over elements:

for(Card card : cardList){
    System.out.println(card);
}

When to encode space to plus (+) or %20?

Its better to always encode spaces as %20, not as "+".

It was RFC-1866 (HTML 2.0 specification), which specified that space characters should be encoded as "+" in "application/x-www-form-urlencoded" content-type key-value pairs. (see paragraph 8.2.1. subparagraph 1.). This way of encoding form data is also given in later HTML specifications, look for relevant paragraphs about application/x-www-form-urlencoded.

Here is an example of such a string in URL where RFC-1866 allows encoding spaces as pluses: "http://example.com/over/there?name=foo+bar". So, only after "?", spaces can be replaced by pluses, according to RFC-1866. In other cases, spaces should be encoded to %20. But since it's hard to determine the context, it's the best practice to never encode spaces as "+".

I would recommend to percent-encode all character except "unreserved" defined in RFC-3986, p.2.3

unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"

Object spread vs. Object.assign

NOTE: Spread is NOT just syntactic sugar around Object.assign. They operate much differently behind the scenes.

Object.assign applies setters to a new object, Spread does not. In addition, the object must be iterable.

Copy Use this if you need the value of the object as it is at this moment, and you don't want that value to reflect any changes made by other owners of the object.

Use it for creating a shallow copy of the object good practice to always set immutable properties to copy - because mutable versions can be passed into immutable properties, copy will ensure that you'll always be dealing with an immutable object

Assign Assign is somewhat the opposite to copy. Assign will generate a setter which assigns the value to the instance variable directly, rather than copying or retaining it. When calling the getter of an assign property, it returns a reference to the actual data.

How to get row data by clicking a button in a row in an ASP.NET gridview

<asp:TemplateField>
   <ItemTemplate>
  <asp:LinkButton runat="server" ID="LnKB" Text='edit' OnClick="LnKB_Click"   > 
 </asp:LinkButton>
 </ItemTemplate>
</asp:TemplateField>

  protected void LnKB_Click(object sender, System.EventArgs e)
  {
        LinkButton lb = sender as LinkButton;

        GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
        int x = clickedRow.RowIndex;
        int id = Convert.ToInt32(yourgridviewname.Rows[x].Cells[0].Text);
        lbl.Text = yourgridviewname.Rows[x].Cells[2].Text; 
   }

Solving "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection" InvalidOperationException

By default Entity Framework uses lazy-loading for navigation properties. That's why these properties should be marked as virtual - EF creates proxy class for your entity and overrides navigation properties to allow lazy-loading. E.g. if you have this entity:

public class MemberLoan
{
   public string LoandProviderCode { get; set; }
   public virtual Membership Membership { get; set; }
}

Entity Framework will return proxy inherited from this entity and provide DbContext instance to this proxy in order to allow lazy loading of membership later:

public class MemberLoanProxy : MemberLoan
{
    private CosisEntities db;
    private int membershipId;
    private Membership membership;

    public override Membership Membership 
    { 
       get 
       {
          if (membership == null)
              membership = db.Memberships.Find(membershipId);
          return membership;
       }
       set { membership = value; }
    }
}

So, entity has instance of DbContext which was used for loading entity. That's your problem. You have using block around CosisEntities usage. Which disposes context before entities are returned. When some code later tries to use lazy-loaded navigation property, it fails, because context is disposed at that moment.

To fix this behavior you can use eager loading of navigation properties which you will need later:

IQueryable<MemberLoan> query = db.MemberLoans.Include(m => m.Membership);

That will pre-load all memberships and lazy-loading will not be used. For details see Loading Related Entities article on MSDN.

Sending the bearer token with axios

Here is a unique way of setting Authorization token in axios. Setting configuration to every axios call is not a good idea and you can change the default Authorization token by:

import axios from 'axios';
axios.defaults.baseURL = 'http://localhost:1010/'
axios.defaults.headers.common = {'Authorization': `bearer ${token}`}
export default axios;

Edit, Thanks to Jason Norwood-Young.

Some API require bearer to be written as Bearer, so you can do:

axios.defaults.headers.common = {'Authorization': `Bearer ${token}`}

Now you don't need to set configuration to every API call. Now Authorization token is set to every axios call.

jdk7 32 bit windows version to download

Go to the download page and download the Windows x86 version with filename jdk-7-windows-i586.exe.

What does [STAThread] do?

It tells the compiler that you're in a Single Thread Apartment model. This is an evil COM thing, it's usually used for Windows Forms (GUI's) as that uses Win32 for its drawing, which is implemented as STA. If you are using something that's STA model from multiple threads then you get corrupted objects.

This is why you have to invoke onto the Gui from another thread (if you've done any forms coding).

Basically don't worry about it, just accept that Windows GUI threads must be marked as STA otherwise weird stuff happens.

How to iterate object keys using *ngFor

I think the most elegant way to do that is to use the javascript Object.keys like this (I had first implemented a pipe for that but for me, it just complicated my work unnecessary):

in the Component pass Object to template:

Object = Object;

then in the template:

<div *ngFor="let key of Object.keys(objs)">
   my key: {{key}}
   my object {{objs[key] | json}} <!-- hier I could use ngFor again with Object.keys(objs[key]) -->
</div>

If you have a lot of subobjects you should create a component that will print the object for you. By printing the values and keys as you want and on an subobject calling itselfe recursively.

Hier you can find an stackblitz demo for both methods.

button image as form input submit button?

You could use an image submit button:

<input type="image" src="images/login.jpg" alt="Submit Form" />

awk without printing newline

one way

awk '/^\*\*/{gsub("*","");printf "\n"$0" ";next}{printf $0" "}' to-plot.xls

How do I install g++ for Fedora?

Just make a sample 'Hello World' Program and try to compile it using "g++ sam.cpp" in terminal, and it will ask you if you wish to download the g++ package. Press y to install.

Tomcat is not deploying my web project from Eclipse

I have the same problem, my solution is:

  • Install WTP Maven integration (don't know if this is necessary)
  • Project -> Run Configurations (Select your tomcat server) -> Run

For a few hours I tried to deploy and start application using Servers window but it didn't worked. My war was not placed in wptwebapps folder, manually deplying war to webapps worked.

Using Run Configurations made my app finally deployable...

How to disable Hyper-V in command line?

You can have a Windows 10 configuration with and without Hyper-V as follows in an Admin prompt:

bcdedit /copy {current} /d "Windows 10 no Hyper-V"

find the new id of the just created "Windows 10 no Hyper-V" bootentry, eg. {094a0b01-3350-11e7-99e1-bc5ec82bc470}

bcdedit /set {094a0b01-3350-11e7-99e1-bc5ec82bc470} hypervisorlaunchtype Off

After rebooting you can choose between Windows 10 with and without Hyper-V at startup

ORA-12170: TNS:Connect timeout occurred

Check the FIREWALL, to allow the connection at the server from your client. By allowing Domain network or create rule.

Assign keyboard shortcut to run procedure

For assigning a keyboard key to button on the sheet you can use this code, just copy this code to the sheet which contain the button.

Here Return specifies the key and get_detail is the procedure name.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    Application.OnKey "{RETURN}", "get_detail"

End Sub

Now within this sheet whenever you press Enter button the assigned macro will be called.

CASE in WHERE, SQL Server

Try this:

WHERE a.Country = (CASE WHEN @Country > 0 THEN @Country ELSE a.Country END)

What regular expression will match valid international phone numbers?

A simple version for european numbers, that matches numbers like 0034617393211 but also long ones as 004401484172842.

^0{2}[0-9]{11,}

Hope it helps :·)

Oracle: Call stored procedure inside the package

You're nearly there, just take out the EXECUTE:

DECLARE
  procId NUMBER;

BEGIN
  PKG1.INIT(1143824, 0, procId);
  DBMS_OUTPUT.PUT_LINE(procId);
END;

initialize a vector to zeros C++/C++11

Initializing a vector having struct, class or Union can be done this way

std::vector<SomeStruct> someStructVect(length);
memset(someStructVect.data(), 0, sizeof(SomeStruct)*length);

How do I create a Bash alias?

I need to run the Postgres database and created an alias for the purpose. The work through is provided below:

$ nano ~/.bash_profile 

# in the bash_profile, insert the following texts:

alias pgst="pg_ctl -D /usr/local/var/postgres start"
alias pgsp="pg_ctl -D /usr/local/var/postgres stop"


$ source ~/.bash_profile 

### This will start the Postgres server 
$ pgst

### This will stop the Postgres server 
$ pgsp

How to get the first line of a file in a bash script?

The question didn't ask which is fastest, but to add to the sed answer, -n '1p' is badly performing as the pattern space is still scanned on large files. Out of curiosity I found that 'head' wins over sed narrowly:

# best:
head -n1 $bigfile >/dev/null

# a bit slower than head (I saw about 10% difference):
sed '1q' $bigfile >/dev/null

# VERY slow:
sed -n '1p' $bigfile >/dev/null

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

Just Simply use

use css code: text-transform: uppercase;

Struct with template variables in C++

Looks like @monkeyking is trying it to make it more obvious code as shown below

template <typename T> 
struct Array { 
  size_t x; 
  T *ary; 
};

typedef Array<int> iArray;
typedef Array<float> fArray;

Can I set an unlimited length for maxJsonLength in web.config?

use lib\Newtonsoft.Json.dll

public string serializeObj(dynamic json) {        
    return JsonConvert.SerializeObject(json);
}

Count number of columns in a table row

Count all td in table1:

_x000D_
_x000D_
console.log(_x000D_
table1.querySelectorAll("td").length_x000D_
)
_x000D_
<table id="table1">_x000D_
<tr>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
</tr>_x000D_
<table>
_x000D_
_x000D_
_x000D_

Count all td into each tr of table1.

_x000D_
_x000D_
table1.querySelectorAll("tr").forEach(function(e){_x000D_
 console.log( e.querySelectorAll("td").length )_x000D_
})
_x000D_
<table id="table1">_x000D_
<tr>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
</tr>_x000D_
<table>
_x000D_
_x000D_
_x000D_

How to filter specific apps for ACTION_SEND intent (and set a different text for each app)

I have improved @dacoinminster answer and this is the result with an example to share your app:

// Intents with SEND action
PackageManager packageManager = context.getPackageManager();
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
List<ResolveInfo> resolveInfoList = packageManager.queryIntentActivities(sendIntent, 0);

List<LabeledIntent> intentList = new ArrayList<LabeledIntent>();
Resources resources = context.getResources();

for (int j = 0; j < resolveInfoList.size(); j++) {
    ResolveInfo resolveInfo = resolveInfoList.get(j);
    String packageName = resolveInfo.activityInfo.packageName;
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_SEND);
    intent.setComponent(new ComponentName(packageName,
    resolveInfo.activityInfo.name));
    intent.setType("text/plain");

    if (packageName.contains("twitter")) {
        intent.putExtra(Intent.EXTRA_TEXT, resources.getString(R.string.twitter) + "https://play.google.com/store/apps/details?id=" + context.getPackageName());
    } else {
        // skip android mail and gmail to avoid adding to the list twice
        if (packageName.contains("android.email") || packageName.contains("android.gm")) {
            continue;
        }
        intent.putExtra(Intent.EXTRA_TEXT, resources.getString(R.string.largeTextForFacebookWhatsapp) + "https://play.google.com/store/apps/details?id=" + context.getPackageName());
    }

    intentList.add(new LabeledIntent(intent, packageName, resolveInfo.loadLabel(packageManager), resolveInfo.icon));
}

Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:"));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, resources.getString(R.string.subjectForMailApps));
emailIntent.putExtra(Intent.EXTRA_TEXT, resources.getString(R.string.largeTextForMailApps) + "https://play.google.com/store/apps/details?id=" + context.getPackageName());

context.startActivity(Intent.createChooser(emailIntent, resources.getString(R.string.compartirEn)).putExtra(Intent.EXTRA_INITIAL_INTENTS, intentList.toArray(new LabeledIntent[intentList.size()])));

How do I partially update an object in MongoDB so the new object will overlay / merge with the existing one

If I understand the question correctly, you want to update a document with the contents of another document, but only the fields that are not already present, and completely ignore the fields that are already set (even if to another value).

There is no way to do that in a single command.

You have to query the document first, figure out what you want to $set and then update it (using the old values as a matching filter to make sure you don't get concurrent updates in between).


Another reading of your question would be that you are happy with $set, but do not want to explicitly set all fields. How would you pass in the data then?

You know you can do the following:

db.collection.update(  { _id:...} , { $set: someObjectWithNewData } 

Remove characters except digits from string using Python?

Ugly but works:

>>> s
'aaa12333bb445bb54b5b52'
>>> a = ''.join(filter(lambda x : x.isdigit(), s))
>>> a
'1233344554552'
>>>

Assign output of os.system to a variable and prevent it from being displayed on the screen

The commands module is a reasonably high-level way to do this:

import commands
status, output = commands.getstatusoutput("cat /etc/services")

status is 0, output is the contents of /etc/services.

How can I find the version of php that is running on a distinct domain name?

I use redbot, a great tool to see php version, but also many other useful infos like headers, encoding, keepalive and many more, try it on

http://redbot.org

I loveit !

I also upvote Neil answer : curl -I http://websitename.com

How to multiply all integers inside list

Another functional approach which is maybe a little easier to look at than an anonymous function if you go that route is using functools.partial to utilize the two-parameter operator.mul with a fixed multiple

>>> from functools import partial
>>> from operator import mul
>>> double = partial(mul, 2)
>>> list(map(double, [1, 2, 3]))
[2, 4, 6]

Android: Unable to add window. Permission denied for this window type

I did manage to finally display a window on the lock screen with the use of TYPE_SYSTEM_OVERLAY instead of TYPE_KEYGUARD_DIALOG. This works as expected and adds the window on the lock screen.

The problem with this is that the window is added on top of everything it possibly can. That is, the window will even appear on top of your keypad/pattern lock in case of secure lock screens. In the case of an unsecured lock screen, it will appear on top of the notification tray if you open it from the lock screen.

For me, that is unacceptable. I hope that this may help anybody else facing this problem.

How do I read a response from Python Requests?

Requests doesn't have an equivalent to Urlib2's read().

>>> import requests
>>> response = requests.get("http://www.google.com")
>>> print response.content
'<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage"><head>....'
>>> print response.content == response.text
True

It looks like the POST request you are making is returning no content. Which is often the case with a POST request. Perhaps it set a cookie? The status code is telling you that the POST succeeded after all.

Edit for Python 3:

Python now handles data types differently. response.content returns a sequence of bytes (integers that represent ASCII) while response.text is a string (sequence of chars).

Thus,

>>> print response.content == response.text
False

>>> print str(response.content) == response.text
True

Default values and initialization in Java

In the first case you are declaring "int a" as a local variable(as declared inside a method) and local varible do not get default value.

But instance variable are given default value both for static and non-static.

Default value for instance variable:

int = 0

float,double = 0.0

reference variable = null

char = 0 (space character)

boolean = false

Raw SQL Query without DbSet - Entity Framework Core

Building on the other answers I've written this helper that accomplishes the task, including example usage:

public static class Helper
{
    public static List<T> RawSqlQuery<T>(string query, Func<DbDataReader, T> map)
    {
        using (var context = new DbContext())
        {
            using (var command = context.Database.GetDbConnection().CreateCommand())
            {
                command.CommandText = query;
                command.CommandType = CommandType.Text;

                context.Database.OpenConnection();

                using (var result = command.ExecuteReader())
                {
                    var entities = new List<T>();

                    while (result.Read())
                    {
                        entities.Add(map(result));
                    }

                    return entities;
                }
            }
        }
    }

Usage:

public class TopUser
{
    public string Name { get; set; }

    public int Count { get; set; }
}

var result = Helper.RawSqlQuery(
    "SELECT TOP 10 Name, COUNT(*) FROM Users U"
    + " INNER JOIN Signups S ON U.UserId = S.UserId"
    + " GROUP BY U.Name ORDER BY COUNT(*) DESC",
    x => new TopUser { Name = (string)x[0], Count = (int)x[1] });

result.ForEach(x => Console.WriteLine($"{x.Name,-25}{x.Count}"));

I plan to get rid of it as soon as built-in support is added. According to a statement by Arthur Vickers from the EF Core team it is a high priority for post 2.0. The issue is being tracked here.

Android camera android.hardware.Camera deprecated

API Documentation

According to the Android developers guide for android.hardware.Camera, they state:

We recommend using the new android.hardware.camera2 API for new applications.

On the information page about android.hardware.camera2, (linked above), it is stated:

The android.hardware.camera2 package provides an interface to individual camera devices connected to an Android device. It replaces the deprecated Camera class.

The problem

When you check that documentation you'll find that the implementation of these 2 Camera API's are very different.

For example getting camera orientation on android.hardware.camera

@Override
public int getOrientation(final int cameraId) {
    Camera.CameraInfo info = new Camera.CameraInfo();
    Camera.getCameraInfo(cameraId, info);
    return info.orientation;
}

Versus android.hardware.camera2

@Override
public int getOrientation(final int cameraId) {
    try {
        CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
        String[] cameraIds = manager.getCameraIdList();
        CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraIds[cameraId]);
        return characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
    } catch (CameraAccessException e) {
        // TODO handle error properly or pass it on
        return 0;
    }
}

This makes it hard to switch from one to another and write code that can handle both implementations.

Note that in this single code example I already had to work around the fact that the olde camera API works with int primitives for camera IDs while the new one works with String objects. For this example I quickly fixed that by using the int as an index in the new API. If the camera's returned aren't always in the same order this will already cause issues. Alternative approach is to work with String objects and String representation of the old int cameraIDs which is probably safer.

One away around

Now to work around this huge difference you can implement an interface first and reference that interface in your code.

Here I'll list some code for that interface and the 2 implementations. You can limit the implementation to what you actually use of the camera API to limit the amount of work.

In the next section I'll quickly explain how to load one or another.

The interface wrapping all you need, to limit this example I only have 2 methods here.

public interface CameraSupport {
    CameraSupport open(int cameraId);
    int getOrientation(int cameraId);
}

Now have a class for the old camera hardware api:

@SuppressWarnings("deprecation")
public class CameraOld implements CameraSupport {

    private Camera camera;

    @Override
    public CameraSupport open(final int cameraId) {
        this.camera = Camera.open(cameraId);
        return this;
    }

    @Override
    public int getOrientation(final int cameraId) {
       Camera.CameraInfo info = new Camera.CameraInfo();
       Camera.getCameraInfo(cameraId, info);
       return info.orientation;
    }
}

And another one for the new hardware api:

public class CameraNew implements CameraSupport {

    private CameraDevice camera;
    private CameraManager manager;

    public CameraNew(final Context context) {
        this.manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
    }

    @Override
    public CameraSupport open(final int cameraId) {
        try {
            String[] cameraIds = manager.getCameraIdList();
            manager.openCamera(cameraIds[cameraId], new CameraDevice.StateCallback() {
                @Override
                public void onOpened(CameraDevice camera) {
                    CameraNew.this.camera = camera;
                }

                @Override
                public void onDisconnected(CameraDevice camera) {
                    CameraNew.this.camera = camera;
                    // TODO handle
                }

                @Override
                public void onError(CameraDevice camera, int error) {
                    CameraNew.this.camera = camera;
                    // TODO handle
                }
            }, null);
        } catch (Exception e) {
            // TODO handle
        }
        return this;
    }

    @Override
    public int getOrientation(final int cameraId) {
        try {
            String[] cameraIds = manager.getCameraIdList();
            CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraIds[cameraId]);
            return characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
        } catch (CameraAccessException e) {
            // TODO handle
            return 0;
        }
    }
}

Loading the proper API

Now to load either your CameraOld or CameraNew class you'll have to check the API level since CameraNew is only available from api level 21.

If you have dependency injection set up already you can do so in your module when providing the CameraSupport implementation. Example:

@Module public class CameraModule {

    @Provides
    CameraSupport provideCameraSupport(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            return new CameraNew(context);
        } else {
            return new CameraOld();
        }
    } 
}

If you don't use DI you can just make a utility or use Factory pattern to create the proper one. Important part is that the API level is checked.

Difference between filter and filter_by in SQLAlchemy

filter_by is used for simple queries on the column names using regular kwargs, like

db.users.filter_by(name='Joe')

The same can be accomplished with filter, not using kwargs, but instead using the '==' equality operator, which has been overloaded on the db.users.name object:

db.users.filter(db.users.name=='Joe')

You can also write more powerful queries using filter, such as expressions like:

db.users.filter(or_(db.users.name=='Ryan', db.users.country=='England'))

How to correct indentation in IntelliJ

You can also try out ctrl + alt + I even though you can also use l as well.

Find difference between timestamps in seconds in PostgreSQL

SELECT (cast(timestamp_1 as bigint) - cast(timestamp_2 as bigint)) FROM table;

In case if someone is having an issue using extract.

How to run Python script on terminal?

If you are working with Ubuntu, sometimes you need to run as sudo:

For Python2:

sudo python gameover.py

For Python3:

sudo python3 gameover.py

How to add not null constraint to existing column in MySQL

Would like to add:

After update, such as

ALTER TABLE table_name modify column_name tinyint(4) NOT NULL;

If you get

ERROR 1138 (22004): Invalid use of NULL value

Make sure you update the table first to have values in the related column (so it's not null)

Get 2 Digit Number For The Month

append 0 before it by checking if the value falls between 1 and 9 by first casting it to varchar

select case when DATEPART(month, getdate()) between 1 and 9 
then '0' else '' end + cast(DATEPART(month, getdate()) as varchar(2))

Fail to create Android virtual Device, "No system image installed for this Target"

If you use Android Studio .Open the SDK-Manager, checked "Show Package Details" you will find out "Android Wear ARM EABI v7a System Image" download it , success !

HTML5 input type range show range value

Try This :

 <input min="0" max="100" id="when_change_range" type="range">
 <input type="text" id="text_for_show_range">

and in jQuery section :

 $('#when_change_range').change(function(){
 document.getElementById('text_for_show_range').value=$(this).val();
  });

How to insert tab character when expandtab option is on in Vim

From the documentation on expandtab:

To insert a real tab when expandtab is on, use CTRL-V<Tab>. See also :retab and ins-expandtab.
This option is reset when the paste option is set and restored when the paste option is reset.

So if you have a mapping for toggling the paste option, e.g.

set pastetoggle=<F2>

you could also do <F2>Tab<F2>.

REST API - Bulk Create or Update in single request

In a project I worked at we solved this problem by implement something we called 'Batch' requests. We defined a path /batch where we accepted json in the following format:

[  
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 1,
         binder: 1
      }
   },
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 5,
         binder: 8
      }
   },
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 6,
         binder: 3
      }
   },
]

The response have the status code 207 (Multi-Status) and looks like this:

[  
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 1,
         binder: 1
      }
      status: 200
   },
   {
      path: '/docs',
      method: 'post',
      body: {
         error: {
            msg: 'A document with doc_number 5 already exists'
            ...
         }
      },
      status: 409
   },
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 6,
         binder: 3
      },
      status: 200
   },
]

You could also add support for headers in this structure. We implemented something that proved useful which was variables to use between requests in a batch, meaning we can use the response from one request as input to another.

Facebook and Google have similar implementations:
https://developers.google.com/gmail/api/guides/batch
https://developers.facebook.com/docs/graph-api/making-multiple-requests

When you want to create or update a resource with the same call I would use either POST or PUT depending on the case. If the document already exist, do you want the entire document to be:

  1. Replaced by the document you send in (i.e. missing properties in request will be removed and already existing overwritten)?
  2. Merged with the document you send in (i.e. missing properties in request will not be removed and already existing properties will be overwritten)?

In case you want the behavior from alternative 1 you should use a POST and in case you want the behavior from alternative 2 you should use PUT.

http://restcookbook.com/HTTP%20Methods/put-vs-post/

As people already suggested you could also go for PATCH, but I prefer to keep API's simple and not use extra verbs if they are not needed.

WCF ServiceHost access rights

Open a command prompt as the administrator and you write below command to add your URL:

netsh http add urlacl url=http://+:8000/YourServiceLibrary/YourService user=Everyone

Eclipse interface icons very small on high resolution screen in Windows 8.1

The compatibility mode for Windows Xp, it's only available for the Eclipse 32 bit version and after running in this compatibility mode the icons and text will be the right size, but blurry because they are scaled from their native resolution to the screen resolution and doing so the quality is lost.

Default values in a C Struct

While macros and/or functions (as already suggested) will work (and might have other positive effects (i.e. debug hooks)), they are more complex than needed. The simplest and possibly most elegant solution is to just define a constant that you use for variable initialisation:

const struct foo FOO_DONT_CARE = { // or maybe FOO_DEFAULT or something
    dont_care, dont_care, dont_care, dont_care
};
...
struct foo bar = FOO_DONT_CARE;
bar.id = 42;
bar.current_route = new_route;
update(&bar);

This code has virtually no mental overhead of understanding the indirection, and it is very clear which fields in bar you set explicitly while (safely) ignoring those you do not set.

Passing structs to functions

Passing structs to functions by reference: simply :)

#define maxn 1000

struct solotion
{
    int sol[maxn];
    int arry_h[maxn];
    int cat[maxn];
    int scor[maxn];

};

void inser(solotion &come){
    come.sol[0]=2;
}

void initial(solotion &come){
    for(int i=0;i<maxn;i++)
        come.sol[i]=0;
}

int main()
{
    solotion sol1;
    inser(sol1);
    solotion sol2;
    initial(sol2);
}

How to change default text file encoding in Eclipse?

What worked for me in Eclipse Mars was to go to Window > Preferences > Web > HTML Files, and in the right panel in Encoding select ISO 10646/Unicode(UTF-8), Apply and OK, then and only then my .html files were created with .

Switch php versions on commandline ubuntu 16.04

Interactive switching mode

sudo update-alternatives --config php
sudo update-alternatives --config phar
sudo update-alternatives --config phar.phar

Manual Switching

From PHP 5.6 => PHP 7.1

Default PHP 5.6 is set on your system and you need to switch to PHP 7.1.

Apache:

$ sudo a2dismod php5.6
$ sudo a2enmod php7.1
$ sudo service apache2 restart

Command Line:

$ sudo update-alternatives --set php /usr/bin/php7.1
$ sudo update-alternatives --set phar /usr/bin/phar7.1
$ sudo update-alternatives --set phar.phar /usr/bin/phar.phar7.1

From PHP 7.1 => PHP 5.6

Default PHP 7.1 is set on your system and you need to switch to PHP 5.6.

Apache:

$ sudo a2dismod php7.1
$ sudo a2enmod php5.6
$ sudo service apache2 restart

Command Line:

$ sudo update-alternatives --set php /usr/bin/php5.6

Source

Is it possible to use global variables in Rust?

Heap allocations are possible for static variables if you use the lazy_static macro as seen in the docs

Using this macro, it is possible to have statics that require code to be executed at runtime in order to be initialized. This includes anything requiring heap allocations, like vectors or hash maps, as well as anything that requires function calls to be computed.

// Declares a lazily evaluated constant HashMap. The HashMap will be evaluated once and
// stored behind a global static reference.

use lazy_static::lazy_static;
use std::collections::HashMap;

lazy_static! {
    static ref PRIVILEGES: HashMap<&'static str, Vec<&'static str>> = {
        let mut map = HashMap::new();
        map.insert("James", vec!["user", "admin"]);
        map.insert("Jim", vec!["user"]);
        map
    };
}

fn show_access(name: &str) {
    let access = PRIVILEGES.get(name);
    println!("{}: {:?}", name, access);
}

fn main() {
    let access = PRIVILEGES.get("James");
    println!("James: {:?}", access);

    show_access("Jim");
}

AngularJS : The correct way of binding to a service properties

I think this question has a contextual component.

If you're simply pulling data from a service & radiating that information to it's view, I think binding directly to the service property is just fine. I don't want to write a lot of boilerplate code to simply map service properties to model properties to consume in my view.

Further, performance in angular is based on two things. The first is how many bindings are on a page. The second is how expensive getter functions are. Misko talks about this here

If you need to perform instance specific logic on the service data (as opposed to data massaging applied within the service itself), and the outcome of this impacts the data model exposed to the view, then I would say a $watcher is appropriate, as long as the function isn't terribly expensive. In the case of an expensive function, I would suggest caching the results in a local (to controller) variable, performing your complex operations outside of the $watcher function, and then binding your scope to the result of that.

As a caveat, you shouldn't be hanging any properties directly off your $scope. The $scope variable is NOT your model. It has references to your model.

In my mind, "best practice" for simply radiating information from service down to view:

function TimerCtrl1($scope, Timer) {
  $scope.model = {timerData: Timer.data};
};

And then your view would contain {{model.timerData.lastupdated}}.

How to allow only integers in a textbox?

Another solution is to use a RangeValidator where you set Type="Integer" like this:

<asp:RangeValidator runat="server"
    id="valrNumberOfPreviousOwners"
    ControlToValidate="txtNumberOfPreviousOwners"
    Type="Integer"
    MinimumValue="0"
    MaximumValue="999"
    CssClass="input-error"
    ErrorMessage="Please enter a positive integer."
    Display="Dynamic">
</asp:RangeValidator>

You can set reasonable values for the MinimumValue and MaximumValue attributes too.

How to do a recursive find/replace of a string with awk or sed?

grep -lr 'subdomainA.example.com' | while read file; do sed -i "s/subdomainA.example.com/subdomainB.example.com/g" "$file"; done

I guess most people don't know that they can pipe something into a "while read file" and it avoids those nasty -print0 args, while presevering spaces in filenames.

Further adding an echo before the sed allows you to see what files will change before actually doing it.

Invariant Violation: Could not find "store" in either the context or props of "Connect(SportsDatabase)"

This happened to me when I upgraded. I had to downgrade back.

react-redux ^5.0.6 ? ^7.1.3

Simple UDP example to send and receive data from same socket

here is my soln to define the remote and local port and then write out to a file the received data, put this all in a class of your choice with the correct imports

    static UdpClient sendClient = new UdpClient();
    static int localPort = 49999;
    static int remotePort = 49000;
    static IPEndPoint localEP = new IPEndPoint(IPAddress.Any, localPort);
    static IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), remotePort);
    static string logPath = System.AppDomain.CurrentDomain.BaseDirectory + "/recvd.txt";
    static System.IO.StreamWriter fw = new System.IO.StreamWriter(logPath, true);


    private static void initStuff()
    {
      
        fw.AutoFlush = true;
        sendClient.ExclusiveAddressUse = false;
        sendClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        sendClient.Client.Bind(localEP);
        sendClient.BeginReceive(DataReceived, sendClient);
    }

    private static void DataReceived(IAsyncResult ar)
    {
        UdpClient c = (UdpClient)ar.AsyncState;
        IPEndPoint receivedIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
        Byte[] receivedBytes = c.EndReceive(ar, ref receivedIpEndPoint);
        fw.WriteLine(DateTime.Now.ToString("HH:mm:ss.ff tt") +  " (" + receivedBytes.Length + " bytes)");

        c.BeginReceive(DataReceived, ar.AsyncState);
    }


    static void Main(string[] args)
    {
        initStuff();
        byte[] emptyByte = {};
        sendClient.Send(emptyByte, emptyByte.Length, remoteEP);
    }

Android - running a method periodically using postDelayed() call

Perhaps involve the activity's life-cycle methods to achieve this:

Handler handler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      handler.post(sendData);
}

@Override
protected void onDestroy() {
      super.onDestroy();
      handler.removeCallbacks(sendData);
}


private final Runnable sendData = new Runnable(){
    public void run(){
        try {
            //prepare and send the data here..


            handler.postDelayed(this, 1000);    
        }
        catch (Exception e) {
            e.printStackTrace();
        }   
    }
};

In this approach, if you press back-key on your activity or call finish();, it will also stop the postDelayed callings.

Select current date by default in ASP.Net Calendar control

DateTime.Now will not work, use DateTime.Today instead.

Using the star sign in grep

This worked for me:

grep ".*${expr}" - with double-quotes, preceded by the dot. Where "expr" is whatever string you need in the end of the line.

Standard unix grep w/out additional switches.

Can .NET load and parse a properties file equivalent to Java Properties class?

Final class. Thanks @eXXL.

public class Properties
{
    private Dictionary<String, String> list;
    private String filename;

    public Properties(String file)
    {
        reload(file);
    }

    public String get(String field, String defValue)
    {
        return (get(field) == null) ? (defValue) : (get(field));
    }
    public String get(String field)
    {
        return (list.ContainsKey(field))?(list[field]):(null);
    }

    public void set(String field, Object value)
    {
        if (!list.ContainsKey(field))
            list.Add(field, value.ToString());
        else
            list[field] = value.ToString();
    }

    public void Save()
    {
        Save(this.filename);
    }

    public void Save(String filename)
    {
        this.filename = filename;

        if (!System.IO.File.Exists(filename))
            System.IO.File.Create(filename);

        System.IO.StreamWriter file = new System.IO.StreamWriter(filename);

        foreach(String prop in list.Keys.ToArray())
            if (!String.IsNullOrWhiteSpace(list[prop]))
                file.WriteLine(prop + "=" + list[prop]);

        file.Close();
    }

    public void reload()
    {
        reload(this.filename);
    }

    public void reload(String filename)
    {
        this.filename = filename;
        list = new Dictionary<String, String>();

        if (System.IO.File.Exists(filename))
            loadFromFile(filename);
        else
            System.IO.File.Create(filename);
    }

    private void loadFromFile(String file)
    {
        foreach (String line in System.IO.File.ReadAllLines(file))
        {
            if ((!String.IsNullOrEmpty(line)) &&
                (!line.StartsWith(";")) &&
                (!line.StartsWith("#")) &&
                (!line.StartsWith("'")) &&
                (line.Contains('=')))
            {
                int index = line.IndexOf('=');
                String key = line.Substring(0, index).Trim();
                String value = line.Substring(index + 1).Trim();

                if ((value.StartsWith("\"") && value.EndsWith("\"")) ||
                    (value.StartsWith("'") && value.EndsWith("'")))
                {
                    value = value.Substring(1, value.Length - 2);
                }

                try
                {
                    //ignore dublicates
                    list.Add(key, value);
                }
                catch { }
            }
        }
    }


}

Sample use:

//load
Properties config = new Properties(fileConfig);
//get value whith default value
com_port.Text = config.get("com_port", "1");
//set value
config.set("com_port", com_port.Text);
//save
config.Save()

Get operating system info

Based on the answer by Fred-II I wanted to share my take on the getOS function, it avoids globals, merges both lists and detects the architecture (x32/x64)

/**
 * @param $user_agent null
 * @return string
 */
function getOS($user_agent = null)
{
    if(!isset($user_agent) && isset($_SERVER['HTTP_USER_AGENT'])) {
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
    }

    // https://stackoverflow.com/questions/18070154/get-operating-system-info-with-php
    $os_array = [
        'windows nt 10'                              =>  'Windows 10',
        'windows nt 6.3'                             =>  'Windows 8.1',
        'windows nt 6.2'                             =>  'Windows 8',
        'windows nt 6.1|windows nt 7.0'              =>  'Windows 7',
        'windows nt 6.0'                             =>  'Windows Vista',
        'windows nt 5.2'                             =>  'Windows Server 2003/XP x64',
        'windows nt 5.1'                             =>  'Windows XP',
        'windows xp'                                 =>  'Windows XP',
        'windows nt 5.0|windows nt5.1|windows 2000'  =>  'Windows 2000',
        'windows me'                                 =>  'Windows ME',
        'windows nt 4.0|winnt4.0'                    =>  'Windows NT',
        'windows ce'                                 =>  'Windows CE',
        'windows 98|win98'                           =>  'Windows 98',
        'windows 95|win95'                           =>  'Windows 95',
        'win16'                                      =>  'Windows 3.11',
        'mac os x 10.1[^0-9]'                        =>  'Mac OS X Puma',
        'macintosh|mac os x'                         =>  'Mac OS X',
        'mac_powerpc'                                =>  'Mac OS 9',
        'linux'                                      =>  'Linux',
        'ubuntu'                                     =>  'Linux - Ubuntu',
        'iphone'                                     =>  'iPhone',
        'ipod'                                       =>  'iPod',
        'ipad'                                       =>  'iPad',
        'android'                                    =>  'Android',
        'blackberry'                                 =>  'BlackBerry',
        'webos'                                      =>  'Mobile',

        '(media center pc).([0-9]{1,2}\.[0-9]{1,2})'=>'Windows Media Center',
        '(win)([0-9]{1,2}\.[0-9x]{1,2})'=>'Windows',
        '(win)([0-9]{2})'=>'Windows',
        '(windows)([0-9x]{2})'=>'Windows',

        // Doesn't seem like these are necessary...not totally sure though..
        //'(winnt)([0-9]{1,2}\.[0-9]{1,2}){0,1}'=>'Windows NT',
        //'(windows nt)(([0-9]{1,2}\.[0-9]{1,2}){0,1})'=>'Windows NT', // fix by bg

        'Win 9x 4.90'=>'Windows ME',
        '(windows)([0-9]{1,2}\.[0-9]{1,2})'=>'Windows',
        'win32'=>'Windows',
        '(java)([0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,2})'=>'Java',
        '(Solaris)([0-9]{1,2}\.[0-9x]{1,2}){0,1}'=>'Solaris',
        'dos x86'=>'DOS',
        'Mac OS X'=>'Mac OS X',
        'Mac_PowerPC'=>'Macintosh PowerPC',
        '(mac|Macintosh)'=>'Mac OS',
        '(sunos)([0-9]{1,2}\.[0-9]{1,2}){0,1}'=>'SunOS',
        '(beos)([0-9]{1,2}\.[0-9]{1,2}){0,1}'=>'BeOS',
        '(risc os)([0-9]{1,2}\.[0-9]{1,2})'=>'RISC OS',
        'unix'=>'Unix',
        'os/2'=>'OS/2',
        'freebsd'=>'FreeBSD',
        'openbsd'=>'OpenBSD',
        'netbsd'=>'NetBSD',
        'irix'=>'IRIX',
        'plan9'=>'Plan9',
        'osf'=>'OSF',
        'aix'=>'AIX',
        'GNU Hurd'=>'GNU Hurd',
        '(fedora)'=>'Linux - Fedora',
        '(kubuntu)'=>'Linux - Kubuntu',
        '(ubuntu)'=>'Linux - Ubuntu',
        '(debian)'=>'Linux - Debian',
        '(CentOS)'=>'Linux - CentOS',
        '(Mandriva).([0-9]{1,3}(\.[0-9]{1,3})?(\.[0-9]{1,3})?)'=>'Linux - Mandriva',
        '(SUSE).([0-9]{1,3}(\.[0-9]{1,3})?(\.[0-9]{1,3})?)'=>'Linux - SUSE',
        '(Dropline)'=>'Linux - Slackware (Dropline GNOME)',
        '(ASPLinux)'=>'Linux - ASPLinux',
        '(Red Hat)'=>'Linux - Red Hat',
        // Loads of Linux machines will be detected as unix.
        // Actually, all of the linux machines I've checked have the 'X11' in the User Agent.
        //'X11'=>'Unix',
        '(linux)'=>'Linux',
        '(amigaos)([0-9]{1,2}\.[0-9]{1,2})'=>'AmigaOS',
        'amiga-aweb'=>'AmigaOS',
        'amiga'=>'Amiga',
        'AvantGo'=>'PalmOS',
        //'(Linux)([0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,3}(rel\.[0-9]{1,2}){0,1}-([0-9]{1,2}) i([0-9]{1})86){1}'=>'Linux',
        //'(Linux)([0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,3}(rel\.[0-9]{1,2}){0,1} i([0-9]{1}86)){1}'=>'Linux',
        //'(Linux)([0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,3}(rel\.[0-9]{1,2}){0,1})'=>'Linux',
        '[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,3}'=>'Linux',
        '(webtv)/([0-9]{1,2}\.[0-9]{1,2})'=>'WebTV',
        'Dreamcast'=>'Dreamcast OS',
        'GetRight'=>'Windows',
        'go!zilla'=>'Windows',
        'gozilla'=>'Windows',
        'gulliver'=>'Windows',
        'ia archiver'=>'Windows',
        'NetPositive'=>'Windows',
        'mass downloader'=>'Windows',
        'microsoft'=>'Windows',
        'offline explorer'=>'Windows',
        'teleport'=>'Windows',
        'web downloader'=>'Windows',
        'webcapture'=>'Windows',
        'webcollage'=>'Windows',
        'webcopier'=>'Windows',
        'webstripper'=>'Windows',
        'webzip'=>'Windows',
        'wget'=>'Windows',
        'Java'=>'Unknown',
        'flashget'=>'Windows',

        // delete next line if the script show not the right OS
        //'(PHP)/([0-9]{1,2}.[0-9]{1,2})'=>'PHP',
        'MS FrontPage'=>'Windows',
        '(msproxy)/([0-9]{1,2}.[0-9]{1,2})'=>'Windows',
        '(msie)([0-9]{1,2}.[0-9]{1,2})'=>'Windows',
        'libwww-perl'=>'Unix',
        'UP.Browser'=>'Windows CE',
        'NetAnts'=>'Windows',
    ];

    // https://github.com/ahmad-sa3d/php-useragent/blob/master/core/user_agent.php
    $arch_regex = '/\b(x86_64|x86-64|Win64|WOW64|x64|ia64|amd64|ppc64|sparc64|IRIX64)\b/ix';
    $arch = preg_match($arch_regex, $user_agent) ? '64' : '32';

    foreach ($os_array as $regex => $value) {
        if (preg_match('{\b('.$regex.')\b}i', $user_agent)) {
            return $value.' x'.$arch;
        }
    }

    return 'Unknown';
}

indexOf Case Sensitive?

Here's a version closely resembling Apache's StringUtils version:

public int indexOfIgnoreCase(String str, String searchStr) {
    return indexOfIgnoreCase(str, searchStr, 0);
}

public int indexOfIgnoreCase(String str, String searchStr, int fromIndex) {
    // https://stackoverflow.com/questions/14018478/string-contains-ignore-case/14018511
    if(str == null || searchStr == null) return -1;
    if (searchStr.length() == 0) return fromIndex;  // empty string found; use same behavior as Apache StringUtils
    final int endLimit = str.length() - searchStr.length() + 1;
    for (int i = fromIndex; i < endLimit; i++) {
        if (str.regionMatches(true, i, searchStr, 0, searchStr.length())) return i;
    }
    return -1;
}

MySQL VARCHAR size?

VARCHAR means that it's a variable-length character, so it's only going to take as much space as is necessary. But if you knew something about the underlying structure, it may make sense to restrict VARCHAR to some maximum amount.

For instance, if you were storing comments from the user, you may limit the comment field to only 4000 characters; if so, it doesn't really make any sense to make the sql table have a field that's larger than VARCHAR(4000).

http://dev.mysql.com/doc/refman/5.0/en/char.html

Given a DateTime object, how do I get an ISO 8601 date in string format?

I would just use XmlConvert:

XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.RoundtripKind);

It will automatically preserve the time zone.

Android: findviewbyid: finding view by id when view is not on the same layout invoked by setContentView

I used

View.inflate(getContext(), R.layout.whatever, null)

The using of View.inflate prevents the warning of using null at getLayoutInflater().inflate().

How to get all of the IDs with jQuery?

It's a late answer but now there is an easy way. Current version of jquery lets you search if attribute exists. For example

$('[id]')

will give you all the elements if they have id. If you want all spans with id starting with span you can use

$('span[id^="span"]')

Change default date time format on a single database in SQL Server

You can only change the language on the whole server, not individual databases. However if you need to support the UK you can run the following command before all inputs and outputs:

set language 'british english'

Or if you are having issues entering datatimes from your application you might want to consider a universal input type such as

1-Dec-2008

What is the benefit of using "SET XACT_ABORT ON" in a stored procedure?

Regarding client timeouts and the use of XACT_ABORT to handle them, in my opinion there is at least one very good reason to have timeouts in client APIs like SqlClient, and that is to guard the client application code from deadlocks occurring in SQL server code. In this case the client code has no fault, but has to protect it self from blocking forever waiting for the command to complete on the server. So conversely, if client timeouts have to exist to protect client code, so does XACT_ABORT ON has to protect server code from client aborts, in case the server code takes longer to execute than the client is willing to wait for.

What does mysql error 1025 (HY000): Error on rename of './foo' (errorno: 150) mean?

If you are using a client like MySQL Workbench, right click the desired table from where a foreign key is to be deleted, then select the foreign key tab and delete the indexes.

Then you can run the query like this:

alter table table_name drop foreign_key_col_name;

Detecting IE11 using CSS Capability/Feature Detection

This seems to work:

@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {  
   /* IE10+ specific styles go here */  
}

https://www.limecanvas.com/css-hacks-for-targeting-ie-10-and-above/

Find files with size in Unix

Assuming you have GNU find:

find . -size +10000k -printf '%s %f\n'

If you want a constant width for the size field, you can do something like:

find . -size +10000k -printf '%10s %f\n'

Note that -size +1000k selects files of at least 10,240,000 bytes (k is 1024, not 1000). You said in a comment that you want files bigger than 1M; if that's 1024*1024 bytes, then this:

find . -size +1M ...

will do the trick -- except that it will also print the size and name of files that are exactly 1024*1024 bytes. If that matters, you could use:

find . -size +1048575c ...

You need to decide just what criterion you want.

How do you get the logical xor of two variables in Python?

Exclusive Or is defined as follows

def xor( a, b ):
    return (a or b) and not (a and b)

Where do I find old versions of Android NDK?

The 64 bit versions are available also:

http://dl.google.com/android/ndk/android-ndk-r8e-darwin-x86_64.tar.bz2

just replace the R8E release/version/iteration

How to display the string html contents into webbrowser control?

Instead of navigating to blank, you can do

webBrowser1.DocumentText="0";
webBrowser1.Document.OpenNew(true);
webBrowser1.Document.Write(theHTML);
webBrowser1.Refresh();

No need to wait for events or anything else. You can check the MSDN for OpenNew, while I have tested the initial DocumentText assignment in one of my projects and it works.

How do you say not equal to in Ruby?

Yes. In Ruby the not equal to operator is:

!=

You can get a full list of ruby operators here: https://www.tutorialspoint.com/ruby/ruby_operators.htm.

Typescript: Type 'string | undefined' is not assignable to type 'string'

You can use the NonNullable Utility Type:

Example

type T0 = NonNullable<string | number | undefined>;  // string | number
type T1 = NonNullable<string[] | null | undefined>;  // string[]

Docs.

Save child objects automatically using JPA Hibernate

Here are the ways to assign parent object in child object of Bi-directional relations ?

Suppose you have a relation say One-To-Many,then for each parent object,a set of child object exists. In bi-directional relations,each child object will have reference to its parent.

eg : Each Department will have list of Employees and each Employee is part of some department.This is called Bi directional relations.

To achieve this, one way is to assign parent in child object while persisting parent object

Parent parent = new Parent();
...
Child c1 = new Child();
...
c1.setParent(parent);

List<Child> children = new ArrayList<Child>();
children.add(c1);
parent.setChilds(children);

session.save(parent);

Other way is, you can do using hibernate Intercepter,this way helps you not to write above code for all models.

Hibernate interceptor provide apis to do your own work before perform any DB operation.Likewise onSave of object, we can assign parent object in child objects using reflection.

public class CustomEntityInterceptor extends EmptyInterceptor {

    @Override
    public boolean onSave(
            final Object entity, final Serializable id, final Object[] state, final String[] propertyNames,
            final Type[] types) {
        if (types != null) {
            for (int i = 0; i < types.length; i++) {
                if (types[i].isCollectionType()) {
                    String propertyName = propertyNames[i];
                    propertyName = propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
                    try {
                        Method method = entity.getClass().getMethod("get" + propertyName);
                        List<Object> objectList = (List<Object>) method.invoke(entity);

                        if (objectList != null) {
                            for (Object object : objectList) {
                                String entityName = entity.getClass().getSimpleName();
                                Method eachMethod = object.getClass().getMethod("set" + entityName, entity.getClass());
                                eachMethod.invoke(object, entity);
                            }
                        }

                    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
        return true;
    }

}

And you can register Intercepter to configuration as

new Configuration().setInterceptor( new CustomEntityInterceptor() );

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

This is how to retrieve a Column Name from a DataColumn:

MyDataTable.Columns(1).ColumnName 

To get the name of all DataColumns within your DataTable:

Dim name(DT.Columns.Count) As String
Dim i As Integer = 0
For Each column As DataColumn In DT.Columns
  name(i) = column.ColumnName
  i += 1
Next

References

How to add multiple classes to a ReactJS Component?

If you don't feel like importing another module, this function works like the classNames module.

function classNames(rules) {
    var classes = ''

    Object.keys(rules).forEach(item => {    
        if (rules[item])
            classes += (classes.length ? ' ' : '') + item
    })

    return classes
} 

You can use it like this:

render() {
    var classes = classNames({
        'storeInfoDiv': true,  
        'hover': this.state.isHovered == this.props.store.store_id
    })   

    return (
        <SomeComponent style={classes} />
    )
}

Count work days between two dates

(I'm a few points shy of commenting privileges)

If you decide to forgo the +1 day in CMS's elegant solution, note that if your start date and end date are in the same weekend, you get a negative answer. Ie., 2008/10/26 to 2008/10/26 returns -1.

my rather simplistic solution:

select @Result = (..CMS's answer..)
if  (@Result < 0)
        select @Result = 0
    RETURN @Result

.. which also sets all erroneous posts with start date after end date to zero. Something you may or may not be looking for.

How to include (source) R script in other scripts

Say util.R produces a function foo(). You can check if this function is available in the global environment and source the script if it isn't:

if(identical(length(ls(pattern = "^foo$")), 0))
    source("util.R")

That will find anything with the name foo. If you want to find a function, then (as mentioned by @Andrie) exists() is helpful but needs to be told exactly what type of object to look for, e.g.

if(exists("foo", mode = "function"))
    source("util.R")

Here is exists() in action:

> exists("foo", mode = "function")
[1] FALSE
> foo <- function(x) x
> exists("foo", mode = "function")
[1] TRUE
> rm(foo)
> foo <- 1:10
> exists("foo", mode = "function")
[1] FALSE

Curl command without using cache

The -H 'Cache-Control: no-cache' argument is not guaranteed to work because the remote server or any proxy layers in between can ignore it. If it doesn't work, you can do it the old-fashioned way, by adding a unique querystring parameter. Usually, the servers/proxies will think it's a unique URL and not use the cache.

curl "http://www.example.com?foo123"

You have to use a different querystring value every time, though. Otherwise, the server/proxies will match the cache again. To automatically generate a different querystring parameter every time, you can use date +%s, which will return the seconds since epoch.

curl "http://www.example.com?$(date +%s)"

Converting string to title case

I used the above references and complete solution is:-

Use Namespace System.Globalization;
string str="INFOA2Z means all information";

//Need result like "Infoa2z Means All Information"
//We need to convert the string in lowercase also, otherwise it is not working properly.

TextInfo ProperCase= new CultureInfo("en-US", false).TextInfo;

str= ProperCase.ToTitleCase(str.toLower());

http://www.infoa2z.com/asp.net/change-string-to-proper-case-in-an-asp.net-using-c#

What is the most "pythonic" way to iterate over a list in chunks?

Modified from the recipes section of Python's itertools docs:

from itertools import zip_longest

def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

Example
In pseudocode to keep the example terse.

grouper('ABCDEFG', 3, 'x') --> 'ABC' 'DEF' 'Gxx'

Note: on Python 2 use izip_longest instead of zip_longest.

Remove a modified file from pull request

Switch to the branch from which you created the pull request:

$ git checkout pull-request-branch

Overwrite the modified file(s) with the file in another branch, let's consider it's master:

git checkout origin/master -- src/main/java/HelloWorld.java

Commit and push it to the remote:

git commit -m "Removed a modified file from pull request"
git push origin pull-request-branch

regex string replace

Just change + to -:

str = str.replace(/[^a-z0-9-]/g, "");

You can read it as:

  1. [^ ]: match NOT from the set
  2. [^a-z0-9-]: match if not a-z, 0-9 or -
  3. / /g: do global match

More information:

Thymeleaf: Concatenation - Could not parse as expression


We can concat Like this :


<h5 th:text ="${currentItem.first_name}+ ' ' + ${currentItem.last_name}"></h5>

Parse an URL in JavaScript

I wrote a javascript url parsing library, URL.js, you can use it for this.

Example:

url.parse("http://mysite.com/form_image_edit.php?img_id=33").get.img_id === "33"

jQuery - on change input text

This is from a comment on the jQuery documentation page:

In older, pre-HTML5 browsers, "keyup" is definitely what you're looking for.

In HTML5 there is a new event, "input", which behaves exactly like you seem to think "change" should have behaved - in that it fires as soon as a key is pressed to enter information into a form.

$('element').bind('input',function);

Access Control Request Headers, is added to header in AJAX request with jQuery

Here is an example how to set a request header in a jQuery Ajax call:

$.ajax({
  type: "POST",
  beforeSend: function(request) {
    request.setRequestHeader("Authority", authorizationToken);
  },
  url: "entities",
  data: "json=" + escape(JSON.stringify(createRequestObject)),
  processData: false,
  success: function(msg) {
    $("#results").append("The result =" + StringifyPretty(msg));
  }
});

Null vs. False vs. 0 in PHP

Null is nothing, False is a bit, and 0 is (probably) 32 bits.

Not a PHP expert, but in some of the more modern languages those aren't interchangeable. I kind of miss having 0 and false be interchangeable, but with boolean being an actual type you can have methods and objects associated with it so that's just a tradeoff. Null is null though, the absence of anything essentially.

How to convert a NumPy array to PIL image applying matplotlib colormap

Quite a busy one-liner, but here it is:

  1. First ensure your NumPy array, myarray, is normalised with the max value at 1.0.
  2. Apply the colormap directly to myarray.
  3. Rescale to the 0-255 range.
  4. Convert to integers, using np.uint8().
  5. Use Image.fromarray().

And you're done:

from PIL import Image
from matplotlib import cm
im = Image.fromarray(np.uint8(cm.gist_earth(myarray)*255))

with plt.savefig():

Enter image description here

with im.save():

Enter image description here

Can anyone explain python's relative imports?

If you are going to call relative.py directly and i.e. if you really want to import from a top level module you have to explicitly add it to the sys.path list.
Here is how it should work:

# Add this line to the beginning of relative.py file
import sys
sys.path.append('..')

# Now you can do imports from one directory top cause it is in the sys.path
import parent

# And even like this:
from parent import Parent

If you think the above can cause some kind of inconsistency you can use this instead:

sys.path.append(sys.path[0] + "/..")

sys.path[0] refers to the path that the entry point was ran from.

Any way to make plot points in scatterplot more transparent in R?

If you are using the hex codes, you can add two more digits at the end of the code to represent the alpha channel:

E.g. half-transparency red:

plot(1:100, main="Example of Plot With Transparency")
lines(1:100 + sin(1:100*2*pi/(20)), col='#FF000088', lwd=4)
mtext("use `col='#FF000088'` for the lines() function")

example plot of color with transparency

How to get the indexpath.row when an element is activated?

Extend UITableView to create function that get indexpath for a view:

extension UITableView {
    func indexPath(for view: UIView) -> IndexPath? {
        self.indexPathForRow(at: view.convert(.zero, to: self))
    }
}

How to use:

let row = tableView.indexPath(for: sender)?.row

Linux bash script to extract IP address

  /sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'

Setting the selected attribute on a select list using jQuery

I'd iterate through the options, comparing the text to what I want to be selected, then set the selected attribute on that option. Once you find the correct one, terminate the iteration (unless you have a multiselect).

 $('#dropdown').find('option').each( function() {
      var $this = $(this);
      if ($this.text() == 'B') {
         $this.attr('selected','selected');
         return false;
      }
 });

cannot call member function without object

You are right - you declared a new use defined type (Name_pairs) and you need variable of that type to use it.

The code should go like this:

Name_pairs np;
np.read_names()

Update value of a nested dictionary of varying depth

Just use python-benedict (I did it), it has a merge (deepupdate) utility method and many others. It works with python 2 / python 3 and it is well tested.

from benedict import benedict

dictionary1=benedict({'level1':{'level2':{'levelA':0,'levelB':1}}})
update={'level1':{'level2':{'levelB':10}}}
dictionary1.merge(update)
print(dictionary1)
# >> {'level1':{'level2':{'levelA':0,'levelB':10}}}

Installation: pip install python-benedict

Documentation: https://github.com/fabiocaccamo/python-benedict

Note: I am the author of this project

How do I create a file AND any folders, if the folders don't exist?

. given a path, how can we recursively create all the folders necessary to create the file .. for that path

Creates all directories and subdirectories as specified by path.

Directory.CreateDirectory(path);

then you may create a file.

ScrollTo function in AngularJS

I used andrew joslin's answer, which works great but triggered an angular route change, which created a jumpy looking scroll for me. If you want to avoid triggering a route change,

myApp.directive('scrollOnClick', function() {
  return {
    restrict: 'A',
    link: function(scope, $elm, attrs) {
      var idToScroll = attrs.href;
      $elm.on('click', function(event) {
        event.preventDefault();
        var $target;
        if (idToScroll) {
          $target = $(idToScroll);
        } else {
          $target = $elm;
        }
        $("body").animate({scrollTop: $target.offset().top}, "slow");
        return false;
      });
    }
  }
});

Reverting to a specific commit based on commit id with Git?

If you want to force the issue, you can do:

git reset --hard c14809fafb08b9e96ff2879999ba8c807d10fb07

send you back to how your git clone looked like at the time of the checkin

How to remove outliers in boxplot in R?

See ?boxplot for all the help you need.

 outline: if ‘outline’ is not true, the outliers are not drawn (as
          points whereas S+ uses lines).

boxplot(x,horizontal=TRUE,axes=FALSE,outline=FALSE)

And for extending the range of the whiskers and suppressing the outliers inside this range:

   range: this determines how far the plot whiskers extend out from the
          box.  If ‘range’ is positive, the whiskers extend to the most
          extreme data point which is no more than ‘range’ times the
          interquartile range from the box. A value of zero causes the
          whiskers to extend to the data extremes.

# change the value of range to change the whisker length
boxplot(x,horizontal=TRUE,axes=FALSE,range=2)

How to float a div over Google Maps?

Try this:

<style>
   #wrapper { position: relative; }
   #over_map { position: absolute; top: 10px; left: 10px; z-index: 99; }
</style>

<div id="wrapper">
   <div id="google_map">

   </div>

   <div id="over_map">

   </div>
</div>

When should I use Kruskal as opposed to Prim (and vice versa)?

One important application of Kruskal's algorithm is in single link clustering.

Consider n vertices and you have a complete graph.To obtain a k clusters of those n points.Run Kruskal's algorithm over the first n-(k-1) edges of the sorted set of edges.You obtain k-cluster of the graph with maximum spacing.

Converting Array to List

If you are dealing with String[] instead of int[], We can use

ArrayList<String> list = new ArrayList<>();
list.addAll(Arrays.asList(StringArray));

How to get cumulative sum

A CTE version, just for fun:

;
WITH  abcd
        AS ( SELECT id
                   ,SomeNumt
                   ,SomeNumt AS MySum
             FROM   @t
             WHERE  id = 1
             UNION ALL
             SELECT t.id
                   ,t.SomeNumt
                   ,t.SomeNumt + a.MySum AS MySum
             FROM   @t AS t
                    JOIN abcd AS a ON a.id = t.id - 1
           )
  SELECT  *  FROM    abcd
OPTION  ( MAXRECURSION 1000 ) -- limit recursion here, or 0 for no limit.

Returns:

id          SomeNumt    MySum
----------- ----------- -----------
1           10          10
2           12          22
3           3           25
4           15          40
5           23          63

Use different Python version with virtualenv

These are the steps you can follow when you are on a shared hosting environment and need to install & compile Python from source and then create venv from your Python version. For Python 2.7.9. you would do something along these lines:

mkdir ~/src
wget http://www.python.org/ftp/python/2.7.9/Python-2.7.9.tgz
tar -zxvf Python-2.7.9.tgz
cd Python-2.7.9
mkdir ~/.localpython
./configure --prefix=$HOME/.localpython
make
make install

virtual env

cd ~/src
wget https://pypi.python.org/packages/5c/79/5dae7494b9f5ed061cff9a8ab8d6e1f02db352f3facf907d9eb614fb80e9/virtualenv-15.0.2.tar.gz#md5=0ed59863994daf1292827ffdbba80a63
tar -zxvf virtualenv-15.0.2.tar.gz
cd virtualenv-15.0.2/
~/.localpython/bin/python setup.py install
virtualenv ve -p $HOME/.localpython/bin/python2.7
source ve/bin/activate   

Naturally, this can be applicable to any situation where you want to replicate the exact environment you work and deploy on.

Convert .pem to .crt and .key

0. Prerequisite: openssl should be installed. On Windows, if Git Bash is installed, try that! Alternate binaries can be found here.

1. Extract .key from .pem:

openssl pkey -in cert.pem -out cert.key

2. Extract .crt from .pem:

openssl crl2pkcs7 -nocrl -certfile cert.pem | openssl pkcs7 -print_certs -out cert.crt

Use of def, val, and var in scala

To provide another perspective, "def" in Scala means something that will be evaluated each time when it's used, while val is something that is evaluated immediately and only once. Here, the expression def person = new Person("Kumar",12) entails that whenever we use "person" we will get a new Person("Kumar",12) call. Therefore it's natural that the two "person.age" are non-related.

This is the way I understand Scala(probably in a more "functional" manner). I'm not sure if

def defines a method
val defines a fixed value (which cannot be modified)
var defines a variable (which can be modified)

is really what Scala intends to mean though. I don't really like to think that way at least...

Is there a way to specify a default property value in Spring XML?

<foo name="port">
   <value>${my.server.port:8088}</value>
</foo>

should work for you to have 8088 as default port

See also: http://blog.callistaenterprise.se/2011/11/17/configure-your-spring-web-application/

Assignment inside lambda expression in Python

TL;DR: When using functional idioms it's better to write functional code

As many people have pointed out, in Python lambdas assignment is not allowed. In general when using functional idioms your better off thinking in a functional manner which means wherever possible no side effects and no assignments.

Here is functional solution which uses a lambda. I've assigned the lambda to fn for clarity (and because it got a little long-ish).

from operator import add
from itertools import ifilter, ifilterfalse
fn = lambda l, pred: add(list(ifilter(pred, iter(l))), [ifilterfalse(pred, iter(l)).next()])
objs = [Object(name=""), Object(name="fake_name"), Object(name="")]
fn(objs, lambda o: o.name != '')

You can also make this deal with iterators rather than lists by changing things around a little. You also have some different imports.

from itertools import chain, islice, ifilter, ifilterfalse
fn = lambda l, pred: chain(ifilter(pred, iter(l)), islice(ifilterfalse(pred, iter(l)), 1))

You can always reoganize the code to reduce the length of the statements.

Array.Add vs +=

If you want a dynamically sized array, then you should make a list. Not only will you get the .Add() functionality, but as @frode-f explains, dynamic arrays are more memory efficient and a better practice anyway.

And it's so easy to use.

Instead of your array declaration, try this:

$outItems = New-Object System.Collections.Generic.List[System.Object]

Adding items is simple.

$outItems.Add(1)
$outItems.Add("hi")

And if you really want an array when you're done, there's a function for that too.

$outItems.ToArray()

Checkboxes in web pages – how to make them bigger?

In case this can help anyone, here's simple CSS as a jumping off point. Turns it into a basic rounded square big enough for thumbs with a toggled background color.

_x000D_
_x000D_
input[type='checkbox'] {_x000D_
    -webkit-appearance:none;_x000D_
    width:30px;_x000D_
    height:30px;_x000D_
    background:white;_x000D_
    border-radius:5px;_x000D_
    border:2px solid #555;_x000D_
}_x000D_
input[type='checkbox']:checked {_x000D_
    background: #abd;_x000D_
}
_x000D_
<input type="checkbox" />
_x000D_
_x000D_
_x000D_

What version of javac built my jar?

I build a little bash script (on github) based on Davids suggestion using the file command

Sort dataGridView columns in C# ? (Windows Form)

You can control the data returned from SQL database by ordering the data returned:

orderby [Name]

If you execute the SQL query from your application, order the data returned. For example, make a function that calls the procedure or executes the SQL and give it a parameter that gets the orderby criteria. Because if you ordered the data returned from database it will consume time but order it since it's executed as you say that you want it to be ordered not from the UI you want it to be ordered in the run time so order it when executing the SQL query.

Generate .pem file used to set up Apple Push Notifications

To enable Push Notification for your iOS app, you will need to create and upload the Apple Push Notification Certificate (.pem file) to us so we will be able to connect to Apple Push Server on your behalf.

(Updated version with updated screen shots Here)

Step 1: Login to iOS Provisioning Portal, click "Certificates" on the left navigation bar. Then, click "+" button.

enter image description here

Step 2: Select Apple Push Notification service SSL (Production) option under Distribution section, then click "Continue" button.

enter image description here

Step 3: Select the App ID you want to use for your BYO app (How to Create An App ID), then click "Continue" to go to next step.

enter image description here

Step 4: Follow the steps "About Creating a Certificate Signing Request (CSR)" to create a Certificate Signing Request.

enter image description here

To supplement the instruction provided by Apple. Here are some of the additional screenshots to assist you to complete the required steps:

Step 4 Supplementary Screenshot 1: Navigate to Certificate Assistant of Keychain Access on your Mac.

enter image description here

Step 4 Supplementary Screenshot 2: Fill in the Certificate Information. Click Continue.

enter image description here

Step 5: Upload the ".certSigningRequest" file which is generated in Step 4, then click "Generate" button.

enter image description here

Step 6: Click "Done" to finish the registration, the iOS Provisioning Portal Page will be refreshed that looks like the following screen:

enter image description here

Then Click "Download" button to download the certificate (.cer file) you've created just now. - Double click the downloaded file to install the certificate into Keychain Access on your Mac.

Step 7: On your Mac, go to "Keychain", look for the certificate you have just installed. If unsure which certificate is the correct one, it should start with "Apple Production IOS Push Services:" followed by your app's bundle ID.

enter image description here

Step 8: Expand the certificate, you should see the private key with either your name or your company name. Select both items by using the "Select" key on your keyboard, right click (or cmd-click if you use a single button mouse), choose "Export 2 items", like Below:

enter image description here

Then save the p12 file with name "pushcert.p12" to your Desktop - now you will be prompted to enter a password to protect it, you can either click Enter to skip the password or enter a password you desire.

Step 9: Now the most difficult part - open "Terminal" on your Mac, and run the following commands:

cd
cd Desktop
openssl pkcs12 -in pushcert.p12 -out pushcert.pem -nodes -clcerts

Step 10: Remove pushcert.p12 from Desktop to avoid mis-uploading it to Build Your Own area. Open "Terminal" on your Mac, and run the following commands:

cd
cd Desktop
rm pushcert.p12

Step 11 - NEW AWS UPDATE: Create new pushcert.p12 to submit to AWS SNS. Double click on the new pushcert.pem, then export the one highlighed on the green only.

enter image description here Credit: AWS new update

Now you have successfully created an Apple Push Notification Certificate (.p12 file)! You will need to upload this file to our Build Your Own area later on. :)

Validate fields after user has left a field

ng-model-options in AngularJS 1.3 (beta as of this writing) is documented to support {updateOn: 'blur'}. For earlier versions, something like the following worked for me:

myApp.directive('myForm', function() {
  return {
    require: 'form',
    link: function(scope, element, attrs, formController) {
      scope.validate = function(name) {
        formController[name].isInvalid
            = formController[name].$invalid;
      };
    }
  };
});

With a template like this:

<form name="myForm" novalidate="novalidate" data-my-form="">
<input type="email" name="eMail" required="required" ng-blur="validate('eMail')" />
<span ng-show="myForm.eMail.isInvalid">Please enter a valid e-mail address.</span>
<button type="submit">Submit Form</button>
</form>

How to 'grep' a continuous stream?

you may consider this answer as enhancement .. usually I am using

tail -F <fileName> | grep --line-buffered  <pattern> -A 3 -B 5

-F is better in case of file rotate (-f will not work properly if file rotated)

-A and -B is useful to get lines just before and after the pattern occurrence .. these blocks will appeared between dashed line separators

But For me I prefer doing the following

tail -F <file> | less

this is very useful if you want to search inside streamed logs. I mean go back and forward and look deeply

How to open my files in data_folder with pandas using relative path?

Try

import pandas as pd
pd.read_csv("../data_folder/data.csv")

On delete cascade with doctrine2

There are two kinds of cascades in Doctrine:

1) ORM level - uses cascade={"remove"} in the association - this is a calculation that is done in the UnitOfWork and does not affect the database structure. When you remove an object, the UnitOfWork will iterate over all objects in the association and remove them.

2) Database level - uses onDelete="CASCADE" on the association's joinColumn - this will add On Delete Cascade to the foreign key column in the database:

@ORM\JoinColumn(name="father_id", referencedColumnName="id", onDelete="CASCADE")

I also want to point out that the way you have your cascade={"remove"} right now, if you delete a Child object, this cascade will remove the Parent object. Clearly not what you want.

Convert java.util.date default format to Timestamp in Java

java.time

I am providing the modern answer. The Timestamp class was always poorly designed, a real hack on top of the already poorly designed Date class. Both those classes are now long outdated. Don’t use them.

When the question was asked, you would need a Timestamp for sending a point in time to the SQL database. Since JDBC 4.2 that is no longer the case. Assuming your database needs a timestamp with time zone (recommended for true timestamps), pass it an OffsetDateTime.

Before we can do that we need to overcome a real trouble with your sample string, Mon May 27 11:46:15 IST 2013: the time zone abbreviation. IST may mean Irish Summer Time, Israel Standard Time or India Standard Time (I have even read that Java may parse it into Atlantic/Reykjavik time zone — Icelandic Standard Time?) To control the interpretation we pass our preferred time zone to the formatter that we are using for parsing.

    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .appendPattern("EEE MMM dd HH:mm:ss ")
            .appendZoneText(TextStyle.SHORT, Set.of(ZoneId.of("Asia/Kolkata")))
            .appendPattern(" yyyy")
            .toFormatter(Locale.ROOT);
    String dateString = "Mon May 27 11:46:15 IST 2013";
    OffsetDateTime dateTime = formatter.parse(dateString, Instant::from)
            .atOffset(ZoneOffset.UTC);
    System.out.println(dateTime);

This snippet prints:

2013-05-27T06:16:15Z

This is the UTC equivalent of your string (assuming IST was for India Standard Time). Pass the OffsetDateTime to your database using one of the PreparedStatement.setObject methods (not setTimestamp).

How can I convert this into timestamp and calculate in seconds the difference between the same and current time?

Calculating the difference in seconds goes very naturally with java.time:

    long differenceInSeconds = ChronoUnit.SECONDS
            .between(dateTime, OffsetDateTime.now(ZoneOffset.UTC));
    System.out.println(differenceInSeconds);

When running just now I got:

202213260

Link: Oracle tutorial: Date Time explaining how to use java.time.

Parsing JSON Array within JSON Object

Your code is fine, just replace the following line:

JSONArray jsonMainArr = new JSONArray(mainJSON.getJSONArray("source"));

with this line:

JSONArray jsonMainArr = mainJSON.getJSONArray("source");

how to check the dtype of a column in python pandas

I know this is a bit of an old thread but with pandas 19.02, you can do:

df.select_dtypes(include=['float64']).apply(your_function)
df.select_dtypes(exclude=['string','object']).apply(your_other_function)

http://pandas.pydata.org/pandas-docs/version/0.19.2/generated/pandas.DataFrame.select_dtypes.html

Is it possible to indent JavaScript code in Notepad++?

I think you want a code beautifier, this one looks quick and easy: http://jsbeautifier.org/

Detect enter press in JTextField

Do you want to do something like this ?

JTextField mTextField = new JTextField();
    mTextField.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            if(e.getKeyCode() == KeyEvent.VK_ENTER){
                // something like...
               //mTextField.getText();
               // or...
               //mButton.doClick();
            }
        }

    });

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

In PL/SQL v.10

keyword declare is used to declare variable

DECLARE stupidvar varchar(20);

to assign a value you can set it when you declare

DECLARE stupidvar varchar(20) := '12345678';

or to select something into that variable you use INTO statement, however you need to wrap statement in BEGIN and END, also you need to make sure that only single value is returned, and don't forget semicolons.

so the full statement would come out following:

DECLARE stupidvar varchar(20);
BEGIN
    SELECT stupid into stupidvar FROM stupiddata CC 
    WHERE stupidid = 2;
END;

Your variable is only usable within BEGIN and END so if you want to use more than one you will have to do multiple BEGIN END wrappings

DECLARE stupidvar varchar(20);
BEGIN
    SELECT stupid into stupidvar FROM stupiddata CC 
    WHERE stupidid = 2;

    DECLARE evenmorestupidvar varchar(20);
    BEGIN
        SELECT evenmorestupid into evenmorestupidvar FROM evenmorestupiddata CCC 
        WHERE evenmorestupidid = 42;

        INSERT INTO newstupiddata (newstupidcolumn, newevenmorestupidstupidcolumn)
        SELECT stupidvar, evenmorestupidvar 
        FROM dual

    END;
END;

Hope this saves you some time

Convert array of integers to comma-separated string

Use LINQ Aggregate method to convert array of integers to a comma separated string

var intArray = new []{1,2,3,4};
string concatedString = intArray.Aggregate((a, b) =>Convert.ToString(a) + "," +Convert.ToString( b));
Response.Write(concatedString);

output will be

1,2,3,4

This is one of the solution you can use if you have not .net 4 installed.

Python: count repeated elements in the list

Use Counter

>>> from collections import Counter
>>> MyList = ["a", "b", "a", "c", "c", "a", "c"]
>>> c = Counter(MyList)
>>> c
Counter({'a': 3, 'c': 3, 'b': 1})

How to plot two columns of a pandas data frame using points?

You can specify the style of the plotted line when calling df.plot:

df.plot(x='col_name_1', y='col_name_2', style='o')

The style argument can also be a dict or list, e.g.:

import numpy as np
import pandas as pd

d = {'one' : np.random.rand(10),
     'two' : np.random.rand(10)}

df = pd.DataFrame(d)

df.plot(style=['o','rx'])

All the accepted style formats are listed in the documentation of matplotlib.pyplot.plot.

Output

GCC dump preprocessor defines

A portable approach that works equally well on Linux or Windows (where there is no /dev/null):

echo | gcc -dM -E -

For c++ you may use (replace c++11 with whatever version you use):

echo | gcc -x c++ -std=c++11 -dM -E -

It works by telling gcc to preprocess stdin (which is produced by echo) and print all preprocessor defines (search for -dletters). If you want to know what defines are added when you include a header file you can use -dD option which is similar to -dM but does not include predefined macros:

echo "#include <stdlib.h>" | gcc -x c++ -std=c++11 -dD -E -

Note, however, that empty input still produces lots of defines with -dD option.

How to use setInterval and clearInterval?

Side note – if you want to use separate functions to set & clear interval, the interval variable have to be accessible for all of them, in 'relative global', or 'one level up' scope:

var interval = null;    

function startStuff(func, time) {
    interval = setInterval(func, time);
}

function stopStuff() {
    clearInterval(interval);
}

git: Switch branch and ignore any changes without committing

switching to a new branch losing changes:

git checkout -b YOUR_NEW_BRANCH_NAME --force

switching to an existing branch losing changes:

git checkout YOUR_BRANCH --force

Could not load file or assembly '' or one of its dependencies

To make Visual Studio adding 3rd party assembly or even your own assembly from other project in solution to GAC please do next:

  1. Open Package.package from Package folder in SharePoint project.

  2. Click Advanced in bottom area.

  3. Click Add and chose which type of assembly you want to add.

  4. In dialog select dll file, chec GAC or BIN, add safe controls and class resources entries if required. Click Ok.

Your assembly will be packaged to WSP, defined in manifest and deployed everytime.

Execution failed for task ':app:compileDebugAidl': aidl is missing

buildtools layout in 23.0.0.rc2 was reverted

so to be able to use it, you need to upgrade the plugin to 1.3.0-beta2 or higher as i show below:

enter image description here

Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies

I solved this issue by removing all the NuGet packages from solution and reinstalling them. One of the NuGet Packages was dependent upon NewtonSoft and it was not showing in references

How do I delete multiple rows with different IDs?

Delete from BA_CITY_MASTER where CITY_NAME in (select CITY_NAME from BA_CITY_MASTER group by CITY_NAME having count(CITY_NAME)>1);

Can we overload the main method in Java?

Yes According to my point of view, we are able to overload the main method but method overloading that's it. For Example

class main_overload {
    public static void main(int a) {
        System.out.println(a);
    }
    public static void main(String args[]) {
        System.out.println("That's My Main Function");
        main(100);
    }
}

In This Double Back slash Step, I am just calling the main method....

Editor does not contain a main type

A simpler way is to close the project and reopen it.

How do I create a new Git branch from an old commit?

git checkout -b NEW_BRANCH_NAME COMMIT_ID

This will create a new branch called 'NEW_BRANCH_NAME' and check it out.

("check out" means "to switch to the branch")

git branch NEW_BRANCH_NAME COMMIT_ID

This just creates the new branch without checking it out.


in the comments many people seem to prefer doing this in two steps. here's how to do so in two steps:

git checkout COMMIT_ID
# you are now in the "detached head" state
git checkout -b NEW_BRANCH_NAME

get dictionary key by value

I was in a situation where Linq binding was not available and had to expand lambda explicitly. It resulted in a simple function:

public static T KeyByValue<T, W>(this Dictionary<T, W> dict, W val)
{
    T key = default;
    foreach (KeyValuePair<T, W> pair in dict)
    {
        if (EqualityComparer<W>.Default.Equals(pair.Value, val))
        {
            key = pair.Key;
            break;
        }
    }
    return key;
}

Call it like follows:

public static void Main()
{
    Dictionary<string, string> dict = new Dictionary<string, string>()
    {
        {"1", "one"},
        {"2", "two"},
        {"3", "three"}
    };

    string key = KeyByValue(dict, "two");       
    Console.WriteLine("Key: " + key);
}

Works on .NET 2.0 and in other limited environments.

SQL Query - Concatenating Results into One String

For SQL Server 2005 and above use Coalesce for nulls and I am using Cast or Convert if there are numeric values -

declare @CodeNameString  nvarchar(max)
select  @CodeNameString = COALESCE(@CodeNameString + ',', '')  + Cast(CodeName as varchar) from AccountCodes  ORDER BY Sort
select  @CodeNameString

converting json to string in python

There are other differences. For instance, {'time': datetime.now()} cannot be serialized to JSON, but can be converted to string. You should use one of these tools depending on the purpose (i.e. will the result later be decoded).