Programs & Examples On #Code contracts

Code Contracts is a Microsoft open source project which allows you to express pre-conditions, post-conditions, and assertions directly in code.

How to change JDK version for an Eclipse project

If you are using maven build tool then add the below properties to it and doing a maven update will solve the problem

<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

'Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format'

This should be called a warning, not an error. At least the email says that the icon file is "recommended" and not "required". You can safely ignore this warning if you target iOS 6. Of course, for iOS 7 you would need the new dimensions and also look out for the new rounding of the icon's corners

Passing arguments to JavaScript function from code-behind

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Call java script function on Code behind</title>
    <script  type="text/javascript">
    function abc()
    {
        var a=20;
        var b=30;
        alert("you enter"+a+":"+b);
    }
    </script>
</head>

cs code

protected void Page_Load(object sender, EventArgs e)
{
    TextBox2.Attributes.Add("onkeypress", "return abc();");
}

try this

Browser back button handling

You can also add hash when page is loading:

location.hash = "noBack";

Then just handle location hash change to add another hash:

$(window).on('hashchange', function() {
    location.hash = "noBack";
});

That makes hash always present and back button tries to remove hash at first. Hash is then added again by "hashchange" handler - so page would never actually can be changed to previous one.

Reliable way for a Bash script to get the full path to itself

As realpath is not installed per default on my Linux system, the following works for me:

SCRIPT="$(readlink --canonicalize-existing "$0")"
SCRIPTPATH="$(dirname "$SCRIPT")"

$SCRIPT will contain the real file path to the script and $SCRIPTPATH the real path of the directory containing the script.

Before using this read the comments of this answer.

How to update a git clone --mirror?

See here: Git doesn't clone all branches on subsequent clones?

If you really want this by pulling branches instead of push --mirror, you can have a look here:

"fetch --all" in a git bare repository doesn't synchronize local branches to the remote ones

This answer provides detailed steps on how to achieve that relatively easily:

How do you get a directory listing in C?

I've created an open source (BSD) C header that deals with this problem. It currently supports POSIX and Windows. Please check it out:

https://github.com/cxong/tinydir

tinydir_dir dir;
tinydir_open(&dir, "/path/to/dir");

while (dir.has_next)
{
    tinydir_file file;
    tinydir_readfile(&dir, &file);

    printf("%s", file.name);
    if (file.is_dir)
    {
        printf("/");
    }
    printf("\n");

    tinydir_next(&dir);
}

tinydir_close(&dir);

Add JsonArray to JsonObject

Just try below a simple solution:

JsonObject body=new JsonObject();
body.add("orders", (JsonElement) orders);

whenever my JSON request is like:

{
      "role": "RT",
      "orders": [
        {
          "order_id": "ORDER201908aPq9Gs",
          "cart_id": 164444,
          "affiliate_id": 0,
          "orm_order_status": 9,
          "status_comments": "IC DUE - Auto moved to Instruction Call Due after 48hrs",
          "status_date": "2020-04-15",
        }
      ]
    }

How to print without newline or space?

In Python 3, you can use the sep= and end= parameters of the print function:

To not add a newline to the end of the string:

print('.', end='')

To not add a space between all the function arguments you want to print:

print('a', 'b', 'c', sep='')

You can pass any string to either parameter, and you can use both parameters at the same time.

If you are having trouble with buffering, you can flush the output by adding flush=True keyword argument:

print('.', end='', flush=True)

Python 2.6 and 2.7

From Python 2.6 you can either import the print function from Python 3 using the __future__ module:

from __future__ import print_function

which allows you to use the Python 3 solution above.

However, note that the flush keyword is not available in the version of the print function imported from __future__ in Python 2; it only works in Python 3, more specifically 3.3 and later. In earlier versions you'll still need to flush manually with a call to sys.stdout.flush(). You'll also have to rewrite all other print statements in the file where you do this import.

Or you can use sys.stdout.write()

import sys
sys.stdout.write('.')

You may also need to call

sys.stdout.flush()

to ensure stdout is flushed immediately.

The difference in months between dates in MySQL

I prefer this way, because evryone will understand it clearly at the first glance:

SELECT
    12 * (YEAR(to) - YEAR(from)) + (MONTH(to) - MONTH(from)) AS months
FROM
    tab;

create table with sequence.nextval in oracle

In Oracle 12c you can also declare an identity column

CREATE TABLE identity_test_tab (
  id          NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY,
  description VARCHAR2(30)
);

examples & performance tests here ... where, is shorts, the conclusion is that the direct use of the sequence or the new identity column are much faster than the triggers.

Creating a selector from a method name with parameters

Beyond what's been said already about selectors, you may want to look at the NSInvocation class.

An NSInvocation is an Objective-C message rendered static, that is, it is an action turned into an object. NSInvocation objects are used to store and forward messages between objects and between applications, primarily by NSTimer objects and the distributed objects system.

An NSInvocation object contains all the elements of an Objective-C message: a target, a selector, arguments, and the return value. Each of these elements can be set directly, and the return value is set automatically when the NSInvocation object is dispatched.

Keep in mind that while it's useful in certain situations, you don't use NSInvocation in a normal day of coding. If you're just trying to get two objects to talk to each other, consider defining an informal or formal delegate protocol, or passing a selector and target object as has already been mentioned.

MySQL error code: 1175 during UPDATE in MySQL Workbench

just type SET SQL_SAFE_UPDATES = 0; before the delete or update and set to 1 again SET SQL_SAFE_UPDATES = 1

How to find which version of TensorFlow is installed in my system?

The tensorflow version can be checked either on terminal or console or in any IDE editer as well (like Spyder or Jupyter notebook, etc)

Simple command to check version:

(py36) C:\WINDOWS\system32>python
Python 3.6.8 |Anaconda custom (64-bit)

>>> import tensorflow as tf
>>> tf.__version__
'1.13.1'

How to always show the vertical scrollbar in a browser?

jQuery shouldn't be required. You could try adding the CSS:

body    {overflow-y:scroll;}

This works across the latest browsers, even IE6.

How to Populate a DataTable from a Stored Procedure

Use an SqlDataAdapter instead, it's much easier and you don't need to define the column names yourself, it will get the column names from the query results:

using (SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString))
{
    using (SqlCommand cmd = new SqlCommand("usp_GetABCD", sqlcon))
    {
        cmd.CommandType = CommandType.StoredProcedure;

        using (SqlDataAdapter da = new SqlDataAdapter(cmd))
        {
            DataTable dt = new DataTable();

            da.Fill(dt);
        }
    }
}

How to force a web browser NOT to cache images

I made a PHP script that automatically adds the timestamps for all images in the HTML page. You just need to include this script in your pages. Enjoy!

http://alv90.altervista.org/how-to-force-the-browser-not-to-cache-images/

MySQL "Or" Condition

Wrap your AND logic in parenthesis, like this:

mysql_query("SELECT * FROM Drinks WHERE email='$Email' AND (date='$Date_Today' OR date='$Date_Yesterday' OR date='$Date_TwoDaysAgo' OR date='$Date_ThreeDaysAgo' OR date='$Date_FourDaysAgo' OR date='$Date_FiveDaysAgo' OR date='$Date_SixDaysAgo' OR date='$Date_SevenDaysAgo')");

How to properly reference local resources in HTML?

  • A leading slash tells the browser to start at the root directory.
  • If you don't have the leading slash, you're referencing from the current directory.
  • If you add two dots before the leading slash, it means you're referencing the parent of the current directory.

Take the following folder structure

demo folder structure

notice:

  • the ROOT checkmark is green,
  • the second checkmark is orange,
  • the third checkmark is purple,
  • the forth checkmark is yellow

Now in the index.html.en file you'll want to put the following markup

<p>
    <span>src="check_mark.png"</span>
    <img src="check_mark.png" />
    <span>I'm purple because I'm referenced from this current directory</span>
</p>

<p>
    <span>src="/check_mark.png"</span>
    <img src="/check_mark.png" />
    <span>I'm green because I'm referenced from the ROOT directory</span>
</p>

<p>
    <span>src="subfolder/check_mark.png"</span>
    <img src="subfolder/check_mark.png" />
    <span>I'm yellow because I'm referenced from the child of this current directory</span>
</p>

<p>
    <span>src="/subfolder/check_mark.png"</span>
    <img src="/subfolder/check_mark.png" />
    <span>I'm orange because I'm referenced from the child of the ROOT directory</span>
</p>

<p>
    <span>src="../subfolder/check_mark.png"</span>
    <img src="../subfolder/check_mark.png" />
    <span>I'm purple because I'm referenced from the parent of this current directory</span>
</p>

<p>
    <span>src="subfolder/subfolder/check_mark.png"</span>
    <img src="subfolder/subfolder/check_mark.png" />
    <span>I'm [broken] because there is no subfolder two children down from this current directory</span>
</p>

<p>
    <span>src="/subfolder/subfolder/check_mark.png"</span>
    <img src="/subfolder/subfolder/check_mark.png" />
    <span>I'm purple because I'm referenced two children down from the ROOT directory</span>
</p>

Now if you load up the index.html.en file located in the second subfolder
http://example.com/subfolder/subfolder/

This will be your output

enter image description here

Fit cell width to content

Setting

max-width:100%;
white-space:nowrap;

will solve your problem.

JavaScript: Create and save file

A very minor improvement of the code by Awesomeness01 (no need for anchor tag) with addition as suggested by trueimage (support for IE):

// Function to download data to a file
function download(data, filename, type) {
    var file = new Blob([data], {type: type});
    if (window.navigator.msSaveOrOpenBlob) // IE10+
        window.navigator.msSaveOrOpenBlob(file, filename);
    else { // Others
        var a = document.createElement("a"),
                url = URL.createObjectURL(file);
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        setTimeout(function() {
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);  
        }, 0); 
    }
}

Tested to be working properly in Chrome, FireFox and IE10.

In Safari, the data gets opened in a new tab and one would have to manually save this file.

Styling input radio with css

Like this

DEMO

CSS

#slideselector {
    position: absolue;
    top:0;
    left:0;
    border: 2px solid black;
    padding-top: 1px;
}
.slidebutton {
    height: 21px;
    margin: 2px;
}
#slideshow { 
    margin: 50px auto; 
    position: relative; 
    width: 240px; 
    height: 240px; 
    padding: 10px; 
    box-shadow: 0 0 20px rgba(0,0,0,0.4); 
}

#slideshow > div { 
    position: absolute; 
    top: 10px; 
    left: 10px; 
    right: 10px; 
    bottom: 10px;
    overflow:hidden;
}

.imgLike {
    width:100%;
    height:100%;
}
/* Radio */

input[type="radio"] {
    background-color: #ddd;
    background-image: -webkit-linear-gradient(0deg, transparent 20%, hsla(0,0%,100%,.7), transparent 80%),
                      -webkit-linear-gradient(90deg, transparent 20%, hsla(0,0%,100%,.7), transparent 80%);
    border-radius: 10px;
    box-shadow: inset 0 1px 1px hsla(0,0%,100%,.8),
                0 0 0 1px hsla(0,0%,0%,.6),
                0 2px 3px hsla(0,0%,0%,.6),
                0 4px 3px hsla(0,0%,0%,.4),
                0 6px 6px hsla(0,0%,0%,.2),
                0 10px 6px hsla(0,0%,0%,.2);
    cursor: pointer;
    display: inline-block;
    height: 15px;
    margin-right: 15px;
    position: relative;
    width: 15px;
    -webkit-appearance: none;
}
input[type="radio"]:after {
    background-color: #444;
    border-radius: 25px;
    box-shadow: inset 0 0 0 1px hsla(0,0%,0%,.4),
                0 1px 1px hsla(0,0%,100%,.8);
    content: '';
    display: block;
    height: 7px;
    left: 4px;
    position: relative;
    top: 4px;
    width: 7px;
}
input[type="radio"]:checked:after {
    background-color: #f66;
    box-shadow: inset 0 0 0 1px hsla(0,0%,0%,.4),
                inset 0 2px 2px hsla(0,0%,100%,.4),
                0 1px 1px hsla(0,0%,100%,.8),
                0 0 2px 2px hsla(0,70%,70%,.4);
}

SQL Server Operating system error 5: "5(Access is denied.)"

The problem is due to lack of permissions for SQL Server to access the mdf & ldf files. All these procedures will work :

  1. you can directly change the MSSQLSERVER service startup user account, with the user account who have better privileges on the files. Then try to attach the database.
  2. Or you can assign the user to the file in security tab of the mdf & ldf files properties with read and and write privileges checked.
  3. Startup with windows administrator account, and open SQL Server with run as administrator option and try to login with windows authentication and now try to attach the database.

Turning off eslint rule for a specific file

Simple and effective.

Eslint 6.7.0 brought "ignorePatterns" to write it in .eslintrc.json like this example:

{
    "ignorePatterns": ["fileToBeIgnored.js"],
    "rules": {
        //...
    }
}

See docs

What is the `data-target` attribute in Bootstrap 3?

data-target is used by bootstrap to make your life easier. You (mostly) do not need to write a single line of Javascript to use their pre-made JavaScript components.

The data-target attribute should contain a CSS selector that points to the HTML Element that will be changed.

Modal Example Code from BS3:

<!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  [...]
</div>

In this example, the button has data-target="#myModal", if you click on it, <div id="myModal">...</div> will be modified (in this case faded in). This happens because #myModal in CSS selectors points to elements that have an id attribute with the myModal value.

Further information about the HTML5 "data-" attribute: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes

How to check if a json key exists?

I am just adding another thing, In case you just want to check whether anything is created in JSONObject or not you can use length(), because by default when JSONObject is initialized and no key is inserted, it just has empty braces {} and using has(String key) doesn't make any sense.

So you can directly write if (jsonObject.length() > 0) and do your things.

Happy learning!

Swift alert view with OK and Cancel: which button tapped?

You can easily do this by using UIAlertController

let alertController = UIAlertController(
       title: "Your title", message: "Your message", preferredStyle: .alert)
let defaultAction = UIAlertAction(
       title: "Close Alert", style: .default, handler: nil)
//you can add custom actions as well 
alertController.addAction(defaultAction)

present(alertController, animated: true, completion: nil)

.

Reference: iOS Show Alert

How to decompile to java files intellij idea

I use JD-GUI for extract all decompiled java classes to java files.

How can I split a text into sentences?

Here is a middle of the road approach that doesn't rely on any external libraries. I use list comprehension to exclude overlaps between abbreviations and terminators as well as to exclude overlaps between variations on terminations, for example: '.' vs. '."'

abbreviations = {'dr.': 'doctor', 'mr.': 'mister', 'bro.': 'brother', 'bro': 'brother', 'mrs.': 'mistress', 'ms.': 'miss', 'jr.': 'junior', 'sr.': 'senior',
                 'i.e.': 'for example', 'e.g.': 'for example', 'vs.': 'versus'}
terminators = ['.', '!', '?']
wrappers = ['"', "'", ')', ']', '}']


def find_sentences(paragraph):
   end = True
   sentences = []
   while end > -1:
       end = find_sentence_end(paragraph)
       if end > -1:
           sentences.append(paragraph[end:].strip())
           paragraph = paragraph[:end]
   sentences.append(paragraph)
   sentences.reverse()
   return sentences


def find_sentence_end(paragraph):
    [possible_endings, contraction_locations] = [[], []]
    contractions = abbreviations.keys()
    sentence_terminators = terminators + [terminator + wrapper for wrapper in wrappers for terminator in terminators]
    for sentence_terminator in sentence_terminators:
        t_indices = list(find_all(paragraph, sentence_terminator))
        possible_endings.extend(([] if not len(t_indices) else [[i, len(sentence_terminator)] for i in t_indices]))
    for contraction in contractions:
        c_indices = list(find_all(paragraph, contraction))
        contraction_locations.extend(([] if not len(c_indices) else [i + len(contraction) for i in c_indices]))
    possible_endings = [pe for pe in possible_endings if pe[0] + pe[1] not in contraction_locations]
    if len(paragraph) in [pe[0] + pe[1] for pe in possible_endings]:
        max_end_start = max([pe[0] for pe in possible_endings])
        possible_endings = [pe for pe in possible_endings if pe[0] != max_end_start]
    possible_endings = [pe[0] + pe[1] for pe in possible_endings if sum(pe) > len(paragraph) or (sum(pe) < len(paragraph) and paragraph[sum(pe)] == ' ')]
    end = (-1 if not len(possible_endings) else max(possible_endings))
    return end


def find_all(a_str, sub):
    start = 0
    while True:
        start = a_str.find(sub, start)
        if start == -1:
            return
        yield start
        start += len(sub)

I used Karl's find_all function from this entry: Find all occurrences of a substring in Python

How do I remove a single file from the staging area (undo git add)?

For newer versions of Git there is git restore --staged <file>.

When I do a git status with Git version 2.26.2.windows.1 it is also recommended for unstaging:

Changes to be committed:
  (use "git restore --staged <file>..." to unstage)

(This post shows, that in earlier versions git reset HEAD was recommended at this point)

I can highly recommend this post explaining the differences between git revert, git restore and git reset and also additional parameters for git restore.

How to get all of the IDs with jQuery?

Not a real array, but objs are all associative arrays in javascript.

I chose not to use a real array with [] and [].push because technically, you can have multiple ID's on a page even though that is incorrect to do so. So just another option in case some html has duplicated ID's

$(function() {

       var oArr = {};
       $("*[id]").each(function() {
           var id = $(this).attr('id');
           if (!oArr[id]) oArr[id] = true;
       });

       for (var prop in oArr)
           alert(prop);

   });

How to create custom button in Android using XML Styles

<gradient android:startColor="#ffdd00"
    android:endColor="@color/colorPrimary"
    android:centerColor="#ffff" />

<corners android:radius="33dp"/>

<padding
    android:bottom="7dp"
    android:left="7dp"
    android:right="7dp"
    android:top="7dp"
    />

Difference between SET autocommit=1 and START TRANSACTION in mysql (Have I missed something?)

In InnoDB you have START TRANSACTION;, which in this engine is the officialy recommended way to do transactions, instead of SET AUTOCOMMIT = 0; (don't use SET AUTOCOMMIT = 0; for transactions in InnoDB unless it is for optimizing read only transactions). Commit with COMMIT;.

You might want to use SET AUTOCOMMIT = 0; in InnoDB for testing purposes, and not precisely for transactions.

In MyISAM you do not have START TRANSACTION;. In this engine, use SET AUTOCOMMIT = 0; for transactions. Commit with COMMIT; or SET AUTOCOMMIT = 1; (Difference explained in MyISAM example commentary below). You can do transactions this way in InnoDB too.

Source: http://dev.mysql.com/doc/refman/5.6/en/glossary.html#glos_autocommit

Examples of general use transactions:

/* InnoDB */
START TRANSACTION;

INSERT INTO table_name (table_field) VALUES ('foo');
INSERT INTO table_name (table_field) VALUES ('bar');

COMMIT; /* SET AUTOCOMMIT = 1 might not set AUTOCOMMIT to its previous state */

/* MyISAM */
SET AUTOCOMMIT = 0;

INSERT INTO table_name (table_field) VALUES ('foo');
INSERT INTO table_name (table_field) VALUES ('bar');

SET AUTOCOMMIT = 1; /* COMMIT statement instead would not restore AUTOCOMMIT to 1 */

How can I convert a hex string to a byte array?

I think this may work.

public static byte[] StrToByteArray(string str)
    {
        Dictionary<string, byte> hexindex = new Dictionary<string, byte>();
        for (int i = 0; i <= 255; i++)
            hexindex.Add(i.ToString("X2"), (byte)i);

        List<byte> hexres = new List<byte>();
        for (int i = 0; i < str.Length; i += 2)            
            hexres.Add(hexindex[str.Substring(i, 2)]);

        return hexres.ToArray();
    }

int *array = new int[n]; what is this function actually doing?

As of C++11, the memory-safe way to do this (still using a similar construction) is with std::unique_ptr:

std::unique_ptr<int[]> array(new int[n]);

This creates a smart pointer to a memory block large enough for n integers that automatically deletes itself when it goes out of scope. This automatic clean-up is important because it avoids the scenario where your code quits early and never reaches your delete [] array; statement.

Another (probably preferred) option would be to use std::vector if you need an array capable of dynamic resizing. This is good when you need an unknown amount of space, but it has some disadvantages (non-constant time to add/delete an element). You could create an array and add elements to it with something like:

std::vector<int> array;
array.push_back(1);  // adds 1 to end of array
array.push_back(2);  // adds 2 to end of array
// array now contains elements [1, 2]

JS: Uncaught TypeError: object is not a function (onclick)

I was able to figure it out by following the answer in this thread: https://stackoverflow.com/a/8968495/1543447

Basically, I renamed all values, function names, and element names to different values so they wouldn't conflict - and it worked!

Tkinter: "Python may not be configured for Tk"

According to http://wiki.python.org/moin/TkInter :

If it fails with "No module named _tkinter", your Python configuration needs to be modified to include this module (which is an extension module implemented in C). Do not edit Modules/Setup (it is out of date). You may have to install Tcl and Tk (when using RPM, install the -devel RPMs as well) and/or edit the setup.py script to point to the right locations where Tcl/Tk is installed. If you install Tcl/Tk in the default locations, simply rerunning "make" should build the _tkinter extension.

com.jcraft.jsch.JSchException: UnknownHostKey

I would either:

  1. Try to ssh from the command line and accept the public key (the host will be added to ~/.ssh/known_hosts and everything should then work fine from Jsch) -OR-
  2. Configure JSch to not use "StrictHostKeyChecking" (this introduces insecurities and should only be used for testing purposes), using the following code:

    java.util.Properties config = new java.util.Properties(); 
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    

Option #1 (adding the host to the ~/.ssh/known_hosts file) has my preference.

How do I link object files in C? Fails with "Undefined symbols for architecture x86_64"

The existing answers already cover the "how", but I just wanted to elaborate on the "what" and "why" for others who might be wondering.

What a compiler (gcc) does: The term "compile" is a bit of an overloaded term because it is used at a high-level to mean "convert source code to a program", but more technically means to "convert source code to object code". A compiler like gcc actually performs two related, but arguably distinct functions to turn your source code into a program: compiling (as in the latter definition of turning source to object code) and linking (the process of combining the necessary object code files together into one complete executable).

The original error that you saw is technically a "linking error", and is thrown by "ld", the linker. Unlike (strict) compile-time errors, there is no reference to source code lines, as the linker is already in object space.

By default, when gcc is given source code as input, it attempts to compile each and then link them all together. As noted in the other responses, it's possible to use flags to instruct gcc to just compile first, then use the object files later to link in a separate step. This two-step process may seem unnecessary (and probably is for very small programs) but it is very important when managing a very large program, where compiling the entire project each time you make a small change would waste a considerable amount of time.

DateTime format to SQL format using C#

try this below

DateTime myDateTime = DateTime.Now;
string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss.fff");

XXHDPI and XXXHDPI dimensions in dp for images and icons in android

You can use a vector. Instead of worry about different screen sizes you only need to create an .svg file and import it to your project using Vector Asset Studio.

How do I count occurrence of duplicate items in array

I came here from google looking for a way to count the occurence of duplicate items in an array. Here is the way to do it simply:

$colors = array("red", "green", "blue", "red", "yellow", "blue");
$unique_colors = array_unique($colors);
// $unique colors : array("red", "green", "blue", "yellow")
$duplicates = count($colors) - count($unique_colors);
// $duplicates = 6 - 4 = 2
if( $duplicates == 0 ){
 echo "There are no duplicates";
}
echo "No. of Duplicates are :" . $duplicates;

// Output: No. of Duplicates are: 2

How array_unique() works?

It elements all the duplicates. ex: Lets say we have an array as follows -

$cars = array( [0]=>"lambo", [1]=>"ferrari", [2]=>"Lotus", [3]=>"ferrari", [4]=>"Bugatti");

When you do $cars = array_unique($cars); cars will have only following elements. $cars = array( [0]=>"lambo", [1]=>"ferrari", [2]=>"Lotus", [4]=>"Bugatti");

To read more: https://www.w3schools.com/php/func_array_unique.asp

Hope it is helpful to those who are coming here from google looking for a way to count duplicate values in array.

Access an arbitrary element in a dictionary in Python

How about, this. Not mentioned here yet.

py 2 & 3

a = {"a":2,"b":3}
a[list(a)[0]] # the first element is here
>>> 2

Convert decimal to hexadecimal in UNIX shell script

echo "obase=16; 34" | bc

If you want to filter a whole file of integers, one per line:

( echo "obase=16" ; cat file_of_integers ) | bc

how to open a page in new tab on button click in asp.net?

try this rather than redirect...

Response.Write("<script>");
Response.Write("window.open('ClickPicture.aspx','_blank')");
Response.Write("</script>");

How to use template module with different set of variables?

- name: copy vhosts
  template: src=site-vhost.conf dest=/etc/apache2/sites-enabled/{{ item }}.conf
  with_items:
    - somehost.local
    - otherhost.local
  notify: restart apache

IMPORTANT: Note that an item does not have to be just a string, it can be an object with as many properties as you like, so that way you can pass any number of variables.

In the template I have:

<VirtualHost *:80>
    ServerAdmin [email protected]
    ServerName {{ item }}
    DocumentRoot /vagrant/public


    ErrorLog ${APACHE_LOG_DIR}/error-{{ item }}.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

php execute a background process

I know it is a 100 year old post, but anyway, thought it might be useful to someone. You can put an invisible image somewhere on the page pointing to the url that needs to run in the background, like this:

<img src="run-in-background.php" border="0" alt="" width="1" height="1" />

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

Instead of making the control public, you can create a property that controls its visibility:

public bool ControlIsVisible
{
     get { return control.Visible; }
     set { control.Visible = value; }
}

This creates a proper accessor to that control that won't expose the control's whole set of properties.

How to elegantly check if a number is within a range?

EDIT: New Answer provided. I was just starting out using C# when I wrote the first answer to this question, and in hindsight I now realize that my "solution" was / is naive and inefficient.

My original answer: I'd go with the more simple version:

if(Enumerable.Range(1,100).Contains(intInQuestion)) { ...DoStuff; }

A Better Way

As I haven't seen any other solution that is more efficient (according to my tests at least), I'll give it another go.

New and better way that also works with negative ranges:

// Returns true if x is in range [min..max], else false 
bool inRange(int x, int min=1, int max=100) => ((x - max)*(x - min) <= 0);

This can be used with both positive and negative ranges and defaults to a range of

1..100 (inclusive) and uses x as the number to check followed by an optional range defined by min and max.

Adding Examples For Good Measure

Example 1:

// Returns true if x is in range [min..max], else false 
bool inRange(int x, int min=1, int max=100) => ((x - max)*(x - min) <= 0);

Console.WriteLine(inRange(25));
Console.WriteLine(inRange(1));
Console.WriteLine(inRange(100));
Console.WriteLine(inRange(25, 30, 150));
Console.WriteLine(inRange(-25, -50, 0));

Returns:

True
True
True
False
True

Example 2: Using a list of random ints between 1 and 150

// Returns true if x is in range [min..max], else false 
bool inRange(int x, int min=1, int max=100) => ((x - max)*(x - min) <= 0);

// Generate 100000 ints between 1 and 150
var intsToCheck = new List<int>();
var randGen = new Random();
for(int i = 0; i < 100000; ++i){
    intsToCheck.Add(randGen.Next(150) + 1);
}

var counter = 0;
foreach(int n in intsToCheck) {
    if(inRange(n)) ++counter;
}

Console.WriteLine("{0} ints found in range 1..100", counter);

Returns:

66660 ints found in range 1..100

Execution Time: 0.016 second(s)

How do I fix the npm UNMET PEER DEPENDENCY warning?

In my case all the dependencies were already there. Please update NPM in that case as it might have been crashed. It solved my problem.

npm install -g npm

C# "No suitable method found to override." -- but there is one

I do not see the class Ext being derived from Base.

How can I keep my branch up to date with master with git?

Assuming you're fine with taking all of the changes in master, what you want is:

git checkout <my branch>

to switch the working tree to your branch; then:

git merge master

to merge all the changes in master with yours.

How to write a UTF-8 file with Java?

All of the answers given here wont work since java's UTF-8 writing is bugged.

http://tripoverit.blogspot.com/2007/04/javas-utf-8-and-unicode-writing-is.html

Writing MemoryStream to Response Object

I had the same issue. try this: copy to MemoryStream -> delete file -> download.

string absolutePath = "~/your path";
try {
    //copy to MemoryStream
    MemoryStream ms = new MemoryStream();
    using (FileStream fs = File.OpenRead(Server.MapPath(absolutePath))) 
    { 
        fs.CopyTo(ms); 
    }

    //Delete file
    if(File.Exists(Server.MapPath(absolutePath)))
       File.Delete(Server.MapPath(absolutePath))

    //Download file
    Response.Clear()
    Response.ContentType = "image/jpg";
    Response.AddHeader("Content-Disposition", "attachment;filename=\"" + absolutePath + "\"");
    Response.BinaryWrite(ms.ToArray())
}
catch {}

Response.End();

Is there a way to create key-value pairs in Bash script?

In bash, we use

declare -A name_of_dictonary_variable

so that Bash understands it is a dictionary.

For e.g. you want to create sounds dictionary then,

declare -A sounds

sounds[dog]="Bark"

sounds[wolf]="Howl"

where dog and wolf are "keys", and Bark and Howl are "values".

You can access all values using : echo ${sounds[@]} OR echo ${sounds[*]}

You can access all keys only using: echo ${!sounds[@]}

And if you want any value for a particular key, you can use:

${sounds[dog]}

this will give you value (Bark) for key (Dog).

Django error - matching query does not exist

Maybe you have no Comments record with such primary key, then you should use this code:

try:
    comment = Comment.objects.get(pk=comment_id)
except Comment.DoesNotExist:
    comment = None

How to pass a user / password in ansible command

I used the command

ansible -i inventory example -m ping -u <your_user_name> --ask-pass

And it will ask for your password.

For anyone who gets the error:

to use the 'ssh' connection type with passwords, you must install the sshpass program

On MacOS, you can follow below instructions to install sshpass:

  1. Download the Source Code
  2. Extract it and cd into the directory
  3. ./configure
  4. sudo make install

Create stacked barplot where each stack is scaled to sum to 100%

Chris Beeley is rigth, you only need the proportions by column. Using your data is:

 your_matrix<-( 
               rbind(
                       c(23,234,324), 
                       c(34,534,12), 
                       c(56,324,124), 
                       c(34,234,124),
                       c(123,534,654)
                    )
                )

 barplot(prop.table(your_matrix, 2) )

Gives:

enter image description here

Getting Http Status code number (200, 301, 404, etc.) from HttpWebRequest and HttpWebResponse

Just coerce the StatusCode to int.

var statusNumber;
try {
   response = (HttpWebResponse)request.GetResponse();
   // This will have statii from 200 to 30x
   statusNumber = (int)response.StatusCode;
}
catch (WebException we) {
    // Statii 400 to 50x will be here
    statusNumber = (int)we.Response.StatusCode;
}

Android device does not show up in adb list

I tried everything on this thread but nothing worked. My problem: my computer was charging the device when I was connecting the cable on, so I assumed the cable was working, but not. After I swap the cable, adb devices worked. The cable was the issue.

Why do I have to define LD_LIBRARY_PATH with an export every time I run my application?

What you also can do, if it's something you installed on your system, is to add the directory that contains the shared libraries to your /etc/ld.so.conf file, or make a new file in /etc/ld.so.conf.d/

(I've both checked RHEL5 and Ubuntu distribution so I think it's generic for linux)

The ldconfig program will make sure they are system-wide included.

See the following link for more information: www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/dlls.html

How to get Java Decompiler / JD / JD-Eclipse running in Eclipse Helios

  1. Download the JD-Eclipse Update Site(github.com/java-decompiler/jd-eclipse)
  2. Launch Eclipse,

  3. Click on "Help > Install New Software...",

  4. Click on button "Add..." to add an new repository,

  5. Enter "JD-Eclipse Update Site" and select the local site directory,

  6. Check "Java Decompiler Eclipse Plug-in",

  7. Next, next, next... and restart Eclipse.

img src SVG changing the styles with CSS

This might be helpful for people using PHP in combination with .svg images that they want to manipulate with CSS.

You can't overwrite properties inside a img tag with CSS. But when the svg source code is embedded in the HTML you surely can. I like to resolve this issue with a require_once function where I include a .svg.php file. It's like importing an image but you can still overwrite styles with CSS!

First include the svg file:

<?php require_once( '/assets/images/my-icon.svg.php' ); ?>

And it includes this icon for example:

<svg xmlns="http://www.w3.org/2000/svg" width="20.666" height="59.084" viewBox="0 0 20.666 59.084"><g transform="translate(-639.749 -3139)"><path d="M648.536,3173.876c0-2.875-1.725-3.8-3.471-3.8-1.683,0-3.49.9-3.49,3.8,0,3,1.786,3.8,3.49,3.8C646.811,3177.676,648.536,3176.769,648.536,3173.876Zm-3.471,2.341c-.883,0-1.437-.513-1.437-2.341,0-1.971.615-2.381,1.437-2.381.862,0,1.438.349,1.438,2.381,0,1.907-.616,2.339-1.438,2.339Z" fill="#142312"/><path d="M653.471,3170.076a1.565,1.565,0,0,0-1.416.9l-6.558,13.888h1.2a1.565,1.565,0,0,0,1.416-.9l6.559-13.887Z" fill="#142312"/><path d="M655.107,3177.263c-1.684,0-3.471.9-3.471,3.8,0,3,1.766,3.8,3.471,3.8,1.745,0,3.49-.9,3.49-3.8C658.6,3178.186,656.851,3177.263,655.107,3177.263Zm0,6.139c-.884,0-1.438-.514-1.438-2.34,0-1.972.617-2.381,1.438-2.381.862,0,1.437.349,1.437,2.381,0,1.909-.616,2.34-1.437,2.34Z" fill="#142312"/><path d="M656.263,3159.023l-1.49-14.063a1.35,1.35,0,0,0,.329-.293,1.319,1.319,0,0,0,.268-1.123l-.753-3.49a1.328,1.328,0,0,0-1.306-1.054h-6.448a1.336,1.336,0,0,0-1.311,1.068l-.71,3.493a1.344,1.344,0,0,0,.276,1.112,1.532,1.532,0,0,0,.283.262l-1.489,14.087c-1.7,1.727-4.153,4.871-4.153,8.638v28.924a1.339,1.339,0,0,0,1.168,1.49,1.357,1.357,0,0,0,.17.01h17.981a1.366,1.366,0,0,0,1.337-1.366v-29.059C660.414,3163.893,657.963,3160.749,656.263,3159.023Zm-8.307-17.349h4.274l.176.815H647.79Zm9.785,43.634v10.1H642.434v-17.253a4.728,4.728,0,0,1-2.028-4.284,4.661,4.661,0,0,1,2.028-4.215v-2c0-3.162,2.581-5.986,3.687-7.059a1.356,1.356,0,0,0,.4-.819l1.542-14.614H652.1l1.545,14.618a1.362,1.362,0,0,0,.4.819c1.109,1.072,3.688,3.9,3.688,7.059v9.153a5.457,5.457,0,0,1,0,8.5Z" fill="#142312"/></g></svg>

Now we can easily change the fill color like this with CSS:

svg path {
  fill: blue;
}

I first tried to solve this problem with file_get_contents() but the solution above is much faster.

Setting up Gradle for api 26 (Android)

Appart from setting maven source url to your gradle, I would suggest to add both design and appcompat libraries. Currently the latest version is 26.1.0

maven {
    url "https://maven.google.com"
}

...

compile 'com.android.support:appcompat-v7:26.1.0'
compile 'com.android.support:design:26.1.0'

Ajax post request in laravel 5 return error 500 (Internal Server Error)

I guess this has been solved by now but still the best thing to do here is to send the token with your form

{!! csrf_field() !!}

and then in your ajax

$("#try").click(function(){
var url = $(this).attr("data-link");
$.ajax({
    url: "test",
    type:"POST",
    data: { '_token': token, 'someOtherData': someOtherData },
    success:function(data){
        alert(data);
    },error:function(){ 
        alert("error!!!!");
    }
}); //end of ajax
});

Angular 4 HttpClient Query Parameters

search property of type URLSearchParams in RequestOptions class is deprecated in angular 4. Instead, you should use params property of type URLSearchParams.

How to make an executable JAR file?

It's too late to answer for this question. But if someone is searching for this answer now I've made it to run with no errors.

First of all make sure to download and add maven to path. [ mvn --version ] will give you version specifications of it if you have added to the path correctly.

Now , add following code to the maven project [ pom.xml ] , in the following code replace with your own main file entry point for eg [ com.example.test.Test ].

      <plugin>
            <!-- Build an executable JAR -->
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.4</version>
            <configuration>
                <archive>
                    <manifest>
                    <mainClass>
            your_package_to_class_that_contains_main_file .MainFileName</mainClass>
                    </manifest>
                </archive>
            </configuration>
        </plugin>

Now go to the command line [CMD] in your project and type mvn package and it will generate a jar file as something like ProjectName-0.0.1-SNAPSHOT.jar under target directory.

Now navigate to the target directory by cd target.

Finally type java -jar jar-file-name.jar and yes this should work successfully if you don't have any errors in your program.

Matching a space in regex

\040 matches exactly the space character.

Regexp PHP reference

New Link
Escape sequences for Regex PHP

Using request.setAttribute in a JSP page

i think phil is right request option is available till the page load. so if we want to sent value to another page we want to set the in the hidden tag or in side the session if you just need the value only on another page and not more than that then hidden tags are best option if you need that value on more than one page at that time session is the better option than hidden tags.

argparse module How to add option without any argument?

To create an option that needs no value, set the action [docs] of it to 'store_const', 'store_true' or 'store_false'.

Example:

parser.add_argument('-s', '--simulate', action='store_true')

Video streaming over websockets using JavaScript

Is WebSockets over TCP a fast enough protocol to stream a video of, say, 30fps?

Yes.. it is, take a look at this project. Websockets can easily handle HD videostreaming.. However, you should go for Adaptive Streaming. I explain here how you could implement it.

Currently we're working on a webbased instant messaging application with chat, filesharing and video/webcam support. With some bits and tricks we got streaming media through websockets (used HTML5 Media Capture to get the stream from our webcams).

You need to build a stream API and a Media Stream Transceiver to control the related media processing and transport.

Android Emulator Error Message: "PANIC: Missing emulator engine program for 'x86' CPUS."

There are two named emulator binary file. which located under $SDK/tools/emulator another under $SDK/emulator/

  • please make sure you have the right emulator configure(need add $SDK/emulator to your env PATH

I have write a script to help me to invoke the avd list

    #!/bin/bash -e


    echo "--- $# $(PWD)"
    HOME_CURRENT=$(PWD)
    HOME_EMULATOR=/Users/pcao/Library/Android/sdk/emulator

    if [ "$#" -eq 0 ]
    then
        echo "ERROR pls try avd 23 or avd 28 " 
    fi

    if [ "$1" = "23" ]
    then
        echo "enter 23"
        cd $HOME_EMULATOR
        ./emulator -avd Nexus_5_API_23_Android6_ &
        cd $HOME_CURRENT
    fi

    if [ "$1" = "28" ]
    then
        echo "enter 28"
        cd $HOME_EMULATOR
        ./emulator -avd Nexus_5_API_28_GooglePlay_ &
        cd $HOME_CURRENT
    fi


What is the convention in JSON for empty vs. null?

"JSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types."

"The JSON empty concept applies for arrays and objects...Data object does not have a concept of empty lists. Hence, no action is taken on the data object for those properties."

Here is my source.

insert datetime value in sql database with c#

It's more standard to use the format yyyy-mm-dd hh:mm:ss (IE: 2009-06-23 19:30:20)

Using that you won't have to worry about the format of the date (MM/DD/YYYY or DD/MM/YYYY). It will work with all of them.

How to access local files of the filesystem in the Android emulator?

Update! You can access the Android filesystem via Android Device Monitor. In Android Studio go to Tools >> Android >> Android Device Monitor.

Note that you can run your app in the simulator while using the Android Device Monitor. But you cannot debug you app while using the Android Device Monitor.

How/when to use ng-click to call a route?

I used ng-click directive to call a function, while requesting route templateUrl, to decide which <div> has to be show or hide inside route templateUrl page or for different scenarios.

AngularJS 1.6.9

Lets see an example, when in routing page, I need either the add <div> or the edit <div>, which I control using the parent controller models $scope.addProduct and $scope.editProduct boolean.

RoutingTesting.html

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <meta charset="UTF-8">_x000D_
    <title>Testing</title>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-route.min.js"></script>_x000D_
    <script>_x000D_
        var app = angular.module("MyApp", ["ngRoute"]);_x000D_
_x000D_
        app.config(function($routeProvider){_x000D_
            $routeProvider_x000D_
                .when("/TestingPage", {_x000D_
                    templateUrl: "TestingPage.html"_x000D_
                });_x000D_
        });_x000D_
_x000D_
        app.controller("HomeController", function($scope, $location){_x000D_
_x000D_
            $scope.init = function(){_x000D_
                $scope.addProduct = false;_x000D_
                $scope.editProduct = false;_x000D_
            }_x000D_
_x000D_
            $scope.productOperation = function(operationType, productId){_x000D_
                $scope.addProduct = false;_x000D_
                $scope.editProduct = false;_x000D_
_x000D_
                if(operationType === "add"){_x000D_
                    $scope.addProduct = true;_x000D_
                    console.log("Add productOperation requested...");_x000D_
                }else if(operationType === "edit"){_x000D_
                    $scope.editProduct = true;_x000D_
                    console.log("Edit productOperation requested : " + productId);_x000D_
                }_x000D_
_x000D_
                //*************** VERY IMPORTANT NOTE ***************_x000D_
                //comment this $location.path("..."); line, when using <a> anchor tags,_x000D_
                //only useful when <a> below given are commented, and using <input> controls_x000D_
                $location.path("TestingPage");_x000D_
            };_x000D_
_x000D_
        });_x000D_
    </script>_x000D_
</head>_x000D_
<body ng-app="MyApp" ng-controller="HomeController">_x000D_
_x000D_
    <div ng-init="init()">_x000D_
_x000D_
        <!-- Either use <a>anchor tag or input type=button -->_x000D_
_x000D_
        <!--<a href="#!TestingPage" ng-click="productOperation('add', -1)">Add Product</a>-->_x000D_
        <!--<br><br>-->_x000D_
        <!--<a href="#!TestingPage" ng-click="productOperation('edit', 10)">Edit Product</a>-->_x000D_
_x000D_
        <input type="button" ng-click="productOperation('add', -1)" value="Add Product"/>_x000D_
        <br><br>_x000D_
        <input type="button" ng-click="productOperation('edit', 10)" value="Edit Product"/>_x000D_
        <pre>addProduct : {{addProduct}}</pre>_x000D_
        <pre>editProduct : {{editProduct}}</pre>_x000D_
        <ng-view></ng-view>_x000D_
_x000D_
    </div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

TestingPage.html

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <meta charset="UTF-8">_x000D_
    <title>Title</title>_x000D_
    <style>_x000D_
        .productOperation{_x000D_
            position:fixed;_x000D_
            top: 50%;_x000D_
            left: 50%;_x000D_
            width:30em;_x000D_
            height:18em;_x000D_
            margin-left: -15em; /*set to a negative number 1/2 of your width*/_x000D_
            margin-top: -9em; /*set to a negative number 1/2 of your height*/_x000D_
            border: 1px solid #ccc;_x000D_
            background: yellow;_x000D_
        }_x000D_
    </style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="productOperation" >_x000D_
_x000D_
    <div ng-show="addProduct">_x000D_
        <h2 >Add Product enabled</h2>_x000D_
    </div>_x000D_
_x000D_
    <div ng-show="editProduct">_x000D_
        <h2>Edit Product enabled</h2>_x000D_
    </div>_x000D_
_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

both pages - RoutingTesting.html(parent), TestingPage.html(routing page) are in the same directory,

Hope this will help someone.

How does Facebook Sharer select Images and other metadata when sharing my URL?

For secure HTTPS

<meta property="og:image:secure_url" content="https://image.path.png" />

Service Reference Error: Failed to generate code for the service reference

"Reuse types" is not always the problem when this error occurs.

When adding a reference to an older service, click 'advanced' and there 'Add Web Reference'. Now link to your wsdl and everything should be working.

Consider defining a bean of type 'package' in your configuration [Spring-Boot]

@SpringBootApplication
@MapperScan("com.developer.project.mapper")

public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

How to read data from java properties file using Spring Boot

We can read properties file in spring boot using 3 way

1. Read value from application.properties Using @Value

map key as

public class EmailService {

 @Value("${email.username}")
 private String username;

}

2. Read value from application.properties Using @ConfigurationProperties

In this we will map prefix of key using ConfigurationProperties and key name is same as field of class

  @Component
   @ConfigurationProperties("email")
    public class EmailConfig {

        private String   username;
    }

3. Read application.properties Using using Environment object

public class EmailController {

@Autowired
private Environment env;

@GetMapping("/sendmail")
public void sendMail(){     
    System.out.println("reading value from application properties file  using Environment ");
    System.out.println("username ="+ env.getProperty("email.username"));
    System.out.println("pwd ="+ env.getProperty("email.pwd"));
}

Reference : how to read value from application.properties in spring boot

How to check for registry value using VbScript

This should work for you:

Dim oShell
Dim iValue

Set oShell = CreateObject("WScript.Shell")

iValue = oShell.RegRead("HKLM\SOFTWARE\SOMETHINGSOMETHING")

What's the simplest way to print a Java array?

Starting with Java 8, one could also take advantage of the join() method provided by the String class to print out array elements, without the brackets, and separated by a delimiter of choice (which is the space character for the example shown below):

String[] greeting = {"Hey", "there", "amigo!"};
String delimiter = " ";
String.join(delimiter, greeting) 

The output will be "Hey there amigo!".

How can I match on an attribute that contains a certain string?

Here's an example that finds div elements whose className contains atag:

//div[contains(@class, 'atag')]

Here's an example that finds div elements whose className contains atag and btag:

//div[contains(@class, 'atag') and contains(@class ,'btag')]

However, it will also find partial matches like class="catag bobtag".

If you don't want partial matches, see bobince's answer below.

jQuery AJAX Call to PHP Script with JSON Return

try to send content type header from server use this just before echoing

header('Content-Type: application/json');

libstdc++.so.6: cannot open shared object file: No such file or directory

I presume you're running Linux on an amd64 machine. The Folder your executable is residing in (lib32) suggests a 32-bit executable which requires 32-bit libraries.

These seem not to be present on your system, so you need to install them manually. The package name depends on your distribution, for Debian it's ia32-libs, for Fedora libstdc++.<version>.i686.

Change form size at runtime in C#

If you want to manipulate the form programmatically the simplest solution is to keep a reference to it:

static Form myForm;

static void Main()
{
    myForm = new Form();
    Application.Run(myForm);
}

You can then use that to change the size (or what ever else you want to do) at run time. Though as Arrow points out you can't set the Width and Height directly but have to set the Size property.

How to update primary key

When you find it necessary to update a primary key value as well as all matching foreign keys, then the entire design needs to be fixed.

It is tricky to cascade all the necessary foreign keys changes. It is a best practice to never update the primary key, and if you find it necessary, you should use a Surrogate Primary Key, which is a key not derived from application data. As a result its value is unrelated to the business logic and never needs to change (and should be invisible to the end user). You can then update and display some other column.

for example:

BadUserTable
UserID     varchar(20) primary key --user last name
other columns...

when you create many tables that have a FK to UserID, to track everything that the user has worked on, but that user then gets married and wants a ID to match their new last name, you are out of luck.

GoodUserTable
UserID    int identity(1,1) primary key
UserLogin varchar(20) 
other columns....

you now FK the Surrogate Primary Key to all the other tables, and display UserLogin when necessary, allow them to login using that value, and when they need to change it, you change it in one column of one row only.

How to validate phone numbers using regex

Here's one that works well in JavaScript. It's in a string because that's what the Dojo widget was expecting.

It matches a 10 digit North America NANP number with optional extension. Spaces, dashes and periods are accepted delimiters.

"^(\\(?\\d\\d\\d\\)?)( |-|\\.)?\\d\\d\\d( |-|\\.)?\\d{4,4}(( |-|\\.)?[ext\\.]+ ?\\d+)?$"

How can I switch my git repository to a particular commit

All the above commands create a new branch and with the latest commit being the one specified in the command, but just in case you want your current branch HEAD to move to the specified commit, below is the command:

 git checkout <commit_hash>

It detaches and point the HEAD to specified commit and saves from creating a new branch when the user just wants to view the branch state till that particular commit.


You then might want to go back to the latest commit & fix the detached HEAD:

Fix a Git detached head?

How to set image in imageview in android?

1> You can add image from layout itself:

<ImageView
                android:id="@+id/iv_your_image"
                android:layout_width="wrap_content"
                android:layout_height="25dp"
                android:background="@mipmap/your_image"
                android:padding="2dp" />

OR

2> Programmatically in java class:

ImageView ivYouImage= (ImageView)findViewById(R.id.iv_your_image);
        ivYouImage.setImageResource(R.mipmap.ic_changeImage);

OR for fragments:

View rowView= inflater.inflate(R.layout.your_layout, null, true);

ImageView ivYouImage= (ImageView) rowView.findViewById(R.id.iv_your_image);
        ivYouImage.setImageResource(R.mipmap.ic_changeImage);

Zsh: Conda/Pip installs command not found

  1. Open your ~./bashrc
  2. Find the following code (maybe something similar) that launches your conda:

    # >>> conda init >>>
    # !! Contents within this block are managed by 'conda init' !!
    __conda_setup="$(CONDA_REPORT_ERRORS=false '/anaconda3/bin/conda' shell.bash hook 2> /dev/null)" if [ $? -eq 0 ]; then
        \eval "$__conda_setup" else
        if [ -f "/anaconda3/etc/profile.d/conda.sh" ]; then
            . "/anaconda3/etc/profile.d/conda.sh"
            CONDA_CHANGEPS1=false conda activate base
        else
            \export PATH="/anaconda3/bin:$PATH"
        fi fi unset __conda_setup
    # <<< conda init <<<

  1. source ~/.zshrc
  2. Things should work.

How to get MAC address of client using PHP?

echo GetMAC();

function GetMAC(){
    ob_start();
    system('getmac');
    $Content = ob_get_contents();
    ob_clean();
    return substr($Content, strpos($Content,'\\')-20, 17);
}

Above will basically execute the getmac program and parse its console-output, resulting to MAC-address of the server (and/or where ever PHP is installed and running on).

How to setup FTP on xampp

XAMPP for linux and mac comes with ProFTPD. Make sure to start the service from XAMPP control panel -> manage servers.

Further complete instructions can be found at localhost XAMPP dashboard -> How-to guides -> Configure FTP Access. I have pasted them below :

  1. Open a new Linux terminal and ensure you are logged in as root.

  2. Create a new group named ftp. This group will contain those user accounts allowed to upload files via FTP.

groupadd ftp

  1. Add your account (in this example, susan) to the new group. Add other users if needed.

usermod -a -G ftp susan

  1. Change the ownership and permissions of the htdocs/ subdirectory of the XAMPP installation directory (typically, /opt/lampp) so that it is writable by the the new ftp group.

cd /opt/lampp chown root.ftp htdocs chmod 775 htdocs

  1. Ensure that proFTPD is running in the XAMPP control panel.

You can now transfer files to the XAMPP server using the steps below:

  1. Start an FTP client like winSCP or FileZilla and enter connection details as below.

If you’re connecting to the server from the same system, use "127.0.0.1" as the host address. If you’re connecting from a different system, use the network hostname or IP address of the XAMPP server.

Use "21" as the port.

Enter your Linux username and password as your FTP credentials.

Your FTP client should now connect to the server and enter the /opt/lampp/htdocs/ directory, which is the default Web server document root.

  1. Transfer the file from your home directory to the server using normal FTP transfer conventions. If you’re using a graphical FTP client, you can usually drag and drop the file from one directory to the other. If you’re using a command-line FTP client, you can use the FTP PUT command.

Once the file is successfully transferred, you should be able to see it in action.

Runnable with a parameter?

You have two options:

  1. Define a named class. Pass your parameter to the constructor of the named class.

  2. Have your anonymous class close over your "parameter". Be sure to mark it as final.

How to convert integer to string in C?

Making your own itoa is also easy, try this :

char* itoa(int i, char b[]){
    char const digit[] = "0123456789";
    char* p = b;
    if(i<0){
        *p++ = '-';
        i *= -1;
    }
    int shifter = i;
    do{ //Move to where representation ends
        ++p;
        shifter = shifter/10;
    }while(shifter);
    *p = '\0';
    do{ //Move back, inserting digits as u go
        *--p = digit[i%10];
        i = i/10;
    }while(i);
    return b;
}

or use the standard sprintf() function.

Fastest way to check if string contains only digits

You could simply do this using LINQ

return str.All(char.IsDigit);

  1. .All returns true for empty strings and exception for null strings.
  2. char.IsDigit is true for all Unicode characters.

How to create a number picker dialog?

A Simple Example:

layout/billing_day_dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <NumberPicker
        android:id="@+id/number_picker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true" />

    <Button
        android:id="@+id/apply_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/number_picker"
        android:text="Apply" />

</RelativeLayout>

NumberPickerActivity.java

import android.app.Activity;

import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.NumberPicker;

public class NumberPickerActivity extends Activity 
{

  @Override
  protected void onCreate(Bundle savedInstanceState) 
  {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.billing_day_dialog);
    NumberPicker np = (NumberPicker)findViewById(R.id.number_picker);
    np.setMinValue(1);// restricted number to minimum value i.e 1
    np.setMaxValue(31);// restricked number to maximum value i.e. 31
    np.setWrapSelectorWheel(true); 

    np.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() 
    {

      @Override
      public void onValueChange(NumberPicker picker, int oldVal, int newVal) 
      {

       // TODO Auto-generated method stub

       String Old = "Old Value : ";

       String New = "New Value : ";

      }
    });

     Log.d("NumberPicker", "NumberPicker");

   }

}/* NumberPickerActivity */

AndroidManifest.xml : Specify theme for the activity as dialogue theme.

<activity
  android:name="org.npn.analytics.call.NumberPickerActivity"
  android:theme="@android:style/Theme.Holo.Dialog"
  android:label="@string/title_activity_number_picker" >
</activity>

Hope it will help.

Add days Oracle SQL

If you want to add N days to your days. You can use the plus operator as follows -

SELECT ( SYSDATE + N ) FROM DUAL;

$_SERVER["REMOTE_ADDR"] gives server IP rather than visitor IP

$_SERVER['REMOTE_ADDR'] gives the IP address from which the request was sent to the web server. This is typically the visitor's address, but in your case, it sounds like there is some kind of proxy sitting right before the web server that intercepts the requests, hence to the web server it appears as though the requests are originating from there.

What's the algorithm to calculate aspect ratio?

Based on the other answers, here is how I got the numbers I needed in Python;

from decimal import Decimal

def gcd(a,b):
    if b == 0:
        return a
    return gcd(b, a%b)

def closest_aspect_ratio(width, height):
    g = gcd(width, height)
    x = Decimal(str(float(width)/float(g)))
    y = Decimal(str(float(height)/float(g)))
    dec = Decimal(str(x/y))
    return dict(x=x, y=y, dec=dec)

>>> closest_aspect_ratio(1024, 768)
{'y': Decimal('3.0'), 
 'x': Decimal('4.0'), 
 'dec': Decimal('1.333333333333333333333333333')}

How to delete object from array inside foreach loop?

I'm not much of a php programmer, but I can say that in C# you cannot modify an array while iterating through it. You may want to try using your foreach loop to identify the index of the element, or elements to remove, then delete the elements after the loop.

How to not wrap contents of a div?

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

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

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

How to obtain the query string from the current URL with JavaScript?

q={};location.search.replace(/([^?&=]+)=([^&]+)/g,(_,k,v)=>q[k]=v);q;

Pandas convert dataframe to array of tuples

Here's a vectorized approach (assuming the dataframe, data_set to be defined as df instead) that returns a list of tuples as shown:

>>> df.set_index(['data_date'])[['data_1', 'data_2']].to_records().tolist()

produces:

[(datetime.datetime(2012, 2, 17, 0, 0), 24.75, 25.03),
 (datetime.datetime(2012, 2, 16, 0, 0), 25.0, 25.07),
 (datetime.datetime(2012, 2, 15, 0, 0), 24.99, 25.15),
 (datetime.datetime(2012, 2, 14, 0, 0), 24.68, 25.05),
 (datetime.datetime(2012, 2, 13, 0, 0), 24.62, 24.77),
 (datetime.datetime(2012, 2, 10, 0, 0), 24.38, 24.61)]

The idea of setting datetime column as the index axis is to aid in the conversion of the Timestamp value to it's corresponding datetime.datetime format equivalent by making use of the convert_datetime64 argument in DF.to_records which does so for a DateTimeIndex dataframe.

This returns a recarray which could be then made to return a list using .tolist


More generalized solution depending on the use case would be:

df.to_records().tolist()                              # Supply index=False to exclude index

Insert a line at specific line number with sed or awk

Perl solutions:

quick and dirty:

perl -lpe 'print "Project_Name=sowstest" if $. == 8' file

  • -l strips newlines and adds them back in, eliminating the need for "\n"
  • -p loops over the input file, printing every line
  • -e executes the code in single quotes

$. is the line number

equivalent to @glenn's awk solution, using named arguments:

perl -slpe 'print $s if $. == $n' -- -n=8 -s="Project_Name=sowstest" file

  • -s enables a rudimentary argument parser
  • -- prevents -n and -s from being parsed by the standard perl argument parser

positional command arguments:

perl -lpe 'BEGIN{$n=shift; $s=shift}; print $s if $. == $n' 8 "Project_Name=sowstest" file

environment variables:

setenv n 8 ; setenv s "Project_Name=sowstest"
echo $n ; echo $s
perl -slpe 'print $ENV{s} if $. == $ENV{n}' file

ENV is the hash which contains all environment variables

Getopt to parse arguments into hash %o:

perl -MGetopt::Std -lpe 'BEGIN{getopt("ns",\%o)}; print $o{s} if $. == $o{n}' -- -n 8 -s "Project_Name=sowstest" file

Getopt::Long and longer option names

perl -MGetopt::Long -lpe 'BEGIN{GetOptions(\%o,"line=i","string=s")}; print $o{string} if $. == $o{line}' -- --line 8 --string "Project_Name=sowstest" file

Getopt is the recommended standard-library solution.
This may be overkill for one-line perl scripts, but it can be done

How to upload file using Selenium WebDriver in Java

This is what I use to upload the image through upload window:

    //open upload window
    upload.click();

    //put path to your image in a clipboard
    StringSelection ss = new StringSelection("C:\\IMG_3827.JPG");
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);

    //imitate mouse events like ENTER, CTRL+C, CTRL+V
    Robot robot = new Robot();
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);

done

find all the name using mysql query which start with the letter 'a'

try using CHARLIST as shown below:

select distinct name from artists where name RLIKE '^[abc]';

use distinct only if you want distinct values only. To read about it Click here.

Assigning out/ref parameters in Moq

This is documentation from Moq site:

// out arguments
var outString = "ack";
// TryParse will return true, and the out argument will return "ack", lazy evaluated
mock.Setup(foo => foo.TryParse("ping", out outString)).Returns(true);


// ref arguments
var instance = new Bar();
// Only matches if the ref argument to the invocation is the same instance
mock.Setup(foo => foo.Submit(ref instance)).Returns(true);

/lib/ld-linux.so.2: bad ELF interpreter: No such file or directory

These are the installation i had to run in order to make it work on fedora 22 :-

glibc-2.21-7.fc22.i686

alsa-lib-1.0.29-1.fc22.i686

qt3-3.3.8b-64.fc22.i686

libusb-1:0.1.5-5.fc22.i686

How to remove blank lines from a Unix file

sed -i '/^$/d' foo

This tells sed to delete every line matching the regex ^$ i.e. every empty line. The -i flag edits the file in-place, if your sed doesn't support that you can write the output to a temporary file and replace the original:

sed '/^$/d' foo > foo.tmp
mv foo.tmp foo

If you also want to remove lines consisting only of whitespace (not just empty lines) then use:

sed -i '/^[[:space:]]*$/d' foo

Edit: also remove whitespace at the end of lines, because apparently you've decided you need that too:

sed -i '/^[[:space:]]*$/d;s/[[:space:]]*$//' foo

How to give a time delay of less than one second in excel vba?

No answer helped me, so I build this.

'   function Timestamp return current time in milliseconds.
'   compatible with JSON or JavaScript Date objects.

Public Function Timestamp () As Currency
    timestamp = (Round(Now(), 0) * 24 * 60 * 60 + Timer()) * 1000
End Function

'   function Sleep let system execute other programs while the milliseconds are not elapsed.

Public Function Sleep(milliseconds As Currency)

    If milliseconds < 0 Then Exit Function

    Dim start As Currency
    start = Timestamp ()

    While (Timestamp () < milliseconds + start)
        DoEvents
    Wend
End Function

Note : In Excel 2007, Now() send Double with decimals to seconds, so i use Timer() to get milliseconds.

Note : Application.Wait() accept seconds and no under (i.e. Application.Wait(Now()) ? Application.Wait(Now()+100*millisecond)))

Note : Application.Wait() doesn't let system execute other program but hardly reduce performance. Prefer usage of DoEvents.

VBA - Run Time Error 1004 'Application Defined or Object Defined Error'

Solution #1: Your statement

.Range(Cells(RangeStartRow, RangeStartColumn), Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues

does not refer to a proper Range to act upon. Instead,

.Range(.Cells(RangeStartRow, RangeStartColumn), .Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues

does (and similarly in some other cases).

Solution #2: Activate Worksheets("Cable Cards") prior to using its cells.

Explanation: Cells(RangeStartRow, RangeStartColumn) (e.g.) gives you a Range, that would be ok, and that is why you often see Cells used in this way. But since it is not applied to a specific object, it applies to the ActiveSheet. Thus, your code attempts using .Range(rng1, rng2), where .Range is a method of one Worksheet object and rng1 and rng2 are in a different Worksheet.

There are two checks that you can do to make this quite evident:

  1. Activate your Worksheets("Cable Cards") prior to executing your Sub and it will start working (now you have well-formed references to Ranges). For the code you posted, adding .Activate right after With... would indeed be a solution, although you might have a similar problem somewhere else in your code when referring to a Range in another Worksheet.

  2. With a sheet other than Worksheets("Cable Cards") active, set a breakpoint at the line throwing the error, start your Sub, and when execution breaks, write at the immediate window

    Debug.Print Cells(RangeStartRow, RangeStartColumn).Address(external:=True)

    Debug.Print .Cells(RangeStartRow, RangeStartColumn).Address(external:=True)

    and see the different outcomes.

Conclusion: Using Cells or Range without a specified object (e.g., Worksheet, or Range) might be dangerous, especially when working with more than one Sheet, unless one is quite sure about what Sheet is active.

PL/pgSQL checking if a row exists

Simpler, shorter, faster: EXISTS.

IF EXISTS (SELECT 1 FROM people p WHERE p.person_id = my_person_id) THEN
  -- do something
END IF;

The query planner can stop at the first row found - as opposed to count(), which will scan all matching rows regardless. Makes a difference with big tables. Hardly matters with a condition on a unique column - only one row qualifies anyway (and there is an index to look it up quickly).

Improved with input from @a_horse_with_no_name in the comments below.

You could even use an empty SELECT list:

IF EXISTS (SELECT FROM people p WHERE p.person_id = my_person_id) THEN ...

Since the SELECT list is not relevant to the outcome of EXISTS. Only the existence of at least one qualifying row matters.

For each row return the column name of the largest value

If you're interested in a data.table solution, here's one. It's a bit tricky since you prefer to get the id for the first maximum. It's much easier if you'd rather want the last maximum. Nevertheless, it's not that complicated and it's fast!

Here I've generated data of your dimensions (26746 * 18).

Data

set.seed(45)
DF <- data.frame(matrix(sample(10, 26746*18, TRUE), ncol=18))

data.table answer:

require(data.table)
DT <- data.table(value=unlist(DF, use.names=FALSE), 
            colid = 1:nrow(DF), rowid = rep(names(DF), each=nrow(DF)))
setkey(DT, colid, value)
t1 <- DT[J(unique(colid), DT[J(unique(colid)), value, mult="last"]), rowid, mult="first"]

Benchmarking:

# data.table solution
system.time({
DT <- data.table(value=unlist(DF, use.names=FALSE), 
            colid = 1:nrow(DF), rowid = rep(names(DF), each=nrow(DF)))
setkey(DT, colid, value)
t1 <- DT[J(unique(colid), DT[J(unique(colid)), value, mult="last"]), rowid, mult="first"]
})
#   user  system elapsed 
#  0.174   0.029   0.227 

# apply solution from @thelatemail
system.time(t2 <- colnames(DF)[apply(DF,1,which.max)])
#   user  system elapsed 
#  2.322   0.036   2.602 

identical(t1, t2)
# [1] TRUE

It's about 11 times faster on data of these dimensions, and data.table scales pretty well too.


Edit: if any of the max ids is okay, then:

DT <- data.table(value=unlist(DF, use.names=FALSE), 
            colid = 1:nrow(DF), rowid = rep(names(DF), each=nrow(DF)))
setkey(DT, colid, value)
t1 <- DT[J(unique(colid)), rowid, mult="last"]

In a unix shell, how to get yesterday's date into a variable?

If you have Perl available (and your date doesn't have nice features like yesterday), you can use:

pax> date
Thu Aug 18 19:29:49 XYZ 2010

pax> dt=$(perl -e 'use POSIX;print strftime "%d/%m/%Y%",localtime time-86400;')

pax> echo $dt
17/08/2010

How to add Headers on RESTful call using Jersey Client API

String sBodys="Body";
HashMap<String,String> headers= new HashMap<>();
Client c = Client.create();
WebResource resource = c.resource("http://consulta/rs");
WebResource.Builder builder = resource.accept(MediaType.APPLICATION_JSON);
builder.type(MediaType.APPLICATION_JSON);
if(headers!=null){
      LOGGER.debug("se setean los headers");
      for (Map.Entry<String, String> entry : headers.entrySet()) {
          String key = entry.getKey();
          String value = entry.getValue();
          LOGGER.debug("key: "+entry.getKey());
          LOGGER.debug("value: "+entry.getValue());
          builder.header(key, value);
      }
  }
ClientResponse response = builder.post(ClientResponse.class,sBodys);

How to get the nth occurrence in a string?

_x000D_
_x000D_
const string = "XYZ 123 ABC 456 ABC 789 ABC";_x000D_
_x000D_
function getPosition(string, subString, index) {_x000D_
  return string.split(subString, index).join(subString).length;_x000D_
}_x000D_
_x000D_
console.log(_x000D_
  getPosition(string, 'ABC', 2) // --> 16_x000D_
)
_x000D_
_x000D_
_x000D_

How do I use a delimiter with Scanner.useDelimiter in Java?

With Scanner the default delimiters are the whitespace characters.

But Scanner can define where a token starts and ends based on a set of delimiter, wich could be specified in two ways:

  1. Using the Scanner method: useDelimiter(String pattern)
  2. Using the Scanner method : useDelimiter(Pattern pattern) where Pattern is a regular expression that specifies the delimiter set.

So useDelimiter() methods are used to tokenize the Scanner input, and behave like StringTokenizer class, take a look at these tutorials for further information:

And here is an Example:

public static void main(String[] args) {

    // Initialize Scanner object
    Scanner scan = new Scanner("Anna Mills/Female/18");
    // initialize the string delimiter
    scan.useDelimiter("/");
    // Printing the tokenized Strings
    while(scan.hasNext()){
        System.out.println(scan.next());
    }
    // closing the scanner stream
    scan.close();
}

Prints this output:

Anna Mills
Female
18

What's the difference between returning value or Promise.resolve from then()

The rule is, if the function that is in the then handler returns a value, the promise resolves/rejects with that value, and if the function returns a promise, what happens is, the next then clause will be the then clause of the promise the function returned, so, in this case, the first example falls through the normal sequence of the thens and prints out values as one might expect, in the second example, the promise object that gets returned when you do Promise.resolve("bbb")'s then is the then that gets invoked when chaining(for all intents and purposes). The way it actually works is described below in more detail.

Quoting from the Promises/A+ spec:

The promise resolution procedure is an abstract operation taking as input a promise and a value, which we denote as [[Resolve]](promise, x). If x is a thenable, it attempts to make promise adopt the state of x, under the assumption that x behaves at least somewhat like a promise. Otherwise, it fulfills promise with the value x.

This treatment of thenables allows promise implementations to interoperate, as long as they expose a Promises/A+-compliant then method. It also allows Promises/A+ implementations to “assimilate” nonconformant implementations with reasonable then methods.

The key thing to notice here is this line:

if x is a promise, adopt its state [3.4]

link: https://promisesaplus.com/#point-49

curl: (6) Could not resolve host: google.com; Name or service not known

I have today similar problem. But weirder.

  • host - works host pl.archive.ubuntu.com
  • dig - works on default and on all other DNS's dig pl.archive.ubuntu.com, dig @127.0.1.1 pl.archive.ubuntu.com
  • curl - doesn't work! but for some addresses it does. WEIRD! Same in Ruby, APT and many more.
$ curl -v http://google.com/
*   Trying 172.217.18.78...
* Connected to google.com (172.217.18.78) port 80 (#0)
> GET / HTTP/1.1
> Host: google.com
> User-Agent: curl/7.47.0
> Accept: */*
>
< HTTP/1.1 302 Found
< Cache-Control: private
< Content-Type: text/html; charset=UTF-8
< Referrer-Policy: no-referrer
< Location: http://www.google.pl/?gfe_rd=cr&ei=pt9UWfqXL4uBX_W5n8gB
< Content-Length: 256
< Date: Thu, 29 Jun 2017 11:08:22 GMT
<
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="http://www.google.pl/?gfe_rd=cr&ei=pt9UWfqXL4uBX_W5n8gB">here</A>.
</BODY></HTML>
* Connection #0 to host google.com left intact

$ curl -v http://pl.archive.ubuntu.com/
* Could not resolve host: pl.archive.ubuntu.com
* Closing connection 0
curl: (6) Could not resolve host: pl.archive.ubuntu.com

Revelation

Eventually I used strace on curl and found that it was connection to nscd deamon.

connect(4, {sa_family=AF_LOCAL, sun_path="/var/run/nscd/socket"}, 110) = 0

Solution

I've restarted the nscd service (Name Service Cache Daemon) and it helped to solve this issue!

systemctl restart nscd.service

Default Activity not found in Android Studio

  1. In Android Studio

  2. Go to edit Configuration .

  3. Select the app.

  4. choose the lunch Activity path.

  5. apply, OK.

    Thanks!!

How to encode a string in JavaScript for displaying in HTML?

function htmlEntities(str) {
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

So then with var unsafestring = "<oohlook&atme>"; you would use htmlEntities(unsafestring);

How to add line break for UILabel?

NSCharacterSet *charSet = NSCharacterSet.newlineCharacterSet;
NSString *formatted = [[unformatted componentsSeparatedByCharactersInSet:charSet] componentsJoinedByString:@"\n"];

What is &amp used for

HTML doesn't recognize the & but it will recognize &amp; because it is equal to & in HTML

I looked over this post someone had made: http://www.webmasterworld.com/forum21/8851.htm

jQuery get specific option tag text

You can get selected option text by using function .text();

you can call the function like this :

jQuery("select option:selected").text();

Scanner is skipping nextLine() after using next() or nextFoo()?

That's because the Scanner.nextInt method does not read the newline character in your input created by hitting "Enter," and so the call to Scanner.nextLine returns after reading that newline.

You will encounter the similar behaviour when you use Scanner.nextLine after Scanner.next() or any Scanner.nextFoo method (except nextLine itself).

Workaround:

  • Either put a Scanner.nextLine call after each Scanner.nextInt or Scanner.nextFoo to consume rest of that line including newline

    int option = input.nextInt();
    input.nextLine();  // Consume newline left-over
    String str1 = input.nextLine();
    
  • Or, even better, read the input through Scanner.nextLine and convert your input to the proper format you need. For example, you may convert to an integer using Integer.parseInt(String) method.

    int option = 0;
    try {
        option = Integer.parseInt(input.nextLine());
    } catch (NumberFormatException e) {
        e.printStackTrace();
    }
    String str1 = input.nextLine();
    

Why can I ping a server but not connect via SSH?

Find out two pieces of information

  • Whats the hostname or IP of the target ssh server
  • What port is the ssh daemon listening on (default is port 22)

$> telnet <hostname or ip> <port>

Assuming the daemon is up and running and listening on that port it should etablish a telnet session. Likely causes:

  • The ssh daemon is not running
  • The host is blocking the target port with its software firewall
  • Some intermediate network device is blocking or filtering the target port
  • The ssh daemon is listening on a non standard port
  • A TCP wrapper is configured and is filtering out your source host

remove legend title in ggplot

For Error: 'opts' is deprecated. Use theme() instead. (Defunct; last used in version 0.9.1)' I replaced opts(title = "Boxplot - Candidate's Tweet Scores") with labs(title = "Boxplot - Candidate's Tweet Scores"). It worked!

Homebrew: Could not symlink, /usr/local/bin is not writable

For those running into this issue (granted 4 years after this post was made) while running Mac OS High Sierra - the steps outlined here solved the problem for me. Essentially just outlines uninstalling and reinstalling brew.

https://medium.com/@mrkdsgn/brew-error-on-macos-high-sierra-check-you-have-permission-to-write-to-usr-local-e8bd1c6a22d4

After running those steps, brew link worked like a charm!

Python: Pandas Dataframe how to multiply entire column with a scalar

I got this warning using Pandas 0.22. You can avoid this by being very explicit using the assign method:

df = df.assign(quantity = df.quantity.mul(-1))

Is there a difference between "==" and "is"?

Python difference between is and equals(==)

The is operator may seem like the same as the equality operator but they are not same.

The is checks if both the variables point to the same object whereas the == sign checks if the values for the two variables are the same.

So if the is operator returns True then the equality is definitely True, but the opposite may or may not be True.

Here is an example to demonstrate the similarity and the difference.

>>> a = b = [1,2,3]
>>> c = [1,2,3]
>>> a == b
True
>>> a == c
True
>>> a is b
True
>>> a is c
False
>>> a = [1,2,3]
>>> b = [1,2]
>>> a == b
False
>>> a is b
False
>>> del a[2]
>>> a == b
True
>>> a is b
False
Tip: Avoid using is operator for immutable types such as strings and numbers, the result is unpredictable.

Cannot implicitly convert type from Task<>

You need to make TestGetMethod async too and attach await in front of GetIdList(); will unwrap the task to List<int>, So if your helper function is returning Task make sure you have await as you are calling the function async too.

public Task<List<int>> TestGetMethod()
{
    return GetIdList();
}    

async Task<List<int>> GetIdList()
{
    using (HttpClient proxy = new HttpClient())
    {
        string response = await proxy.GetStringAsync("www.test.com");
        List<int> idList = JsonConvert.DeserializeObject<List<int>>();
        return idList;
    }
}

Another option

public async void TestGetMethod(List<int> results)
{
    results = await GetIdList(); // await will unwrap the List<int>
}

Android, How to create option Menu

Replace return super.onCreateOptionsMenu(menu); with return true; in your onCreateOptionsMenu method This will help

And you should also have the onCreate method in your activity

How do I make a self extract and running installer

I have created step by step instructions on how to do this as I also was very confused about how to get this working.

How to make a self extracting archive that runs your setup.exe with 7zip -sfx switch

Here are the steps.

Step 1 - Setup your installation folder

To make this easy create a folder c:\Install. This is where we will copy all the required files.

Step 2 - 7Zip your installers

  1. Go to the folder that has your .msi and your setup.exe
  2. Select both the .msi and the setup.exe
  3. Right-Click and choose 7Zip --> "Add to Archive"
  4. Name your archive "Installer.7z" (or a name of your choice)
  5. Click Ok
  6. You should now have "Installer.7z".
  7. Copy this .7z file to your c:\Install directory

Step 3 - Get the 7z-Extra sfx extension module

You need to download 7zSD.sfx

  1. Download one of the LZMA packages from here
  2. Extract the package and find 7zSD.sfx in the bin folder.
  3. Copy the file "7zSD.sfx" to c:\Install

Step 4 - Setup your config.txt

I would recommend using NotePad++ to edit this text file as you will need to encode in UTF-8, the following instructions are using notepad++.

  1. Using windows explorer go to c:\Install
  2. right-click and choose "New Text File" and name it config.txt
  3. right-click and choose "Edit with NotePad++
  4. Click the "Encoding Menu" and choose "Encode in UTF-8"
  5. Enter something like this:

    ;!@Install@!UTF-8!
    Title="SOFTWARE v1.0.0.0"
    BeginPrompt="Do you want to install SOFTWARE v1.0.0.0?"
    RunProgram="setup.exe"
    ;!@InstallEnd@!
    

Edit this replacing [SOFTWARE v1.0.0.0] with your product name. Notes on the parameters and options for the setup file are here.

CheckPoint

You should now have a folder "c:\Install" with the following 3 files:

  1. Installer.7z
  2. 7zSD.sfx
  3. config.txt

Step 5 - Create the archive

These instructions I found on the web but nowhere did it explain any of the 4 steps above.

  1. Open a cmd window, Window + R --> cmd --> press enter
  2. In the command window type the following

    cd \
    cd Install
    copy /b 7zSD.sfx + config.txt + Installer.7z MyInstaller.exe
    
  3. Look in c:\Install and you will now see you have a MyInstaller.exe

  4. You are finished

Run the installer

Double click on MyInstaller.exe and it will prompt with your message. Click OK and the setup.exe will run.

P.S. Note on Automation

Now that you have this working in your c:\Install directory I would create an "Install.bat" file and put the copy script in it.

copy /b 7zSD.sfx + config.txt + Installer.7z MyInstaller.exe

Now you can just edit and run the Install.bat every time you need to rebuild a new version of you deployment package.

How do I select text nodes with jQuery?

if you want to strip all tags, then try this

function:

String.prototype.stripTags=function(){
var rtag=/<.*?[^>]>/g;
return this.replace(rtag,'');
}

usage:

var newText=$('selector').html().stripTags();

pandas get rows which are NOT in other dataframe

The currently selected solution produces incorrect results. To correctly solve this problem, we can perform a left-join from df1 to df2, making sure to first get just the unique rows for df2.

First, we need to modify the original DataFrame to add the row with data [3, 10].

df1 = pd.DataFrame(data = {'col1' : [1, 2, 3, 4, 5, 3], 
                           'col2' : [10, 11, 12, 13, 14, 10]}) 
df2 = pd.DataFrame(data = {'col1' : [1, 2, 3],
                           'col2' : [10, 11, 12]})

df1

   col1  col2
0     1    10
1     2    11
2     3    12
3     4    13
4     5    14
5     3    10

df2

   col1  col2
0     1    10
1     2    11
2     3    12

Perform a left-join, eliminating duplicates in df2 so that each row of df1 joins with exactly 1 row of df2. Use the parameter indicator to return an extra column indicating which table the row was from.

df_all = df1.merge(df2.drop_duplicates(), on=['col1','col2'], 
                   how='left', indicator=True)
df_all

   col1  col2     _merge
0     1    10       both
1     2    11       both
2     3    12       both
3     4    13  left_only
4     5    14  left_only
5     3    10  left_only

Create a boolean condition:

df_all['_merge'] == 'left_only'

0    False
1    False
2    False
3     True
4     True
5     True
Name: _merge, dtype: bool

Why other solutions are wrong

A few solutions make the same mistake - they only check that each value is independently in each column, not together in the same row. Adding the last row, which is unique but has the values from both columns from df2 exposes the mistake:

common = df1.merge(df2,on=['col1','col2'])
(~df1.col1.isin(common.col1))&(~df1.col2.isin(common.col2))
0    False
1    False
2    False
3     True
4     True
5    False
dtype: bool

This solution gets the same wrong result:

df1.isin(df2.to_dict('l')).all(1)

Using ADB to capture the screen

To save to a file on Windows, OSX and Linux

adb exec-out screencap -p > screen.png

To copy to clipboard on Linux use

adb exec-out screencap -p | xclip -t image/png

How to install a private NPM module without my own registry?

cd somedir
npm install .

or

npm install path/to/somedir

somedir must contain the package.json inside it.

It knows about git too:

npm install git://github.com/visionmedia/express.git

How to resolve "could not execute statement; SQL [n/a]; constraint [numbering];"?

In my case, this happens when I try to save an object in hibernate or other orm-mapping with null property which can not be null in database table. This happens when you try to save an object, but the save action doesn't comply with the contraints of the table.

Git commit -a "untracked files"?

For others having the same problem, try running

git add . which will add all files of the current directory to track (including untracked) and then use

git commit -a to commit all tracked files.

As suggested by @Pacerier, one liner that does the same thing is

git add -A

Populating Spring @Value during Unit Test

Adding PropertyPlaceholderConfigurer in configuration is working for me.

@Configuration
@ComponentScan
@EnableJpaRepositories
@EnableTransactionManagement
public class TestConfiguration {
    @Bean
    public DataSource dataSource() {
        EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
        builder.setType(EmbeddedDatabaseType.DERBY);
        return builder.build();
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource());
        entityManagerFactoryBean.setPackagesToScan(new String[] { "com.test.model" });
        // Use hibernate
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        entityManagerFactoryBean.setJpaVendorAdapter(vendorAdapter);
        entityManagerFactoryBean.setJpaProperties(getHibernateProperties());
        return entityManagerFactoryBean;
    }

    private Properties getHibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.show_sql", "false");
        properties.put("hibernate.dialect", "org.hibernate.dialect.DerbyDialect");
        properties.put("hibernate.hbm2ddl.auto", "update");
        return properties;
    }

    @Bean
    public JpaTransactionManager transactionManager() {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
         transactionManager.setEntityManagerFactory(
              entityManagerFactory().getObject()
         );

         return transactionManager;
    }

    @Bean
    PropertyPlaceholderConfigurer propConfig() {
        PropertyPlaceholderConfigurer placeholderConfigurer = new PropertyPlaceholderConfigurer();
        placeholderConfigurer.setLocation(new ClassPathResource("application_test.properties"));
        return placeholderConfigurer;
    }
}

And in test class

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestConfiguration.class)
public class DataServiceTest {

    @Autowired
    private DataService dataService;

    @Autowired
    private DataRepository dataRepository;

    @Value("${Api.url}")
    private String baseUrl;

    @Test
    public void testUpdateData() {
        List<Data> datas = (List<Data>) dataRepository.findAll();
        assertTrue(datas.isEmpty());
        dataService.updateDatas();
        datas = (List<Data>) dataRepository.findAll();
        assertFalse(datas.isEmpty());
    }
}

display Java.util.Date in a specific format

It makes no sense, but:

System.out.println(dateFormat.format(dateFormat.parse("31/05/2011")))

SimpleDateFormat.parse() = // parse Date from String
SimpleDateFormat.format() = // format Date into String

How to stop a thread created by implementing runnable interface?

Stopping the thread in midway using Thread.stop() is not a good practice. More appropriate way is to make the thread return programmatically. Let the Runnable object use a shared variable in the run() method. Whenever you want the thread to stop, use that variable as a flag.

EDIT: Sample code

class MyThread implements Runnable{
    
    private Boolean stop = false;
    
    public void run(){
        
        while(!stop){
            
            //some business logic
        }
    }
    public Boolean getStop() {
        return stop;
    }

    public void setStop(Boolean stop) {
        this.stop = stop;
    }       
}

public class TestStop {
    
    public static void main(String[] args){
        
        MyThread myThread = new MyThread();
        Thread th = new Thread(myThread);
        th.start();
        
        //Some logic goes there to decide whether to 
        //stop the thread or not. 
        
        //This will compell the thread to stop
        myThread.setStop(true);
    }
}

Finding the index of an item in a list

Finding the index of an item given a list containing it in Python

For a list ["foo", "bar", "baz"] and an item in the list "bar", what's the cleanest way to get its index (1) in Python?

Well, sure, there's the index method, which returns the index of the first occurrence:

>>> l = ["foo", "bar", "baz"]
>>> l.index('bar')
1

There are a couple of issues with this method:

  • if the value isn't in the list, you'll get a ValueError
  • if more than one of the value is in the list, you only get the index for the first one

No values

If the value could be missing, you need to catch the ValueError.

You can do so with a reusable definition like this:

def index(a_list, value):
    try:
        return a_list.index(value)
    except ValueError:
        return None

And use it like this:

>>> print(index(l, 'quux'))
None
>>> print(index(l, 'bar'))
1

And the downside of this is that you will probably have a check for if the returned value is or is not None:

result = index(a_list, value)
if result is not None:
    do_something(result)

More than one value in the list

If you could have more occurrences, you'll not get complete information with list.index:

>>> l.append('bar')
>>> l
['foo', 'bar', 'baz', 'bar']
>>> l.index('bar')              # nothing at index 3?
1

You might enumerate into a list comprehension the indexes:

>>> [index for index, v in enumerate(l) if v == 'bar']
[1, 3]
>>> [index for index, v in enumerate(l) if v == 'boink']
[]

If you have no occurrences, you can check for that with boolean check of the result, or just do nothing if you loop over the results:

indexes = [index for index, v in enumerate(l) if v == 'boink']
for index in indexes:
    do_something(index)

Better data munging with pandas

If you have pandas, you can easily get this information with a Series object:

>>> import pandas as pd
>>> series = pd.Series(l)
>>> series
0    foo
1    bar
2    baz
3    bar
dtype: object

A comparison check will return a series of booleans:

>>> series == 'bar'
0    False
1     True
2    False
3     True
dtype: bool

Pass that series of booleans to the series via subscript notation, and you get just the matching members:

>>> series[series == 'bar']
1    bar
3    bar
dtype: object

If you want just the indexes, the index attribute returns a series of integers:

>>> series[series == 'bar'].index
Int64Index([1, 3], dtype='int64')

And if you want them in a list or tuple, just pass them to the constructor:

>>> list(series[series == 'bar'].index)
[1, 3]

Yes, you could use a list comprehension with enumerate too, but that's just not as elegant, in my opinion - you're doing tests for equality in Python, instead of letting builtin code written in C handle it:

>>> [i for i, value in enumerate(l) if value == 'bar']
[1, 3]

Is this an XY problem?

The XY problem is asking about your attempted solution rather than your actual problem.

Why do you think you need the index given an element in a list?

If you already know the value, why do you care where it is in a list?

If the value isn't there, catching the ValueError is rather verbose - and I prefer to avoid that.

I'm usually iterating over the list anyways, so I'll usually keep a pointer to any interesting information, getting the index with enumerate.

If you're munging data, you should probably be using pandas - which has far more elegant tools than the pure Python workarounds I've shown.

I do not recall needing list.index, myself. However, I have looked through the Python standard library, and I see some excellent uses for it.

There are many, many uses for it in idlelib, for GUI and text parsing.

The keyword module uses it to find comment markers in the module to automatically regenerate the list of keywords in it via metaprogramming.

In Lib/mailbox.py it seems to be using it like an ordered mapping:

key_list[key_list.index(old)] = new

and

del key_list[key_list.index(key)]

In Lib/http/cookiejar.py, seems to be used to get the next month:

mon = MONTHS_LOWER.index(mon.lower())+1

In Lib/tarfile.py similar to distutils to get a slice up to an item:

members = members[:members.index(tarinfo)]

In Lib/pickletools.py:

numtopop = before.index(markobject)

What these usages seem to have in common is that they seem to operate on lists of constrained sizes (important because of O(n) lookup time for list.index), and they're mostly used in parsing (and UI in the case of Idle).

While there are use-cases for it, they are fairly uncommon. If you find yourself looking for this answer, ask yourself if what you're doing is the most direct usage of the tools provided by the language for your use-case.

When should I use mmap for file access?

mmap has the advantage when you have random access on big files. Another advantage is that you access it with memory operations (memcpy, pointer arithmetic), without bothering with the buffering. Normal I/O can sometimes be quite difficult when using buffers when you have structures bigger than your buffer. The code to handle that is often difficult to get right, mmap is generally easier. This said, there are certain traps when working with mmap. As people have already mentioned, mmap is quite costly to set up, so it is worth using only for a given size (varying from machine to machine).

For pure sequential accesses to the file, it is also not always the better solution, though an appropriate call to madvise can mitigate the problem.

You have to be careful with alignment restrictions of your architecture(SPARC, itanium), with read/write IO the buffers are often properly aligned and do not trap when dereferencing a casted pointer.

You also have to be careful that you do not access outside of the map. It can easily happen if you use string functions on your map, and your file does not contain a \0 at the end. It will work most of the time when your file size is not a multiple of the page size as the last page is filled with 0 (the mapped area is always in the size of a multiple of your page size).

Changing background colour of tr element on mouseover

Try it

<!- HTML -->
<tr onmouseover="mOvr(this,'#ffa');" onmouseout="mOut(this,'#FFF');">

<script>
function mOvr(src,clrOver) { 
  if (!src.contains(event.fromElement)) { 
  src.bgColor = clrOver; 
  } 
} 
function mOut(src,clrIn) { 
  if (!src.contains(event.toElement)) { 
  src.bgColor = clrIn; 
  } 
} 
</script>

Dynamically creating keys in a JavaScript associative array

All modern browsers support a Map, which is a key/value data structure. There are a couple of reasons that make using a Map better than Object:

  • An Object has a prototype, so there are default keys in the map.
  • The keys of an Object are strings, where they can be any value for a Map.
  • You can get the size of a Map easily while you have to keep track of size for an Object.

Example:

var myMap = new Map();

var keyObj = {},
    keyFunc = function () {},
    keyString = "a string";

myMap.set(keyString, "value associated with 'a string'");
myMap.set(keyObj, "value associated with keyObj");
myMap.set(keyFunc, "value associated with keyFunc");

myMap.size; // 3

myMap.get(keyString);    // "value associated with 'a string'"
myMap.get(keyObj);       // "value associated with keyObj"
myMap.get(keyFunc);      // "value associated with keyFunc"

If you want keys that are not referenced from other objects to be garbage collected, consider using a WeakMap instead of a Map.

ImportError: No Module named simplejson

Sometimes there is permission errors. Try:

sudo pip install simplejson

Hope it helps.

dispatch_after - GCD in Swift?

In Swift 5, use in the below:

 DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: closure) 

// time gap, specify unit is second
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2)) {
            Singleton.shared().printDate()
        }
// default time gap is second, you can reduce it
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
          // just do it!
    }

Response::json() - Laravel 5.1

From a controller you can also return an Object/Array and it will be sent as a JSON response (including the correct HTTP headers).

public function show($id)
{
    return Customer::find($id);
}

How to open a new tab in GNOME Terminal from command line?

Just in case, you want to open

  • a new window
  • with two tabs
  • and executing command in there
  • and having them stay open...

here you go:

gnome-terminal --geometry=73x16+0+0 --window \
  --working-directory=/depot --title='A' --command="bash -c ls;bash" \
  --tab --working-directory=/depot/kn --title='B' --command="bash -c ls;bash"

(same for mate-terminal btw.)

How to get the bluetooth devices as a list?

I tried the below code,

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
<TextView 
    android:id="@+id/bluetoothstate" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    />
<Button
    android:id="@+id/listpaireddevices" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    android:text="List Paired Devices" 
    android:enabled="false"
    /> 
<TextView
    android:id="@+id/bluetoothstate" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    />

ListPairedDevicesActivity.java

import java.util.Set;

import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ListPairedDevicesActivity extends ListActivity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);

  ArrayAdapter<String> btArrayAdapter 
    = new ArrayAdapter<String>(this,
             android.R.layout.simple_list_item_1);

  BluetoothAdapter bluetoothAdapter 
   = BluetoothAdapter.getDefaultAdapter();
  Set<BluetoothDevice> pairedDevices 
   = bluetoothAdapter.getBondedDevices();

  if (pairedDevices.size() > 0) {
      for (BluetoothDevice device : pairedDevices) {
       String deviceBTName = device.getName();
       String deviceBTMajorClass 
        = getBTMajorDeviceClass(device
          .getBluetoothClass()
          .getMajorDeviceClass());
       btArrayAdapter.add(deviceBTName + "\n" 
         + deviceBTMajorClass);
      }
  }
  setListAdapter(btArrayAdapter);

 }

 private String getBTMajorDeviceClass(int major){
  switch(major){ 
  case BluetoothClass.Device.Major.AUDIO_VIDEO:
   return "AUDIO_VIDEO";
  case BluetoothClass.Device.Major.COMPUTER:
   return "COMPUTER";
  case BluetoothClass.Device.Major.HEALTH:
   return "HEALTH";
  case BluetoothClass.Device.Major.IMAGING:
   return "IMAGING"; 
  case BluetoothClass.Device.Major.MISC:
   return "MISC";
  case BluetoothClass.Device.Major.NETWORKING:
   return "NETWORKING"; 
  case BluetoothClass.Device.Major.PERIPHERAL:
   return "PERIPHERAL";
  case BluetoothClass.Device.Major.PHONE:
   return "PHONE";
  case BluetoothClass.Device.Major.TOY:
   return "TOY";
  case BluetoothClass.Device.Major.UNCATEGORIZED:
   return "UNCATEGORIZED";
  case BluetoothClass.Device.Major.WEARABLE:
   return "AUDIO_VIDEO";
  default: return "unknown!";
  }
 }

 @Override
 protected void onListItemClick(ListView l, View v, int position, long id) {
  // TODO Auto-generated method stub
  super.onListItemClick(l, v, position, id);

     Intent intent = new Intent();
     setResult(RESULT_OK, intent);
     finish();
 }

}

AndroidBluetooth.java

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class AndroidBluetooth extends Activity {

 private static final int REQUEST_ENABLE_BT = 1;
 private static final int REQUEST_PAIRED_DEVICE = 2;

    /** Called when the activity is first created. */
 Button btnListPairedDevices;
 TextView stateBluetooth;
 BluetoothAdapter bluetoothAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btnListPairedDevices = (Button)findViewById(R.id.listpaireddevices);

        stateBluetooth = (TextView)findViewById(R.id.bluetoothstate);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        CheckBlueToothState();

        btnListPairedDevices.setOnClickListener(btnListPairedDevicesOnClickListener);
    }

    private void CheckBlueToothState(){
     if (bluetoothAdapter == null){
         stateBluetooth.setText("Bluetooth NOT support");
        }else{
         if (bluetoothAdapter.isEnabled()){
          if(bluetoothAdapter.isDiscovering()){
           stateBluetooth.setText("Bluetooth is currently in device discovery process.");
          }else{
           stateBluetooth.setText("Bluetooth is Enabled.");
           btnListPairedDevices.setEnabled(true);
          }
         }else{
          stateBluetooth.setText("Bluetooth is NOT Enabled!");
          Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
             startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
         }
        }
    }

    private Button.OnClickListener btnListPairedDevicesOnClickListener
    = new Button.OnClickListener(){

  @Override
  public void onClick(View arg0) {
   // TODO Auto-generated method stub
   Intent intent = new Intent();
   intent.setClass(AndroidBluetooth.this, ListPairedDevicesActivity.class);
   startActivityForResult(intent, REQUEST_PAIRED_DEVICE); 
  }};

 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  // TODO Auto-generated method stub
  if(requestCode == REQUEST_ENABLE_BT){
   CheckBlueToothState();
  }if (requestCode == REQUEST_PAIRED_DEVICE){
   if(resultCode == RESULT_OK){

   }
  } 
 }   
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.test.AndroidBluetooth"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="7" />
    <uses-permission android:name="android.permission.BLUETOOTH"></uses-permission>

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AndroidBluetooth"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
  <activity android:name=".ListPairedDevicesActivity" 
      android:label="AndroidBluetooth: List of Paired Devices"/>
    </application>
</manifest>

What does the 'u' symbol mean in front of string values?

The 'u' in front of the string values means the string is a Unicode string. Unicode is a way to represent more characters than normal ASCII can manage. The fact that you're seeing the u means you're on Python 2 - strings are Unicode by default on Python 3, but on Python 2, the u in front distinguishes Unicode strings. The rest of this answer will focus on Python 2.

You can create a Unicode string multiple ways:

>>> u'foo'
u'foo'
>>> unicode('foo') # Python 2 only
u'foo'

But the real reason is to represent something like this (translation here):

>>> val = u'???????????? ? ?????????????'
>>> val
u'\u041e\u0437\u043d\u0430\u043a\u043e\u043c\u044c\u0442\u0435\u0441\u044c \u0441 \u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u0430\u0446\u0438\u0435\u0439'
>>> print val
???????????? ? ?????????????

For the most part, Unicode and non-Unicode strings are interoperable on Python 2.

There are other symbols you will see, such as the "raw" symbol r for telling a string not to interpret backslashes. This is extremely useful for writing regular expressions.

>>> 'foo\"'
'foo"'
>>> r'foo\"'
'foo\\"'

Unicode and non-Unicode strings can be equal on Python 2:

>>> bird1 = unicode('unladen swallow')
>>> bird2 = 'unladen swallow'
>>> bird1 == bird2
True

but not on Python 3:

>>> x = u'asdf' # Python 3
>>> y = b'asdf' # b indicates bytestring
>>> x == y
False

assign multiple variables to the same value in Javascript

The original variables you listed can be declared and assigned to the same value in a short line of code using destructuring assignment. The keywords let, const, and var can all be used for this type of assignment.

let [moveUp, moveDown, moveLeft, moveRight, mouseDown, touchDown] = Array(6).fill(false);

How to generate xsd from wsdl

Once I found an xsd link on the top of the wsdl. Like this wsdl example from the web, you can see a link xsd1. The server has to be running to see it.

<?xml version="1.0"?>
<definitions name="StockQuote"
             targetNamespace="http://example.com/stockquote.wsdl"
             xmlns:tns="http://example.com/stockquote.wsdl"
             xmlns:xsd1="http://example.com/stockquote.xsd"
             xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
             xmlns="http://schemas.xmlsoap.org/wsdl/">

How to use global variable in node.js?

Global variables can be used in Node when used wisely.

Declaration of global variables in Node:

a = 10;
GLOBAL.a = 10;
global.a = 10;

All of the above commands the same actions with different syntaxes.

Use global variables when they are not about to be changed

Here an example of something that can happen when using global variables:

// app.js
a = 10; // no var or let or const means global

// users.js
app.get("/users", (req, res, next) => {
   res.send(a); // 10;
});

// permissions.js
app.get("/permissions", (req, res, next) => {
   a = 11; // notice that there is no previous declaration of a in the permissions.js, means we looking for the global instance of a.
   res.send(a); // 11;
});

Explained:

Run users route first and receive 10;

Then run permissions route and receive 11;

Then run again the users route and receive 11 as well instead of 10;

Global variables can be overtaken!

Now think about using express and assignin res object as global.. And you end up with async error become corrupt and server is shuts down.

When to use global vars?

As I said - when var is not about to be changed. Anyways it's more recommended that you will be using the process.env object from the config file.

Integer to hex string in C++

Use std::stringstream to convert integers into strings and its special manipulators to set the base. For example like that:

std::stringstream sstream;
sstream << std::hex << my_integer;
std::string result = sstream.str();

Can anyone explain me StandardScaler?

We apply StandardScalar() on a row basis.

So, for each row in a column (I am assuming that you are working with a Pandas DataFrame):

x_new = (x_original - mean_of_distribution) / std_of_distribution

Few points -

  1. It is called Standard Scalar as we are dividing it by the standard deviation of the distribution (distr. of the feature). Similarly, you can guess for MinMaxScalar().

  2. The original distribution remains the same after applying StandardScalar(). It is a common misconception that the distribution gets changed to a Normal Distribution. We are just squashing the range into [0, 1].

Passing parameters in Javascript onClick event

It is probably better to create a dedicated function to create the link so you can avoid creating two anonymous functions. Thus:

<div id="div"></div>

<script>
  function getLink(id)
  {
    var link = document.createElement('a');
    link.setAttribute('href', '#');
    link.innerHTML = id;
    link.onclick = function()
    {
      onClickLink(id);
    };
    link.style.display = 'block';
    return link;
  }
  var div = document.getElementById('div');
  for (var i = 0; i < 10; i += 1)
  {
    div.appendChild(getLink(i.toString()));
  }
</script>

Although in both cases you end up with two functions, I just think it is better to wrap it in a function that is semantically easier to comprehend.

What is a good Hash Function?

What you're saying here is you want to have one that uses has collision resistance. Try using SHA-2. Or try using a (good) block cipher in a one way compression function (never tried that before), like AES in Miyaguchi-Preenel mode. The problem with that is that you need to:

1) have an IV. Try using the first 256 bits of the fractional parts of Khinchin's constant or something like that. 2) have a padding scheme. Easy. Barrow it from a hash like MD5 or SHA-3 (Keccak [pronounced 'ket-chak']). If you don't care about the security (a few others said this), look at FNV or lookup2 by Bob Jenkins (actually I'm the first one who reccomends lookup2) Also try MurmurHash, it's fast (check this: .16 cpb).

Does JSON syntax allow duplicate keys in an object?

According to RFC-7159, the current standard for JSON published by the Internet Engineering Task Force (IETF), states "The names within an object SHOULD be unique". However, according to RFC-2119 which defines the terminology used in IETF documents, the word "should" in fact means "... there may exist valid reasons in particular circumstances to ignore a particular item, but the full implications must be understood and carefully weighed before choosing a different course." What this essentially means is that while having unique keys is recommended, it is not a must. We can have duplicate keys in a JSON object, and it would still be valid.

From practical application, I have seen the value from the last key is considered when duplicate keys are found in a JSON.

Create intermediate folders if one doesn't exist

A nice Java 7+ answer from Benoit Blanchon can be found here:

With Java 7, you can use Files.createDirectories().

For instance:

Files.createDirectories(Paths.get("/path/to/directory"));

Android - How to decode and decompile any APK file?

You can try this website http://www.decompileandroid.com Just upload the .apk file and rest of it will be done by this site.

How to replace NA values in a table for selected columns

this works fine for me

DataTable DT = new DataTable();

DT = DT.AsEnumerable().Select(R =>
{
      R["Campo1"] = valor;
      return (R);
}).ToArray().CopyToDataTable();

Upgrade python without breaking yum

I read a piece with a comment that states the following commands can be run now. I have not tested myself so be careful.

$ yum install -y epel-release
$ yum install -y python36

How to check if a row exists in MySQL? (i.e. check if an email exists in MySQL)

The following are tried, tested and proven methods to check if a row exists.

(Some of which I use myself, or have used in the past).

Edit: I made an previous error in my syntax where I used mysqli_query() twice. Please consult the revision(s).

I.e.:

if (!mysqli_query($con,$query)) which should have simply read as if (!$query).

  • I apologize for overlooking that mistake.

Side note: Both '".$var."' and '$var' do the same thing. You can use either one, both are valid syntax.

Here are the two edited queries:

$query = mysqli_query($con, "SELECT * FROM emails WHERE email='".$email."'");

    if (!$query)
    {
        die('Error: ' . mysqli_error($con));
    }

if(mysqli_num_rows($query) > 0){

    echo "email already exists";

}else{

    // do something

}

and in your case:

$query = mysqli_query($dbl, "SELECT * FROM `tblUser` WHERE email='".$email."'");

    if (!$query)
    {
        die('Error: ' . mysqli_error($dbl));
    }

if(mysqli_num_rows($query) > 0){

    echo "email already exists";

}else{

    // do something

}

You can also use mysqli_ with a prepared statement method:

$query = "SELECT `email` FROM `tblUser` WHERE email=?";

if ($stmt = $dbl->prepare($query)){

        $stmt->bind_param("s", $email);

        if($stmt->execute()){
            $stmt->store_result();

            $email_check= "";         
            $stmt->bind_result($email_check);
            $stmt->fetch();

            if ($stmt->num_rows == 1){

            echo "That Email already exists.";
            exit;

            }
        }
    }

Or a PDO method with a prepared statement:

<?php
$email = $_POST['email'];

$mysql_hostname = 'xxx';
$mysql_username = 'xxx';
$mysql_password = 'xxx';
$mysql_dbname = 'xxx';

try {
$conn= new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password); 
     $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
     exit( $e->getMessage() );
}

// assuming a named submit button
if(isset($_POST['submit']))
    {

        try {
            $stmt = $conn->prepare('SELECT `email` FROM `tblUser` WHERE email = ?');
            $stmt->bindParam(1, $_POST['email']); 
            $stmt->execute();
            while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

            }
        }
        catch(PDOException $e) {
            echo 'ERROR: ' . $e->getMessage();
        }

    if($stmt->rowCount() > 0){
        echo "The record exists!";
    } else {
        echo "The record is non-existant.";
    }


    }
?>
  • Prepared statements are best to be used to help protect against an SQL injection.

N.B.:

When dealing with forms and POST arrays as used/outlined above, make sure that the POST arrays contain values, that a POST method is used for the form and matching named attributes for the inputs.

  • FYI: Forms default to a GET method if not explicity instructed.

Note: <input type = "text" name = "var"> - $_POST['var'] match. $_POST['Var'] no match.

  • POST arrays are case-sensitive.

Consult:

Error checking references:

Please note that MySQL APIs do not intermix, in case you may be visiting this Q&A and you're using mysql_ to connect with (and querying with).

  • You must use the same one from connecting to querying.

Consult the following about this:

If you are using the mysql_ API and have no choice to work with it, then consult the following Q&A on Stack:

The mysql_* functions are deprecated and will be removed from future PHP releases.

  • It's time to step into the 21st century.

You can also add a UNIQUE constraint to (a) row(s).

References:

Why are my PHP files showing as plain text?

You will need to add handlers in Apache to handle php code.

Edit by command sudo vi /etc/httpd/conf/httpd.conf

Add these two handlers

  AddType application/x-httpd-php .php
  AddType application/x-httpd-php .php3

at position specified below

<IfModule mime_module>

 AddType application/x-compress .Z
 AddType application/x-gzip .gz .tgz

--Add Here--


</IfModule>

for more details on AddType handlers

http://httpd.apache.org/docs/2.2/mod/mod_mime.html

What is the use of the %n format specifier in C?

It will store value of number of characters printed so far in that printf() function.

Example:

int a;
printf("Hello World %n \n", &a);
printf("Characters printed so far = %d",a);

The output of this program will be

Hello World
Characters printed so far = 12

Exiting from python Command Line

This message is the __str__ attribute of exit

look at these examples :

1

>>> print exit
Use exit() or Ctrl-D (i.e. EOF) to exit

2

>>> exit.__str__()
'Use exit() or Ctrl-D (i.e. EOF) to exit'

3

>>> getattr(exit, '__str__')()
'Use exit() or Ctrl-D (i.e. EOF) to exit'

How to detect the character encoding of a text file?

If you want to pursue a "simple" solution, you might find this class I put together useful:

http://www.architectshack.com/TextFileEncodingDetector.ashx

It does the BOM detection automatically first, and then tries to differentiate between Unicode encodings without BOM, vs some other default encoding (generally Windows-1252, incorrectly labelled as Encoding.ASCII in .Net).

As noted above, a "heavier" solution involving NCharDet or MLang may be more appropriate, and as I note on the overview page of this class, the best is to provide some form of interactivity with the user if at all possible, because there simply is no 100% detection rate possible!

Snippet in case the site is offline:

using System;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;

namespace KlerksSoft
{
    public static class TextFileEncodingDetector
    {
        /*
         * Simple class to handle text file encoding woes (in a primarily English-speaking tech 
         *      world).
         * 
         *  - This code is fully managed, no shady calls to MLang (the unmanaged codepage
         *      detection library originally developed for Internet Explorer).
         * 
         *  - This class does NOT try to detect arbitrary codepages/charsets, it really only
         *      aims to differentiate between some of the most common variants of Unicode 
         *      encoding, and a "default" (western / ascii-based) encoding alternative provided
         *      by the caller.
         *      
         *  - As there is no "Reliable" way to distinguish between UTF-8 (without BOM) and 
         *      Windows-1252 (in .Net, also incorrectly called "ASCII") encodings, we use a 
         *      heuristic - so the more of the file we can sample the better the guess. If you 
         *      are going to read the whole file into memory at some point, then best to pass 
         *      in the whole byte byte array directly. Otherwise, decide how to trade off 
         *      reliability against performance / memory usage.
         *      
         *  - The UTF-8 detection heuristic only works for western text, as it relies on 
         *      the presence of UTF-8 encoded accented and other characters found in the upper 
         *      ranges of the Latin-1 and (particularly) Windows-1252 codepages.
         *  
         *  - For more general detection routines, see existing projects / resources:
         *    - MLang - Microsoft library originally for IE6, available in Windows XP and later APIs now (I think?)
         *      - MLang .Net bindings: http://www.codeproject.com/KB/recipes/DetectEncoding.aspx
         *    - CharDet - Mozilla browser's detection routines
         *      - Ported to Java then .Net: http://www.conceptdevelopment.net/Localization/NCharDet/
         *      - Ported straight to .Net: http://code.google.com/p/chardetsharp/source/browse
         *  
         * Copyright Tao Klerks, 2010-2012, [email protected]
         * Licensed under the modified BSD license:
         * 
Redistribution and use in source and binary forms, with or without modification, are 
permitted provided that the following conditions are met:
 - Redistributions of source code must retain the above copyright notice, this list of 
conditions and the following disclaimer.
 - Redistributions in binary form must reproduce the above copyright notice, this list 
of conditions and the following disclaimer in the documentation and/or other materials
provided with the distribution.
 - The name of the author may not be used to endorse or promote products derived from 
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, 
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY 
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY 
OF SUCH DAMAGE.
         * 
         * CHANGELOG:
         *  - 2012-02-03: 
         *    - Simpler methods, removing the silly "DefaultEncoding" parameter (with "??" operator, saves no typing)
         *    - More complete methods
         *      - Optionally return indication of whether BOM was found in "Detect" methods
         *      - Provide straight-to-string method for byte arrays (GetStringFromByteArray)
         */

        const long _defaultHeuristicSampleSize = 0x10000; //completely arbitrary - inappropriate for high numbers of files / high speed requirements

        public static Encoding DetectTextFileEncoding(string InputFilename)
        {
            using (FileStream textfileStream = File.OpenRead(InputFilename))
            {
                return DetectTextFileEncoding(textfileStream, _defaultHeuristicSampleSize);
            }
        }

        public static Encoding DetectTextFileEncoding(FileStream InputFileStream, long HeuristicSampleSize)
        {
            bool uselessBool = false;
            return DetectTextFileEncoding(InputFileStream, _defaultHeuristicSampleSize, out uselessBool);
        }

        public static Encoding DetectTextFileEncoding(FileStream InputFileStream, long HeuristicSampleSize, out bool HasBOM)
        {
            if (InputFileStream == null)
                throw new ArgumentNullException("Must provide a valid Filestream!", "InputFileStream");

            if (!InputFileStream.CanRead)
                throw new ArgumentException("Provided file stream is not readable!", "InputFileStream");

            if (!InputFileStream.CanSeek)
                throw new ArgumentException("Provided file stream cannot seek!", "InputFileStream");

            Encoding encodingFound = null;

            long originalPos = InputFileStream.Position;

            InputFileStream.Position = 0;


            //First read only what we need for BOM detection
            byte[] bomBytes = new byte[InputFileStream.Length > 4 ? 4 : InputFileStream.Length];
            InputFileStream.Read(bomBytes, 0, bomBytes.Length);

            encodingFound = DetectBOMBytes(bomBytes);

            if (encodingFound != null)
            {
                InputFileStream.Position = originalPos;
                HasBOM = true;
                return encodingFound;
            }


            //BOM Detection failed, going for heuristics now.
            //  create sample byte array and populate it
            byte[] sampleBytes = new byte[HeuristicSampleSize > InputFileStream.Length ? InputFileStream.Length : HeuristicSampleSize];
            Array.Copy(bomBytes, sampleBytes, bomBytes.Length);
            if (InputFileStream.Length > bomBytes.Length)
                InputFileStream.Read(sampleBytes, bomBytes.Length, sampleBytes.Length - bomBytes.Length);
            InputFileStream.Position = originalPos;

            //test byte array content
            encodingFound = DetectUnicodeInByteSampleByHeuristics(sampleBytes);

            HasBOM = false;
            return encodingFound;
        }

        public static Encoding DetectTextByteArrayEncoding(byte[] TextData)
        {
            bool uselessBool = false;
            return DetectTextByteArrayEncoding(TextData, out uselessBool);
        }

        public static Encoding DetectTextByteArrayEncoding(byte[] TextData, out bool HasBOM)
        {
            if (TextData == null)
                throw new ArgumentNullException("Must provide a valid text data byte array!", "TextData");

            Encoding encodingFound = null;

            encodingFound = DetectBOMBytes(TextData);

            if (encodingFound != null)
            {
                HasBOM = true;
                return encodingFound;
            }
            else
            {
                //test byte array content
                encodingFound = DetectUnicodeInByteSampleByHeuristics(TextData);

                HasBOM = false;
                return encodingFound;
            }
        }

        public static string GetStringFromByteArray(byte[] TextData, Encoding DefaultEncoding)
        {
            return GetStringFromByteArray(TextData, DefaultEncoding, _defaultHeuristicSampleSize);
        }

        public static string GetStringFromByteArray(byte[] TextData, Encoding DefaultEncoding, long MaxHeuristicSampleSize)
        {
            if (TextData == null)
                throw new ArgumentNullException("Must provide a valid text data byte array!", "TextData");

            Encoding encodingFound = null;

            encodingFound = DetectBOMBytes(TextData);

            if (encodingFound != null)
            {
                //For some reason, the default encodings don't detect/swallow their own preambles!!
                return encodingFound.GetString(TextData, encodingFound.GetPreamble().Length, TextData.Length - encodingFound.GetPreamble().Length);
            }
            else
            {
                byte[] heuristicSample = null;
                if (TextData.Length > MaxHeuristicSampleSize)
                {
                    heuristicSample = new byte[MaxHeuristicSampleSize];
                    Array.Copy(TextData, heuristicSample, MaxHeuristicSampleSize);
                }
                else
                {
                    heuristicSample = TextData;
                }

                encodingFound = DetectUnicodeInByteSampleByHeuristics(TextData) ?? DefaultEncoding;
                return encodingFound.GetString(TextData);
            }
        }


        public static Encoding DetectBOMBytes(byte[] BOMBytes)
        {
            if (BOMBytes == null)
                throw new ArgumentNullException("Must provide a valid BOM byte array!", "BOMBytes");

            if (BOMBytes.Length < 2)
                return null;

            if (BOMBytes[0] == 0xff 
                && BOMBytes[1] == 0xfe 
                && (BOMBytes.Length < 4 
                    || BOMBytes[2] != 0 
                    || BOMBytes[3] != 0
                    )
                )
                return Encoding.Unicode;

            if (BOMBytes[0] == 0xfe 
                && BOMBytes[1] == 0xff
                )
                return Encoding.BigEndianUnicode;

            if (BOMBytes.Length < 3)
                return null;

            if (BOMBytes[0] == 0xef && BOMBytes[1] == 0xbb && BOMBytes[2] == 0xbf)
                return Encoding.UTF8;

            if (BOMBytes[0] == 0x2b && BOMBytes[1] == 0x2f && BOMBytes[2] == 0x76)
                return Encoding.UTF7;

            if (BOMBytes.Length < 4)
                return null;

            if (BOMBytes[0] == 0xff && BOMBytes[1] == 0xfe && BOMBytes[2] == 0 && BOMBytes[3] == 0)
                return Encoding.UTF32;

            if (BOMBytes[0] == 0 && BOMBytes[1] == 0 && BOMBytes[2] == 0xfe && BOMBytes[3] == 0xff)
                return Encoding.GetEncoding(12001);

            return null;
        }

        public static Encoding DetectUnicodeInByteSampleByHeuristics(byte[] SampleBytes)
        {
            long oddBinaryNullsInSample = 0;
            long evenBinaryNullsInSample = 0;
            long suspiciousUTF8SequenceCount = 0;
            long suspiciousUTF8BytesTotal = 0;
            long likelyUSASCIIBytesInSample = 0;

            //Cycle through, keeping count of binary null positions, possible UTF-8 
            //  sequences from upper ranges of Windows-1252, and probable US-ASCII 
            //  character counts.

            long currentPos = 0;
            int skipUTF8Bytes = 0;

            while (currentPos < SampleBytes.Length)
            {
                //binary null distribution
                if (SampleBytes[currentPos] == 0)
                {
                    if (currentPos % 2 == 0)
                        evenBinaryNullsInSample++;
                    else
                        oddBinaryNullsInSample++;
                }

                //likely US-ASCII characters
                if (IsCommonUSASCIIByte(SampleBytes[currentPos]))
                    likelyUSASCIIBytesInSample++;

                //suspicious sequences (look like UTF-8)
                if (skipUTF8Bytes == 0)
                {
                    int lengthFound = DetectSuspiciousUTF8SequenceLength(SampleBytes, currentPos);

                    if (lengthFound > 0)
                    {
                        suspiciousUTF8SequenceCount++;
                        suspiciousUTF8BytesTotal += lengthFound;
                        skipUTF8Bytes = lengthFound - 1;
                    }
                }
                else
                {
                    skipUTF8Bytes--;
                }

                currentPos++;
            }

            //1: UTF-16 LE - in english / european environments, this is usually characterized by a 
            //  high proportion of odd binary nulls (starting at 0), with (as this is text) a low 
            //  proportion of even binary nulls.
            //  The thresholds here used (less than 20% nulls where you expect non-nulls, and more than
            //  60% nulls where you do expect nulls) are completely arbitrary.

            if (((evenBinaryNullsInSample * 2.0) / SampleBytes.Length) < 0.2 
                && ((oddBinaryNullsInSample * 2.0) / SampleBytes.Length) > 0.6
                )
                return Encoding.Unicode;


            //2: UTF-16 BE - in english / european environments, this is usually characterized by a 
            //  high proportion of even binary nulls (starting at 0), with (as this is text) a low 
            //  proportion of odd binary nulls.
            //  The thresholds here used (less than 20% nulls where you expect non-nulls, and more than
            //  60% nulls where you do expect nulls) are completely arbitrary.

            if (((oddBinaryNullsInSample * 2.0) / SampleBytes.Length) < 0.2 
                && ((evenBinaryNullsInSample * 2.0) / SampleBytes.Length) > 0.6
                )
                return Encoding.BigEndianUnicode;


            //3: UTF-8 - Martin Dürst outlines a method for detecting whether something CAN be UTF-8 content 
            //  using regexp, in his w3c.org unicode FAQ entry: 
            //  http://www.w3.org/International/questions/qa-forms-utf-8
            //  adapted here for C#.
            string potentiallyMangledString = Encoding.ASCII.GetString(SampleBytes);
            Regex UTF8Validator = new Regex(@"\A(" 
                + @"[\x09\x0A\x0D\x20-\x7E]"
                + @"|[\xC2-\xDF][\x80-\xBF]"
                + @"|\xE0[\xA0-\xBF][\x80-\xBF]"
                + @"|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}"
                + @"|\xED[\x80-\x9F][\x80-\xBF]"
                + @"|\xF0[\x90-\xBF][\x80-\xBF]{2}"
                + @"|[\xF1-\xF3][\x80-\xBF]{3}"
                + @"|\xF4[\x80-\x8F][\x80-\xBF]{2}"
                + @")*\z");
            if (UTF8Validator.IsMatch(potentiallyMangledString))
            {
                //Unfortunately, just the fact that it CAN be UTF-8 doesn't tell you much about probabilities.
                //If all the characters are in the 0-127 range, no harm done, most western charsets are same as UTF-8 in these ranges.
                //If some of the characters were in the upper range (western accented characters), however, they would likely be mangled to 2-byte by the UTF-8 encoding process.
                // So, we need to play stats.

                // The "Random" likelihood of any pair of randomly generated characters being one 
                //   of these "suspicious" character sequences is:
                //     128 / (256 * 256) = 0.2%.
                //
                // In western text data, that is SIGNIFICANTLY reduced - most text data stays in the <127 
                //   character range, so we assume that more than 1 in 500,000 of these character 
                //   sequences indicates UTF-8. The number 500,000 is completely arbitrary - so sue me.
                //
                // We can only assume these character sequences will be rare if we ALSO assume that this
                //   IS in fact western text - in which case the bulk of the UTF-8 encoded data (that is 
                //   not already suspicious sequences) should be plain US-ASCII bytes. This, I 
                //   arbitrarily decided, should be 80% (a random distribution, eg binary data, would yield 
                //   approx 40%, so the chances of hitting this threshold by accident in random data are 
                //   VERY low). 

                if ((suspiciousUTF8SequenceCount * 500000.0 / SampleBytes.Length >= 1) //suspicious sequences
                    && (
                           //all suspicious, so cannot evaluate proportion of US-Ascii
                           SampleBytes.Length - suspiciousUTF8BytesTotal == 0 
                           ||
                           likelyUSASCIIBytesInSample * 1.0 / (SampleBytes.Length - suspiciousUTF8BytesTotal) >= 0.8
                       )
                    )
                    return Encoding.UTF8;
            }

            return null;
        }

        private static bool IsCommonUSASCIIByte(byte testByte)
        {
            if (testByte == 0x0A //lf
                || testByte == 0x0D //cr
                || testByte == 0x09 //tab
                || (testByte >= 0x20 && testByte <= 0x2F) //common punctuation
                || (testByte >= 0x30 && testByte <= 0x39) //digits
                || (testByte >= 0x3A && testByte <= 0x40) //common punctuation
                || (testByte >= 0x41 && testByte <= 0x5A) //capital letters
                || (testByte >= 0x5B && testByte <= 0x60) //common punctuation
                || (testByte >= 0x61 && testByte <= 0x7A) //lowercase letters
                || (testByte >= 0x7B && testByte <= 0x7E) //common punctuation
                )
                return true;
            else
                return false;
        }

        private static int DetectSuspiciousUTF8SequenceLength(byte[] SampleBytes, long currentPos)
        {
            int lengthFound = 0;

            if (SampleBytes.Length >= currentPos + 1 
                && SampleBytes[currentPos] == 0xC2
                )
            {
                if (SampleBytes[currentPos + 1] == 0x81 
                    || SampleBytes[currentPos + 1] == 0x8D 
                    || SampleBytes[currentPos + 1] == 0x8F
                    )
                    lengthFound = 2;
                else if (SampleBytes[currentPos + 1] == 0x90 
                    || SampleBytes[currentPos + 1] == 0x9D
                    )
                    lengthFound = 2;
                else if (SampleBytes[currentPos + 1] >= 0xA0 
                    && SampleBytes[currentPos + 1] <= 0xBF
                    )
                    lengthFound = 2;
            }
            else if (SampleBytes.Length >= currentPos + 1 
                && SampleBytes[currentPos] == 0xC3
                )
            {
                if (SampleBytes[currentPos + 1] >= 0x80 
                    && SampleBytes[currentPos + 1] <= 0xBF
                    )
                    lengthFound = 2;
            }
            else if (SampleBytes.Length >= currentPos + 1 
                && SampleBytes[currentPos] == 0xC5
                )
            {
                if (SampleBytes[currentPos + 1] == 0x92 
                    || SampleBytes[currentPos + 1] == 0x93
                    )
                    lengthFound = 2;
                else if (SampleBytes[currentPos + 1] == 0xA0 
                    || SampleBytes[currentPos + 1] == 0xA1
                    )
                    lengthFound = 2;
                else if (SampleBytes[currentPos + 1] == 0xB8 
                    || SampleBytes[currentPos + 1] == 0xBD 
                    || SampleBytes[currentPos + 1] == 0xBE
                    )
                    lengthFound = 2;
            }
            else if (SampleBytes.Length >= currentPos + 1 
                && SampleBytes[currentPos] == 0xC6
                )
            {
                if (SampleBytes[currentPos + 1] == 0x92)
                    lengthFound = 2;
            }
            else if (SampleBytes.Length >= currentPos + 1 
                && SampleBytes[currentPos] == 0xCB
                )
            {
                if (SampleBytes[currentPos + 1] == 0x86 
                    || SampleBytes[currentPos + 1] == 0x9C
                    )
                    lengthFound = 2;
            }
            else if (SampleBytes.Length >= currentPos + 2 
                && SampleBytes[currentPos] == 0xE2
                )
            {
                if (SampleBytes[currentPos + 1] == 0x80)
                {
                    if (SampleBytes[currentPos + 2] == 0x93 
                        || SampleBytes[currentPos + 2] == 0x94
                        )
                        lengthFound = 3;
                    if (SampleBytes[currentPos + 2] == 0x98 
                        || SampleBytes[currentPos + 2] == 0x99 
                        || SampleBytes[currentPos + 2] == 0x9A
                        )
                        lengthFound = 3;
                    if (SampleBytes[currentPos + 2] == 0x9C 
                        || SampleBytes[currentPos + 2] == 0x9D 
                        || SampleBytes[currentPos + 2] == 0x9E
                        )
                        lengthFound = 3;
                    if (SampleBytes[currentPos + 2] == 0xA0 
                        || SampleBytes[currentPos + 2] == 0xA1 
                        || SampleBytes[currentPos + 2] == 0xA2
                        )
                        lengthFound = 3;
                    if (SampleBytes[currentPos + 2] == 0xA6)
                        lengthFound = 3;
                    if (SampleBytes[currentPos + 2] == 0xB0)
                        lengthFound = 3;
                    if (SampleBytes[currentPos + 2] == 0xB9 
                        || SampleBytes[currentPos + 2] == 0xBA
                        )
                        lengthFound = 3;
                }
                else if (SampleBytes[currentPos + 1] == 0x82 
                    && SampleBytes[currentPos + 2] == 0xAC
                    )
                    lengthFound = 3;
                else if (SampleBytes[currentPos + 1] == 0x84 
                    && SampleBytes[currentPos + 2] == 0xA2
                    )
                    lengthFound = 3;
            }

            return lengthFound;
        }

    }
}

Multiple bluetooth connection

Yes, your device can simultaneously connect to 7 other Bluetooth devices at the same time, in theory. Such a connection is called a piconet. A more complex connection pattern is the scatternet.

The reason it is limited to 7 other devices is because the assigned bit field for LT_ADDR in L2CAP protocol is only 3.

How to process images of a video, frame by frame, in video streaming using OpenCV and Python

The only solution I have found is not to set the index to a previous frame and wait (then OpenCV stops reading frames, anyway), but to initialize the capture one more time. So, it looks like this:

cap = cv2.VideoCapture(camera_url)
while True:
    ret, frame = cap.read()

    if not ret:
        cap = cv.VideoCapture(camera_url)
        continue

    # do your processing here

And it works perfectly!

How to use pip with Python 3.x alongside Python 2.x

First, install Python 3 pip using:

sudo apt-get install python3-pip

Then, to use Python 3 pip use:

pip3 install <module-name>

For Python 2 pip use:

pip install <module-name>

How to get to a particular element in a List in java?

The toString method of array types in Java isn't particularly meaningful, other than telling you what that is an array of.

You can use java.util.Arrays.toString for that.

Or if your lines only contain numbers, and you want a line as 1,2,3,4... instead of [1, 2, 3, ...], you can use:

java.util.Arrays.toString(someArray).replaceAll("\\]| |\\[","")

How to filter data in dataview

Eg:

Datatable newTable =  new DataTable();

            foreach(string s1 in list)
            {
                if (s1 != string.Empty) {
                    dvProducts.RowFilter = "(CODE like '" + serachText + "*') AND (CODE <> '" + s1 + "')";
                    foreach(DataRow dr in dvProducts.ToTable().Rows)
                    {
                       newTable.ImportRow(dr);
                    }
                }
            }
ListView1.DataSource = newTable;
ListView1.DataBind();

How to git clone a specific tag

Use --single-branch option to only clone history leading to tip of the tag. This saves a lot of unnecessary code from being cloned.

git clone <repo_url> --branch <tag_name> --single-branch

JavaScript OR (||) variable assignment explanation

This is made to assign a default value, in this case the value of y, if the x variable is falsy.

The boolean operators in JavaScript can return an operand, and not always a boolean result as in other languages.

The Logical OR operator (||) returns the value of its second operand, if the first one is falsy, otherwise the value of the first operand is returned.

For example:

"foo" || "bar"; // returns "foo"
false || "bar"; // returns "bar"

Falsy values are those who coerce to false when used in boolean context, and they are 0, null, undefined, an empty string, NaN and of course false.

Converting DateTime format using razor

For all the given solution, when you try this in a modern browser (like FF), and you have set the correct model

// Model
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime Start { get; set; }

// View
<div class="form-group">
    @Html.LabelFor(model => model.Start, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.Start, "{0:dd-MM-yyyy}", new { htmlAttributes = new { @class = "form-control"} })
    </div>
</div>

mvc(5) wil render (the type of the input is set to date based on your date settings in your model!)

<div class="col-md-10">
<input class="form-control text-box single-line" data-val="true" data-val-date="The field Start must be a date." data-val-required="The Start field is required." id="Start" name="Start" value="01-05-2018" type="date">
        <span class="field-validation-valid text-danger" data-valmsg-for="Start" data-valmsg-replace="true"></span>
</div>

And the browser will show

enter image description here

To fix this you need to change the type to text instead of date (also if you want to use your custom calender)

@Html.EditorFor(model => model.Start, "{0:dd-MM-yyyy}", new { htmlAttributes = new { @class = "form-control", @type = "text" } })

How to simulate target="_blank" in JavaScript

You can extract the href from the a tag:

window.open(document.getElementById('redirect').href);

Change MySQL default character set to UTF-8 in my.cnf?

This question already has a lot of answers, but Mathias Bynens mentioned that 'utf8mb4' should be used instead of 'utf8' in order to have better UTF-8 support ('utf8' does not support 4 byte characters, fields are truncated on insert). I consider this to be an important difference. So here is yet another answer on how to set the default character set and collation. One that'll allow you to insert a pile of poo ().

This works on MySQL 5.5.35.

Note, that some of the settings may be optional. As I'm not entirely sure that I haven't forgotten anything, I'll make this answer a community wiki.

Old Settings

mysql> SHOW VARIABLES LIKE 'char%'; SHOW VARIABLES LIKE 'collation%';
+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | utf8                       |
| character_set_connection | utf8                       |
| character_set_database   | latin1                     |
| character_set_filesystem | binary                     |
| character_set_results    | utf8                       |
| character_set_server     | latin1                     |
| character_set_system     | utf8                       |
| character_sets_dir       | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.00 sec)

+----------------------+-------------------+
| Variable_name        | Value             |
+----------------------+-------------------+
| collation_connection | utf8_general_ci   |
| collation_database   | latin1_swedish_ci |
| collation_server     | latin1_swedish_ci |
+----------------------+-------------------+
3 rows in set (0.00 sec)

Config

#  
# UTF-8 should be used instead of Latin1. Obviously.
# NOTE "utf8" in MySQL is NOT full UTF-8: http://mathiasbynens.be/notes/mysql-utf8mb4

[client]
default-character-set = utf8mb4

[mysqld]
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci

[mysql]
default-character-set = utf8mb4

New Settings

mysql> SHOW VARIABLES LIKE 'char%'; SHOW VARIABLES LIKE 'collation%';
+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | utf8mb4                    |
| character_set_connection | utf8mb4                    |
| character_set_database   | utf8mb4                    |
| character_set_filesystem | binary                     |
| character_set_results    | utf8mb4                    |
| character_set_server     | utf8mb4                    |
| character_set_system     | utf8                       |
| character_sets_dir       | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.00 sec)

+----------------------+--------------------+
| Variable_name        | Value              |
+----------------------+--------------------+
| collation_connection | utf8mb4_general_ci |
| collation_database   | utf8mb4_unicode_ci |
| collation_server     | utf8mb4_unicode_ci |
+----------------------+--------------------+
3 rows in set (0.00 sec)

character_set_system is always utf8.

This won't affect existing tables, it's just the default setting (used for new tables). The following ALTER code can be used to convert an existing table (without the dump-restore workaround):

ALTER DATABASE databasename CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE tablename CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

Edit:

On a MySQL 5.0 server: character_set_client, character_set_connection, character_set_results, collation_connection remain at latin1. Issuing SET NAMES utf8 (utf8mb4 not available in that version) sets those to utf8 as well.


Caveat: If you had a utf8 table with an index column of type VARCHAR(255), it can't be converted in some cases, because the maximum key length is exceeded (Specified key was too long; max key length is 767 bytes.). If possible, reduce the column size from 255 to 191 (because 191 * 4 = 764 < 767 < 192 * 4 = 768). After that, the table can be converted.

Translating touch events from Javascript to jQuery

jQuery 'fixes up' events to account for browser differences. When it does so, you can always access the 'native' event with event.originalEvent (see the Special Properties subheading on this page).

Can we have multiple <tbody> in same <table>?

I have created a JSFiddle where I have two nested ng-repeats with tables, and the parent ng-repeat on tbody. If you inspect any row in the table, you will see there are six tbody elements, i.e. the parent level.

HTML

<div>
        <table class="table table-hover table-condensed table-striped">
            <thead>
                <tr>
                    <th>Store ID</th>
                    <th>Name</th>
                    <th>Address</th>
                    <th>City</th>
                    <th>Cost</th>
                    <th>Sales</th>
                    <th>Revenue</th>
                    <th>Employees</th>
                    <th>Employees H-sum</th>
                </tr>
            </thead>
            <tbody data-ng-repeat="storedata in storeDataModel.storedata">
                <tr id="storedata.store.storeId" class="clickableRow" title="Click to toggle collapse/expand day summaries for this store." data-ng-click="selectTableRow($index, storedata.store.storeId)">
                    <td>{{storedata.store.storeId}}</td>
                    <td>{{storedata.store.storeName}}</td>
                    <td>{{storedata.store.storeAddress}}</td>
                    <td>{{storedata.store.storeCity}}</td>
                    <td>{{storedata.data.costTotal}}</td>
                    <td>{{storedata.data.salesTotal}}</td>
                    <td>{{storedata.data.revenueTotal}}</td>
                    <td>{{storedata.data.averageEmployees}}</td>
                    <td>{{storedata.data.averageEmployeesHours}}</td>
                </tr>
                <tr data-ng-show="dayDataCollapse[$index]">
                    <td colspan="2">&nbsp;</td>
                    <td colspan="7">
                        <div>
                            <div class="pull-right">
                                <table class="table table-hover table-condensed table-striped">
                                    <thead>
                                        <tr>
                                            <th></th>
                                            <th>Date [YYYY-MM-dd]</th>
                                            <th>Cost</th>
                                            <th>Sales</th>
                                            <th>Revenue</th>
                                            <th>Employees</th>
                                            <th>Employees H-sum</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr data-ng-repeat="dayData in storeDataModel.storedata[$index].data.dayData">
                                            <td class="pullright">
                                                <button type="btn btn-small" title="Click to show transactions for this specific day..." data-ng-click=""><i class="icon-list"></i>
                                                </button>
                                            </td>
                                            <td>{{dayData.date}}</td>
                                            <td>{{dayData.cost}}</td>
                                            <td>{{dayData.sales}}</td>
                                            <td>{{dayData.revenue}}</td>
                                            <td>{{dayData.employees}}</td>
                                            <td>{{dayData.employeesHoursSum}}</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>

( Side note: This fills up the DOM if you have a lot of data on both levels, so I am therefore working on a directive to fetch data and replace, i.e. adding into DOM when clicking parent and removing when another is clicked or same parent again. To get the kind of behavior you find on Prisjakt.nu, if you scroll down to the computers listed and click on the row (not the links). If you do that and inspect elements you will see that a tr is added and then removed if parent is clicked again or another. )

What is the difference between encrypting and signing in asymmetric encryption?

Functionally, you use public/private key encryption to make certain only the receiver can read your message. The message is encrypted using the public key of the receiver and decrypted using the private key of the receiver.

Signing you can use to let the receiver know you created the message and it has not changed during transfer. Message signing is done using your own private key. The receiver can use your public key to check the message has not been tampered.

As for the algorithm used: that involves a one-way function see for example wikipedia. One of the first of such algorithms use large prime-numbers but more one-way functions have been invented since.

Search for 'Bob', 'Alice' and 'Mallory' to find introduction articles on the internet.

Angularjs Template Default Value if Binding Null / Undefined (With Filter)

Just in case you want to try something else. This is what worked for me:

Based on Ternary Operator which has following structure:

condition ? value-if-true : value-if-false

As result:

{{gallery.date?(gallery.date | date:'mediumDate'):"Various" }}

Get protocol + host name from URL

The standard library function urllib.parse.urlsplit() is all you need. Here is an example for Python3:

>>> import urllib.parse
>>> o = urllib.parse.urlsplit('https://user:[email protected]:8080/dir/page.html?q1=test&q2=a2#anchor1')
>>> o.scheme
'https'
>>> o.netloc
'user:[email protected]:8080'
>>> o.hostname
'www.example.com'
>>> o.port
8080
>>> o.path
'/dir/page.html'
>>> o.query
'q1=test&q2=a2'
>>> o.fragment
'anchor1'
>>> o.username
'user'
>>> o.password
'pass'

Preferred way of getting the selected item of a JComboBox

String x = JComboBox.getSelectedItem().toString();

will convert any value weather it is Integer, Double, Long, Short into text on the other hand,

String x = String.valueOf(JComboBox.getSelectedItem());

will avoid null values, and convert the selected item from object to string

Finding child element of parent pure javascript

The children property returns an array of elements, like so:

parent = document.querySelector('.parent');
children = parent.children; // [<div class="child1">]

There are alternatives to querySelector, like document.getElementsByClassName('parent')[0] if you so desire.


Edit: Now that I think about it, you could just use querySelectorAll to get decendents of parent having a class name of child1:

children = document.querySelectorAll('.parent .child1');

The difference between qS and qSA is that the latter returns all elements matching the selector, while the former only returns the first such element.

Android getResources().getDrawable() deprecated API 22

getResources().getDrawable() was deprecated in API level 22. Now we must add the theme:

getDrawable (int id, Resources.Theme theme) (Added in API level 21)

This is an example:

myImgView.setImageDrawable(getResources().getDrawable(R.drawable.myimage, getApplicationContext().getTheme()));

This is an example how to validate for later versions:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //>= API 21
     myImgView.setImageDrawable(getResources().getDrawable(R.drawable.myimage, getApplicationContext().getTheme()));
   } else { 
     myImgView.setImageDrawable(getResources().getDrawable(R.drawable.myimage));
}

PHP cURL custom headers

Use the following Syntax

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.example.com/process.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$vars);  //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$headers = [
    'X-Apple-Tz: 0',
    'X-Apple-Store-Front: 143444,12',
    'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Encoding: gzip, deflate',
    'Accept-Language: en-US,en;q=0.5',
    'Cache-Control: no-cache',
    'Content-Type: application/x-www-form-urlencoded; charset=utf-8',
    'Host: www.example.com',
    'Referer: http://www.example.com/index.php', //Your referrer address
    'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:28.0) Gecko/20100101 Firefox/28.0',
    'X-MicrosoftAjax: Delta=true'
];

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$server_output = curl_exec ($ch);

curl_close ($ch);

print  $server_output ;

Telnet is not recognized as internal or external command

You can also try dism /online /Enable-Feature /FeatureName:TelnetClient

Run this command with "Run as an administrator"

Reference

Variable not accessible when initialized outside function

It really depends on where your JavaScript code is located.

The problem is probably caused by the DOM not being loaded when the line

var systemStatus = document.getElementById("system-status");

is executed. You could try calling this in an onload event, or ideally use a DOM ready type event from a JavaScript framework.

How to tell if a string contains a certain character in JavaScript?

ES6 contains inbuilt method (includes) in String's prototype, which can be used to check if string contains another string or not.

_x000D_
_x000D_
var str = 'To be, or not to be, that is the question.';_x000D_
_x000D_
console.log(str.includes('To be')); 
_x000D_
_x000D_
_x000D_

Following polyfill can be used to add this method in non-supported browsers. (Source)

_x000D_
_x000D_
if (!String.prototype.includes) {_x000D_
  String.prototype.includes = function(search, start) {_x000D_
    'use strict';_x000D_
    if (typeof start !== 'number') {_x000D_
      start = 0;_x000D_
    }_x000D_
    _x000D_
    if (start + search.length > this.length) {_x000D_
      return false;_x000D_
    } else {_x000D_
      return this.indexOf(search, start) !== -1;_x000D_
    }_x000D_
  };_x000D_
}
_x000D_
_x000D_
_x000D_

What is the difference between Release and Debug modes in Visual Studio?

Debug and Release are just labels for different solution configurations. You can add others if you want. A project I once worked on had one called "Debug Internal" which was used to turn on the in-house editing features of the application. You can see this if you go to Configuration Manager... (it's on the Build menu). You can find more information on MSDN Library under Configuration Manager Dialog Box.

Each solution configuration then consists of a bunch of project configurations. Again, these are just labels, this time for a collection of settings for your project. For example, our C++ library projects have project configurations called "Debug", "Debug_Unicode", "Debug_MT", etc.

The available settings depend on what type of project you're building. For a .NET project, it's a fairly small set: #defines and a few other things. For a C++ project, you get a much bigger variety of things to tweak.

In general, though, you'll use "Debug" when you want your project to be built with the optimiser turned off, and when you want full debugging/symbol information included in your build (in the .PDB file, usually). You'll use "Release" when you want the optimiser turned on, and when you don't want full debugging information included.

NodeJS - What does "socket hang up" actually mean?

below is a simple example where I got the same error when I missed to add the commented code in below example. Uncommenting the code req.end() will resolve this issue.

var fs = require("fs");
var https = require("https");

var options = {
    host: "en.wikipedia.org",
    path: "/wiki/George_Washington",
    port: 443,
    method: "GET"
};

var req = https.request(options, function (res) {
    console.log(res.statusCode);
});


// req.end();

Connection to SQL Server Works Sometimes

In my case, the parameter Persist Security Info=true with the user and password in connection string is causing the problem. Removing the parameter or set to false solve the problem.

Get image data url in JavaScript?

In HTML5 better use this:

{
//...
canvas.width = img.naturalWidth; //img.width;
canvas.height = img.naturalHeight; //img.height;
//...
}

How to set x axis values in matplotlib python?

The scaling on your example figure is a bit strange but you can force it by plotting the index of each x-value and then setting the ticks to the data points:

import matplotlib.pyplot as plt
x = [0.00001,0.001,0.01,0.1,0.5,1,5]
# create an index for each tick position
xi = list(range(len(x)))
y = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]
plt.ylim(0.8,1.4)
# plot the index for the x-values
plt.plot(xi, y, marker='o', linestyle='--', color='r', label='Square') 
plt.xlabel('x')
plt.ylabel('y') 
plt.xticks(xi, x)
plt.title('compare')
plt.legend() 
plt.show()