Programs & Examples On #Retaincount

#NAME?

Creating a SearchView that looks like the material design guidelines

To achieve desired look of SearchView, you can use styles.

First, you need to create style for your SearchView, which should look something like this:

<style name="CustomSearchView" parent="Widget.AppCompat.SearchView">
    <item name="searchIcon">@null</item>
    <item name="queryBackground">@null</item>
</style>

Whole list of attributes you can find at this article, under the "SearchView" section.

Secondly, you need to create a style for your Toolbar, which is used as ActionBar:

<style name="ToolbarSearchView" parent="Base.ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="searchViewStyle">@style/CustomSearchView</item>
</style>

And finally you need to update your Toolbar theme attribute this way:

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    app:theme="@style/ToolbarSearchView" />

Result:

enter image description here

NOTE: You need to change your Toolbar theme attribute directly. If you'll just update your main theme searchViewStyle attribute it wouldn't affect your Toolbar.

Floating point vs integer calculations on modern hardware

Two points to consider -

Modern hardware can overlap instructions, execute them in parallel and reorder them to make best use of the hardware. And also, any significant floating point program is likely to have significant integer work too even if it's only calculating indices into arrays, loop counter etc. so even if you have a slow floating point instruction it may well be running on a separate bit of hardware overlapped with some of the integer work. My point being that even if the floating point instructions are slow that integer ones, your overall program may run faster because it can make use of more of the hardware.

As always, the only way to be sure is to profile your actual program.

Second point is that most CPUs these days have SIMD instructions for floating point that can operate on multiple floating point values all at the same time. For example you can load 4 floats into a single SSE register and the perform 4 multiplications on them all in parallel. If you can rewrite parts of your code to use SSE instructions then it seems likely it will be faster than an integer version. Visual c++ provides compiler intrinsic functions to do this, see http://msdn.microsoft.com/en-us/library/x5c07e2a(v=VS.80).aspx for some information.

python: get directory two levels up

(pathlib.Path('../../') ).resolve()

I want to multiply two columns in a pandas DataFrame and add the result into a new column

If we're willing to sacrifice the succinctness of Hayden's solution, one could also do something like this:

In [22]: orders_df['C'] = orders_df.Action.apply(
               lambda x: (1 if x == 'Sell' else -1))

In [23]: orders_df   # New column C represents the sign of the transaction
Out[23]:
   Prices  Amount Action  C
0       3      57   Sell  1
1      89      42   Sell  1
2      45      70    Buy -1
3       6      43   Sell  1
4      60      47   Sell  1
5      19      16    Buy -1
6      56      89   Sell  1
7       3      28    Buy -1
8      56      69   Sell  1
9      90      49    Buy -1

Now we have eliminated the need for the if statement. Using DataFrame.apply(), we also do away with the for loop. As Hayden noted, vectorized operations are always faster.

In [24]: orders_df['Value'] = orders_df.Prices * orders_df.Amount * orders_df.C

In [25]: orders_df   # The resulting dataframe
Out[25]:
   Prices  Amount Action  C  Value
0       3      57   Sell  1    171
1      89      42   Sell  1   3738
2      45      70    Buy -1  -3150
3       6      43   Sell  1    258
4      60      47   Sell  1   2820
5      19      16    Buy -1   -304
6      56      89   Sell  1   4984
7       3      28    Buy -1    -84
8      56      69   Sell  1   3864
9      90      49    Buy -1  -4410

This solution takes two lines of code instead of one, but is a bit easier to read. I suspect that the computational costs are similar as well.

System.loadLibrary(...) couldn't find native library in my case

actually, you can't just put a .so file in the /libs/armeabi/ and load it with System.loadLibrary. You need to create an Android.mk file and declare a prebuilt module where you specify your .so file as a source.

To do so, put your .so file and the Android.mk file in the jni folder. Your Android.mk should look something like that:

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)
LOCAL_MODULE    := libcalculate
LOCAL_SRC_FILES := libcalculate.so
include $(PREBUILT_SHARED_LIBRARY)

Source : Android NDK documentation about prebuilt

An internal error occurred during: "Updating Maven Project". Unsupported IClasspathEntry kind=4

I had to do it slightly different to work for me:

  1. rightclick project, remove maven nature (or in newer eclipse, "Maven->Disable Maven Nature")
  2. mvn eclipse:clean (with project open in eclipse/STS)
  3. delete the project in eclipse (but do not delete the sources)
  4. Import existing Maven project

How to kill a child process after a given timeout in Bash?

#Kill command after 10 seconds
timeout 10 command

#If you don't have timeout installed, this is almost the same:
sh -c '(sleep 10; kill "$$") & command'

#The same as above, with muted duplicate messages:
sh -c '(sleep 10; kill "$$" 2>/dev/null) & command'

Find a class somewhere inside dozens of JAR files?

I've always used this on Windows and its worked exceptionally well.

findstr /s /m /c:"package/classname" *.jar, where

findstr.exe comes standard with Windows and the params:

  • /s = recursively
  • /m = print only the filename if there is a match
  • /c = literal string (in this case your package name + class names separated by '/')

Hope this helps someone.

Listening for variable changes in JavaScript

Not directly: you need a pair getter/setter with an "addListener/removeListener" interface of some sort... or an NPAPI plugin (but that's another story altogether).

How to strip a specific word from a string?

Providing you know the index value of the beginning and end of each word you wish to replace in the character array, and you only wish to replace that particular chunk of data, you could do it like this.

>>> s = "papa is papa is papa"
>>> s = s[:8]+s[8:13].replace("papa", "mama")+s[13:]
>>> print(s)
papa is mama is papa

Alternatively, if you also wish to retain the original data structure, you could store it in a dictionary.

>>> bin = {}
>>> s = "papa is papa is papa"
>>> bin["0"] = s
>>> s = s[:8]+s[8:13].replace("papa", "mama")+s[13:]
>>> print(bin["0"])
papa is papa is papa
>>> print(s)
papa is mama is papa

How to save a Python interactive session?

As far as Linux goes, one can use script command to record the whole session. It is part of util-linux package so should be on most Linux systems . You can create and alias or function that will call script -c python and that will be saved to a typescript file. For instance, here's a reprint of one such file.

$ cat typescript                                                                                                      
Script started on Sat 14 May 2016 08:30:08 AM MDT
Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print 'Hello Pythonic World'
Hello Pythonic World
>>> 

Script done on Sat 14 May 2016 08:30:42 AM MDT

Small disadvantage here is that the script records everything , even line-feeds, whenever you hit backspaces , etc. So you may want to use col to clean up the output (see this post on Unix&Linux Stackexchange) .

Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries

Since Django 2.0 the ForeignKey field requires two positional arguments:

  1. the model to map to
  2. the on_delete argument
categorie = models.ForeignKey('Categorie', on_delete=models.PROTECT)

Here are some methods can used in on_delete

  1. CASCADE

Cascade deletes. Django emulates the behavior of the SQL constraint ON DELETE CASCADE and also deletes the object containing the ForeignKey

  1. PROTECT

Prevent deletion of the referenced object by raising ProtectedError, a subclass of django.db.IntegrityError.

  1. DO_NOTHING

Take no action. If your database backend enforces referential integrity, this will cause an IntegrityError unless you manually add an SQL ON DELETE constraint to the database field.

you can find more about on_delete by reading the documentation.

I need an unordered list without any bullets

ul{list-style-type:none;}

Just set the style of unordered list is none.

Is it possible to disable the network in iOS Simulator?

You can use Little Snitch to cut off network traffic to any individual process, including ones that run on the iOS simulator. That way you can keep your internet connection and disconnect your running app.

Reading from file using read() function

Read Byte by Byte and check that each byte against '\n' if it is not, then store it into buffer
if it is '\n' add '\0' to buffer and then use atoi()

You can read a single byte like this

char c;
read(fd,&c,1);

See read()

Java NIO: What does IOException: Broken pipe mean?

Broken pipe simply means that the connection has failed. It is reasonable to assume that this is unrecoverable, and to then perform any required cleanup actions (closing connections, etc). I don't believe that you would ever see this simply due to the connection not yet being complete.

If you are using non-blocking mode then the SocketChannel.connect method will return false, and you will need to use the isConnectionPending and finishConnect methods to insure that the connection is complete. I would generally code based upon the expectation that things will work, and then catch exceptions to detect failure, rather than relying on frequent calls to "isConnected".

Action Bar's onClick listener for the Home button

if anyone else need the solution

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == android.R.id.home) {
        onBackPressed();  return true;
    }

    return super.onOptionsItemSelected(item);
}

What is the difference between ( for... in ) and ( for... of ) statements?

There are some already defined data types which allows us to iterate over them easily e.g Array, Map, String Objects

Normal for in iterates over the iterator and in response provides us with the keys that are in the order of insertion as shown in below example.

  const numbers = [1,2,3,4,5];
   for(let number in number) {
     console.log(number);
   }

   // result: 0, 1, 2, 3, 4

Now if we try same with for of, then in response it provides us with the values not the keys. e.g

  const numbers = [1,2,3,4,5];
   for(let numbers of numbers) {
    console.log(number);
  }

  // result: 1, 2, 3, 4, 5

So looking at both of the iterators we can easily differentiate the difference between both of them.

Note:- For of only works with the Symbol.iterator

So if we try to iterate over normal object, then it will give us an error e.g-

const Room = {
   area: 1000,
   height: 7,
   floor: 2
 }

for(let prop in Room) {
 console.log(prop);
 } 

// Result area, height, floor

for(let prop of Room) {
  console.log(prop);
 } 

Room is not iterable

Now for iterating over we need to define an ES6 Symbol.iterator e.g

  const Room= {
    area: 1000, height: 7, floor: 2,
   [Symbol.iterator]: function* (){
    yield this.area;
    yield this.height;
    yield this.floors;
  }
}


for(let prop of Room) {
  console.log(prop);
 } 

//Result 1000, 7, 2

This is the difference between For in and For of. Hope that it might clear the difference.

Fatal error: Out of memory, but I do have plenty of memory (PHP)

I ran accross the same kind of problem with the server dying when trying to use the swap. This is because mod_php does not free memory ever. So Apache processes keep growing either reaching apache or PHP's memory limit or, if there's no limit, crashing the server.

Restarting apache makes it to spawn new fresh slim processes but as they run PHP scripts over time, they grow until problems arise.

The solution is to make apache to kill processes after a certain number of queries served so it will create new ones ( There are some questions related to that) reducing the MaxRequestsPerChild configuration option to, let's say 100 (Defaults to 1000).

Of course this may reduce server performances as it takes ressources to kill and spawn new processes but at least it keeps the site working. You might be tempted to raise the number of running processes to keep performances high, be sure PHP (or apache) memory limit x max number of processes do not get over your server's physical ram.

Here's my experience, hope it helps.

Android ListView with onClick items

You start new activities with intents. One method to send data to an intent is to pass a class that implements parcelable in the intent. Take note you are passing a copy of the class.

http://developer.android.com/reference/android/os/Parcelable.html

Here I have an onItemClick. I create intent and putExtra an entire class into the intent. The class I'm sending has implemented parcelable. Tip: You only need implement the parseable over what is minimally needed to re-create the class. Ie maybe a filename or something simple like a string something that a constructor can use to create the class. The new activity can later getExtras and it is essentially creating a copy of the class with its constructor method.

Here I launch the kmlreader class of my app when I recieve an onclick in the listview.

Note: below summary is a list of the class that I am passing so get(position) returns the class infact it is the same list that populates the listview

List<KmlSummary> summary = null;
...

public final static String EXTRA_KMLSUMMARY = "com.gosylvester.bestrides.util.KmlSummary";

...

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
        long id) {
    lastshownitem = position;
    Intent intent = new Intent(context, KmlReader.class);
    intent.putExtra(ImageTextListViewActivity.EXTRA_KMLSUMMARY,
            summary.get(position));
    startActivity(intent);
}

later in the new activity I pull out the parseable class with

kmlSummary = intent.getExtras().getParcelable(
                ImageTextListViewActivity.EXTRA_KMLSUMMARY);

//note:
//KmlSummary implements parcelable.
//there is a constructor method for parcel in
// and a overridden writetoparcel method
// these are really easy to setup.

public KmlSummary(Parcel in) {
    this._id = in.readInt();
    this._description = in.readString();
    this._name = in.readString();
    this.set_bounds(in.readDouble(), in.readDouble(), in.readDouble(),
    in.readDouble());
    this._resrawid = in.readInt();
    this._resdrawableid = in.readInt();
     this._pathstring = in.readString();
    String s = in.readString();
    this.set_isThumbCreated(Boolean.parseBoolean(s));
}

@Override
public void writeToParcel(Parcel arg0, int arg1) {
    arg0.writeInt(this._id);
    arg0.writeString(this._description);
    arg0.writeString(this._name);
    arg0.writeDouble(this.get_bounds().southwest.latitude);
    arg0.writeDouble(this.get_bounds().southwest.longitude);
    arg0.writeDouble(this.get_bounds().northeast.latitude);
    arg0.writeDouble(this.get_bounds().northeast.longitude);
    arg0.writeInt(this._resrawid);
    arg0.writeInt(this._resdrawableid);
    arg0.writeString(this.get_pathstring());
    String s = Boolean.toString(this.isThumbCreated());
    arg0.writeString(s);
}

Good Luck Danny117

Multiple IF AND statements excel

Consider that you have multiple "tests", e.g.,

  1. If E2 = 'in play' and F2 = 'closed', output 3
  2. If E2 = 'in play' and F2 = 'suspended', output 2
  3. Etc.

What you really need to do is put successive tests in the False argument. You're presently trying to separate each test by a comma, and that won't work.

Your first three tests can all be joined in one expression like:

=IF(E2="In Play",IF(F2="Closed",3,IF(F2="suspended",2,IF(F2="Null",1))))

Remembering that each successive test needs to be the nested FALSE argument of the preceding test, you can do this:

=IF(E2="In Play",IF(F2="Closed",3,IF(F2="suspended",2,IF(F2="Null",1))),IF(AND(E2="Pre-Play",F2="Null"),-1,IF(AND(E2="completed",F2="closed"),2,IF(AND(E2="suspended",F2="Null"),3,-2))))

How to change the color of header bar and address bar in newest Chrome version on Lollipop?

You actually need 3 meta tags to support Android, iPhone and Windows Phone

<!-- Chrome, Firefox OS and Opera -->
<meta name="theme-color" content="#4285f4">
<!-- Windows Phone -->
<meta name="msapplication-navbutton-color" content="#4285f4">
<!-- iOS Safari -->
<meta name="apple-mobile-web-app-status-bar-style" content="#4285f4">

How to generate a QR Code for an Android application?

Here is my simple and working function to generate a Bitmap! I Use ZXing1.3.jar only! I've also set Correction Level to High!

PS: x and y are reversed, it's normal, because bitMatrix reverse x and y. This code works perfectly with a square image.

public static Bitmap generateQrCode(String myCodeText) throws WriterException {
    Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
    hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // H = 30% damage

    QRCodeWriter qrCodeWriter = new QRCodeWriter();

    int size = 256;

    ByteMatrix bitMatrix = qrCodeWriter.encode(myCodeText,BarcodeFormat.QR_CODE, size, size, hintMap);
    int width = bitMatrix.width();
    Bitmap bmp = Bitmap.createBitmap(width, width, Bitmap.Config.RGB_565);
    for (int x = 0; x < width; x++) {
        for (int y = 0; y < width; y++) {
            bmp.setPixel(y, x, bitMatrix.get(x, y)==0 ? Color.BLACK : Color.WHITE);
        }
    }
    return bmp;
}

EDIT

It's faster to use bitmap.setPixels(...) with a pixel int array instead of bitmap.setPixel one by one:

        BitMatrix bitMatrix = writer.encode(inputValue, BarcodeFormat.QR_CODE, size, size);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        int[] pixels = new int[width * height];
        for (int y = 0; y < height; y++) {
            int offset = y * width;
            for (int x = 0; x < width; x++) {
                pixels[offset + x] = bitMatrix.get(x, y) ? BLACK : WHITE;
            }
        }

        bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);

C# "internal" access modifier when doing unit testing

I'm using .NET Core 3.1.101 and the .csproj additions that worked for me were:

<PropertyGroup>
  <!-- Explicitly generate Assembly Info -->
  <GenerateAssemblyInfo>true</GenerateAssemblyInfo>
</PropertyGroup>

<ItemGroup>
  <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleToAttribute">
  <_Parameter1>MyProject.Tests</_Parameter1>
  </AssemblyAttribute>
</ItemGroup>

Python error message io.UnsupportedOperation: not readable

This will let you read, write and create the file if it don't exist:

f = open('filename.txt','a+')
f = open('filename.txt','r+')

Often used commands:

f.readline() #Read next line
f.seek(0) #Jump to beginning
f.read(0) #Read all file
f.write('test text') #Write 'test text' to file
f.close() #Close file

Bash Script : what does #!/bin/bash mean?

When the first characters in a script are #!, that is called the shebang. If your file starts with #!/path/to/something the standard is to run something and pass the rest of the file to that program as an input.

With that said, the difference between #!/bin/bash, #!/bin/sh, or even #!/bin/zsh is whether the bash, sh, or zsh programs are used to interpret the rest of the file. bash and sh are just different programs, traditionally. On some Linux systems they are two copies of the same program. On other Linux systems, sh is a link to dash, and on traditional Unix systems (Solaris, Irix, etc) bash is usually a completely different program from sh.

Of course, the rest of the line doesn't have to end in sh. It could just as well be #!/usr/bin/python, #!/usr/bin/perl, or even #!/usr/local/bin/my_own_scripting_language.

Get time in milliseconds using C#

I use the following class. I found it on the Internet once, postulated to be the best NOW().

/// <summary>Class to get current timestamp with enough precision</summary>
static class CurrentMillis
{
    private static readonly DateTime Jan1St1970 = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    /// <summary>Get extra long current timestamp</summary>
    public static long Millis { get { return (long)((DateTime.UtcNow - Jan1St1970).TotalMilliseconds); } }
}

Source unknown.

ERROR 1049 (42000): Unknown database 'mydatabasename'

If dump file contains:

CREATE DATABASE mydatabasename;
USE mydatabasename; 

You may just use in CLI:

mysql -uroot –pmypassword < mydatabase.sql

It works.

Insert into ... values ( SELECT ... FROM ... )

Instead of VALUES part of INSERT query, just use SELECT query as below.

INSERT INTO table1 ( column1 , 2, 3... )
SELECT col1, 2, 3... FROM table2

How to make an input type=button act like a hyperlink and redirect using a get request?

I think that is your need.

a href="#" onclick="document.forms[0].submit();return false;"

How to save a pandas DataFrame table as a png

Pandas allows you to plot tables using matplotlib (details here). Usually this plots the table directly onto a plot (with axes and everything) which is not what you want. However, these can be removed first:

import matplotlib.pyplot as plt
import pandas as pd
from pandas.table.plotting import table # EDIT: see deprecation warnings below

ax = plt.subplot(111, frame_on=False) # no visible frame
ax.xaxis.set_visible(False)  # hide the x axis
ax.yaxis.set_visible(False)  # hide the y axis

table(ax, df)  # where df is your data frame

plt.savefig('mytable.png')

The output might not be the prettiest but you can find additional arguments for the table() function here. Also thanks to this post for info on how to remove axes in matplotlib.


EDIT:

Here is a (admittedly quite hacky) way of simulating multi-indexes when plotting using the method above. If you have a multi-index data frame called df that looks like:

first  second
bar    one       1.991802
       two       0.403415
baz    one      -1.024986
       two      -0.522366
foo    one       0.350297
       two      -0.444106
qux    one      -0.472536
       two       0.999393
dtype: float64

First reset the indexes so they become normal columns

df = df.reset_index() 
df
    first second       0
0   bar    one  1.991802
1   bar    two  0.403415
2   baz    one -1.024986
3   baz    two -0.522366
4   foo    one  0.350297
5   foo    two -0.444106
6   qux    one -0.472536
7   qux    two  0.999393

Remove all duplicates from the higher order multi-index columns by setting them to an empty string (in my example I only have duplicate indexes in "first"):

df.ix[df.duplicated('first') , 'first'] = '' # see deprecation warnings below
df
  first second         0
0   bar    one  1.991802
1          two  0.403415
2   baz    one -1.024986
3          two -0.522366
4   foo    one  0.350297
5          two -0.444106
6   qux    one -0.472536
7          two  0.999393

Change the column names over your "indexes" to the empty string

new_cols = df.columns.values
new_cols[:2] = '',''  # since my index columns are the two left-most on the table
df.columns = new_cols 

Now call the table function but set all the row labels in the table to the empty string (this makes sure the actual indexes of your plot are not displayed):

table(ax, df, rowLabels=['']*df.shape[0], loc='center')

et voila:

enter image description here

Your not-so-pretty but totally functional multi-indexed table.

EDIT: DEPRECATION WARNINGS

As pointed out in the comments, the import statement for table:

from pandas.tools.plotting import table

is now deprecated in newer versions of pandas in favour of:

from pandas.plotting import table 

EDIT: DEPRECATION WARNINGS 2

The ix indexer has now been fully deprecated so we should use the loc indexer instead. Replace:

df.ix[df.duplicated('first') , 'first'] = ''

with

df.loc[df.duplicated('first') , 'first'] = ''

PHP sessions default timeout

It depends on the server configuration or the relevant directives session.gc_maxlifetime in php.ini.

Typically the default is 24 minutes (1440 seconds), but your webhost may have altered the default to something else.

How can I iterate JSONObject to get individual items

You can try this it will recursively find all key values in a json object and constructs as a map . You can simply get which key you want from the Map .

public static Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
    Iterator<String> keys = json.keys();
    while(keys.hasNext()){
        String key = keys.next();
        String val = null;
        try{
             JSONObject value = json.getJSONObject(key);
             parse(value,out);
        }catch(Exception e){
            val = json.getString(key);
        }

        if(val != null){
            out.put(key,val);
        }
    }
    return out;
}

 public static void main(String[] args) throws JSONException {

    String json = "{'ipinfo': {'ip_address': '131.208.128.15','ip_type': 'Mapped','Location': {'continent': 'north america','latitude': 30.1,'longitude': -81.714,'CountryData': {'country': 'united states','country_code': 'us'},'region': 'southeast','StateData': {'state': 'florida','state_code': 'fl'},'CityData': {'city': 'fleming island','postal_code': '32003','time_zone': -5}}}}";

    JSONObject object = new JSONObject(json);

    JSONObject info = object.getJSONObject("ipinfo");

    Map<String,String> out = new HashMap<String, String>();

    parse(info,out);

    String latitude = out.get("latitude");
    String longitude = out.get("longitude");
    String city = out.get("city");
    String state = out.get("state");
    String country = out.get("country");
    String postal = out.get("postal_code");

    System.out.println("Latitude : " + latitude + " LongiTude : " + longitude + " City : "+city + " State : "+ state + " Country : "+country+" postal "+postal);

    System.out.println("ALL VALUE " + out);

}

Output:

    Latitude : 30.1 LongiTude : -81.714 City : fleming island State : florida Country : united states postal 32003
ALL VALUE {region=southeast, ip_type=Mapped, state_code=fl, state=florida, country_code=us, city=fleming island, country=united states, time_zone=-5, ip_address=131.208.128.15, postal_code=32003, continent=north america, longitude=-81.714, latitude=30.1}

PHP If Statement with Multiple Conditions

You can try this:

<?php
    echo (($var=='abc' || $var=='def' || $var=='hij' || $var=='klm' || $var=='nop') ? "true" : "false");
?>

How to atomically delete keys matching a pattern using Redis

I tried most of methods mentioned above but they didn't work for me, after some searches I found these points:

  • if you have more than one db on redis you should determine the database using -n [number]
  • if you have a few keys use del but if there are thousands or millions of keys it's better to use unlink because unlink is non-blocking while del is blocking, for more information visit this page unlink vs del
  • also keys are like del and is blocking

so I used this code to delete keys by pattern:

 redis-cli -n 2 --scan --pattern '[your pattern]' | xargs redis-cli -n 2 unlink 

Deciding between HttpClient and WebClient

I have benchmark between HttpClient, WebClient, HttpWebResponse then call Rest Web Api

and result Call Rest Web Api Benchmark

---------------------Stage 1  ---- 10 Request

{00:00:17.2232544} ====>HttpClinet
{00:00:04.3108986} ====>WebRequest
{00:00:04.5436889} ====>WebClient

---------------------Stage 1  ---- 10 Request--Small Size
{00:00:17.2232544}====>HttpClinet
{00:00:04.3108986}====>WebRequest
{00:00:04.5436889}====>WebClient

---------------------Stage 3  ---- 10 sync Request--Small Size
{00:00:15.3047502}====>HttpClinet
{00:00:03.5505249}====>WebRequest
{00:00:04.0761359}====>WebClient

---------------------Stage 4  ---- 100 sync Request--Small Size
{00:03:23.6268086}====>HttpClinet
{00:00:47.1406632}====>WebRequest
{00:01:01.2319499}====>WebClient

---------------------Stage 5  ---- 10 sync Request--Max Size

{00:00:58.1804677}====>HttpClinet    
{00:00:58.0710444}====>WebRequest    
{00:00:38.4170938}====>WebClient
    
---------------------Stage 6  ---- 10 sync Request--Max Size

{00:01:04.9964278}====>HttpClinet    
{00:00:59.1429764}====>WebRequest    
{00:00:32.0584836}====>WebClient

_____ WebClient Is faster ()

var stopWatch = new Stopwatch();
        stopWatch.Start();
        for (var i = 0; i < 10; ++i)
        {
            CallGetHttpClient();
            CallPostHttpClient();
        }

        stopWatch.Stop();

        var httpClientValue = stopWatch.Elapsed;

        stopWatch = new Stopwatch();

        stopWatch.Start();
        for (var i = 0; i < 10; ++i)
        {
            CallGetWebRequest();
            CallPostWebRequest();
        }

        stopWatch.Stop();

        var webRequesttValue = stopWatch.Elapsed;


        stopWatch = new Stopwatch();

        stopWatch.Start();
        for (var i = 0; i < 10; ++i)
        {

            CallGetWebClient();
            CallPostWebClient();

        }

        stopWatch.Stop();

        var webClientValue = stopWatch.Elapsed;

//-------------------------Functions

private void CallPostHttpClient()
    {
        var httpClient = new HttpClient();
        httpClient.BaseAddress = new Uri("https://localhost:44354/api/test/");
        var responseTask = httpClient.PostAsync("PostJson", null);
        responseTask.Wait();

        var result = responseTask.Result;
        var readTask = result.Content.ReadAsStringAsync().Result;

    }
    private void CallGetHttpClient()
    {
        var httpClient = new HttpClient();
        httpClient.BaseAddress = new Uri("https://localhost:44354/api/test/");
        var responseTask = httpClient.GetAsync("getjson");
        responseTask.Wait();

        var result = responseTask.Result;
        var readTask = result.Content.ReadAsStringAsync().Result;

    }
    private string CallGetWebRequest()
    {
        var request = (HttpWebRequest)WebRequest.Create("https://localhost:44354/api/test/getjson");

        request.Method = "GET";
        request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;

        var content = string.Empty;

        using (var response = (HttpWebResponse)request.GetResponse())
        {
            using (var stream = response.GetResponseStream())
            {
                using (var sr = new StreamReader(stream))
                {
                    content = sr.ReadToEnd();
                }
            }
        }

        return content;
    }
    private string CallPostWebRequest()
    {

        var apiUrl = "https://localhost:44354/api/test/PostJson";


        HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(new Uri(apiUrl));
        httpRequest.ContentType = "application/json";
        httpRequest.Method = "POST";
        httpRequest.ContentLength = 0;

        using (var httpResponse = (HttpWebResponse)httpRequest.GetResponse())
        {
            using (Stream stream = httpResponse.GetResponseStream())
            {
                var json = new StreamReader(stream).ReadToEnd();
                return json;
            }
        }

        return "";
    }

    private string CallGetWebClient()
    {
        string apiUrl = "https://localhost:44354/api/test/getjson";


        var client = new WebClient();

        client.Headers["Content-type"] = "application/json";

        client.Encoding = Encoding.UTF8;

        var json = client.DownloadString(apiUrl);


        return json;
    }

    private string CallPostWebClient()
    {
        string apiUrl = "https://localhost:44354/api/test/PostJson";


        var client = new WebClient();

        client.Headers["Content-type"] = "application/json";

        client.Encoding = Encoding.UTF8;

        var json = client.UploadString(apiUrl, "");


        return json;
    }

Play infinitely looping video on-load in HTML5

For iPhone it works if you add also playsinline so:

<video width="320" height="240" autoplay loop muted playsinline>
  <source src="movie.mp4" type="video/mp4" />
</video>

Passing arrays as url parameter

Edit: Don't miss Stefan's solution above, which uses the very handy http_build_query() function: https://stackoverflow.com/a/1764199/179125

knittl is right on about escaping. However, there's a simpler way to do this:

$url = 'http://example.com/index.php?';
$url .= 'aValues[]=' . implode('&amp;aValues[]=', array_map('urlencode', $aValues));

If you want to do this with an associative array, try this instead:

PHP 5.3+ (lambda function)

$url = 'http://example.com/index.php?';
$url .= implode('&amp;', array_map(function($key, $val) {
    return 'aValues[' . urlencode($key) . ']=' . urlencode($val);
  },
  array_keys($aValues), $aValues)
);

PHP <5.3 (callback)

function urlify($key, $val) {
  return 'aValues[' . urlencode($key) . ']=' . urlencode($val);
}

$url = 'http://example.com/index.php?';
$url .= implode('&amp;', array_map('urlify', array_keys($aValues), $aValues));

Manage toolbar's navigation and back button from fragment in android

Add a toolbar to your xml

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Fragment title"/>

</android.support.v7.widget.Toolbar>

Then inside your onCreateView method in the Fragment:

Toolbar toolbar = view.findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.ic_back_button);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
         getActivity().onBackPressed();
    }
});

Search all of Git history for a string?

Try the following commands to search the string inside all previous tracked files:

git log --patch  | less +/searching_string

or

git rev-list --all | GIT_PAGER=cat xargs git grep 'search_string'

which needs to be run from the parent directory where you'd like to do the searching.

How to check if input file is empty in jQuery

Just check the length of files property, which is a FileList object contained on the input element

if( document.getElementById("videoUploadFile").files.length == 0 ){
    console.log("no files selected");
}

Typing the Enter/Return key using Python and Selenium

To enter keys using Selenium, first you need to import the following library:

import org.openqa.selenium.Keys

then add this code where you want to enter the key

WebElement.sendKeys(Keys.RETURN);

You can replace RETURN with any key from the list according to your requirement.

Select data from "show tables" MySQL query

You may be closer than you think — SHOW TABLES already behaves a lot like SELECT:

$pdo = new PDO("mysql:host=$host;dbname=$dbname",$user,$pass);
foreach ($pdo->query("SHOW TABLES") as $row) {
    print "Table $row[Tables_in_$dbname]\n";
}

How to create an integer-for-loop in Ruby?

If you're doing this in your erb view (for Rails), be mindful of the <% and <%= differences. What you'd want is:

<% (1..x).each do |i| %>
  Code to display using <%= stuff %> that you want to display    
<% end %>

For plain Ruby, you can refer to: http://www.tutorialspoint.com/ruby/ruby_loops.htm

How do I copy a 2 Dimensional array in Java?

You can give below code a try,

public void multiArrayCopy(int[][] source,int[][] destination){
destination=source.clone();}

Hope it works.

Checking the form field values before submitting that page

Don't know for sure, but it sounds like it is still submitting. I quick solution would be to change your (guessing at your code here):

<input type="submit" value="Submit" onclick="checkform()">

to a button:

<input type="button" value="Submit" onclick="checkform()">

That way your form still gets submitted (from the else part of your checkform()) and it shouldn't be reloading the page.

There are other, perhaps better, ways of handling it but this works in the mean time.

How do I validate a date in rails?

I'm guessing you're using the date_select helper to generate the tags for the date. Another way you could do it is to use select form helper for the day, month, year fields. Like this (example I used is the created_at date field):

<%= f.select :month, (1..12).to_a, selected: @user.created_at.month %>
<%= f.select :day, (1..31).to_a, selected: @user.created_at.day %>
<%= f.select :year, ((Time.now.year - 20)..Time.now.year).to_a, selected: @user.created_at.year %>

And in the model, you validate the date:

attr_accessor :month, :day, :year
validate :validate_created_at

private

def convert_created_at
  begin
    self.created_at = Date.civil(self.year.to_i, self.month.to_i, self.day.to_i)
  rescue ArgumentError
    false
  end
end

def validate_created_at
  errors.add("Created at date", "is invalid.") unless convert_created_at
end

If you're looking for a plugin solution, I'd checkout the validates_timeliness plugin. It works like this (from the github page):

class Person < ActiveRecord::Base
  validates_date :date_of_birth, on_or_before: lambda { Date.current }
  # or
  validates :date_of_birth, timeliness: { on_or_before: lambda { Date.current }, type: :date }
end 

The list of validation methods available are as follows:

validates_date     - validate value as date
validates_time     - validate value as time only i.e. '12:20pm'
validates_datetime - validate value as a full date and time
validates          - use the :timeliness key and set the type in the hash.

Using Python to execute a command on every file in a folder

I had a similar problem, with a lot of help from the web and this post I made a small application, my target is VCD and SVCD and I don't delete the source but I reckon it will be fairly easy to adapt to your own needs.

It can convert 1 video and cut it or can convert all videos in a folder, rename them and put them in a subfolder /VCD

I also add a small interface, hope someone else find it useful!

I put the code and file in here btw: http://tequilaphp.wordpress.com/2010/08/27/learning-python-making-a-svcd-gui/

Has an event handler already been added?

If this is the only handler, you can check to see if the event is null, if it isn't, the handler has been added.

I think you can safely call -= on the event with your handler even if it's not added (if not, you could catch it) -- to make sure it isn't in there before adding.

How to empty a Heroku database

Assuming you want to reset your PostgreSQL database and set it back up, use:

heroku apps

to list your applications on Heroku. Find the name of your current application (application_name). Then run

heroku config | grep POSTGRESQL

to get the name of your databases. An example could be

HEROKU_POSTGRESQL_WHITE_URL

Finally, given application_name and database_url, you should run

heroku pg:reset `database_url` --confirm `application_name`
heroku run rake db:migrate
heroku restart

What's the most efficient way to test two integer ranges for overlap?

If someone is looking for a one-liner which calculates the actual overlap:

int overlap = ( x2 > y1 || y2 < x1 ) ? 0 : (y2 >= y1 && x2 <= y1 ? y1 : y2) - ( x2 <= x1 && y2 >= x1 ? x1 : x2) + 1; //max 11 operations

If you want a couple fewer operations, but a couple more variables:

bool b1 = x2 <= y1;
bool b2 = y2 >= x1;
int overlap = ( !b1 || !b2 ) ? 0 : (y2 >= y1 && b1 ? y1 : y2) - ( x2 <= x1 && b2 ? x1 : x2) + 1; // max 9 operations

Declaring and initializing arrays in C

There is no such particular way in which you can initialize the array after declaring it once.

There are three options only:

1.) initialize them in different lines :

int array[SIZE];

array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
//...
//...
//...

But thats not what you want i guess.

2.) Initialize them using a for or while loop:

for (i = 0; i < MAX ; i++)  {
    array[i] = i;
}

This is the BEST WAY by the way to achieve your goal.

3.) In case your requirement is to initialize the array in one line itself, you have to define at-least an array with initialization. And then copy it to your destination array, but I think that there is no benefit of doing so, in that case you should define and initialize your array in one line itself.

And can I ask you why specifically you want to do so???

SQL Server - NOT IN

SELECT  *  FROM Table1 
WHERE MAKE+MODEL+[Serial Number]  not in
    (select make+model+[serial number] from Table2 
     WHERE make+model+[serial number] IS NOT NULL)

That worked for me, where make+model+[serial number] was one field name

WCF on IIS8; *.svc handler mapping doesn't work

Windows 8 with IIS8

  • Hit Windows+X
  • Select Programs and Features (first item on list)
  • Select Turn Windows Features on or off on the left
  • Expand .NET Framework 4.5 Advanced Services
  • Expand WCF Services
  • Enable HTTP Activation

How do I write good/correct package __init__.py files

Your __init__.py should have a docstring.

Although all the functionality is implemented in modules and subpackages, your package docstring is the place to document where to start. For example, consider the python email package. The package documentation is an introduction describing the purpose, background, and how the various components within the package work together. If you automatically generate documentation from docstrings using sphinx or another package, the package docstring is exactly the right place to describe such an introduction.

For any other content, see the excellent answers by firecrow and Alex Martelli.

SQL distinct for 2 fields in a database

How about simply:

select distinct c1, c2 from t

or

select c1, c2, count(*)
from t
group by c1, c2

Find a file by name in Visual Studio Code

Press Ctl+T will open a search box. Delete # symbol and enter your file name.

Building a complete online payment gateway like Paypal

Big task, chances are you shouldn't reinvent the wheel rather using an existing wheel (such as paypal).

However, if you insist on continuing. Start small, you can use a credit card processing facility (Moneris, Authorize.NET) to process credit cards. Most providers have an API you can use. Be wary that you may need to use different providers depending on the card type (Discover, Visa, Amex, Mastercard) and Country (USA, Canada, UK). So build it so that you can communicate with multiple credit card processing APIs.

Security is essential if you are storing credit cards and payment details. Ensure that you are encrypting things properly.

Again, don't reinvent the wheel. You are better off using an existing provider and focussing your development attention on solving an problem that can't easily be purchase.

How to convert a Binary String to a base 10 integer in Java

Fixed version of java's Integer.parseInt(text) to work with negative numbers:

public static int parseInt(String binary) {
    if (binary.length() < Integer.SIZE) return Integer.parseInt(binary, 2);

    int result = 0;
    byte[] bytes = binary.getBytes();

    for (int i = 0; i < bytes.length; i++) {
        if (bytes[i] == 49) {
            result = result | (1 << (bytes.length - 1 - i));
        }
    }

    return result;
}

Sorting arraylist in alphabetical order (case insensitive)

try this code

Collections.sort(yourarraylist, new SortBasedOnName());



import java.util.Comparator;
import com.RealHelp.objects.FBFriends_Obj;
import com.RealHelp.ui.importFBContacts;

public class SortBasedOnName implements Comparator
{
public int compare(Object o1, Object o2) 
{

    FBFriends_Obj dd1 = (FBFriends_Obj)o1;// where FBFriends_Obj is your object class
    FBFriends_Obj dd2 = (FBFriends_Obj)o2;
    return dd1.uname.compareToIgnoreCase(dd2.uname);//where uname is field name
}

}

How to calculate combination and permutation in R?

It might be that the package "Combinations" is not updated anymore and does not work with a recent version of R (I was also unable to install it on R 2.13.1 on windows). The package "combinat" installs without problem for me and might be a solution for you depending on what exactly you're trying to do.

Update all objects in a collection using LINQ

No, LINQ doesn't support a manner of mass updating. The only shorter way would be to use a ForEach extension method - Why there is no ForEach extension method on IEnumerable?

Bootstrap modal appearing under background

Check your css to see if you have any blurs and filters. I removed this code from my css and the modal worked normally again

.modal-open .main-wrapper {
    -webkit-filter: blur(1px);
    -moz-filter: blur(1px);
    -o-filter: blur(1px);
    -ms-filter: blur(1px);
    filter: blur(1px);
}

Python Socket Multiple Clients

def get_clients():
    first_run = True
    startMainMenu = False

    while True:
        if first_run:
            global done
            done = False
            Thread(target=animate, args=("Waiting For Connection",)).start()

        Client, address = objSocket.accept()
        global menuIsOn
        if menuIsOn:
            menuIsOn = False  # will stop main menu
            startMainMenu = True

        done = True

        # Get Current Directory in Client Machine
        current_client_directory = Client.recv(1024).decode("utf-8", errors="ignore")

        # beep on connection
        beep()
        print(f"{bcolors.OKBLUE}\n***** Incoming Connection *****{bcolors.OKGREEN}")
        print('* Connected to: ' + address[0] + ':' + str(address[1]))
        try:
            get_client_info(Client, first_run)
        except Exception as e:
            print("Error data received is not a json!")
            print(e)
        now = datetime.now()
        current_time = now.strftime("%D %H:%M:%S")
        print("* Current Time =", current_time)

        print("* Current Folder in Client: " + current_client_directory + bcolors.WARNING)

        connections.append(Client)

        addresses.append(address)

        if first_run:
            Thread(target=threaded_main_menu, daemon=True).start()

            first_run = False
        else:
            print(f"{bcolors.OKBLUE}* Hit Enter To Continue.{bcolors.WARNING}\n#>", end="")
        if startMainMenu == True:
            Thread(target=threaded_main_menu, daemon=True).start()
            startMainMenu = False

Reshape an array in NumPy

a = np.arange(18).reshape(9,2)
b = a.reshape(3,3,2).swapaxes(0,2)

# a: 
array([[ 0,  1],
       [ 2,  3],
       [ 4,  5],
       [ 6,  7],
       [ 8,  9],
       [10, 11],
       [12, 13],
       [14, 15],
       [16, 17]])


# b:
array([[[ 0,  6, 12],
        [ 2,  8, 14],
        [ 4, 10, 16]],

       [[ 1,  7, 13],
        [ 3,  9, 15],
        [ 5, 11, 17]]])

How to find Max Date in List<Object>?

LocalDate maxDate = dates.stream()
                            .max( Comparator.comparing( LocalDate::toEpochDay ) )
                            .get();

LocalDate minDate = dates.stream()
                            .min( Comparator.comparing( LocalDate::toEpochDay ) )
                            .get();

jQuery vs document.querySelectorAll

Just a comment on this, when using material design lite, jquery selector does not return the property for material design for some reason.

For:

<div class="logonfield mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
        <input class="mdl-textfield__input" type="text" id="myinputfield" required>
        <label class="mdl-textfield__label" for="myinputfield">Enter something..</label>
      </div>

This works:

document.querySelector('#myinputfield').parentNode.MaterialTextfield.change();

This does not:

$('#myinputfield').parentNode.MaterialTextfield.change();

How to abort an interactive rebase if --abort doesn't work?

Try to follow the advice you see on the screen, and first reset your master's HEAD to the commit it expects.

git update-ref refs/heads/master b918ac16a33881ce00799bea63d9c23bf7022d67

Then, abort the rebase again.

Angular2 RC6: '<component> is not a known element'

For me path for templateUrl was not correct

I was using

shopping-list-edit.component.html

Whereas it should have been

./shopping-list-edit.component.html

Silly mistake but happens when starting out. Hope that helps somebody in distress.

Why do I always get the same sequence of random numbers with rand()?

rand() returns pseudo-random numbers. It generates numbers based on a given algorithm. The starting point of that algorithm is always the same, so you'll see the same sequence generated for each invocation. This is handy when you need to verify the behavior and consistency of your program.

You can set the "seed" of the random generator with the srand function(only call srand once in a program) One common way to get different sequences from the rand() generator is to set the seed to the current time or the id of the process:

srand(time(NULL)); or srand(getpid()); at the start of the program.

Generating real randomness is very very hard for a computer, but for practical non-crypto related work, an algorithm that tries to evenly distribute the generated sequences works fine.

Convert JSON string to dict using Python

When I started using json, I was confused and unable to figure it out for some time, but finally I got what I wanted
Here is the simple solution

import json
m = {'id': 2, 'name': 'hussain'}
n = json.dumps(m)
o = json.loads(n)
print(o['id'], o['name'])

How to get data out of a Node.js http get request

Shorter example using http.get:

require('http').get('http://httpbin.org/ip', (res) => {
    res.setEncoding('utf8');
    res.on('data', function (body) {
        console.log(body);
    });
});

How to download file in swift?

Yes you can very easily downloads Files from the remote Url Using this code. This Code is working Fine for Me.

func DownlondFromUrl(){
   // Create destination URL 
let documentsUrl:URL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
let destinationFileUrl = documentsUrl.appendingPathComponent("downloadedFile.jpg")

//Create URL to the source file you want to download
let fileURL = URL(string: "https://s3.amazonaws.com/learn-swift/IMG_0001.JPG")

let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)

let request = URLRequest(url:fileURL!)

let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
    if let tempLocalUrl = tempLocalUrl, error == nil {
        // Success
        if let statusCode = (response as? HTTPURLResponse)?.statusCode {
            print("Successfully downloaded. Status code: \(statusCode)")
        }

        do {
            try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
        } catch (let writeError) {
            print("Error creating a file \(destinationFileUrl) : \(writeError)")
        }

    } else {
        print("Error took place while downloading a file. Error description: %@", error?.localizedDescription);
    }
}
task.resume()
}

How to Set/Update State of StatefulWidget from other StatefulWidget in Flutter?

1.On Child Widget : add parameter Function paramter

class ChildWidget extends StatefulWidget {
  final Function() notifyParent;
  ChildWidget({Key key, @required this.notifyParent}) : super(key: key);
}

2.On Parent Widget : create a Function for the child to callback

refresh() {
  setState(() {});
}

3.On Parent Widget : pass parentFunction to Child Widget

new ChildWidget( notifyParent: refresh );  

4.On Child Widget : call the Parent Function

  widget.notifyParent();

how to insert value into DataGridView Cell?

int index= datagridview.rows.add();
datagridview.rows[index].cells[1].value=1;
datagridview.rows[index].cells[2].value="a";
datagridview.rows[index].cells[3].value="b";

hope this help! :)

How do I move a table into a schema in T-SQL

Short answer:

ALTER SCHEMA new_schema TRANSFER old_schema.table_name

I can confirm that the data in the table remains intact, which is probably quite important :)

Long answer as per MSDN docs,

ALTER SCHEMA schema_name 
   TRANSFER [ Object | Type | XML Schema Collection ] securable_name [;]

If it's a table (or anything besides a Type or XML Schema collection), you can leave out the word Object since that's the default.

Waiting for Target Device to Come Online

For Linux users using KVM and facing this problem try setting the Graphics option on the Android Virtual Device to Software instead of Automatic or Hardware . As previously mentioned in this answer.

I can confirm that the method works for Arch Linux, Ubuntu 16.04, as well as windows with or without a proprietary graphics card using Android Studio version 2.3.1+

concatenate two strings

You can use concatenation operator and instead of declaring two variables only use one variable

String finalString =  cursor.getString(numcol) + cursor.getString(cursor.getColumnIndexOrThrow(db.KEY_DESTINATIE));

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

Sorry, misunderstood your question.

According to Javascript - capturing onsubmit when calling form.submit():

I was recently asked: "Why doesn't the form.onsubmit event get fired when I submit my form using javascript?"

The answer: Current browsers do not adhere to this part of the html specification. The event only fires when it is activated by a user - and does not fire when activated by code.

(emphasis added).

Note: "activated by a user" also includes hitting submit buttons (probably including default submit behaviour from the enter key but I haven't tried this). Nor, I believe, does it get triggered if you (with code) click a submit button.

What difference between the DATE, TIME, DATETIME, and TIMESTAMP Types

Saty described the differences between them. For your practice, you can use datetime in order to keep the output of NOW().

For example:

CREATE TABLE Orders
(
  OrderId int NOT NULL,
  ProductName varchar(50) NOT NULL,
  OrderDate datetime NOT NULL DEFAULT NOW(),
  PRIMARY KEY (OrderId)
)

You can read more at w3schools.

Get the time difference between two datetimes

Typescript: following should work,

export const getTimeBetweenDates = ({
  until,
  format
}: {
  until: number;
  format: 'seconds' | 'minutes' | 'hours' | 'days';
}): number => {
  const date = new Date();
  const remainingTime = new Date(until * 1000);
  const getFrom = moment([date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()]);
  const getUntil = moment([remainingTime.getUTCFullYear(), remainingTime.getUTCMonth(), remainingTime.getUTCDate()]);
  const diff = getUntil.diff(getFrom, format);
  return !isNaN(diff) ? diff : null;
};

Passing struct to function

The line function implementation should be:

void addStudent(struct student person) {

}

person is not a type but a variable, you cannot use it as the type of a function parameter.

Also, make sure your struct is defined before the prototype of the function addStudent as the prototype uses it.

Auto select file in Solution Explorer from its open tab

It's in VS2012 - Specifically the 2-Arrow icon at the top of the solution explorer (Left/Right arrows, one above the other). This automatically jumps to the current file.

This icon is only visible if you've got Track Active Item in Solution Explorer disabled.

LEFT JOIN in LINQ to entities?

You can read an article i have written for joins in LINQ here

var query = 
from  u in Repo.T_Benutzer
join bg in Repo.T_Benutzer_Benutzergruppen
    on u.BE_ID equals bg.BEBG_BE
into temp
from j in temp.DefaultIfEmpty()
select new
{
    BE_User = u.BE_User,
    BEBG_BG = (int?)j.BEBG_BG// == null ? -1 : j.BEBG_BG
            //, bg.Name 
}

The following is the equivalent using extension methods:

var query = 
Repo.T_Benutzer
.GroupJoin
(
    Repo.T_Benutzer_Benutzergruppen,
    x=>x.BE_ID,
    x=>x.BEBG_BE,
    (o,i)=>new {o,i}
)
.SelectMany
(
    x => x.i.DefaultIfEmpty(),
    (o,i) => new
    {
        BE_User = o.o.BE_User,
        BEBG_BG = (int?)i.BEBG_BG
    }
);

How to define a Sql Server connection string to use in VB.NET?

Standard Security:

Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;

Trusted Connection:

Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;

will be glad if it helps.

Regards.

jQuery: How to get to a particular child of a parent?

This will find the first parent with class box then find the first child class with regex matching something and get the id.

$(".mylink").closest(".box").find('[class*="something"]').first().attr("id")

android.content.res.Resources$NotFoundException: String resource ID #0x0

if you get the values in int you have to use string for that it is throwing the error

before

  holder.villageName.setText(villageModelList.get(position).getVillageName());
    holder.villageCount.setText(villageModelList.get(position).getPeopleCount());
    holder.peopleCount.setText(villageModelList.get(position).getPeopleCount());

after

  holder.villageName.setText(villageModelList.get(position).getVillageName());
    holder.villageCount.setText(String.valueOf(villageModelList.get(position).getPeopleCount()));
    holder.peopleCount.setText(String.valueOf(villageModelList.get(position).getPeopleCount()));

you can solve the error by adding the String.valueOf

How to add local .jar file dependency to build.gradle file?

The Question already has been answered in detail. I still want to add something that seems very surprising to me:

The "gradle dependencies" task does not list any file dependencies. Even though you might think so, as they have been specified in the "dependencies" block after all..

So don't rely on the output of this to check whether your referenced local lib files are working correctly.

MVC 3: How to render a view without its layout page when loaded via ajax?

With ASP.NET 5 there is no Request variable available anymore. You can access it now with Context.Request

Also there is no IsAjaxRequest() Method anymore, you have to write it by yourself, for example in Extensions\HttpRequestExtensions.cs

using System;
using Microsoft.AspNetCore.Http;

namespace Microsoft.AspNetCore.Mvc
{
    public static class HttpRequestExtensions
    {
        public static bool IsAjaxRequest(this HttpRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            return (request.Headers != null) && (request.Headers["X-Requested-With"] == "XMLHttpRequest");
        }
    }
}

I searched for a while now on this and hope that will help some others too ;)

Resource: https://github.com/aspnet/AspNetCore/issues/2729

How to enable TLS 1.2 in Java 7

Add following option for java application:

-Dhttps.protocols=TLSv1,TLSv1.1,TLSv1.2  

How return error message in spring mvc @Controller

Here is an alternative. Create a generic exception that takes a status code and a message. Then create an exception handler. Use the exception handler to retrieve the information out of the exception and return to the caller of the service.

http://javaninja.net/2016/06/throwing-exceptions-messages-spring-mvc-controller/

public class ResourceException extends RuntimeException {

    private HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;

    public HttpStatus getHttpStatus() {
        return httpStatus;
    }

    /**
     * Constructs a new runtime exception with the specified detail message.
     * The cause is not initialized, and may subsequently be initialized by a
     * call to {@link #initCause}.
     * @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()}
     *                method.
     */
    public ResourceException(HttpStatus httpStatus, String message) {
        super(message);
        this.httpStatus = httpStatus;
    }
}

Then use an exception handler to retrieve the information and return it to the service caller.

@ControllerAdvice
public class ExceptionHandlerAdvice { 

    @ExceptionHandler(ResourceException.class)
    public ResponseEntity handleException(ResourceException e) {
        // log exception 
        return ResponseEntity.status(e.getHttpStatus()).body(e.getMessage());
    }         
} 

Then create an exception when you need to.

throw new ResourceException(HttpStatus.NOT_FOUND, "We were unable to find the specified resource.");

removeEventListener on anonymous functions in JavaScript

Possibly not the best solution in terms of what you are asking. I have still not determined an efficient method for removing anonymous function declared inline with the event listener invocation.

I personally use a variable to store the <target> and declare the function outside of the event listener invocation eg:

const target = document.querySelector('<identifier>');

function myFunc(event) { function code; }

target.addEventListener('click', myFunc);

Then to remove the listener:

target.removeEventListener('click', myFunc);

Not the top recommendation you will receive but to remove anonymous functions the only solution I have found useful is to remove then replace the HTML element. I am sure there must be a better vanilla JS method but I haven't seen it yet.

How to clean old dependencies from maven repositories?

Given a POM file for a maven project you can remove all its dependencies in the local repository (by default ~/.m2/respository) using the Apache Maven Dependency Plugin.

It includes the dependency:purge-local-repository functionality that removes the project dependencies from the local repository, and optionally re-resolve them.

To clean the local dependencies you just have to used the optional parameter reResolve and set it to false since it is set to true by default.

This command line call should work:

mvn dependency:purge-local-repository -DreResolve=false

Using partial views in ASP.net MVC 4

Change the code where you load the partial view to:

@Html.Partial("_CreateNote", new QuickNotes.Models.Note())

This is because the partial view is expecting a Note but is getting passed the model of the parent view which is the IEnumerable

how to find 2d array size in c++

Along with the _countof() macro you can refer to the array size using pointer notation, where the array name by itself refers to the row, the indirection operator appended by the array name refers to the column.

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    int beans[3][4]{
        { 1, 2, 3, 4 }, 
        { 5, 6, 7, 8 }, 
        { 9, 10, 11, 12 }
    };

    cout << "Row size = " << _countof(beans)  // Output row size
        << "\nColumn size = " << _countof(*beans);  // Output column size
    cout << endl;

    // Used in a for loop with a pointer.

    int(*pbeans)[4]{ beans };

    for (int i{}; i < _countof(beans); ++i) {

        cout << endl;

        for (int j{}; j < _countof(*beans); ++j) {

            cout << setw(4) << pbeans[i][j];
        }
    };

    cout << endl;
}

Get text of the selected option with jQuery

Close, you can use

$('#select_2 option:selected').html()

Linking a qtDesigner .ui file to python/pyqt?

Using Anaconda3 (September 2018) and QT designer 5.9.5. In QT designer, save your file as ui. Open Anaconda prompt. Search for your file: cd C:.... (copy/paste the access path of your file). Then write: pyuic5 -x helloworld.ui -o helloworld.py (helloworld = name of your file). Enter. Launch Spyder. Open your file .py.

ORA-01652 Unable to extend temp segment by in tablespace

Create a new datafile by running the following command:

alter tablespace TABLE_SPACE_NAME add datafile 'D:\oracle\Oradata\TEMP04.dbf'            
   size 2000M autoextend on;

Favicon dimensions?

The format of favicon must be square otherwise the browser will stretch it. Unfortunatelly, Internet Explorer < 11 do not support .gif, or .png filetypes, but only Microsoft's .ico format. You can use some "favicon generator" app like: http://favicon-generator.org/

Converting unix time into date-time via excel

in case the above does not work for you. for me this did not for some reasons;

the UNIX numbers i am working on are from the Mozilla place.sqlite dates.

to make it work : i splitted the UNIX cells into two cells : one of the first 10 numbers (the date) and the other 4 numbers left (the seconds i believe)

Then i used this formula, =(A1/86400)+25569 where A1 contains the cell with the first 10 number; and it worked

JavaScript inside an <img title="<a href='#' onClick='alert('Hello World!')>The Link</a>" /> possible?

When you click on the image you'll get the alert:

<img src="logo1.jpg" onClick='alert("Hello World!")'/>

if this is what you want.

Best way to check if MySQL results returned in PHP?

What is more logical then testing the TYPE of the result variable before processing? It is either of type 'boolean' or 'resource'. When you use a boolean for parameter with mysqli_num_rows, a warning will be generated because the function expects a resource.

$result = mysqli_query($dbs, $sql);

if(gettype($result)=='boolean'){ // test for boolean
    if($result){  // returned TRUE, e.g. in case of a DELETE sql  
        echo "SQL succeeded"; 
    } else { // returned FALSE
        echo "Error: " . mysqli_error($dbs);
    } 
} else { // must be a resource
    if(mysqli_num_rows($result)){

       // process the data    

    }
    mysqli_free_result($result);  
 }

How to use XPath preceding-sibling correctly

You don't need to go level up and use .. since all buttons are on the same level:

//button[contains(.,'Arcade Reader')]/preceding-sibling::button[@name='settings']

How are POST and GET variables handled in Python?

Python is only a language, to get GET and POST data, you need a web framework or toolkit written in Python. Django is one, as Charlie points out, the cgi and urllib standard modules are others. Also available are Turbogears, Pylons, CherryPy, web.py, mod_python, fastcgi, etc, etc.

In Django, your view functions receive a request argument which has request.GET and request.POST. Other frameworks will do it differently.

Set width of a "Position: fixed" div relative to parent div

Use this CSS:

#container {
    width: 400px;
    border: 1px solid red;
}

#fixed {
    position: fixed;
    width: inherit;
    border: 1px solid green;
}

The #fixed element will inherit it's parent width, so it will be 100% of that.

How to change credentials for SVN repository in Eclipse?

For Mac ,

  1. Close the Eclipse Workspace
  2. Go to /Users/username/.subversion/auth/svn.simple
  3. Delete. The file inside it with encrypted(Big Alpha Numeric) file name.
  4. Open key chain(/Applications/Utilities/) and delete the key saved for SVN.
  5. Now open Eclipse workspace try to update your project , prompt will show up asking you the SVN credentials
  6. Give you updated SVN credentials and update it In keychain .

How do I list all the columns in a table?

Microsoft SQL Server Management Studio 2008 R2:

In a query editor, if you highlight the text of table name (ex dbo.MyTable) and hit ALT+F1, you'll get a list of column names, type, length, etc.

ALT+F1 while you've highlighted dbo.MyTable is the equivalent of running EXEC sp_help 'dbo.MyTable' according to this site

I can't get the variations on querying INFORMATION_SCHEMA.COLUMNS to work, so I use this instead.

How do you add UI inside cells in a google spreadsheet using app script?

Status 2018:

There seems to be no way to place buttons (drawings, images) within cells in a way that would allow them to be linked to Apps Script functions.


This being said, there are some things that you can indeed do:

You can...

You can place images within cells using IMAGE(URL), but they cannot be linked to Apps Script functions.

You can place images within cells and link them to URLs using:
=HYPERLINK("http://example.com"; IMAGE("http://example.com/myimage.png"; 1))

You can create drawings as described in the answer of @Eduardo and they can be linked to Apps Script functions, but they will be stand-alone items that float freely "above" the spreadsheet and cannot be positioned in cells. They cannot be copied from cell to cell and they do not have a row or col position that the script function could read.

getting exception "IllegalStateException: Can not perform this action after onSaveInstanceState"

onSaveInstance will be called if a user rotates the screen so that it can load resources associated with the new orientation.

It's possible that this user rotated the screen followed by pressing the back button (because it's also possible that this user fumbled their phone while using your app)

How do I tell Gradle to use specific JDK version?

If you add JDK_PATH in gradle.properties your build become dependent on on that particular path. Instead Run gradle task with following command line parametemer

gradle build -Dorg.gradle.java.home=/JDK_PATH

This way your build is not dependent on some concrete path.

Reactjs: Unexpected token '<' Error

The issue Unexpected token '<' is because of missing the babel preset.

Solution : You have to configure your webpack configuration as follows

{
  test   : /\.jsx?$/,
  exclude: /(node_modules|bower_components)/,
  loader : 'babel',
  query  : {
    presets:[ 'react', 'es2015' ]
  }
}

here .jsx checks both .js and .jsx formats.

you can simply install the babel dependency using node as follows

npm install babel-preset-react

Thank you

Should I use 'border: none' or 'border: 0'?

Easiest Way to remove border with css

border: 0;

Log to the base 2 in python

It's good to know that

alt text

but also know that math.log takes an optional second argument which allows you to specify the base:

In [22]: import math

In [23]: math.log?
Type:       builtin_function_or_method
Base Class: <type 'builtin_function_or_method'>
String Form:    <built-in function log>
Namespace:  Interactive
Docstring:
    log(x[, base]) -> the logarithm of x to the given base.
    If the base not specified, returns the natural logarithm (base e) of x.


In [25]: math.log(8,2)
Out[25]: 3.0

How do I split a string so I can access item x?

This question is not about a string split approach, but about how to get the nth element.

All answers here are doing some kind of string splitting using recursion, CTEs, multiple CHARINDEX, REVERSE and PATINDEX, inventing functions, call for CLR methods, number tables, CROSS APPLYs ... Most answers cover many lines of code.

But - if you really want nothing more than an approach to get the nth element - this can be done as real one-liner, no UDF, not even a sub-select... And as an extra benefit: type safe

Get part 2 delimited by a space:

DECLARE @input NVARCHAR(100)=N'part1 part2 part3';
SELECT CAST(N'<x>' + REPLACE(@input,N' ',N'</x><x>') + N'</x>' AS XML).value('/x[2]','nvarchar(max)')

Of course you can use variables for delimiter and position (use sql:column to retrieve the position directly from a query's value):

DECLARE @dlmt NVARCHAR(10)=N' ';
DECLARE @pos INT = 2;
SELECT CAST(N'<x>' + REPLACE(@input,@dlmt,N'</x><x>') + N'</x>' AS XML).value('/x[sql:variable("@pos")][1]','nvarchar(max)')

If your string might include forbidden characters (especially one among &><), you still can do it this way. Just use FOR XML PATH on your string first to replace all forbidden characters with the fitting escape sequence implicitly.

It's a very special case if - additionally - your delimiter is the semicolon. In this case I replace the delimiter first to '#DLMT#', and replace this to the XML tags finally:

SET @input=N'Some <, > and &;Other äöü@€;One more';
SET @dlmt=N';';
SELECT CAST(N'<x>' + REPLACE((SELECT REPLACE(@input,@dlmt,'#DLMT#') AS [*] FOR XML PATH('')),N'#DLMT#',N'</x><x>') + N'</x>' AS XML).value('/x[sql:variable("@pos")][1]','nvarchar(max)');

UPDATE for SQL-Server 2016+

Regretfully the developers forgot to return the part's index with STRING_SPLIT. But, using SQL-Server 2016+, there is JSON_VALUE and OPENJSON.

With JSON_VALUE we can pass in the position as the index' array.

For OPENJSON the documentation states clearly:

When OPENJSON parses a JSON array, the function returns the indexes of the elements in the JSON text as keys.

A string like 1,2,3 needs nothing more than brackets: [1,2,3].
A string of words like this is an example needs to be ["this","is","an","example"].
These are very easy string operations. Just try it out:

DECLARE @str VARCHAR(100)='Hello John Smith';
DECLARE @position INT = 2;

--We can build the json-path '$[1]' using CONCAT
SELECT JSON_VALUE('["' + REPLACE(@str,' ','","') + '"]',CONCAT('$[',@position-1,']'));

--See this for a position safe string-splitter (zero-based):

SELECT  JsonArray.[key] AS [Position]
       ,JsonArray.[value] AS [Part]
FROM OPENJSON('["' + REPLACE(@str,' ','","') + '"]') JsonArray

In this post I tested various approaches and found, that OPENJSON is really fast. Even much faster than the famous "delimitedSplit8k()" method...

UPDATE 2 - Get the values type-safe

We can use an array within an array simply by using doubled [[]]. This allows for a typed WITH-clause:

DECLARE  @SomeDelimitedString VARCHAR(100)='part1|1|20190920';

DECLARE @JsonArray NVARCHAR(MAX)=CONCAT('[["',REPLACE(@SomeDelimitedString,'|','","'),'"]]');

SELECT @SomeDelimitedString          AS TheOriginal
      ,@JsonArray                    AS TransformedToJSON
      ,ValuesFromTheArray.*
FROM OPENJSON(@JsonArray)
WITH(TheFirstFragment  VARCHAR(100) '$[0]'
    ,TheSecondFragment INT          '$[1]'
    ,TheThirdFragment  DATE         '$[2]') ValuesFromTheArray

How do I adb pull ALL files of a folder present in SD Card

if your using jellybean just start cmd, type adb devices to make sure your readable, type adb pull sdcard/ sdcard_(the date or extra) <---this file needs to be made in adb directory beforehand. PROFIT!

In other versions type adb pull mnt/sdcard/ sdcard_(the date or extra)

Remember to make file or your either gonna have a mess or it wont work.

jQuery .ajax() POST Request throws 405 (Method Not Allowed) on RESTful WCF

You can create the required headers in a filter too.

@WebFilter(urlPatterns="/rest/*")
public class AllowAccessFilter implements Filter {
    @Override
    public void doFilter(ServletRequest sRequest, ServletResponse sResponse, FilterChain chain) throws IOException, ServletException {
        System.out.println("in AllowAccessFilter.doFilter");
        HttpServletRequest request = (HttpServletRequest)sRequest;
        HttpServletResponse response = (HttpServletResponse)sResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type"); 
        chain.doFilter(request, response);
    }
    ...
}

Prevent a webpage from navigating away using JavaScript

That suggested error message may duplicate the error message the browser already displays. In chrome, the 2 similar error messages are displayed one after another in the same window.

In chrome, the text displayed after the custom message is: "Are you sure you want to leave this page?". In firefox, it does not display our custom error message at all (but still displays the dialog).

A more appropriate error message might be:

window.onbeforeunload = function() {
    return "If you leave this page, you will lose any unsaved changes.";
}

Or stackoverflow style: "You have started writing or editing a post."

How can I call a function using a function pointer?

bool (*FuncPtr)()

FuncPtr = A;
FuncPtr();

If you want to call one of those functions conditionally, you should consider using an array of function pointers. In this case you'd have 3 elements pointing to A, B, and C and you call one depending on the index to the array, such as funcArray0 for A.

MySQL Query to select data from last week?

If you're looking to retrieve records within the last 7 days, you can use the snippet below:

SELECT date FROM table_name WHERE DATE(date) >= CURDATE() - INTERVAL 7 DAY;

How to get distinct values for non-key column fields in Laravel?

For those who like me doing same mistake. Here is the elaborated answer Tested in Laravel 5.7

A. Records in DB

UserFile::orderBy('created_at','desc')->get()->toArray();

Array
(
    [0] => Array
        (
            [id] => 2073
            [type] => 'DL'
            [url] => 'https://i.picsum.photos/12/884/200/300.jpg'
            [created_at] => 2020-08-05 17:16:48
            [updated_at] => 2020-08-06 18:08:38
        )

    [1] => Array
        (
            [id] => 2074
            [type] => 'PROFILE'
            [url] => 'https://i.picsum.photos/13/884/200/300.jpg'
            [created_at] => 2020-08-05 17:20:06
            [updated_at] => 2020-08-06 18:08:38
        )

    [2] => Array
        (
            [id] => 2076
            [type] => 'PROFILE'
            [url] => 'https://i.picsum.photos/13/884/200/300.jpg'
            [created_at] => 2020-08-05 17:22:01
            [updated_at] => 2020-08-06 18:08:38
        )

    [3] => Array
        (
            [id] => 2086
            [type] => 'PROFILE'
            [url] => 'https://i.picsum.photos/13/884/200/300.jpg'
            [created_at] => 2020-08-05 19:22:41
            [updated_at] => 2020-08-06 18:08:38
        )
)

B. Desired Grouped result

UserFile::select('type','url','updated_at)->distinct('type')->get()->toArray();

Array
(
    [0] => Array
        (
            [type] => 'DL'
            [url] => 'https://i.picsum.photos/12/884/200/300.jpg'
            [updated_at] => 2020-08-06 18:08:38 
        )

    [1] => Array
        (
            [type] => 'PROFILE'
            [url] => 'https://i.picsum.photos/13/884/200/300.jpg'
            [updated_at] => 2020-08-06 18:08:38
        )
)

So Pass only those columns in "select()", values of which are same. For example: 'type','url'. You can add more columns provided they have same value like 'updated_at'.

If you try to pass "created_at" or "id" in "select()", then you will get the records same as A. Because they are different for each row in DB.

Can enums be subclassed to add new elements?

I suggest you take the other way around approach.

Instead of extending the existing enumeration, create a larger one and create a subset of it. For exemple if you had an enumeration called PET and you wanted to extend it to ANIMAL you should do this instead:

public enum ANIMAL {
    WOLF,CAT, DOG
} 
EnumSet<ANIMAL> pets = EnumSet.of(ANIMAL.CAT, ANIMAL.DOG);

Be careful, pets is not an immutable collections, you might want to use Guava or Java9 for more safety.

angular js unknown provider

pkozlowski's answer is correct, but just in case this happens to someone else, I had the same error after creating the same module twice by mistake; the second definition was overriding the provider of the first:

I created the module by doing

angular.module('MyService'...
).factory(...);

then a bit further down in the same file:

angular.module('MyService'...
).value('version','0.1');

The correct way of doing this is:

angular.module('MyService'...
).factory(...).value('version','0.1');

MySQL remove all whitespaces from the entire column

Since the question is how to replace ALL whitespaces

UPDATE `table` 
SET `col_name` = REPLACE
(REPLACE(REPLACE(`col_name`, ' ', ''), '\t', ''), '\n', '');

isolating a sub-string in a string before a symbol in SQL Server 2008

This can achieve using two SQL functions- SUBSTRING and CHARINDEX

You can read strings to a variable as shown in the above answers, or can add it to a SELECT statement as below:

SELECT SUBSTRING('Net Operating Loss - 2007' ,0, CHARINDEX('-','Net Operating Loss - 2007'))

C++ compile error: has initializer but incomplete type

` Please include either of these:

`#include<sstream>`

using std::istringstream; 

Code coverage for Jest built on top of Jasmine

Try Chutzpah. I have just used it. And I blogged about it on how to integrate in Visual Studio.

This is how I did code coverage with Chutzpah: Code Coverage with Chutzpah

How do I use cascade delete with SQL Server?

Use something like

ALTER TABLE T2
ADD CONSTRAINT fk_employee
FOREIGN KEY (employeeID)
REFERENCES T1 (employeeID)
ON DELETE CASCADE;

Fill in the correct column names and you should be set. As mark_s correctly stated, if you have already a foreign key constraint in place, you maybe need to delete the old one first and then create the new one.

How can I get the timezone name in JavaScript?

In javascript , the Date.getTimezoneOffset() method returns the time-zone offset from UTC, in minutes, for the current locale.

var x = new Date();
var currentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;

Moment'timezone will be a useful tool. http://momentjs.com/timezone/

Convert Dates Between Timezones

var newYork    = moment.tz("2014-06-01 12:00", "America/New_York");
var losAngeles = newYork.clone().tz("America/Los_Angeles");
var london     = newYork.clone().tz("Europe/London");

newYork.format();    // 2014-06-01T12:00:00-04:00
losAngeles.format(); // 2014-06-01T09:00:00-07:00
london.format();     // 2014-06-01T17:00:00+01:00

Kotlin Error : Could not find org.jetbrains.kotlin:kotlin-stdlib-jre7:1.0.7

In Project level build.gradle use only this version

ext.kotlin_version = '1.3.31'

Remove other versions

This will only work with the latest version of android studio 3.4

UPDATE: Try to use the latest version of kotlin with latest Android studio to avoid an error.

Jackson enum Serializing and DeSerializer

Note that as of this commit in June 2015 (Jackson 2.6.2 and above) you can now simply write:

public enum Event {
    @JsonProperty("forgot password")
    FORGOT_PASSWORD;
}

The behavior is documented here: https://fasterxml.github.io/jackson-annotations/javadoc/2.11/com/fasterxml/jackson/annotation/JsonProperty.html

Starting with Jackson 2.6 this annotation may also be used to change serialization of Enum like so:

 public enum MyEnum {
      @JsonProperty("theFirstValue") THE_FIRST_VALUE,
      @JsonProperty("another_value") ANOTHER_VALUE;
 }

as an alternative to using JsonValue annotation.

Negative regex for Perl string pattern match

What's wrong with using two regexs (or three)? This makes your intentions more clear and may even improve your performance:

if ($string =~ /^(Clinton|Reagan)/i && $string !~ /Bush/i) { ... }

if (($string =~ /^Clinton/i || $string =~ /^Reagan/i)
        && $string !~ /Bush/i) {
    print "$string\n"
}

how to implement Interfaces in C++?

C++ has no built-in concepts of interfaces. You can implement it using abstract classes which contains only pure virtual functions. Since it allows multiple inheritance, you can inherit this class to create another class which will then contain this interface (I mean, object interface :) ) in it.

An example would be something like this -

class Interface
{
public:
    Interface(){}
    virtual ~Interface(){}
    virtual void method1() = 0;    // "= 0" part makes this method pure virtual, and
                                   // also makes this class abstract.
    virtual void method2() = 0;
};

class Concrete : public Interface
{
private:
    int myMember;

public:
    Concrete(){}
    ~Concrete(){}
    void method1();
    void method2();
};

// Provide implementation for the first method
void Concrete::method1()
{
    // Your implementation
}

// Provide implementation for the second method
void Concrete::method2()
{
    // Your implementation
}

int main(void)
{
    Interface *f = new Concrete();

    f->method1();
    f->method2();

    delete f;

    return 0;
}

what is the use of $this->uri->segment(3) in codeigniter pagination

In your code $this->uri->segment(3) refers to the pagination offset which you use in your query. According to your $config['base_url'] = base_url().'index.php/papplicant/viewdeletedrecords/' ;, $this->uri->segment(3) i.e segment 3 refers to the offset. The first segment is the controller, second is the method, there after comes the parameters sent to the controllers as segments.

Call a Vue.js component method from outside the component

Using Vue 3:

const app = createApp({})

// register an options object
app.component('my-component', {
  /* ... */
})

....

// retrieve a registered component
const MyComponent = app.component('my-component')

MyComponent.methods.greet();

https://v3.vuejs.org/api/application-api.html#component

Python error: AttributeError: 'module' object has no attribute

When you import lib, you're importing the package. The only file to get evaluated and run in this case is the 0 byte __init__.py in the lib directory.

If you want access to your function, you can do something like this from lib.mod1 import mod1 and then run the mod12 function like so mod1.mod12().

If you want to be able to access mod1 when you import lib, you need to put an import mod1 inside the __init__.py file inside the lib directory.

Using routes in Express-js

No one should ever have to keep writing app.use('/someRoute', require('someFile')) until it forms a heap of code.

It just doesn't make sense at all to be spending time invoking/defining routings. Even if you do need custom control, it's probably only for some of the time, and for the most bit you want to be able to just create a standard file structure of routings and have a module do it automatically.

Try Route Magic

As you scale your app, the routing invocations will start to form a giant heap of code that serves no purpose. You want to do just 2 lines of code to handle all the app.use routing invocations with Route Magic like this:

const magic = require('express-routemagic')
magic.use(app, __dirname, '[your route directory]')

For those you want to handle manually, just don't use pass the directory to Magic.

What is the difference between --save and --save-dev?

The difference between --save and --save-dev may not be immediately noticeable if you have tried them both on your own projects. So here are a few examples...

Lets say you were building an app that used the moment package to parse and display dates. Your app is a scheduler so it really needs this package to run, as in: cannot run without it. In this case you would use

npm install moment --save

This would create a new value in your package.json

"dependencies": {
   ...
   "moment": "^2.17.1"
}

When you are developing, it really helps to use tools such as test suites and may need jasmine-core and karma. In this case you would use

npm install jasmine-core --save-dev
npm install karma --save-dev

This would also create a new value in your package.json

"devDependencies": {
    ...
    "jasmine-core": "^2.5.2",
    "karma": "^1.4.1",
}

You do not need the test suite to run the app in its normal state, so it is a --save-dev type dependency, nothing more. You can see how if you do not understand what is really happening, it is a bit hard to imagine.

Taken directly from NPM docs docs#dependencies

Dependencies

Dependencies are specified in a simple object that maps a package name to a version range. The version range is a string which has one or more space-separated descriptors. Dependencies can also be identified with a tarball or git URL.

Please do not put test harnesses or transpilers in your dependencies object. See devDependencies, below.

Even in the docs, it asks you to use --save-dev for modules such as test harnesses.

I hope this helps and is clear.

Example of multipart/form-data

Many thanks to @Ciro Santilli answer! I found that his choice for boundary is quite "unhappy" because all of thoose hyphens: in fact, as @Fake Name commented, when you are using your boundary inside request it comes with two more hyphens on front:

Example:

POST / HTTP/1.1
HOST: host.example.com
Cookie: some_cookies...
Connection: Keep-Alive
Content-Type: multipart/form-data; boundary=12345

--12345
Content-Disposition: form-data; name="sometext"

some text that you wrote in your html form ...
--12345
Content-Disposition: form-data; name="name_of_post_request" filename="filename.xyz"

content of filename.xyz that you upload in your form with input[type=file]
--12345
Content-Disposition: form-data; name="image" filename="picture_of_sunset.jpg"

content of picture_of_sunset.jpg ...
--12345--

I found on this w3.org page that is possible to incapsulate multipart/mixed header in a multipart/form-data, simply choosing another boundary string inside multipart/mixed and using that one to incapsulate data. At the end, you must "close" all boundary used in FILO order to close the POST request (like:

POST / HTTP/1.1
...
Content-Type: multipart/form-data; boundary=12345

--12345
Content-Disposition: form-data; name="sometext"

some text sent via post...
--12345
Content-Disposition: form-data; name="files"
Content-Type: multipart/mixed; boundary=abcde

--abcde
Content-Disposition: file; file="picture.jpg"

content of jpg...
--abcde
Content-Disposition: file; file="test.py"

content of test.py file ....
--abcde--
--12345--

Take a look at the link above.

Why binary_crossentropy and categorical_crossentropy give different performances for the same problem?

when using the categorical_crossentropy loss, your targets should be in categorical format (e.g. if you have 10 classes, the target for each sample should be a 10-dimensional vector that is all-zeros except for a 1 at the index corresponding to the class of the sample).

'adb' is not recognized as an internal or external command, operable program or batch file

If you didn't set a path for ADB, you can run .\adb instead of adb at sdk/platformtools.

Heatmap in matplotlib with pcolor?

The python seaborn module is based on matplotlib, and produces a very nice heatmap.

Below is an implementation with seaborn, designed for the ipython/jupyter notebook.

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
# import the data directly into a pandas dataframe
nba = pd.read_csv("http://datasets.flowingdata.com/ppg2008.csv", index_col='Name  ')
# remove index title
nba.index.name = ""
# normalize data columns
nba_norm = (nba - nba.mean()) / (nba.max() - nba.min())
# relabel columns
labels = ['Games', 'Minutes', 'Points', 'Field goals made', 'Field goal attempts', 'Field goal percentage', 'Free throws made', 
          'Free throws attempts', 'Free throws percentage','Three-pointers made', 'Three-point attempt', 'Three-point percentage', 
          'Offensive rebounds', 'Defensive rebounds', 'Total rebounds', 'Assists', 'Steals', 'Blocks', 'Turnover', 'Personal foul']
nba_norm.columns = labels
# set appropriate font and dpi
sns.set(font_scale=1.2)
sns.set_style({"savefig.dpi": 100})
# plot it out
ax = sns.heatmap(nba_norm, cmap=plt.cm.Blues, linewidths=.1)
# set the x-axis labels on the top
ax.xaxis.tick_top()
# rotate the x-axis labels
plt.xticks(rotation=90)
# get figure (usually obtained via "fig,ax=plt.subplots()" with matplotlib)
fig = ax.get_figure()
# specify dimensions and save
fig.set_size_inches(15, 20)
fig.savefig("nba.png")

The output looks like this: seaborn nba heatmap I used the matplotlib Blues color map, but personally find the default colors quite beautiful. I used matplotlib to rotate the x-axis labels, as I couldn't find the seaborn syntax. As noted by grexor, it was necessary to specify the dimensions (fig.set_size_inches) by trial and error, which I found a bit frustrating.

As noted by Paul H, you can easily add the values to heat maps (annot=True), but in this case I didn't think it improved the figure. Several code snippets were taken from the excellent answer by joelotz.

Function that creates a timestamp in c#

You can also use

Stopwatch.GetTimestamp().ToString();

How to read line by line or a whole text file at once?

I know this is a really really old thread but I'd like to also point out another way which is actually really simple... This is some sample code:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {

    ifstream file("filename.txt");
    string content;

    while(file >> content) {
        cout << content << ' ';
    }
    return 0;
}

How to get MD5 sum of a string using python?

You can use b character in front of a string literal:

import hashlib
print(hashlib.md5(b"Hello MD5").hexdigest())
print(hashlib.md5("Hello MD5".encode('utf-8')).hexdigest())

Out:

e5dadf6524624f79c3127e247f04b548
e5dadf6524624f79c3127e247f04b548

Get Mouse Position

MouseInfo.getPointerInfo().getLocation() might be helpful. It returns a Point object corresponding to current mouse position.

Excel- compare two cell from different sheet, if true copy value from other cell

In your destination field you want to use VLOOKUP like so:

=VLOOKUP(Sheet1!A1:A100,Sheet2!A1:F100,6,FALSE)

VLOOKUP Arguments:

  1. The set fields you want to lookup.
  2. The table range you want to lookup up your value against. The first column of your defined table should be the column you want compared against your lookup field. The table range should also contain the value you want to display (Column F).
  3. This defines what field you want to display upon a match.
  4. FALSE tells VLOOKUP to do an exact match.

How to configure multi-module Maven + Sonar + JaCoCo to give merged coverage report?

This sample works very well for me :

<plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>0.8.2</version>
            <executions>
                <execution>
                    <id>pre-unit-test</id>
                    <goals>
                        <goal>prepare-agent</goal>
                    </goals>
                    <configuration>
                        <destFile>${project.build.directory}/coverage-reports/jacoco-ut.exec</destFile>
                        <propertyName>surefireArgLine</propertyName>
                    </configuration>
                </execution>
                <execution>
                    <id>pre-integration-test</id>
                    <goals>
                        <goal>prepare-agent-integration</goal>
                    </goals>
                    <configuration>
                        <destFile>${project.build.directory}/coverage-reports/jacoco-it.exec</destFile>
                        <!--<excludes>
                            <exclude>com.asimio.demo.rest</exclude>
                            <exclude>com.asimio.demo.service</exclude>
                        </excludes>-->
                        <propertyName>testArgLine</propertyName>
                    </configuration>
                </execution>
                <execution>
                    <id>post-integration-test</id>
                    <phase>post-integration-test</phase>
                    <goals>
                        <goal>report</goal>
                    </goals>
                    <configuration>
                        <dataFile>${project.build.directory}/coverage-reports/jacoco-it.exec</dataFile>
                        <outputDirectory>${project.reporting.outputDirectory}/jacoco-it</outputDirectory>
                    </configuration>
                </execution>
                <execution>
                    <id>post-unit-test</id>
                    <phase>prepare-package</phase>
                    <goals>
                        <goal>report</goal>
                    </goals>
                    <configuration>
                        <dataFile>${project.build.directory}/coverage-reports/jacoco-ut.exec</dataFile>
                        <outputDirectory>${project.reporting.outputDirectory}/jacoco-ut</outputDirectory>
                    </configuration>
                </execution>
                <execution>
                    <id>merge-results</id>
                    <phase>verify</phase>
                    <goals>
                        <goal>merge</goal>
                    </goals>
                    <configuration>
                        <fileSets>
                            <fileSet>
                                <directory>${project.build.directory}/coverage-reports</directory>
                                <includes>
                                    <include>*.exec</include>
                                </includes>
                            </fileSet>
                        </fileSets>
                        <destFile>${project.build.directory}/coverage-reports/aggregate.exec</destFile>
                    </configuration>
                </execution>
                <execution>
                    <id>post-merge-report</id>
                    <phase>verify</phase>
                    <goals>
                        <goal>report</goal>
                    </goals>
                    <configuration>
                        <dataFile>${project.build.directory}/coverage-reports/aggregate.exec</dataFile>
                        <outputDirectory>${project.reporting.outputDirectory}/jacoco-aggregate</outputDirectory>
                    </configuration>
                </execution>
            </executions>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.18.1</version>
            <configuration>
                <argLine>${surefireArgLine}</argLine>
                <!--<skipTests>${skip.unit.tests}</skipTests>-->
                <includes>
                    <include>**/*Test.java</include>
                    <!--<include>**/*MT.java</include>
                    <include>**/*Test.java</include>-->
                </includes>
            <!--    <skipTests>${skipUTMTs}</skipTests>-->
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-failsafe-plugin</artifactId>
            <version>2.12.4</version>
            <configuration>
                <!--<skipTests>${skipTests}</skipTests>
                <skipITs>${skipITs}</skipITs>-->
                <argLine>${testArgLine}</argLine>
                <includes>
                    <include>**/*IT.java</include>
                </includes>
                <!--<excludes>
                    <exclude>**/*UT*.java</exclude>
                </excludes>-->
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>integration-test</goal>
                        <goal>verify</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

Get current time in milliseconds in Python?

The simpliest way I've found to get the current UTC time in milliseconds is:

# timeutil.py
import datetime


def get_epochtime_ms():
    return round(datetime.datetime.utcnow().timestamp() * 1000)

# sample.py
import timeutil


timeutil.get_epochtime_ms()

Change Twitter Bootstrap Tooltip content on click

$(this).attr('data-original-title', 'click here to publish')
       .tooltip('fixTitle')
       .tooltip('show');

Useful if you need to change a tooltip's text after it has been initialized with attr 'data-original-title'.

deleted object would be re-saved by cascade (remove deleted object from associations)

The solution is to do exactly what the exception message tells you:

Caused by: org.hibernate.ObjectDeletedException: deleted object would be re-saved by cascade (remove deleted object from associations)

Remove the deleted object from an associations (sets, lists, or maps) that it is in. In particular, i suspect, from PlayList.PlaylistadMaps. It's not enough to just delete the object, you have to remove it from any cascading collections which refer to it.

In fact, since your collection has orphanRemoval = true, you don't need to delete it explicitly. You just need to remove it from the set.

What is a StackOverflowError?

The term "stack overrun (overflow)" is often used but a misnomer; attacks do not overflow the stack but buffers on the stack.

-- from lecture slides of Prof. Dr. Dieter Gollmann

Key Presses in Python

Install the pywin32 extensions. Then you can do the following:

import win32com.client as comclt
wsh= comclt.Dispatch("WScript.Shell")
wsh.AppActivate("Notepad") # select another application
wsh.SendKeys("a") # send the keys you want

Search for documentation of the WScript.Shell object (I believe installed by default in all Windows XP installations). You can start here, perhaps.

EDIT: Sending F11

import win32com.client as comctl
wsh = comctl.Dispatch("WScript.Shell")

# Google Chrome window title
wsh.AppActivate("icanhazip.com")
wsh.SendKeys("{F11}")

Redirect to specified URL on PHP script completion?

You could always just use the tag to refresh the page - or maybe just drop the necessary javascript into the page at the end that would cause the page to redirect. You could even throw that in an onload function, so once its finished, the page is redirected

<?php

  echo $htmlHeader;
  while($stuff){
    echo $stuff;
  }
  echo "<script>window.location = 'http://www.yourdomain.com'</script>";
?>

Get Wordpress Category from Single Post

For the lazy and the learning, to put it into your theme, Rfvgyhn's full code

<?php $category = get_the_category();
$firstCategory = $category[0]->cat_name; echo $firstCategory;?>

Check if XML Element exists

Not sure what you're wanting to do but using a DTD or schema might be all you need to validate the xml.

Otherwise, if you want to find an element you could use an xpath query to search for a particular element.

How can I clear the Scanner buffer in Java?

Try this:

in.nextLine();

This advances the Scanner to the next line.

Check if a String contains numbers Java

If you want to extract the first number out of the input string, you can do-

public static String extractNumber(final String str) {                
    
    if(str == null || str.isEmpty()) return "";
    
    StringBuilder sb = new StringBuilder();
    boolean found = false;
    for(char c : str.toCharArray()){
        if(Character.isDigit(c)){
            sb.append(c);
            found = true;
        } else if(found){
            // If we already found a digit before and this char is not a digit, stop looping
            break;                
        }
    }
    
    return sb.toString();
}

Examples:

For input "123abc", the method above will return 123.

For "abc1000def", 1000.

For "555abc45", 555.

For "abc", will return an empty string.

What is the facade design pattern?

A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design.

The Facade design pattern is a structural pattern as it defines a manner for creating relationships between classes or entities. The facade design pattern is used to define a simplified interface to a more complex subsystem.

The facade pattern is ideal when working with a large number of interdependent classes, or with classes that require the use of multiple methods, particularly when they are complicated to use or difficult to understand. The facade class is a "wrapper" that contains a set of members that are easily understood and simple to use. These members access the subsystem on behalf of the facade user, hiding the implementation details.

The facade design pattern is particularly useful when wrapping subsystems that are poorly designed but cannot be refactored because the source code is unavailable or the existing interface is widely used. Sometimes you may decide to implement more than one facade to provide subsets of functionality for different purposes.

One example use of the facade pattern is for integrating a web site with a business application. The existing software may include large amounts of business logic that must be accessed in a particular manner. The web site may require only limited access to this business logic. For example, the web site may need to show whether an item for sale has reached a limited level of stock. The IsLowStock method of the facade class could return a Boolean value to indicate this. Behind the scenes, this method could be hiding the complexities of processing the current physical stock, incoming stock, allocated items and the low stock level for each item.

difference between throw and throw new Exception()

Most important difference is that second expression erases type of exception. And exception type plays vital role in catching exceptions:

public void MyMethod ()
{
    // both can throw IOException
    try { foo(); } catch { throw; }
    try { bar(); } catch(E) {throw new Exception(E.message); }
}

(...)

try {
    MyMethod ();
} catch (IOException ex) {
    Console.WriteLine ("Error with I/O"); // [1]
} catch (Exception ex) {
    Console.WriteLine ("Other error");    // [2]
}

If foo() throws IOException, [1] catch block will catch exception. But when bar() throws IOException, it will be converted to plain Exception ant won't be caught by [1] catch block.

How to restrict UITextField to take only numbers in Swift?

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    // return true if the replacementString only contains numeric characters
    let digits = NSCharacterSet.decimalDigitCharacterSet()
    for c in string {
        if !digits.characterIsMember(c) {
            return false
        }
    }

    return true
}

This solution will work even if the user switches keyboards or tries to paste a non-numeric string into the text field.

Make sure to set the delegate property of the appropriate text field.

Python re.sub replace with matched content

For the replacement portion, Python uses \1 the way sed and vi do, not $1 the way Perl, Java, and Javascript (amongst others) do. Furthermore, because \1 interpolates in regular strings as the character U+0001, you need to use a raw string or \escape it.

Python 3.2 (r32:88445, Jul 27 2011, 13:41:33) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> method = 'images/:id/huge'
>>> import re
>>> re.sub(':([a-z]+)', r'<span>\1</span>', method)
'images/<span>id</span>/huge'
>>> 

Add column in dataframe from list

A solution improving on the great one from @sparrow.

Let df, be your dataset, and mylist the list with the values you want to add to the dataframe.

Let's suppose you want to call your new column simply, new_column

First make the list into a Series:

column_values = pd.Series(mylist)

Then use the insert function to add the column. This function has the advantage to let you choose in which position you want to place the column. In the following example we will position the new column in the first position from left (by setting loc=0)

df.insert(loc=0, column='new_column', value=column_values)

String to object in JS

Here is my approach to handle some edge cases like having whitespaces and other primitive types as values

const str = " c:234 , d:sdfg ,e: true, f:null, g: undefined, h:name "; 

const strToObj = str
  .trim()
  .split(",")
  .reduce((acc, item) => {
    const [key, val = ""] = item.trim().split(":");
    let newVal = val.trim();

    if (newVal == "null") {
      newVal = null;
    } else if (newVal == "undefined") {
      newVal = void 0;
    } else if (!Number.isNaN(Number(newVal))) {
      newVal = Number(newVal);
    }else if (newVal == "true" || newVal == "false") {
      newVal = Boolean(newVal);
    }
    return { ...acc, [key.trim()]: newVal };
  }, {});

Display UIViewController as Popup in iPhone

Swift 4:

To add an overlay, or the popup view You can also use the Container View with which you get a free View Controller ( you get the Container View from the usual object palette/library)

enter image description here

Steps:

  1. Have a View (ViewForContainer in the pic) that holds this Container View, to dim it when the contents of Container View are displayed. Connect the outlet inside the first View Controller

  2. Hide this View when 1st VC loads

  3. Unhide when Button is clicked enter image description here

  4. To dim this View when the Container View content is displayed, set the Views Background to Black and opacity to 30%

enter image description here

You will get this effect when you click on the Button enter image description here

jquery mobile background image

With JQM 1.4.2 this one works for me (Change theme to the used one):

.ui-page-theme-b, .ui-page-theme-b .ui-panel-wrapper {
    background: transparent url(../img/xxx) !important;
    background-repeat:repeat !important;
}

How to set cookie value with AJAX request?

Basically, ajax request as well as synchronous request sends your document cookies automatically. So, you need to set your cookie to document, not to request. However, your request is cross-domain, and things became more complicated. Basing on this answer, additionally to set document cookie, you should allow its sending to cross-domain environment:

type: "GET",    
url: "http://example.com",
cache: false,
// NO setCookies option available, set cookie to document
//setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
crossDomain: true,
dataType: 'json',
xhrFields: {
    withCredentials: true
},
success: function (data) {
    alert(data);
});

How can I remove Nan from list Python/NumPy

I like to remove missing values from a list like this:

list_no_nan = [x for x in list_with_nan if pd.notnull(x)]

SQL Query Where Date = Today Minus 7 Days

declare @lastweek datetime
declare @now datetime
set @now = getdate()
set @lastweek = dateadd(day,-7,@now)

SELECT URLX, COUNT(URLx) AS Count
FROM ExternalHits
WHERE datex BETWEEN @lastweek AND @now
GROUP BY URLx
ORDER BY Count DESC; 

Java - sending HTTP parameters via POST method easily

import java.net.*;

public class Demo{

  public static void main(){

       String data = "data=Hello+World!";
       URL url = new URL("http://localhost:8084/WebListenerServer/webListener");
       HttpURLConnection con = (HttpURLConnection) url.openConnection();
       con.setRequestMethod("POST");
       con.setDoOutput(true);
       con.getOutputStream().write(data.getBytes("UTF-8"));
       con.getInputStream();

    }

}

Get Value of Row in Datatable c#

for (Int32 i = 1; i < dt_pattern.Rows.Count - 1; i++){ double yATmax = ToDouble(dt_pattern.Rows[i]["Ampl"].ToString()) + AT; }

if you want to get around the + 1 issue

How can I truncate a datetime in SQL Server?

In SQl 2005 your trunc_date function could be written like this.

(1)

CREATE FUNCTION trunc_date(@date DATETIME)
RETURNS DATETIME
AS
BEGIN
    CAST(FLOOR( CAST( @date AS FLOAT ) )AS DATETIME)
END

The first method is much much cleaner. It uses only 3 method calls including the final CAST() and performs no string concatenation, which is an automatic plus. Furthermore, there are no huge type casts here. If you can imagine that Date/Time stamps can be represented, then converting from dates to numbers and back to dates is a fairly easy process.

(2)

CREATE FUNCTION trunc_date(@date DATETIME)
RETURNS DATETIME
AS
BEGIN
      SELECT CONVERT(varchar, @date,112)
END

If you are concerned about microsoft's implementation of datetimes (2) or (3) might be ok.

(3)

CREATE FUNCTION trunc_date(@date DATETIME)
RETURNS DATETIME
AS
BEGIN
SELECT CAST((STR( YEAR( @date ) ) + '/' +STR( MONTH( @date ) ) + '/' +STR( DAY(@date ) )
) AS DATETIME
END

Third, the more verbose method. This requires breaking the date into its year, month, and day parts, putting them together in "yyyy/mm/dd" format, then casting that back to a date. This method involves 7 method calls including the final CAST(), not to mention string concatenation.

HTTP Status 500 - Error instantiating servlet class pkg.coreServlet

The servlet class should be in the WEB-INF/classes not WEB-INF/src.

How do I pull files from remote without overwriting local files?

Well, yes, and no...

I understand that you want your local copies to "override" what's in the remote, but, oh, man, if someone has modified the files in the remote repo in some different way, and you just ignore their changes and try to "force" your own changes without even looking at possible conflicts, well, I weep for you (and your coworkers) ;-)

That said, though, it's really easy to do the "right thing..."

Step 1:

git stash

in your local repo. That will save away your local updates into the stash, then revert your modified files back to their pre-edit state.

Step 2:

git pull

to get any modified versions. Now, hopefully, that won't get any new versions of the files you're worried about. If it doesn't, then the next step will work smoothly. If it does, then you've got some work to do, and you'll be glad you did.

Step 3:

git stash pop

That will merge your modified versions that you stashed away in Step 1 with the versions you just pulled in Step 2. If everything goes smoothly, then you'll be all set!

If, on the other hand, there were real conflicts between what you pulled in Step 2 and your modifications (due to someone else editing in the interim), you'll find out and be told to resolve them. Do it.

Things will work out much better this way - it will probably keep your changes without any real work on your part, while alerting you to serious, serious issues.

How to apply CSS page-break to print a table with lots of rows?

I eventually realised that my bulk content that was overflowing the table and not breaking properly simply didn't even need to be inside a table.

While it's not a technical solution, it solved my problem to simply end the table when I no longer needed a table; then started a new one for the footer.

Hope it helps someone... good luck!

Get Multiple Values in SQL Server Cursor

Do not use @@fetch_status - this will return status from the last cursor in the current connection. Use the example below:

declare @sqCur cursor;
declare @data varchar(1000);
declare @i int = 0, @lastNum int, @rowNum int;
set @sqCur = cursor local static read_only for 
    select
         row_number() over (order by(select null)) as RowNum
        ,Data -- you fields
    from YourIntTable
open @cur
begin try
    fetch last from @cur into @lastNum, @data
    fetch absolute 1 from @cur into @rowNum, @data --start from the beginning and get first value 
    while @i < @lastNum
    begin
        set @i += 1

        --Do your job here
        print @data

        fetch next from @cur into @rowNum, @data
    end
end try
begin catch
    close @cur      --|
    deallocate @cur --|-remove this 3 lines if you do not throw
    ;throw          --|
end catch
close @cur
deallocate @cur

How to increase code font size in IntelliJ?

On Intellij Idea 3.3(Ultimate) System : Mac

IntelliJ Idea ? Preferences (CMD + ,) ? Editor ? General(Main) : Uncheck/Check "Change font size(Zoon) with Command + Mouse Wheel"

do <something> N times (declarative syntax)

TypeScript Implementation:

For those of you who are interested in how to implement String.times and Number.times in a way that is type safe and works with the thisArg, here ya go:

declare global {
    interface Number {
        times: (callbackFn: (iteration: number) => void, thisArg?: any) => void;
    }
    interface String {
        times: (callbackFn: (iteration: number) => void, thisArg?: any) => void;
    }
}

Number.prototype.times = function (callbackFn, thisArg) {
    const num = this.valueOf()
    if (typeof callbackFn !== "function" ) {
        throw new TypeError("callbackFn is not a function")
    }
    if (num < 0) {
        throw new RangeError('Must not be negative')
    }
    if (!isFinite(num)) {
        throw new RangeError('Must be Finite')
    }
    if (isNaN(num)) {
        throw new RangeError('Must not be NaN')
    }

    [...Array(num)].forEach((_, i) => callbackFn.bind(thisArg, i + 1)())
    // Other elegant solutions
    // new Array<null>(num).fill(null).forEach(() => {})
    // Array.from({length: num}).forEach(() => {})
}

String.prototype.times = function (callbackFn, thisArg) {
    let num = parseInt(this.valueOf())
    if (typeof callbackFn !== "function" ) {
        throw new TypeError("callbackFn is not a function")
    }
    if (num < 0) {
        throw new RangeError('Must not be negative')
    }
    if (!isFinite(num)) {
        throw new RangeError('Must be Finite')
    }
    // num is NaN if `this` is an empty string 
    if (isNaN(num)) {
        num = 0
    }

    [...Array(num)].forEach((_, i) => callbackFn.bind(thisArg, i + 1)())
    // Other elegant solutions
    // new Array<null>(num).fill(null).forEach(() => {})
    // Array.from({length: num}).forEach(() => {})
}

A link to the TypeScript Playground with some examples can be found here

This post implements solutions posted by: Andreas Bergström, vinyll, Ozay Duman, & SeregPie

GitHub - error: failed to push some refs to '[email protected]:myrepo.git'

Try this:

  1. git push -u origin master
  2. git push -f origin master

Sometimes #1 works and sometimes #2 for me. I am not sure why it reacts in this way

How do I get the picture size with PIL?

Since scipy's imread is deprecated, use imageio.imread.

  1. Install - pip install imageio
  2. Use height, width, channels = imageio.imread(filepath).shape

How to use GOOGLEFINANCE(("CURRENCY:EURAUD")) function

The syntax is:

=GOOGLEFINANCE(ticker, [attribute], [start_date], [num_days|end_date], [interval])

Sample usage:

=GOOGLEFINANCE("GOOG", "price", DATE(2014,1,1), DATE(2014,12,31), "DAILY")
=GOOGLEFINANCE("GOOG","price",TODAY()-30,TODAY())
=GOOGLEFINANCE(A2,A3)
=117.80*Index(GOOGLEFINANCE("CURRENCY:EURGBP", "close", DATE(2014,1,1)), 2, 2)

For instance if you'd like to convert the rate on specific date, here is some more advanced example:

=IF($C2 = "GBP", "", Index(GoogleFinance(CONCATENATE("CURRENCY:", C2, "GBP"), "close", DATE(year($A2), month($A2), day($A2)), DATE(year($A2), month($A2), day($A2)+1), "DAILY"), 2))

where $A2 is your date (e.g. 01/01/2015) and C2 is your currency (e.g. EUR).

See more samples at Docs editors Help at Google.

Correct way to pause a Python program

I assume you want to pause without input.

Use:

time.sleep(seconds)

iPhone: How to get current milliseconds?

I benchmarked all the other answers on an iPhone 4S and iPad 3 (release builds). CACurrentMediaTime has the least overhead by a small margin. timeIntervalSince1970 is far slower than the others, probably due to NSDate instantiation overhead, though it may not matter for many use cases.

I'd recommend CACurrentMediaTime if you want the least overhead and don't mind adding the Quartz Framework dependency. Or gettimeofday if portability is a priority for you.

iPhone 4S

CACurrentMediaTime: 1.33 µs/call
gettimeofday: 1.38 µs/call
[NSDate timeIntervalSinceReferenceDate]: 1.45 µs/call
CFAbsoluteTimeGetCurrent: 1.48 µs/call
[[NSDate date] timeIntervalSince1970]: 4.93 µs/call

iPad 3

CACurrentMediaTime: 1.25 µs/call
gettimeofday: 1.33 µs/call
CFAbsoluteTimeGetCurrent: 1.34 µs/call
[NSDate timeIntervalSinceReferenceDate]: 1.37 µs/call
[[NSDate date] timeIntervalSince1970]: 3.47 µs/call

Add an incremental number in a field in INSERT INTO SELECT query in SQL Server

You can use the row_number() function for this.

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
            row_number() over (order by (select NULL))
    FROM PM_Ingrediants 
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

If you want to start with the maximum already in the table then do:

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
           coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
    FROM PM_Ingrediants cross join
         (select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

Finally, you can just make the sequence column an auto-incrementing identity column. This saves the need to increment it each time:

create table PM_Ingrediants_Arrangement_Temp ( . . .
    sequence int identity(1, 1) -- and might consider making this a primary key too
    . . .
)

Adding elements to an xml file in C#

If you want to add an attribute, and not an element, you have to say so:

XElement root = new XElement("Snippet");
root.Add(new XAttribute("name", "name goes here"));
root.Add(new XElement("SnippetCode", "SnippetCode"));

The code above produces the following XML element:

<Snippet name="name goes here">
  <SnippetCode>SnippetCode</SnippetCode>
</Snippet> 

Calling Scalar-valued Functions in SQL

Are you sure it's not a Table-Valued Function?

The reason I ask:

CREATE FUNCTION dbo.chk_mgr(@mgr VARCHAR(50)) 
RETURNS @mgr_table TABLE (mgr_name VARCHAR(50))
AS
BEGIN 
  INSERT @mgr_table (mgr_name) VALUES ('pointy haired boss') 
  RETURN
END 
GO

SELECT dbo.chk_mgr('asdf')
GO

Result:

Msg 4121, Level 16, State 1, Line 1
Cannot find either column "dbo" or the user-defined function 
or aggregate "dbo.chk_mgr", or the name is ambiguous.

However...

SELECT * FROM dbo.chk_mgr('asdf') 

mgr_name
------------------
pointy haired boss

Validate that a string is a positive integer

Two answers for you:

  • Based on parsing

  • Regular expression

Note that in both cases, I've interpreted "positive integer" to include 0, even though 0 is not positive. I include notes if you want to disallow 0.

Based on Parsing

If you want it to be a normalized decimal integer string over a reasonable range of values, you can do this:

function isNormalInteger(str) {
    var n = Math.floor(Number(str));
    return n !== Infinity && String(n) === str && n >= 0;
}

or if you want to allow whitespace and leading zeros:

function isNormalInteger(str) {
    str = str.trim();
    if (!str) {
        return false;
    }
    str = str.replace(/^0+/, "") || "0";
    var n = Math.floor(Number(str));
    return n !== Infinity && String(n) === str && n >= 0;
}

Live testbed (without handling leading zeros or whitespace):

_x000D_
_x000D_
function isNormalInteger(str) {_x000D_
    var n = Math.floor(Number(str));_x000D_
    return n !== Infinity && String(n) === str && n >= 0;_x000D_
}_x000D_
function gid(id) {_x000D_
    return document.getElementById(id);_x000D_
}_x000D_
function test(str, expect) {_x000D_
    var result = isNormalInteger(str);_x000D_
    console.log(_x000D_
        str + ": " +_x000D_
        (result ? "Yes" : "No") +_x000D_
        (expect === undefined ? "" : !!expect === !!result ? " <= OK" : " <= ERROR ***")_x000D_
    );_x000D_
}_x000D_
gid("btn").addEventListener(_x000D_
    "click",_x000D_
    function() {_x000D_
        test(gid("text").value);_x000D_
    },_x000D_
    false_x000D_
);_x000D_
test("1", true);_x000D_
test("1.23", false);_x000D_
test("1234567890123", true);_x000D_
test("1234567890123.1", false);_x000D_
test("0123", false); // false because we don't handle leading 0s_x000D_
test(" 123 ", false); // false because we don't handle whitespace
_x000D_
<label>_x000D_
  String:_x000D_
  <input id="text" type="text" value="">_x000D_
<label>_x000D_
<input id="btn" type="button" value="Check">
_x000D_
_x000D_
_x000D_

Live testbed (with handling for leading zeros and whitespace):

_x000D_
_x000D_
function isNormalInteger(str) {_x000D_
    str = str.trim();_x000D_
    if (!str) {_x000D_
        return false;_x000D_
    }_x000D_
    str = str.replace(/^0+/, "") || "0";_x000D_
    var n = Math.floor(Number(str));_x000D_
    return String(n) === str && n >= 0;_x000D_
}_x000D_
function gid(id) {_x000D_
    return document.getElementById(id);_x000D_
}_x000D_
function test(str, expect) {_x000D_
    var result = isNormalInteger(str);_x000D_
    console.log(_x000D_
        str + ": " +_x000D_
        (result ? "Yes" : "No") +_x000D_
        (expect === undefined ? "" : !!expect === !!result ? " <= OK" : " <= ERROR ***")_x000D_
    );_x000D_
}_x000D_
gid("btn").addEventListener(_x000D_
    "click",_x000D_
    function() {_x000D_
        test(gid("text").value);_x000D_
    },_x000D_
    false_x000D_
);_x000D_
test("1", true);_x000D_
test("1.23", false);_x000D_
test("1234567890123", true);_x000D_
test("1234567890123.1", false);_x000D_
test("0123", true);_x000D_
test(" 123 ", true);
_x000D_
<label>_x000D_
  String:_x000D_
  <input id="text" type="text" value="">_x000D_
<label>_x000D_
<input id="btn" type="button" value="Check">
_x000D_
_x000D_
_x000D_

If you want to disallow 0, just change >= 0 to > 0. (Or, in the version that allows leading zeros, remove the || "0" on the replace line.)

How that works:

  1. In the version allowing whitespace and leading zeros:

    • str = str.trim(); removes any leading and trailing whitepace.
    • if (!str) catches a blank string and returns, no point in doing the rest of the work.
    • str = str.replace(/^0+/, "") || "0"; removes all leading 0s from the string — but if that results in a blank string, restores a single 0.
  2. Number(str): Convert str to a number; the number may well have a fractional portion, or may be NaN.

  3. Math.floor: Truncate the number (chops off any fractional portion).

  4. String(...): Converts the result back into a normal decimal string. For really big numbers, this will go to scientific notation, which may break this approach. (I don't quite know where the split is, the details are in the spec, but for whole numbers I believe it's at the point you've exceeded 21 digits [by which time the number has become very imprecise, as IEEE-754 double-precision numbers only have roughtly 15 digits of precision..)

  5. ... === str: Compares that to the original string.

  6. n >= 0: Check that it's positive.

Note that this fails for the input "+1", any input in scientific notation that doesn't turn back into the same scientific notation at the String(...) stage, and for any value that the kind of number JavaScript uses (IEEE-754 double-precision binary floating point) can't accurately represent which parses as closer to a different value than the given one (which includes many integers over 9,007,199,254,740,992; for instance, 1234567890123456789 will fail). The former is an easy fix, the latter two not so much.

Regular Expression

The other approach is to test the characters of the string via a regular expression, if your goal is to just allow (say) an optional + followed by either 0 or a string in normal decimal format:

function isNormalInteger(str) {
    return /^\+?(0|[1-9]\d*)$/.test(str);
}

Live testbed:

_x000D_
_x000D_
function isNormalInteger(str) {_x000D_
    return /^\+?(0|[1-9]\d*)$/.test(str);_x000D_
}_x000D_
function gid(id) {_x000D_
    return document.getElementById(id);_x000D_
}_x000D_
function test(str, expect) {_x000D_
    var result = isNormalInteger(str);_x000D_
    console.log(_x000D_
        str + ": " +_x000D_
        (result ? "Yes" : "No") +_x000D_
        (expect === undefined ? "" : !!expect === !!result ? " <= OK" : " <= ERROR ***")_x000D_
    );_x000D_
}_x000D_
gid("btn").addEventListener(_x000D_
    "click",_x000D_
    function() {_x000D_
        test(gid("text").value);_x000D_
    },_x000D_
    false_x000D_
);_x000D_
test("1", true);_x000D_
test("1.23", false);_x000D_
test("1234567890123", true);_x000D_
test("1234567890123.1", false);_x000D_
test("0123", false); // false because we don't handle leading 0s_x000D_
test(" 123 ", false); // false because we don't handle whitespace
_x000D_
<label>_x000D_
  String:_x000D_
  <input id="text" type="text" value="">_x000D_
<label>_x000D_
<input id="btn" type="button" value="Check">
_x000D_
_x000D_
_x000D_

How that works:

  1. ^: Match start of string

  2. \+?: Allow a single, optional + (remove this if you don't want to)

  3. (?:...|...): Allow one of these two options (without creating a capture group):

    1. (0|...): Allow 0 on its own...

    2. (...|[1-9]\d*): ...or a number starting with something other than 0 and followed by any number of decimal digits.

  4. $: Match end of string.

If you want to disallow 0 (because it's not positive), the regular expression becomes just /^\+?[1-9]\d*$/ (e.g., we can lose the alternation that we needed to allow 0).

If you want to allow leading zeroes (0123, 00524), then just replace the alternation (?:0|[1-9]\d*) with \d+

function isNormalInteger(str) {
    return /^\+?\d+$/.test(str);
}

If you want to allow whitespace, add \s* just after ^ and \s* just before $.

Note for when you convert that to a number: On modern engines it would probably be fine to use +str or Number(str) to do it, but older ones might extend those in a non-standard (but formerly-allowed) way that says a leading zero means octal (base 8), e.g "010" => 8. Once you've validated the number, you can safely use parseInt(str, 10) to ensure that it's parsed as decimal (base 10). parseInt would ignore garbage at the end of the string, but we've ensured there isn't any with the regex.

Are email addresses case sensitive?

IETF Open Standards RFC 5321 2.4. General Syntax Principles and Transaction Model

SMTP implementations MUST take care to preserve the case of mailbox local-parts. In particular, for some hosts, the user "smith" is different from the user "Smith".

Mailbox domains follow normal DNS rules and are hence not case sensitive

How to clear jQuery validation error messages?

To remove the validation summary you could write this

$('div#errorMessage').remove();

However, once you removed , again if validation failed it won't show this validation summary because you removed it. Instead use hide and display using the below code

$('div#errorMessage').css('display', 'none');

$('div#errorMessage').css('display', 'block');  

How do I include a pipe | in my linux find -exec command?

I found that running a string shell command (sh -c) works best, for example:

find -name 'file_*' -follow -type f -exec bash -c "zcat \"{}\" | agrep -dEOE 'grep'" \;

MySQL check if a table exists without throwing an exception

If you're using MySQL 5.0 and later, you could try:

SELECT COUNT(*)
FROM information_schema.tables 
WHERE table_schema = '[database name]' 
AND table_name = '[table name]';

Any results indicate the table exists.

From: http://www.electrictoolbox.com/check-if-mysql-table-exists/

How can I switch word wrap on and off in Visual Studio Code?

Since 1.9, it's possible to select a specific language for word wrap settings (or any settings). You can find this in the command palette under:

Preferences: Configure Language Specific Settings...

Which will take you to your "settings.json" for a selected language where you might include:

"[markdown]": {
  "editor.wordWrapColumn": 100,
  "editor.wordWrap": "wordWrapColumn"
},

What does it mean to bind a multicast (UDP) socket?

Correction for What does it mean to bind a multicast (udp) socket? as long as it partially true at the following quote:

The "bind" operation is basically saying, "use this local UDP port for sending and receiving data. In other words, it allocates that UDP port for exclusive use for your application

There is one exception. Multiple applications can share the same port for listening (usually it has practical value for multicast datagrams), if the SO_REUSEADDR option applied. For example

int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); // create UDP socket somehow
...
int set_option_on = 1;
// it is important to do "reuse address" before bind, not after
int res = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*) &set_option_on, 
    sizeof(set_option_on));
res = bind(sock, src_addr, len);

If several processes did such "reuse binding", then every UDP datagram received on that shared port will be delivered to each of the processes (providing natural joint with multicasts traffic).

Here are further details regarding what happens in a few cases:

  1. attempt of any bind ("exclusive" or "reuse") to free port will be successful

  2. attempt to "exclusive binding" will fail if the port is already "reuse-binded"

  3. attempt to "reuse binding" will fail if some process keeps "exclusive binding"

SQL Server - Convert date field to UTC

As mentioned here previously, there is no build-in way to perform time zone rules aware date conversion in SQL Server (at least as of SQL Server 2012).

You have essentially three choices to do this right:

  1. Perform the conversion outside of SQL Server and store results in the database
  2. Introduce time zone offset rules in a standalone table and create stored procedures or UDFs to reference the rules table to perform conversions. You can find one take on this approach over at SQL Server Central (registration required)
  3. You can create a SQL CLR UDF; I will describe the approach here

While SQL Server does not offer tools to perform time zone rules aware date conversion, the .NET framework does, and as long as you can use SQL CLR, you can take advantage of that.

In Visual Studio 2012, make sure you have the data tools installed (otherwise, SQL Server project won't show up as an option), and create a new SQL Server project.

Then, add a new SQL CLR C# User Defined Function, call it "ConvertToUtc". VS will generate boiler plate for you that should look something like this:

public partial class UserDefinedFunctions
{
    [Microsoft.SqlServer.Server.SqlFunction]
    public static SqlString ConvertToUtc()
    {
        // Put your code here
        return new SqlString (string.Empty);
    }
}

We want to make several changes here. For one, we want to return a SqlDateTime rather than a SqlString. Secondly, we want to do something useful. :)

Your revised code should look like this:

public partial class UserDefinedFunctions
{
    [Microsoft.SqlServer.Server.SqlFunction]
    public static SqlDateTime ConvertToUtc(SqlDateTime sqlLocalDate)
    {
        // convert to UTC and use explicit conversion
        // to return a SqlDateTime
        return TimeZone.CurrentTimeZone.ToUniversalTime(sqlLocalDate.Value);
    }
}

At this point, we are ready to try it out. The simplest way is to use the built-in Publish facility in Visual Studio. Right-click on the database project and select "Publish". Set up your database connection and name, and then either click "Publish" to push the code into the database or click "Generate Script" if you'd like to store the script for posterity (or to push the bits into production).

Once you have the UDF in the database, you can see it in action:

declare @dt as datetime
set @dt = '12/1/2013 1:00 pm'
select dbo.ConvertToUtc(@dt)

C#, Looping through dataset and show each record from a dataset column

foreach (DataRow dr in ds.Tables[0].Rows)
{
    //your code here
}

Function names in C++: Capitalize or not?

There isn't so much a 'correct' way for the language. It's more personal preference or what the standard is for your team. I usually use the myFunction() when I'm doing my own code. Also, a style you didn't mention that you will often see in C++ is my_function() - no caps, underscores instead of spaces.

Really it is just dictated by the code your working in. Or, if it's your own project, your own personal preference then.

INFO: No Spring WebApplicationInitializer types detected on classpath

I also had the same problem. My maven had tomcat7 plugin but the JRE environment was 1.6. I changed my tomcat7 to tomcat6 and the error was gone.