Programs & Examples On #Ca1001

Best way to combine two or more byte arrays in C#

    public static bool MyConcat<T>(ref T[] base_arr, ref T[] add_arr)
    {
        try
        {
            int base_size = base_arr.Length;
            int size_T = System.Runtime.InteropServices.Marshal.SizeOf(base_arr[0]);
            Array.Resize(ref base_arr, base_size + add_arr.Length);
            Buffer.BlockCopy(add_arr, 0, base_arr, base_size * size_T, add_arr.Length * size_T);
        }
        catch (IndexOutOfRangeException ioor)
        {
            MessageBox.Show(ioor.Message);
            return false;
        }
        return true;
    }

Git fatal: protocol 'https' is not supported

Copy in plain notepad (git clone https://github.com/./Spoon-Knife.git) and paste it in cmd. now it will work.

Delete rows containing specific strings in R

You could use dplyr::filter() and negate a grepl() match:

library(dplyr)

df %>% 
  filter(!grepl('REVERSE', Name))

Or with dplyr::filter() and negating a stringr::str_detect() match:

library(stringr)

df %>% 
  filter(!str_detect(Name, 'REVERSE'))

Can IntelliJ IDEA encapsulate all of the functionality of WebStorm and PHPStorm through plugins?

Definitely a great question. I've noted this also as a sub question of the choice for versions within IDEa that this link may help to address...

http://www.jetbrains.com/idea/features/editions_comparison_matrix.html

it as well potentially possesses a ground work for looking at your other IDE choices and the options they provide.

I'm thinking WebStorm is best for JavaScript and Git repo management, meaning the HTML5 CSS Cordova kinds of stacks, which is really where (I believe along with others) the future lies and energies should be focused now... but ya it depends on your needs, etc.

Anyway this tells that story too... http://www.jetbrains.com/products.html

Python - AttributeError: 'numpy.ndarray' object has no attribute 'append'

append on an ndarray is ambiguous; to which axis do you want to append the data? Without knowing precisely what your data looks like, I can only provide an example using numpy.concatenate that I hope will help:

import numpy as np

pixels = np.array([[3,3]])
pix = [4,4]
pixels = np.concatenate((pixels,[pix]),axis=0)

# [[3 3]
#  [4 4]]

UIButton: how to center an image and a text using imageEdgeInsets and titleEdgeInsets?

This works well for me, for several buttons, with different image width and different title length :

Subclass UIButton

override func layoutSubviews() {
    super.layoutSubviews()

    if let image = imageView?.image {

        let margin = 30 - image.size.width / 2
        let titleRect = titleRectForContentRect(bounds)
        let titleOffset = (bounds.width - titleRect.width - image.size.width - margin) / 2


        contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left
            imageEdgeInsets = UIEdgeInsetsMake(0, margin, 0, 0)
            titleEdgeInsets = UIEdgeInsetsMake(0, (bounds.width - titleRect.width -  image.size.width - margin) / 2, 0, 0)
    }

}

OAuth: how to test with local URLs?

You can edit the hosts file on windows or linux Windows : C:\Windows\System32\Drivers\etc\hosts Linux : /etc/hosts

localhost name resolution is handled within DNS itself.

127.0.0.1 mywebsite.com

after you finish your tests you just comment the line you add to disable it

127.0.0.1 mywebsite.com

Ajax request returns 200 OK, but an error event is fired instead of success

If you always return JSON from the server (no empty responses), dataType: 'json' should work and contentType is not needed. However make sure the JSON output...

jQuery AJAX will throw a 'parseerror' on valid but unserialized JSON!

What are some resources for getting started in operating system development?

My operating systems course in undergrad had us building a number of subsystems for OS/161, a simple, BSD-like kernel that provides some of the basics while leaving the freedom to explore various design space decisions in implementing higher-level services.

Hibernate: flush() and commit()

By default flush mode is AUTO which means that: "The Session is sometimes flushed before query execution in order to ensure that queries never return stale state", but most of the time session is flushed when you commit your changes. Manual calling of the flush method is usefull when you use FlushMode=MANUAL or you want to do some kind of optimization. But I have never done this so I can't give you practical advice.

Why is JsonRequestBehavior needed?

You do not need it.

If your action has the HttpPost attribute, then you do not need to bother with setting the JsonRequestBehavior and use the overload without it. There is an overload for each method without the JsonRequestBehavior enum. Here they are:

Without JsonRequestBehavior

protected internal JsonResult Json(object data);
protected internal JsonResult Json(object data, string contentType);
protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding);

With JsonRequestBehavior

protected internal JsonResult Json(object data, JsonRequestBehavior behavior);
protected internal JsonResult Json(object data, string contentType, 
                                   JsonRequestBehavior behavior);
protected internal virtual JsonResult Json(object data, string contentType, 
    Encoding contentEncoding, JsonRequestBehavior behavior);

How to download the latest artifact from Artifactory repository?

I use Nexus and this code works for me—can retrive both release and last snaphsot, depending on repository type:

server="http://example.com/nexus/content/repositories"
repo="snapshots"
name="com.exmple.server"
artifact="com/example/$name"
path=$server/$repo/$artifact
mvnMetadata=$(curl -s "$path/maven-metadata.xml")
echo "Metadata: $mvnMetadata"
jar=""
version=$( echo "$mvnMetadata" | xpath -e "//versioning/release/text()" 2> /dev/null)
if [[ $version = *[!\ ]* ]]; then
  jar=$name-$version.jar
else
  version=$(echo "$mvnMetadata" | xpath -e "//versioning/versions/version[last()]/text()")
  snapshotMetadata=$(curl -s "$path/$version/maven-metadata.xml")
  timestamp=$(echo "$snapshotMetadata" | xpath -e "//snapshot/timestamp/text()")
  buildNumber=$(echo "$snapshotMetadata" | xpath -e "//snapshot/buildNumber/text()")
  snapshotVersion=$(echo "$version" | sed 's/\(-SNAPSHOT\)*$//g')
  jar=$name-$snapshotVersion-$timestamp-$buildNumber.jar
fi
jarUrl=$path/$version/$jar
echo $jarUrl
mkdir -p /opt/server/
wget -O /opt/server/server.jar -q -N $jarUrl

Escaping backslash in string - javascript

For security reasons, it is not possible to get the real, full path of a file, referred through an <input type="file" /> element.

This question already mentions, and links to other Stack Overflow questions regarding this topic.


Previous answer, kept as a reference for future visitors who reach this page through the title, tags and question.
The backslash has to be escaped.

string = string.split("\\");

In JavaScript, the backslash is used to escape special characters, such as newlines (\n). If you want to use a literal backslash, a double backslash has to be used.

So, if you want to match two backslashes, four backslashes has to be used. For example,alert("\\\\") will show a dialog containing two backslashes.

Rails: FATAL - Peer authentication failed for user (PG::Error)

This is the most foolproof way to get your rails app working with postgres in the development environment in Ubuntu 13.10.

1) Create rails app with postgres YAML and 'pg' gem in the Gemfile:

$ rails new my_application -d postgresql

2) Give it some CRUD functionality. If you're just seeing if postgres works, create a scaffold:

$ rails g scaffold cats name:string age:integer colour:string

3) As of rails 4.0.1 the -d postgresql option generates a YAML that doesn't include a host parameter. I found I needed this. Edit the development section and create the following parameters:

encoding: UTF-8
host: localhost
database: my_application_development
username: thisismynewusername
password: thisismynewpassword 

Note the database parameter is for a database that doesn't exit yet, and the username and password are credentials for a role that doesn't exist either. We'll create those later on!

This is how config/database.yml should look (no shame in copypasting :D ):

development:
  adapter: postgresql
  pool: 5
  # these are our new parameters
  encoding: UTF-8
  database: my_application_development
  host: localhost
  username: thisismynewusername
  password: thisismynewpassword

test:
  # this won't work 
  adapter: postgresql
  encoding: unicode
  database: my_application_test
  pool: 5
  username: my_application
  password:

production:
  # this won't work 
  adapter: postgresql
  encoding: unicode
  database: my_application_production
  pool: 5
  username: my_application
  password:

4) Start the postgres shell with this command:

$ psql

4a) You may get this error if your current user (as in your computer user) doesn't have a corresponding administration postgres role.

psql: FATAL:  role "your_username" does not exist

Now I've only installed postgres once, so I may be wrong here, but I think postgres automatically creates an administration role with the same credentials as the user you installed postgres as.

4b) So this means you need to change to the user that installed postgres to use the psql command and start the shell:

$ sudo su postgres

And then run

$ psql

5) You'll know you're in the postgres shell because your terminal will look like this:

$ psql
psql (9.1.10)
Type "help" for help.

postgres=# 

6) Using the postgresql syntax, let's create the user we specified in config/database.yml's development section:

postgres=# CREATE ROLE thisismynewusername WITH LOGIN PASSWORD 'thisismynewpassword';

Now, there's some subtleties here so let's go over them.

  • The role's username, thisismynewusername, does not have quotes of any kind around it
  • Specify the keyword LOGIN after the WITH. If you don't, the role will still be created, but it won't be able to log in to the database!
  • The role's password, thisismynewpassword, needs to be in single quotes. Not double quotes.
  • Add a semi colon on the end ;)

You should see this in your terminal:

postgres=#
CREATE ROLE
postgres=#

That means, "ROLE CREATED", but postgres' alerts seem to adopt the same imperative conventions of git hub.

7) Now, still in the postgres shell, we need to create the database with the name we set in the YAML. Make the user we created in step 6 its owner:

postgres=# CREATE DATABASE my_application_development OWNER thisismynewusername;

You'll know if you were successful because you'll get the output:

CREATE DATABASE

8) Quit the postgres shell:

\q

9) Now the moment of truth:

$ RAILS_ENV=development rake db:migrate

If you get this:

==  CreateCats: migrating =================================================
-- create_table(:cats)
   -> 0.0028s
==  CreateCats: migrated (0.0028s) ========================================

Congratulations, postgres is working perfectly with your app.

9a) On my local machine, I kept getting a permission error. I can't remember it exactly, but it was an error along the lines of

Can't access the files. Change permissions to 666.

Though I'd advise thinking very carefully about recursively setting write privaledges on a production machine, locally, I gave my whole app read write privileges like this:

9b) Climb up one directory level:

$ cd ..

9c) Set the permissions of the my_application directory and all its contents to 666:

$ chmod -R 0666 my_application

9d) And run the migration again:

$ RAILS_ENV=development rake db:migrate

==  CreateCats: migrating =================================================
-- create_table(:cats)
   -> 0.0028s
==  CreateCats: migrated (0.0028s) ========================================

Some tips and tricks if you muck up

Try these before restarting all of these steps:

The mynewusername user doesn't have privileges to CRUD to the my_app_development database? Drop the database and create it again with mynewusername as the owner:

1) Start the postgres shell:

$ psql

2) Drop the my_app_development database. Be careful! Drop means utterly delete!

postgres=# DROP DATABASE my_app_development;

3) Recreate another my_app_development and make mynewusername the owner:

postgres=# CREATE DATABASE my_application_development OWNER mynewusername;

4) Quit the shell:

postgres=# \q

The mynewusername user can't log into the database? Think you wrote the wrong password in the YAML and can't quite remember the password you entered using the postgres shell? Simply alter the role with the YAML password:

1) Open up your YAML, and copy the password to your clipboard:

 development:
      adapter: postgresql
      pool: 5
      # these are our new parameters
      encoding: UTF-8
      database: my_application_development
      host: localhost
      username: thisismynewusername
      password: musthavebeenverydrunkwheniwrotethis

2) Start the postgres shell:

$ psql    

3) Update mynewusername's password. Paste in the password, and remember to put single quotes around it:

postgres=# ALTER ROLE mynewusername PASSWORD `musthavebeenverydrunkwheniwrotethis`;

4) Quit the shell:

postgres=# \q

Trying to connect to localhost via a database viewer such as Dbeaver, and don't know what your postgres user's password is? Change it like this:

1) Run passwd as a superuser:

$ sudo passwd postgres

2) Enter your accounts password for sudo (nothing to do with postgres):

[sudo] password for starkers: myaccountpassword

3) Create the postgres account's new passwod:

Enter new UNIX password: databasesarefun
Retype new UNIX password: databasesarefun
passwd: password updated successfully

Getting this error message?:

Run `$ bin/rake db:create db:migrate` to create your database
$ rake db:create db:migrate
PG::InsufficientPrivilege: ERROR:  permission denied to create database

4) You need to give your user the ability to create databases. From the psql shell:

ALTER ROLE thisismynewusername WITH CREATEDB

SQLSTATE[HY000] [1045] Access denied for user 'username'@'localhost' using CakePHP

Check Following Things

  • Make Sure You Have MySQL Server Running
  • Check connection with default credentials i.e. username : 'root' & password : '' [Blank Password]
  • Try login phpmyadmin with same credentials
  • Try to put 127.0.0.1 instead localhost or your lan IP would do too.
  • Make sure you are running MySql on 3306 and if you have configured make sure to state it while making a connection

Is Java RegEx case-insensitive?

RegexBuddy is telling me if you want to include it at the beginning, this is the correct syntax:

"(?i)\\b(\\w+)\\b(\\s+\\1)+\\b"

Determine if running on a rooted device

Using C++ with the ndk is the best approach to detect root even if the user is using applications that hide his root such as RootCloak. I tested this code with RootCloak and I was able to detect the root even if the user is trying to hide it. So your cpp file would like:

#include <jni.h>
#include <string>


/**
 *
 * function that checks for the su binary files and operates even if 
 * root cloak is installed
 * @return integer 1: device is rooted, 0: device is not 
 *rooted
*/
extern "C"
JNIEXPORT int JNICALL


Java_com_example_user_root_1native_rootFunction(JNIEnv *env,jobject thiz){
const char *paths[] ={"/system/app/Superuser.apk", "/sbin/su", "/system/bin/su",
                      "/system/xbin/su", "/data/local/xbin/su", "/data/local/bin/su", "/system/sd/xbin/su",
                      "/system/bin/failsafe/su", "/data/local/su", "/su/bin/su"};

int counter =0;
while (counter<9){
    if(FILE *file = fopen(paths[counter],"r")){
        fclose(file);
        return 1;
    }
    counter++;
}
return 0;
}

And you will call the function from your java code as follows

public class Root_detect {



   /**
    *
    * function that calls a native function to check if the device is 
    *rooted or not
    * @return boolean: true if the device is rooted, false if the 
    *device is not rooted
   */
   public boolean check_rooted(){

        int checker = rootFunction();

        if(checker==1){
           return true;
        }else {
           return false;
        }
   }
   static {
    System.loadLibrary("cpp-root-lib");//name of your cpp file
   }

   public native int rootFunction();
}

How do I create a file and write to it?

public class Program {
    public static void main(String[] args) {
        String text = "Hello world";
        BufferedWriter output = null;
        try {
            File file = new File("example.txt");
            output = new BufferedWriter(new FileWriter(file));
            output.write(text);
        } catch ( IOException e ) {
            e.printStackTrace();
        } finally {
          if ( output != null ) {
            output.close();
          }
        }
    }
}

Why is it faster to check if dictionary contains the key, rather than catch the exception in case it doesn't?

On the one hand, throwing exceptions is inherently expensive, because the stack has to be unwound etc.
On the other hand, accessing a value in a dictionary by its key is cheap, because it's a fast, O(1) operation.

BTW: The correct way to do this is to use TryGetValue

obj item;
if(!dict.TryGetValue(name, out item))
    return null;
return item;

This accesses the dictionary only once instead of twice.
If you really want to just return null if the key doesn't exist, the above code can be simplified further:

obj item;
dict.TryGetValue(name, out item);
return item;

This works, because TryGetValue sets item to null if no key with name exists.

Open files always in a new tab

Use workbench.editor.enablePreview: false to disable Preview mode completely.

Use workbench.editor.enablePreviewFromQuickOpen: false to disable Preview mode for the files open from quick open menu.

Show only two digit after decimal

Use DecimalFormat.

DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale, including support for Western, Arabic, and Indic digits. It also supports different kinds of numbers, including integers (123), fixed-point numbers (123.4), scientific notation (1.23E4), percentages (12%), and currency amounts ($123). All of these can be localized.

Code snippet -

double i2=i/60000;
tv.setText(new DecimalFormat("##.##").format(i2));

Output -

5.81

How to check if a character in a string is a digit or letter

     char temp = yourString.charAt(0);
     if(Character.isDigit(temp))
     {
         ..........
     }else if (Character.isLetter(temp))
     {
          ......
      }else
     {
      ....
     }

Why check both isset() and !empty()

  • From the PHP Web site, referring to the empty() function:

Returns FALSE if var has a non-empty and non-zero value.

That’s a good thing to know. In other words, everything from NULL, to 0 to “” will return TRUE when using the empty() function.

  • Here is the description of what the isset() function returns:

Returns TRUE if var exists; FALSE otherwise.

In other words, only variables that don’t exist (or, variables with strictly NULL values) will return FALSE on the isset() function. All variables that have any type of value, whether it is 0, a blank text string, etc. will return TRUE.

How to form a correct MySQL connection string?

try creating connection string this way:

MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "mysql7.000webhost.com";
conn_string.UserID = "a455555_test";
conn_string.Password = "a455555_me";
conn_string.Database = "xxxxxxxx";

using (MySqlConnection conn = new MySqlConnection(conn_string.ToString()))
using (MySqlCommand cmd = conn.CreateCommand())
{    //watch out for this SQL injection vulnerability below
     cmd.CommandText = string.Format("INSERT Test (lat, long) VALUES ({0},{1})",
                                    OSGconv.deciLat, OSGconv.deciLon);
     conn.Open();
     cmd.ExecuteNonQuery();
}

How to work with complex numbers in C?

Complex types are in the C language since C99 standard (-std=c99 option of GCC). Some compilers may implement complex types even in more earlier modes, but this is non-standard and non-portable extension (e.g. IBM XL, GCC, may be intel,... ).

You can start from http://en.wikipedia.org/wiki/Complex.h - it gives a description of functions from complex.h

This manual http://pubs.opengroup.org/onlinepubs/009604499/basedefs/complex.h.html also gives some info about macros.

To declare a complex variable, use

  double _Complex  a;        // use c* functions without suffix

or

  float _Complex   b;        // use c*f functions - with f suffix
  long double _Complex c;    // use c*l functions - with l suffix

To give a value into complex, use _Complex_I macro from complex.h:

  float _Complex d = 2.0f + 2.0f*_Complex_I;

(actually there can be some problems here with (0,-0i) numbers and NaNs in single half of complex)

Module is cabs(a)/cabsl(c)/cabsf(b); Real part is creal(a), Imaginary is cimag(a). carg(a) is for complex argument.

To directly access (read/write) real an imag part you may use this unportable GCC-extension:

 __real__ a = 1.4;
 __imag__ a = 2.0;
 float b = __real__ a;

How to convert xml into array in php?

Converting an XML string ($buffer) into a simplified array ignoring attributes and grouping child-elements with the same names:

function XML2Array(SimpleXMLElement $parent)
{
    $array = array();

    foreach ($parent as $name => $element) {
        ($node = & $array[$name])
            && (1 === count($node) ? $node = array($node) : 1)
            && $node = & $node[];

        $node = $element->count() ? XML2Array($element) : trim($element);
    }

    return $array;
}

$xml   = simplexml_load_string($buffer);
$array = XML2Array($xml);
$array = array($xml->getName() => $array);

Result:

Array
(
    [aaaa] => Array
        (
            [bbb] => Array
                (
                    [cccc] => Array
                        (
                            [dddd] => 
                            [eeee] => 
                        )

                )

        )

)

If you also want to have the attributes, they are available via JSON encoding/decoding of SimpleXMLElement. This is often the most easy quick'n'dirty solution:

$xml   = simplexml_load_string($buffer);
$array = json_decode(json_encode((array) $xml), true);
$array = array($xml->getName() => $array);

Result:

Array
(
    [aaaa] => Array
        (
            [@attributes] => Array
                (
                    [Version] => 1.0
                )

            [bbb] => Array
                (
                    [cccc] => Array
                        (
                            [dddd] => Array
                                (
                                    [@attributes] => Array
                                        (
                                            [Id] => id:pass
                                        )

                                )

                            [eeee] => Array
                                (
                                    [@attributes] => Array
                                        (
                                            [name] => hearaman
                                            [age] => 24
                                        )

                                )

                        )

                )

        )

)

Take note that all these methods only work in the namespace of the XML document.

Writing a dict to txt file and reading it back?

You can iterate through the key-value pair and write it into file

pair = {'name': name,'location': location}
with open('F:\\twitter.json', 'a') as f:
     f.writelines('{}:{}'.format(k,v) for k, v in pair.items())
     f.write('\n')

PHP, getting variable from another php-file

You can, but the variable in your last include will overwrite the variable in your first one:

myfile.php

$var = 'test';

mysecondfile.php

$var = 'tester';

test.php

include 'myfile.php';
echo $var;

include 'mysecondfile.php';
echo $var;

Output:

test

tester

I suggest using different variable names.

EditText underline below text property

change your colorAccent which color you need that color set on colorAccent and run you get the output

Does Python have a ternary conditional operator?

Vinko Vrsalovic's answer is good enough. There is only one more thing:

Note that conditionals are an expression, not a statement. This means you can't use assignment statements or pass or other statements within a conditional expression

Walrus operator in Python 3.8

After that walrus operator was introduced in Python 3.8, there is something changed.

(a := 3) if True else (b := 5)

gives a = 3 and b is not defined,

(a := 3) if False else (b := 5)

gives a is not defined and b = 5, and

c = (a := 3) if False else (b := 5)

gives c = 5, a is not defined and b = 5.

Even if this may be ugly, assignments can be done inside conditional expressions after Python 3.8. Anyway, it is still better to use normal if statement instead in this case.

How many bits is a "word"?

On x86/x64 processors, a byte is 8 bits, and there are 256 possible binary states in 8 bits, 0 thru 255. This is how the OS translates your keyboard key strokes into letters on the screen. When you press the 'A' key, the keyboard sends a binary signal equal to the number 97 to the computer, and the computer prints a lowercase 'a' on the screen. You can confirm this in any Windows text editing software by holding an ALT key, typing 97 on the NUMPAD, then releasing the ALT key. If you replace '97' with any number from 0 to 255, you will see the character associated with that number on the system's character code page printed on the screen.

If a character is 8 bits, or 1 byte, then a WORD must be at least 2 characters, so 16 bits or 2 bytes. Traditionally, you might think of a word as a varying number of characters, but in a computer, everything that is calculable is based on static rules. Besides, a computer doesn't know what letters and symbols are, it only knows how to count numbers. So, in computer language, if a WORD is equal to 2 characters, then a double-word, or DWORD, is 2 WORDs, which is the same as 4 characters or bytes, which is equal to 32 bits. Furthermore, a quad-word, or QWORD, is 2 DWORDs, same as 4 WORDs, 8 characters, or 64 bits.

Note that these terms are limited in function to the Windows API for developers, but may appear in other circumstances (eg. the Linux dd command uses numerical suffixes to compound byte and block sizes, where c is 1 byte and w is bytes).

Inherit CSS class

CSS "classes" are not OOP "classes". The inheritance works the other way around.
A DOM element can have many classes, either directly or inherited or otherwise associated, which will all be applied in order, overriding earlier defined properties:

<div class="foo bar">
.foo {
    color: blue;
    width: 200px;
}

.bar {
    color: red;
}

The div will be 200px wide and have the color red.

You override properties of DOM elements with different classes, not properties of CSS classes. CSS "classes" are rulesets, the same way ids or tags can be used as rulesets.

Note that the order in which the classes are applied depends on the precedence and specificity of the selector, which is a complex enough topic in itself.

Create an array with random values

var myArray = [];
var arrayMax = 40;
var limit = arrayMax + 1;
for (var i = 0; i < arrayMax; i++) {
  myArray.push(Math.floor(Math.random()*limit));
}

This above is the traditional way of doing it but I second @Pointy and @Phrogz if you want to avoid duplicates in your array without having to do expensive computation

Test for array of string type in TypeScript

You can have do it easily using Array.prototype.some() as below.

const isStringArray = (test: any[]): boolean => {
 return Array.isArray(test) && !test.some((value) => typeof value !== 'string')
}
const myArray = ["A", "B", "C"]
console.log(isStringArray(myArray)) // will be log true if string array

I believe this approach is better that others. That is why I am posting this answer.

Update on Sebastian Vittersø's comment

Here you can use Array.prototype.every() as well.

const isStringArray = (test: any[]): boolean => {
 return Array.isArray(test) && test.every((value) => typeof value === 'string')
}

How to insert values in table with foreign key using MySQL?

Case 1: Insert Row and Query Foreign Key

Here is an alternate syntax I use:

INSERT INTO tab_student 
   SET name_student = 'Bobby Tables',
       id_teacher_fk = (
       SELECT id_teacher
         FROM tab_teacher
        WHERE name_teacher = 'Dr. Smith')

I'm doing this in Excel to import a pivot table to a dimension table and a fact table in SQL so you can import to both department and expenses tables from the following:

enter image description here

Case 2: Insert Row and Then Insert Dependant Row

Luckily, MySQL supports LAST_INSERT_ID() exactly for this purpose.

INSERT INTO tab_teacher
   SET name_teacher = 'Dr. Smith';
INSERT INTO tab_student 
   SET name_student = 'Bobby Tables',
       id_teacher_fk = LAST_INSERT_ID()

Apache shutdown unexpectedly

On your XAMPP control panel, next to apache, select the "Config" option and select the first file (httpd.conf):

there, look for the "listen" line (you may use the find tool in the notepad) and there must be a line stating "Listen 80". Note: there are other lines with "listen" on them but they should be commented (start with a #), the one you need to change is the one saying exactly "listen 80". Now change it to "Listen 1337".

Start apache now.

If the error subsists, it's because there's another port that's already in use. So, select the config option again (next to apache in your xampp control panel) and select the second option this time (httpd-ssl.conf):

there, look for the line "Listen 443" and change it to "Listen 7331".

Start apache, it should be working now.

Call asynchronous method in constructor?

The best solution is to acknowledge the asynchronous nature of the download and design for it.

In other words, decide what your application should look like while the data is downloading. Have the page constructor set up that view, and start the download. When the download completes update the page to display the data.

I have a blog post on asynchronous constructors that you may find useful. Also, some MSDN articles; one on asynchronous data-binding (if you're using MVVM) and another on asynchronous best practices (i.e., you should avoid async void).

Paste multiple columns together

library(plyr)

ldply(apply(data, 1, function(x) data.frame(
                      x = paste(x[2:4],sep="",collapse="-"))))

#      x
#1 a-d-g
#2 b-e-h
#3 c-f-i

#  and with just the vector of names you have:

ldply(apply(data, 1, function(x) data.frame(
                      x = paste(x[c('b','c','d')],sep="",collapse="-"))))

# or equally:
mynames <-c('b','c','d')
ldply(apply(data, 1, function(x) data.frame(
                      x = paste(x[mynames],sep="",collapse="-"))))    

Android add placeholder text to EditText

You have to use the android:hint attribute

<EditText
android:id="@+id/message"
android:hint="<<Your placeholder>>"
/>

In Android Studio, you can switch from XML -> Design View and click on the Component in the layout, the EditText field in this case. This will show all the applicable attributes for that GUI component. This will be handy when you don't know about all the attributes that are there.

You would be surprised to see that EditText has more than 140 attributes for customization.

SQL - Update multiple records in one query

INSERT INTO tablename
    (name, salary)
    VALUES 
        ('Bob', 1125),
        ('Jane', 1200),
        ('Frank', 1100),
        ('Susan', 1175),
        ('John', 1150)
        ON DUPLICATE KEY UPDATE salary = VALUES(salary);

How to get an object's methods?

the best way is:

let methods = Object.getOwnPropertyNames(yourobject);
console.log(methods)

use 'let' only in es6, use 'var' instead

Highlight Bash/shell code in Markdown files

Using the knitr package:

```{r, engine='bash', code_block_name} ...

E.g.:

```{r, engine='bash', count_lines}
wc -l en_US.twitter.txt
```

You can also use:

  • engine='sh' for shell
  • engine='python' for Python
  • engine='perl', engine='haskell' and a bunch of other C-like languages and even gawk, AWK, etc.

How do you remove an invalid remote branch reference from Git?

In my case I was trying to delete entries that were saved in .git/packed-refs. You can edit this plain text file and delete entries from it that git br -D doesn't know how to touch (At least in ver 1.7.9.5).

I found this solution here: https://stackoverflow.com/a/11050880/1695680

Calling Oracle stored procedure from C#?

This Code works well for me calling oracle stored procedure

Add references by right clicking on your project name in solution explorer >Add Reference >.Net then Add namespaces.

using System.Data.OracleClient;
using System.Data;

then paste this code in event Handler

        string str = "User ID=username;Password=password;Data Source=Test";
        OracleConnection conn = new OracleConnection(str);
        OracleCommand cmd = new OracleCommand("stored_procedure_name", conn);
        cmd.CommandType = CommandType.StoredProcedure;
        --Ad parameter list--
        cmd.Parameters.Add("parameter_name", "varchar2").Value = value;
        ....
        conn.Open();
        cmd.ExecuteNonQuery();

And its Done...Happy Coding with C#

How to disable the ability to select in a DataGridView?

Use the DataGridView.ReadOnly property

The code in the MSDN example illustrates the use of this property in a DataGridView control intended primarily for display. In this example, the visual appearance of the control is customized in several ways and the control is configured for limited interactivity.

Observe these settings in the sample code:

// Set property values appropriate for read-only
// display and limited interactivity
dataGridView1.AllowUserToAddRows = false;
dataGridView1.AllowUserToDeleteRows = false;
dataGridView1.AllowUserToOrderColumns = true;
dataGridView1.ReadOnly = true;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView1.MultiSelect = false;
dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
dataGridView1.AllowUserToResizeColumns = false;
dataGridView1.ColumnHeadersHeightSizeMode = 
DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
dataGridView1.AllowUserToResizeRows = false;
dataGridView1.RowHeadersWidthSizeMode = 
DataGridViewRowHeadersWidthSizeMode.DisableResizing;

Easiest way to toggle 2 classes in jQuery

If your element exposes class A from the start, you can write:

$(element).toggleClass("A B");

This will remove class A and add class B. If you do that again, it will remove class B and reinstate class A.

If you want to match the elements that expose either class, you can use a multiple class selector and write:

$(".A, .B").toggleClass("A B");

CMD: Export all the screen content to a text file

If you want to output ALL verbosity, not just stdout. But also any printf statements made by the program, any warnings, infos, etc, you have to add 2>&1 at the end of the command line.

In your case, the command will be

Program.exe > file.txt 2>&1

How do I create delegates in Objective-C?

Answer is actually answered, but I would like to give you a "cheat sheet" for creating a delegate:

DELEGATE SCRIPT

CLASS A - Where delegate is calling function

@protocol <#Protocol Name#> <NSObject>

-(void)delegateMethod;

@end

@interface <#Some ViewController#> : <#UIViewController#> 

@property (nonatomic, assign) id <<#Protocol Name#>> delegate;

@end


@implementation <#Some ViewController#> 

-(void)someMethod {
    [self.delegate methodName];
}

@end




CLASS B - Where delegate is called 

@interface <#Other ViewController#> (<#Delegate Name#>) {}
@end

@implementation <#Other ViewController#> 

-(void)otherMethod {
    CLASSA *classA = [[CLASSA alloc] init];

    [classA setDelegate:self];
}

-delegateMethod() {

}

@end

Assign output of a program to a variable using a MS batch file

I wrote the script that pings google.com every 5 seconds and logging results with current time. Here you can find output to variables "commandLineStr" (with indices)

@echo off

:LOOPSTART

echo %DATE:~0% %TIME:~0,8% >> Pingtest.log

SETLOCAL ENABLEDELAYEDEXPANSION
SET scriptCount=1
FOR /F "tokens=* USEBACKQ" %%F IN (`ping google.com -n 1`) DO (
  SET commandLineStr!scriptCount!=%%F
  SET /a scriptCount=!scriptCount!+1
)
@ECHO %commandLineStr1% >> PingTest.log
@ECHO %commandLineStr2% >> PingTest.log
ENDLOCAL

timeout 5 > nul

GOTO LOOPSTART

Getting started with OpenCV 2.4 and MinGW on Windows 7

As pointed out by @Nenad Bulatovic one has to be careful while adding libraries(19th step). one should not add any trailing spaces while adding each library line by line. otherwise mingw goes haywire.

Deploying my application at the root in Tomcat

In tomcat 7 with these changes, i'm able to access myAPP at / and ROOT at /ROOT

<Context path="" docBase="myAPP">
     <!-- Default set of monitored resources -->
     <WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>
<Context path="ROOT" docBase="ROOT">
     <!-- Default set of monitored resources -->
     <WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>

Add above to the <Host> section in server.xml

Why is Visual Studio 2013 very slow?

If you are debugging an ASP.NET website using Internet Explorer 10 (and later), make sure to turn off your Internet Explorer 'LastPass' password manager plugin. LastPass will bring your debugging sessions to a crawl and significantly reduce your capacity for patience!

I submitted a support ticket to Lastpass about this and they acknowledged the issue without any intention to fix it, merely saying: "LastPass is not compatible with Visual Studio 2013".

Django datetime issues (default=datetime.now())

David had the right answer. The parenthesis () makes it so that the callable timezone.now() is called every time the model is evaluated. If you remove the () from timezone.now() (or datetime.now(), if using the naive datetime object) to make it just this:

default=timezone.now

Then it will work as you expect:
New objects will receive the current date when they are created, but the date won't be overridden every time you do manage.py makemigrations/migrate.

I just encountered this. Much thanks to David.

Resize iframe height according to content height in it

To directly answer your two subquestions: No, you cannot do this with Ajax, nor can you calculate it with PHP.

What I have done in the past is use a trigger from the iframe'd page in window.onload (NOT domready, as it can take a while for images to load) to pass the page's body height to the parent.

<body onload='parent.resizeIframe(document.body.scrollHeight)'>

Then the parent.resizeIframe looks like this:

function resizeIframe(newHeight)
{
    document.getElementById('blogIframe').style.height = parseInt(newHeight,10) + 10 + 'px';
}

Et voila, you have a robust resizer that triggers once the page is fully rendered with no nasty contentdocument vs contentWindow fiddling :)

Sure, now people will see your iframe at default height first, but this can be easily handled by hiding your iframe at first and just showing a 'loading' image. Then, when the resizeIframe function kicks in, put two extra lines in there that will hide the loading image, and show the iframe for that faux Ajax look.

Of course, this only works from the same domain, so you may want to have a proxy PHP script to embed this stuff, and once you go there, you might as well just embed your blog's RSS feed directly into your site with PHP.

How to NodeJS require inside TypeScript file?

Typescript will always complain when it is unable to find a symbol. The compiler comes together with a set of default definitions for window, document and such specified in a file called lib.d.ts. If I do a grep for require in this file I can find no definition of a function require. Hence, we have to tell the compiler ourselves that this function will exist at runtime using the declare syntax:

declare function require(name:string);
var sampleModule = require('modulename');

On my system, this compiles just fine.

Moment.js: Date between dates

You can use one of the moment plugin -> moment-range to deal with date range:

var startDate = new Date(2013, 1, 12)
  , endDate   = new Date(2013, 1, 15)
  , date  = new Date(2013, 2, 15)
  , range = moment().range(startDate, endDate);

range.contains(date); // false

Nested routes with react router v4 / v5

react-router v6

Update for 2021

The upcoming v6 will have nested Route components that Just Work™

See example code in this blog post

The question is about v4/v5, but when v6 ships the correct answer will be just use that if you can.


react-router v4 & v5

It's true that in order to nest Routes you need to place them in the child component of the Route.

However if you prefer a more inline syntax rather than breaking your Routes up across components, you can provide a functional component to the render prop of the Route you want to nest under.

<BrowserRouter>

  <Route path="/" component={Frontpage} exact />
  <Route path="/home" component={HomePage} />
  <Route path="/about" component={AboutPage} />

  <Route
    path="/admin"
    render={({ match: { url } }) => (
      <>
        <Route path={`${url}/`} component={Backend} exact />
        <Route path={`${url}/home`} component={Dashboard} />
        <Route path={`${url}/users`} component={UserPage} />
      </>
    )}
  />

</BrowserRouter>

If you're interested in why the render prop should be used, and not the component prop, it's because it stops the inline functional component from being remounted on every render. See the documentation for more detail.

Note that the example wraps the nested Routes in a Fragment. Prior to React 16, you can use a container <div> instead.

How can I detect the touch event of an UIImageView?

A UIImageView is derived from a UIView which is derived from UIResponder so it's ready to handle touch events. You'll want to provide the touchesBegan, touchesMoved, and touchesEnded methods and they'll get called if the user taps the image. If all you want is a tap event, it's easier to just use a custom button with the image set as the button image. But if you want finer-grain control over taps, moves, etc. this is the way to go.

You'll also want to look at a few more things:

  • Override canBecomeFirstResponder and return YES to indicate that the view can become the focus of touch events (the default is NO).

  • Set the userInteractionEnabled property to YES. The default for UIViews is YES, but for UIImageViews is NO so you have to explicitly turn it on.

  • If you want to respond to multi-touch events (i.e. pinch, zoom, etc) you'll want to set multipleTouchEnabled to YES.

SQL GROUP BY CASE statement with aggregate function

I think the answer is pretty simple (unless I'm missing something?)

SELECT    
CASE
    WHEN col1 > col2 THEN SUM(col3*col4)
    ELSE 0
END AS some_product
FROM some_table
GROUP BY
CASE
    WHEN col1 > col2 THEN SUM(col3*col4)
    ELSE 0
END

You can put the CASE STATEMENT in the GROUP BY verbatim (minus the alias column name)

Decompile an APK, modify it and then recompile it

  1. First download the dex2jar tool from Following link http://code.google.com/p/dex2jar/downloads/list

  2. Extract the file it create dex2jar folder

  3. Now you pick your apk file and change its extension .apk to .zip after changing extension it seems to be zip file then extract this zip file you found classes.dex file

  4. Now pick classes.dex file and put it into dex2jar folder

  5. Now open cmd window and type the path of dex2jar folder

  6. Now type the command dex2jar.bat classes.dex and press Enter

  7. Now Open the dex2jar folder you found classes_dex2jar.jar file

  8. Next you download the java decompiler tool from the following link http://java.decompiler.free.fr/?q=jdgui

  9. Last Step Open the file classes_dex2jar.jar in java decompiler tool now you can see apk code

Mysql: Select all data between two dates

You can use as an alternate solution:

SELECT * FROM TABLE_NAME WHERE `date` >= '1-jan-2013' 
OR `date` <= '12-jan-2013'

jQuery: how to change title of document during .ready()?

I am using some nested layouts in Ruby on Rails, and in one of the layouts i have a need to read in a string from a div and set that as the title of the document.

The correct way to do this is on the server side.

In your layout, there at some point will be some code which puts the text in the div. Make this code also set some instance variable such as @page_title, and then in your outer layout have it do <%= @page_title || 'Default Title' %>

Finding median of list in Python

I defined a median function for a list of numbers as

def median(numbers):
    return (sorted(numbers)[int(round((len(numbers) - 1) / 2.0))] + sorted(numbers)[int(round((len(numbers) - 1) // 2.0))]) / 2.0

How to install plugin for Eclipse from .zip

To install the plug-in, unzip the file into the Eclipse installation directory (or the plug-in directory depending on how the plug-in is packaged). The plug-in will not appear until you have restarted your workspace (Reboot Eclipse).

Adding additional data to select options using jQuery

HTML Markup

<select id="select">
  <option value="1" data-foo="dogs">this</option>
  <option value="2" data-foo="cats">that</option>
  <option value="3" data-foo="gerbils">other</option>
</select>

Code

// JavaScript using jQuery
$(function(){
    $('select').change(function(){
       var selected = $(this).find('option:selected');
       var extra = selected.data('foo'); 
       ...
    });
});

// Plain old JavaScript
var sel = document.getElementById('select');
var selected = sel.options[sel.selectedIndex];
var extra = selected.getAttribute('data-foo');

See this as a working sample using jQuery here: http://jsfiddle.net/GsdCj/1/
See this as a working sample using plain JavaScript here: http://jsfiddle.net/GsdCj/2/

By using data attributes from HTML5 you can add extra data to elements in a syntactically-valid manner that is also easily accessible from jQuery.

Adding an onclick function to go to url in JavaScript?

In jquery to send a user to a different URL you can do it like this:

$("a#thing_to_click").on('click', function(){
     window.location = "http://www.google.com/";    
});

this way will work too but the above is the newer more correct way to do it these days

$("a#thing_to_click").click(function(e){
         e.preventDefault();
         window.location = "http://www.google.com/";    
});

Scroll RecyclerView to show selected item on top

What i may add here is how to make it work together with DiffUtil and ListAdapter

You may note that calling recyclerView.scrollToPosition(pos) or (recyclerView.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(pos, offset) wouldn't work if called straight after adapter.submitList. It is because the differ looks for changes in a background thread and then asynchronously notifies adapter about changes. On a SO i have seen several wrong answers with unnecessary delays & etc to solve this.

To handle the situation properly the submitList has a callback which is invoked when changes have applied.

So the proper kotlin implementations in this case are:

//memorise target item here and a scroll offset if needed
adapter.submitList(items) { 
    val pos = /* here you may find a new position of the item or just use just a static position. It depends on your case */
    recyclerView.scrollToPosition(pos) 
}
//or
adapter.submitList(items) { recyclerView.smoothScrollToPosition(pos) }
//or etc
adapter.submitList(items) { (recyclerView.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(pos, offset) }

Sql Server trigger insert values from new row into another table

You can use OLDand NEW in the trigger to access those values which had changed in that trigger. Mysql Ref

Linux - Install redis-cli only

you may scp it from your redis machine if you have one, its just single binary. Or copy with nc if private network (this method is insecure):

redisclient: nc -l 8888 > /usr/local/bin/redis-cli
redisserver: cat /usr/local/bin/redis-cli | nc redisclient 8888

Is there a unique Android device ID?

Not recommended as deviceId can be used as tracking in 3rd party hands, but this is another way.

@SuppressLint("HardwareIds")
private String getDeviceID() {
    deviceId = Settings.Secure.getString(getApplicationContext().getContentResolver(),
                    Settings.Secure.ANDROID_ID);
    return deviceId;
}

Python Traceback (most recent call last)

You are using Python 2 for which the input() function tries to evaluate the expression entered. Because you enter a string, Python treats it as a name and tries to evaluate it. If there is no variable defined with that name you will get a NameError exception.

To fix the problem, in Python 2, you can use raw_input(). This returns the string entered by the user and does not attempt to evaluate it.

Note that if you were using Python 3, input() behaves the same as raw_input() does in Python 2.

Laravel 5.1 - Checking a Database Connection

You can also run this:

php artisan migrate:status

It makes a db connection connection to get migrations from migrations table. It'll throw an exception if the connection fails.

How can I read the client's machine/computer name from the browser?

No this data is not exposed. The only data that is available is what is exposed through the HTTP request which might include their OS and other such information. But certainly not machine name.

How to use type: "POST" in jsonp ajax call

If you just want to do a form POST to your own site using $.ajax() (for example, to emulate an AJAX experience), then you can use the jQuery Form Plugin. However, if you need to do a form POST to a different domain, or to your own domain but using a different protocol (a non-secure http: page posting to a secure https: page), then you'll come upon cross-domain scripting restrictions that you won't be able to resolve with jQuery alone (more info). In such cases, you'll need to bring out the big guns: YQL. Put plainly, YQL is a web scraping language with a SQL-like syntax that allows you to query the entire internet as one large table. As it stands now, in my humble opinion YQL is the only [easy] way to go if you want to do cross-domain form POSTing using client-side JavaScript.

More specifically, you'll need to use YQL's Open Data Table containing an Execute block to make this happen. For a good summary on how to do this, you can read the article "Scraping HTML documents that require POST data with YQL". Luckily for us, YQL guru Christian Heilmann has already created an Open Data Table that handles POST data. You can play around with Christian's "htmlpost" table on the YQL Console. Here's a breakdown of the YQL syntax:

  • select * - select all columns, similar to SQL, but in this case the columns are XML elements or JSON objects returned by the query. In the context of scraping web pages, these "columns" generally correspond to HTML elements, so if want to retrieve only the page title, then you would use select head.title.
  • from htmlpost - what table to query; in this case, use the "htmlpost" Open Data Table (you can use your own custom table if this one doesn't suit your needs).
  • url="..." - the form's action URI.
  • postdata="..." - the serialized form data.
  • xpath="..." - the XPath of the nodes you want to include in the response. This acts as the filtering mechanism, so if you want to include only <p> tags then you would use xpath="//p"; to include everything you would use xpath="//*".

Click 'Test' to execute the YQL query. Once you are happy with the results, be sure to (1) click 'JSON' to set the response format to JSON, and (2) uncheck "Diagnostics" to minimize the size of the JSON payload by removing extraneous diagnostics information. The most important bit is the URL at the bottom of the page -- this is the URL you would use in a $.ajax() statement.

Here, I'm going to show you the exact steps to do a cross-domain form POST via a YQL query using this sample form:

<form id="form-post" action="https://www.example.com/add/member" method="post">
  <input type="text" name="firstname">
  <input type="text" name="lastname">
  <button type="button" onclick="doSubmit()">Add Member</button>
</form>

Your JavaScript would look like this:

function doSubmit() {
  $.ajax({
    url: '//query.yahooapis.com/v1/public/yql?q=select%20*%20from%20htmlpost%20where%0Aurl%3D%22' +
         encodeURIComponent($('#form-post').attr('action')) + '%22%20%0Aand%20postdata%3D%22' +
         encodeURIComponent($('#form-post').serialize()) +
         '%22%20and%20xpath%3D%22%2F%2F*%22&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=',
    dataType: 'json', /* Optional - jQuery autodetects this by default */
    success: function(response) {
      console.log(response);
    }
  });
}

The url string is the query URL copied from the YQL Console, except with the form's encoded action URI and serialized input data dynamically inserted.

NOTE: Please be aware of security implications when passing sensitive information over the internet. Ensure the page you are submitting sensitive information from is secure (https:) and using TLS 1.x instead of SSL 3.0.

String comparison in Python: is vs. ==

The logic is not flawed. The statement

if x is y then x==y is also True

should never be read to mean

if x==y then x is y

It is a logical error on the part of the reader to assume that the converse of a logic statement is true. See http://en.wikipedia.org/wiki/Converse_(logic)

Function pointer to member function

While this is based on the sterling answers elsewhere on this page, I had a use case which wasn't completely solved by them; for a vector of pointers to functions do the following:

#include <iostream>
#include <vector>
#include <stdio.h>
#include <stdlib.h>

class A{
public:
  typedef vector<int> (A::*AFunc)(int I1,int I2);
  vector<AFunc> FuncList;
  inline int Subtract(int I1,int I2){return I1-I2;};
  inline int Add(int I1,int I2){return I1+I2;};
  ...
  void Populate();
  void ExecuteAll();
};

void A::Populate(){
    FuncList.push_back(&A::Subtract);
    FuncList.push_back(&A::Add);
    ...
}

void A::ExecuteAll(){
  int In1=1,In2=2,Out=0;
  for(size_t FuncId=0;FuncId<FuncList.size();FuncId++){
    Out=(this->*FuncList[FuncId])(In1,In2);
    printf("Function %ld output %d\n",FuncId,Out);
  }
}

int main(){
  A Demo;
  Demo.Populate();
  Demo.ExecuteAll();
  return 0;
}

Something like this is useful if you are writing a command interpreter with indexed functions that need to be married up with parameter syntax and help tips etc. Possibly also useful in menus.

Open directory using C

Parameters passed to the C program executable is nothing but an array of string(or character pointer),so memory would have been already allocated for these input parameter before your program access these parameters,so no need to allocate buffer,and that way you can avoid error handling code in your program as well(Reduce chances of segfault :)).

datetime datatype in java

Since Java 8, it seems like the java.time standard library is the way to go. From Joda time web page:

Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.


Back to your question. Were you to use Java 8, I think you want LocalDateTime. Because it contains the date and time-of-the-day, but is unaware of time zone or any reference point in time such as the unix epoch.

How to make a TextBox accept only alphabetic characters?

Write Code in Text_KeyPress Event as

 private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {

        if (!char.IsLetter(e.KeyChar))
        {
            e.Handled = true;
        }
    }

Test a weekly cron job

None of these answers fit my specific situation, which was that I wanted to run one specific cron job, just once, and run it immediately.

I'm on a Ubuntu server, and I use cPanel to setup my cron jobs.

I simply wrote down my current settings, and then edited them to be one minute from now. When I fixed another bug, I just edited it again to one minute from now. And when I was all done, I just reset the settings back to how they were before.

Example: It's 4:34pm right now, so I put 35 16 * * *, for it to run at 16:35.

It worked like a charm, and the most I ever had to wait was a little less than one minute.

I thought this was a better option than some of the other answers because I didn't want to run all of my weekly crons, and I didn't want the job to run every minute. It takes me a few minutes to fix whatever the issues were before I'm ready to test it again. Hopefully this helps someone.

passing 2 $index values within nested ng-repeat

Just use ng-repeat="(sectionIndex, section) in sections"

and that will be useable on the next level ng-repeat down.

<ul ng-repeat="(sectionIndex, section) in sections">
    <li  class="section_title {{section.active}}" >
        {{section.name}}
    </li>
    <ul>
        <li ng-repeat="tutorial in section.tutorials">
            {{tutorial.name}}, Your section index is {{sectionIndex}}
        </li>
    </ul>
</ul>

Image steganography that could survive jpeg compression

Quite a few applications seem to implement Steganography on JPEG, so it's feasible:

http://www.jjtc.com/Steganography/toolmatrix.htm

Here's an article regarding a relevant algorithm (PM1) to get you started:

http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1

How do you change text to bold in Android?

From the XML you can set the textStyle to bold as below

<TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Bold text"
   android:textStyle="bold"/>

You can set the TextView to bold programmatically as below

textview.setTypeface(Typeface.DEFAULT_BOLD);

Tooltip with HTML content without JavaScript

Pure CSS:

_x000D_
_x000D_
.app-tooltip {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.app-tooltip:before {_x000D_
  content: attr(data-title);_x000D_
  background-color: rgba(97, 97, 97, 0.9);_x000D_
  color: #fff;_x000D_
  font-size: 12px;_x000D_
  padding: 10px;_x000D_
  position: absolute;_x000D_
  bottom: -50px;_x000D_
  opacity: 0;_x000D_
  transition: all 0.4s ease;_x000D_
  font-weight: 500;_x000D_
  z-index: 2;_x000D_
}_x000D_
_x000D_
.app-tooltip:after {_x000D_
  content: '';_x000D_
  position: absolute;_x000D_
  opacity: 0;_x000D_
  left: 5px;_x000D_
  bottom: -16px;_x000D_
  border-style: solid;_x000D_
  border-width: 0 10px 10px 10px;_x000D_
  border-color: transparent transparent rgba(97, 97, 97, 0.9) transparent;_x000D_
  transition: all 0.4s ease;_x000D_
}_x000D_
_x000D_
.app-tooltip:hover:after,_x000D_
.app-tooltip:hover:before {_x000D_
  opacity: 1;_x000D_
}
_x000D_
<div href="#" class="app-tooltip" data-title="Your message here"> Test here</div>
_x000D_
_x000D_
_x000D_

git rebase merge conflict

When you have a conflict during rebase you have three options:

  • You can run git rebase --abort to completely undo the rebase. Git will return you to your branch's state as it was before git rebase was called.

  • You can run git rebase --skip to completely skip the commit. That means that none of the changes introduced by the problematic commit will be included. It is very rare that you would choose this option.

  • You can fix the conflict as iltempo said. When you're finished, you'll need to call git rebase --continue. My mergetool is kdiff3 but there are many more which you can use to solve conflicts. You only need to set your merge tool in git's settings so it can be invoked when you call git mergetool https://git-scm.com/docs/git-mergetool

If none of the above works for you, then go for a walk and try again :)

How would you do a "not in" query with LINQ?

 DynamicWebsiteEntities db = new DynamicWebsiteEntities();
    var data = (from dt_sub in db.Subjects_Details
                                //Sub Query - 1
                            let sub_s_g = (from sg in db.Subjects_In_Group
                                           where sg.GroupId == groupId
                                           select sg.SubjectId)
                            //Where Cause
                            where !sub_s_g.Contains(dt_sub.Id) && dt_sub.IsLanguage == false
                            //Order By Cause
                            orderby dt_sub.Subject_Name

                            select dt_sub)
                           .AsEnumerable();
                  
                                SelectList multiSelect = new SelectList(data, "Id", "Subject_Name", selectedValue);

    //======================================OR===========================================

    var data = (from dt_sub in db.Subjects_Details

                               
                            //Where Cause
                            where !(from sg in db.Subjects_In_Group
                                           where sg.GroupId == groupId
                                           select sg.SubjectId).Contains(dt_sub.Id) && dt_sub.IsLanguage == false

                            //Order By Cause
                            orderby dt_sub.Subject_Name

                            select dt_sub)

                           .AsEnumerable();

How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure?

The linked list holds operations on the shared data structure.

For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).

In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.

In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.

Setting action for back button in navigation controller

Found a solution which retains the back button style as well. Add the following method to your view controller.

-(void) overrideBack{

    UIButton *transparentButton = [[UIButton alloc] init];
    [transparentButton setFrame:CGRectMake(0,0, 50, 40)];
    [transparentButton setBackgroundColor:[UIColor clearColor]];
    [transparentButton addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:transparentButton];


}

Now provide a functionality as needed in the following method:

-(void)backAction:(UIBarButtonItem *)sender {
    //Your functionality
}

All it does is to cover the back button with a transparent button ;)

Unstaged changes left after git reset --hard

If other answers are not working, trying adding the files, then resetting

$ git add -A
$ git reset --hard

In my case, this helped when there were a bunch of empty files that git was tracking.

Generate random numbers uniformly over an entire range

This should provide a uniform distribution over the range [low, high) without using floats, as long as the overall range is less than RAND_MAX.

uint32_t rand_range_low(uint32_t low, uint32_t high)
{
    uint32_t val;
    // only for 0 < range <= RAND_MAX
    assert(low < high);
    assert(high - low <= RAND_MAX);

    uint32_t range = high-low;
    uint32_t scale = RAND_MAX/range;
    do {
        val = rand();
    } while (val >= scale * range); // since scale is truncated, pick a new val until it's lower than scale*range
    return val/scale + low;
}

and for values greater than RAND_MAX you want something like

uint32_t rand_range(uint32_t low, uint32_t high)
{
    assert(high>low);
    uint32_t val;
    uint32_t range = high-low;
    if (range < RAND_MAX)
        return rand_range_low(low, high);
    uint32_t scale = range/RAND_MAX;
    do {
        val = rand() + rand_range(0, scale) * RAND_MAX; // scale the initial range in RAND_MAX steps, then add an offset to get a uniform interval
    } while (val >= range);
    return val + low;
}

This is roughly how std::uniform_int_distribution does things.

How can I connect to a Tor hidden service using cURL in PHP?

You need to set option CURLOPT_PROXYTYPE to CURLPROXY_SOCKS5_HOSTNAME, which sadly wasn't defined in old PHP versions, circa pre-5.6; if you have earlier in but you can explicitly use its value, which is equal to 7:

curl_setopt($ch, CURLOPT_PROXYTYPE, 7);

Darken background image on hover

I would add a div around the image and make the image change in opacity on hover and add an inset box shadow to the div on hover.

img:hover{
    opacity:.5;
}
.image:hover{
    box-shadow: inset 10px 10px 100px 100px #000;
}

<div class="image"><img src="image.jpg" /></div>

Allow only numeric value in textbox using Javascript

Javascript For only numeric value in textbox ::

<input type="text" id="textBox" runat="server" class="form-control" onkeydown="return onlyNos(event)" tabindex="0" /> 


    <!--Only Numeric value in Textbox Script -->
        <script type="text/javascript">
            function onlyNos(e, t) {
                try {
                    if (window.event) {
                        var charCode = window.event.keyCode;
                    }
                    else if (e) {
                        var charCode = e.which;
                    }
                    else { return true; }
                    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
                        return false;
                    }
                    return true;
                }
                catch (err) {
                    alert(err.Description);
                }
            }
        </script>
        <!--Only Numeric value in Textbox Script -->

MongoDB query with an 'or' condition

Query objects in Mongo by default AND expressions together. Mongo currently does not include an OR operator for such queries, however there are ways to express such queries.

Use "in" or "where".

Its gonna be something like this:

db.mycollection.find( { $where : function() { 
return ( this.startTime < Now() && this.expireTime > Now() || this.expireTime == null ); } } );

How to align absolutely positioned element to center?

try this method, working fine for me

position: absolute;
left: 50%;
transform: translateX(-50%); 

How do I upgrade PHP in Mac OS X?

Use this Command:

curl -s http://php-osx.liip.ch/install.sh | bash -s 7.0

Finding Variable Type in JavaScript

In JavaScript everything is an object

console.log(type of({}))  //Object
console.log(type of([]))  //Object

To get Real type , use this

console.log(Object.prototype.toString.call({}))   //[object Object]
console.log(Object.prototype.toString.call([]))   //[object Array]

Hope this helps

twitter bootstrap 3.0 typeahead ajax example

Here is my step by step experience, inspired by typeahead examples, from a Scala/PlayFramework app we are working on.

In a script LearnerNameTypeAhead.coffee (convertible of course to JS) I have:

$ ->
  learners = new Bloodhound(
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace("value")
    queryTokenizer: Bloodhound.tokenizers.whitespace
    remote: "/learner/namelike?nameLikeStr=%QUERY"
  )
  learners.initialize()
  $("#firstName").typeahead 
    minLength: 3
    hint: true
    highlight:true
   ,
    name: "learners"
    displayKey: "value"
    source: learners.ttAdapter()

I included the typeahead bundle and my script on the page, and there is a div around my input field as follows:

<script [email protected]("javascripts/typeahead.bundle.js")></script>
<script [email protected]("javascripts/LearnerNameTypeAhead.js") type="text/javascript" ></script>
<div>
  <input name="firstName" id="firstName" class="typeahead" placeholder="First Name" value="@firstName">
</div>

The result is that for each character typed in the input field after the first minLength (3) characters, the page issues a GET request with a URL looking like /learner/namelike?nameLikeStr= plus the currently typed characters. The server code returns a json array of objects containing fields "id" and "value", for example like this:

[ {
    "id": "109",
    "value": "Graham Jones"
  },
  {
    "id": "5833",
    "value": "Hezekiah Jones"
} ]

For play I need something in the routes file:

GET /learner/namelike controllers.Learners.namesLike(nameLikeStr:String)

And finally, I set some of the styling for the dropdown, etc. in a new typeahead.css file which I included in the page's <head> (or accessible .css)

.tt-dropdown-menu {
  width: 252px;
  margin-top: 12px;
  padding: 8px 0;
  background-color: #fff;
  border: 1px solid #ccc;
  border: 1px solid rgba(0, 0, 0, 0.2);
  -webkit-border-radius: 8px;
     -moz-border-radius: 8px;
          border-radius: 8px;
  -webkit-box-shadow: 0 5px 10px rgba(0,0,0,.2);
     -moz-box-shadow: 0 5px 10px rgba(0,0,0,.2);
          box-shadow: 0 5px 10px rgba(0,0,0,.2);
}
.typeahead {
  background-color: #fff;
}
.typeahead:focus {
  border: 2px solid #0097cf;
}
.tt-query {
  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
     -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
}
.tt-hint {
  color: #999
}
.tt-suggestion {
  padding: 3px 20px;
  font-size: 18px;
  line-height: 24px;
}
.tt-suggestion.tt-cursor {
  color: #fff;
  background-color: #0097cf;
}
.tt-suggestion p {
  margin: 0;
}

Forms authentication timeout vs sessionState timeout

The slidingExpiration=true value is basically saying that after every request made, the timer is reset and as long as the user makes a request within the timeout value, he will continue to be authenticated.

This is not correct. The authentication cookie timeout will only be reset if half the time of the timeout has passed.

See for example https://support.microsoft.com/de-ch/kb/910439/en-us or https://itworksonmymachine.wordpress.com/2008/07/17/forms-authentication-timeout-vs-session-timeout/

Set cellpadding and cellspacing in CSS?

Basics

For controlling "cellpadding" in CSS, you can simply use padding on table cells. E.g. for 10px of "cellpadding":

td { 
    padding: 10px;
}

For "cellspacing", you can apply the border-spacing CSS property to your table. E.g. for 10px of "cellspacing":

table { 
    border-spacing: 10px;
    border-collapse: separate;
}

This property will even allow separate horizontal and vertical spacing, something you couldn't do with old-school "cellspacing".

Issues in IE = 7

This will work in almost all popular browsers except for Internet Explorer up through Internet Explorer 7, where you're almost out of luck. I say "almost" because these browsers still support the border-collapse property, which merges the borders of adjoining table cells. If you're trying to eliminate cellspacing (that is, cellspacing="0") then border-collapse:collapse should have the same effect: no space between table cells. This support is buggy, though, as it does not override an existing cellspacing HTML attribute on the table element.

In short: for non-Internet Explorer 5-7 browsers, border-spacing handles you. For Internet Explorer, if your situation is just right (you want 0 cellspacing and your table doesn't have it defined already), you can use border-collapse:collapse.

table { 
    border-spacing: 0;
    border-collapse: collapse;
}

Note: For a great overview of CSS properties that one can apply to tables and for which browsers, see this fantastic Quirksmode page.

How can I parse a JSON file with PHP?

Loop through the JSON with a foreach loop as key-value pairs. Do type-checking to determine if more looping needs to be done.

foreach($json_a as $key => $value) {
    echo $key;
    if (gettype($value) == "object") {
        foreach ($value as $key => $value) {
          # and so on
        }
    }
}

Chart.js v2 - hiding grid lines

OK, nevermind.. I found the trick:

    scales: {
      yAxes: [
        {
          gridLines: {
                lineWidth: 0
            }
        }
      ]
    }

How to find Oracle Service Name

With SQL Developer you should also find it without writing any query. Right click on your Connection/Propriety.

You should see the name on the left under something like "connection details" and should look like "Connectionname@servicename", or on the right, under the connection's details.

What to do on TransactionTooLargeException

This one line of code in writeToParcel(Parcel dest, int flags) method helped me to get rid of TransactionTooLargeException.

dest=Parcel.obtain(); 

After this code only i am writing all data to the parcel object i.e dest.writeInt() etc.

How do I conditionally apply CSS styles in AngularJS?

As of AngularJS v1.2.0rc, ng-class and even ng-attr-class fail with SVG elements (They did work earlier, even with normal binding inside the class attribute)

Specifically, none of these work now:

ng-class="current==this_element?'active':' ' "
ng-attr-class="{{current==this_element?'active':' '}}"
class="class1 class2 .... {{current==this_element?'active':''}}"

As a workaround, I've to use

ng-attr-otherAttr="{{current==this_element?'active':''}}"

and then style using

[otherAttr='active'] {
   ... styles ...
}

DateTime "null" value

You can set the DateTime to Nullable. By default DateTime is not nullable. You can make it nullable in a couple of ways. Using a question mark after the type DateTime? myTime or using the generic style Nullable.

DateTime? nullDate = null;

or

DateTime? nullDate;

Using Python, find anagrams for a list of words

Most of previous answers are correct, here is another way to compare two strings. The main benefit of using this strategy versus sort is space/time complexity which is n log of n.

1.Check the length of string

2.Build frequency Dictionary and compare if they both match then we have successfully identified anagram words

def char_frequency(word):
    frequency  = {}
    for char in word:
        #if character  is in frequency then increment the value
        if char in frequency:
            frequency[char] += 1
        #else add character and set it to 1
        else:
            frequency[char] = 1
    return frequency 


a_word ='google'
b_word ='ooggle'
#check length of the words 
if (len(a_word) != len(b_word)):
   print ("not anagram")
else:
    #here we check the frequecy to see if we get the same
    if ( char_frequency(a_word) == char_frequency(b_word)):
        print("found anagram")
    else:
        print("no anagram")

PHP: How do you determine every Nth iteration of a loop?

Use the modulo arithmetic operation found here in the PHP manual.

e.g.

$x = 3;

for($i=0; $i<10; $i++)
{
    if($i % $x == 0)
    {
        // display image
    }
}

For a more detailed understanding of modulus calculations, click here.

Where's my JSON data in my incoming Django request?

Its important to remember Python 3 has a different way to represent strings - they are byte arrays.

Using Django 1.9 and Python 2.7 and sending the JSON data in the main body (not a header) you would use something like:

mydata = json.loads(request.body)

But for Django 1.9 and Python 3.4 you would use:

mydata = json.loads(request.body.decode("utf-8"))

I just went through this learning curve making my first Py3 Django app!

Difference between -XX:+UseParallelGC and -XX:+UseParNewGC

UseParNewGC usually knowns as "parallel young generation collector" is same in all ways as the parallel garbage collector (-XX:+UseParallelGC), except that its more sophiscated and effiecient. Also it can be used with a "concurrent low pause collector".

See Java GC FAQ, question 22 for more information.

Note that there are some known bugs with UseParNewGC

Disabling of EditText in Android

if you use android:editable="false", eclipse will remind you this message "android:editable is deprecated: Use inputType instead".

So, I use android:focusable="false" instead, it worked well for me.

How can I convert a string to upper- or lower-case with XSLT?

upper-case(string) and lower-case(string)

How to access form methods and controls from a class in C#?

You need to make the members in the for the form class either public or, if the service class is in the same assembly, internal. Windows controls' visibility can be controlled through their Modifiers properties.

Note that it's generally considered a bad practice to explicitly tie a service class to a UI class. Rather you should create good interfaces between the service class and the form class. That said, for learning or just generally messing around, the earth won't spin off its axis if you expose form members for service classes.

rp

Error: Configuration with name 'default' not found in Android Studio

Removing few react-native dependencies solved the problem

Deleting these lines the problem is resolved. This line is created by rnpm link but is a bug.

compile project(':react-native-gps')
compile project(':react-native-maps')

javascript Unable to get property 'value' of undefined or null reference

You can't access element like you did (document.frm_new_user_request). You have to use the function getElementById:

document.getElementById("frm_new_user_request")

So getting a value from an input could look like this:

var value = document.getElementById("frm_new_user_request").value

Also you can use some JavaScript framework, e.g. jQuery, which simplifies operations with DOM (Document Object Model) and also hides differences between various browsers from you.

Getting a value from an input using jQuery would look like this:

  • input with ID "element": var value = $("#element).value
  • input with class "element": var value = $(".element).value

I have filtered my Excel data and now I want to number the rows. How do I do that?

I had the same need to fill up a column with a sequence series for each value on another column. I tried all the answers above and could not fix the problem. I solved it with a simple VBA macro.

My data have the same structure (but with 3000 rows):

  • N2 is the column on which the table is filtered;
  • N3 is the column where I wanted to fill a series;

A | B

N2 | N3

1 | 1

2 | 1

3 | 1

1 | 2

6 | 1

4 | 1

2 | 2

1 | 3

5 | 1

Here below the code:

> Sub Seq_N3() ' ' Seq_N3 Macro ' Sequence numbering of N3 based on N2 value
> do N2 
>     Dim N2 As Integer
>     Dim seq As Integer
> 
>         With ActiveSheet
>             
>             For N2 = 1 To 7 Step 1
>             seq = 1                 ' 
>             .Range("B2").Select     ' 
>             
>                 Do While ActiveCell.Offset(0, -1).Value2 <> 0
>                     
>                     If ActiveCell.Offset(0, -1).Value2 = N2 Then        
>                         ActiveCell.Value2 = seq                         
>                         seq = seq + 1                                   
>                         ActiveCell.Offset(1, 0).Select
>                     Else
>                         ActiveCell.Offset(1, 0).Select                  
>                     End If
>                     
>                 Loop
>                 
>             Next N2
>                    
>         End With End Sub

Hope it helps!

HTML select drop-down with an input field

You can use input text with "list" attribute, which refers to the datalist of values.

_x000D_
_x000D_
<input type="text" name="city" list="cityname">_x000D_
    <datalist id="cityname">_x000D_
      <option value="Boston">_x000D_
      <option value="Cambridge">_x000D_
    </datalist>
_x000D_
_x000D_
_x000D_

This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist

Echo a blank (empty) line to the console from a Windows batch file

There is often the tip to use 'echo.'

But that is slow, and it could fail with an error message, as cmd.exe will search first for a file named 'echo' (without extension) and only when the file doesn't exists it outputs an empty line.

You could use echo(. This is approximately 20 times faster, and it works always. The only drawback could be that it looks odd.

More about the different ECHO:/\ variants is at DOS tips: ECHO. FAILS to give text or blank line.

Websocket onerror - how to read error description?

Alongside nmaier's answer, as he said you'll always receive code 1006. However, if you were to somehow theoretically receive other codes, here is code to display the results (via RFC6455).

you will almost never get these codes in practice so this code is pretty much pointless

var websocket;
if ("WebSocket" in window)
{
    websocket = new WebSocket("ws://yourDomainNameHere.org/");

    websocket.onopen = function (event) {
        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was opened");
    };
    websocket.onclose = function (event) {
        var reason;
        alert(event.code);
        // See http://tools.ietf.org/html/rfc6455#section-7.4.1
        if (event.code == 1000)
            reason = "Normal closure, meaning that the purpose for which the connection was established has been fulfilled.";
        else if(event.code == 1001)
            reason = "An endpoint is \"going away\", such as a server going down or a browser having navigated away from a page.";
        else if(event.code == 1002)
            reason = "An endpoint is terminating the connection due to a protocol error";
        else if(event.code == 1003)
            reason = "An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message).";
        else if(event.code == 1004)
            reason = "Reserved. The specific meaning might be defined in the future.";
        else if(event.code == 1005)
            reason = "No status code was actually present.";
        else if(event.code == 1006)
           reason = "The connection was closed abnormally, e.g., without sending or receiving a Close control frame";
        else if(event.code == 1007)
            reason = "An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629] data within a text message).";
        else if(event.code == 1008)
            reason = "An endpoint is terminating the connection because it has received a message that \"violates its policy\". This reason is given either if there is no other sutible reason, or if there is a need to hide specific details about the policy.";
        else if(event.code == 1009)
           reason = "An endpoint is terminating the connection because it has received a message that is too big for it to process.";
        else if(event.code == 1010) // Note that this status code is not used by the server, because it can fail the WebSocket handshake instead.
            reason = "An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake. <br /> Specifically, the extensions that are needed are: " + event.reason;
        else if(event.code == 1011)
            reason = "A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.";
        else if(event.code == 1015)
            reason = "The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).";
        else
            reason = "Unknown reason";

        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was closed for reason: " + reason);
    };
    websocket.onmessage = function (event) {
        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "New message arrived: " + event.data);
    };
    websocket.onerror = function (event) {
        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "There was an error with your websocket.");
    };
}
else
{
    alert("Websocket is not supported by your browser");
    return;
}

websocket.send("Yo wazzup");

websocket.close();

See http://jsfiddle.net/gr0bhrqr/

Why do we have to override the equals() method in Java?

From the article Override equals and hashCode in Java:

Default implementation of equals() class provided by java.lang.Object compares memory location and only return true if two reference variable are pointing to same memory location i.e. essentially they are same object.

Java recommends to override equals and hashCode method if equality is going to be defined by logical way or via some business logic: example:

many classes in Java standard library does override it e.g. String overrides equals, whose implementation of equals() method return true if content of two String objects are exactly same

Integer wrapper class overrides equals to perform numerical comparison etc.

What is special about /dev/tty?

The 'c' means it's a character device. tty is a special file representing the 'controlling terminal' for the current process.

Character Devices

Unix supports 'device files', which aren't really files at all, but file-like access points to hardware devices. A 'character' device is one which is interfaced byte-by-byte (as opposed to buffered IO).

TTY

/dev/tty is a special file, representing the terminal for the current process. So, when you echo 1 > /dev/tty, your message ('1') will appear on your screen. Likewise, when you cat /dev/tty, your subsequent input gets duplicated (until you press Ctrl-C).

/dev/tty doesn't 'contain' anything as such, but you can read from it and write to it (for what it's worth). I can't think of a good use for it, but there are similar files which are very useful for simple IO operations (e.g. /dev/ttyS0 is normally your serial port)

This quote is from http://tldp.org/HOWTO/Text-Terminal-HOWTO-7.html#ss7.3 :

/dev/tty stands for the controlling terminal (if any) for the current process. To find out which tty's are attached to which processes use the "ps -a" command at the shell prompt (command line). Look at the "tty" column. For the shell process you're in, /dev/tty is the terminal you are now using. Type "tty" at the shell prompt to see what it is (see manual pg. tty(1)). /dev/tty is something like a link to the actually terminal device name with some additional features for C-programmers: see the manual page tty(4).

Here is the man page: http://linux.die.net/man/4/tty

How do I get a background location update every n minutes in my iOS application?

I did this in an application I'm developing. The timers don't work when the app is in the background but the app is constantly receiving the location updates. I read somewhere in the documentation (i can't seem to find it now, i'll post an update when i do) that a method can be called only on an active run loop when the app is in the background. The app delegate has an active run loop even in the bg so you dont need to create your own to make this work. [Im not sure if this is the correct explanation but thats how I understood from what i read]

First of all, add the location object for the key UIBackgroundModes in your app's info.plist. Now, what you need to do is start the location updates anywhere in your app:

    CLLocationManager locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;//or whatever class you have for managing location
    [locationManager startUpdatingLocation];

Next, write a method to handle the location updates, say -(void)didUpdateToLocation:(CLLocation*)location, in the app delegate. Then implement the method locationManager:didUpdateLocation:fromLocation of CLLocationManagerDelegate in the class in which you started the location manager (since we set the location manager delegate to 'self'). Inside this method you need to check if the time interval after which you have to handle the location updates has elapsed. You can do this by saving the current time every time. If that time has elapsed, call the method UpdateLocation from your app delegate:

NSDate *newLocationTimestamp = newLocation.timestamp;
NSDate *lastLocationUpdateTiemstamp;

int locationUpdateInterval = 300;//5 mins

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
if (userDefaults) {

        lastLocationUpdateTiemstamp = [userDefaults objectForKey:kLastLocationUpdateTimestamp];

        if (!([newLocationTimestamp timeIntervalSinceDate:lastLocationUpdateTiemstamp] < locationUpdateInterval)) {
            //NSLog(@"New Location: %@", newLocation);
            [(AppDelegate*)[UIApplication sharedApplication].delegate didUpdateToLocation:newLocation];
            [userDefaults setObject:newLocationTimestamp forKey:kLastLocationUpdateTimestamp];
        }
    }
}

This will call your method every 5 mins even when your app is in background. Imp: This implementation drains the battery, if your location data's accuracy is not critical you should use [locationManager startMonitoringSignificantLocationChanges]

Before adding this to your app, please read the Location Awareness Programming Guide

jquery/javascript convert date string to date

Use moment js for any date operation.

https://momentjs.com/

_x000D_
_x000D_
console.log(moment("Sunday, February 28, 2010").format('MM/DD/YYYY'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

Using Python Requests: Sessions, Cookies, and POST

I don't know how stubhub's api works, but generally it should look like this:

s = requests.Session()
data = {"login":"my_login", "password":"my_password"}
url = "http://example.net/login"
r = s.post(url, data=data)

Now your session contains cookies provided by login form. To access cookies of this session simply use

s.cookies

Any further actions like another requests will have this cookie

How do you Programmatically Download a Webpage in Java

Get help from this class it get code and filter some information.

public class MainActivity extends AppCompatActivity {

    EditText url;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_main );

        url = ((EditText)findViewById( R.id.editText));
        DownloadCode obj = new DownloadCode();

        try {
            String des=" ";

            String tag1= "<div class=\"description\">";
            String l = obj.execute( "http://www.nu.edu.pk/Campus/Chiniot-Faisalabad/Faculty" ).get();

            url.setText( l );
            url.setText( " " );

            String[] t1 = l.split(tag1);
            String[] t2 = t1[0].split( "</div>" );
            url.setText( t2[0] );

        }
        catch (Exception e)
        {
            Toast.makeText( this,e.toString(),Toast.LENGTH_SHORT ).show();
        }

    }
                                        // input, extrafunctionrunparallel, output
    class DownloadCode extends AsyncTask<String,Void,String>
    {
        @Override
        protected String doInBackground(String... WebAddress) // string of webAddress separate by ','
        {
            String htmlcontent = " ";
            try {
                URL url = new URL( WebAddress[0] );
                HttpURLConnection c = (HttpURLConnection) url.openConnection();
                c.connect();
                InputStream input = c.getInputStream();
                int data;
                InputStreamReader reader = new InputStreamReader( input );

                data = reader.read();

                while (data != -1)
                {
                    char content = (char) data;
                    htmlcontent+=content;
                    data = reader.read();
                }
            }
            catch (Exception e)
            {
                Log.i("Status : ",e.toString());
            }
            return htmlcontent;
        }
    }
}

make bootstrap twitter dialog modal draggable

$("#myModal").draggable({
    handle: ".modal-header"
}); 

it works for me. I got it from there. if you give me thanks please give 70% to Andres Ilich

Check mySQL version on Mac 10.8.5

Every time you used the mysql console, the version is shown.

 mysql -u user

Successful console login shows the following which includes the mysql server version.

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1432
Server version: 5.5.9-log Source distribution

Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

You can also check the mysql server version directly by executing the following command:

mysql --version

You may also check the version information from the mysql console itself using the version variables:

mysql> SHOW VARIABLES LIKE "%version%";

Output will be something like this:

+-------------------------+---------------------+
| Variable_name           | Value               |
+-------------------------+---------------------+
| innodb_version          | 1.1.5               |
| protocol_version        | 10                  |
| slave_type_conversions  |                     |
| version                 | 5.5.9-log           |
| version_comment         | Source distribution |
| version_compile_machine | i386                |
| version_compile_os      | osx10.4             |
+-------------------------+---------------------+
7 rows in set (0.01 sec)

You may also use this:

mysql> select @@version;

The STATUS command display version information as well.

mysql> STATUS

You can also check the version by executing this command:

mysql -v

It's worth mentioning that if you have encountered something like this:

ERROR 2002 (HY000): Can't connect to local MySQL server through socket
'/tmp/mysql.sock' (2)

you can fix it by:

sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /tmp/mysql.sock

jQuery Remove string from string

I assume that the text "username1" is just a placeholder for what will eventually be an actual username. Assuming that,

  • If the username is not allowed to have spaces, then just search for everything before the first space or comma (thus finding both "u1 likes this" and "u1, u2, and u3 like this").
  • If it is allowed to have a space, it would probably be easier to wrap each username in it's own span tag server-side, before sending it to the client, and then just working with the span tags.

Difference between r+ and w+ in fopen()

Both r+ and w+ can read and write to a file. However, r+ doesn't delete the content of the file and doesn't create a new file if such file doesn't exist, whereas w+ deletes the content of the file and creates it if it doesn't exist.

Parameter "stratify" from method "train_test_split" (scikit Learn)

This stratify parameter makes a split so that the proportion of values in the sample produced will be the same as the proportion of values provided to parameter stratify.

For example, if variable y is a binary categorical variable with values 0 and 1 and there are 25% of zeros and 75% of ones, stratify=y will make sure that your random split has 25% of 0's and 75% of 1's.

How do browser cookie domains work?

I was surprised to read section 3.3.2 about rejecting cookies:

http://tools.ietf.org/html/rfc2965

That says that a browser should reject a cookie from x.y.z.com with domain .z.com, because 'x.y' contains a dot. So, unless I am misinterpreting the RFC and/or the questions above, there could be questions added:

Will a cookie for .example.com be available for www.yyy.example.com? No.

Will a cookie set by origin server www.yyy.example.com, with domain .example.com, have it's value sent by the user agent to xxx.example.com? No.

How do I get the current absolute URL in Ruby on Rails?

You can either use

request.original_url 

or

"#{request.protocol}#{request.host_with_port}" 

to get the current URL.

how to delete default values in text field using selenium?

.clear() can be used to clear the text

  (locator).clear();

using clear with the locator deletes all the value in that exact locator.

Connection timeout for SQL server

Yes, you could append ;Connection Timeout=30 to your connection string and specify the value you wish.

The timeout value set in the Connection Timeout property is a time expressed in seconds. If this property isn't set, the timeout value for the connection is the default value (15 seconds).

Moreover, setting the timeout value to 0, you are specifying that your attempt to connect waits an infinite time. As described in the documentation, this is something that you shouldn't set in your connection string:

A value of 0 indicates no limit, and should be avoided in a ConnectionString because an attempt to connect waits indefinitely.

How do I copy a version of a single file from one git branch to another?

1) Ensure you're in branch where you need a copy of the file. for eg: i want sub branch file in master so you need to checkout or should be in master git checkout master

2) Now checkout specific file alone you want from sub branch into master,

git checkout sub_branch file_path/my_file.ext

here sub_branch means where you have that file followed by filename you need to copy.

How to make a variadic macro (variable number of arguments)

I don't think that's possible, you could fake it with double parens ... just as long you don't need the arguments individually.

#define macro(ARGS) some_complicated (whatever ARGS)
// ...
macro((a,b,c))
macro((d,e))

jquery data selector

Here's a plugin that simplifies life https://github.com/rootical/jQueryDataSelector

Use it like that:

data selector           jQuery selector
  $$('name')              $('[data-name]')
  $$('name', 10)          $('[data-name=10]')
  $$('name', false)       $('[data-name=false]')
  $$('name', null)        $('[data-name]')
  $$('name', {})          Syntax error

Include .so library in apk in android studio

I had the same problem. Check out the comment in https://gist.github.com/khernyo/4226923#comment-812526

It says:

for gradle android plugin v0.3 use "com.android.build.gradle.tasks.PackageApplication"

That should fix your problem.

Handling multiple IDs in jQuery

Yes, #id selectors combined with a multiple selector (comma) is perfectly valid in both jQuery and CSS.

However, for your example, since <script> comes before the elements, you need a document.ready handler, so it waits until the elements are in the DOM to go looking for them, like this:

<script>
  $(function() {
    $("#segement1,#segement2,#segement3").hide()
  });
</script>

<div id="segement1"></div>
<div id="segement2"></div>
<div id="segement3"></div>

Shell script : How to cut part of a string

$ ruby -ne 'puts $_.scan(/id=(\d+)/)' file
9
10

Docker CE on RHEL - Requires: container-selinux >= 2.9

Installing the Selinux from the Centos repository worked for me:
1. Go to http://mirror.centos.org/centos/7/extras/x86_64/Packages/
2. Find the latest version for container-selinux i.e. container-selinux-2.21-1.el7.noarch.rpm
3. Run the following command on your terminal: $ sudo yum install -y http://mirror.centos.org/centos/7/extras/x86_64/Packages/**Add_current_container-selinux_package_here**
4. The command should looks like the following $ sudo yum install -y http://mirror.centos.org/centos/7/extras/x86_64/Packages/container-selinux-2.21-1.el7.noarch.rpm
Note: the container version is constantly being updated, that is why you should look for the latest version in the Centos' repository

Generate random password string with requirements in javascript

My Crypto based take on the problem. Using ES6 and omitting any browser feature checks. Any comments on security or performance?

const generatePassword = (
  passwordLength = 12,
  passwordChars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
) =>
  [...window.crypto.getRandomValues(new Uint32Array(passwordLength))]
    .map(x => passwordChars[x % passwordChars.length])
    .join('');

How to import existing Android project into Eclipse?

Im not sure this will solve your problem since I dont know where it originats from, but when I import a project i go File -> Import -> Existing projects into workspace. Maybe it will circumvent your problem.

Difference between char* and const char*?

The question is what's the difference between

char *name

which points to a constant string literal, and

const char *cname

I.e. given

char *name = "foo";

and

const char *cname = "foo";

There is not much difference between the 2 and both can be seen as correct. Due to the long legacy of C code, the string literals have had a type of char[], not const char[], and there are lots of older code that likewise accept char * instead of const char *, even when they do not modify the arguments.

The principal difference of the 2 in general is that *cname or cname[n] will evaluate to lvalues of type const char, whereas *name or name[n] will evaluate to lvalues of type char, which are modifiable lvalues. A conforming compiler is required to produce a diagnostics message if target of the assignment is not a modifiable lvalue; it need not produce any warning on assignment to lvalues of type char:

name[0] = 'x'; // no diagnostics *needed*
cname[0] = 'x'; // a conforming compiler *must* produce a diagnostic message

The compiler is not required to stop the compilation in either case; it is enough that it produces a warning for the assignment to cname[0]. The resulting program is not a correct program. The behaviour of the construct is undefined. It may crash, or even worse, it might not crash, and might change the string literal in memory.

How to sort an array of ints using a custom comparator?

How about using streams (Java 8)?

int[] ia = {99, 11, 7, 21, 4, 2};
ia = Arrays.stream(ia).
    boxed().
    sorted((a, b) -> b.compareTo(a)). // sort descending
    mapToInt(i -> i).
    toArray();

Or in-place:

int[] ia = {99, 11, 7, 21, 4, 2};
System.arraycopy(
        Arrays.stream(ia).
            boxed().
            sorted((a, b) -> b.compareTo(a)). // sort descending
            mapToInt(i -> i).
            toArray(),
        0,
        ia,
        0,
        ia.length
    );

check android application is in foreground or not?

With the new Android Architecture of Lifecycle extensions, we can achieve this with utmost ease.

Just ensure you pull this dependency in your build.gradle file:

dependencies {
    implementation "android.arch.lifecycle:extensions:1.1.0"
}

Then in your Application class, use this:

class ArchLifecycleApp : Application(), LifecycleObserver {

    override fun onCreate() {
        super.onCreate()
        ProcessLifecycleOwner.get().lifecycle.addObserver(this)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onAppBackgrounded() {
        Log.d("MyApp", "App in background")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onAppForegrounded() {
        Log.d("MyApp", "App in foreground")
    }
}

In the end, update your AndroidManifest.xml file with:

<application
    android:name=".ArchLifecycleApp"
    //Your extra code
    ....>
</application>

Now, on everytime the Application goes to Foreground or Background, we are going to receive the Logs associated with the two methods declared.

Visual Studio Expand/Collapse keyboard shortcuts

I have always wanted Visual Studio to include an option to just collapse / expand the regions. I have the following macros which will do just that.

Imports EnvDTE
Imports System.Diagnostics
' Macros for improving keyboard support for "#region ... #endregion"
Public Module CollapseExpandRegions
' Expands all regions in the current document
  Sub ExpandAllRegions()

    Dim objSelection As TextSelection ' Our selection object

    DTE.SuppressUI = True ' Disable UI while we do this
    objSelection = DTE.ActiveDocument.Selection() ' Hook up to the ActiveDocument's selection
    objSelection.StartOfDocument() ' Shoot to the start of the document

    ' Loop through the document finding all instances of #region. This action has the side benefit
    ' of actually zooming us to the text in question when it is found and ALSO expanding it since it
    ' is an outline.
    Do While objSelection.FindText("#region", vsFindOptions.vsFindOptionsMatchInHiddenText)
        ' This next command would be what we would normally do *IF* the find operation didn't do it for us.
        'DTE.ExecuteCommand("Edit.ToggleOutliningExpansion")
    Loop
    objSelection.StartOfDocument() ' Shoot us back to the start of the document
    DTE.SuppressUI = False ' Reenable the UI

    objSelection = Nothing ' Release our object

  End Sub

  ' Collapses all regions in the current document
  Sub CollapseAllRegions()
    Dim objSelection As TextSelection ' Our selection object

    ExpandAllRegions() ' Force the expansion of all regions

    DTE.SuppressUI = True ' Disable UI while we do this
    objSelection = DTE.ActiveDocument.Selection() ' Hook up to the ActiveDocument's selection
    objSelection.EndOfDocument() ' Shoot to the end of the document

    ' Find the first occurence of #region from the end of the document to the start of the document. Note:
    ' Note: Once a #region is "collapsed" .FindText only sees it's "textual descriptor" unless
    ' vsFindOptions.vsFindOptionsMatchInHiddenText is specified. So when a #region "My Class" is collapsed,
    ' .FindText would subsequently see the text 'My Class' instead of '#region "My Class"' for the subsequent
    ' passes and skip any regions already collapsed.
    Do While (objSelection.FindText("#region", vsFindOptions.vsFindOptionsBackwards))
        DTE.ExecuteCommand("Edit.ToggleOutliningExpansion") ' Collapse this #region
        'objSelection.EndOfDocument() ' Shoot back to the end of the document for
        ' another pass.
    Loop
    objSelection.StartOfDocument() ' All done, head back to the start of the doc
    DTE.SuppressUI = False ' Reenable the UI

    objSelection = Nothing ' Release our object

  End Sub
End Module

EDIT: There is now a shortcut called Edit.ToggleOutliningExpansion (Ctrl+M, Ctrl+M) for doing just that.

Best way to save a trained model in PyTorch?

If you want to save the model and wants to resume the training later:

Single GPU: Save:

state = {
        'epoch': epoch,
        'state_dict': model.state_dict(),
        'optimizer': optimizer.state_dict(),
}
savepath='checkpoint.t7'
torch.save(state,savepath)

Load:

checkpoint = torch.load('checkpoint.t7')
model.load_state_dict(checkpoint['state_dict'])
optimizer.load_state_dict(checkpoint['optimizer'])
epoch = checkpoint['epoch']

Multiple GPU: Save

state = {
        'epoch': epoch,
        'state_dict': model.module.state_dict(),
        'optimizer': optimizer.state_dict(),
}
savepath='checkpoint.t7'
torch.save(state,savepath)

Load:

checkpoint = torch.load('checkpoint.t7')
model.load_state_dict(checkpoint['state_dict'])
optimizer.load_state_dict(checkpoint['optimizer'])
epoch = checkpoint['epoch']

#Don't call DataParallel before loading the model otherwise you will get an error

model = nn.DataParallel(model) #ignore the line if you want to load on Single GPU

Get ID from URL with jQuery

My url is like this http://www.default-search.net/?sid=503 . I want to get 503 . I wrote the following code .

var baseUrl = (window.location).href; // You can also use document.URL
var koopId = baseUrl.substring(baseUrl.lastIndexOf('=') + 1);
alert(koopId)//503

If you use

var v = window.location.pathname;
console.log(v)

You will get only "/";

SQL JOIN, GROUP BY on three tables to get totals

I have a tip for those, who want to get various aggregated values from the same table.

Lets say I have table with users and table with points the users acquire. So the connection between them is 1:N (one user, many points records).

Now in the table 'points' I also store the information about for what did the user get the points (login, clicking a banner etc.). And I want to list all users ordered by SUM(points) AND then by SUM(points WHERE type = x). That is to say ordered by all the points user has and then by points the user got for a specific action (eg. login).

The SQL would be:

SELECT SUM(points.points) AS points_all, SUM(points.points * (points.type = 7)) AS points_login
FROM user
LEFT JOIN points ON user.id = points.user_id
GROUP BY user.id

The beauty of this is in the SUM(points.points * (points.type = 7)) where the inner parenthesis evaluates to either 0 or 1 thus multiplying the given points value by 0 or 1, depending on wheteher it equals to the the type of points we want.

How do I properly 'printf' an integer and a string in C?

You're on the right track. Here's a corrected version:

char str[10];
int n;

printf("type a string: ");
scanf("%s %d", str, &n);

printf("%s\n", str);
printf("%d\n", n);

Let's talk through the changes:

  1. allocate an int (n) to store your number in
  2. tell scanf to read in first a string and then a number (%d means number, as you already knew from your printf

That's pretty much all there is to it. Your code is a little bit dangerous, still, because any user input that's longer than 9 characters will overflow str and start trampling your stack.

Matplotlib discrete colorbar

I think you'd want to look at colors.ListedColormap to generate your colormap, or if you just need a static colormap I've been working on an app that might help.

How to use onSaveInstanceState() and onRestoreInstanceState()?

When your activity is recreated after it was previously destroyed, you can recover your saved state from the Bundle that the system passes your activity. Both the onCreate() and onRestoreInstanceState() callback methods receive the same Bundle that contains the instance state information.

Because the onCreate() method is called whether the system is creating a new instance of your activity or recreating a previous one, you must check whether the state Bundle is null before you attempt to read it. If it is null, then the system is creating a new instance of the activity, instead of restoring a previous one that was destroyed.

static final String STATE_USER = "user";
private String mUser;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Check whether we're recreating a previously destroyed instance
    if (savedInstanceState != null) {
        // Restore value of members from saved state
        mUser = savedInstanceState.getString(STATE_USER);
    } else {
        // Probably initialize members with default values for a new instance
        mUser = "NewUser";
    }
}

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    savedInstanceState.putString(STATE_USER, mUser);
    // Always call the superclass so it can save the view hierarchy state
    super.onSaveInstanceState(savedInstanceState);
}

http://developer.android.com/training/basics/activity-lifecycle/recreating.html

Is there possibility of sum of ArrayList without looping

Once is out (March 2014) you'll be able to use streams:

If you have a List<Integer>

int sum = list.stream().mapToInt(Integer::intValue).sum();

If it's an int[]

int sum = IntStream.of(a).sum();

Calculate percentage saved between two numbers?

100% - discounted price / full price

How to store date/time and timestamps in UTC time zone with JPA and Hibernate

Hibernate does not allow for specifying time zones by annotation or any other means. If you use Calendar instead of date, you can implement a workaround using HIbernate property AccessType and implementing the mapping yourself. The more advanced solution is to implement a custom UserType to map your Date or Calendar. Both solutions are explained in my blog post here: http://www.joobik.com/2010/11/mapping-dates-and-time-zones-with.html

What is the best Java QR code generator library?

QRGen is a good library that creates a layer on top of ZXing and makes QR Code generation in Java a piece of cake.

How to send file contents as body entity using cURL

I believe you're looking for the @filename syntax, e.g.:

strip new lines

curl --data "@/path/to/filename" http://...

keep new lines

curl --data-binary "@/path/to/filename" http://...

curl will strip all newlines from the file. If you want to send the file with newlines intact, use --data-binary in place of --data

What is the difference between CloseableHttpClient and HttpClient in Apache HttpClient API?

CloseableHttpClient is the base class of the httpclient library, the one all implementations use. Other subclasses are for the most part deprecated.

The HttpClient is an interface for this class and other classes.

You should then use the CloseableHttpClient in your code, and create it using the HttpClientBuilder. If you need to wrap the client to add specific behaviour you should use request and response interceptors instead of wrapping with the HttpClient.

This answer was given in the context of httpclient-4.3.

How can I create a copy of an object in Python?

Shallow copy with copy.copy()

#!/usr/bin/env python3

import copy

class C():
    def __init__(self):
        self.x = [1]
        self.y = [2]

# It copies.
c = C()
d = copy.copy(c)
d.x = [3]
assert c.x == [1]
assert d.x == [3]

# It's shallow.
c = C()
d = copy.copy(c)
d.x[0] = 3
assert c.x == [3]
assert d.x == [3]

Deep copy with copy.deepcopy()

#!/usr/bin/env python3
import copy
class C():
    def __init__(self):
        self.x = [1]
        self.y = [2]
c = C()
d = copy.deepcopy(c)
d.x[0] = 3
assert c.x == [1]
assert d.x == [3]

Documentation: https://docs.python.org/3/library/copy.html

Tested on Python 3.6.5.

CSS: 100% font size - 100% of what?

Relative to the default size defined to that font.

If someone opens your page on a web browser, there's a default font and font size it uses.

SQL Server 2012 column identity increment jumping from 6 to 1000+ on 7th entry

Got the same problem, found the following bug report in SQL Server 2012 If still relevant see conditions that cause the issue - there are some workarounds there as well (didn't try though). Failover or Restart Results in Reseed of Identity

Using a dictionary to count the items in a list

in 2.7 and 3.1 there is special Counter dict for this purpose.

>>> from collections import Counter
>>> Counter(['apple','red','apple','red','red','pear'])
Counter({'red': 3, 'apple': 2, 'pear': 1})

What is logits, softmax and softmax_cross_entropy_with_logits?

Short version:

Suppose you have two tensors, where y_hat contains computed scores for each class (for example, from y = W*x +b) and y_true contains one-hot encoded true labels.

y_hat  = ... # Predicted label, e.g. y = tf.matmul(X, W) + b
y_true = ... # True label, one-hot encoded

If you interpret the scores in y_hat as unnormalized log probabilities, then they are logits.

Additionally, the total cross-entropy loss computed in this manner:

y_hat_softmax = tf.nn.softmax(y_hat)
total_loss = tf.reduce_mean(-tf.reduce_sum(y_true * tf.log(y_hat_softmax), [1]))

is essentially equivalent to the total cross-entropy loss computed with the function softmax_cross_entropy_with_logits():

total_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y_hat, y_true))

Long version:

In the output layer of your neural network, you will probably compute an array that contains the class scores for each of your training instances, such as from a computation y_hat = W*x + b. To serve as an example, below I've created a y_hat as a 2 x 3 array, where the rows correspond to the training instances and the columns correspond to classes. So here there are 2 training instances and 3 classes.

import tensorflow as tf
import numpy as np

sess = tf.Session()

# Create example y_hat.
y_hat = tf.convert_to_tensor(np.array([[0.5, 1.5, 0.1],[2.2, 1.3, 1.7]]))
sess.run(y_hat)
# array([[ 0.5,  1.5,  0.1],
#        [ 2.2,  1.3,  1.7]])

Note that the values are not normalized (i.e. the rows don't add up to 1). In order to normalize them, we can apply the softmax function, which interprets the input as unnormalized log probabilities (aka logits) and outputs normalized linear probabilities.

y_hat_softmax = tf.nn.softmax(y_hat)
sess.run(y_hat_softmax)
# array([[ 0.227863  ,  0.61939586,  0.15274114],
#        [ 0.49674623,  0.20196195,  0.30129182]])

It's important to fully understand what the softmax output is saying. Below I've shown a table that more clearly represents the output above. It can be seen that, for example, the probability of training instance 1 being "Class 2" is 0.619. The class probabilities for each training instance are normalized, so the sum of each row is 1.0.

                      Pr(Class 1)  Pr(Class 2)  Pr(Class 3)
                    ,--------------------------------------
Training instance 1 | 0.227863   | 0.61939586 | 0.15274114
Training instance 2 | 0.49674623 | 0.20196195 | 0.30129182

So now we have class probabilities for each training instance, where we can take the argmax() of each row to generate a final classification. From above, we may generate that training instance 1 belongs to "Class 2" and training instance 2 belongs to "Class 1".

Are these classifications correct? We need to measure against the true labels from the training set. You will need a one-hot encoded y_true array, where again the rows are training instances and columns are classes. Below I've created an example y_true one-hot array where the true label for training instance 1 is "Class 2" and the true label for training instance 2 is "Class 3".

y_true = tf.convert_to_tensor(np.array([[0.0, 1.0, 0.0],[0.0, 0.0, 1.0]]))
sess.run(y_true)
# array([[ 0.,  1.,  0.],
#        [ 0.,  0.,  1.]])

Is the probability distribution in y_hat_softmax close to the probability distribution in y_true? We can use cross-entropy loss to measure the error.

Formula for cross-entropy loss

We can compute the cross-entropy loss on a row-wise basis and see the results. Below we can see that training instance 1 has a loss of 0.479, while training instance 2 has a higher loss of 1.200. This result makes sense because in our example above, y_hat_softmax showed that training instance 1's highest probability was for "Class 2", which matches training instance 1 in y_true; however, the prediction for training instance 2 showed a highest probability for "Class 1", which does not match the true class "Class 3".

loss_per_instance_1 = -tf.reduce_sum(y_true * tf.log(y_hat_softmax), reduction_indices=[1])
sess.run(loss_per_instance_1)
# array([ 0.4790107 ,  1.19967598])

What we really want is the total loss over all the training instances. So we can compute:

total_loss_1 = tf.reduce_mean(-tf.reduce_sum(y_true * tf.log(y_hat_softmax), reduction_indices=[1]))
sess.run(total_loss_1)
# 0.83934333897877944

Using softmax_cross_entropy_with_logits()

We can instead compute the total cross entropy loss using the tf.nn.softmax_cross_entropy_with_logits() function, as shown below.

loss_per_instance_2 = tf.nn.softmax_cross_entropy_with_logits(y_hat, y_true)
sess.run(loss_per_instance_2)
# array([ 0.4790107 ,  1.19967598])

total_loss_2 = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y_hat, y_true))
sess.run(total_loss_2)
# 0.83934333897877922

Note that total_loss_1 and total_loss_2 produce essentially equivalent results with some small differences in the very final digits. However, you might as well use the second approach: it takes one less line of code and accumulates less numerical error because the softmax is done for you inside of softmax_cross_entropy_with_logits().

Table row and column number in jQuery

Can you output that data in the cells as you are creating the table?

so your table would look like this:

<table>
  <thead>...</thead>
  <tbody>
    <tr><td data-row='1' data-column='1'>value</td>
      <td data-row='1' data-column='2'>value</td>
      <td data-row='1' data-column='3'>value</td></tr>

  <tbody>
</table>

then it would be a simple matter

$("td").click(function(event) {
   var row = $(this).attr("data-row");
   var col = $(this).attr("data-col");
}

C++ queue - simple example

Simply declare it as below if you want to us the STL queue container.

std::queue<myclass*> my_queue;

Could not load file or assembly "Oracle.DataAccess" or one of its dependencies

i Have face the same issue and resolved by replacing the old Oracle.DataAccess.dll with new Oracle.DataAccess.dll(which come with oracle client when install)

in my case the path of new Oracle.DataAccess.dll is

  • E:\app\Rehman.Rashid\product\11.2.0\client_1\ODP.NET\bin

Spring: How to inject a value to static field?

This is my sample code for load static variable

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class OnelinkConfig {
    public static int MODULE_CODE;
    public static int DEFAULT_PAGE;
    public static int DEFAULT_SIZE;

    @Autowired
    public void loadOnelinkConfig(@Value("${onelink.config.exception.module.code}") int code,
            @Value("${onelink.config.default.page}") int page, @Value("${onelink.config.default.size}") int size) {
        MODULE_CODE = code;
        DEFAULT_PAGE = page;
        DEFAULT_SIZE = size;
    }
}

What is a good practice to check if an environmental variable exists or not?

In case you want to check if multiple env variables are not set, you can do the following:

import os

MANDATORY_ENV_VARS = ["FOO", "BAR"]

for var in MANDATORY_ENV_VARS:
    if var not in os.environ:
        raise EnvironmentError("Failed because {} is not set.".format(var))

BitBucket - download source as ZIP

I was trying to figure out if it's possible to browse the code of an earlier commit like you can on GitHub and it brought me here. I used the information I found here, and after fiddling around with the urls, I actually found a way to browse code of old commits as well. Even though the question/answer is about downloading the code of an earlier commit, I thought I'd just add an answer for browsing the code also.

When you're browsing your code the URL is something like:

https://bitbucket.org/user/repo/src/

and by adding a commit hash at the end like this:

https://bitbucket.org/user/repo/src/a0328cb

You can browse the code at the point of that commit. I don't understand why there's no dropdown box for choosing a commit directly, the feature is already there. Strange.

how to always round up to the next integer

(list.Count() + 9) / 10

Everything else here is either overkill or simply wrong (except for bestsss' answer, which is awesome). We do not want the overhead of a function call (Math.Truncate(), Math.Ceiling(), etc.) when simple math is enough.


OP's question generalizes (pigeonhole principle) to:

How many boxes do I need to store x objects if only y objects fit into each box?

The solution:

  1. derives from the realization that the last box might be partially empty, and
  2. is (x + y - 1) ÷ y using integer division.

You'll recall from 3rd grade math that integer division is what we're doing when we say 5 ÷ 2 = 2.

Floating-point division is when we say 5 ÷ 2 = 2.5, but we don't want that here.

Many programming languages support integer division. In languages derived from C, you get it automatically when you divide int types (short, int, long, etc.). The remainder/fractional part of any division operation is simply dropped, thus:

5 / 2 == 2

Replacing our original question with x = 5 and y = 2 we have:

How many boxes do I need to store 5 objects if only 2 objects fit into each box?

The answer should now be obvious: 3 boxes -- the first two boxes hold two objects each and the last box holds one.

(x + y - 1) ÷ y =
(5 + 2 - 1) ÷ 2 =
6 ÷ 2 =
3

So for the original question, x = list.Count(), y = 10, which gives the solution using no additional function calls:

(list.Count() + 9) / 10

From inside of a Docker container, how do I connect to the localhost of the machine?

Edit: If you are using Docker-for-mac or Docker-for-Windows 18.03+, just connect to your mysql service using the host host.docker.internal (instead of the 127.0.0.1 in your connection string).

As of Docker 18.09.3, this does not work on Docker-for-Linux. A fix has been submitted on March the 8th, 2019 and will hopefully be merged to the code base. Until then, a workaround is to use a container as described in qoomon's answer.

2020-01: some progress has been made. If all goes well, this should land in Docker 20.04

Docker 20.10-beta1 has been reported to implement host.docker.internal :

$ docker run --rm --add-host host.docker.internal:host-gateway alpine ping host.docker.internal
PING host.docker.internal (172.17.0.1): 56 data bytes
64 bytes from 172.17.0.1: seq=0 ttl=64 time=0.534 ms
64 bytes from 172.17.0.1: seq=1 ttl=64 time=0.176 ms
...

TLDR

Use --network="host" in your docker run command, then 127.0.0.1 in your docker container will point to your docker host.

Note: This mode only works on Docker for Linux, per the documentation.


Note on docker container networking modes

Docker offers different networking modes when running containers. Depending on the mode you choose you would connect to your MySQL database running on the docker host differently.

docker run --network="bridge" (default)

Docker creates a bridge named docker0 by default. Both the docker host and the docker containers have an IP address on that bridge.

on the Docker host, type sudo ip addr show docker0 you will have an output looking like:

[vagrant@docker:~] $ sudo ip addr show docker0
4: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
    link/ether 56:84:7a:fe:97:99 brd ff:ff:ff:ff:ff:ff
    inet 172.17.42.1/16 scope global docker0
       valid_lft forever preferred_lft forever
    inet6 fe80::5484:7aff:fefe:9799/64 scope link
       valid_lft forever preferred_lft forever

So here my docker host has the IP address 172.17.42.1 on the docker0 network interface.

Now start a new container and get a shell on it: docker run --rm -it ubuntu:trusty bash and within the container type ip addr show eth0 to discover how its main network interface is set up:

root@e77f6a1b3740:/# ip addr show eth0
863: eth0: <BROADCAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 66:32:13:f0:f1:e3 brd ff:ff:ff:ff:ff:ff
    inet 172.17.1.192/16 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::6432:13ff:fef0:f1e3/64 scope link
       valid_lft forever preferred_lft forever

Here my container has the IP address 172.17.1.192. Now look at the routing table:

root@e77f6a1b3740:/# route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         172.17.42.1     0.0.0.0         UG    0      0        0 eth0
172.17.0.0      *               255.255.0.0     U     0      0        0 eth0

So the IP Address of the docker host 172.17.42.1 is set as the default route and is accessible from your container.

root@e77f6a1b3740:/# ping 172.17.42.1
PING 172.17.42.1 (172.17.42.1) 56(84) bytes of data.
64 bytes from 172.17.42.1: icmp_seq=1 ttl=64 time=0.070 ms
64 bytes from 172.17.42.1: icmp_seq=2 ttl=64 time=0.201 ms
64 bytes from 172.17.42.1: icmp_seq=3 ttl=64 time=0.116 ms

docker run --network="host"

Alternatively you can run a docker container with network settings set to host. Such a container will share the network stack with the docker host and from the container point of view, localhost (or 127.0.0.1) will refer to the docker host.

Be aware that any port opened in your docker container would be opened on the docker host. And this without requiring the -p or -P docker run option.

IP config on my docker host:

[vagrant@docker:~] $ ip addr show eth0
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 08:00:27:98:dc:aa brd ff:ff:ff:ff:ff:ff
    inet 10.0.2.15/24 brd 10.0.2.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::a00:27ff:fe98:dcaa/64 scope link
       valid_lft forever preferred_lft forever

and from a docker container in host mode:

[vagrant@docker:~] $ docker run --rm -it --network=host ubuntu:trusty ip addr show eth0
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 08:00:27:98:dc:aa brd ff:ff:ff:ff:ff:ff
    inet 10.0.2.15/24 brd 10.0.2.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::a00:27ff:fe98:dcaa/64 scope link
       valid_lft forever preferred_lft forever

As you can see both the docker host and docker container share the exact same network interface and as such have the same IP address.


Connecting to MySQL from containers

bridge mode

To access MySQL running on the docker host from containers in bridge mode, you need to make sure the MySQL service is listening for connections on the 172.17.42.1 IP address.

To do so, make sure you have either bind-address = 172.17.42.1 or bind-address = 0.0.0.0 in your MySQL config file (my.cnf).

If you need to set an environment variable with the IP address of the gateway, you can run the following code in a container :

export DOCKER_HOST_IP=$(route -n | awk '/UG[ \t]/{print $2}')

then in your application, use the DOCKER_HOST_IP environment variable to open the connection to MySQL.

Note: if you use bind-address = 0.0.0.0 your MySQL server will listen for connections on all network interfaces. That means your MySQL server could be reached from the Internet ; make sure to setup firewall rules accordingly.

Note 2: if you use bind-address = 172.17.42.1 your MySQL server won't listen for connections made to 127.0.0.1. Processes running on the docker host that would want to connect to MySQL would have to use the 172.17.42.1 IP address.

host mode

To access MySQL running on the docker host from containers in host mode, you can keep bind-address = 127.0.0.1 in your MySQL configuration and all you need to do is to connect to 127.0.0.1 from your containers:

[vagrant@docker:~] $ docker run --rm -it --network=host mysql mysql -h 127.0.0.1 -uroot -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 36
Server version: 5.5.41-0ubuntu0.14.04.1 (Ubuntu)

Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

note: Do use mysql -h 127.0.0.1 and not mysql -h localhost; otherwise the MySQL client would try to connect using a unix socket.

jQuery: serialize() form and other parameters

serialize() effectively turns the form values into a valid querystring, as such you can simply append to the string:

$.ajax({
    type : 'POST',
    url : 'url',
    data : $('#form').serialize() + "&par1=1&par2=2&par3=232"
}

Execution failed app:processDebugResources Android Studio

For me it was an error with my resources, Just changed the resources of my project in resources folder and res folder(i.e. for android) and it worked fine.

Build Successful

Total Time: 1 min 10.034 secs

Excel: How to check if a cell is empty with VBA?

IsEmpty() would be the quickest way to check for that.

IsNull() would seem like a similar solution, but keep in mind Null has to be assigned to the cell; it's not inherently created in the cell.

Also, you can check the cell by:

count()

counta()

Len(range("BCell").Value) = 0

Is there a query language for JSON?


I've just finished a releaseable version of a clientside JS-lib (defiant.js) that does what you're looking for. With defiant.js, you can query a JSON structure with the XPath expressions you're familiar with (no new syntax expressions as in JSONPath).

Example of how it works (see it in browser here http://defiantjs.com/defiant.js/demo/sum.avg.htm):

var data = [
       { "x": 2, "y": 0 },
       { "x": 3, "y": 1 },
       { "x": 4, "y": 1 },
       { "x": 2, "y": 1 }
    ],
    res = JSON.search( data, '//*[ y > 0 ]' );

console.log( res.sum('x') );
// 9
console.log( res.avg('x') );
// 3
console.log( res.min('x') );
// 2
console.log( res.max('x') );
// 4

As you can see, DefiantJS extends the global object JSON with a search function and the returned array is delivered with aggregate functions. DefiantJS contains a few other functionalities but those are out of the scope for this subject. Anywho, you can test the lib with a clientside XPath Evaluator. I think people not familiar with XPath will find this evaluator useful.
http://defiantjs.com/#xpath_evaluator

More information about defiant.js
http://defiantjs.com/
https://github.com/hbi99/defiant.js

I hope you find it useful... Regards

WPF chart controls

Free tools supporting panning / zooming:

Free tools without built in pan / zoom support:

Paid tools with built in pan / zoom support:

Full Disclosure: I have been heavily involved in development of Visiblox, hence I know that library in much more detail than the others.

Auto increment primary key in SQL Server Management Studio 2012

I had this issue where I had already created the table and could not change it without dropping the table so what I did was: (Not sure when they implemented this but had it in SQL 2016)

Right click on the table in the Object Explorer:

Script Table as > DROP And CREATE To > New Query Editor Window

Then do the edit to the script said by Josien; scroll to the bottom where the CREATE TABLE is, find your Primary Key and append IDENTITY(1,1) to the end before the comma. Run script.

The DROP and CREATE script was also helpful for me because of this issue. (Which the generated script handles.)

Get current time in seconds since the Epoch on Linux, Bash

So far, all the answers use the external program date.

Since Bash 4.2, printf has a new modifier %(dateformat)T that, when used with argument -1 outputs the current date with format given by dateformat, handled by strftime(3) (man 3 strftime for informations about the formats).

So, for a pure Bash solution:

printf '%(%s)T\n' -1

or if you need to store the result in a variable var:

printf -v var '%(%s)T' -1

No external programs and no subshells!

Since Bash 4.3, it's even possible to not specify the -1:

printf -v var '%(%s)T'

(but it might be wiser to always give the argument -1 nonetheless).

If you use -2 as argument instead of -1, Bash will use the time the shell was started instead of the current date. This can be used to compute elapsed times

$ printf -v beg '%(%s)T\n' -2
$ printf -v now '%(%s)T\n' -1
$ echo beg=$beg now=$now elapsed=$((now-beg))
beg=1583949610 now=1583953032 elapsed=3422

How do I create a message box with "Yes", "No" choices and a DialogResult?

Try this:

if (MessageBox.Show("Are you sure", "Title_here", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
{
    Do something here for 'Yes'...
}

How do I URL encode a string

ios 7 update

NSString *encode = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

NSString *decode = [encode stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

'uint32_t' identifier not found error

On Windows I usually use windows types. To use it you have to include <Windows.h>.

In this case uint32_t is UINT32 or just UINT.

All types definitions are here: http://msdn.microsoft.com/en-us/library/windows/desktop/aa383751%28v=vs.85%29.aspx

Easy way of running the same junit test over and over?

I build a module that allows do this kind of tests. But it is focused not only in repeat. But in guarantee that some piece of code is Thread safe.

https://github.com/anderson-marques/concurrent-testing

Maven dependency:

<dependency>
    <groupId>org.lite</groupId>
    <artifactId>concurrent-testing</artifactId>
    <version>1.0.0</version>
</dependency>

Example of use:

package org.lite.concurrent.testing;

import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import ConcurrentTest;
import ConcurrentTestsRule;

/**
 * Concurrent tests examples
 */
public class ExampleTest {

    /**
     * Create a new TestRule that will be applied to all tests
     */
    @Rule
    public ConcurrentTestsRule ct = ConcurrentTestsRule.silentTests();

    /**
     * Tests using 10 threads and make 20 requests. This means until 10 simultaneous requests.
     */
    @Test
    @ConcurrentTest(requests = 20, threads = 10)
    public void testConcurrentExecutionSuccess(){
        Assert.assertTrue(true);
    }

    /**
     * Tests using 10 threads and make 20 requests. This means until 10 simultaneous requests.
     */
    @Test
    @ConcurrentTest(requests = 200, threads = 10, timeoutMillis = 100)
    public void testConcurrentExecutionSuccessWaitOnly100Millissecond(){
    }

    @Test(expected = RuntimeException.class)
    @ConcurrentTest(requests = 3)
    public void testConcurrentExecutionFail(){
        throw new RuntimeException("Fail");
    }
}

This is a open source project. Feel free to improve.

.htaccess rewrite subdomain to directory

Redirect subdomain directory:

RewriteCond %{HTTP_HOST} ^([^.]+)\.(archive\.example\.com)$ [NC]
RewriteRule ^ http://%2/%1%{REQUEST_URI} [L,R=301]

How to plot a subset of a data frame in R?

with(dfr[dfr$var3 < 155,], plot(var1, var2)) should do the trick.

Edit regarding multiple conditions:

with(dfr[(dfr$var3 < 155) & (dfr$var4 > 27),], plot(var1, var2))

Keep the order of the JSON keys during JSON conversion to CSV

In the real world, an application will almost always have java bean or domain that is to be serialized/de-serialized to/from JSON. Its already mentioned that JSON Object specification does not guarantee order and any manipulation to that behavior does not justify the requirement. I had the same scenario in my application where I needed to preserve order just for the sack of readability purpose. I used standard jackson way to serialize my java bean to JSON:

Object object = getObject();  //the source java bean that needs conversion
String jsonString = new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(object);

In order to make the json with an ordered set of elements I just use JSON property annotation in the the Java bean I used for conversion. An example below:

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"name","phone","city","id"})
public class SampleBean implements Serializable {
    private int id;
    private String name:
    private String city;
    private String phone;

    //...standard getters and setters
}

the getObject() used above:

public SampleBean getObject(){
    SampleBean bean  = new SampleBean();
    bean.setId("100");
    bean.setName("SomeName");
    bean.setCity("SomeCity");
    bean.setPhone("1234567890");
    return bean;
}

The output shows as per Json property order annotation:

{
    name: "SomeName",
    phone: "1234567890",
    city: "SomeCity",
    id: 100
}

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

My response is fairly late. I faced the same problem. I am on Windows 10. This is what I did:

  • Open a new Command prompt (CMD.EXE)
  • Set the environment variables . set myvar1=myvalue1
  • Launch VS Code from that Command prompt by typing code and then press ENTER
  • VS code was launched and it inherited all the custom variables that I had set in the parent CMD window

Optionally, you can also use the Control Panel -> System properties window to set the variables on a more permanent basis

Hope this helps.

How to center a navigation bar with CSS or HTML?

You could also use float and inline-block to center your nav like the following:

nav li {
   float: left;
}
nav {
   display: inline-block;
}

nodejs get file name from absolute path?

In NodeJS, __filename.split(/\|//).pop() returns just the file name from the absolute file path on any OS platform. Why need to care about remembering/importing an API while this regex approach also letting us recollect our regex skills.

CSS: image link, change on hover

The problem with changing it via JavaScript or CSS is that if you have a slower connection, the image will take a second to change to the hovered version. This will cause an undesirable flash as one disappears while the other downloads.

What I've done before is have two images. Then hide and show each depending on the hover state. This will allow for a clean switch between the two images.

<a href="/settings">
    <img class="default" src="settings-default.svg"/>
    <img class="hover" src="settings-hover.svg"/>
    <span>Settings</span>
</a>

a img.hover {
    display: none;
}
a img.default {
    display: inherit;
}
a:hover img.hover {
    display: inherit;
}
a:hover img.default {
    display: none;
}

Importing PNG files into Numpy?

I like the build-in pathlib libary because of quick options like directory= Path.cwd() Together with opencv it's quite easy to read pngs to numpy arrays. In this example you can even check the prefix of the image.

from pathlib import Path
import cv2
prefix = "p00"
suffix = ".png"
directory= Path.cwd()
file_names= [subp.name for subp in directory.rglob('*') if  (prefix in subp.name) & (suffix == subp.suffix)]
file_names.sort()
print(file_names)

all_frames= []
for file_name in file_names:
    file_path = str(directory / file_name)
    frame=cv2.imread(file_path)
    all_frames.append(frame)
print(type(all_frames[0]))
print(all_frames[0] [1][1])

Output:

['p000.png', 'p001.png', 'p002.png', 'p003.png', 'p004.png', 'p005.png', 'p006.png', 'p007.png', 'p008.png', 'p009.png']
<class 'numpy.ndarray'>
[255 255 255]

Run a Docker image as a container

  • To list the Docker images

    $ docker images
    
  • If your application wants to run in with port 80, and you can expose a different port to bind locally, say 8080:

    $ docker run -d --restart=always -p 8080:80 image_name:version
    

Facebook user url by id

Accepted answer didn't work for me, this does:

https://www.facebook.com/app_scoped_user_id/10152384781676191

Can I add jars to maven 2 build classpath without installing them?

A quick&dirty batch solution (based on Alex's answer):

libs.bat

@ECHO OFF
FOR %%I IN (*.jar) DO (
echo ^<dependency^>
echo ^<groupId^>local.dummy^</groupId^>
echo ^<artifactId^>%%I^</artifactId^>
echo ^<version^>0.0.1^</version^>
echo ^<scope^>system^</scope^>
echo ^<systemPath^>${project.basedir}/lib/%%I^</systemPath^>
echo ^</dependency^>
)

Execute it like this: libs.bat > libs.txt. Then open libs.txt and copy its content as dependencies.

In my case, I only needed the libraries to compile my code, and this solution was the best for that purpose.

How can I find all *.js file in directory recursively in Linux?

If you just want the list, then you should ask here: http://unix.stackexchange.com

The answer is: cd / && find -name *.js

If you want to implement this, you have to specify the language.

Opening a folder in explorer and selecting a file

Use "/select,c:\file.txt"

Notice there should be a comma after /select instead of space..

Getting assembly name

You could try this code which uses the System.Reflection.AssemblyTitleAttribute.Title property:

((AssemblyTitleAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(AssemblyTitleAttribute), false)).Title;

Count number of rows matching a criteria

Just give a try using subset

nrow(subset(data,condition))

Example

nrow(subset(myData,sCode == "CA"))