Programs & Examples On #Accordionpane

is a GUI element consisting of a vertically stacked list of items. Each item can be expanded to show more content.

Iterate keys in a C++ map

Without Boost, you could do it like this. It would be nice if you could write a cast operator instead of getKeyIterator(), but I can't get it to compile.

#include <map>
#include <unordered_map>


template<typename K, typename V>
class key_iterator: public std::unordered_map<K,V>::iterator {

public:

    const K &operator*() const {
        return std::unordered_map<K,V>::iterator::operator*().first;
    }

    const K *operator->() const {
        return &(**this);
    }
};

template<typename K,typename V>
key_iterator<K,V> getKeyIterator(typename std::unordered_map<K,V>::iterator &it) {
    return *static_cast<key_iterator<K,V> *>(&it);
}

int _tmain(int argc, _TCHAR* argv[])
{
    std::unordered_map<std::string, std::string> myMap;
    myMap["one"]="A";
    myMap["two"]="B";
    myMap["three"]="C";
    key_iterator<std::string, std::string> &it=getKeyIterator<std::string,std::string>(myMap.begin());
    for (; it!=myMap.end(); ++it) {
        printf("%s\n",it->c_str());
    }
}

git: diff between file in local repo and origin

If [remote-path] and [local-path] are the same, you can do

$ git fetch origin master
$ git diff origin/master -- [local-path]

Note 1: The second command above will compare against the locally stored remote tracking branch. The fetch command is required to update the remote tracking branch to be in sync with the contents of the remote server. Alternatively, you can just do

$ git diff master:<path-or-file-name>

Note 2: master can be replaced in the above examples with any branch name

Powershell v3 Invoke-WebRequest HTTPS error

An alternative implementation in pure (without Add-Type of source):

#requires -Version 5
#requires -PSEdition Desktop

class TrustAllCertsPolicy : System.Net.ICertificatePolicy {
    [bool] CheckValidationResult([System.Net.ServicePoint] $a,
                                 [System.Security.Cryptography.X509Certificates.X509Certificate] $b,
                                 [System.Net.WebRequest] $c,
                                 [int] $d) {
        return $true
    }
}
[System.Net.ServicePointManager]::CertificatePolicy = [TrustAllCertsPolicy]::new()

`node-pre-gyp install --fallback-to-build` failed during MeanJS installation on OSX

Just use this command and it will handle this error npm install --unsafe-perm --allow-root

How to convert base64 string to image?

You can try using open-cv to save the file since it helps with image type conversions internally. The sample code:

import cv2
import numpy as np

def save(encoded_data, filename):
    nparr = np.fromstring(encoded_data.decode('base64'), np.uint8)
    img = cv2.imdecode(nparr, cv2.IMREAD_ANYCOLOR)
    return cv2.imwrite(filename, img)

Then somewhere in your code you can use it like this:

save(base_64_string, 'testfile.png');
save(base_64_string, 'testfile.jpg');
save(base_64_string, 'testfile.bmp');

Print the data in ResultSet along with column names

For those who wanted more better version of the resultset printing as util class This was really helpful for printing resultset and does many things from a single util... thanks to Hami Torun!

In this class printResultSet uses ResultSetMetaData in a generic way have a look at it..


import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

public final class DBTablePrinter {

    /**
     * Column type category for CHAR, VARCHAR
     * and similar text columns.
     */
    public static final int CATEGORY_STRING = 1;
    /**
     * Column type category for TINYINT, SMALLINT,
     * INT and BIGINT columns.
     */
    public static final int CATEGORY_INTEGER = 2;
    /**
     * Column type category for REAL, DOUBLE,
     * and DECIMAL columns.
     */
    public static final int CATEGORY_DOUBLE = 3;
    /**
     * Column type category for date and time related columns like
     * DATE, TIME, TIMESTAMP etc.
     */
    public static final int CATEGORY_DATETIME = 4;
    /**
     * Column type category for BOOLEAN columns.
     */
    public static final int CATEGORY_BOOLEAN = 5;
    /**
     * Column type category for types for which the type name
     * will be printed instead of the content, like BLOB,
     * BINARY, ARRAY etc.
     */
    public static final int CATEGORY_OTHER = 0;
    /**
     * Default maximum number of rows to query and print.
     */
    private static final int DEFAULT_MAX_ROWS = 10;
    /**
     * Default maximum width for text columns
     * (like a VARCHAR) column.
     */
    private static final int DEFAULT_MAX_TEXT_COL_WIDTH = 150;

    /**
     * Overloaded method that prints rows from table tableName
     * to standard out using the given database connection
     * conn. Total number of rows will be limited to
     * {@link #DEFAULT_MAX_ROWS} and
     * {@link #DEFAULT_MAX_TEXT_COL_WIDTH} will be used to limit
     * the width of text columns (like a VARCHAR column).
     *
     * @param conn      Database connection object (java.sql.Connection)
     * @param tableName Name of the database table
     */
    public static void printTable(Connection conn, String tableName) {
        printTable(conn, tableName, DEFAULT_MAX_ROWS, DEFAULT_MAX_TEXT_COL_WIDTH);
    }

    /**
     * Overloaded method that prints rows from table tableName
     * to standard out using the given database connection
     * conn. Total number of rows will be limited to
     * maxRows and
     * {@link #DEFAULT_MAX_TEXT_COL_WIDTH} will be used to limit
     * the width of text columns (like a VARCHAR column).
     *
     * @param conn      Database connection object (java.sql.Connection)
     * @param tableName Name of the database table
     * @param maxRows   Number of max. rows to query and print
     */
    public static void printTable(Connection conn, String tableName, int maxRows) {
        printTable(conn, tableName, maxRows, DEFAULT_MAX_TEXT_COL_WIDTH);
    }

    /**
     * Overloaded method that prints rows from table tableName
     * to standard out using the given database connection
     * conn. Total number of rows will be limited to
     * maxRows and
     * maxStringColWidth will be used to limit
     * the width of text columns (like a VARCHAR column).
     *
     * @param conn              Database connection object (java.sql.Connection)
     * @param tableName         Name of the database table
     * @param maxRows           Number of max. rows to query and print
     * @param maxStringColWidth Max. width of text columns
     */
    public static void printTable(Connection conn, String tableName, int maxRows, int maxStringColWidth) {
        if (conn == null) {
            System.err.println("DBTablePrinter Error: No connection to database (Connection is null)!");
            return;
        }
        if (tableName == null) {
            System.err.println("DBTablePrinter Error: No table name (tableName is null)!");
            return;
        }
        if (tableName.length() == 0) {
            System.err.println("DBTablePrinter Error: Empty table name!");
            return;
        }
        if (maxRows 
     * ResultSet to standard out using {@link #DEFAULT_MAX_TEXT_COL_WIDTH}
     * to limit the width of text columns.
     *
     * @param rs The ResultSet to print
     */
    public static void printResultSet(ResultSet rs) {
        printResultSet(rs, DEFAULT_MAX_TEXT_COL_WIDTH);
    }

    /**
     * Overloaded method to print rows of a 
     * ResultSet to standard out using maxStringColWidth
     * to limit the width of text columns.
     *
     * @param rs                The ResultSet to print
     * @param maxStringColWidth Max. width of text columns
     */
    public static void printResultSet(ResultSet rs, int maxStringColWidth) {
        try {
            if (rs == null) {
                System.err.println("DBTablePrinter Error: Result set is null!");
                return;
            }
            if (rs.isClosed()) {
                System.err.println("DBTablePrinter Error: Result Set is closed!");
                return;
            }
            if (maxStringColWidth  columns = new ArrayList(columnCount);

            // List of table names. Can be more than one if it is a joined
            // table query
            List tableNames = new ArrayList(columnCount);

            // Get the columns and their meta data.
            // NOTE: columnIndex for rsmd.getXXX methods STARTS AT 1 NOT 0
            for (int i = 1; i  maxStringColWidth) {
                                value = value.substring(0, maxStringColWidth - 3) + "...";
                            }
                            break;
                    }

                    // Adjust the column width
                    c.setWidth(value.length() > c.getWidth() ? value.length() : c.getWidth());
                    c.addValue(value);
                } // END of for loop columnCount
                rowCount++;

            } // END of while (rs.next)

            /*
            At this point we have gone through meta data, get the
            columns and created all Column objects, iterated over the
            ResultSet rows, populated the column values and adjusted
            the column widths.
            We cannot start printing just yet because we have to prepare
            a row separator String.
             */

            // For the fun of it, I will use StringBuilder
            StringBuilder strToPrint = new StringBuilder();
            StringBuilder rowSeparator = new StringBuilder();

            /*
            Prepare column labels to print as well as the row separator.
            It should look something like this:
            +--------+------------+------------+-----------+  (row separator)
            | EMP_NO | BIRTH_DATE | FIRST_NAME | LAST_NAME |  (labels row)
            +--------+------------+------------+-----------+  (row separator)
             */

            // Iterate over columns
            for (Column c : columns) {
                int width = c.getWidth();

                // Center the column label
                String toPrint;
                String name = c.getLabel();
                int diff = width - name.length();

                if ((diff % 2) == 1) {
                    // diff is not divisible by 2, add 1 to width (and diff)
                    // so that we can have equal padding to the left and right
                    // of the column label.
                    width++;
                    diff++;
                    c.setWidth(width);
                }

                int paddingSize = diff / 2; // InteliJ says casting to int is redundant.

                // Cool String repeater code thanks to user102008 at stackoverflow.com

                String padding = new String(new char[paddingSize]).replace("\0", " ");

                toPrint = "| " + padding + name + padding + " ";
                // END centering the column label

                strToPrint.append(toPrint);

                rowSeparator.append("+");
                rowSeparator.append(new String(new char[width + 2]).replace("\0", "-"));
            }

            String lineSeparator = System.getProperty("line.separator");

            // Is this really necessary ??
            lineSeparator = lineSeparator == null ? "\n" : lineSeparator;

            rowSeparator.append("+").append(lineSeparator);

            strToPrint.append("|").append(lineSeparator);
            strToPrint.insert(0, rowSeparator);
            strToPrint.append(rowSeparator);

            StringJoiner sj = new StringJoiner(", ");
            for (String name : tableNames) {
                sj.add(name);
            }

            String info = "Printing " + rowCount;
            info += rowCount > 1 ? " rows from " : " row from ";
            info += tableNames.size() > 1 ? "tables " : "table ";
            info += sj.toString();

            System.out.println(info);

            // Print out the formatted column labels
            System.out.print(strToPrint.toString());

            String format;

            // Print out the rows
            for (int i = 0; i 
     * Integers should not be truncated so column widths should
     * be adjusted without a column width limit. Text columns should be
     * left justified and can be truncated to a max. column width etc...

*

* See also: * java.sql.Types * * @param type Generic SQL type * @return The category this type belongs to */ private static int whichCategory(int type) { switch (type) { case Types.BIGINT: case Types.TINYINT: case Types.SMALLINT: case Types.INTEGER: return CATEGORY_INTEGER; case Types.REAL: case Types.DOUBLE: case Types.DECIMAL: return CATEGORY_DOUBLE; case Types.DATE: case Types.TIME: case Types.TIME_WITH_TIMEZONE: case Types.TIMESTAMP: case Types.TIMESTAMP_WITH_TIMEZONE: return CATEGORY_DATETIME; case Types.BOOLEAN: return CATEGORY_BOOLEAN; case Types.VARCHAR: case Types.NVARCHAR: case Types.LONGVARCHAR: case Types.LONGNVARCHAR: case Types.CHAR: case Types.NCHAR: return CATEGORY_STRING; default: return CATEGORY_OTHER; } } /** * Represents a database table column. */ private static class Column { /** * Column label. */ private String label; /** * Generic SQL type of the column as defined in * * java.sql.Types * . */ private int type; /** * Generic SQL type name of the column as defined in * * java.sql.Types * . */ private String typeName; /** * Width of the column that will be adjusted according to column label * and values to be printed. */ private int width = 0; /** * Column values from each row of a ResultSet. */ private List values = new ArrayList(); /** * Flag for text justification using String.format. * Empty string ("") to justify right, * dash (-) to justify left. * * @see #justifyLeft() */ private String justifyFlag = ""; /** * Column type category. The columns will be categorised according * to their column types and specific needs to print them correctly. */ private int typeCategory = 0; /** * Constructs a new Column with a column label, * generic SQL type and type name (as defined in * * java.sql.Types * ) * * @param label Column label or name * @param type Generic SQL type * @param typeName Generic SQL type name */ public Column(String label, int type, String typeName) { this.label = label; this.type = type; this.typeName = typeName; } /** * Returns the column label * * @return Column label */ public String getLabel() { return label; } /** * Returns the generic SQL type of the column * * @return Generic SQL type */ public int getType() { return type; } /** * Returns the generic SQL type name of the column * * @return Generic SQL type name */ public String getTypeName() { return typeName; } /** * Returns the width of the column * * @return Column width */ public int getWidth() { return width; } /** * Sets the width of the column to width * * @param width Width of the column */ public void setWidth(int width) { this.width = width; } /** * Adds a String representation (value) * of a value to this column object's {@link #values} list. * These values will come from each row of a * * ResultSet * of a database query. * * @param value The column value to add to {@link #values} */ public void addValue(String value) { values.add(value); } /** * Returns the column value at row index i. * Note that the index starts at 0 so that getValue(0) * will get the value for this column from the first row * of a * ResultSet. * * @param i The index of the column value to get * @return The String representation of the value */ public String getValue(int i) { return values.get(i); } /** * Returns the value of the {@link #justifyFlag}. The column * values will be printed using String.format and * this flag will be used to right or left justify the text. * * @return The {@link #justifyFlag} of this column * @see #justifyLeft() */ public String getJustifyFlag() { return justifyFlag; } /** * Sets {@link #justifyFlag} to "-" so that * the column value will be left justified when printed with * String.format. Typically numbers will be right * justified and text will be left justified. */ public void justifyLeft() { this.justifyFlag = "-"; } /** * Returns the generic SQL type category of the column * * @return The {@link #typeCategory} of the column */ public int getTypeCategory() { return typeCategory; } /** * Sets the {@link #typeCategory} of the column * * @param typeCategory The type category */ public void setTypeCategory(int typeCategory) { this.typeCategory = typeCategory; } } }

This is the scala version of doing this... which will print column names and data as well in a generic way...

def printQuery(res: ResultSet): Unit = {
    val rsmd = res.getMetaData
    val columnCount = rsmd.getColumnCount
    var rowCnt = 0
    val s = StringBuilder.newBuilder
    while (res.next()) {

      s.clear()
      if (rowCnt == 0) {
        s.append("| ")
        for (i <- 1 to columnCount) {
          val name = rsmd.getColumnName(i)
          s.append(name)
          s.append("| ")
        }
        s.append("\n")
      }
      rowCnt += 1
      s.append("| ")
      for (i <- 1 to columnCount) {
        if (i > 1)
          s.append(" | ")
        s.append(res.getString(i))
      }
      s.append(" |")
      System.out.println(s)
    }
    System.out.println(s"TOTAL: $rowCnt rows")
  }

How can I display the current branch and folder path in terminal?

Simple way

Open ~/.bash_profile in your favorite editor and add the following content to the bottom.

Git branch in prompt.

parse_git_branch() {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}

export PS1="\u@\h \[\033[32m\]\w - \$(parse_git_branch)\[\033[00m\] $ "

Add Git Branch To Terminal Prompt (Mac)

How to get visitor's location (i.e. country) using geolocation?

A very easy to use service is provided by ws.geonames.org. Here's an example URL:

http://ws.geonames.org/countryCode?lat=43.7534932&lng=28.5743187&type=JSON

And here's some (jQuery) code which I've added to your code:

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        $.getJSON('http://ws.geonames.org/countryCode', {
            lat: position.coords.latitude,
            lng: position.coords.longitude,
            type: 'JSON'
        }, function(result) {
            alert('Country: ' + result.countryName + '\n' + 'Code: ' + result.countryCode);
        });
    });
}?

Try it on jsfiddle.net ...

Preventing SQL injection in Node.js

The easiest way is to handle all of your database interactions in its own module that you export to your routes. If your route has no context of the database then SQL can't touch it anyway.

Rotating a Div Element in jQuery

I doubt you can rotate an element using DOM/CSS. Your best bet would be to render to a canvas and rotate that (not sure on the specifics).

using mailto to send email with an attachment

If you are using c# on the desktop, you can use SimpleMapi. That way it will be sent using the default mail client, and the user has the option of reviewing the message before sending, just like mailto:.

To use it you add the Simple-MAPI.NET package (it's 13Kb), and run:

var mapi = new SimpleMapi();
mapi.AddRecipient(null, address, false);
mapi.Attach(path);
//mapi.Logon(ParentForm.Handle);    //not really necessary
mapi.Send(subject, body, true);

Make javascript alert Yes/No Instead of Ok/Cancel

You cannot do that with the native confirm() as it is the browser’s method.

You have to create a plugin for a confirm box (or try one created by someone else). And they often look better, too.

Additional Tip: Change your English sentence to something like

Really, Delete this Thing?

Where should I put <script> tags in HTML markup?

XHTML Won't Validate if the script is anywhere other than within the head element. turns out it can be everywhere.

You can defer the execution with something like jQuery so it doesn't matter where it's placed (except for a small performance hit during parsing).

jquery data selector

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

Use it like that:

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

Add 10 seconds to a Date

Just for the performance maniacs among us.

getTime

var d = new Date('2014-01-01 10:11:55');
d = new Date(d.getTime() + 10000);

5,196,949 Ops/sec, fastest


setSeconds

var d = new Date('2014-01-01 10:11:55');
d.setSeconds(d.getSeconds() + 10);

2,936,604 Ops/sec, 43% slower


moment.js

var d = new moment('2014-01-01 10:11:55');
d = d.add(10, 'seconds');

22,549 Ops/sec, 100% slower


So maybe its the least human readable (not that bad) but the fastest way of going :)

jspref online tests

Python dictionary: Get list of values for list of keys

Following closure of Python: efficient way to create a list from dict values with a given order

Retrieving the keys without building the list:

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import collections


class DictListProxy(collections.Sequence):
    def __init__(self, klist, kdict, *args, **kwargs):
        super(DictListProxy, self).__init__(*args, **kwargs)
        self.klist = klist
        self.kdict = kdict

    def __len__(self):
        return len(self.klist)

    def __getitem__(self, key):
        return self.kdict[self.klist[key]]


myDict = {'age': 'value1', 'size': 'value2', 'weigth': 'value3'}
order_list = ['age', 'weigth', 'size']

dlp = DictListProxy(order_list, myDict)

print(','.join(dlp))
print()
print(dlp[1])

The output:

value1,value3,value2

value3

Which matches the order given by the list

How to parse a JSON string into JsonNode in Jackson?

New approach to old question. A solution that works from java 9+

ObjectNode agencyNode = new ObjectMapper().valueToTree(Map.of("key", "value"));

is more readable and maintainable for complex objects. Ej

Map<String, Object> agencyMap = Map.of(
        "name", "Agencia Prueba",
        "phone1", "1198788373",
        "address", "Larrea 45 e/ calligaris y paris",
        "number", 267,
        "enable", true,
        "location", Map.of("id", 54),
        "responsible", Set.of(Map.of("id", 405)),
        "sellers", List.of(Map.of("id", 605))
);
ObjectNode agencyNode = new ObjectMapper().valueToTree(agencyMap);

How to make HTML table cell editable?

I am using this for editable field

_x000D_
_x000D_
<table class="table table-bordered table-responsive-md table-striped text-center">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th class="text-center">Citation</th>_x000D_
      <th class="text-center">Security</th>_x000D_
      <th class="text-center">Implementation</th>_x000D_
      <th class="text-center">Description</th>_x000D_
      <th class="text-center">Solution</th>_x000D_
      <th class="text-center">Remove</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td class="pt-3-half" contenteditable="false">Aurelia Vega</td>_x000D_
      <td class="pt-3-half" contenteditable="false">30</td>_x000D_
      <td class="pt-3-half" contenteditable="false">Deepends</td>_x000D_
      <td class="pt-3-half" contenteditable="true"><input type="text" name="add1" value="spain" class="border-none"></td>_x000D_
      <td class="pt-3-half" contenteditable="true"><input type="text" name="add1" value="marid" class="border-none"></td>_x000D_
      <td>_x000D_
        <span class="table-remove"><button type="button"_x000D_
                              class="btn btn-danger btn-rounded btn-sm my-0">Remove</button></span>_x000D_
      </td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Show Curl POST Request Headers? Is there a way to do this?

You can see the information regarding the transfer by doing:

curl_setopt($curl_exect, CURLINFO_HEADER_OUT, true);

before the request, and

$information = curl_getinfo($curl_exect);

after the request

View: http://www.php.net/manual/en/function.curl-getinfo.php

You can also use the CURLOPT_HEADER in your curl_setopt

curl_setopt($curl_exect, CURLOPT_HEADER, true);

$httpcode = curl_getinfo($c, CURLINFO_HTTP_CODE);

return $httpcode == 200;

These are just some methods of using the headers.

Using PHP with Socket.io

I know the struggle man! But I recently had it pretty much working with Workerman. If you have not stumbled upon this php framework then you better check this out!

Well, Workerman is an asynchronous event driven PHP framework for easily building fast, scalable network applications. (I just copied and pasted that from their website hahahah http://www.workerman.net/en/)

The easy way to explain this is that when it comes web socket programming all you really need to have is to have 2 files in your server or local server (wherever you are working at).

  1. server.php (source code which will respond to all the client's request)

  2. client.php/client.html (source code which will do the requesting stuffs)

So basically, you right the code first on you server.php and start the server. Normally, as I am using windows which adds more of the struggle, I run the server through this command --> php server.php start

Well if you are using xampp. Here's one way to do it. Go to wherever you want to put your files. In our case, we're going to the put the files in

C:/xampp/htdocs/websocket/server.php

C:/xampp/htdocs/websocket/client.php or client.html

Assuming that you already have those files in your local server. Open your Git Bash or Command Line or Terminal or whichever you are using and download the php libraries here.

https://github.com/walkor/Workerman

https://github.com/walkor/phpsocket.io

I usually download it via composer and just autoload those files in my php scripts.

And also check this one. This is really important! You need this javascript libary in order for you client.php or client.html to communicate with the server.php when you run it.

https://github.com/walkor/phpsocket.io/tree/master/examples/chat/public/socket.io-client

I just copy and pasted that socket.io-client folder on the same level as my server.php and my client.php

Here is the server.php sourcecode

<?php
require __DIR__ . '/vendor/autoload.php';

use Workerman\Worker;
use PHPSocketIO\SocketIO;

// listen port 2021 for socket.io client
$io = new SocketIO(2021);
$io->on('connection', function($socket)use($io){
    $socket->on('send message', function($msg)use($io){
        $io->emit('new message', $msg);
    });
});

Worker::runAll();

And here is the client.php or client.html sourcecode

<!DOCTYPE html>
<html>
    <head>
        <title>Chat</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">        
    </head>
    <body>
        <div id="chat-messages" style="overflow-y: scroll; height: 100px; "></div>        
        <input type="text" class="message">
    </body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>    
    <script src="socket.io-client/socket.io.js"></script>  
    <script>
            var socket = io.connect("ws://127.0.0.1:2021");

            $('.message').on('change', function(){
                socket.emit('send message', $(this).val());
                $(this).val('');
            });

            socket.on('new message', function(data){
                $('#chat-messages').append('<p>' + data +'</p>');
            });
    </script>
</html>

Once again, open your command line or git bash or terminal where you put your server.php file. So in our case, that is C:/xampp/htdocs/websocket/ and typed in php server.php start and press enter.

Then go to you browser and type http://localhost/websocket/client.php to visit your site. Then just type anything to that textbox and you will see a basic php websocket on the go!

You just need to remember. In web socket programming, it just needs a server and a client. Run the server code first and the open the client code. And there you have it! Hope this helps!

Using LINQ to find item in a List but get "Value cannot be null. Parameter name: source"

Here are more code examples that will produce the argument null exception:

List<Myobj> myList = null;
//from this point on, any linq statement you perform on myList will throw an argument null exception
myList.ToList();
myList.GroupBy(m => m.Id);
myList.Count();
myList.Where(m => m.Id == 0);
myList.Select(m => m.Id == 0);
//etc...

How can I get a list of users from active directory?

Include the System.DirectoryServices.dll, then use the code below:

DirectoryEntry directoryEntry = new DirectoryEntry("WinNT://" + Environment.MachineName);
string userNames="Users: ";

foreach (DirectoryEntry child in directoryEntry.Children)
{
    if (child.SchemaClassName == "User")
    {
        userNames += child.Name + Environment.NewLine   ;         
    }

}
MessageBox.Show(userNames);

Mocking HttpClient in unit tests

Microsoft now recommends using an IHttpClientFactory instead of directly using HttpClient:

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-5.0

Example Mock with request that returns expected result:

private LoginController GetLoginController()
{
    var expected = "Hello world";
    var mockFactory = new Mock<IHttpClientFactory>();

    var mockMessageHandler = new Mock<HttpMessageHandler>();
    mockMessageHandler.Protected()
        .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
        .ReturnsAsync(new HttpResponseMessage
        {
            StatusCode = HttpStatusCode.OK,
            Content = new StringContent(expected)
        });

    var httpClient = new HttpClient(mockMessageHandler.Object);

    mockFactory.Setup(_ => _.CreateClient(It.IsAny<string>())).Returns(httpClient);

    var logger = Mock.Of<ILogger<LoginController>>();

    var controller = new LoginController(logger, mockFactory.Object);

    return controller;
}

Source:

https://stackoverflow.com/a/66256132/3850405

SQL query for finding records where count > 1

I wouldn't recommend the HAVING keyword for newbies, it is essentially for legacy purposes.

I am not clear on what is the key for this table (is it fully normalized, I wonder?), consequently I find it difficult to follow your specification:

I would like to find all records for all users that have more than one payment per day with the same account number... Additionally, there should be a filter than only counts the records whose ZIP code is different.

So I've taken a literal interpretation.

The following is more verbose but could be easier to understand and therefore maintain (I've used a CTE for the table PAYMENT_TALLIES but it could be a VIEW:

WITH PAYMENT_TALLIES (user_id, zip, tally)
     AS
     (
      SELECT user_id, zip, COUNT(*) AS tally
        FROM PAYMENT
       GROUP 
          BY user_id, zip
     )
SELECT DISTINCT *
  FROM PAYMENT AS P
 WHERE EXISTS (
               SELECT * 
                 FROM PAYMENT_TALLIES AS PT
                WHERE P.user_id = PT.user_id
                      AND PT.tally > 1
              );

ORA-00907: missing right parenthesis

Albeit from the useless _T and incorrectly spelled histories. If you are using SQL*Plus, it does not accept create table statements with empty new lines between create table <name> ( and column definitions.

How to make a DIV not wrap?

The combo you need is

white-space: nowrap

on the parent and

display: inline-block; // or inline

on the children

How can I create an object and add attributes to it?

Which objects are you using? Just tried that with a sample class and it worked fine:

class MyClass:
  i = 123456
  def f(self):
    return "hello world"

b = MyClass()
b.c = MyClass()
setattr(b.c, 'test', 123)
b.c.test

And I got 123 as the answer.

The only situation where I see this failing is if you're trying a setattr on a builtin object.

Update: From the comment this is a repetition of: Why can't you add attributes to object in python?

Only one expression can be specified in the select list when the subquery is not introduced with EXISTS

It's complaining about

COUNT(DISTINCT dNum) AS ud 

inside the subquery. Only one column can be returned from the subquery unless you are performing an exists query. I'm not sure why you want to do a count on the same column twice, superficially it looks redundant to what you are doing. The subquery here is only a filter it is not the same as a join. i.e. you use it to restrict data, not to specify what columns to get back.

How do I get an animated gif to work in WPF?

I, too, did a search and found several different solution in just a thread on the old MSDN forums. (link no longer worked so I removed it)

The simplest to execute seems to be to use a WinForms PictureBox control, and went like this (changed a few things from the thread, most of it the same).

Add a reference to System.Windows.Forms, WindowsFormsIntegration, and System.Drawing to your project first.

<Window x:Class="GifExample.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:wfi="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
    xmlns:winForms="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
    Loaded="Window_Loaded" >
    <Grid>
        <wfi:WindowsFormsHost>
            <winForms:PictureBox x:Name="pictureBoxLoading">
            </winForms:PictureBox>
        </wfi:WindowsFormsHost>
    </Grid>
</Window >

Then in the Window_Loaded handler, you would set the pictureBoxLoading.ImageLocation property to the image file path that you want to show.

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    pictureBoxLoading.ImageLocation = "../Images/mygif.gif";
}

The MediaElement control was mentioned in that thread, but it is also mentioned that it is a rather heavy control, so there were a number of alternatives, including at least 2 homebrewed controls based on the Image control, so this is the simplest.

Pause in Python

One way is to leave a raw_input() at the end so the script waits for you to press enter before it terminates.

The advantage of using raw_input() instead of msvcrt.* stuff is that the former is a part of standard Python (i.e. absolutely cross-platform). This also means that the script window will be alive after double-clicking on the script file icon, without the need to do

cmd /K python <script>

How to pass an array to a function in VBA?

Your function worked for me after changing its declaration to this ...

Function processArr(Arr As Variant) As String

You could also consider a ParamArray like this ...

Function processArr(ParamArray Arr() As Variant) As String
    'Dim N As Variant
    Dim N As Long
    Dim finalStr As String
    For N = LBound(Arr) To UBound(Arr)
        finalStr = finalStr & Arr(N)
    Next N
    processArr = finalStr
End Function

And then call the function like this ...

processArr("foo", "bar")

Concatenating strings doesn't work as expected

std::string a = "Hello ";
std::string b = "World ";
std::string c = a;
c.append(b);

New to unit testing, how to write great tests?

My tests just seems so tightly bound to the method (testing all codepath, expecting some inner methods to be called a number of times, with certain arguments), that it seems that if I ever refactor the method, the tests will fail even if the final behavior of the method did not change.

I think you are doing it wrong.

A unit test should:

  • test one method
  • provide some specific arguments to that method
  • test that the result is as expected

It should not look inside the method to see what it is doing, so changing the internals should not cause the test to fail. You should not directly test that private methods are being called. If you are interested in finding out whether your private code is being tested then use a code coverage tool. But don't get obsessed by this: 100% coverage is not a requirement.

If your method calls public methods in other classes, and these calls are guaranteed by your interface, then you can test that these calls are being made by using a mocking framework.

You should not use the method itself (or any of the internal code it uses) to generate the expected result dynamically. The expected result should be hard-coded into your test case so that it does not change when the implementation changes. Here's a simplified example of what a unit test should do:

testAdd()
{
    int x = 5;
    int y = -2;
    int expectedResult = 3;
    Calculator calculator = new Calculator();
    int actualResult = calculator.Add(x, y);
    Assert.AreEqual(expectedResult, actualResult);
}

Note that how the result is calculated is not checked - only that the result is correct. Keep adding more and more simple test cases like the above until you have have covered as many scenarios as possible. Use your code coverage tool to see if you have missed any interesting paths.

What does template <unsigned int N> mean?

You templatize your class based on an 'unsigned int'.

Example:

template <unsigned int N>
class MyArray
{
    public:
    private:
        double    data[N]; // Use N as the size of the array
};

int main()
{
    MyArray<2>     a1;
    MyArray<2>     a2;

    MyArray<4>     b1;

    a1 = a2;  // OK The arrays are the same size.
    a1 = b1;  // FAIL because the size of the array is part of the
              //      template and thus the type, a1 and b1 are different types.
              //      Thus this is a COMPILE time failure.
 }

How to send POST request?

You can't achieve POST requests using urllib (only for GET), instead try using requests module, e.g.:

Example 1.0:

import requests

base_url="www.server.com"
final_url="/{0}/friendly/{1}/url".format(base_url,any_value_here)

payload = {'number': 2, 'value': 1}
response = requests.post(final_url, data=payload)

print(response.text) #TEXT/HTML
print(response.status_code, response.reason) #HTTP

Example 1.2:

>>> import requests

>>> payload = {'key1': 'value1', 'key2': 'value2'}

>>> r = requests.post("http://httpbin.org/post", data=payload)
>>> print(r.text)
{
  ...
  "form": {
    "key2": "value2",
    "key1": "value1"
  },
  ...
}

Example 1.3:

>>> import json

>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}

>>> r = requests.post(url, data=json.dumps(payload))

CSS: How to remove pseudo elements (after, before,...)?

You need to add a css rule that removes the after content (through a class)..


An update due to some valid comments.

The more correct way to completely remove/disable the :after rule is to use

p.no-after:after{content:none;}

as Gillian Lo Wong answered.


Original answer

You need to add a css rule that removes the after content (through a class)..

p.no-after:after{content:"";}

and add that class to your p when you want to with this line

$('p').addClass('no-after'); // replace the p selector with what you need...

a working example at : http://www.jsfiddle.net/G2czw/

What is the difference between buffer and cache memory in Linux?

buffer and cache.

A buffer is something that has yet to be "written" to disk.

A cache is something that has been "read" from the disk and stored for later use.

c# foreach (property in object)... Is there a simple way of doing this?

Your'e almost there, you just need to get the properties from the type, rather than expect the properties to be accessible in the form of a collection or property bag:

var property in obj.GetType().GetProperties()

From there you can access like so:

property.Name
property.GetValue(obj, null)

With GetValue the second parameter will allow you to specify index values, which will work with properties returning collections - since a string is a collection of chars, you can also specify an index to return a character if needs be.

How to get array keys in Javascript?

I think you should use an Object ({}) and not an array ([]) for this.

A set of data is associated with each key. It screams for using an object. Do:

var obj = {};
obj[46] = { sel:46, min:0,  max:52 };
obj[666] = { whatever:true };

// This is what for..in is for
for (var prop in obj) {
  console.log(obj[prop]);
}

Maybe some utility stuff like this can help:

window.WidthRange = (function () {
  var obj = {};
  return {
    getObj: function () {return obj;}
    , add: function (key, data) {
        obj[key] = data;
        return this; // enabling chaining
      }
  }
})();

// Usage (using chaining calls):
WidthRange.add(66, {foo: true})
.add(67, {bar: false})
.add(69, {baz: 'maybe', bork:'absolutely'});

var obj = WidthRange.getObj();
for (var prop in obj) {
  console.log(obj[prop]);
}

Using Pipes within ngModel on INPUT Elements in Angular

because of two way binding, To prevent error of:

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was 
checked.

you can call a function to change model like this:

<input [ngModel]="item.value" 
  (ngModelChange)="getNewValue($event)" name="inputField" type="text" />


import { UseMyPipeToFormatThatValuePipe } from './path';

constructor({
    private UseMyPipeToFormatThatValue: UseMyPipeToFormatThatValuePipe,
})

getNewValue(ev: any): any {
    item.value= this.useMyPipeToFormatThatValue.transform(ev);
}

it'll be good if there is a better solution to prevent this error.

I keep getting this error for my simple python program: "TypeError: 'float' object cannot be interpreted as an integer"

Also possible is to fix this with np.arange() instead of range which works for float numbers:

import numpy as np
for i in np.arange(c/10):

How do I execute external program within C code in linux with arguments?

For a simple way, use system():

#include <stdlib.h>
...
int status = system("./foo 1 2 3");

system() will wait for foo to complete execution, then return a status variable which you can use to check e.g. exitcode (the command's exitcode gets multiplied by 256, so divide system()'s return value by that to get the actual exitcode: int exitcode = status / 256).

The manpage for wait() (in section 2, man 2 wait on your Linux system) lists the various macros you can use to examine the status, the most interesting ones would be WIFEXITED and WEXITSTATUS.

Alternatively, if you need to read foo's standard output, use popen(3), which returns a file pointer (FILE *); interacting with the command's standard input/output is then the same as reading from or writing to a file.

How to add a class to a given element?

To add an additional class to an element:

To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so:

document.getElementById("MyElement").className += " MyClass";

To change all classes for an element:

To replace all existing classes with one or more new classes, set the className attribute:

document.getElementById("MyElement").className = "MyClass";

(You can use a space-delimited list to apply multiple classes.)

What are the differences between using the terminal on a mac vs linux?

@Michael Durrant's answer ably covers the shell itself, but the shell environment also includes the various commands you use in the shell and these are going to be similar -- but not identical -- between OS X and linux. In general, both will have the same core commands and features (especially those defined in the Posix standard), but a lot of extensions will be different.

For example, linux systems generally have a useradd command to create new users, but OS X doesn't. On OS X, you generally use the GUI to create users; if you need to create them from the command line, you use dscl (which linux doesn't have) to edit the user database (see here). (Update: starting in macOS High Sierra v10.13, you can use sysadminctl -addUser instead.)

Also, some commands they have in common will have different features and options. For example, linuxes generally include GNU sed, which uses the -r option to invoke extended regular expressions; on OS X, you'd use the -E option to get the same effect. Similarly, in linux you might use ls --color=auto to get colorized output; on macOS, the closest equivalent is ls -G.

EDIT: Another difference is that many linux commands allow options to be specified after their arguments (e.g. ls file1 file2 -l), while most OS X commands require options to come strictly first (ls -l file1 file2).

Finally, since the OS itself is different, some commands wind up behaving differently between the OSes. For example, on linux you'd probably use ifconfig to change your network configuration. On OS X, ifconfig will work (probably with slightly different syntax), but your changes are likely to be overwritten randomly by the system configuration daemon; instead you should edit the network preferences with networksetup, and then let the config daemon apply them to the live network state.

Serialize object to query string in JavaScript/jQuery

For a quick non-JQuery function...

function jsonToQueryString(json) {
    return '?' + 
        Object.keys(json).map(function(key) {
            return encodeURIComponent(key) + '=' +
                encodeURIComponent(json[key]);
        }).join('&');
}

Note this doesn't handle arrays or nested objects.

How to wait for a number of threads to complete?

Consider using java.util.concurrent.CountDownLatch. Examples in javadocs

How to display HTML <FORM> as inline element?

You can accomplish what you want, I think, simply by including the submit button within the paragraph:

     <pre>
     <p>Read this sentence  <input  type='submit' value='or push this button'/></p>
     </pre>   

Inline IF Statement in C#

You may define your enum like so and use cast where needed

public enum MyEnum
{
    VariablePeriods = 1,
    FixedPeriods = 2
}

Usage

public class Entity
{
    public MyEnum Property { get; set; }
}

var returnedFromDB = 1;
var entity = new Entity();
entity.Property = (MyEnum)returnedFromDB;

MySQL integer field is returned as string in PHP

My solution is to pass the query result $rs and get a assoc array of the casted data as the return:

function cast_query_results($rs) {
    $fields = mysqli_fetch_fields($rs);
    $data = array();
    $types = array();
    foreach($fields as $field) {
        switch($field->type) {
            case 3:
                $types[$field->name] = 'int';
                break;
            case 4:
                $types[$field->name] = 'float';
                break;
            default:
                $types[$field->name] = 'string';
                break;
        }
    }
    while($row=mysqli_fetch_assoc($rs)) array_push($data,$row);
    for($i=0;$i<count($data);$i++) {
        foreach($types as $name => $type) {
            settype($data[$i][$name], $type);
        }
    }
    return $data;
}

Example usage:

$dbconn = mysqli_connect('localhost','user','passwd','tablename');
$rs = mysqli_query($dbconn, "SELECT * FROM Matches");
$matches = cast_query_results($rs);
// $matches is now a assoc array of rows properly casted to ints/floats/strings

How to check if AlarmManager already has an alarm set?

While almost everyone over here has given the correct answer, no body explained on what basis are the Alarms work

You can actually learn more about AlarmManager and its working here . But here is the quick answer

You see AlarmManager basically schedules a PendingIntent at some time in future. So in order to cancel the scheduled Alarm you need to cancel the PendingIntent.

Always keep note of two things while creating the PendingIntent

PendingIntent.getBroadcast(context,REQUEST_CODE,intent, PendingIntent.FLAG_UPDATE_CURRENT);
  • Request Code - Acts as the unique identifier
  • Flag - Defines the behavior of PendingIntent

Now to check if the Alarm is already scheduled or to cancel the Alarm you just need to get access to the same PendingIntent. This can be done if you use same request code and use FLAG_NO_CREATE like shown below

PendingIntent pendingIntent=PendingIntent.getBroadcast(this,REQUEST_CODE,intent,PendingIntent.FLAG_NO_CREATE);

if (pendingIntent!=null)
   alarmManager.cancel(pendingIntent);

With FLAG_NO_CREATE it will return null if the PendingIntent doesn't already exist. If it already exists it returns reference to the existing PendingIntent

How to store images in mysql database using php

insert image zh

-while we insert image in database using insert query

$Image = $_FILES['Image']['name'];
    if(!$Image)
    {
      $Image="";
    }
    else
    {
      $file_path = 'upload/';
      $file_path = $file_path . basename( $_FILES['Image']['name']);    
      if(move_uploaded_file($_FILES['Image']['tmp_name'], $file_path)) 
     { 
}
}

FFmpeg on Android

First, add the dependency of FFmpeg library

implementation 'com.writingminds:FFmpegAndroid:0.3.2'

Then load in activity

FFmpeg ffmpeg;
    private void trimVideo(ProgressDialog progressDialog) {

    outputAudioMux = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).getAbsolutePath()
            + "/VidEffectsFilter" + "/" + new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date())
            + "filter_apply.mp4";

    if (startTrim.equals("")) {
        startTrim = "00:00:00";
    }

    if (endTrim.equals("")) {
        endTrim = timeTrim(player.getDuration());
    }

    String[] cmd = new String[]{"-ss", startTrim + ".00", "-t", endTrim + ".00", "-noaccurate_seek", "-i", videoPath, "-codec", "copy", "-avoid_negative_ts", "1", outputAudioMux};


    execFFmpegBinary1(cmd, progressDialog);
    }



    private void execFFmpegBinary1(final String[] command, ProgressDialog prpg) {

    ProgressDialog progressDialog = prpg;

    try {
        ffmpeg.execute(command, new ExecuteBinaryResponseHandler() {
            @Override
            public void onFailure(String s) {
                progressDialog.dismiss();
                Toast.makeText(PlayerTestActivity.this, "Fail to generate video", Toast.LENGTH_SHORT).show();
                Log.d(TAG, "FAILED with output : " + s);
            }

            @Override
            public void onSuccess(String s) {
                Log.d(TAG, "SUCCESS wgith output : " + s);

//                    pathVideo = outputAudioMux;
                String finalPath = outputAudioMux;
                videoPath = outputAudioMux;
                Toast.makeText(PlayerTestActivity.this, "Storage Path =" + finalPath, Toast.LENGTH_SHORT).show();

                Intent intent = new Intent(PlayerTestActivity.this, ShareVideoActivity.class);
                intent.putExtra("pathGPU", finalPath);
                startActivity(intent);
                finish();
                MediaScannerConnection.scanFile(PlayerTestActivity.this, new String[]{finalPath}, new String[]{"mp4"}, null);

            }

            @Override
            public void onProgress(String s) {
                Log.d(TAG, "Started gcommand : ffmpeg " + command);
                progressDialog.setMessage("Please Wait video triming...");
            }

            @Override
            public void onStart() {
                Log.d(TAG, "Startedf command : ffmpeg " + command);

            }

            @Override
            public void onFinish() {
                Log.d(TAG, "Finished f command : ffmpeg " + command);
                progressDialog.dismiss();
            }
        });
    } catch (FFmpegCommandAlreadyRunningException e) {
        // do nothing for now
    }
}

  private void loadFFMpegBinary() {
    try {
        if (ffmpeg == null) {
            ffmpeg = FFmpeg.getInstance(this);
        }
        ffmpeg.loadBinary(new LoadBinaryResponseHandler() {
            @Override
            public void onFailure() {
                showUnsupportedExceptionDialog();
            }

            @Override
            public void onSuccess() {
                Log.d("dd", "ffmpeg : correct Loaded");
            }
        });
    } catch (FFmpegNotSupportedException e) {
        showUnsupportedExceptionDialog();
    } catch (Exception e) {
        Log.d("dd", "EXception no controlada : " + e);
    }
}

private void showUnsupportedExceptionDialog() {
    new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setTitle("Not Supported")
            .setMessage("Device Not Supported")
            .setCancelable(false)
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            })
            .create()
            .show();

}
    public String timeTrim(long milliseconds) {
        String finalTimerString = "";
        String minutString = "";
        String secondsString = "";

        // Convert total duration into time
        int hours = (int) (milliseconds / (1000 * 60 * 60));
        int minutes = (int) (milliseconds % (1000 * 60 * 60)) / (1000 * 60);
        int seconds = (int) ((milliseconds % (1000 * 60 * 60)) % (1000 * 60) / 1000);
        // Add hours if there

        if (hours < 10) {
            finalTimerString = "0" + hours + ":";
        } else {
            finalTimerString = hours + ":";
        }


        if (minutes < 10) {
            minutString = "0" + minutes;
        } else {
            minutString = "" + minutes;
        }

        // Prepending 0 to seconds if it is one digit
        if (seconds < 10) {
            secondsString = "0" + seconds;
        } else {
            secondsString = "" + seconds;
        }

        finalTimerString = finalTimerString + minutString + ":" + secondsString;

        // return timer string
        return finalTimerString;
    }

Also use another feature by FFmpeg

===> merge audio to video
String[] cmd = new String[]{"-i", yourRealPath, "-i", arrayList.get(posmusic).getPath(), "-map", "1:a", "-map", "0:v", "-codec", "copy", "-shortest", outputcrop};


===> Flip vertical :
String[] cm = new String[]{"-i", yourRealPath, "-vf", "vflip", "-codec:v", "libx264", "-preset", "ultrafast", "-codec:a", "copy", outputcrop1};


===> Flip horizontally :  
String[] cm = new String[]{"-i", yourRealPath, "-vf", "hflip", "-codec:v", "libx264", "-preset", "ultrafast", "-codec:a", "copy", outputcrop1};


===> Rotate 90 degrees clockwise:
String[] cm=new String[]{"-i", yourRealPath, "-c", "copy", "-metadata:s:v:0", "rotate=90", outputcrop1};


===> Compress Video
String[] complexCommand = {"-y", "-i", yourRealPath, "-strict", "experimental", "-vcodec", "libx264", "-preset", "ultrafast", "-crf", "24", "-acodec", "aac", "-ar", "22050", "-ac", "2", "-b", "360k", "-s", "1280x720", outputcrop1};


===> Speed up down video
String[] complexCommand = {"-y", "-i", yourRealPath, "-filter_complex", "[0:v]setpts=2.0*PTS[v];[0:a]atempo=0.5[a]", "-map", "[v]", "-map", "[a]", "-b:v", "2097k", "-r", "60", "-vcodec", "mpeg4", outputcrop1};
String[] complexCommand = {"-y", "-i", yourRealPath, "-filter_complex", "[0:v]setpts=1.0*PTS[v];[0:a]atempo=1.0[a]", "-map", "[v]", "-map", "[a]", "-b:v", "2097k", "-r", "60", "-vcodec", "mpeg4", outputcrop1};
String[] complexCommand = {"-y", "-i", yourRealPath, "-filter_complex", "[0:v]setpts=0.75*PTS[v];[0:a]atempo=1.5[a]", "-map", "[v]", "-map", "[a]", "-b:v", "2097k", "-r", "60", "-vcodec", "mpeg4", outputcrop1};
String[] complexCommand = {"-y", "-i", yourRealPath, "-filter_complex", "[0:v]setpts=0.5*PTS[v];[0:a]atempo=2.0[a]", "-map", "[v]", "-map", "[a]", "-b:v", "2097k", "-r", "60", "-vcodec", "mpeg4", outputcrop1};



===> Add two mp3 files 

StringBuilder sb = new StringBuilder();
sb.append("-i ");
sb.append(textSngname);
sb.append(" -i ");
sb.append(mAudioFilename);
sb.append(" -filter_complex [0:0][1:0]concat=n=2:v=0:a=1[out] -map [out] ");
sb.append(finalfile);
---> ffmpeg.execute(sb.toString().split(" "), new ExecuteBinaryResponseHandler()




===> Add three mp3 files

StringBuilder sb = new StringBuilder();
sb.append("-i ");
sb.append(firstSngname);
sb.append(" -i ");
sb.append(textSngname);
sb.append(" -i ");
sb.append(mAudioFilename);
sb.append(" -filter_complex [0:0][1:0][2:0]concat=n=3:v=0:a=1[out] -map [out] ");
sb.append(finalfile);
---> ffmpeg.execute(sb.toString().split(" "), new ExecuteBinaryResponseHandler()

How to run multiple Python versions on Windows

One easy way for this is that you can use

py -3.8 -m pip install virtualenv here -3.8 goes with your [version number]

After installing the virtualenv, you can create the virtual environment of your application using

py -3.8 -m virtualenv [your env name]

then cd to venv, enter activate

This would activate the python version you like. Just change the version number to use a different python version.

How to lowercase a pandas dataframe string column if it has missing values?

you can try this one also,

df= df.applymap(lambda s:s.lower() if type(s) == str else s)

The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel

I just removed the slash at the end of url and it began working... /managers/games/id/push/ to:

$http({
  method: 'POST',
  url: "/managers/games/id/push",

This may have to do with upgrading to laravel 5.8?

Adjusting and image Size to fit a div (bootstrap)

Just a heads up that Bootstrap 4 now uses img-fluid instead of img-responsive, so double check which version you're using if you're having problems.

Commands out of sync; you can't run this command now

Here is what was MY PROBLEM!!!

The param binding was "dynamic" so I had a variable that sets the params of the data in order to use bind_param. So that variable was wrong but instead of throwing an error like "wrong param data" it says "out of sync bla bla bla" so I was confused...

How do I set a VB.Net ComboBox default value

Just go to the combo box properties - DropDownStyle and change it to "DropDownList"

This will make visible the first item.

mailto using javascript

No need for jQuery. And it isn't necessary to open a new window. Protocols which doesn't return HTTP data to the browser (mailto:, irc://, magnet:, ftp:// (<- it depends how it is implemented, normally the browser has an FTP client built in)) can be queried in the same window without losing the current content. In your case:

function redirect()
{
    window.location.href = "mailto:[email protected]";
}
<body onload="javascript: redirect();">

Or just directly

<body onload="javascript: window.location.href='mailto:[email protected]';">

WCF Service , how to increase the timeout?

The best way is to change any setting you want in your code.

Check out the below example:

using(WCFServiceClient client = new WCFServiceClient ())
{ 
    client.Endpoint.Binding.SendTimeout = new TimeSpan(0, 1, 30);
}

What is a correct MIME type for .docx, .pptx, etc.?

Here are the correct Microsoft Office MIME types for HTTP content streaming:

Extension MIME Type
.doc      application/msword
.dot      application/msword

.docx     application/vnd.openxmlformats-officedocument.wordprocessingml.document
.dotx     application/vnd.openxmlformats-officedocument.wordprocessingml.template
.docm     application/vnd.ms-word.document.macroEnabled.12
.dotm     application/vnd.ms-word.template.macroEnabled.12

.xls      application/vnd.ms-excel
.xlt      application/vnd.ms-excel
.xla      application/vnd.ms-excel

.xlsx     application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.xltx     application/vnd.openxmlformats-officedocument.spreadsheetml.template
.xlsm     application/vnd.ms-excel.sheet.macroEnabled.12
.xltm     application/vnd.ms-excel.template.macroEnabled.12
.xlam     application/vnd.ms-excel.addin.macroEnabled.12
.xlsb     application/vnd.ms-excel.sheet.binary.macroEnabled.12

.ppt      application/vnd.ms-powerpoint
.pot      application/vnd.ms-powerpoint
.pps      application/vnd.ms-powerpoint
.ppa      application/vnd.ms-powerpoint

.pptx     application/vnd.openxmlformats-officedocument.presentationml.presentation
.potx     application/vnd.openxmlformats-officedocument.presentationml.template
.ppsx     application/vnd.openxmlformats-officedocument.presentationml.slideshow
.ppam     application/vnd.ms-powerpoint.addin.macroEnabled.12
.pptm     application/vnd.ms-powerpoint.presentation.macroEnabled.12
.potm     application/vnd.ms-powerpoint.template.macroEnabled.12
.ppsm     application/vnd.ms-powerpoint.slideshow.macroEnabled.12

.mdb      application/vnd.ms-access

For further details check out this TechNet article and this blog post.

How to change the remote a branch is tracking?

For me the fix was:

git remote set-url origin https://some_url/some_repo

Then:

git push

How can I get zoom functionality for images?

This is a very late addition to this thread but I've been working on an image view that supports zoom and pan and has a couple of features I haven't found elsewhere. This started out as a way of displaying very large images without causing OutOfMemoryErrors, by subsampling the image when zoomed out and loading higher resolution tiles when zoomed in. It now supports use in a ViewPager, rotation manually or using EXIF information (90° stops), override of selected touch events using OnClickListener or your own GestureDetector or OnTouchListener, subclassing to add overlays, pan while zooming, and fling momentum.

It's not intended as a general use replacement for ImageView so doesn't extend it, and doesn't support display of images from resources, only assets and external files. It requires SDK 10.

Source is on GitHub, and there's a sample that illustrates use in a ViewPager.

https://github.com/davemorrissey/subsampling-scale-image-view

symfony 2 twig limit the length of the text and put three dots

I wrote this simple marco for the same purpose, hope it helps:

{%- macro stringMaxLength(str, maxLength) -%}
    {%- if str | length < maxLength -%}
        {{ str }}
    {%- else -%}
        {{ str|slice(0, maxLength) }}...
    {%- endif -%}
{%- endmacro -%}

Usage Example #1 (Output: "my long string here ..."):

{{ _self.stringMaxLength("my long string here bla bla bla la", 20) }}

Usage Example #2 (Output: "shorter string!"):

{{ _self.stringMaxLength("shorter string!", 20) }}

What does this symbol mean in IntelliJ? (red circle on bottom-left corner of file name, with 'J' in it)

This situation happens when the IDE looks for src folder, and it cannot find it in the path. Select the project root (F4 in windows) > Go to Modules on Side Tab > Select Sources > Select appropriate folder with source files in it> Click on the blue sources folder icon (for adding sources) > Click on Green Test Sources folder ( to add Unit test folders).

Best way to access a control on another form in Windows Forms?

After reading the additional details, I agree with robcthegeek: raise an event. Create a custom EventArgs and pass the neccessary parameters through it.

How to call a method daily, at specific time, in C#?

Solution with System.Threading.Timer:

    private void nameOfMethod()
    {
        //do something
    }

    /// <summary>
    /// run method at 22:00 every day
    /// </summary>
    private void runMethodEveryDay()
    {
        var runAt = DateTime.Today + TimeSpan.FromHours(22);

        if(runAt.Hour>=22)
            runAt = runAt.AddDays(1.00d); //if aplication is started after 22:00 

        var dueTime = runAt - DateTime.Now; //time before first run ; 

        long broj3 = (long)dueTime.TotalMilliseconds;
        TimeSpan ts2 = new TimeSpan(24, 0, 1);//period of repeating method
        long broj4 = (long)ts2.TotalMilliseconds;
        timer2 = new System.Threading.Timer(_ => nameOfMethod(), null, broj3, broj4);
    }

android pick images from gallery

Here is a full example for request permission (if need), pick image from gallery, then convert image to bitmap or file

AndroidManifesh.xml

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

Activity

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        button_pick_image.setOnClickListener {
            pickImage()
        }
    }

    private fun pickImage() {
        if (ActivityCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            val intent = Intent(
                Intent.ACTION_PICK,
                MediaStore.Images.Media.INTERNAL_CONTENT_URI
            )
            intent.type = "image/*"
            intent.putExtra("crop", "true")
            intent.putExtra("scale", true)
            intent.putExtra("aspectX", 16)
            intent.putExtra("aspectY", 9)
            startActivityForResult(intent, PICK_IMAGE_REQUEST_CODE)
        } else {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
                READ_EXTERNAL_STORAGE_REQUEST_CODE
            )
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == PICK_IMAGE_REQUEST_CODE) {
            if (resultCode != Activity.RESULT_OK) {
                return
            }
            val uri = data?.data
            if (uri != null) {
                val imageFile = uriToImageFile(uri)
                // todo do something with file
            }
            if (uri != null) {
                val imageBitmap = uriToBitmap(uri)
                // todo do something with bitmap
            }
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            READ_EXTERNAL_STORAGE_REQUEST_CODE -> {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // pick image after request permission success
                    pickImage()
                }
            }
        }
    }

    private fun uriToImageFile(uri: Uri): File? {
        val filePathColumn = arrayOf(MediaStore.Images.Media.DATA)
        val cursor = contentResolver.query(uri, filePathColumn, null, null, null)
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                val columnIndex = cursor.getColumnIndex(filePathColumn[0])
                val filePath = cursor.getString(columnIndex)
                cursor.close()
                return File(filePath)
            }
            cursor.close()
        }
        return null
    }

    private fun uriToBitmap(uri: Uri): Bitmap {
        return MediaStore.Images.Media.getBitmap(this.contentResolver, uri)
    }

    companion object {
        const val PICK_IMAGE_REQUEST_CODE = 1000
        const val READ_EXTERNAL_STORAGE_REQUEST_CODE = 1001
    }
}

Demo
https://github.com/PhanVanLinh/AndroidPickImage

Push method in React Hooks (useState)?

To expand a little further, here are some common examples. Starting with:

const [theArray, setTheArray] = useState(initialArray);
const [theObject, setTheObject] = useState(initialObject);

Push element at end of array

setTheArray(prevArray => [...prevArray, newValue])

Push/update element at end of object

setTheObject(prevState => ({ ...prevState, currentOrNewKey: newValue}));

Push/update element at end of array of objects

setTheArray(prevState => [...prevState, {currentOrNewKey: newValue}]);

Push element at end of object of arrays

let specificArrayInObject = theObject.array.slice();
specificArrayInObject.push(newValue);
const newObj = { ...theObject, [event.target.name]: specificArrayInObject };
theObject(newObj);

Here are some working examples too. https://codesandbox.io/s/reacthooks-push-r991u

How to unpack and pack pkg file?

In addition to what @abarnert said, I today had to find out that the default cpio utility on Mountain Lion uses a different archive format per default (not sure which), even with the man page stating it would use the old cpio/odc format. So, if anyone stumbles upon the cpio read error: bad file format message while trying to install his/her manipulated packages, be sure to include the format in the re-pack step:

find ./Foo.app | cpio -o --format odc | gzip -c > Payload

what is the size of an enum type data in C++?

It depends. The standard only demands that it is large enough to hold all values, so formally an enum like enum foo { zero, one, two }; needs to only be one byte large. However most implementations make those enums as large as ints (that's faster on modern hardware; moreover it's needed for compatibility with C where enums are basically glorified ints). Note however that C++ allows enums with initializers outside of the int range, and for those enums the size will of course also be larger. For example, if you have enum bar { a, b = 1LL << 35 }; then your enum will be larger than 32 bits (most likely 64 bits) even on a system with 32 bit ints (note that in C that enum would not be allowed).

SQL (MySQL) vs NoSQL (CouchDB)

One of the best options is to go for MongoDB(NOSql dB) that supports scalability.Stores large amounts of data nothing but bigdata in the form of documents unlike rows and tables in sql.This is fasters that follows sharding of the data.Uses replicasets to ensure data guarantee that maintains multiple servers having primary db server as the base. Language independent. Flexible to use

Python Dictionary Comprehension

You can use the dict.fromkeys class method ...

>>> dict.fromkeys(range(5), True)
{0: True, 1: True, 2: True, 3: True, 4: True}

This is the fastest way to create a dictionary where all the keys map to the same value.

But do not use this with mutable objects:

d = dict.fromkeys(range(5), [])
# {0: [], 1: [], 2: [], 3: [], 4: []}
d[1].append(2)
# {0: [2], 1: [2], 2: [2], 3: [2], 4: [2]} !!!

If you don't actually need to initialize all the keys, a defaultdict might be useful as well:

from collections import defaultdict
d = defaultdict(True)

To answer the second part, a dict-comprehension is just what you need:

{k: k for k in range(10)}

You probably shouldn't do this but you could also create a subclass of dict which works somewhat like a defaultdict if you override __missing__:

>>> class KeyDict(dict):
...    def __missing__(self, key):
...       #self[key] = key  # Maybe add this also?
...       return key
... 
>>> d = KeyDict()
>>> d[1]
1
>>> d[2]
2
>>> d[3]
3
>>> print(d)
{}

Is there any sed like utility for cmd.exe?

I needed a sed tool that worked for the Windows cmd.exe prompt. Eric Pement's port of sed to a single DOS .exe worked great for me.

It's pretty well documented.

How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?

  • I used date.exe, and renamed it to date_unxutils.exe to avoid conflicts.

  • Put it inside bin folder next to the batch script.

Code

:: Add binaries to temp path
IF EXIST bin SET PATH=%PATH%;bin

:: Create UTC Timestamp string in a custom format
:: Example: 20210128172058
set timestamp_command='date_unxutils.exe -u +"%%Y%%m%%d%%H%%M%%S"'
FOR /F %%i IN (%timestamp_command%) DO set timestamp=%%i
echo %timestamp%

Download UnxUtils

References

  • This awesome answer that I build upon.

Windows batch - concatenate multiple text files into one

We can use normal CAT command to merge files..

D:> cat *.csv > outputs.csv

Xamarin 2.0 vs Appcelerator Titanium vs PhoneGap

There's also AppGyver Steroids that unites PhoneGap and Native UI nicely.

With Steroids you can add things like native tabs, native navigation bar, native animations and transitions, native modal windows, native drawer/panel (facebooks side menu) etc. to your PhoneGap app.

Here's a demo: http://youtu.be/oXWwDMdoTCk?t=20m17s

Swift Open Link in Safari

It's not "baked in to Swift", but you can use standard UIKit methods to do it. Take a look at UIApplication's openUrl(_:) (deprecated) and open(_:options:completionHandler:).

Swift 4 + Swift 5 (iOS 10 and above)

guard let url = URL(string: "https://stackoverflow.com") else { return }
UIApplication.shared.open(url)

Swift 3 (iOS 9 and below)

guard let url = URL(string: "https://stackoverflow.com") else { return }
UIApplication.shared.openURL(url)

Swift 2.2

guard let url = URL(string: "https://stackoverflow.com") else { return }
UIApplication.sharedApplication().openURL(url)    

Creating a list of dictionaries results in a list of copies of the same dictionary

You have misunderstood the Python list object. It is similar to a C pointer-array. It does not actually "copy" the object which you append to it. Instead, it just store a "pointer" to that object.

Try the following code:

>>> d={}
>>> dlist=[]
>>> for i in xrange(0,3):
    d['data']=i
    dlist.append(d)
    print(d)

{'data': 0}
{'data': 1}
{'data': 2}
>>> print(dlist)
[{'data': 2}, {'data': 2}, {'data': 2}]

So why is print(dlist) not the same as print(d)?

The following code shows you the reason:

>>> for i in dlist:
    print "the list item point to object:", id(i)

the list item point to object: 47472232
the list item point to object: 47472232
the list item point to object: 47472232

So you can see all the items in the dlist is actually pointing to the same dict object.

The real answer to this question will be to append the "copy" of the target item, by using d.copy().

>>> dlist=[]
>>> for i in xrange(0,3):
    d['data']=i
    dlist.append(d.copy())
    print(d)

{'data': 0}
{'data': 1}
{'data': 2}
>>> print dlist
[{'data': 0}, {'data': 1}, {'data': 2}]

Try the id() trick, you can see the list items actually point to completely different objects.

>>> for i in dlist:
    print "the list item points to object:", id(i)

the list item points to object: 33861576
the list item points to object: 47472520
the list item points to object: 47458120

How do I create a singleton service in Angular 2?

Jason is completely right! It's caused by the way dependency injection works. It's based on hierarchical injectors.

There are several injectors within an Angular2 application:

  • The root one you configure when bootstrapping your application
  • An injector per component. If you use a component inside another one. The component injector is a child of the parent component one. The application component (the one you specify when boostrapping your application) has the root injector as parent one).

When Angular2 tries to inject something in the component constructor:

  • It looks into the injector associated with the component. If there is matching one, it will use it to get the corresponding instance. This instance is lazily created and is a singleton for this injector.
  • If there is no provider at this level, it will look at the parent injector (and so on).

So if you want to have a singleton for the whole application, you need to have the provider defined either at the level of the root injector or the application component injector.

But Angular2 will look at the injector tree from the bottom. This means that the provider at the lowest level will be used and the scope of the associated instance will be this level.

See this question for more details:

Session TimeOut in web.xml

The docs says:

The session-timeout element defines the default session timeout interval for all sessions created in this web application. The specified timeout must be expressed in a whole number of minutes. If the timeout is 0 or less, the container ensures the default behaviour of sessions is never to time out. If this element is not specified, the container must set its default timeout period.

How do I fix certificate errors when running wget on an HTTPS URL in Cygwin?

If you don't care about checking the validity of the certificate just add the --no-check-certificate option on the wget command-line. This worked well for me.

NOTE: This opens you up to man-in-the-middle (MitM) attacks, and is not recommended for anything where you care about security.

Cannot obtain value of local or argument as it is not available at this instruction pointer, possibly because it has been optimized away

In visual Studio 2017 goto Debug->Option then check Debugging->general-> and check this option

relevant Visual Studio 2017 Options

How do I fix maven error The JAVA_HOME environment variable is not defined correctly?

I had the same problem on Windows 7.

The JAVA_HOME environment variable is not defined correctly
This environment variable is needed to run this program
NB: JAVA_HOME should point to a JDK not a JRE

The solution turned out to be very simple - right click on command prompt shortcut and choose "Run as Administrator". After that, the problem disappeared)

Is there a way to get the source code from an APK file?

This site https://www.apkdecompilers.com/ did it automatically.

I tried the site mentioned in the accepted answer first but that didn't work for me.

How do you read scanf until EOF in C?

Scanf is pretty much always more trouble than it's worth. Here are two better ways to do what you're trying to do. This first one is a more-or-less direct translation of your code. It's longer, but you can look at it and see clearly what it does, unlike with scanf.

#include <stdio.h>
#include <ctype.h>
int main(void)
{
    char buf[1024], *p, *q;
    while (fgets(buf, 1024, stdin))
    {
        p = buf;
        while (*p)
        {
            while (*p && isspace(*p)) p++;
            q = p;
            while (*q && !isspace(*q)) q++;
            *q = '\0';
            if (p != q)
                puts(p);
            p = q;
        }
    }
    return 0;
}

And here's another version. It's a little harder to see what this does by inspection, but it does not break if a line is longer than 1024 characters, so it's the code I would use in production. (Well, really what I would use in production is tr -s '[:space:]' '\n', but this is how you implement something like that.)

#include <stdio.h>
#include <ctype.h>
int main(void)
{
    int ch, lastch = '\0';
    while ((ch = getchar()) != EOF)
    {
        if (!isspace(ch))
            putchar(ch);
        if (!isspace(lastch))
            putchar('\n');
        lastch = ch;
    }
    if (lastch != '\0' && !isspace(lastch))
        putchar('\n');
    return 0;
}

Laravel Eloquent - Get one Row

Simply use this:

$user = User::whereEmail($email)->first();

How to do scanf for single char in C

The only code that worked for me is:

scanf(" %c",&c);

I was having the same problem, and only with single characters. After an hour of random testing I can not report an issue yet. One would think that C would have by now a bullet-proof function to retrieve single characters from the keyboard, and not an array of possible hackarounds... Just saying...

Android Camera Preview Stretched

Hi the getOptimalPreview() that is here didn't worked for me so I want to share my version:

private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {

    if (sizes==null) return null;

    Camera.Size optimalSize = null;
    double ratio = (double)h/w;
    double minDiff = Double.MAX_VALUE;
    double newDiff;
    for (Camera.Size size : sizes) {
        newDiff = Math.abs((double)size.width/size.height - ratio);
        if (newDiff < minDiff) {
            optimalSize = size;
            minDiff = newDiff;
        }
    }
    return optimalSize;
}

How to convert Varchar to Int in sql server 2008?

That is the correct way to convert it to an INT as long as you don't have any alpha characters or NULL values.

If you have any NULL values, use

ISNULL(column1, 0)

Replace Fragment inside a ViewPager

I have created a ViewPager with 3 elements and 2 sub elements for index 2 and 3 and here what I wanted to do..

enter image description here

I have implemented this with the help from previous questions and answers from StackOverFlow and here is the link.

ViewPagerChildFragments

Ruby's File.open gives "No such file or directory - text.txt (Errno::ENOENT)" error

Please use chomp() or chomp() with STDIN

i.e. test1.rb

print 'Enter File name: '

fname = STDIN.gets.chomp()  # or fname = gets.chomp()


fname_read = File.open(fname)

puts fname_read.read()

SQL Call Stored Procedure for each Row without using a cursor

A better solution for this is to

  1. Copy/past code of Stored Procedure
  2. Join that code with the table for which you want to run it again (for each row)

This was you get a clean table-formatted output. While if you run SP for every row, you get a separate query result for each iteration which is ugly.

How can I get the day of a specific date with PHP

You can use the date function. I'm using strtotime to get the timestamp to that day ; there are other solutions, like mktime, for instance.

For instance, with the 'D' modifier, for the textual representation in three letters :

$timestamp = strtotime('2009-10-22');

$day = date('D', $timestamp);
var_dump($day);

You will get :

string 'Thu' (length=3)

And with the 'l' modifier, for the full textual representation :

$day = date('l', $timestamp);
var_dump($day);

You get :

string 'Thursday' (length=8)

Or the 'w' modifier, to get to number of the day (0 to 6, 0 being sunday, and 6 being saturday) :

$day = date('w', $timestamp);
var_dump($day);

You'll obtain :

string '4' (length=1)

Get the records of last month in SQL server

If you are looking for previous month data:

date(date_created)>=date_sub(date_format(curdate(),"%Y-%m-01"),interval 1 month) and 
date(date_created)<=date_sub(date_format(curdate(),'%Y-%m-01'),interval 1 day)

This will also work when the year changes. It will also work on MySQL.

How do you use variables in a simple PostgreSQL script?

For the official CLI client "psql" see here. And "pgAdmin3" 1.10 (still in beta) has "pgScript".

What is the T-SQL syntax to connect to another SQL Server?

Whenever we are trying to retrieve any data from another server we need two steps.

First step:

-- Server one scalar variable
DECLARE @SERVER VARCHAR(MAX)
--Oracle is the server to which we want to connect
EXEC SP_ADDLINKEDSERVER @SERVER='ORACLE'

Second step:

--DBO is the owner name to know table owner name execute (SP_HELP TABLENAME)    
SELECT * INTO DESTINATION_TABLE_NAME 
FROM ORACLE.SOURCE_DATABASENAME.DBO.SOURCE_TABLE

How to avoid precompiled headers

try to add #include "stdafx.h" before #include "iostream"

Chrome / Safari not filling 100% height of flex parent

I have had a similar issue in iOS 8, 9 and 10 and the info above couldn't fix it, however I did discover a solution after a day of working on this. Granted it won't work for everyone but in my case my items were stacked in a column and had 0 height when it should have been content height. Switching the css to be row and wrap fixed the issue. This only works if you have a single item and they are stacked but since it took me a day to find this out I thought I should share my fix!

.wrapper {
    flex-direction: column; // <-- Remove this line
    flex-direction: row; // <-- replace it with
    flex-wrap: wrap; // <-- Add wrapping
}

.item {
    width: 100%;
}

Storing and Retrieving ArrayList values from hashmap

Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
     Map.Entry pairs = (Map.Entry)it.next();

     if(pairs.getKey().equals("mango"))
     {
        map.put(pairs.getKey(), pairs.getValue().add(18));
     }

     else if(!map.containsKey("mango"))
     {
        List<Integer> ints = new ArrayList<Integer>();
        ints.add(18);
        map.put("mango",ints);
     }

     it.remove(); // avoids a ConcurrentModificationException
}

EDIT: So inside the while try this:

map.put(pairs.getKey(), pairs.getValue().add(number))

You are getting the error because you are trying to put an integer to the values, whereas it is expected an ArrayList.

EDIT 2: Then put the following inside your while loop:

if(pairs.getKey().equals("mango"))
{
    map.put(pairs.getKey(), pairs.getValue().add(18));
}

else if(!map.containsKey("mango"))
{
     List<Integer> ints = new ArrayList<Integer>();
     ints.add(18);
     map.put("mango",ints);
 }

EDIT 3: By reading your requirements, I come to think you may not need a loop. You may want to only check if the map contains the key mango, and if it does add 18, else create a new entry in the map with key mango and value 18.

So all you may need is the following, without the loop:

if(map.containsKey("mango"))
{
    map.put("mango", map.get("mango).add(18));
}

else
{
    List<Integer> ints = new ArrayList<Integer>();
    ints.add(18);
    map.put("mango", ints);
}

Creating a JSON array in C#

Also , with Anonymous types ( I prefer not to do this) -- this is just another approach.

void Main()
{
    var x = new
    {
        items = new[]
        {
            new
            {
                name = "command", index = "X", optional = "0"
            },
            new
            {
                name = "command", index = "X", optional = "0"
            }
        }
    };
    JavaScriptSerializer js = new JavaScriptSerializer(); //system.web.extension assembly....
    Console.WriteLine(js.Serialize(x));
}

result :

{"items":[{"name":"command","index":"X","optional":"0"},{"name":"command","index":"X","optional":"0"}]}

Is there a default password to connect to vagrant when using `homestead ssh` for the first time?

After trying a lot of passwords and becoming totally confused why my public key password is not working I found out that I have to use vagrant as password.

Maybe this info helps someone else too - that's because I've written it down here.

Edit:
According to the Vagrant documentation, there is usually a default password for the user vagrant which is vagrant.
Read more on here: official website

In recent versions however, they have moved to generating keypairs for each machine. If you would like to find out where that key is, you can run vagrant ssh -- -v. This will show the verbose output of the ssh login process. You should see a line like

debug1: Trying private key: /home/aaron/Documents/VMs/.vagrant/machines/default/virtualbox/private_key

What is the use of System.in.read()?

Just to complement the accepted answer, you could also use System.out.read() like this:

class Example {
    public static void main(String args[])
        throws java.io.IOException { // This works! No need to use try{// ...}catch(IOException ex){// ...}         

        System.out.println("Type a letter: ");
        char letter = (char) System.in.read();
        System.out.println("You typed the letter " + letter);
    }
}

Use 'import module' or 'from module import'?

As Jan Wrobel mentions, one aspect of the different imports is in which way the imports are disclosed.

Module mymath

from math import gcd
...

Use of mymath:

import mymath
mymath.gcd(30, 42)  # will work though maybe not expected

If I imported gcd only for internal use, not to disclose it to users of mymath, this can be inconvenient. I have this pretty often, and in most cases I want to "keep my modules clean".

Apart from the proposal of Jan Wrobel to obscure this a bit more by using import math instead, I have started to hide imports from disclosure by using a leading underscore:

# for instance...
from math import gcd as _gcd
# or...
import math as _math

In larger projects this "best practice" allows my to exactly control what is disclosed to subsequent imports and what isn't. This keeps my modules clean and pays back at a certain size of project.

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

After days trying to find the answer, I finally found

display: table;

There was surprisingly very little information available online about how to actually getting it to work, even here, so on to the "How":

To use this fantastic piece of code, you need to think back to when tables were the only real way to structure HTML, namely the syntax. To get a table with 2 rows and 3 columns, you'd have to do the following:

<table>
    <tr>
        <td></td>
        <td></td>
        <td></td>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
    </tr>
</table>

Similarly to get CSS to do it, you'd use the following:

HTML

<div id="table">
    <div class="tr">
        <div class="td"></div>
        <div class="td"></div>
        <div class="td"></div>
    </div>
    <div class="tr">
        <div class="td"></div>
        <div class="td"></div>
        <div class="td"></div>
    </div>
</div>

CSS

#table{ 
    display: table; 
}
.tr{ 
    display: table-row; 
}
.td{ 
    display: table-cell; }

As you can see in the JSFiddle example below, the divs in the 3rd column have no content, yet are respecting the auto height set by the text in the first 2 columns. WIN!

http://jsfiddle.net/blyzz/1djs97yv/1/

It's worth noting that display: table; does not work in IE6 or 7 (thanks, FelipeAls), so depending on your needs with regards to browser compatibility, this may not be the answer that you are seeking.

Call to undefined function App\Http\Controllers\ [ function name ]

say you define the static getFactorial function inside a CodeController

then this is the way you need to call a static function, because static properties and methods exists with in the class, not in the objects created using the class.

CodeController::getFactorial($index);

----------------UPDATE----------------

To best practice I think you can put this kind of functions inside a separate file so you can maintain with more easily.

to do that

create a folder inside app directory and name it as lib (you can put a name you like).

this folder to needs to be autoload to do that add app/lib to composer.json as below. and run the composer dumpautoload command.

"autoload": {
    "classmap": [
                "app/commands",
                "app/controllers",
                ............
                "app/lib"
    ]
},

then files inside lib will autoloaded.

then create a file inside lib, i name it helperFunctions.php

inside that define the function.

if ( ! function_exists('getFactorial'))
{

    /**
     * return the factorial of a number
     *
     * @param $number
     * @return string
     */
    function getFactorial($date)
    {
        $fact = 1;

        for($i = 1; $i <= $num ;$i++)
            $fact = $fact * $i;

        return $fact;

     }
}

and call it anywhere within the app as

$fatorial_value = getFactorial(225);

What is the easiest way to get the current day of the week in Android?

Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
// 3 letter name form of the day
System.out.println(new SimpleDateFormat("EE", Locale.ENGLISH).format(date.getTime()));
// full name form of the day
System.out.println(new SimpleDateFormat("EEEE", Locale.ENGLISH).format(date.getTime()));

Result (for today):

Sat
Saturday

UPDATE: java8

LocalDate date = LocalDate.now();
DayOfWeek dow = date.getDayOfWeek();
System.out.println("Enum = " + dow);

String dayName = dow.getDisplayName(TextStyle.FULL, Locale.ENGLISH);
System.out.println("FULL = " + dayName);

dayName = dow.getDisplayName(TextStyle.FULL_STANDALONE, Locale.ENGLISH);
System.out.println("FULL_STANDALONE = " + dayName);

dayName = dow.getDisplayName(TextStyle.NARROW, Locale.ENGLISH);
System.out.println("NARROW = " + dayName);

dayName = dow.getDisplayName(TextStyle.NARROW_STANDALONE, Locale.ENGLISH);
System.out.println("NARROW_STANDALONE = " + dayName);

dayName = dow.getDisplayName(TextStyle.SHORT, Locale.ENGLISH);
System.out.println("SHORT = " + dayName);

dayName = dow.getDisplayName(TextStyle.SHORT_STANDALONE, Locale.ENGLISH);
System.out.println("SHORT_STANDALONE = " + dayName);

Result (for today):

Enum = SATURDAY
FULL = Saturday
FULL_STANDALONE = Saturday
NARROW = S
NARROW_STANDALONE = 6
SHORT = Sat
SHORT_STANDALONE = Sat

How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?

Try this

select * from mytable a join
(select home, max(datetime) datetime
from mytable
group by home) b
 on a.home = b.home and a.datetime = b.datetime

Regards K

if statement checks for null but still throws a NullPointerException

Change Below line

if (str == null | str.length() == 0) {

into

if (str == null || str.isEmpty()) {

now your code will run corectlly. Make sure str.isEmpty() comes after str == null because calling isEmpty() on null will cause NullPointerException. Because of Java uses Short-circuit evaluation when str == null is true it will not evaluate str.isEmpty()

Where should I put the log4j.properties file?

I know it's a bit late to answer this question, and maybe you already found the solution, but I'm posting the solution I found (after I googled a lot) so it may help a little:

  1. Put log4j.properties under WEB-INF\classes of the project as mentioned previously in this thread.
  2. Put log4j-xx.jar under WEB-INF\lib
  3. Test if log4j was loaded: add -Dlog4j.debug @ the end of your java options of tomcat

Hope this will help.

rgds

how to read xml file from url using php

you can get the data from the XML by using "simplexml_load_file" Function. Please refer this link

http://php.net/manual/en/function.simplexml-load-file.php

$url = "http://maps.google.com/maps/api/directions/xml?origin=Quentin+Road+Brooklyn%2C+New+York%2C+11234+United+States&destination=550+Madison+Avenue+New+York%2C+New+York%2C+10001+United+States&sensor=false";
$xml = simplexml_load_file($url);
print_r($xml);

Saving binary data as file using JavaScript from a browser

Try

_x000D_
_x000D_
let bytes = [65,108,105,99,101,39,115,32,65,100,118,101,110,116,117,114,101];_x000D_
_x000D_
let base64data = btoa(String.fromCharCode.apply(null, bytes));_x000D_
_x000D_
let a = document.createElement('a');_x000D_
a.href = 'data:;base64,' + base64data;_x000D_
a.download = 'binFile.txt'; _x000D_
a.click();
_x000D_
_x000D_
_x000D_

I convert here binary data to base64 (for bigger data conversion use this) - during downloading browser decode it automatically and save raw data in file. 2020.06.14 I upgrade Chrome to 83.0 and above SO snippet stop working (probably due to sandbox security restrictions) - but JSFiddle version works - here

Unable to execute dex: Multiple dex files define Lcom/myapp/R$array;

This problem was happening me, I had an external .jar in my libs folder called gson-2.2.2.jar but for some reason there were two of them, gson-2.2.2.jar and gson-2.2.2.jar(1), I simply deleted the latter and my project built fine again.

How to export table as CSV with headings on Postgresql?

This solution worked for me using \copy.

psql -h <host> -U <user> -d <dbname> -c "\copy <table_name> FROM '<path to csvfile/file.csv>' with (format csv,header true, delimiter ',');"

Using BufferedReader to read Text File

You can assign the result of br.readLine() to a variable and use that both for processing and for checking, like so:

String line = br.readLine();
while (line != null) { // You might also want to check for empty?
    System.out.println(line);
    line = br.readLine();
}

How do I use Comparator to define a custom sort order?

In Java 8 you can do something like this:

You first need an Enum:

public enum Color {
    BLUE, YELLOW, RED
}

Car class:

public class Car {

    Color color;

    ....

    public Color getColor() {
        return color;
    }

    public void setColor(Color color) {
        this.color = color;
    }
}

And then, using your car list, you can simply do:

Collections.sort(carList, Comparator:comparing(CarSort::getColor));

What is a race condition?

A race condition is an undesirable situation that occurs when two or more process can access and change the shared data at the same time.It occurred because there were conflicting accesses to a resource . Critical section problem may cause race condition. To solve critical condition among the process we have take out only one process at a time which execute the critical section.

How to start an application without waiting in a batch file?

If start can't find what it's looking for, it does what you describe.

Since what you're doing should work, it's very likely you're leaving out some quotes (or putting extras in).

Reverse a string without using reversed() or [::-1]?

You can simply use the pop as suggested. Here are one liners fot that

chaine = 'qwertyuiop'
''.join([chaine[-(x + 1)] for x in range(len(chaine))])
'poiuytrewq'
gg = list(chaine)
''.join([gg.pop() for _ in range(len(gg))])
'poiuytrewq'

CertificateException: No name matching ssl.someUrl.de found

If you're looking for a Kafka error, this might because the upgrade of Kafka's version from 1.x to 2.x.

javax.net.ssl.SSLHandshakeException: General SSLEngine problem ... javax.net.ssl.SSLHandshakeException: General SSLEngine problem ... java.security.cert.CertificateException: No name matching *** found

or

[Producer clientId=producer-1] Connection to node -2 failed authentication due to: SSL handshake failed

The default value for ssl.endpoint.identification.algorithm was changed to https, which performs hostname verification (man-in-the-middle attacks are possible otherwise). Set ssl.endpoint.identification.algorithm to an empty string to restore the previous behaviour. Apache Kafka Notable changes in 2.0.0

Solution: SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, ""

Connecting to SQL Server using windows authentication

Check out www.connectionstrings.com for a ton of samples of proper connection strings.

In your case, use this:

Server=localhost;Database=employeedetails;Integrated Security=SSPI

Update: obviously, the service account used to run ASP.NET web apps doesn't have access to SQL Server, and judging from that error message, you're probably using "anonymous authentication" on your web site.

So you either need to add this account IIS APPPOOL\ASP.NET V4.0 as a SQL Server login and give that login access to your database, or you need to switch to using "Windows authentication" on your ASP.NET web site so that the calling Windows account will be passed through to SQL Server and used as a login on SQL Server.

Char array to hex string C++

I've found good example here Display-char-as-Hexadecimal-String-in-C++:

  std::vector<char> randomBytes(n);
  file.read(&randomBytes[0], n);

  // Displaying bytes: method 1
  // --------------------------
  for (auto& el : randomBytes)
    std::cout << std::setfill('0') << std::setw(2) << std::hex << (0xff & (unsigned int)el);
  std::cout << '\n';

  // Displaying bytes: method 2
  // --------------------------
  for (auto& el : randomBytes)
    printf("%02hhx", el);
  std::cout << '\n';
  return 0;

Method 1 as shown above is probably the more C++ way:

Cast to an unsigned int
Use std::hex to represent the value as hexadecimal digits
Use std::setw and std::setfill from <iomanip> to format
Note that you need to mask the cast int against 0xff to display the least significant byte:
(0xff & (unsigned int)el).

Otherwise, if the highest bit is set the cast will result in the three most significant bytes being set to ff.

jQuery see if any or no checkboxes are selected

You can do this:

  if ($('#form_id :checkbox:checked').length > 0){
    // one or more checkboxes are checked
  }
  else{
   // no checkboxes are checked
  }

Where:

  • :checkbox filter selector selects all checkbox.
  • :checked will select checked checkboxes
  • length will give the number of checked ones there

How to center HTML5 Videos?

I was having the same problem, until I realized that <video> elements are inline elements, not block elements. You need only set the container element to have text-align: center; in order to center the video horizontally on the page.

Handling a Menu Item Click Event - Android

in addition to the options shown in your question, there is the possibility of implementing the action directly in your xml file from the menu, for example:

<item
   android:id="@+id/OK_MENU_ITEM"
   android:onClick="showMsgDirectMenuXml" />

And for your Java (Activity) file, you need to implement a public method with a single parameter of type MenuItem, for example:

 private void showMsgDirectMenuXml(MenuItem item) {
    Toast toast = Toast.makeText(this, "OK", Toast.LENGTH_LONG);
    toast.show();
  }

NOTE: This method will have behavior similar to the onOptionsItemSelected (MenuItem item)

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

If you are in Chrome you can check the Post Data

Here is How to check the Post data

  1. Go to Network Tab
  2. Look for the Link to which you are sending Post Data
  3. Click on it
  4. In the Headers, you can check Request Payload to check the post data

Chrome's DevTools

Laravel 5.2 - pluck() method returns array

laravel pluck returns an array

if your query is:

 $name = DB::table('users')->where('name', 'John')->pluck('name');

then the array is like this (key is the index of the item. auto incremented value):

[
    1 => "name1",
    2 => "name2",
    .
    .
    .
    100 => "name100"
]

but if you do like this:

$name = DB::table('users')->where('name', 'John')->pluck('name','id');

then the key is actual index in the database.

key||value
[
    1 => "name1",
    2 => "name2",
    .
    .
    .
    100 => "name100"
]

you can set any value as key.

What does the Visual Studio "Any CPU" target mean?

Any CPU means that it will work on any platform. This is because managed code is similar to Java. Think of it as being compiled to a byte code that is interpreted by the .NET Framework at run-time.

C++ does not have this option because it is compiled to machine code that is platform specific.

What are .dex files in Android?

.dex file

Compiled Android application code file.

Android programs are compiled into .dex (Dalvik Executable) files, which are in turn zipped into a single .apk file on the device. .dex files can be created automatically by Android, by translating the compiled applications written in the Java programming language.

send mail to multiple receiver with HTML mailto

"There are no safe means of assigning multiple recipients to a single mailto: link via HTML. There are safe, non-HTML, ways of assigning multiple recipients from a mailto: link."

http://www.sightspecific.com/~mosh/www_faq/multrec.html

For a quick fix to your problem, change your ; to a comma , and eliminate the spaces between email addresses

<a href='mailto:[email protected],[email protected]'>Email Us</a>

Insert Unicode character into JavaScript

Although @ruakh gave a good answer, I will add some alternatives for completeness:

You could in fact use even var Omega = '&#937;' in JavaScript, but only if your JavaScript code is:

  • inside an event attribute, as in onclick="var Omega = '&#937'; alert(Omega)" or
  • in a script element inside an XHTML (or XHTML + XML) document served with an XML content type.

In these cases, the code will be first (before getting passed to the JavaScript interpreter) be parsed by an HTML parser so that character references like &#937; are recognized. The restrictions make this an impractical approach in most cases.

You can also enter the O character as such, as in var Omega = 'O', but then the character encoding must allow that, the encoding must be properly declared, and you need software that let you enter such characters. This is a clean solution and quite feasible if you use UTF-8 encoding for everything and are prepared to deal with the issues created by it. Source code will be readable, and reading it, you immediately see the character itself, instead of code notations. On the other hand, it may cause surprises if other people start working with your code.

Using the \u notation, as in var Omega = '\u03A9', works independently of character encoding, and it is in practice almost universal. It can however be as such used only up to U+FFFF, i.e. up to \uffff, but most characters that most people ever heard of fall into that area. (If you need “higher” characters, you need to use either surrogate pairs or one of the two approaches above.)

You can also construct a character using the String.fromCharCode() method, passing as a parameter the Unicode number, in decimal as in var Omega = String.fromCharCode(937) or in hexadecimal as in var Omega = String.fromCharCode(0x3A9). This works up to U+FFFF. This approach can be used even when you have the Unicode number in a variable.

Read and write a String from text file

It is recommended to read and write files asynchronously! and it's so easy to do in pure Swift,
here is the protocol:

protocol FileRepository {
    func read(from path: String) throws -> String
    func readAsync(from path: String, completion: @escaping (Result<String, Error>) -> Void)
    func write(_ string: String, to path: String) throws
    func writeAsync(_ string: String, to path: String, completion: @escaping (Result<Void, Error>) -> Void)
}

As you can see it allows you to read and write files synchronously or asynchronously.

Here is my implementation in Swift 5:

class DefaultFileRepository {
    
    // MARK: Properties
    
    let queue: DispatchQueue = .global()
    let fileManager: FileManager = .default
    lazy var baseURL: URL = {
        try! fileManager
            .url(for: .libraryDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
            .appendingPathComponent("MyFiles")
    }()
    
    
    // MARK: Private functions
    
    private func doRead(from path: String) throws -> String {
        let url = baseURL.appendingPathComponent(path)
        
        var isDir: ObjCBool = false
        guard fileManager.fileExists(atPath: url.path, isDirectory: &isDir) && !isDir.boolValue else {
            throw ReadWriteError.doesNotExist
        }
        
        let string: String
        do {
            string = try String(contentsOf: url)
        } catch {
            throw ReadWriteError.readFailed(error)
        }
        
        return string
    }
    
    private func doWrite(_ string: String, to path: String) throws {
        let url = baseURL.appendingPathComponent(path)
        let folderURL = url.deletingLastPathComponent()
        
        var isFolderDir: ObjCBool = false
        if fileManager.fileExists(atPath: folderURL.path, isDirectory: &isFolderDir) {
            if !isFolderDir.boolValue {
                throw ReadWriteError.canNotCreateFolder
            }
        } else {
            do {
                try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
            } catch {
                throw ReadWriteError.canNotCreateFolder
            }
        }
        
        var isDir: ObjCBool = false
        guard !fileManager.fileExists(atPath: url.path, isDirectory: &isDir) || !isDir.boolValue else {
            throw ReadWriteError.canNotCreateFile
        }
        
        guard let data = string.data(using: .utf8) else {
            throw ReadWriteError.encodingFailed
        }
        
        do {
            try data.write(to: url)
        } catch {
            throw ReadWriteError.writeFailed(error)
        }
    }
    
}


extension DefaultFileRepository: FileRepository {
    func read(from path: String) throws -> String {
        try queue.sync { try self.doRead(from: path) }
    }
    
    func readAsync(from path: String, completion: @escaping (Result<String, Error>) -> Void) {
        queue.async {
            do {
                let result = try self.doRead(from: path)
                completion(.success(result))
            } catch {
                completion(.failure(error))
            }
        }
    }
    
    func write(_ string: String, to path: String) throws {
        try queue.sync { try self.doWrite(string, to: path) }
    }
    
    func writeAsync(_ string: String, to path: String, completion: @escaping (Result<Void, Error>) -> Void) {
        queue.async {
            do {
                try self.doWrite(string, to: path)
                completion(.success(Void()))
            } catch {
                completion(.failure(error))
            }
        }
    }
    
}


enum ReadWriteError: LocalizedError {
    
    // MARK: Cases
    
    case doesNotExist
    case readFailed(Error)
    case canNotCreateFolder
    case canNotCreateFile
    case encodingFailed
    case writeFailed(Error)
}

keyCode values for numeric keypad?

Little bit cleared @A.Morel's answer. You might beware of keyboard language layout. Some keyboard layouts changed default numeric keys to symbols.

let key = parseInt(e.key)
if (isNaN(key)) {
  console.log("is not numeric")
}
else {
  console.log("is numeric")
}

div inside php echo

You can do the following:

echo '<div class="my_class">';
echo ($cart->count_product > 0) ? $cart->count_product : '';
echo '</div>';

If you want to have it inside your statement, do this:

if($cart->count_product > 0) 
{
    echo '<div class="my_class">'.$cart->count_product.'</div>';
}

You don't need the else statement, since you're only going to output the above when it's truthy anyway.

How to access Anaconda command prompt in Windows 10 (64-bit)

How to add anaconda installation directory to your PATH variables

1. open environmental variables window

Do this by either going to my computer and then right clicking the background for the context menu > "properties". On the left side open "advanced system settings" or just search for "env..." in start menu ([Win]+[s] keys).

Then click on environment variables

If you struggle with this step read this explanation.

2. Edit Path in the user environmental variables section and add three new entries:

  • D:\path\to\anaconda3
  • D:\path\to\anaconda3\Scripts
  • D:\path\to\anaconda3\Library\bin

D:\path\to\anaconda3 should be the folder where you have installed anaconda

Click [OK] on all opened windows.

If you did everything correctly, you can test a conda command by opening a new powershell window.

conda --version

This should output something like: conda 4.8.2

Compiled vs. Interpreted Languages

The extreme and simple cases:

  • A compiler will produce a binary executable in the target machine's native executable format. This binary file contains all required resources except for system libraries; it's ready to run with no further preparation and processing and it runs like lightning because the code is the native code for the CPU on the target machine.

  • An interpreter will present the user with a prompt in a loop where he can enter statements or code, and upon hitting RUN or the equivalent the interpreter will examine, scan, parse and interpretatively execute each line until the program runs to a stopping point or an error. Because each line is treated on its own and the interpreter doesn't "learn" anything from having seen the line before, the effort of converting human-readable language to machine instructions is incurred every time for every line, so it's dog slow. On the bright side, the user can inspect and otherwise interact with his program in all kinds of ways: Changing variables, changing code, running in trace or debug modes... whatever.

With those out of the way, let me explain that life ain't so simple any more. For instance,

  • Many interpreters will pre-compile the code they're given so the translation step doesn't have to be repeated again and again.
  • Some compilers compile not to CPU-specific machine instructions but to bytecode, a kind of artificial machine code for a ficticious machine. This makes the compiled program a bit more portable, but requires a bytecode interpreter on every target system.
  • The bytecode interpreters (I'm looking at Java here) recently tend to re-compile the bytecode they get for the CPU of the target section just before execution (called JIT). To save time, this is often only done for code that runs often (hotspots).
  • Some systems that look and act like interpreters (Clojure, for instance) compile any code they get, immediately, but allow interactive access to the program's environment. That's basically the convenience of interpreters with the speed of binary compilation.
  • Some compilers don't really compile, they just pre-digest and compress code. I heard a while back that's how Perl works. So sometimes the compiler is just doing a bit of the work and most of it is still interpretation.

In the end, these days, interpreting vs. compiling is a trade-off, with time spent (once) compiling often being rewarded by better runtime performance, but an interpretative environment giving more opportunities for interaction. Compiling vs. interpreting is mostly a matter of how the work of "understanding" the program is divided up between different processes, and the line is a bit blurry these days as languages and products try to offer the best of both worlds.

How do you do a ‘Pause’ with PowerShell 2.0?

The solutions like cmd /c pause cause a new command interpreter to start and run in the background. Although acceptable in some cases, this isn't really ideal.

The solutions using Read-Host force the user to press Enter and are not really "any key".

This solution will give you a true "press any key to continue" interface and will not start a new interpreter, which will essentially mimic the original pause command.

Write-Host "Press any key to continue..."
[void][System.Console]::ReadKey($true)

display: inline-block extra margin

The divs are treated as inline-elements. Just as a space or line-break between two spans would create a gap, it does between inline-blocks. You could either give them a negative margin or set word-spacing: -1; on the surrounding container.

Amazon Interview Question: Design an OO parking lot

In an Object Oriented parking lot, there will be no need for attendants because the cars will "know how to park".

Finding a usable car on the lot will be difficult; the most common models will either have all their moving parts exposed as public member variables, or they will be "fully encapsulated" cars with no windows or doors.

The parking spaces in our OO parking lot will not match the size and shape of the cars (an "impediance mismatch" between the spaces and the cars)

License tags on our lot will have a dot between each letter and digit. Handicaped parking will only be available for licenses beginning with "_", and licenses beginning with "m_" will be towed.

Handling NULL values in Hive

Try using isnull(a), isnotnull(a), nvl(), etc. On some versions(potentially in conjunction with the server settings - atleast with the one I am working on) of hive the 'IS NULL' and 'IS NOT NULL' syntax does not execute the logic when it is compiled. Check here for more information.

How do you push just a single Git branch (and no other branches)?

By default git push updates all the remote branches. But you can configure git to update only the current branch to it's upstream.

git config push.default upstream

It means git will update only the current (checked out) branch when you do git push.

Other valid options are:

  • nothing : Do not push anything (error out) unless a refspec is explicitly given. This is primarily meant for people who want to avoid mistakes by always being explicit.
  • matching : Push all branches having the same name on both ends. (default option prior to Ver 1.7.11)
  • upstream: Push the current branch to its upstream branch. This mode only makes sense if you are pushing to the same repository you would normally pull from (i.e. central workflow). No need to have the same name for local and remote branch.
  • tracking : Deprecated, use upstream instead.
  • current : Push the current branch to the remote branch of the same name on the receiving end. Works in both central and non-central workflows.
  • simple : [available since Ver 1.7.11] in centralized workflow, work like upstream with an added safety to refuse to push if the upstream branch’s name is different from the local one. When pushing to a remote that is different from the remote you normally pull from, work as current. This is the safest option and is suited for beginners. This mode has become the default in Git 2.0.

How can I determine if a .NET assembly was built for x86 or x64?

Try to use CorFlagsReader from this project at CodePlex. It has no references to other assemblies and it can be used as is.

How to save a BufferedImage as a File

File outputfile = new File("image.jpg");
ImageIO.write(bufferedImage, "jpg", outputfile);

What is an opaque response, and what purpose does it serve?

Opaque responses can't be accessed by JavaScript, but you can still cache them with the Cache API and respond with them in the fetch event handler in a service worker. So they're useful for making your app offline, also for resources that you can't control (e.g. resources on a CDN that doesn't set the CORS headers).

Check if list<t> contains any of another list

Here is a sample to find if there are match elements in another list

List<int> nums1 = new List<int> { 2, 4, 6, 8, 10 };
List<int> nums2 = new List<int> { 1, 3, 6, 9, 12};

if (nums1.Any(x => nums2.Any(y => y == x)))
{
    Console.WriteLine("There are equal elements");
}
else
{
    Console.WriteLine("No Match Found!");
}

Reasons for using the set.seed function

basically set.seed() function will help to reuse the same set of random variables , which we may need in future to again evaluate particular task again with same random varibales

we just need to declare it before using any random numbers generating function.

VBA copy rows that meet criteria to another sheet

After formatting the previous answer to my own code, I have found an efficient way to copy all necessary data if you are attempting to paste the values returned via AutoFilter to a separate sheet.

With .Range("A1:A" & LastRow)
    .Autofilter Field:=1, Criteria1:="=*" & strSearch & "*"
    .Offset(1,0).SpecialCells(xlCellTypeVisible).Cells.Copy
    Sheets("Sheet2").activate
    DestinationRange.PasteSpecial
End With

In this block, the AutoFilter finds all of the rows that contain the value of strSearch and filters out all of the other values. It then copies the cells (using offset in case there is a header), opens the destination sheet and pastes the values to the specified range on the destination sheet.

How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

I think that using the @EnableAutoConfiguration annotation on a test class won't work if you are using @SpringApplicationConfiguration to load your Application class. The thing is that you already have a @EnableAutoConfiguration annotation in the Application class that does not exclude the CrshAutoConfiguration.Spring uses that annotation instead of the one on your test class to do the auto configuration of your beans.

I think that your best bet is to use a different application context for your tests and exclude the CrshAutoConfiguration in that class.

I did some tests and it seems that @EnableAutoConfiguration on the test class is completely ignore if you are using the @SpringApplicationConfiguration annotation and the SpringJUnit4ClassRunner.

Foreign Key Django Model

I would advise, it is slightly better practise to use string model references for ForeignKey relationships if utilising an app based approach to seperation of logical concerns .

So, expanding on Martijn Pieters' answer:

class Person(models.Model):
    name = models.CharField(max_length=50)
    birthday = models.DateField()
    anniversary = models.ForeignKey(
        'app_label.Anniversary', on_delete=models.CASCADE)
    address = models.ForeignKey(
        'app_label.Address', on_delete=models.CASCADE)

class Address(models.Model):
    line1 = models.CharField(max_length=150)
    line2 = models.CharField(max_length=150)
    postalcode = models.CharField(max_length=10)
    city = models.CharField(max_length=150)
    country = models.CharField(max_length=150)

class Anniversary(models.Model):
    date = models.DateField()

Tools: replace not replacing in Android manifest

Final Working Solution for me (Highlighted the tages in the sample code):

  1. add the xmlns:tools line in the manifest tag
  2. add tools:replace in the application tag

Example:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="pagination.yoga.com.tamiltv"
    **xmlns:tools="http://schemas.android.com/tools"**
    >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        **tools:replace="android:icon,android:theme"**
        >

MySQL Stored procedure variables from SELECT statements

You simply need to enclose your SELECT statements in parentheses to indicate that they are subqueries:

SET cityLat = (SELECT cities.lat FROM cities WHERE cities.id = cityID);

Alternatively, you can use MySQL's SELECT ... INTO syntax. One advantage of this approach is that both cityLat and cityLng can be assigned from a single table-access:

SELECT lat, lng INTO cityLat, cityLng FROM cities WHERE id = cityID;

However, the entire procedure can be replaced with a single self-joined SELECT statement:

SELECT   b.*, HAVERSINE(a.lat, a.lng, b.lat, b.lng) AS dist
FROM     cities AS a, cities AS b
WHERE    a.id = cityID
ORDER BY dist
LIMIT    10;

In-place edits with sed on OS X

You can use:

sed -i -e 's/<string-to-find>/<string-to-replace>/' <your-file-path>

Example:

sed -i -e 's/Hello/Bye/' file.txt

This works flawless in Mac.

Generating an MD5 checksum of a file

change the file_path to your file

import hashlib
def getMd5(file_path):
    m = hashlib.md5()
    with open(file_path,'rb') as f:
        line = f.read()
        m.update(line)
    md5code = m.hexdigest()
    return md5code

"While .. End While" doesn't work in VBA?

VBA is not VB/VB.NET

The correct reference to use is Do..Loop Statement (VBA). Also see the article Excel VBA For, Do While, and Do Until. One way to write this is:

Do While counter < 20
    counter = counter + 1
Loop

(But a For..Next might be more appropriate here.)

Happy coding.

How can I find the version of the Fedora I use?

The simplest command which can give you what you need but some other good info too is:

hostnamectl

The type initializer for 'Oracle.DataAccess.Client.OracleConnection' threw an exception

This is an old, but still relevant question, and while the answers here are helpful no one answer fully addressed both of the OP's questions.

1. Do I have to install ODP.NET and Oracle client on the computer that I want to run my application?

YES - if you are using ODP.NET, Unmanaged. This is the version that you typically install when you choose "Oracle Data Provider for .NET" in the Oracle Client installer (for example). You Download this from Oracle (just google it: Oracle URLs change often).

But If you are using ODP.NET, Managed (and you probably want to use this one this instead) then No, you only need to install (or deploy) ODP.NET, Managed with the app, not the full Oracle Client. See below for details.

2. If yes, is there other way that I don't have to install them but still can run my application?

Yes, there is at least one way. And it is the Managed port of ODP.NET.

Unfortunately the usual workarounds, including ODBC, Microsoft's Oracle Provider for .NET (yes, that old, deprecated one), and the ODP.NET, Unmanaged DLL all require the Oracle client to be installed. It wasn't until our friends at Oracle gave us a nice little (~5MB) DLL that is also Managed. This means no more having to depoy 32-bit and 64-bit versions to go with 32-bit and 64-bit Oracle clients! And no more issues with assembly binding where you build against 10.0.2.1 (or whatever) but your customers install a range of clients from 9i all the way to 12c, including the 'g' ones in the middle) because you can just ship it with your app, and manage it via nuget.

But if you use ODP.NET, Managed which is available as a nuget package, then you do not need to install the Oracle Client. You only need the ODP.NET, Managed DLL. And if you were previously using the ODP.NET, Unmanaged DLL, it is very easy to switch: simply change all your references to the Managed ODP.NET (.csproj files in csharp, etc.), and then change any using statements, for example: using Oracle.DataAccess.Client becomes using Oracle.ManagedDataAccess.Client and that's it! (Unless you were supposedly using some of the more advanced DB management features in the full client that are exposed in the ODP.NET, Unmanaged, which I have not done myself, so good luck with that..). And also nuke all of those annoying assemblyBindingRedirect nodes from your app.config/web.config files and never sweat that junk again!

References:

Troubleshooting:

That error typically means ODP.NET was found OK, but Oracle client was not found or not installed. This could also occur when the architecture doesn't match (32-bit Oracle client is installed, but trying to use 64-bit Unmanaged ODP.NET, or vice versa). This can also happen due to permissions issues and path issues and other problems with the app domain (your web app or your EXE or whatever) not being able to find the Oracle DLLs to actually communicate with Oracle over the network (the ODP.NET Unmanaged DLLs are basically just wrappers for this that hook into ADO and stuff).

Common solutions I have found to this problem:

App is 64-bit?

  • Install 64-bit Oracle Client (32-bit one wont work)

App is 32-bit?

  • Install 32-bit Oracle Client (64-bit one wont work)

Oracle Client is already installed for the correct architecture?

  • Verify your environment PATH and ORACLE_HOME variables, make sure Oracle can be found (newer versions may use Registry instead)
  • Verify the ORACLE_HOME and settings in the Registry (And remember: Registry is either 32-bit or 64-bit, so make sure you check the one that matches your app!)
  • Verify permissions on the ORACLE_HOME folder. If you don't know where this is, check the Registry. I have seen cases where ASP.NET app worker process was using Network Service user and for some reason installing 32-bit and 64-bit clients side by side resulted in the permissions being removed from the first client for the Authorized Users group.. fixing perms on the home folder fixed this.
  • As always, it is handy to Use SysInternals Process Monitor to find out what file is missing or can't be read.

App store link for "rate/review this app"

Starting in iOS 10.3:

import StoreKit

func someFunction() {
 SKStoreReviewController.requestReview()
}

but its has been just released with 10.3, so you will still need some fallback method for older versions as described above

pull access denied repository does not exist or may require docker login

If you're downloading from somewhere else than your own registry or docker-hub, you might have to do a separate agreement of terms on their site, like the case with Oracle's docker registry. It allows you to do docker login fine, but pulling the container won't still work until you go to their site and agree on their terms.

java.lang.ClassNotFoundException:com.mysql.jdbc.Driver

if it is standalone program, download mysql connector jar and add it to your classpath.

if it is a maven project, add below dependency and run your program.

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.37</version>
</dependency>

ExpressJS How to structure an application?

1) Your Express project filesystem maybe like:

/ ...
/lib
/node_modules
/public
/views
      app.js
      config.json
      package.json

app.js - you global app container

2) Module main file (lib/mymodule/index.js):

var express = require('express');    
var app = module.exports = express();
// and load module dependencies ...  

// this place to set module settings
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');

// then do module staff    
app.get('/mymodule/route/',function(req,res){ res.send('module works!') });

3) Connect module in main app.js

...
var mymodule = require('mymodule');
app.use(mymodule);

4) Sample logic

lib/login
lib/db
lib/config
lib/users
lib/verify
lib/
   /api/ 
   ...
lib/
   /admin/
      /users/
      /settings/
      /groups/
...
  • Best for testing
  • Best for scale
  • Separate depends by module
  • Grouping route by functionality (or modules)

tj says/show on Vimeo interesting idea how modularize express application - Modular web applications with Node.js and Express. Powerful and simple.

Why does Math.Round(2.5) return 2 instead of 3?

You should check MSDN for Math.Round:

The behavior of this method follows IEEE Standard 754, section 4. This kind of rounding is sometimes called rounding to nearest, or banker's rounding.

You can specify the behavior of Math.Round using an overload:

Math.Round(2.5, 0, MidpointRounding.AwayFromZero); // gives 3

Math.Round(2.5, 0, MidpointRounding.ToEven); // gives 2

How to create a file in Ruby

Try

File.open("out.txt", "w") do |f|     
  f.write(data_you_want_to_write)   
end

without using the

File.new "out.txt"

Where is database .bak file saved from SQL Server Management Studio?

If the backup wasn't created in the default location, you can use this T-SQL (run this in SSMS) to find the file path for the most recent backup for all DBs on your SQL Server instance:

SELECT  DatabaseName = x.database_name,
        LastBackupFileName = x.physical_device_name,
        LastBackupDatetime = x.backup_start_date
FROM (  SELECT  bs.database_name,
                bs.backup_start_date,
                bmf.physical_device_name,
                  Ordinal = ROW_NUMBER() OVER( PARTITION BY bs.database_name ORDER BY bs.backup_start_date DESC )
          FROM  msdb.dbo.backupmediafamily bmf
                  JOIN msdb.dbo.backupmediaset bms ON bmf.media_set_id = bms.media_set_id
                  JOIN msdb.dbo.backupset bs ON bms.media_set_id = bs.media_set_id
          WHERE   bs.[type] = 'D'
                  AND bs.is_copy_only = 0 ) x
WHERE x.Ordinal = 1
ORDER BY DatabaseName;

Google Maps API - Get Coordinates of address

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

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

PHP class: Global variable as property in class

If you want to access a property from inside a class you should:

private $classNumber = 8;

LDAP server which is my base dn

Either you set LDAP_DOMAIN variable or you misconfigured it. Jump inside of ldap machine/container and run:

slapcat > backup.ldif

If it fails, check punctuation, quotes etc while you assigned variable "LDAP_DOMAIN" Otherwise you will find answer inside on backup.ldif file.

Rename Pandas DataFrame Index

For Single Index :

 df.index.rename('new_name')

For Multi Index :

 df.index.rename(['new_name','new_name2'])

WE can also use this in latest pandas :

rename_axis

SimpleDateFormat and locale based format string

Java8

 import java.time.format.DateTimeFormatter;         
 myDate.format(DateTimeFormatter.ofPattern("dd-MMM-YYYY",new Locale("ar")))

What is the best way to programmatically detect porn images?

Nude.js based on the whitepaper by Rigan Ap-apid from De La Salle University.

Python - PIP install trouble shooting - PermissionError: [WinError 5] Access is denied

Do not use the command prompt in the IDE. Run the command prompt from windows as an administrator. I'm sure this will solve the problem. If not, uninstall pip and reinstall the latest one directly.

Python's most efficient way to choose longest string in list?

def LongestEntry(lstName):
  totalEntries = len(lstName)
  currentEntry = 0
  longestLength = 0
  while currentEntry < totalEntries:
    thisEntry = len(str(lstName[currentEntry]))
    if int(thisEntry) > int(longestLength):
      longestLength = thisEntry
      longestEntry = currentEntry
    currentEntry += 1
  return longestLength

How is VIP swapping + CNAMEs better than IP swapping + A records?

A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.

Check if table exists and if it doesn't exist, create it in SQL Server 2008

Declare @Username varchar(20)
Set @Username = 'Mike'

if not exists 
(Select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'tblEmp')

Begin
    Create table tblEmp (ID int primary key, Name varchar(50))
    Print (@Username + ' Table created successfully')
End

Else

Begin
    Print (@Username + ' : this Table Already exists in the database')
End

SQL - Update multiple records in one query

Try either multi-table update syntax

UPDATE config t1 JOIN config t2
    ON t1.config_name = 'name1' AND t2.config_name = 'name2'
   SET t1.config_value = 'value',
       t2.config_value = 'value2';

Here is SQLFiddle demo

or conditional update

UPDATE config
   SET config_value = CASE config_name 
                      WHEN 'name1' THEN 'value' 
                      WHEN 'name2' THEN 'value2' 
                      ELSE config_value
                      END
 WHERE config_name IN('name1', 'name2');

Here is SQLFiddle demo

How do I check to see if my array includes an object?

Array's include?method accepts any object, not just a string. This should work:

@suggested_horses = [] 
@suggested_horses << Horse.first(:offset => rand(Horse.count)) 
while @suggested_horses.length < 8 
  horse = Horse.first(:offset => rand(Horse.count)) 
  @suggested_horses << horse unless @suggested_horses.include?(horse)
end

How to parse/format dates with LocalDateTime? (Java 8)

All the answers are good. The java8+ have these patterns for parsing and formatting timezone: V, z, O, X, x, Z.

Here's they are, for parsing, according to rules from the documentation :

   Symbol  Meaning                     Presentation      Examples
   ------  -------                     ------------      -------
   V       time-zone ID                zone-id           America/Los_Angeles; Z; -08:30
   z       time-zone name              zone-name         Pacific Standard Time; PST
   O       localized zone-offset       offset-O          GMT+8; GMT+08:00; UTC-08:00;
   X       zone-offset 'Z' for zero    offset-X          Z; -08; -0830; -08:30; -083015; -08:30:15;
   x       zone-offset                 offset-x          +0000; -08; -0830; -08:30; -083015; -08:30:15;
   Z       zone-offset                 offset-Z          +0000; -0800; -08:00;

But how about formatting? Here's a sample for a date (assuming ZonedDateTime) that show these patters behavior for different formatting patters:

// The helper function:
static void printInPattern(ZonedDateTime dt, String pattern) {
    System.out.println(pattern + ": " + dt.format(DateTimeFormatter.ofPattern(pattern)));
}        

// The date:
String strDate = "2020-11-03 16:40:44 America/Los_Angeles";
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss zzzz");
ZonedDateTime dt = ZonedDateTime.parse(strDate, format);
// 2020-11-03T16:40:44-08:00[America/Los_Angeles]

// Rules:
// printInPattern(dt, "V");     // exception!
printInPattern(dt, "VV");       // America/Los_Angeles
// printInPattern(dt, "VVV");   // exception!
// printInPattern(dt, "VVVV");  // exception!
printInPattern(dt, "z");        // PST
printInPattern(dt, "zz");       // PST
printInPattern(dt, "zzz");      // PST
printInPattern(dt, "zzzz");     // Pacific Standard Time
printInPattern(dt, "O");        // GMT-8
// printInPattern(dt, "OO");    // exception!
// printInPattern(dt, "OO0");   // exception!
printInPattern(dt, "OOOO");     // GMT-08:00
printInPattern(dt, "X");        // -08
printInPattern(dt, "XX");       // -0800
printInPattern(dt, "XXX");      // -08:00
printInPattern(dt, "XXXX");     // -0800
printInPattern(dt, "XXXXX");    // -08:00
printInPattern(dt, "x");        // -08
printInPattern(dt, "xx");       // -0800
printInPattern(dt, "xxx");      // -08:00
printInPattern(dt, "xxxx");     // -0800
printInPattern(dt, "xxxxx");    // -08:00
printInPattern(dt, "Z");        // -0800
printInPattern(dt, "ZZ");       // -0800
printInPattern(dt, "ZZZ");      // -0800
printInPattern(dt, "ZZZZ");     // GMT-08:00
printInPattern(dt, "ZZZZZ");    // -08:00

In the case of positive offset the + sign character is used everywhere(where there is - now) and never omitted.

This well works for new java.time types. If you're about to use these for java.util.Date or java.util.Calendar - not all going to work as those types are broken(and so marked as deprecated, please don't use them)

css3 text-shadow in IE9

The answer of crdunst is pretty neat and the best looking answer I've found but there's no explanation on how to use and the code is bigger than needed.

The only code you need:

#element {
    background-color: #cacbcf;
    text-shadow: 2px 2px 4px rgba(0,0,0, 0.5);
    filter: chroma(color=#cacbcf) progid:DXImageTransform.Microsoft.dropshadow(color=#60000000, offX=2, offY=2);
}

First you MUST specify a background-color - if your element should be transparent just copy the background-color of the parent or let it inherit. The color at the chroma-filter must match the background-color to fix those artifacts around the text (but here you must copy the color, you can't write inherit). Note that I haven't shortened the dropshadow-filter - it works but the shadows are then cut to the element dimensions (noticeable with big shadows; try to set the offsets to atleast 4).

TIP: If you want to use colors with transparency (alpha-channel) write in a #AARRGGBB notation, where AA stands for a hexadezimal value of the opacity - from 01 to FE, because FF and ironically also 00 means no transparency and is therefore useless.. ^^ Just go a little lower than in the rgba notation because the shadows aren't soft and the same alpha value would appear darker then. ;)

A nice snippet to convert the alpha value for IE (JavaScript, just paste into the console):

var number = 0.5; //alpha value from the rgba() notation
("0"+(Math.round(0.75 * number * 255).toString(16))).slice(-2);

ISSUES: The text/font behaves like an image after the shadow is applied; it gets pixelated and blurry after you zoom in... But that's IE's issue, not mine.

Live demo of the shadow here: http://jsfiddle.net/12khvfru/2/

How to create circular ProgressBar in android?

You can try this Circle Progress library

enter image description here

enter image description here

NB: please always use same width and height for progress views

DonutProgress:

 <com.github.lzyzsd.circleprogress.DonutProgress
        android:id="@+id/donut_progress"
        android:layout_marginLeft="50dp"
        android:layout_width="100dp"
        android:layout_height="100dp"
        custom:circle_progress="20"/>

CircleProgress:

  <com.github.lzyzsd.circleprogress.CircleProgress
        android:id="@+id/circle_progress"
        android:layout_marginLeft="50dp"
        android:layout_width="100dp"
        android:layout_height="100dp"
        custom:circle_progress="20"/>

ArcProgress:

<com.github.lzyzsd.circleprogress.ArcProgress
        android:id="@+id/arc_progress"
        android:background="#214193"
        android:layout_marginLeft="50dp"
        android:layout_width="100dp"
        android:layout_height="100dp"
        custom:arc_progress="55"
        custom:arc_bottom_text="MEMORY"/>

How can I remove a key and its value from an associative array?

Consider this array:

$arr = array("key1" => "value1", "key2" => "value2", "key3" => "value3", "key4" => "value4");
  • To remove an element using the array key:

    // To unset an element from array using Key:
    unset($arr["key2"]);
    var_dump($arr);
    // output: array(3) { ["key1"]=> string(6) "value1" ["key3"]=> string(6) "value3" ["key4"]=> string(6) "value4" }
    
  • To remove element by value:

    // remove an element by value:
    $arr = array_diff($arr, ["value1"]);
    var_dump($arr);
    // output: array(2) { ["key3"]=> string(6) "value3" ["key4"]=> string(6) "value4" } 
    

read more about array_diff: http://php.net/manual/en/function.array-diff.php

  • To remove an element by using index:

    array_splice($arr, 1, 1);
    var_dump($arr);
    // array(1) { ["key3"]=> string(6) "value3" } 
    

read more about array_splice: http://php.net/manual/en/function.array-splice.php

In Java 8 how do I transform a Map<K,V> to another Map<K,V> using a lambda?

Keep it Simple and use Java 8:-

 Map<String, AccountGroupMappingModel> mapAccountGroup=CustomerDAO.getAccountGroupMapping();
 Map<String, AccountGroupMappingModel> mapH2ToBydAccountGroups = 
              mapAccountGroup.entrySet().stream()
                         .collect(Collectors.toMap(e->e.getValue().getH2AccountGroup(),
                                                   e ->e.getValue())
                                  );

MySQL root password change

a common error i run into from time to time, is that i forget the -p option, so are you sure you used:

mysql -u root -p

Heroku + node.js error (Web process failed to bind to $PORT within 60 seconds of launch)

Edit package.json:

...
"engines": {
"node": "5.0.0",
"npm": "4.6.1"
},
...

and Server.js:

...
var port = process.env.PORT || 3000;
app.listen(port, "0.0.0.0", function() {
console.log("Listening on Port 3000");
});
...

Remove space above and below <p> tag HTML

<p> tags have built in padding and margin. You could create a CSS selector combined with some javascript for instances when your <p> is empty. Probably overkill, but it should do what you need it to do.

CSS example: .NoPaddingOrMargin {padding: 0px; margin:0px}

Getting value of HTML text input

See my jsFiddle here: http://jsfiddle.net/fuDBL/

Whenever you change the email field, the link is updated automatically. This requires a small amount of jQuery. So now your form will work as needed, but your link will be updated dynamically so that when someone clicks on it, it contains what they entered in the email field. You should validate the input on the receiving page.

$('input[name="email"]').change(function(){
  $('#regLink').attr('href')+$('input[name="email"]').val();
});

How to change the default collation of a table?

may need to change the SCHEMA not only table

ALTER SCHEMA `<database name>`  DEFAULT CHARACTER SET utf8mb4  DEFAULT COLLATE utf8mb4_unicode_ci (as Rich said - utf8mb4);

(mariaDB 10)

Error : getaddrinfo ENOTFOUND registry.npmjs.org registry.npmjs.org:443

npm config set registry https://registry.npmjs.org/

this is the only solution for me.

How do I assert my exception message with JUnit Test annotation?

I like the @Rule answer. However, if for some reason you don't want to use rules. There is a third option.

@Test (expected = RuntimeException.class)
public void myTestMethod()
{
   try
   {
      //Run exception throwing operation here
   }
   catch(RuntimeException re)
   {
      String message = "Employee ID is null";
      assertEquals(message, re.getMessage());
      throw re;
    }
    fail("Employee Id Null exception did not throw!");
  }

Change Row background color based on cell value DataTable

DataTables has functionality for this since v 1.10

https://datatables.net/reference/option/createdRow

Example:

$('#tid_css').DataTable({
  // ...
  "createdRow": function(row, data, dataIndex) {
    if (data["column_index"] == "column_value") {
      $(row).css("background-color", "Orange");
      $(row).addClass("warning");
    }
  },
  // ...
});

Join a list of items with different types as string in Python

Calling str(...) is the Pythonic way to convert something to a string.

You might want to consider why you want a list of strings. You could instead keep it as a list of integers and only convert the integers to strings when you need to display them. For example, if you have a list of integers then you can convert them one by one in a for-loop and join them with ,:

print(','.join(str(x) for x in list_of_ints))

How to put more than 1000 values into an Oracle IN clause

Where do you get the list of ids from in the first place? Since they are IDs in your database, did they come from some previous query?

When I have seen this in the past it has been because:-

  1. a reference table is missing and the correct way would be to add the new table, put an attribute on that table and join to it
  2. a list of ids is extracted from the database, and then used in a subsequent SQL statement (perhaps later or on another server or whatever). In this case, the answer is to never extract it from the database. Either store in a temporary table or just write one query.

I think there may be better ways to rework this code that just getting this SQL statement to work. If you provide more details you might get some ideas.

Contains case insensitive

Another options is to use the search method as follow:

if (referrer.search(new RegExp("Ral", "i")) == -1) { ...

It looks more elegant then converting the whole string to lower case and it may be more efficient.
With toLowerCase() the code have two pass over the string, one pass is on the entire string to convert it to lower case and another is to look for the desired index.
With RegExp the code have one pass over the string which it looks to match the desired index.

Therefore, on long strings I recommend to use the RegExp version (I guess that on short strings this efficiency comes on the account of creating the RegExp object though)

How to insert multiple rows from array using CodeIgniter framework?

$query= array(); 
foreach( $your_data as $row ) {
    $query[] = '("'.mysql_real_escape_string($row['text']).'", '.$row['category_id'].')';
}
mysql_query('INSERT INTO table (text, category) VALUES '.implode(',', $query));

How do I clear this setInterval inside a function?

// Initiate set interval and assign it to intervalListener
var intervalListener = self.setInterval(function () {someProcess()}, 1000);
function someProcess() {
  console.log('someProcess() has been called');
  // If some condition is true clear the interval
  if (stopIntervalIsTrue) {
    window.clearInterval(intervalListener);
  }
}

Formatting floats in a numpy array

In order to make numpy display float arrays in an arbitrary format, you can define a custom function that takes a float value as its input and returns a formatted string:

In [1]: float_formatter = "{:.2f}".format

The f here means fixed-point format (not 'scientific'), and the .2 means two decimal places (you can read more about string formatting here).

Let's test it out with a float value:

In [2]: float_formatter(1.234567E3)
Out[2]: '1234.57'

To make numpy print all float arrays this way, you can pass the formatter= argument to np.set_printoptions:

In [3]: np.set_printoptions(formatter={'float_kind':float_formatter})

Now numpy will print all float arrays this way:

In [4]: np.random.randn(5) * 10
Out[4]: array([5.25, 3.91, 0.04, -1.53, 6.68]

Note that this only affects numpy arrays, not scalars:

In [5]: np.pi
Out[5]: 3.141592653589793

It also won't affect non-floats, complex floats etc - you will need to define separate formatters for other scalar types.

You should also be aware that this only affects how numpy displays float values - the actual values that will be used in computations will retain their original precision.

For example:

In [6]: a = np.array([1E-9])

In [7]: a
Out[7]: array([0.00])

In [8]: a == 0
Out[8]: array([False], dtype=bool)

numpy prints a as if it were equal to 0, but it is not - it still equals 1E-9.

If you actually want to round the values in your array in a way that affects how they will be used in calculations, you should use np.round, as others have already pointed out.

How do I generate sourcemaps when using babel and webpack?

Maybe someone else has this problem at one point. If you use the UglifyJsPlugin in webpack 2 you need to explicitly specify the sourceMap flag. For example:

new webpack.optimize.UglifyJsPlugin({ sourceMap: true })

How can I stop a running MySQL query?

Connect to mysql

mysql -uusername -p  -hhostname

show full processlist:

mysql> show full processlist;
+---------+--------+-------------------+---------+---------+------+-------+------------------+
| Id      | User   | Host              | db      | Command | Time | State | Info             |
+---------+--------+-------------------+---------+---------+------+-------+------------------+
| 9255451 | logreg | dmin001.ops:37651 | logdata | Query   |    0 | NULL  | show processlist |
+---------+--------+-------------------+---------+---------+------+-------+------------------+

Kill the specific query. Here id=9255451

mysql> kill 9255451;

If you get permission denied, try this SQL:

CALL mysql.rds_kill(9255451)