Programs & Examples On #Core motion

Core Motion is a framework within Apple's iOS SDK used to access all kind of motion sensor data. Introduced in version 4.0 it is the recommended way of accessing gyroscope or accelerometer data, and since version 5.0 magnetometer (compass) data as well.

How to crop(cut) text files based on starting and ending line-numbers in cygwin?

You can use wc -l to figure out the total # of lines.

You can then combine head and tail to get at the range you want. Let's assume the log is 40,000 lines, you want the last 1562 lines, then of those you want the first 838. So:

tail -1562 MyHugeLogFile.log | head -838 | ....

Or there's probably an easier way using sed or awk.

Nested select statement in SQL Server

You need to alias the subquery.

SELECT name FROM (SELECT name FROM agentinformation) a  

or to be more explicit

SELECT a.name FROM (SELECT name FROM agentinformation) a  

HTML <select> selected option background-color CSS style

We Can override the blue color in to our custom color It works for Internet Explorer, Firefox and Chrome:

By using this below following CSS:

option: checked, option: hover {
    Color: #ffffff;
    background: #614767 repeat url("data:image/gif;base64,R0lGODlh8ACgAPAAAGFGZQAAACH5BAAAAAAALAAAAADwAKAAAAL+hI+py+0Po5y02ouz3rz7D4biSJbmiabqyrbuC8fyTNf2jef6zvf+DwwKh8Si8YhMKpfMpvMJjUqn1Kr1is1qt9yu9wsOi8fksvmMTqvX7Lb7DY/L5/S6/Y7P6/f8vv8PGCg4SFhoeIiYqLjI2Oj4CBkpOUlZaXmJmam5ydnp+QkaKjpKWmp6ipqqusra6voKGys7S1tre4ubq7vL2+v7CxwsPExcbHyMnKy8zNzs/AwdLT1NXW19jZ2tvc3d7f0NHi4+Tl5ufo6err7O3u7+Dh8vP09fb3+Pn6+/z9/v/w8woMCBBAsaPIgwocKFDBs6fAgxosSJFCtavIhRVgEAOw");
}

R: Select values from data table in range

Lots of options here, but one of the easiest to follow is subset. Consider:

> set.seed(43)
> df <- data.frame(name = sample(letters, 100, TRUE), date = sample(1:500, 100, TRUE))
> 
> subset(df, date > 5 & date < 15)
   name date
11    k   10
67    y   12
86    e    8

You can also insert logic directly into the index for your data.frame. The comma separates the rows from columns. We just have to remember that R indexes rows first, then columns. So here we are saying rows with date > 5 & < 15 and then all columns:

df[df$date > 5 & df$date < 15 ,]

I'd also recommend checking out the help pages for subset, ?subset and the logical operators ?"&"

Creating an empty Pandas DataFrame, then filling it?

Here's a couple of suggestions:

Use date_range for the index:

import datetime
import pandas as pd
import numpy as np

todays_date = datetime.datetime.now().date()
index = pd.date_range(todays_date-datetime.timedelta(10), periods=10, freq='D')

columns = ['A','B', 'C']

Note: we could create an empty DataFrame (with NaNs) simply by writing:

df_ = pd.DataFrame(index=index, columns=columns)
df_ = df_.fillna(0) # with 0s rather than NaNs

To do these type of calculations for the data, use a numpy array:

data = np.array([np.arange(10)]*3).T

Hence we can create the DataFrame:

In [10]: df = pd.DataFrame(data, index=index, columns=columns)

In [11]: df
Out[11]: 
            A  B  C
2012-11-29  0  0  0
2012-11-30  1  1  1
2012-12-01  2  2  2
2012-12-02  3  3  3
2012-12-03  4  4  4
2012-12-04  5  5  5
2012-12-05  6  6  6
2012-12-06  7  7  7
2012-12-07  8  8  8
2012-12-08  9  9  9

MySQL with Node.js

Here is production code which may help you.

Package.json

{
  "name": "node-mysql",
  "version": "0.0.1",
  "dependencies": {
    "express": "^4.10.6",
    "mysql": "^2.5.4"
  }
}

Here is Server file.

var express   =    require("express");
var mysql     =    require('mysql');
var app       =    express();

var pool      =    mysql.createPool({
    connectionLimit : 100, //important
    host     : 'localhost',
    user     : 'root',
    password : '',
    database : 'address_book',
    debug    :  false
});

function handle_database(req,res) {

    pool.getConnection(function(err,connection){
        if (err) {
          connection.release();
          res.json({"code" : 100, "status" : "Error in connection database"});
          return;
        }   

        console.log('connected as id ' + connection.threadId);

        connection.query("select * from user",function(err,rows){
            connection.release();
            if(!err) {
                res.json(rows);
            }           
        });

        connection.on('error', function(err) {      
              res.json({"code" : 100, "status" : "Error in connection database"});
              return;     
        });
  });
}

app.get("/",function(req,res){-
        handle_database(req,res);
});

app.listen(3000);

Reference : https://codeforgeek.com/2015/01/nodejs-mysql-tutorial/

How to fill a Javascript object literal with many static key/value pairs efficiently?

It works fine with the object literal notation:

var map = { key : { "aaa", "rrr" }, 
            key2: { "bbb", "ppp" } // trailing comma leads to syntax error in IE!
          }

Btw, the common way to instantiate arrays

var array = [];
// directly with values:
var array = [ "val1", "val2", 3 /*numbers may be unquoted*/, 5, "val5" ];

and objects

var object = {};

Also you can do either:

obj.property     // this is prefered but you can also do
obj["property"]  // this is the way to go when you have the keyname stored in a var

var key = "property";
obj[key] // is the same like obj.property

How do I add an element to array in reducer of React native redux?

I have a sample

import * as types from '../../helpers/ActionTypes';

var initialState = {
  changedValues: {}
};
const quickEdit = (state = initialState, action) => {

  switch (action.type) {

    case types.PRODUCT_QUICKEDIT:
      {
        const item = action.item;
        const changedValues = {
          ...state.changedValues,
          [item.id]: item,
        };

        return {
          ...state,
          loading: true,
          changedValues: changedValues,
        };
      }
    default:
      {
        return state;
      }
  }
};

export default quickEdit;

Smooth scrolling with just pure css

You need to use the target selector.

Here is a fiddle with another example: http://jsfiddle.net/YYPKM/3/

How can a windows service programmatically restart itself?

I don't think it can. When a service is "stopped", it gets totally unloaded.

Well, OK, there's always a way I suppose. For instance, you could create a detached process to stop the service, then restart it, then exit.

Angularjs error Unknown provider

Make sure you are loading those modules (myApp.services and myApp.directives) as dependencies of your main app module, like this:

angular.module('myApp', ['myApp.directives', 'myApp.services']);

plunker: http://plnkr.co/edit/wxuFx6qOMfbuwPq1HqeM?p=preview

sql searching multiple words in a string

In SQL Server 2005+ with Full-Text indexing switched on, I'd do the following:

SELECT *
  FROM T
 WHERE CONTAINS(C, '"David" OR "Robi" OR "Moses"');

If you wanted your search to bring back results where the result is prefixed with David, Robi or Moses you could do:

SELECT *
  FROM T
 WHERE CONTAINS(C, '"David*" OR "Robi*" OR "Moses*"');

How to change the color of progressbar in C# .NET 3.5?

OK, it took me a while to read all the answers and links. Here's what I got out of them:

Sample Results

The accepted answer disables visual styles, it does allow you to set the color to anything you want, but the result looks plain:

enter image description here

Using the following method, you can get something like this instead:

enter image description here

How To

First, include this if you haven't: using System.Runtime.InteropServices;

Second, you can either create this new class, or put its code into an existing static non-generic class:

public static class ModifyProgressBarColor
{
    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
    static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr w, IntPtr l);
    public static void SetState(this ProgressBar pBar, int state)
    {
        SendMessage(pBar.Handle, 1040, (IntPtr)state, IntPtr.Zero);
    }
}

Now, to use it, simply call:

progressBar1.SetState(2);

Note the second parameter in SetState, 1 = normal (green); 2 = error (red); 3 = warning (yellow).

Hope it helps!

How do I read all classes from a Java package in the classpath?

Here is another option, slight modification to another answer in above/below:

Reflections reflections = new Reflections("com.example.project.package", 
    new SubTypesScanner(false));
Set<Class<? extends Object>> allClasses = 
    reflections.getSubTypesOf(Object.class);

Print multiple arguments in Python

This is what I do:

print("Total score for " + name + " is " + score)

Remember to put a space after for and before and after is.

Why am I getting a NoClassDefFoundError in Java?

The technique below helped me many times:

System.out.println(TheNoDefFoundClass.class.getProtectionDomain().getCodeSource().getLocation());

where the TheNoDefFoundClass is the class that might be "lost" due to a preference for an older version of the same library used by your program. This most frequently happens with the cases, when the client software is being deployed into a dominant container, armed with its own classloaders and tons of ancient versions of most popular libs.

What is the point of the diamond operator (<>) in Java 7?

When you write List<String> list = new LinkedList();, compiler produces an "unchecked" warning. You may ignore it, but if you used to ignore these warnings you may also miss a warning that notifies you about a real type safety problem.

So, it's better to write a code that doesn't generate extra warnings, and diamond operator allows you to do it in convenient way without unnecessary repetition.

Adding List<t>.add() another list

List<T>.Add adds a single element. Instead, use List<T>.AddRange to add multiple values.

Additionally, List<T>.AddRange takes an IEnumerable<T>, so you don't need to convert tripDetails into a List<TripDetails>, you can pass it directly, e.g.:

tripDetailsCollection.AddRange(tripDetails);

Chrome doesn't delete session cookies

This maybe because Chrome is still running in background after you close the browser. Try to disable this feature by doing following:

  1. Open chrome://settings/
  2. Click "Show advanced settings ..."
  3. Navigate down to System section and disable "Continue running background apps when Google Chrome is closed". This will force Chrome to close completely and then it will delete session cookies.

However, I think Chrome should check and delete previous session cookies at it starting instead of closing.

Creating table variable in SQL server 2008 R2

@tableName Table variables are alive for duration of the script running only i.e. they are only session level objects.

To test this, open two query editor windows under sql server management studio, and create table variables with same name but different structures. You will get an idea. The @tableName object is thus temporary and used for our internal processing of data, and it doesn't contribute to the actual database structure.

There is another type of table object which can be created for temporary use. They are #tableName objects declared like similar create statement for physical tables:

Create table #test (Id int, Name varchar(50))

This table object is created and stored in temp database. Unlike the first one, this object is more useful, can store large data and takes part in transactions etc. These tables are alive till the connection is open. You have to drop the created object by following script before re-creating it.

IF OBJECT_ID('tempdb..#test') IS NOT NULL
  DROP TABLE #test 

Hope this makes sense !

I am getting "java.lang.ClassNotFoundException: com.google.gson.Gson" error even though it is defined in my classpath

In case of a JSP/Servlet webapplication, you just need to drop 3rd party JAR files in /WEB-INF/lib folder. If the project is a Dynamic Web Project, then Eclipse will automatically take care about setting the buildpath right as well. You do not need to fiddle with Eclipse buildpath. Don't forget to undo it all.

How to convert a Kotlin source file to a Java source file

you can go to Tools > Kotlin > Show kotlin bytecode

enter image description here

enter image description here

enter image description here

Replacing some characters in a string with another character

You might find this link helpful:

http://tldp.org/LDP/abs/html/string-manipulation.html

In general,

To replace the first match of $substring with $replacement:

${string/substring/replacement}

To replace all matches of $substring with $replacement:

${string//substring/replacement}

EDIT: Note that this applies to a variable named $string.

Visual Studio 2017 errors on standard headers

This problem may also happen if you have a unit test project that has a different C++ version than the project you want to test.

Example:

  • EXE with C++ 17 enabled explicitly
  • Unit Test with C++ version set to "Default"

Solution: change the Unit Test to C++17 as well.

Screenshot

How to return a result from a VBA function

VBA functions treat the function name itself as a sort of variable. So instead of using a "return" statement, you would just say:

test = 1

Notice, though, that this does not break out of the function. Any code after this statement will also be executed. Thus, you can have many assignment statements that assign different values to test, and whatever the value is when you reach the end of the function will be the value returned.

Returning string from C function

I came across this thread while working on my understanding of Cython. My extension to the original question might be of use to others working at the C / Cython interface. So this is the extension of the original question: how do I return a string from a C function, making it available to Cython & thus to Python?

For those not familiar with it, Cython allows you to statically type Python code that you need to speed up. So the process is, enjoy writing Python :), find its a bit slow somewhere, profile it, calve off a function or two and cythonize them. Wow. Close to C speed (it compiles to C) Fixed. Yay. The other use is importing C functions or libraries into Python as done here.

This will print a string and return the same or another string to Python. There are 3 files, the c file c_hello.c, the cython file sayhello.pyx, and the cython setup file sayhello.pyx. When they are compiled using python setup.py build_ext --inplace they generate a shared library file that can be imported into python or ipython and the function sayhello.hello run.

c_hello.c

#include <stdio.h>

char *c_hello() {
  char *mystr = "Hello World!\n";
  return mystr;
  // return "this string";  // alterative
}

sayhello.pyx

cdef extern from "c_hello.c":
    cdef char* c_hello()

def hello():
    return c_hello()

setup.py

from setuptools import setup
from setuptools.extension import Extension
from Cython.Distutils import build_ext
from Cython.Build import cythonize


ext_modules = cythonize([Extension("sayhello", ["sayhello.pyx"])])


setup(
name = 'Hello world app',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules
)

Print array elements on separate lines in Bash?

I tried the answers here in a giant for...if loop, but didn't get any joy - so I did it like this, maybe messy but did the job:

 # EXP_LIST2 is iterated    
 # imagine a for loop
     EXP_LIST="List item"    
     EXP_LIST2="$EXP_LIST2 \n $EXP_LIST"
 done 
 echo -e $EXP_LIST2

although that added a space to the list, which is fine - I wanted it indented a bit. Also presume the "\n" could be printed in the original $EP_LIST.

Reset MySQL root password using ALTER USER statement after install on Mac

Mysql 5.7.24 get root first login

step 1: get password from log

 grep root@localhost /var/log/mysqld.log
    Output
        2019-01-17T09:58:34.459520Z 1 [Note] A temporary password is generated for root@localhost: wHkJHUxeR4)w

step 2: login with him to mysql

mysql -uroot -p'wHkJHUxeR4)w'

step 3: you put new root password

SET PASSWORD = PASSWORD('xxxxx');

you get ERROR 1819 (HY000): Your password does not satisfy the current policy requirements

how fix it?

run this SET GLOBAL validate_password_policy=LOW;

Try Again SET PASSWORD = PASSWORD('xxxxx');

Finding last occurrence of substring in string, replacing that

This should do it

old_string = "this is going to have a full stop. some written sstuff!"
k = old_string.rfind(".")
new_string = old_string[:k] + ". - " + old_string[k+1:]

No generated R.java file in my project

I Had a similar problem

Best way to Identify this problem is to identify Lint warnings:: *Right Click on project > Android Tools > Run Lint : Common Errors*

  • That helps us to show some errors through which we can fix things which make R.java regenerated once again
  • By following above steps i identified that i had added some image files that i have not used -> I removed them -> That fixed the problem !

Finally Clean the project !

How to find the socket connection state in C?

You could call getsockopt just like the following:

int error = 0;
socklen_t len = sizeof (error);
int retval = getsockopt (socket_fd, SOL_SOCKET, SO_ERROR, &error, &len);

To test if the socket is up:

if (retval != 0) {
    /* there was a problem getting the error code */
    fprintf(stderr, "error getting socket error code: %s\n", strerror(retval));
    return;
}

if (error != 0) {
    /* socket has a non zero error status */
    fprintf(stderr, "socket error: %s\n", strerror(error));
}

Is it possible to force Excel recognize UTF-8 CSV files automatically?

Yes it is possible. When writing the stream creating the csv, the first thing to do is this:

myStream.Write(Encoding.UTF8.GetPreamble(), 0, Encoding.UTF8.GetPreamble().Length)

How do you iterate through every file/directory recursively in standard C++?

A fast solution is using C's Dirent.h library.

Working code fragment from Wikipedia:

#include <stdio.h>
#include <dirent.h>

int listdir(const char *path) {
    struct dirent *entry;
    DIR *dp;

    dp = opendir(path);
    if (dp == NULL) {
        perror("opendir: Path does not exist or could not be read.");
        return -1;
    }

    while ((entry = readdir(dp)))
        puts(entry->d_name);

    closedir(dp);
    return 0;
}

Is it possible to add an array or object to SharedPreferences on Android

You can use putStringSet

This allow you to save a HashSet in your preferences, just like this:

Save

Set<String> values;

SharedPreferences sharedPref = 
    mContext.getSharedPreferences(PREF_KEY, Context.MODE_PRIVATE);

Editor editor = sharedPref.edit();

editor.putStringSet("YOUR_KEY", values);
editor.apply();

Retrive

SharedPreferences sharedPref = 
    mContext.getSharedPreferences(PREF_KEY, Context.MODE_PRIVATE);

Editor editor = sharedPref.edit();

Set<String> newList = editor.getStringSet("YOUR_KEY", null);

The putStringSet allow just a Set and this is an unordered list.

Javascript/Jquery to change class onclick?

I would think this: http://jsfiddle.net/Skooljester/S3y5p/1/ should do it. If I don't have the class names 100% correct you can just change them to whatever you need them to be.

PHP String to Float

Well, if user write 1,00,000 then floatvar will show error. So -

floatval(preg_replace("/[^-0-9\.]/","",$input));

This is much more reliable.

Usage :

$input = '1,03,24,23,434,500.6798633 this';
echo floatval(preg_replace("/[^-0-9\.]/","",$input));

jQuery addClass onClick

Try to make your css more specific so that the new (green) style is more specific than the previous one, so that it worked for me!

For example, you might use in css:

button:active {/*your style here*/}

Instead of (probably not working):

.active {/*style*/} (.active is not a pseudo-class)

Hope it helps!

Email Address Validation for ASP.NET

Any script tags posted on an ASP.NET web form will cause your site to throw and unhandled exception.

You can use a asp regex validator to confirm input, just ensure you wrap your code behind method with a if(IsValid) clause in case your javascript is bypassed. If your client javascript is bypassed and script tags are posted to your asp.net form, asp.net will throw a unhandled exception.

You can use something like:

<asp:RegularExpressionValidator ID="regexEmailValid" runat="server" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="tbEmail" ErrorMessage="Invalid Email Format"></asp:RegularExpressionValidator>

Creating a "Hello World" WebSocket example

I couldnt find a simple working example anywhere (as of Jan 19), so here is an updated version. I have chrome version 71.0.3578.98.

C# Websocket server :

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;

namespace WebSocketServer
{
    class Program
    {
    static Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
    static private string guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";

    static void Main(string[] args)
    {
        serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8080));
        serverSocket.Listen(1); //just one socket
        serverSocket.BeginAccept(null, 0, OnAccept, null);
        Console.Read();
    }

    private static void OnAccept(IAsyncResult result)
    {
        byte[] buffer = new byte[1024];
        try
        {
            Socket client = null;
            string headerResponse = "";
            if (serverSocket != null && serverSocket.IsBound)
            {
                client = serverSocket.EndAccept(result);
                var i = client.Receive(buffer);
                headerResponse = (System.Text.Encoding.UTF8.GetString(buffer)).Substring(0, i);
                // write received data to the console
                Console.WriteLine(headerResponse);
                Console.WriteLine("=====================");
            }
            if (client != null)
            {
                /* Handshaking and managing ClientSocket */
                var key = headerResponse.Replace("ey:", "`")
                          .Split('`')[1]                     // dGhlIHNhbXBsZSBub25jZQ== \r\n .......
                          .Replace("\r", "").Split('\n')[0]  // dGhlIHNhbXBsZSBub25jZQ==
                          .Trim();

                // key should now equal dGhlIHNhbXBsZSBub25jZQ==
                var test1 = AcceptKey(ref key);

                var newLine = "\r\n";

                var response = "HTTP/1.1 101 Switching Protocols" + newLine
                     + "Upgrade: websocket" + newLine
                     + "Connection: Upgrade" + newLine
                     + "Sec-WebSocket-Accept: " + test1 + newLine + newLine
                     //+ "Sec-WebSocket-Protocol: chat, superchat" + newLine
                     //+ "Sec-WebSocket-Version: 13" + newLine
                     ;

                client.Send(System.Text.Encoding.UTF8.GetBytes(response));
                var i = client.Receive(buffer); // wait for client to send a message
                string browserSent = GetDecodedData(buffer, i);
                Console.WriteLine("BrowserSent: " + browserSent);

                Console.WriteLine("=====================");
                //now send message to client
                client.Send(GetFrameFromString("This is message from server to client."));
                System.Threading.Thread.Sleep(10000);//wait for message to be sent
            }
        }
        catch (SocketException exception)
        {
            throw exception;
        }
        finally
        {
            if (serverSocket != null && serverSocket.IsBound)
            {
                serverSocket.BeginAccept(null, 0, OnAccept, null);
            }
        }
    }

    public static T[] SubArray<T>(T[] data, int index, int length)
    {
        T[] result = new T[length];
        Array.Copy(data, index, result, 0, length);
        return result;
    }

    private static string AcceptKey(ref string key)
    {
        string longKey = key + guid;
        byte[] hashBytes = ComputeHash(longKey);
        return Convert.ToBase64String(hashBytes);
    }

    static SHA1 sha1 = SHA1CryptoServiceProvider.Create();
    private static byte[] ComputeHash(string str)
    {
        return sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(str));
    }

    //Needed to decode frame
    public static string GetDecodedData(byte[] buffer, int length)
    {
        byte b = buffer[1];
        int dataLength = 0;
        int totalLength = 0;
        int keyIndex = 0;

        if (b - 128 <= 125)
        {
            dataLength = b - 128;
            keyIndex = 2;
            totalLength = dataLength + 6;
        }

        if (b - 128 == 126)
        {
            dataLength = BitConverter.ToInt16(new byte[] { buffer[3], buffer[2] }, 0);
            keyIndex = 4;
            totalLength = dataLength + 8;
        }

        if (b - 128 == 127)
        {
            dataLength = (int)BitConverter.ToInt64(new byte[] { buffer[9], buffer[8], buffer[7], buffer[6], buffer[5], buffer[4], buffer[3], buffer[2] }, 0);
            keyIndex = 10;
            totalLength = dataLength + 14;
        }

        if (totalLength > length)
            throw new Exception("The buffer length is small than the data length");

        byte[] key = new byte[] { buffer[keyIndex], buffer[keyIndex + 1], buffer[keyIndex + 2], buffer[keyIndex + 3] };

        int dataIndex = keyIndex + 4;
        int count = 0;
        for (int i = dataIndex; i < totalLength; i++)
        {
            buffer[i] = (byte)(buffer[i] ^ key[count % 4]);
            count++;
        }

        return Encoding.ASCII.GetString(buffer, dataIndex, dataLength);
    }

    //function to create  frames to send to client 
    /// <summary>
    /// Enum for opcode types
    /// </summary>
    public enum EOpcodeType
    {
        /* Denotes a continuation code */
        Fragment = 0,

        /* Denotes a text code */
        Text = 1,

        /* Denotes a binary code */
        Binary = 2,

        /* Denotes a closed connection */
        ClosedConnection = 8,

        /* Denotes a ping*/
        Ping = 9,

        /* Denotes a pong */
        Pong = 10
    }

    /// <summary>Gets an encoded websocket frame to send to a client from a string</summary>
    /// <param name="Message">The message to encode into the frame</param>
    /// <param name="Opcode">The opcode of the frame</param>
    /// <returns>Byte array in form of a websocket frame</returns>
    public static byte[] GetFrameFromString(string Message, EOpcodeType Opcode = EOpcodeType.Text)
    {
        byte[] response;
        byte[] bytesRaw = Encoding.Default.GetBytes(Message);
        byte[] frame = new byte[10];

        int indexStartRawData = -1;
        int length = bytesRaw.Length;

        frame[0] = (byte)(128 + (int)Opcode);
        if (length <= 125)
        {
            frame[1] = (byte)length;
            indexStartRawData = 2;
        }
        else if (length >= 126 && length <= 65535)
        {
            frame[1] = (byte)126;
            frame[2] = (byte)((length >> 8) & 255);
            frame[3] = (byte)(length & 255);
            indexStartRawData = 4;
        }
        else
        {
            frame[1] = (byte)127;
            frame[2] = (byte)((length >> 56) & 255);
            frame[3] = (byte)((length >> 48) & 255);
            frame[4] = (byte)((length >> 40) & 255);
            frame[5] = (byte)((length >> 32) & 255);
            frame[6] = (byte)((length >> 24) & 255);
            frame[7] = (byte)((length >> 16) & 255);
            frame[8] = (byte)((length >> 8) & 255);
            frame[9] = (byte)(length & 255);

            indexStartRawData = 10;
        }

        response = new byte[indexStartRawData + length];

        int i, reponseIdx = 0;

        //Add the frame bytes to the reponse
        for (i = 0; i < indexStartRawData; i++)
        {
            response[reponseIdx] = frame[i];
            reponseIdx++;
        }

        //Add the data bytes to the response
        for (i = 0; i < length; i++)
        {
            response[reponseIdx] = bytesRaw[i];
            reponseIdx++;
        }

        return response;
    }
}
}

Client html and javascript:

_x000D_
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"_x000D_
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
    <script type="text/javascript">_x000D_
        var socket = new WebSocket('ws://localhost:8080/websession');_x000D_
        socket.onopen = function() {_x000D_
           // alert('handshake successfully established. May send data now...');_x000D_
     socket.send("Hi there from browser.");_x000D_
        };_x000D_
  socket.onmessage = function (evt) {_x000D_
                //alert("About to receive data");_x000D_
                var received_msg = evt.data;_x000D_
                alert("Message received = "+received_msg);_x000D_
            };_x000D_
        socket.onclose = function() {_x000D_
            alert('connection closed');_x000D_
        };_x000D_
    </script>_x000D_
</head>_x000D_
<body>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Using await outside of an async function

There is always this of course:

(async () => {
    await ...

    // all of the script.... 

})();
// nothing else

This makes a quick function with async where you can use await. It saves you the need to make an async function which is great! //credits Silve2611

Laravel 5 Carbon format datetime

Try that:

$createdAt = Carbon::parse(date_format($item['created_at'],'d/m/Y H:i:s');
$createdAt= $createdAt->format('M d Y');

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

After commenting @Marcin answer, I have more carefully checked one of my students code where I found the same weird behavior, even after only 2 epochs ! (So @Marcin's explanation was not very likely in my case).

And I found that the answer is actually very simple: the accuracy computed with the Keras method evaluate is just plain wrong when using binary_crossentropy with more than 2 labels. You can check that by recomputing the accuracy yourself (first call the Keras method "predict" and then compute the number of correct answers returned by predict): you get the true accuracy, which is much lower than the Keras "evaluate" one.

how to get the selected index of a drop down

You can also use :checked for <select> elements

e.g.,

document.querySelector('select option:checked')
document.querySelector('select option:checked').getAttribute('value')

You don't even have to get the index and then reference the element by its sibling index.

Succeeded installing but could not start apache 2.4 on my windows 7 system

I was also facing the same issue, then i tried restarting my system after every change and it worked for me:

  1. Uninstall Apache2.4 in cmd prompt (run administrator) with the command: httpd -k uninstall.
  2. Restart the system.
  3. open cmd prompt (run administrator) with the command: httpd -k install.
  4. Then httpd -k install.

Hope you find useful.

How can I format bytes a cell in Excel as KB, MB, GB etc?

It is a bit of a "brute force" but works ;)

=IF(E4/1000<1;CONCATENATE(E4;" bps");IF(E4/1000<1000;CONCATENATE(ROUND(E4/1000;2);" kbps");IF(E4/1000000<1000;CONCATENATE(ROUND(E4/1000000;2);" mbps");IF(E4/1000000000<1000;CONCATENATE(ROUND(E4/1000000000;2);" gbps")))))

enter image description here

Header div stays at top, vertical scrolling div below with scrollbar only attached to that div

Found the flex magic.

Here's an example of how to do a fixed header and a scrollable content. Code:

<!DOCTYPE html>
<html style="height: 100%">
  <head>
    <meta charset=utf-8 />
    <title>Holy Grail</title>
    <!-- Reset browser defaults -->
    <link rel="stylesheet" href="reset.css">
  </head>
  <body style="display: flex; height: 100%; flex-direction: column">
    <div>HEADER<br/>------------
    </div>
    <div style="flex: 1; overflow: auto">
        CONTENT - START<br/>
        <script>
        for (var i=0 ; i<1000 ; ++i) {
          document.write(" Very long content!");
        }
        </script>
        <br/>CONTENT - END
    </div>
  </body>
</html>

* The advantage of the flex solution is that the content is independent of other parts of the layout. For example, the content doesn't need to know height of the header.

For a full Holy Grail implementation (header, footer, nav, side, and content), using flex display, go to here.

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

I regularly use IntelliJ, PHPStorm and WebStorm. Would love to only use IntelliJ. As pointed out by the vendor the "Open Directory" functionality not being in IntelliJ is painful.

Now for the rub part; I have tried using IntelliJ as my single IDE and have found performance to be terrible compared to the lighter weight versions. Intellisense is almost useless in IntelliJ compared to WebStorm.

Position a div container on the right side

Is this what you wanted? - http://jsfiddle.net/jomanlk/x5vyC/3/

Floats on both sides now

#wrapper{
    background:red;
    overflow:auto;
}

#c1{
   float:left;
   background:blue;
}

#c2{
    background:green;
    float:right;
}?

<div id="wrapper">
    <div id="c1">con1</div>
    <div id="c2">con2</div>
</div>?

Remove a data connection from an Excel 2010 spreadsheet in compatibility mode

I manage to solve this in excel 97-2003, in a file with .xls extension this way: I went to the page where I had the linked data, with the cursor over the imported data table, go to tab Design --> External Data Table --> Unlink Unlink all tables (conections), delete all conections in Data --> Conections --> Conections save your work and done! regards, Dan

Multi-key dictionary in c#?

Tuples will be (are) in .Net 4.0 Until then, you can also use a

 Dictionary<key1, Dictionary<key2, TypeObject>> 

or, creating a custom collection class to represent this...

 public class TwoKeyDictionary<K1, K2, T>: 
        Dictionary<K1, Dictionary<K2, T>> { }

or, with three keys...

public class ThreeKeyDictionary<K1, K2, K3, T> :
    Dictionary<K1, Dictionary<K2, Dictionary<K3, T>>> { }

The model backing the <Database> context has changed since the database was created

This error can indicate an issue with your connection string and whether your connection string name matches the Database context declaration.

I had this error because I had named the local database wrongly (silly mistake) and the name of the connection string in web.config of "DefaultConnection" did not match the MyDbContext i.e.

public MyDbContext(): base("DefaultConnection")
{}


<connectionStrings>
    <add name="DefaultConnection" ...
  </connectionStrings>

Android "hello world" pushnotification example

Overview of gcm: You send a request to google server from your android phone. You receive a registration id as a response. You will then have to send this registration id to the server from where you wish to send notifications to the mobile. Using this registration id you can then send notification to the device.

Answer:

  1. To send a notification you send the data(message) with the registration id of the device to https://android.googleapis.com/gcm/send. (use curl in php).
  2. To receive notification and registration etc, thats all you will be requiring.
  3. You will have to store the registration id on the device as well as on server. If you use GCM.jar the registration id is stored in preferences. If you wish you can save it in your local database as well.

OpenCV error: the function is not implemented

Don't waste your time trying to resolve this issue, this was made clear by the makers themselves. Instead of cv2.imshow() use this:

img = cv2.imread('path_to_image')
plt.imshow(img, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([])  # to hide tick values on X and Y axis
plt.show()

How to sort a NSArray alphabetically?

The other answers provided here mention using @selector(localizedCaseInsensitiveCompare:) This works great for an array of NSString, however if you want to extend this to another type of object, and sort those objects according to a 'name' property, you should do this instead:

NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
sortedArray=[anArray sortedArrayUsingDescriptors:@[sort]];

Your objects will be sorted according to the name property of those objects.

If you want the sorting to be case insensitive, you would need to set the descriptor like this

NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)];

How to store arrays in MySQL?

MySQL 5.7 now provides a JSON data type. This new datatype provides a convenient new way to store complex data: lists, dictionaries, etc.

That said, arrays don't map well databases which is why object-relational maps can be quite complex. Historically people have stored lists/arrays in MySQL by creating a table that describes them and adding each value as its own record. The table may have only 2 or 3 columns, or it may contain many more. How you store this type of data really depends on characteristics of the data.

For example, does the list contain a static or dynamic number of entries? Will the list stay small, or is it expected to grow to millions of records? Will there be lots of reads on this table? Lots of writes? Lots of updates? These are all factors that need to be considered when deciding how to store collections of data.

Also, Key/Value data stores, Document stores such as Cassandra, MongoDB, Redis etc provide a good solution as well. Just be aware of where the data is actually being stored (if its being stored on disk or in memory). Not all of your data needs to be in the same database. Some data does not map well to a relational database and you may have reasons for storing it elsewhere, or you may want to use an in-memory key:value database as a hot-cache for data stored on disk somewhere or as an ephemeral storage for things like sessions.

Is Python strongly typed?

TLDR;

Python typing is Dynamic so you can change a string variable to an int

x = 'somestring'
x = 50

Python typing is Strong so you can't merge types:

'foo' + 3 --> TypeError: cannot concatenate 'str' and 'int' objects

In weakly-typed Javascript this happens...

 'foo'+3 = 'foo3'

Regarding Type Inference

Java forces you to explicitly declare your object types

int x = 50;

Kotlin uses inference to realize it's an int

x = 50

But because both languages use static types, x can't be changed from an int. Neither language would allow a dynamic change like

x = 50
x = 'now a string'

how to clear the screen in python

If you mean the screen where you have that interpreter prompt >>> you can do CTRL+L on Bash shell can help. Windows does not have equivalent. You can do

import os
os.system('cls')  # on windows

or

os.system('clear')  # on linux / os x

Can you use CSS to mirror/flip text?

For cross browser compatibility create this class

.mirror-icon:before {
    -webkit-transform: scale(-1, 1);
    -moz-transform: scale(-1, 1);
    -ms-transform: scale(-1, 1);
    -o-transform: scale(-1, 1);
    transform: scale(-1, 1);
}

And add it to your icon class, i.e.

<i class="icon-search mirror-icon"></i>

to get a search icon with the handle on the left

How to convert date to timestamp in PHP?


This method works on both Windows and Unix and is time-zone aware, which is probably what you want if you work with dates.

If you don't care about timezone, or want to use the time zone your server uses:

$d = DateTime::createFromFormat('d-m-Y H:i:s', '22-09-2008 00:00:00');
if ($d === false) {
    die("Incorrect date string");
} else {
    echo $d->getTimestamp();
}

1222093324 (This will differ depending on your server time zone...)


If you want to specify in which time zone, here EST. (Same as New York.)

$d = DateTime::createFromFormat(
    'd-m-Y H:i:s',
    '22-09-2008 00:00:00',
    new DateTimeZone('EST')
);

if ($d === false) {
    die("Incorrect date string");
} else {
    echo $d->getTimestamp();
}

1222093305


Or if you want to use UTC. (Same as "GMT".)

$d = DateTime::createFromFormat(
    'd-m-Y H:i:s',
    '22-09-2008 00:00:00',
    new DateTimeZone('UTC')
);

if ($d === false) {
    die("Incorrect date string");
} else {
    echo $d->getTimestamp();
}

1222093289


Regardless, it's always a good starting point to be strict when parsing strings into structured data. It can save awkward debugging in the future. Therefore I recommend to always specify date format.

Opening port 80 EC2 Amazon web services

Some quick tips:

  1. Disable the inbuilt firewall on your Windows instances.
  2. Use the IP address rather than the DNS entry.
  3. Create a security group for tcp ports 1 to 65000 and for source 0.0.0.0/0. It's obviously not to be used for production purposes, but it will help avoid the Security Groups as a source of problems.
  4. Check that you can actually ping your server. This may also necessitate some Security Group modification.

How do I check when a UITextField changes?

Swift 3

 textField.addTarget(self, action: #selector(ViewController.textFieldDidChange(sender:)), for: UIControlEvents.editingChanged)

Apache is not running from XAMPP Control Panel ( Error: Apache shutdown unexpectedly. This may be due to a blocked port)

Had the same problem and none of the above solutions worked. So, by reading carefully the logs, I found this message :

10:55:42 [Apache] Port 443 in use by ""C:\Program Files (x86)\VMware\VMware Workstation\vmware-hostd.exe" -u "C:\ProgramData\VMware\hostd\config.xml"" with PID 1908!

enter image description here

In my case, I had just to stop the VMWare service which was running automatically.

enter image description here

The key is to read carefully the message given by XAMPP Panel when started.

Hope this help!

How to create a numpy array of all True or all False?

If it doesn't have to be writeable you can create such an array with np.broadcast_to:

>>> import numpy as np
>>> np.broadcast_to(True, (2, 5))
array([[ True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True]], dtype=bool)

If you need it writable you can also create an empty array and fill it yourself:

>>> arr = np.empty((2, 5), dtype=bool)
>>> arr.fill(1)
>>> arr
array([[ True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True]], dtype=bool)

These approaches are only alternative suggestions. In general you should stick with np.full, np.zeros or np.ones like the other answers suggest.

Iterate keys in a C++ map

Without BOOST, directly using key and value

for(auto const& [key, value]: m_map)
    {
    std::cout<<" key="<<key;
    std::cout<<" value="<<value<<std::endl;
    }

How do I check to see if a value is an integer in MySQL?

I have tried using the regular expressions listed above, but they do not work for the following:

SELECT '12 INCHES' REGEXP '^(-|\\+){0,1}([0-9]+\\.[0-9]*|[0-9]*\\.[0-9]+|[0-9]+)$' FROM ...

The above will return 1 (TRUE), meaning the test of the string '12 INCHES' against the regular expression above, returns TRUE. It looks like a number based on the regular expression used above. In this case, because the 12 is at the beginning of the string, the regular expression interprets it as a number.

The following will return the right value (i.e. 0) because the string starts with characters instead of digits

SELECT 'TOP 10' REGEXP '^(-|\\+){0,1}([0-9]+\\.[0-9]*|[0-9]*\\.[0-9]+|[0-9]+)$' FROM ...

The above will return 0 (FALSE) because the beginning of the string is text and not numeric.

However, if you are dealing with strings that have a mix of numbers and letters that begin with a number, you will not get the results you want. REGEXP will interpret the string as a valid number when in fact it is not.

How do I load a PHP file into a variable?

ob_start();
include "yourfile.php";
$myvar = ob_get_clean();

ob_get_clean()

Error when deploying an artifact in Nexus

I had the same problem today with the addition "Return code is: 400, ReasonPhrase: Bad Request." which turned out to be the "artifact is already deployed with that version if it is a release" problem from answer above enter link description here

One solution not mentioned yet is to configure Nexus to allow redeployment into a Release repository. Maybe not a best practice, because this is set for a reason, you nevertheless could go to "Access Settings" in your Nexus repositories´ "Configuration"-Tab and set the "Deployment Policy" to "Allow Redeploy".

How can I break from a try/catch block without throwing an exception in Java

You can always do it with a break from a loop construct or a labeled break as specified in aioobies answer.

public static void main(String[] args) {
    do {
        try {
            // code..
            if (condition)
                break;
            // more code...
        } catch (Exception e) {

        }
    } while (false);
}

How to get a specific column value from a DataTable in c#

The table normally contains multiple rows. Use a loop and use row.Field<string>(0) to access the value of each row.

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>("File");
}

You can also access it via index:

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>(0);
}

If you expect only one row, you can also use the indexer of DataRowCollection:

string file = dt.Rows[0].Field<string>(0); 

Since this fails if the table is empty, use dt.Rows.Count to check if there is a row:

if(dt.Rows.Count > 0)
    file = dt.Rows[0].Field<string>(0);

If "0" then leave the cell blank

=iferror(1/ (1/ H15+G16-F16 ), "")

this way avoids repeating the central calculation (which can often be much longer or more processor hungry than the one you have here...

enjoy

Changing Shell Text Color (Windows)

This is extremely simple! Rather than importing odd modules for python or trying long commands you can take advantage of windows OS commands.

In windows, commands exist to change the command prompt text color. You can use this in python by starting with a: import os

Next you need to have a line changing the text color, place it were you want in your code. os.system('color 4')

You can figure out the other colors by starting cmd.exe and typing color help.

The good part? Thats all their is to it, to simple lines of code. -Day

Javascript (+) sign concatenates instead of giving sum of variables

Use only:

divID = "question-" + parseInt(i) + 1;

When "n" comes from html input field or is declared as string, you need to use explicit conversion.

var n = "1"; //type is string
var frstCol = 5;
lstCol = frstCol + parseInt(n);

If "n" is integer, don't need conversion.

n = 1; //type is int
var frstCol = 5, lstCol = frstCol + n;

How to drop all user tables?

The easiest way would be to drop the tablespace then build the tablespace back up. But I'd rather not have to do that. This is similar to Henry's except that I just do a copy/paste on the resultset in my gui.

SELECT
  'DROP'
  ,object_type
  ,object_name
  ,CASE(object_type)
     WHEN 'TABLE' THEN 'CASCADE CONSTRAINTS;'
     ELSE ';'
   END
 FROM user_objects
 WHERE
   object_type IN ('TABLE','VIEW','PACKAGE','PROCEDURE','FUNCTION','SEQUENCE')

How to find the files that are created in the last hour in unix

check out this link and then help yourself out.

the basic code is

#create a temp. file
echo "hi " >  t.tmp
# set the file time to 2 hours ago
touch -t 200405121120  t.tmp 
# then check for files
find /admin//dump -type f  -newer t.tmp -print -exec ls -lt {} \; | pg

ASP.NET Web API - PUT & DELETE Verbs Not Allowed - IIS 8

Change Your Web.Config file as below. It will act like charm.

In node <system.webServer> add below portion of code

<modules runAllManagedModulesForAllRequests="true">
  <remove name="WebDAVModule"/>
</modules>

After adding, your Web.Config will look like below

<system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true">
        <remove name="WebDAVModule"/>
    </modules>
    <httpProtocol>
    <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
    </customHeaders>
    </httpProtocol>
    <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
</system.webServer>

Differences between socket.io and websockets

Misconceptions

There are few common misconceptions regarding WebSocket and Socket.IO:

  1. The first misconception is that using Socket.IO is significantly easier than using WebSocket which doesn't seem to be the case. See examples below.

  2. The second misconception is that WebSocket is not widely supported in the browsers. See below for more info.

  3. The third misconception is that Socket.IO downgrades the connection as a fallback on older browsers. It actually assumes that the browser is old and starts an AJAX connection to the server, that gets later upgraded on browsers supporting WebSocket, after some traffic is exchanged. See below for details.

My experiment

I wrote an npm module to demonstrate the difference between WebSocket and Socket.IO:

It is a simple example of server-side and client-side code - the client connects to the server using either WebSocket or Socket.IO and the server sends three messages in 1s intervals, which are added to the DOM by the client.

Server-side

Compare the server-side example of using WebSocket and Socket.IO to do the same in an Express.js app:

WebSocket Server

WebSocket server example using Express.js:

var path = require('path');
var app = require('express')();
var ws = require('express-ws')(app);
app.get('/', (req, res) => {
  console.error('express connection');
  res.sendFile(path.join(__dirname, 'ws.html'));
});
app.ws('/', (s, req) => {
  console.error('websocket connection');
  for (var t = 0; t < 3; t++)
    setTimeout(() => s.send('message from server', ()=>{}), 1000*t);
});
app.listen(3001, () => console.error('listening on http://localhost:3001/'));
console.error('websocket example');

Source: https://github.com/rsp/node-websocket-vs-socket.io/blob/master/ws.js

Socket.IO Server

Socket.IO server example using Express.js:

var path = require('path');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', (req, res) => {
  console.error('express connection');
  res.sendFile(path.join(__dirname, 'si.html'));
});
io.on('connection', s => {
  console.error('socket.io connection');
  for (var t = 0; t < 3; t++)
    setTimeout(() => s.emit('message', 'message from server'), 1000*t);
});
http.listen(3002, () => console.error('listening on http://localhost:3002/'));
console.error('socket.io example');

Source: https://github.com/rsp/node-websocket-vs-socket.io/blob/master/si.js

Client-side

Compare the client-side example of using WebSocket and Socket.IO to do the same in the browser:

WebSocket Client

WebSocket client example using vanilla JavaScript:

var l = document.getElementById('l');
var log = function (m) {
    var i = document.createElement('li');
    i.innerText = new Date().toISOString()+' '+m;
    l.appendChild(i);
}
log('opening websocket connection');
var s = new WebSocket('ws://'+window.location.host+'/');
s.addEventListener('error', function (m) { log("error"); });
s.addEventListener('open', function (m) { log("websocket connection open"); });
s.addEventListener('message', function (m) { log(m.data); });

Source: https://github.com/rsp/node-websocket-vs-socket.io/blob/master/ws.html

Socket.IO Client

Socket.IO client example using vanilla JavaScript:

var l = document.getElementById('l');
var log = function (m) {
    var i = document.createElement('li');
    i.innerText = new Date().toISOString()+' '+m;
    l.appendChild(i);
}
log('opening socket.io connection');
var s = io();
s.on('connect_error', function (m) { log("error"); });
s.on('connect', function (m) { log("socket.io connection open"); });
s.on('message', function (m) { log(m); });

Source: https://github.com/rsp/node-websocket-vs-socket.io/blob/master/si.html

Network traffic

To see the difference in network traffic you can run my test. Here are the results that I got:

WebSocket Results

2 requests, 1.50 KB, 0.05 s

From those 2 requests:

  1. HTML page itself
  2. connection upgrade to WebSocket

(The connection upgrade request is visible on the developer tools with a 101 Switching Protocols response.)

Socket.IO Results

6 requests, 181.56 KB, 0.25 s

From those 6 requests:

  1. the HTML page itself
  2. Socket.IO's JavaScript (180 kilobytes)
  3. first long polling AJAX request
  4. second long polling AJAX request
  5. third long polling AJAX request
  6. connection upgrade to WebSocket

Screenshots

WebSocket results that I got on localhost:

WebSocket results - websocket-vs-socket.io module

Socket.IO results that I got on localhost:

Socket.IO results - websocket-vs-socket.io module

Test yourself

Quick start:

# Install:
npm i -g websocket-vs-socket.io
# Run the server:
websocket-vs-socket.io

Open http://localhost:3001/ in your browser, open developer tools with Shift+Ctrl+I, open the Network tab and reload the page with Ctrl+R to see the network traffic for the WebSocket version.

Open http://localhost:3002/ in your browser, open developer tools with Shift+Ctrl+I, open the Network tab and reload the page with Ctrl+R to see the network traffic for the Socket.IO version.

To uninstall:

# Uninstall:
npm rm -g websocket-vs-socket.io

Browser compatibility

As of June 2016 WebSocket works on everything except Opera Mini, including IE higher than 9.

This is the browser compatibility of WebSocket on Can I Use as of June 2016:

enter image description here

See http://caniuse.com/websockets for up-to-date info.

SQL set values of one column equal to values of another column in the same table

Here is sample code that might help you coping Column A to Column B:

UPDATE YourTable
SET ColumnB = ColumnA
WHERE
ColumnB IS NULL
AND ColumnA IS NOT NULL;

VSCode Change Default Terminal

You can also select your default terminal by pressing F1 in VS Code and typing/selecting Terminal: Select Default Shell.

Terminal Selection

Terminal Selection

How do I prevent DIV tag starting a new line?

I am not an expert but try white-space:nowrap;

The white-space property is supported in all major browsers.

Note: The value "inherit" is not supported in IE7 and earlier. IE8 requires a !DOCTYPE. IE9 supports "inherit".

Capitalize the first letter of string in AngularJs

If you are using Angular 4+ then you can just use titlecase

{{toUppercase | titlecase}}

don't have to write any pipes.

How do I count unique visitors to my site?

Here is a nice tutorial, it is what you need. (Source: coursesweb.net/php-mysql)

Register and show online users and visitors

Count Online users and visitors using a MySQL table

In this tutorial you can learn how to register, to count, and display in your webpage the number of online users and visitors. The principle is this: each user / visitor is registered in a text file or database. Every time a page of the website is accessed, the php script deletes all records older than a certain time (eg 2 minutes), adds the current user / visitor and takes the number of records left to display.

You can store the online users and visitors in a file on the server, or in a MySQL table. In this case, I think that using a text file to add and read the records is faster than storing them into a MySQL table, which requires more requests.

First it's presented the method with recording in a text file on the server, than the method with MySQL table.

To download the files with the scripts presented in this tutorial, click -> Count Online Users and Visitors.

• Both scripts can be included in ".php" files (with include()), or in ".html" files (with <script>), as you can see in the examples presented at the bottom of this page; but the server must run PHP.

Storing online users and visitors in a text file

To add records in a file on the server with PHP you must set CHMOD 0766 (or CHMOD 0777) permissions to that file, so the PHP can write data in it.

  1. Create a text file on your server (for example, named userson.txt) and give it CHMOD 0777 permissions (in your FTP application, right click on that file, choose Properties, then select Read, Write, and Execute options).
  2. Create a PHP file (named usersontxt.php) having the code below, then copy this php file in the same directory as userson.txt.

The code for usersontxt.php;

<?php
// Script Online Users and Visitors - http://coursesweb.net/php-mysql/
if(!isset($_SESSION)) session_start();        // start Session, if not already started

$filetxt = 'userson.txt';  // the file in which the online users /visitors are stored
$timeon = 120;             // number of secconds to keep a user online
$sep = '^^';               // characters used to separate the user name and date-time
$vst_id = '-vst-';        // an identifier to know that it is a visitor, not logged user

/*
 If you have an user registration script,
 replace $_SESSION['nume'] with the variable in which the user name is stored.
 You can get a free registration script from:  http://coursesweb.net/php-mysql/register-login-script-users-online_s2
*/

// get the user name if it is logged, or the visitors IP (and add the identifier)

    $uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;

$rgxvst = '/^([0-9\.]*)'. $vst_id. '/i';         // regexp to recognize the line with visitors
$nrvst = 0;                                       // to store the number of visitors

// sets the row with the current user /visitor that must be added in $filetxt (and current timestamp)

    $addrow[] = $uvon. $sep. time();

// check if the file from $filetxt exists and is writable

    if(is_writable($filetxt)) {
      // get into an array the lines added in $filetxt
      $ar_rows = file($filetxt, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
      $nrrows = count($ar_rows);

            // number of rows

  // if there is at least one line, parse the $ar_rows array

      if($nrrows>0) {
        for($i=0; $i<$nrrows; $i++) {
          // get each line and separate the user /visitor and the timestamp
          $ar_line = explode($sep, $ar_rows[$i]);
      // add in $addrow array the records in last $timeon seconds
          if($ar_line[0]!=$uvon && (intval($ar_line[1])+$timeon)>=time()) {
            $addrow[] = $ar_rows[$i];
          }
        }
      }
    }

$nruvon = count($addrow);                   // total online
$usron = '';                                    // to store the name of logged users
// traverse $addrow to get the number of visitors and users
for($i=0; $i<$nruvon; $i++) {
 if(preg_match($rgxvst, $addrow[$i])) $nrvst++;       // increment the visitors
 else {
   // gets and stores the user's name
   $ar_usron = explode($sep, $addrow[$i]);
   $usron .= '<br/> - <i>'. $ar_usron[0]. '</i>';
 }
}
$nrusr = $nruvon - $nrvst;              // gets the users (total - visitors)

// the HTML code with data to be displayed
$reout = '<div id="uvon"><h4>Online: '. $nruvon. '</h4>Visitors: '. $nrvst. '<br/>Users: '. $nrusr. $usron. '</div>';

// write data in $filetxt
if(!file_put_contents($filetxt, implode("\n", $addrow))) $reout = 'Error: Recording file not exists, or is not writable';

// if access from <script>, with GET 'uvon=showon', adds the string to return into a JS statement
// in this way the script can also be included in .html files
if(isset($_GET['uvon']) && $_GET['uvon']=='showon') $reout = "document.write('$reout');";

echo $reout;             // output /display the result
?>
  1. If you want to include the script above in a ".php" file, add the following code in the place you want to show the number of online users and visitors:

4.To show the number of online visitors /users in a ".html" file, use this code:

<script type="text/javascript" src="usersontxt.php?uvon=showon"></script>

This script (and the other presented below) works with $_SESSION. At the beginning of the PHP file in which you use it, you must add: session_start();. Count Online users and visitors using a MySQL table

To register, count and show the number of online visitors and users in a MySQL table, require to perform three SQL queries: Delete the records older than a certain time. Insert a row with the new user /visitor, or, if it is already inserted, Update the timestamp in its column. Select the remaining rows. Here's the code for a script that uses a MySQL table (named "userson") to store and display the Online Users and Visitors.

  1. First we create the "userson" table, with 2 columns (uvon, dt). In the "uvon" column is stored the name of the user (if logged in) or the visitor's IP. In the "dt" column is stored a number with the timestamp (Unix time) when the page is accessed.
  • Add the following code in a php file (for example, named "create_userson.php"):

The code for create_userson.php:

<?php
header('Content-type: text/html; charset=utf-8');

// HERE add your data for connecting to MySQ database
$host = 'localhost';           // MySQL server address
$user = 'root';                // User name
$pass = 'password';            // User`s password
$dbname = 'database';          // Database name

// connect to the MySQL server
$conn = new mysqli($host, $user, $pass, $dbname);

// check connection
if (mysqli_connect_errno()) exit('Connect failed: '. mysqli_connect_error());

// sql query for CREATE "userson" TABLE
$sql = "CREATE TABLE `userson` (
 `uvon` VARCHAR(32) PRIMARY KEY,
 `dt` INT(10) UNSIGNED NOT NULL
 ) CHARACTER SET utf8 COLLATE utf8_general_ci"; 

// Performs the $sql query on the server to create the table
if ($conn->query($sql) === TRUE) echo 'Table "userson" successfully created';
else echo 'Error: '. $conn->error;

$conn->close();
?>
  1. Now we create the script that Inserts, Deletes, and Selects data in the userson table (For explanations about the code, see the comments in script).
  • Add the code below in another php file (named usersmysql.php): In both file you must add your personal data for connecting to MySQL database, in the variables: $host, $user, $pass, and $dbname .

The code for usersmysql.php:

<?php
// Script Online Users and Visitors - coursesweb.net/php-mysql/
if(!isset($_SESSION)) session_start();         // start Session, if not already started

// HERE add your data for connecting to MySQ database
$host = 'localhost';           // MySQL server address
$user = 'root';                // User name
$pass = 'password';            // User`s password
$dbname = 'database';          // Database name

/*
 If you have an user registration script,
 replace $_SESSION['nume'] with the variable in which the user name is stored.
 You can get a free registration script from:  http://coursesweb.net/php-mysql/register-login-script-users-online_s2
*/

// get the user name if it is logged, or the visitors IP (and add the identifier)
$vst_id = '-vst-';         // an identifier to know that it is a visitor, not logged user
$uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;

$rgxvst = '/^([0-9\.]*)'. $vst_id. '/i';         // regexp to recognize the rows with visitors
$dt = time();                                    // current timestamp
$timeon = 120;             // number of secconds to keep a user online
$nrvst = 0;                                     // to store the number of visitors
$nrusr = 0;                                     // to store the number of usersrs
$usron = '';                                    // to store the name of logged users

// connect to the MySQL server
$conn = new mysqli($host, $user, $pass, $dbname);

// Define and execute the Delete, Insert/Update, and Select queries
$sqldel = "DELETE FROM `userson` WHERE `dt`<". ($dt - $timeon);
$sqliu = "INSERT INTO `userson` (`uvon`, `dt`) VALUES ('$uvon', $dt) ON DUPLICATE KEY UPDATE `dt`=$dt";
$sqlsel = "SELECT * FROM `userson`";

// Execute each query
if(!$conn->query($sqldel)) echo 'Error: '. $conn->error;
if(!$conn->query($sqliu)) echo 'Error: '. $conn->error;
$result = $conn->query($sqlsel);

// if the $result contains at least one row
if ($result->num_rows > 0) {
  // traverse the sets of results and set the number of online visitors and users ($nrvst, $nrusr)
  while($row = $result->fetch_assoc()) {
    if(preg_match($rgxvst, $row['uvon'])) $nrvst++;       // increment the visitors
    else {
      $nrusr++;                   // increment the users
      $usron .= '<br/> - <i>'.$row['uvon']. '</i>';          // stores the user's name
    }
  }
}

$conn->close();                  // close the MySQL connection

// the HTML code with data to be displayed
$reout = '<div id="uvon"><h4>Online: '. ($nrusr+$nrvst). '</h4>Visitors: '. $nrvst. '<br/>Users: '. $nrusr. $usron. '</div>';

// if access from <script>, with GET 'uvon=showon', adds the string to return into a JS statement
// in this way the script can also be included in .html files
if(isset($_GET['uvon']) && $_GET['uvon']=='showon') $reout = "document.write('$reout');";

echo $reout;             // output /display the result
?>
  1. After you have created these two php files on your server, run the "create_userson.php" on your browser to create the "userson" table.

  2. Include the usersmysql.php file in the php file in which you want to display the number of online users and visitors.

  3. Or, if you want to insert it in a ".html" file, add this code:

Examples using these scripts

• Including the "usersontxt.php` in a php file:

<!doctype html>

Counter Online Users and Visitors

• Including the "usersmysql.php" in a html file:

<!doctype html>
<html>
<head>
 <meta charset="utf-8" />
 <title>Counter Online Users and Visitors</title>
 <meta name="description" content="PHP script to count and show the number of online users and visitors" />
 <meta name="keywords" content="online users, online visitors" />
</head>
<body>

<!-- Includes the script ("usersontxt.php", or "usersmysql.php") -->
<script type="text/javascript" src="usersmysql.php?uvon=showon"></script>

</body>
</html>

Both scripts (with storing data in a text file on the server, or into a MySQL table) will display a result like this: Online: 5

Visitors: 3 Users: 2

  • MarPlo
  • Marius

How do I make my string comparison case insensitive?

  • The best would be using s1.equalsIgnoreCase(s2): (see javadoc)
  • You can also convert them both to upper/lower case and use s1.equals(s2)

Transparent background in JPEG image

If you’re concerned about the file size of a PNG, you can use an SVG mask to create a transparent JPEG. Here is an example I put together.

How do I format {{$timestamp}} as MM/DD/YYYY in Postman?

You could use moment.js with Postman to give you that timestamp format.

You can add this to the pre-request script:

const moment = require('moment');
pm.globals.set("today", moment().format("MM/DD/YYYY"));

Then reference {{today}} where ever you need it.

If you add this to the Collection Level Pre-request Script, it will be run for each request in the Collection. Rather than needing to add it to all the requests individually.

For more information about using moment in Postman, I wrote a short blog post: https://dannydainton.com/2018/05/21/hold-on-wait-a-moment/

How do I perform HTML decoding/encoding using Python/Django?

I found this in the Cheetah source code (here)

htmlCodes = [
    ['&', '&amp;'],
    ['<', '&lt;'],
    ['>', '&gt;'],
    ['"', '&quot;'],
]
htmlCodesReversed = htmlCodes[:]
htmlCodesReversed.reverse()
def htmlDecode(s, codes=htmlCodesReversed):
    """ Returns the ASCII decoded version of the given HTML string. This does
        NOT remove normal HTML tags like <p>. It is the inverse of htmlEncode()."""
    for code in codes:
        s = s.replace(code[1], code[0])
    return s

not sure why they reverse the list, I think it has to do with the way they encode, so with you it may not need to be reversed. Also if I were you I would change htmlCodes to be a list of tuples rather than a list of lists... this is going in my library though :)

i noticed your title asked for encode too, so here is Cheetah's encode function.

def htmlEncode(s, codes=htmlCodes):
    """ Returns the HTML encoded version of the given string. This is useful to
        display a plain ASCII text string on a web page."""
    for code in codes:
        s = s.replace(code[0], code[1])
    return s

HTML Table cellspacing or padding just top / bottom

Cellspacing is all around the cell and cannot be changed (i.e. if it's set to one, there will be 1 pixel of space on all sides). Padding can be specified discreetly (e.g. padding-top, padding-bottom, padding-left, and padding-right; or padding: [top] [right] [bottom] [left];).

Creating an instance using the class name and calling constructor

You can use reflections

return Class.forName(className).getConstructor(String.class).newInstance(arg);

Location of WSDL.exe

If you have Windows 10 and VS2015, below you can see the Location of WSDL.exe

Path in your pc C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7 Tools

How can I avoid ResultSet is closed exception in Java?

You may have closed either the Connection or Statement that made the ResultSet, which would lead to the ResultSet being closed as well.

How can I wait In Node.js (JavaScript)? l need to pause for a period of time

let co = require('co');
const sleep = ms => new Promise(res => setTimeout(res, ms));

co(function*() {
    console.log('Welcome to My Console,');
    yield sleep(3000);
    console.log('Blah blah blah blah extra-blah');
});

This code above is the side effect of the solving Javascript's asynchronous callback hell problem. This is also the reason I think that makes Javascript a useful language in the backend. Actually this is the most exciting improvement introduced to modern Javascript in my opinion. To fully understand how it works, how generator works needs to be fully understood. The function keyword followed by a * is called a generator function in modern Javascript. The npm package co provided a runner function to run a generator.

Essentially generator function provided a way to pause the execution of a function with yield keyword, at the same time, yield in a generator function made it possible to exchange information between inside the generator and the caller. This provided a mechanism for the caller to extract data from a promise from an asynchronous call and to pass the resolved data back to the generator. Effectively, it makes an asynchronous call synchronous.

Automate scp file transfer using a shell script

This will work:

#!/usr/bin/expect -f

spawn scp -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no file1 file2 file3 user@host:/path/
expect "password:"
send "xyz123\r"
expect "*\r"
expect "\r"
interact

How to handle change of checkbox using jQuery?

get radio value by name

  $('input').on('className', function(event){
        console.log($(this).attr('name'));
        if($(this).attr('name') == "worker")
            {
                resetAll();                 
            }
    });

Can I pass a JavaScript variable to another browser window?

For me the following doesn't work

var A = {foo:'bar'};
var w = window.open("http://example.com");
w.B = A;

// in new window
var B = window.opener.B;

But this works(note the variable name)

var B = {foo:'bar'};
var w = window.open("http://example.com");
w.B = B;

// in new window
var B = window.opener.B;

Also var B should be global.

What does file:///android_asset/www/index.html mean?

it's file:///android_asset/... not file:///android_assets/... notice the plural of assets is wrong even if your file name is assets

Iterating through populated rows

I'm going to make a couple of assumptions in my answer. I'm assuming your data starts in A1 and there are no empty cells in the first column of each row that has data.

This code will:

  1. Find the last row in column A that has data
  2. Loop through each row
  3. Find the last column in current row with data
  4. Loop through each cell in current row up to last column found.

This is not a fast method but will iterate through each one individually as you suggested is your intention.


Sub iterateThroughAll()
    ScreenUpdating = False
    Dim wks As Worksheet
    Set wks = ActiveSheet

    Dim rowRange As Range
    Dim colRange As Range

    Dim LastCol As Long
    Dim LastRow As Long
    LastRow = wks.Cells(wks.Rows.Count, "A").End(xlUp).Row

    Set rowRange = wks.Range("A1:A" & LastRow)

    'Loop through each row
    For Each rrow In rowRange
        'Find Last column in current row
        LastCol = wks.Cells(rrow, wks.Columns.Count).End(xlToLeft).Column
        Set colRange = wks.Range(wks.Cells(rrow, 1), wks.Cells(rrow, LastCol))

        'Loop through all cells in row up to last col
        For Each cell In colRange
            'Do something to each cell
            Debug.Print (cell.Value)
        Next cell
    Next rrow
    ScreenUpdating = True
End Sub

tkinter: how to use after method

You need to give a function to be called after the time delay as the second argument to after:

after(delay_ms, callback=None, *args)

Registers an alarm callback that is called after a given time.

So what you really want to do is this:

tiles_letter = ['a', 'b', 'c', 'd', 'e']

def add_letter():
    rand = random.choice(tiles_letter)
    tile_frame = Label(frame, text=rand)
    tile_frame.pack()
    root.after(500, add_letter)
    tiles_letter.remove(rand)  # remove that tile from list of tiles


root.after(0, add_letter)  # add_letter will run as soon as the mainloop starts.
root.mainloop()

You also need to schedule the function to be called again by repeating the call to after inside the callback function, since after only executes the given function once. This is also noted in the documentation:

The callback is only called once for each call to this method. To keep calling the callback, you need to reregister the callback inside itself

Note that your example will throw an exception as soon as you've exhausted all the entries in tiles_letter, so you need to change your logic to handle that case whichever way you want. The simplest thing would be to add a check at the beginning of add_letter to make sure the list isn't empty, and just return if it is:

def add_letter():
    if not tiles_letter:
        return
    rand = random.choice(tiles_letter)
    tile_frame = Label(frame, text=rand)
    tile_frame.pack()
    root.after(500, add_letter)
    tiles_letter.remove(rand)  # remove that tile from list of tiles

Live-Demo: repl.it

How to inject Javascript in WebBrowser control?

I believe the most simple method to inject Javascript in a WebBrowser Control HTML Document from c# is to invoke the "execScript" method with the code to be injected as argument.

In this example the javascript code is injected and executed at global scope:

var jsCode="alert('hello world from injected code');";
WebBrowser.Document.InvokeScript("execScript", new Object[] { jsCode, "JavaScript" });

If you want to delay execution, inject functions and call them after:

var jsCode="function greet(msg){alert(msg);};";
WebBrowser.Document.InvokeScript("execScript", new Object[] { jsCode, "JavaScript" });
...............
WebBrowser.Document.InvokeScript("greet",new object[] {"hello world"});

This is valid for Windows Forms and WPF WebBrowser controls.

This solution is not cross browser because "execScript" is defined only in IE and Chrome. But the question is about Microsoft WebBrowser controls and IE is the only one supported.

For a valid cross browser method to inject javascript code, create a Function object with the new Keyword. This example creates an anonymous function with injected code and executes it (javascript implements closures and the function has access to global space without local variable pollution).

var jsCode="alert('hello world');";
(new Function(code))();

Of course, you can delay execution:

var jsCode="alert('hello world');";
var inserted=new Function(code);
.................
inserted();

Hope it helps

C# "as" cast vs classic cast

There's nothing deep happening here.. Basically, it's handy to test something to see if it's of a certain type (i.e. use 'as'). You would want to check the result of the 'as' call to see if the result is null.

When you expect a cast to work and you want the exception to be thrown, use the 'classic' method.

How to run a bash script from C++ program

StackOverflow: How to execute a command and get output of command within C++?

StackOverflow: (Using fork,pipe,select): ...nobody does things the hard way any more...

Also if you know how to make user become the super-user that would be nice also. Thanks!

sudo. su. chmod 04500. (setuid() & seteuid(), but they require you to already be root. E..g. chmod'ed 04***.)

Take care. These can open "interesting" security holes...

Depending on what you are doing, you may not need root. (For instance: I'll often chmod/chown /dev devices (serial ports, etc) (under sudo root) so I can use them from my software without being root. On the other hand, that doesn't work so well when loading/unloading kernel modules...)

How to run .sql file in Oracle SQL developer tool to import database?

You could execute the .sql file as a script in the SQL Developer worksheet. Either use the Run Script icon, or simply press F5.

enter image description here

For example,

@path\script.sql;

Remember, you need to put @ as shown above.

But, if you have exported the database using database export utility of SQL Developer, then you should use the Import utility. Follow the steps mentioned here Importing and Exporting using the Oracle SQL Developer 3.0

How to install a python library manually

I'm going to assume compiling the QuickFix package does not produce a setup.py file, but rather only compiles the Python bindings and relies on make install to put them in the appropriate place.

In this case, a quick and dirty fix is to compile the QuickFix source, locate the Python extension modules (you indicated on your system these end with a .so extension), and add that directory to your PYTHONPATH environmental variable e.g., add

export PYTHONPATH=~/path/to/python/extensions:PYTHONPATH

or similar line in your shell configuration file.

A more robust solution would include making sure to compile with ./configure --prefix=$HOME/.local. Assuming QuickFix knows to put the Python files in the appropriate site-packages, when you do make install, it should install the files to ~/.local/lib/pythonX.Y/site-packages, which, for Python 2.6+, should already be on your Python path as the per-user site-packages directory.

If, on the other hand, it did provide a setup.py file, simply run

python setup.py install --user

for Python 2.6+.

Safest way to get last record ID from a table

SELECT IDENT_CURRENT('Table')

You can use one of these examples:

SELECT * FROM Table 
WHERE ID = (
    SELECT IDENT_CURRENT('Table'))

SELECT * FROM Table
WHERE ID = (
    SELECT MAX(ID) FROM Table)

SELECT TOP 1 * FROM Table
ORDER BY ID DESC

But the first one will be more efficient because no index scan is needed (if you have index on Id column).

The second one solution is equivalent to the third (both of them need to scan table to get max id).

FormData.append("key", "value") is not working

New in Chrome 50+ and Firefox 39+ (resp. 44+):

  • formdata.entries() (combine with Array.from() for debugability)
  • formdata.get(key)
  • and more very useful methods

Original answer:

What I usually do to 'debug' a FormData object, is just send it (anywhere!) and check the browser logs (eg. Chrome devtools' Network tab).

You don't need a/the same Ajax framework. You don't need any details. Just send it:

var xhr = new XMLHttpRequest;
xhr.open('POST', '/', true);
xhr.send(data);

Easy.

What does operator "dot" (.) mean?

There is a whole page in the MATLAB documentation dedicated to this topic: Array vs. Matrix Operations. The gist of it is below:

MATLAB® has two different types of arithmetic operations: array operations and matrix operations. You can use these arithmetic operations to perform numeric computations, for example, adding two numbers, raising the elements of an array to a given power, or multiplying two matrices.

Matrix operations follow the rules of linear algebra. By contrast, array operations execute element by element operations and support multidimensional arrays. The period character (.) distinguishes the array operations from the matrix operations. However, since the matrix and array operations are the same for addition and subtraction, the character pairs .+ and .- are unnecessary.

Resize image in PHP

I found a mathematical way to get this job done

Github repo - https://github.com/gayanSandamal/easy-php-image-resizer

Live example - https://plugins.nayague.com/easy-php-image-resizer/

<?php
//path for the image
$source_url = '2018-04-01-1522613288.PNG';

//separate the file name and the extention
$source_url_parts = pathinfo($source_url);
$filename = $source_url_parts['filename'];
$extension = $source_url_parts['extension'];

//define the quality from 1 to 100
$quality = 10;

//detect the width and the height of original image
list($width, $height) = getimagesize($source_url);
$width;
$height;

//define any width that you want as the output. mine is 200px.
$after_width = 200;

//resize only when the original image is larger than expected with.
//this helps you to avoid from unwanted resizing.
if ($width > $after_width) {

    //get the reduced width
    $reduced_width = ($width - $after_width);
    //now convert the reduced width to a percentage and round it to 2 decimal places
    $reduced_radio = round(($reduced_width / $width) * 100, 2);

    //ALL GOOD! let's reduce the same percentage from the height and round it to 2 decimal places
    $reduced_height = round(($height / 100) * $reduced_radio, 2);
    //reduce the calculated height from the original height
    $after_height = $height - $reduced_height;

    //Now detect the file extension
    //if the file extension is 'jpg', 'jpeg', 'JPG' or 'JPEG'
    if ($extension == 'jpg' || $extension == 'jpeg' || $extension == 'JPG' || $extension == 'JPEG') {
        //then return the image as a jpeg image for the next step
        $img = imagecreatefromjpeg($source_url);
    } elseif ($extension == 'png' || $extension == 'PNG') {
        //then return the image as a png image for the next step
        $img = imagecreatefrompng($source_url);
    } else {
        //show an error message if the file extension is not available
        echo 'image extension is not supporting';
    }

    //HERE YOU GO :)
    //Let's do the resize thing
    //imagescale([returned image], [width of the resized image], [height of the resized image], [quality of the resized image]);
    $imgResized = imagescale($img, $after_width, $after_height, $quality);

    //now save the resized image with a suffix called "-resized" and with its extension. 
    imagejpeg($imgResized, $filename . '-resized.'.$extension);

    //Finally frees any memory associated with image
    //**NOTE THAT THIS WONT DELETE THE IMAGE
    imagedestroy($img);
    imagedestroy($imgResized);
}
?>

Using SSH keys inside docker container

You can use multi stage build to build containers This is the approach you can take :-

Stage 1 building an image with ssh

FROM ubuntu as sshImage
LABEL stage=sshImage
ARG SSH_PRIVATE_KEY
WORKDIR /root/temp

RUN apt-get update && \
    apt-get install -y git npm 

RUN mkdir /root/.ssh/ &&\
    echo "${SSH_PRIVATE_KEY}" > /root/.ssh/id_rsa &&\
    chmod 600 /root/.ssh/id_rsa &&\
    touch /root/.ssh/known_hosts &&\
    ssh-keyscan github.com >> /root/.ssh/known_hosts

COPY package*.json ./

RUN npm install

RUN cp -R node_modules prod_node_modules

Stage 2: build your container

FROM node:10-alpine

RUN mkdir -p /usr/app

WORKDIR /usr/app

COPY ./ ./

COPY --from=sshImage /root/temp/prod_node_modules ./node_modules

EXPOSE 3006

CMD ["npm", "run", "dev"] 

add env attribute in your compose file:

   environment:
      - SSH_PRIVATE_KEY=${SSH_PRIVATE_KEY}

then pass args from build script like this:

docker-compose build --build-arg SSH_PRIVATE_KEY="$(cat ~/.ssh/id_rsa)"

And remove the intermediate container it for security. This Will help you cheers.

Equivalent to AssemblyInfo in dotnet core/csproj

You can always add your own AssemblyInfo.cs, which comes in handy for InternalsVisibleToAttribute, CLSCompliantAttribute and others that are not automatically generated.

Adding AssemblyInfo.cs to a Project

  1. In Solution Explorer, right click on <project name> > Add > New Folder.

Add New Folder

  1. Name the folder "Properties".

Name folder Properties

  1. Right click on the "Properties" folder, and click Add > New Item....

Add New Item

  1. Select "Class" and name it "AssemblyInfo.cs".

Name file AssemblyInfo.cs

Suppressing Auto-Generated Attributes

If you want to move your attributes back to AssemblyInfo.cs instead of having them auto-generated, you can suppress them in MSBuild as natemcmaster pointed out in his answer.

Responsive Bootstrap Jumbotron Background Image

You could try this:

Simply place the code in a style tag in the head of the html file

_x000D_
_x000D_
<style>_x000D_
        .jumbotron {_x000D_
            background: url("http://www.californiafootgolfclub.com/static/img/footgolf-1.jpg") center center / cover no-repeat;_x000D_
        }_x000D_
</style>
_x000D_
_x000D_
_x000D_

or put it in a separate css file as shown below

_x000D_
_x000D_
        .jumbotron {_x000D_
            background: url("http://www.californiafootgolfclub.com/static/img/footgolf-1.jpg") center center / cover no-repeat;_x000D_
        }
_x000D_
_x000D_
_x000D_

use center center to center the image horizontally and vertically. use cover to make the image fill out the jumbotron space and finally no-repeat so that the image is not repeated.

How to add new column to MYSQL table?

ALTER TABLE `stor` ADD `buy_price` INT(20) NOT NULL ;

How can I convert a timestamp from yyyy-MM-ddThh:mm:ss:SSSZ format to MM/dd/yyyy hh:mm:ss.SSS format? From ISO8601 to UTC

Enter the original date into a Date object and then print out the result with a DateFormat. You may have to split up the string into smaller pieces to create the initial Date object, if the automatic parse method does not accept your format.

Pseudocode:

Date inputDate = convertYourInputIntoADateInWhateverWayYouPrefer(inputString);
DateFormat outputFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss.SSS");
String outputString = outputFormat.format(inputDate);

How can I conditionally import an ES6 module?

If you'd like, you could use require. This is a way to have a conditional require statement.

let something = null;
let other = null;

if (condition) {
    something = require('something');
    other = require('something').other;
}
if (something && other) {
    something.doStuff();
    other.doOtherStuff();
}

Extract XML Value in bash script

XMLStarlet or another XPath engine is the correct tool for this job.

For instance, with data.xml containing the following:

<root>
  <item> 
    <title>15:54:57 - George:</title>
    <description>Diane DeConn? You saw Diane DeConn!</description> 
  </item> 
  <item> 
    <title>15:55:17 - Jerry:</title> 
    <description>Something huh?</description>
  </item>
</root>

...you can extract only the first title with the following:

xmlstarlet sel -t -m '//title[1]' -v . -n <data.xml

Trying to use sed for this job is troublesome. For instance, the regex-based approaches won't work if the title has attributes; won't handle CDATA sections; won't correctly recognize namespace mappings; can't determine whether a portion of the XML documented is commented out; won't unescape attribute references (such as changing Brewster &amp; Jobs to Brewster & Jobs), and so forth.

Jquery - Uncaught TypeError: Cannot use 'in' operator to search for '324' in

You can also use $.parseJSON(data) that will explicit convert a string thats come from a PHP script to a real JSON array.

Spring MVC: How to return image in @ResponseBody?

if you are using Spring version of 3.1 or newer you can specify "produces" in @RequestMapping annotation. Example below works for me out of box. No need of register converter or anything else if you have web mvc enabled (@EnableWebMvc).

@ResponseBody
@RequestMapping(value = "/photo2", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
public byte[] testphoto() throws IOException {
    InputStream in = servletContext.getResourceAsStream("/images/no_image.jpg");
    return IOUtils.toByteArray(in);
}

What does 'useLegacyV2RuntimeActivationPolicy' do in the .NET 4 config?

After a bit of time (and more searching), I found this blog entry by Jomo Fisher.

One of the recent problems we’ve seen is that, because of the support for side-by-side runtimes, .NET 4.0 has changed the way that it binds to older mixed-mode assemblies. These assemblies are, for example, those that are compiled from C++\CLI. Currently available DirectX assemblies are mixed mode. If you see a message like this then you know you have run into the issue:

Mixed mode assembly is built against version 'v1.1.4322' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.

[Snip]

The good news for applications is that you have the option of falling back to .NET 2.0 era binding for these assemblies by setting an app.config flag like so:

<startup useLegacyV2RuntimeActivationPolicy="true">
  <supportedRuntime version="v4.0"/>
</startup>

So it looks like the way the runtime loads mixed-mode assemblies has changed. I can't find any details about this change, or why it was done. But the useLegacyV2RuntimeActivationPolicy attribute reverts back to CLR 2.0 loading.

How to select a range of the second row to the last row

Try this:

Dim Lastrow As Integer
Lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row

Range("A2:L" & Lastrow).Select

Let's pretend that the value of Lastrow is 50. When you use the following:

Range("A2:L2" & Lastrow).Select

Then it is selecting a range from A2 to L250.

Create a hexadecimal colour based on a string with JavaScript

All you really need is a good hash function. On node, I just use

const crypto = require('crypto');
function strToColor(str) {
    return '#' + crypto.createHash('md5').update(str).digest('hex').substr(0, 6);
}

How can I delete an item from an array in VB.NET?

My favorite way:

Imports System.Runtime.CompilerServices

<Extension()> _
Public Sub RemoveAll(Of T)(ByRef arr As T(), matching As Predicate(Of T))
    If Not IsNothing(arr) Then
        If arr.Count > 0 Then
            Dim ls As List(Of T) = arr.ToList
            ls.RemoveAll(matching)
            arr = ls.ToArray
        End If
    End If
End Sub

Then in the code, whenever I need to remove something from an array I can do it by some property in some object in that array having a certain value, like:

arr.RemoveAll(Function(c) c.MasterContactID.Equals(customer.MasterContactID))

Or if I already know the exact object I want to remove, I can just do:

arr.RemoveAll(function(c) c.equals(customer))

How to define constants in Visual C# like #define in C?

What is the "Visual C#"? There is no such thing. Just C#, or .NET C# :)

Also, Python's convention for constants CONSTANT_NAME is not very common in C#. We are usually using CamelCase according to MSDN standards, e.g. public const string ExtractedMagicString = "vs2019";

Source: Defining constants in C#

Can't perform a React state update on an unmounted component

There is a hook that's fairly common called useIsMounted that solves this problem (for functional components)...

import { useRef, useEffect } from 'react';

export function useIsMounted() {
  const isMounted = useRef(false);

  useEffect(() => {
    isMounted.current = true;
    return () => isMounted.current = false;
  }, []);

  return isMounted;
}

then in your functional component

function Book() {
  const isMounted = useIsMounted();
  ...

  useEffect(() => {
    asyncOperation().then(data => {
      if (isMounted.current) { setState(data); }
    })
  });
  ...
}

AngularJS directive does not update on scope variable changes

A simple solution is to make the scope variable object. Then access the content with {{ whatever-object.whatever-property }}. The variable is not updating because JavaScript pass Primitive type by value. Whereas Object are passed by reference which solves the problem.

How to part DATE and TIME from DATETIME in MySQL

You can achieve that using DATE_FORMAT() (click the link for more other formats)

SELECT DATE_FORMAT(colName, '%Y-%m-%d') DATEONLY, 
       DATE_FORMAT(colName,'%H:%i:%s') TIMEONLY

SQLFiddle Demo

Delete newline in Vim

J deletes extra leading spacing (if any), joining lines with a single space. (With some exceptions: after /[.!?]$/, two spaces may be inserted; before /^\s*)/, no spaces are inserted.)

If you don't want that behavior, gJ simply removes the newline and doesn't do anything clever with spaces at all.

Angular2 - TypeScript : Increment a number after timeout in AppComponent

This is not valid TypeScript code. You can not have method invocations in the body of a class.

// INVALID CODE
export class AppComponent {
  public n: number = 1;
  setTimeout(function() {
    n = n + 10;
  }, 1000);
}

Instead move the setTimeout call to the constructor of the class. Additionally, use the arrow function => to gain access to this.

export class AppComponent {
  public n: number = 1;

  constructor() {
    setTimeout(() => {
      this.n = this.n + 10;
    }, 1000);
  }

}

In TypeScript, you can only refer to class properties or methods via this. That's why the arrow function => is important.

window.onload vs $(document).ready()

Events

$(document).on('ready', handler) binds to the ready event from jQuery. The handler is called when the DOM is loaded. Assets like images maybe still are missing. It will never be called if the document is ready at the time of binding. jQuery uses the DOMContentLoaded-Event for that, emulating it if not available.

$(document).on('load', handler) is an event that will be fired once all resources are loaded from the server. Images are loaded now. While onload is a raw HTML event, ready is built by jQuery.

Functions

$(document).ready(handler) actually is a promise. The handler will be called immediately if document is ready at the time of calling. Otherwise it binds to the ready-Event.

Before jQuery 1.8, $(document).load(handler) existed as an alias to $(document).on('load',handler).

Further Reading

How can I determine if a date is between two dates in Java?

Like so:

Date min, max;   // assume these are set to something
Date d;          // the date in question

return d.compareTo(min) >= 0 && d.compareTo(max) <= 0;

You can use > instead of >= and < instead of <= to exclude the endpoints from the sense of "between."

What do .c and .h file extensions mean to C?

.c : c file (where the real action is, in general)

.h : header file (to be included with a preprocessor #include directive). Contains stuff that is normally deemed to be shared with other parts of your code, like function prototypes, #define'd stuff, extern declaration for global variables (oh, the horror) and the like.

Technically, you could put everything in a single file. A whole C program. million of lines. But we humans tend to organize things. So you create different C files, each one containing particular functions. That's all nice and clean. Then suddenly you realize that a declaration you have into a given C file should exist also in another C file. So you would duplicate them. The best is therefore to extract the declaration and put it into a common file, which is the .h

For example, in the cs50.h you find what are called "forward declarations" of your functions. A forward declaration is a quick way to tell the compiler how a function should be called (e.g. what input params) and what it returns, so it can perform proper checking (for example if you call a function with the wrong number of parameters, it will complain).

Another example. Suppose you write a .c file containing a function performing regular expression matching. You want your function to accept the regular expression, the string to match, and a parameter that tells if the comparison has to be case insensitive.

in the .c you will therefore put

bool matches(string regexp, string s, int flags) { the code }

Now, assume you want to pass the following flags:

0: if the search is case sensitive

1: if the search is case insensitive

And you want to keep yourself open to new flags, so you did not put a boolean. playing with numbers is hard, so you define useful names for these flags

#define MATCH_CASE_SENSITIVE 0
#define MATCH_CASE_INSENSITIVE 1

This info goes into the .h, because if any program wants to use these labels, it has no way of knowing them unless you include the info. Of course you can put them in the .c, but then you would have to include the .c code (whole!) which is a waste of time and a source of trouble.

Versioning SQL Server database

We needed to version our SQL database after we migrated to an x64 platform and our old version broke with the migration. We wrote a C# application which used SQLDMO to map out all of the SQL objects to a folder:

                Root
                    ServerName
                       DatabaseName
                          Schema Objects
                             Database Triggers*
                                .ddltrigger.sql
                             Functions
                                ..function.sql
                             Security
                                Roles
                                   Application Roles
                                      .approle.sql
                                   Database Roles
                                      .role.sql
                                Schemas*
                                   .schema.sql
                                Users
                                   .user.sql
                             Storage
                                Full Text Catalogs*
                                   .fulltext.sql
                             Stored Procedures
                                ..proc.sql
                             Synonyms*
                                .synonym.sql
                             Tables
                                ..table.sql
                                Constraints
                                   ...chkconst.sql
                                   ...defconst.sql
                                Indexes
                                   ...index.sql
                                Keys
                                   ...fkey.sql
                                   ...pkey.sql
                                   ...ukey.sql
                                Triggers
                                   ...trigger.sql
                             Types
                                User-defined Data Types
                                   ..uddt.sql
                                XML Schema Collections*
                                   ..xmlschema.sql
                             Views
                                ..view.sql
                                Indexes
                                   ...index.sql
                                Triggers
                                   ...trigger.sql

The application would then compare the newly written version with the version stored in SVN, and if there were differences it would update SVN. We determined that running the process once a night was sufficient since we did not make that many changes to SQL. It allows us to track changes to all the objects we care about plus it allows us to rebuild our full schema in the event of a serious problem.

Convert HTML string to image

Try the following:

using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

class Program
{
    static void Main(string[] args)
    {
        var source =  @"
        <!DOCTYPE html>
        <html>
            <body>
                <p>An image from W3Schools:</p>
                <img 
                    src=""http://www.w3schools.com/images/w3schools_green.jpg"" 
                    alt=""W3Schools.com"" 
                    width=""104"" 
                    height=""142"">
            </body>
        </html>";
        StartBrowser(source);
        Console.ReadLine();
    }

    private static void StartBrowser(string source)
    {
        var th = new Thread(() =>
        {
            var webBrowser = new WebBrowser();
            webBrowser.ScrollBarsEnabled = false;
            webBrowser.DocumentCompleted +=
                webBrowser_DocumentCompleted;
            webBrowser.DocumentText = source;
            Application.Run();
        });
        th.SetApartmentState(ApartmentState.STA);
        th.Start();
    }

    static void 
        webBrowser_DocumentCompleted(
        object sender, 
        WebBrowserDocumentCompletedEventArgs e)
    {
        var webBrowser = (WebBrowser)sender;
        using (Bitmap bitmap = 
            new Bitmap(
                webBrowser.Width, 
                webBrowser.Height))
        {
            webBrowser
                .DrawToBitmap(
                bitmap, 
                new System.Drawing
                    .Rectangle(0, 0, bitmap.Width, bitmap.Height));
            bitmap.Save(@"filename.jpg", 
                System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }
}

Note: Credits should go to Hans Passant for his excellent answer on the question WebBrowser Control in a new thread which inspired this solution.

What's the difference between setWebViewClient vs. setWebChromeClient?

I feel this question need a bit more details. My answer is inspired from the Android Programming, The Big Nerd Ranch Guide (2nd edition).

By default, JavaScript is off in WebView. You do not always need to have it on, but for some apps, might do require it.

Loading the URL has to be done after configuring the WebView, so you do that last. Before that, you turn JavaScript on by calling getSettings() to get an instance of WebSettings and calling WebSettings.setJavaScriptEnabled(true). WebSettings is the first of the three ways you can modify your WebView. It has various properties you can set, like the user agent string and text size.

After that, you configure your WebViewClient. WebViewClient is an event interface. By providing your own implementation of WebViewClient, you can respond to rendering events. For example, you could detect when the renderer starts loading an image from a particular URL or decide whether to resubmit a POST request to the server.

WebViewClient has many methods you can override, most of which you will not deal with. However, you do need to replace the default WebViewClient’s implementation of shouldOverrideUrlLoading(WebView, String). This method determines what will happen when a new URL is loaded in the WebView, like by pressing a link. If you return true, you are saying, “Do not handle this URL, I am handling it myself.” If you return false, you are saying, “Go ahead and load this URL, WebView, I’m not doing anything with it.”

The default implementation fires an implicit intent with the URL, just like you did earlier. Now, though, this would be a severe problem. The first thing some Web Applications does is redirect you to the mobile version of the website. With the default WebViewClient, that means that you are immediately sent to the user’s default web browser. This is just what you are trying to avoid. The fix is simple – just override the default implementation and return false.

Use WebChromeClient to spruce things up Since you are taking the time to create your own WebView, let’s spruce it up a bit by adding a progress bar and updating the toolbar’s subtitle with the title of the loaded page.

To hook up the ProgressBar, you will use the second callback on WebView: WebChromeClient.

WebViewClient is an interface for responding to rendering events; WebChromeClient is an event interface for reacting to events that should change elements of chrome around the browser. This includes JavaScript alerts, favicons, and of course updates for loading progress and the title of the current page.

Hook it up in onCreateView(…). Using WebChromeClient to spruce things up Progress updates and title updates each have their own callback method, onProgressChanged(WebView, int) and onReceivedTitle(WebView, String). The progress you receive from onProgressChanged(WebView, int) is an integer from 0 to 100. If it is 100, you know that the page is done loading, so you hide the ProgressBar by setting its visibility to View.GONE.

Disclaimer: This information was taken from Android Programming: The Big Nerd Ranch Guide with permission from the authors. For more information on this book or to purchase a copy, please visit bignerdranch.com.

How to use paginator from material angular?

based on Wesley Coetzee's answer i wrote this. Hope it can help anyone googling this issue. I had bugs with swapping the paginator size in the middle of the list that's why i submit my answer:

Paginator html and list

<mat-paginator [length]="localNewspapers.length" pageSize=20
               (page)="getPaginatorData($event)" [pageSizeOptions]="[10, 20, 30]"
               showFirstLastButtons="false">
</mat-paginator>
<mat-list>
   <app-newspaper-pagi-item *ngFor="let paper of (localNewspapers | 
                         slice: lowValue : highValue)"
                         [newspaper]="paper"> 
  </app-newspaper-pagi-item>

Component logic

import {Component, Input, OnInit} from "@angular/core";
import {PageEvent} from "@angular/material";

@Component({
  selector: 'app-uniques-newspaper-list',
  templateUrl: './newspaper-uniques-list.component.html',
})
export class NewspaperUniquesListComponent implements OnInit {
  lowValue: number = 0;
  highValue: number = 20;

  // used to build an array of papers relevant at any given time
  public getPaginatorData(event: PageEvent): PageEvent {
    this.lowValue = event.pageIndex * event.pageSize;
    this.highValue = this.lowValue + event.pageSize;
    return event;
  }

}

jQuery onclick event for <li> tags

Typing in $(this) will return the jQuery element instead of the HTML Element. Then it just depends on what you want to do in the click event.

alert($(this));

How to change the Eclipse default workspace?

You can check the option that shows up when you start eclipse. Please see the figure below

enter image description here

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/dbname

You have to load jdbc driver. Consider below Code.

try {
           Class.forName("com.mysql.jdbc.Driver");

            // connect way #1
            String url1 = "jdbc:mysql://localhost:3306/aavikme";
            String user = "root";
            String password = "aa";

            conn1 = DriverManager.getConnection(url1, user, password);
            if (conn1 != null) {
                System.out.println("Connected to the database test1");
            }

            // connect way #2
            String url2 = "jdbc:mysql://localhost:3306/aavikme?user=root&password=aa";
            conn2 = DriverManager.getConnection(url2);
            if (conn2 != null) {
                System.out.println("Connected to the database test2");
            }

            // connect way #3
            String url3 = "jdbc:mysql://localhost:3306/aavikme";
            Properties info = new Properties();
            info.put("user", "root");
            info.put("password", "aa");

            conn3 = DriverManager.getConnection(url3, info);
            if (conn3 != null) {
                System.out.println("Connected to the database test3");
            }
   } catch (SQLException ex) {
            System.out.println("An error occurred. Maybe user/password is invalid");
            ex.printStackTrace();
   } catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }

Textfield with only bottom border

See this JSFiddle

_x000D_
_x000D_
 input[type="text"]_x000D_
    {_x000D_
        border: 0;_x000D_
        border-bottom: 1px solid red;_x000D_
        outline: 0;_x000D_
    }
_x000D_
<form>_x000D_
        <input type="text" value="See! ONLY BOTTOM BORDER!" />_x000D_
    </form>
_x000D_
_x000D_
_x000D_

Can I serve multiple clients using just Flask app.run() as standalone?

Tips from 2020:

From Flask 1.0, it defaults to enable multiple threads (source), you don't need to do anything, just upgrade it with:

$ pip install -U flask

If you are using flask run instead of app.run() with older versions, you can control the threaded behavior with a command option (--with-threads/--without-threads):

$ flask run --with-threads

It's same as app.run(threaded=True)

Convert a hexadecimal string to an integer efficiently in C?

Edit: Now compatible with MSVC, C++ and non-GNU compilers (see end).

The question was "most efficient way." The OP doesn't specify platform, he could be compiling for a RISC based ATMEL chip with 256 bytes of flash storage for his code.

For the record, and for those (like me), who appreciate the difference between "the easiest way" and the "most efficient way", and who enjoy learning...

static const long hextable[] = {
   [0 ... 255] = -1, // bit aligned access into this table is considerably
   ['0'] = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, // faster for most modern processors,
   ['A'] = 10, 11, 12, 13, 14, 15,       // for the space conscious, reduce to
   ['a'] = 10, 11, 12, 13, 14, 15        // signed char.
};

/** 
 * @brief convert a hexidecimal string to a signed long
 * will not produce or process negative numbers except 
 * to signal error.
 * 
 * @param hex without decoration, case insensitive. 
 * 
 * @return -1 on error, or result (max (sizeof(long)*8)-1 bits)
 */
long hexdec(unsigned const char *hex) {
   long ret = 0; 
   while (*hex && ret >= 0) {
      ret = (ret << 4) | hextable[*hex++];
   }
   return ret; 
}

It requires no external libraries, and it should be blindingly fast. It handles uppercase, lowercase, invalid characters, odd-sized hex input (eg: 0xfff), and the maximum size is limited only by the compiler.

For non-GCC or C++ compilers or compilers that will not accept the fancy hextable declaration.

Replace the first statement with this (longer, but more conforming) version:

static const long hextable[] = { 
    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
    -1,-1, 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,
    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
    -1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
};

Auto Increment after delete in MySQL

ALTER TABLE foo AUTO_INCREMENT=1

If you've deleted the most recent entries, that should set it to use the next lowest available one. As in, as long as there's no 19 already, deleting 16-18 will reset the autoincrement to use 16.


EDIT: I missed the bit about phpmyadmin. You can set it there, too. Go to the table screen, and click the operations tab. There's an AUTOINCREMENT field there that you can set to whatever you need manually.

HTML/JavaScript: Simple form validation on submit

You have several errors there.

First, you have to return a value from the function in the HTML markup: <form name="ff1" method="post" onsubmit="return validateForm();">

Second, in the JSFiddle, you place the code inside onLoad which and then the form won't recognize it - and last you have to return true from the function if all validation is a success - I fixed some issues in the update:

https://jsfiddle.net/mj68cq0b/

function validateURL(url) {
    var reurl = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/;
    return reurl.test(url);
}

function validateForm()
{
    // Validate URL
    var url = $("#frurl").val();
    if (validateURL(url)) { } else {
        alert("Please enter a valid URL, remember including http://");
        return false;
    }

    // Validate Title
    var title = $("#frtitle").val();
    if (title=="" || title==null) {
        alert("Please enter only alphanumeric values for your advertisement title");
        return false;
    }

    // Validate Email
    var email = $("#fremail").val();
    if ((/(.+)@(.+){2,}\.(.+){2,}/.test(email)) || email=="" || email==null) { } else {
        alert("Please enter a valid email");
        return false;
    }
  return true;
}

Get current application physical path within Application_Start

You can use this code:

AppDomain.CurrentDomain.BaseDirectory

How do you change the document font in LaTeX?

For a different approach, I would suggest using the XeTeX or LuaTex system. They allow you to access system fonts (TrueType, OpenType, etc) and set font features. In a typical LaTeX document, you just need to include this in your headers:

\usepackage{fontspec}
\defaultfontfeatures{Mapping=tex-text,Scale=MatchLowercase}
\setmainfont{Times}
\setmonofont{Lucida Sans Typewriter}

It's the fontspec package that allows for \setmainfont and \setmonofont. The ability to choose a multitude of font features is beyond my expertise, but I would suggest looking up some examples and seeing if this would suit your needs.

Just don't forget to replace your favorite latex compiler by the appropriate one (xelatex or lualatex).

How can I output UTF-8 from Perl?

Thanks, finally got an solution to not put utf8::encode all over code. To synthesize and complete for other cases, like write and read files in utf8 and also works with LoadFile of an YAML file in utf8

use utf8;
use open ':encoding(utf8)';
binmode(STDOUT, ":utf8");

open(FH, ">test.txt"); 
print FH "something éá";

use YAML qw(LoadFile Dump);
my $PUBS = LoadFile("cache.yaml");
my $f = "2917";
my $ref = $PUBS->{$f};
print "$f \"".$ref->{name}."\" ". $ref->{primary_uri}." ";

where cache.yaml is:

---
2917:
  id: 2917
  name: Semanário
  primary_uri: 2917.xml

Google Maps setCenter()

 function resize() {
        var map_obj = document.getElementById("map_canvas");

      /*  map_obj.style.width = "500px";
        map_obj.style.height = "225px";*/
        if (map) {
            map.checkResize();
            map.panTo(new GLatLng(lat,lon));
        }
    }

<body onload="initialize()" onunload="GUnload()" onresize="resize()">
<div id="map_canvas" style="width: 100%; height: 100%">
</div>

@Autowired and static method

You have to workaround this via static application context accessor approach:

@Component
public class StaticContextAccessor {

    private static StaticContextAccessor instance;

    @Autowired
    private ApplicationContext applicationContext;

    @PostConstruct
    public void registerInstance() {
        instance = this;
    }

    public static <T> T getBean(Class<T> clazz) {
        return instance.applicationContext.getBean(clazz);
    }

}

Then you can access bean instances in a static manner.

public class Boo {

    public static void randomMethod() {
         StaticContextAccessor.getBean(Foo.class).doStuff();
    }

}

Storing and displaying unicode string (??????) using PHP and MySQL

Did you set proper charset in the HTML Head section?

<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">

or you can set content type in your php script using -

   header( 'Content-Type: text/html; charset=utf-8' ); 

There are already some discussions here on StackOverflow - please have a look

How to make MySQL handle UTF-8 properly setting utf8 with mysql through php

PHP/MySQL with encoding problems

So what i want to know is how can i directly store ???????? into my database and fetch it and display in my webpage using PHP.

I am not sure what you mean by "directly storing in the database" .. did you mean entering data using PhpMyAdmin or any other similar tool? If yes, I have tried using PhpMyAdmin to input unicode data, so it has worked fine for me - You could try inputting data using phpmyadmin and retrieve it using a php script to confirm. If you need to submit data via a Php script just set the NAMES and CHARACTER SET when you create mysql connection, before execute insert queries, and when you select data. Have a look at the above posts to find the syntax. Hope it helps.

** UPDATE ** Just fixed some typos etc

Extracting numbers from vectors of strings

Or simply:

as.numeric(gsub("\\D", "", years))
# [1] 20  1

Array of arrays (Python/NumPy)

If the file is only numerical values separated by tabs, try using the csv library: http://docs.python.org/library/csv.html (you can set the delimiter to '\t')

If you have a textual file in which every line represents a row in a matrix and has integers separated by spaces\tabs, wrapped by a 'arrayname = [...]' syntax, you should do something like:

import re
f = open("your-filename", 'rb')
result_matrix = []
for line in f.readlines():
    match = re.match(r'\s*\w+\s+\=\s+\[(.*?)\]\s*', line)
    if match is None:
        pass # line syntax is wrong - ignore the line
    values_as_strings = match.group(1).split()
    result_matrix.append(map(int, values_as_strings))

Get all files modified in last 30 days in a directory

A couple of issues

  • You're not limiting it to files, so when it finds a matching directory it will list every file within it.
  • You can't use > in -exec without something like bash -c '... > ...'. Though the > will overwrite the file, so you want to redirect the entire find anyway rather than each -exec.
  • +30 is older than 30 days, -30 would be modified in last 30 days.
  • -exec really isn't needed, you could list everything with various -printf options.

Something like below should work

find . -type f -mtime -30 -exec ls -l {} \; > last30days.txt

Example with -printf

find . -type f -mtime -30 -printf "%M %u %g %TR %TD %p\n" > last30days.txt

This will list files in format "permissions owner group time date filename". -printf is generally preferable to -exec in cases where you don't have to do anything complicated. This is because it will run faster as a result of not having to execute subshells for each -exec. Depending on the version of find, you may also be able to use -ls, which has a similar format to above.

How to force maven update?

In my case first I did was:

mvn clean install -U

Still it was showing same error then I closed project and again reopened it. Finally worked.

Jquery .on('scroll') not firing the event while scrolling

$("body").on("custom-scroll", ".myDiv", function(){
    console.log("Scrolled :P");
})

$("#btn").on("click", function(){
    $("body").append('<div class="myDiv"><br><br><p>Content1<p><br><br><p>Content2<p><br><br></div>');
    listenForScrollEvent($(".myDiv"));
});


function listenForScrollEvent(el){
    el.on("scroll", function(){
        el.trigger("custom-scroll");
    })
}

see this post - Bind scroll Event To Dynamic DIV?

Python Requests and persistent sessions

Upon trying all the answers above, I found that using "RequestsCookieJar" instead of the regular CookieJar for subsequent requests fixed my problem.

import requests
import json

# The Login URL
authUrl = 'https://whatever.com/login'

# The subsequent URL
testUrl = 'https://whatever.com/someEndpoint'

# Logout URL
testlogoutUrl = 'https://whatever.com/logout'

# Whatever you are posting
login_data =  {'formPosted':'1', 
               'login_email':'[email protected]', 
               'password':'pw'
               }

# The Authentication token or any other data that we will receive from the Authentication Request. 
token = ''

# Post the login Request
loginRequest = requests.post(authUrl, login_data)
print("{}".format(loginRequest.text))

# Save the request content to your variable. In this case I needed a field called token. 
token = str(json.loads(loginRequest.content)['token'])  # or ['access_token']
print("{}".format(token))

# Verify Successful login
print("{}".format(loginRequest.status_code))

# Create your Requests Cookie Jar for your subsequent requests and add the cookie
jar = requests.cookies.RequestsCookieJar()
jar.set('LWSSO_COOKIE_KEY', token)

# Execute your next request(s) with the Request Cookie Jar set
r = requests.get(testUrl, cookies=jar)
print("R.TEXT: {}".format(r.text))
print("R.STCD: {}".format(r.status_code))

# Execute your logout request(s) with the Request Cookie Jar set
r = requests.delete(testlogoutUrl, cookies=jar)
print("R.TEXT: {}".format(r.text))  # should show "Request Not Authorized"
print("R.STCD: {}".format(r.status_code))  # should show 401

How can I define a composite primary key in SQL?

CREATE TABLE `voting` (
  `QuestionID` int(10) unsigned NOT NULL,
  `MemberId` int(10) unsigned NOT NULL,
  `vote` int(10) unsigned NOT NULL,
  PRIMARY KEY  (`QuestionID`,`MemberId`)
);

How to extract numbers from a string and get an array of ints?

I found this expression simplest

String[] extractednums = msg.split("\\\\D++");

How do you use String.substringWithRange? (or, how do Ranges work in Swift?)

SWIFT 2.0

simple:

let myString = "full text container"
let substring = myString[myString.startIndex..<myString.startIndex.advancedBy(3)] // prints: ful

SWIFT 3.0

let substring = myString[myString.startIndex..<myString.index(myString.startIndex, offsetBy: 3)] // prints: ful

SWIFT 4.0

Substring operations return an instance of the Substring type, instead of String.

let substring = myString[myString.startIndex..<myString.index(myString.startIndex, offsetBy: 3)] // prints: ful

// Convert the result to a String for long-term storage.
let newString = String(substring)

How to safely upgrade an Amazon EC2 instance from t1.micro to large?

Use the AWS EC2 console, not ElasticFox.

First Way:

  • Create a new AMI of the instance
  • Launch it

Alternative Way:

  • Make a snapshot of the disk
  • Launch a large EBS instance with the same AMI type (please note that at this point the disk will contain the data that was present when this AMI was created, not your latest changes)
  • Once is fully booted, stop the new instance
  • Detach the root volume from the stopped instance
  • Create a virtual disk from the snapshot created before in the same availability zone of the new instance
  • Attach the root volume to /dev/sda1
  • Start the new instance again

sendUserActionEvent() is null

This has to do with having two buttons with the same ID in two different Activities, sometimes Android Studio can't find, You just have to give your button a new ID and re Build the Project

ASP.Net MVC Redirect To A Different View

The simplest way is use return View.

return View("ViewName");

Remember, the physical name of the "ViewName" should be something like ViewName.cshtml in your project, if your are using MVC C# / .NET.

Is it possible to style html5 audio tag?

Yes, it's possible, from @Fábio Zangirolami answer

audio::-webkit-media-controls-panel, video::-webkit-media-controls-panel {
                background-color: red;
}

Why is the minidlna database not being refreshed?

MiniDLNA uses inotify, which is a functionality within the Linux kernel, used to discover changes in specific files and directories on the file system. To get it to work, you need inotify support enabled in your kernel.

The notify_interval (notice the lack of a leading 'i'), as far as I can tell, is only used if you have inotify disabled. To use the notify_interval (ie. get the server to 'poll' the file system for changes instead of automatically being notified of them), you have to disable the inotify functionality.

This is how it looks in my /etc/minidlna.conf:

# set this to no to disable inotify monitoring to automatically discover new files
# note: the default is yes
inotify=yes

Make sure that inotify is enabled in your kernel.

If it's not enabled, and you don't want to enable it, a forced rescan is the way to force MiniDLNA to re-scan the drive.

127 Return code from $?

Generally it means:

127 - command not found

but it can also mean that the command is found,
but a library that is required by the command is NOT found.

Java - Using Accessor and Mutator methods

Let's go over the basics: "Accessor" and "Mutator" are just fancy names fot a getter and a setter. A getter, "Accessor", returns a class's variable or its value. A setter, "Mutator", sets a class variable pointer or its value.

So first you need to set up a class with some variables to get/set:

public class IDCard
{
    private String mName;
    private String mFileName;
    private int mID;

}

But oh no! If you instantiate this class the default values for these variables will be meaningless. B.T.W. "instantiate" is a fancy word for doing:

IDCard test = new IDCard();

So - let's set up a default constructor, this is the method being called when you "instantiate" a class.

public IDCard()
{
    mName = "";
    mFileName = "";
    mID = -1;
}

But what if we do know the values we wanna give our variables? So let's make another constructor, one that takes parameters:

public IDCard(String name, int ID, String filename)
{
    mName = name;
    mID = ID;
    mFileName = filename;
}

Wow - this is nice. But stupid. Because we have no way of accessing (=reading) the values of our variables. So let's add a getter, and while we're at it, add a setter as well:

public String getName()
{
    return mName;
}

public void setName( String name )
{
    mName = name;
}

Nice. Now we can access mName. Add the rest of the accessors and mutators and you're now a certified Java newbie. Good luck.

How to get root directory in yii2

To get the base URL you can use this (would return "http:// localhost/yiistore2/upload")

Yii::app()->baseUrl

The following Code would return just "localhost/yiistore2/upload" without http[s]://

Yii::app()->getBaseUrl(true)

Or you could get the webroot path (would return "d:\wamp\www\yii2store")

Yii::getPathOfAlias('webroot')

Cannot refer to a non-final variable inside an inner class defined in a different method

You cannot refer to non-final variables because Java Language Specification says so. From 8.1.3:
"Any local variable, formal method parameter or exception handler parameter used but not declared in an inner class must be declared final." Whole paragraph.
I can see only part of your code - according to me scheduling modification of local variables is a strange idea. Local variables cease to exist when you leave the function. Maybe static fields of a class would be better?

How do I get logs/details of ansible-playbook module executions?

Offical plugins

You can use the output callback plugins. For example, starting in Ansible 2.4, you can use the debug output callback plugin:

# In ansible.cfg:
[defaults]
stdout_callback = debug

(Altervatively, run export ANSIBLE_STDOUT_CALLBACK=debug before running your playbook)

Important: you must run ansible-playbook with the -v (--verbose) option to see the effect. With stdout_callback = debug set, the output should now look something like this:

TASK [Say Hello] ********************************
changed: [192.168.1.2] => {
    "changed": true,
    "rc": 0
}

STDOUT:


Hello!



STDERR:

Shared connection to 192.168.1.2 closed.

There are other modules besides the debug module if you want the output to be formatted differently. There's json, yaml, unixy, dense, minimal, etc. (full list).

For example, with stdout_callback = yaml, the output will look something like this:

TASK [Say Hello] **********************************
changed: [192.168.1.2] => changed=true 
  rc: 0
  stderr: |-
    Shared connection to 192.168.1.2 closed.
  stderr_lines:
  - Shared connection to 192.168.1.2 closed.
  stdout: |2-

    Hello!
  stdout_lines: <omitted>

Third-party plugins

If none of the official plugins are satisfactory, you can try the human_log plugin. There are a few versions:

Rails raw SQL example

You can execute raw query using ActiveRecord. And I will suggest to go with SQL block

query = <<-SQL 
  SELECT * 
  FROM payment_details
  INNER JOIN projects 
          ON projects.id = payment_details.project_id
  ORDER BY payment_details.created_at DESC
SQL

result = ActiveRecord::Base.connection.execute(query)

use video as background for div

I believe this is what you're looking for. It automatically scaled the video to fit the container.

DEMO: http://jsfiddle.net/t8qhgxuy/

Video need to have height and width always set to 100% of the parent.

HTML:

<div class="one"> CONTENT OVER VIDEO
    <video class="video-background" no-controls autoplay src="https://dl.dropboxusercontent.com/u/8974822/cloud-troopers-video.mp4" poster="http://thumb.multicastmedia.com/thumbs/aid/w/h/t1351705158/1571585.jpg"></video>
</div>

<div class="two">
    <video class="video-background" no-controls autoplay src="https://dl.dropboxusercontent.com/u/8974822/cloud-troopers-video.mp4" poster="http://thumb.multicastmedia.com/thumbs/aid/w/h/t1351705158/1571585.jpg"></video> CONTENT OVER VIDEO
</div>

CSS:

body {
    overflow: scroll;
    padding:  60px 20px;
}

.one {
    width: 90%;
    height: 30vw;
    overflow: hidden;
    border: 15px solid red;
    margin-bottom: 40px;
    position: relative;
}

.two{
    width: 30%;
    height: 300px;
    overflow: hidden;
    border: 15px solid blue;
    position: relative;
}

.video-background { /* class name used in javascript too */
    width: 100%; /* width needs to be set to 100% */
    height: 100%; /* height needs to be set to 100% */
    position: absolute;
    left: 0;
    top: 0;
    z-index: -1;
}

JS:

function scaleToFill() {
    $('video.video-background').each(function(index, videoTag) {
       var $video = $(videoTag),
           videoRatio = videoTag.videoWidth / videoTag.videoHeight,
           tagRatio = $video.width() / $video.height(),
           val;

       if (videoRatio < tagRatio) {
           val = tagRatio / videoRatio * 1.02; <!-- size increased by 2% because value is not fine enough and sometimes leaves a couple of white pixels at the edges -->
       } else if (tagRatio < videoRatio) {
           val = videoRatio / tagRatio * 1.02;
       }

       $video.css('transform','scale(' + val  + ',' + val + ')');

    });    
}

$(function () {
    scaleToFill();

    $('.video-background').on('loadeddata', scaleToFill);

    $(window).resize(function() {
        scaleToFill();
    });
});

Including a .js file within a .js file

The best solution for your browser load time would be to use a server side script to join them all together into one big .js file. Make sure to gzip/minify the final version. Single request - nice and compact.

Alternatively, you can use DOM to create a <script> tag and set the src property on it then append it to the <head>. If you need to wait for that functionality to load, you can make the rest of your javascript file be called from the load event on that script tag.

This function is based on the functionality of jQuery $.getScript()

function loadScript(src, f) {
  var head = document.getElementsByTagName("head")[0];
  var script = document.createElement("script");
  script.src = src;
  var done = false;
  script.onload = script.onreadystatechange = function() { 
    // attach to both events for cross browser finish detection:
    if ( !done && (!this.readyState ||
      this.readyState == "loaded" || this.readyState == "complete") ) {
      done = true;
      if (typeof f == 'function') f();
      // cleans up a little memory:
      script.onload = script.onreadystatechange = null;
      head.removeChild(script);
    }
  };
  head.appendChild(script);
}

// example:
loadScript('/some-other-script.js', function() { 
   alert('finished loading');
   finishSetup();
 });

How to convert Java String to JSON Object

@Nishit, JSONObject does not natively understand how to parse through a StringBuilder; instead you appear to be using the JSONObject(java.lang.Object bean) constructor to create the JSONObject, however passing it a StringBuilder.

See this link for more information on that particular constructor.

http://www.json.org/javadoc/org/json/JSONObject.html#JSONObject%28java.lang.Object%29

When a constructor calls for a java.lang.Object class, more than likely it's really telling you that you're expected to create your own class (since all Classes ultimately extend java.lang.Object) and that it will interface with that class in a specific way, albeit normally it will call for an interface instead (hence the name) OR it can accept any class and interface with it "abstractly" such as calling .toString() on it. Bottom line, you typically can't just pass it any class and expect it to work.

At any rate, this particular constructor is explained as such:

Construct a JSONObject from an Object using bean getters. It reflects on all of the public methods of the object. For each of the methods with no parameters and a name starting with "get" or "is" followed by an uppercase letter, the method is invoked, and a key and the value returned from the getter method are put into the new JSONObject. The key is formed by removing the "get" or "is" prefix. If the second remaining character is not upper case, then the first character is converted to lower case. For example, if an object has a method named "getName", and if the result of calling object.getName() is "Larry Fine", then the JSONObject will contain "name": "Larry Fine".

So, what this means is that it's expecting you to create your own class that implements get or is methods (i.e.

public String getName() {...}

or

public boolean isValid() {...}

So, to solve your problem, if you really want that higher level of control and want to do some manipulation (e.g. modify some values, etc.) but still use StringBuilder to dynamically generate the code, you can create a class that extends the StringBuilder class so that you can use the append feature, but implement get/is methods to allow JSONObject to pull the data out of it, however this is likely not what you want/need and depending on the JSON, you might spend a lot of time and energy creating the private fields and get/is methods (or use an IDE to do it for you) or it might be all for naught if you don't necessarily know the breakdown of the JSON string.

So, you can very simply call toString() on the StringBuilder which will provide a String representation of the StringBuilder instance and passing that to the JSONObject constructor, such as below:

...
StringBuilder jsonString = new StringBuilder();
while((readAPIResponse = br.readLine()) != null){
    jsonString.append(readAPIResponse);
}
JSONObject jsonObj = new JSONObject(jsonString.toString());
...

Change DIV content using ajax, php and jQuery

try this

   function getmoviename(id)
   {    
     var p_url= yoururl from where you get movie name,
     jQuery.ajax({
     type: "GET",             
     url: p_url,
     data: "id=" + id,
      success: function(data) {
       $('#summary').html(data);

    }
 });    
 }

and you html part is

  <a href="javascript:void(0);" class="movie" onclick="getmoviename(youridvariable)">
  Name of movie</a>

  <div id="summary">Here is summary of movie</div>

How do you create nested dict in Python?

If you want to create a nested dictionary given a list (arbitrary length) for a path and perform a function on an item that may exist at the end of the path, this handy little recursive function is quite helpful:

def ensure_path(data, path, default=None, default_func=lambda x: x):
    """
    Function:

    - Ensures a path exists within a nested dictionary

    Requires:

    - `data`:
        - Type: dict
        - What: A dictionary to check if the path exists
    - `path`:
        - Type: list of strs
        - What: The path to check

    Optional:

    - `default`:
        - Type: any
        - What: The default item to add to a path that does not yet exist
        - Default: None

    - `default_func`:
        - Type: function
        - What: A single input function that takes in the current path item (or default) and adjusts it
        - Default: `lambda x: x` # Returns the value in the dict or the default value if none was present
    """
    if len(path)>1:
        if path[0] not in data:
            data[path[0]]={}
        data[path[0]]=ensure_path(data=data[path[0]], path=path[1:], default=default, default_func=default_func)
    else:
        if path[0] not in data:
            data[path[0]]=default
        data[path[0]]=default_func(data[path[0]])
    return data

Example:

data={'a':{'b':1}}
ensure_path(data=data, path=['a','c'], default=[1])
print(data) #=> {'a':{'b':1, 'c':[1]}}
ensure_path(data=data, path=['a','c'], default=[1], default_func=lambda x:x+[2])
print(data) #=> {'a': {'b': 1, 'c': [1, 2]}}

Prevent a webpage from navigating away using JavaScript

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

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

A more appropriate error message might be:

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

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

How to easily initialize a list of Tuples?

c# 7.0 lets you do this:

  var tupleList = new List<(int, string)>
  {
      (1, "cow"),
      (5, "chickens"),
      (1, "airplane")
  };

If you don't need a List, but just an array, you can do:

  var tupleList = new(int, string)[]
  {
      (1, "cow"),
      (5, "chickens"),
      (1, "airplane")
  };

And if you don't like "Item1" and "Item2", you can do:

  var tupleList = new List<(int Index, string Name)>
  {
      (1, "cow"),
      (5, "chickens"),
      (1, "airplane")
  };

or for an array:

  var tupleList = new (int Index, string Name)[]
  {
      (1, "cow"),
      (5, "chickens"),
      (1, "airplane")
  };

which lets you do: tupleList[0].Index and tupleList[0].Name

Framework 4.6.2 and below

You must install System.ValueTuple from the Nuget Package Manager.

Framework 4.7 and above

It is built into the framework. Do not install System.ValueTuple. In fact, remove it and delete it from the bin directory.

note: In real life, I wouldn't be able to choose between cow, chickens or airplane. I would be really torn.

macro run-time error '9': subscript out of range

Why are you using a macro? Excel has Password Protection built-in. When you select File/Save As... there should be a Tools button by the Save button, click it then "General Options" where you can enter a "Password to Open" and a "Password to Modify".

how to add jquery in laravel project

you can use online library

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

or else download library and add css in css folder and jquery in js folder.both folder you keep in laravel public folder then you can link like below

<link rel="stylesheet" href="{{asset('css/bootstrap-theme.min.css')}}">
<script src="{{asset('js/jquery.min.js')}}"></script>

or else

{{ HTML::style('css/style.css') }}
{{ HTML::script('js/functions.js') }}

JSON and escaping characters

This is not a bug in either implementation. There is no requirement to escape U+00B0. To quote the RFC:

2.5. Strings

The representation of strings is similar to conventions used in the C family of programming languages. A string begins and ends with quotation marks. All Unicode characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F).

Any character may be escaped.

Escaping everything inflates the size of the data (all code points can be represented in four or fewer bytes in all Unicode transformation formats; whereas encoding them all makes them six or twelve bytes).

It is more likely that you have a text transcoding bug somewhere in your code and escaping everything in the ASCII subset masks the problem. It is a requirement of the JSON spec that all data use a Unicode encoding.

What's the difference between process.cwd() vs __dirname?

process.cwd() returns the current working directory,

i.e. the directory from which you invoked the node command.

__dirname returns the directory name of the directory containing the JavaScript source code file

SQL - How do I get only the numbers after the decimal?

The usual hack (which varies a bit in syntax) is

x - floor(x)

That's the fractional part. To make into an integer, scale it.

(x - floor(x)) * 1000

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

If we stop the algorithm in middle prim's algorithm always generates connected tree, but kruskal on the other hand can give disconnected tree or forest

jQuery scroll() detect when user stops scrolling

please check the jquery mobile scrollstop event

$(document).on("scrollstop",function(){
  alert("Stopped scrolling!");
});

Passing Arrays to Function in C++

The simple answer is that arrays are ALWAYS passed by reference and the int arg[] simply lets the compiler know to expect an array

How to convert object array to string array in Java

For your idea, actually you are approaching the success, but if you do like this should be fine:

for (int i=0;i<String_Array.length;i++) String_Array[i]=(String)Object_Array[i];

BTW, using the Arrays utility method is quite good and make the code elegant.

Changing navigation bar color in Swift

iOS 10 Swift 3.0

If you don't mind to use swift frameworks then us UINeraida to change navigation background as UIColor or HexColor or UIImage and change navigation back button text programmatically, change complete forground text color.

For UINavigationBar

    neraida.navigation.background.color.hexColor("54ad00", isTranslucent: false, viewController: self)
    
    //Change navigation title, backbutton colour
    
    neraida.navigation.foreground.color.uiColor(UIColor.white, viewController: self)
    
    //Change navigation back button title programmatically
    
    neraida.navigation.foreground.backButtonTitle("Custom Title", ViewController: self)
    
    //Apply Background Image to the UINavigationBar
    
    neraida.navigation.background.image("background", edge: (0,0,0,0), barMetrics: .default, isTranslucent: false, viewController: self)

How to search in a List of Java object

I modifie this list and add a List to the samples try this

Pseudocode

Sample {
   List<String> values;
   List<String> getList() {
   return values}
}



for(Sample s : list) {
   if(s.getString.getList.contains("three") {
      return s;
   }
}

EPPlus - Read Excel Table

Below code will read excel data into a datatable, which is converted to list of datarows.

if (FileUpload1.HasFile)
{
    if (Path.GetExtension(FileUpload1.FileName) == ".xlsx")
    {
        Stream fs = FileUpload1.FileContent;
        ExcelPackage package = new ExcelPackage(fs);
        DataTable dt = new DataTable();
        dt= package.ToDataTable();
        List<DataRow> listOfRows = new List<DataRow>();
        listOfRows = dt.AsEnumerable().ToList();

    }
}
using OfficeOpenXml;
using System.Data;
using System.Linq;

 public static class ExcelPackageExtensions
    {
        public static DataTable ToDataTable(this ExcelPackage package)
        {
            ExcelWorksheet workSheet = package.Workbook.Worksheets.First();
            DataTable table = new DataTable();
            foreach (var firstRowCell in workSheet.Cells[1, 1, 1, workSheet.Dimension.End.Column])
            {
                table.Columns.Add(firstRowCell.Text);
            }

            for (var rowNumber = 2; rowNumber <= workSheet.Dimension.End.Row; rowNumber++)
            {
                var row = workSheet.Cells[rowNumber, 1, rowNumber, workSheet.Dimension.End.Column];
                var newRow = table.NewRow();
                foreach (var cell in row)
                {
                    newRow[cell.Start.Column - 1] = cell.Text;
                }
                table.Rows.Add(newRow);
            }
            return table;
        }

    }

Where are Docker images stored on the host machine?

Actually, Docker images are stored in two files as shown by following command

$ docker info

Data file: /var/lib/docker/devicemapper/devicemapper/data

Metadata file: /var/lib/docker/devicemapper/devicemapper/metadata

merge one local branch into another local branch

Just in case you arrived here because you copied a branch name from Github, note that a remote branch is not automatically also a local branch, so a merge will not work and give the "not something we can merge" error.

In that case, you have two options:

git checkout [branchYouWantToMergeInto]
git merge origin/[branchYouWantToMerge]

or

# this creates a local branch
git checkout [branchYouWantToMerge]

git checkout [branchYouWantToMergeInto]
git merge [branchYouWantToMerge]

Could not load file or assembly "System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

Change following:

<bindingRedirect oldVersion="0.0.0.0-4.1.1.2" newVersion="4.1.1.2" />

with the following:

<bindingRedirect oldVersion="0.0.0.0-4.1.1.2" newVersion="4.0.0.0" />

in web.config

What are the new features in C++17?

Language features:

Templates and Generic Code

Lambda

Attributes

Syntax cleanup

Cleaner multi-return and flow control

  • Structured bindings

    • Basically, first-class std::tie with auto
    • Example:
      • const auto [it, inserted] = map.insert( {"foo", bar} );
      • Creates variables it and inserted with deduced type from the pair that map::insert returns.
    • Works with tuple/pair-likes & std::arrays and relatively flat structs
    • Actually named structured bindings in standard
  • if (init; condition) and switch (init; condition)

    • if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
    • Extends the if(decl) to cases where decl isn't convertible-to-bool sensibly.
  • Generalizing range-based for loops

    • Appears to be mostly support for sentinels, or end iterators that are not the same type as begin iterators, which helps with null-terminated loops and the like.
  • if constexpr

    • Much requested feature to simplify almost-generic code.

Misc

Library additions:

Data types

Invoke stuff

File System TS v1

New algorithms

  • for_each_n

  • reduce

  • transform_reduce

  • exclusive_scan

  • inclusive_scan

  • transform_exclusive_scan

  • transform_inclusive_scan

  • Added for threading purposes, exposed even if you aren't using them threaded

Threading

(parts of) Library Fundamentals TS v1 not covered above or below

Container Improvements

Smart pointer changes

Other std datatype improvements:

Misc

Traits

Deprecated

Isocpp.org has has an independent list of changes since C++14; it has been partly pillaged.

Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.

Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.

Additional entries pillaged from SD-6 feature-test list.

clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.

these slides had some features missing elsewhere.

While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:

Removed:

There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:

Papers not yet integrated into above:

  • P0505R0 (constexpr chrono)

  • P0418R2 (atomic tweaks)

  • P0512R0 (template argument deduction tweaks)

  • P0490R0 (structured binding tweaks)

  • P0513R0 (changes to std::hash)

  • P0502R0 (parallel exceptions)

  • P0509R1 (updating restrictions on exception handling)

  • P0012R1 (make exception specifications be part of the type system)

  • P0510R0 (restrictions on variants)

  • P0504R0 (tags for optional/variant/any)

  • P0497R0 (shared ptr tweaks)

  • P0508R0 (structured bindings node handles)

  • P0521R0 (shared pointer use count and unique changes?)

Spec changes:

Further reference:

How to Read and Write from the Serial Port

I spent a lot of time to use SerialPort class and has concluded to use SerialPort.BaseStream class instead. You can see source code: SerialPort-source and SerialPort.BaseStream-source for deep understanding. I created and use code that shown below.

  • The core function public int Recv(byte[] buffer, int maxLen) has name and works like "well known" socket's recv().

  • It means that

    • in one hand it has timeout for no any data and throws TimeoutException.
    • In other hand, when any data has received,
      • it receives data either until maxLen bytes
      • or short timeout (theoretical 6 ms) in UART data flow

.

public class Uart : SerialPort

    {
        private int _receiveTimeout;

        public int ReceiveTimeout { get => _receiveTimeout; set => _receiveTimeout = value; }

        static private string ComPortName = "";

        /// <summary>
        /// It builds PortName using ComPortNum parameter and opens SerialPort.
        /// </summary>
        /// <param name="ComPortNum"></param>
        public Uart(int ComPortNum) : base()
        {
            base.BaudRate = 115200; // default value           
            _receiveTimeout = 2000;
            ComPortName = "COM" + ComPortNum;

            try
            {
                base.PortName = ComPortName;
                base.Open();
            }
            catch (UnauthorizedAccessException ex)
            {
                Console.WriteLine("Error: Port {0} is in use", ComPortName);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Uart exception: " + ex);
            }
        } //Uart()

        /// <summary>
        /// Private property returning positive only Environment.TickCount
        /// </summary>
        private int _tickCount { get => Environment.TickCount & Int32.MaxValue; }


        /// <summary>
        /// It uses SerialPort.BaseStream rather SerialPort functionality .
        /// It Receives up to maxLen number bytes of data, 
        /// Or throws TimeoutException if no any data arrived during ReceiveTimeout. 
        /// It works likes socket-recv routine (explanation in body).
        /// Returns:
        ///    totalReceived - bytes, 
        ///    TimeoutException,
        ///    -1 in non-ComPortNum Exception  
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="maxLen"></param>
        /// <returns></returns>
        public int Recv(byte[] buffer, int maxLen)
        {
            /// The routine works in "pseudo-blocking" mode. It cycles up to first 
            /// data received using BaseStream.ReadTimeout = TimeOutSpan (2 ms).
            /// If no any message received during ReceiveTimeout property, 
            /// the routine throws TimeoutException 
            /// In other hand, if any data has received, first no-data cycle
            /// causes to exit from routine.

            int TimeOutSpan = 2;
            // counts delay in TimeOutSpan-s after end of data to break receive
            int EndOfDataCnt;
            // pseudo-blocking timeout counter
            int TimeOutCnt = _tickCount + _receiveTimeout; 
            //number of currently received data bytes
            int justReceived = 0;
            //number of total received data bytes
            int totalReceived = 0;

            BaseStream.ReadTimeout = TimeOutSpan;
            //causes (2+1)*TimeOutSpan delay after end of data in UART stream
            EndOfDataCnt = 2;
            while (_tickCount < TimeOutCnt && EndOfDataCnt > 0)
            {
                try
                {
                    justReceived = 0; 
                    justReceived = base.BaseStream.Read(buffer, totalReceived, maxLen - totalReceived);
                    totalReceived += justReceived;

                    if (totalReceived >= maxLen)
                        break;
                }
                catch (TimeoutException)
                {
                    if (totalReceived > 0) 
                        EndOfDataCnt--;
                }
                catch (Exception ex)
                {                   
                    totalReceived = -1;
                    base.Close();
                    Console.WriteLine("Recv exception: " + ex);
                    break;
                }

            } //while
            if (totalReceived == 0)
            {              
                throw new TimeoutException();
            }
            else
            {               
                return totalReceived;
            }
        } // Recv()            
    } // Uart

How to get the current date and time

In Java 8 it's:

ZonedDateTime dateTime = ZonedDateTime.now();

How can I get dict from sqlite query?

You could use row_factory, as in the example in the docs:

import sqlite3

def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

con = sqlite3.connect(":memory:")
con.row_factory = dict_factory
cur = con.cursor()
cur.execute("select 1 as a")
print cur.fetchone()["a"]

or follow the advice that's given right after this example in the docs:

If returning a tuple doesn’t suffice and you want name-based access to columns, you should consider setting row_factory to the highly-optimized sqlite3.Row type. Row provides both index-based and case-insensitive name-based access to columns with almost no memory overhead. It will probably be better than your own custom dictionary-based approach or even a db_row based solution.

Use multiple custom fonts using @font-face?

Check out fontsquirrel. They have a web font generator, which will also spit out a suitable stylesheet for your font (look for "@font-face kit"). This stylesheet can be included in your own, or you can use it as a template.

Java ArrayList copy

Yes l1 and l2 will point to the same reference, same object.

If you want to create a new ArrayList based on the other ArrayList you do this:

List<String> l1 = new ArrayList<String>();
l1.add("Hello");
l1.add("World");
List<String> l2 = new ArrayList<String>(l1); //A new arrayList.
l2.add("Everybody");

The result will be l1 will still have 2 elements and l2 will have 3 elements.

sort json object in javascript

In some ways, your question seems very legitimate, but I still might label it an XY problem. I'm guessing the end result is that you want to display the sorted values in some way? As Bergi said in the comments, you can never quite rely on Javascript objects ( {i_am: "an_object"} ) to show their properties in any particular order.

For the displaying order, I might suggest you take each key of the object (ie, i_am) and sort them into an ordered array. Then, use that array when retrieving elements of your object to display. Pseudocode:

var keys = [...]
var sortedKeys = [...]
for (var i = 0; i < sortedKeys.length; i++) {
  var key = sortedKeys[i];
  addObjectToTable(json[key]);
}

Android getActivity() is undefined

If you want to call your activity, just use this . You use the getActivity method when you are inside a fragment.

Getting Lat/Lng from Google marker

You could just call getPosition() on the Marker - have you tried that?

If you're on the deprecated, v2 of the JavaScript API, you can call getLatLng() on GMarker.

How to import a module in Python with importlib.import_module

I think it's better to use importlib.import_module('.c', __name__) since you don't need to know about a and b.

I'm also wondering that, if you have to use importlib.import_module('a.b.c'), why not just use import a.b.c?

How to allow user to pick the image with Swift?

Of course, above answers solve the main problem.

I faced a crash in Swift 3.0 while launching the photo album because Info.plist did not had these flags:

  1. Privacy - Photo Library Usage Description -> NSPhotoLibraryUsageDescription

  2. Privacy - Camera Usage Description -> NSCameraUsageDescription

[screenshot[1]

Please add them if you face similar issue.

Thanks !

Java regex capturing groups indexes

Capturing and grouping

Capturing group (pattern) creates a group that has capturing property.

A related one that you might often see (and use) is (?:pattern), which creates a group without capturing property, hence named non-capturing group.

A group is usually used when you need to repeat a sequence of patterns, e.g. (\.\w+)+, or to specify where alternation should take effect, e.g. ^(0*1|1*0)$ (^, then 0*1 or 1*0, then $) versus ^0*1|1*0$ (^0*1 or 1*0$).

A capturing group, apart from grouping, will also record the text matched by the pattern inside the capturing group (pattern). Using your example, (.*):, .* matches ABC and : matches :, and since .* is inside capturing group (.*), the text ABC is recorded for the capturing group 1.

Group number

The whole pattern is defined to be group number 0.

Any capturing group in the pattern start indexing from 1. The indices are defined by the order of the opening parentheses of the capturing groups. As an example, here are all 5 capturing groups in the below pattern:

(group)(?:non-capturing-group)(g(?:ro|u)p( (nested)inside)(another)group)(?=assertion)
|     |                       |          | |      |      ||       |     |
1-----1                       |          | 4------4      |5-------5     |
                              |          3---------------3              |
                              2-----------------------------------------2

The group numbers are used in back-reference \n in pattern and $n in replacement string.

In other regex flavors (PCRE, Perl), they can also be used in sub-routine calls.

You can access the text matched by certain group with Matcher.group(int group). The group numbers can be identified with the rule stated above.

In some regex flavors (PCRE, Perl), there is a branch reset feature which allows you to use the same number for capturing groups in different branches of alternation.

Group name

From Java 7, you can define a named capturing group (?<name>pattern), and you can access the content matched with Matcher.group(String name). The regex is longer, but the code is more meaningful, since it indicates what you are trying to match or extract with the regex.

The group names are used in back-reference \k<name> in pattern and ${name} in replacement string.

Named capturing groups are still numbered with the same numbering scheme, so they can also be accessed via Matcher.group(int group).

Internally, Java's implementation just maps from the name to the group number. Therefore, you cannot use the same name for 2 different capturing groups.