Programs & Examples On #Cross cutting concerns

Cross-cutting concerns are functions of a program which affect other functions. Since they cannot be completely modularized in both the design and implementation, the resulting code will either be scattered throughout different modules that generate necessary data or tied to specific modules that perform dependant operations. Logging changes to the a database is an example of a cross-cutting concern since it involves checking and updating multiple tables.

excel formula to subtract number of days from a date

Say the 1st date is in A1 cell & the 2nd date is in B1 cell

Make sure that the cell type of both A1 & B1 is DATE.
Then simply put the following formula in C1:

=A1-B1

The result of this formula may look funny to you. Then Change the Cell type of C1 to GENERAL.

It will give you the difference in Days.

You can also use this formula to get the remaining days of year or change the formula as you need:

=365-(A1-B1)

std::thread calling method of class

Not so hard:

#include <thread>

void Test::runMultiThread()
{
    std::thread t1(&Test::calculate, this,  0, 10);
    std::thread t2(&Test::calculate, this, 11, 20);
    t1.join();
    t2.join();
}

If the result of the computation is still needed, use a future instead:

#include <future>

void Test::runMultiThread()
{
     auto f1 = std::async(&Test::calculate, this,  0, 10);
     auto f2 = std::async(&Test::calculate, this, 11, 20);

     auto res1 = f1.get();
     auto res2 = f2.get();
}

Find and Replace text in the entire table using a MySQL query

In the case of sentences with uppercase - lowercase letters, We can use BINARY REPACE

UPDATE `table_1`  SET  `field_1` =  BINARY REPLACE(`field_1`, 'find_string', 'replace_string')

Truncate Two decimal places without rounding

        public static void ReminderDigints(decimal? number, out decimal? Value,  out decimal? Reminder)
        {
            Reminder = null;
            Value = null;
            if (number.HasValue)
            {
                Value = Math.Floor(number.Value);
                Reminder = (number - Math.Truncate(number.Value));
            }
        }



        decimal? number= 50.55m;             
        ReminderDigints(number, out decimal? Value, out decimal? Reminder);

PHP and MySQL Select a Single Value

mysql_* extension has been deprecated in 2013 and removed completely from PHP in 2018. You have two alternatives PDO or MySQLi.

PDO

The simpler option is PDO which has a neat helper function fetchColumn():

$stmt = $pdo->prepare("SELECT id FROM Users WHERE username=?");
$stmt->execute([ $_GET["username"] ]);
$value = $stmt->fetchColumn();

Proper PDO tutorial

MySQLi

You can do the same with MySQLi, but it is more complicated:

$stmt = $mysqliConn->prepare('SELECT id FROM Users WHERE username=?');
$stmt->bind_param("s", $_GET["username"]);
$stmt->execute();
$data = $stmt->get_result()->fetch_assoc();
$value = $data ? $data['id'] : null;

fetch_assoc() could return NULL if there are no rows returned from the DB, which is why I check with ternary if there was any data returned.

What is the list of supported languages/locales on Android?

Arabic, Egypt (ar_EG)
Arabic, Israel (ar_IL)
Bulgarian, Bulgaria (bg_BG)
Catalan, Spain (ca_ES)
Czech, Czech Republic (cs_CZ)
Danish, Denmark(da_DK)
German, Austria (de_AT)
German, Switzerland (de_CH)
German, Germany (de_DE)
German, Liechtenstein (de_LI)
Greek, Greece (el_GR)
English, Australia (en_AU)
English, Canada (en_CA)
English, Britain (en_GB)
English, Ireland (en_IE)
English, India (en_IN)
English, New Zealand (en_NZ)
English, Singapore(en_SG)
English, US (en_US)
English, South Africa (en_ZA)
Spanish (es_ES)
Spanish, US (es_US)
Finnish, Finland (fi_FI)
French, Belgium (fr_BE)
French, Canada (fr_CA)
French, Switzerland (fr_CH)
French, France (fr_FR)
Hebrew, Israel (he_IL)
Hindi, India (hi_IN)
Croatian, Croatia (hr_HR)
Hungarian, Hungary (hu_HU)
Indonesian, Indonesia (id_ID)
Italian, Switzerland (it_CH)
Italian, Italy (it_IT)
Japanese (ja_JP)
Korean (ko_KR)
Lithuanian, Lithuania (lt_LT)
Latvian, Latvia (lv_LV)
Norwegian bokmål, Norway (nb_NO)
Dutch, Belgium (nl_BE)
Dutch, Netherlands (nl_NL)
Polish (pl_PL)
Portuguese, Brazil (pt_BR)
Portuguese, Portugal (pt_PT)
Romanian, Romania (ro_RO)
Russian (ru_RU)
Slovak, Slovakia (sk_SK)
Slovenian, Slovenia (sl_SI)
Serbian (sr_RS)
Swedish, Sweden (sv_SE)
Thai, Thailand (th_TH)
Tagalog, Philippines (tl_PH)
Turkish, Turkey (tr_TR)
Ukrainian, Ukraine (uk_UA)
Vietnamese, Vietnam (vi_VN)
Chinese, PRC (zh_CN)
Chinese, Taiwan (zh_TW)

jQuery select by attribute using AND and OR operators

The and operator in a selector is just an empty string, and the or operator is the comma.

There is however no grouping or priority, so you have to repeat one of the conditions:

a=$('[myc=blue][myid="1"],[myc=blue][myid="3"]');

Python def function: How do you specify the end of the function?

In Python whitespace is significant. The function ends when the indentation becomes smaller (less).

def f():
    pass # first line
    pass # second line
pass # <-- less indentation, not part of function f.

Note that one-line functions can be written without indentation, on one line:

def f(): pass

And, then there is the use of semi-colons, but this is not recommended:

def f(): pass; pass

The three forms above show how the end of a function is defined syntactically. As for the semantics, in Python there are three ways to exit a function:

  • Using the return statement. This works the same as in any other imperative programming language you may know.

  • Using the yield statement. This means that the function is a generator. Explaining its semantics is beyond the scope of this answer. Have a look at Can somebody explain me the python yield statement?

  • By simply executing the last statement. If there are no more statements and the last statement is not a return statement, then the function exists as if the last statement were return None. That is to say, without an explicit return statement a function returns None. This function returns None:

    def f():
        pass
    

    And so does this one:

    def f():
        42
    

Schedule automatic daily upload with FileZilla

FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.

Some references:


Though you can use any other client that allows automation.

You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).

Combine WinSCP scripting capabilities with Windows Scheduler:

A typical WinSCP script for upload (with SFTP) looks like:

open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close

With FTP, just replace the sftp:// with the ftp:// and remove the -hostkey="..." switch.


Similarly for download: How to schedule an automatic FTP download on Windows?


WinSCP can even generate a script from an imported FileZilla session.

For details, see the guide to FileZilla automation.

(I'm the author of WinSCP)


Another option, if you are using SFTP, is the psftp.exe client from PuTTY suite.

How to check if a service is running via batch file and start it, if it is not running?

Maybe a much simpler way? Just adding to the list of answers here:

@for /f "tokens=1,* delims=: " %%a in ('sc queryex state=Inactive') do net start "%%b"

How do you sort an array on multiple columns?

String Appending Method

You can sort by multiple values simply by appending the values into a string and comparing the strings. It is helpful to add a split key character to prevent runoff from one key to the next.

Example

_x000D_
_x000D_
const arr = [ 
    { a: 1, b: 'a', c: 3 },
    { a: 2, b: 'a', c: 5 },
    { a: 1, b: 'b', c: 4 },
    { a: 2, b: 'a', c: 4 }
]


function sortBy (arr, keys, splitKeyChar='~') {
    return arr.sort((i1,i2) => {
        const sortStr1 = keys.reduce((str, key) => str + splitKeyChar+i1[key], '')
        const sortStr2 = keys.reduce((str, key) => str + splitKeyChar+i2[key], '')
        return sortStr1.localeCompare(sortStr2)
    })
}

console.log(sortBy(arr, ['a', 'b', 'c']))
_x000D_
_x000D_
_x000D_

Recursion Method

You can also use Recursion to do this. It is a bit more complex than the String Appending Method but it allows you to do ASC and DESC on the key level. I'm commenting on each section as it is a bit more complex.

There are a few commented out tests to show and verify the sorting works with a mixture of order and default order.

Example

const arr = [ 
    { a: 1, b: 'a', c: 3 },
    { a: 2, b: 'a', c: 5 },
    { a: 1, b: 'b', c: 4 },
    { a: 2, b: 'a', c: 4 }
]


function sortBy (arr, keys) {
    return arr.sort(function sort (i1,i2, sKeys=keys) {
        // Get order and key based on structure
        const compareKey = (sKeys[0].key) ? sKeys[0].key : sKeys[0];
        const order = sKeys[0].order || 'ASC'; // ASC || DESC
        // Calculate compare value and modify based on order
        let compareValue = i1[compareKey].toString().localeCompare(i2[compareKey].toString())
        compareValue = (order.toUpperCase() === 'DESC') ? compareValue * -1 : compareValue
        // See if the next key needs to be considered 
        const checkNextKey = compareValue === 0 && sKeys.length !== 1
        // Return compare value
        return (checkNextKey) ? sort(i1, i2, sKeys.slice(1)): compareValue;
    })
}

// console.log(sortBy(arr, ['a', 'b', 'c']))
console.log(sortBy(arr, [{key:'a',order:'desc'}, 'b', 'c']))
// console.log(sortBy(arr, ['a', 'b', {key:'c',order:'desc'}]))
// console.log(sortBy(arr, ['a', {key:'b',order:'desc'}, 'c']))
// console.log(sortBy(arr, [{key:'a',order:'asc'}, {key:'b',order:'desc'}, {key:'c',order:'desc'}]))

How do Python's any and all functions work?

>>> any([False, False, False])
False
>>> any([False, True, False])
True
>>> all([False, True, True])
False
>>> all([True, True, True])
True

How to compute the similarity between two text documents?

The common way of doing this is to transform the documents into TF-IDF vectors and then compute the cosine similarity between them. Any textbook on information retrieval (IR) covers this. See esp. Introduction to Information Retrieval, which is free and available online.

Computing Pairwise Similarities

TF-IDF (and similar text transformations) are implemented in the Python packages Gensim and scikit-learn. In the latter package, computing cosine similarities is as easy as

from sklearn.feature_extraction.text import TfidfVectorizer

documents = [open(f) for f in text_files]
tfidf = TfidfVectorizer().fit_transform(documents)
# no need to normalize, since Vectorizer will return normalized tf-idf
pairwise_similarity = tfidf * tfidf.T

or, if the documents are plain strings,

>>> corpus = ["I'd like an apple", 
...           "An apple a day keeps the doctor away", 
...           "Never compare an apple to an orange", 
...           "I prefer scikit-learn to Orange", 
...           "The scikit-learn docs are Orange and Blue"]                                                                                                                                                                                                   
>>> vect = TfidfVectorizer(min_df=1, stop_words="english")                                                                                                                                                                                                   
>>> tfidf = vect.fit_transform(corpus)                                                                                                                                                                                                                       
>>> pairwise_similarity = tfidf * tfidf.T 

though Gensim may have more options for this kind of task.

See also this question.

[Disclaimer: I was involved in the scikit-learn TF-IDF implementation.]

Interpreting the Results

From above, pairwise_similarity is a Scipy sparse matrix that is square in shape, with the number of rows and columns equal to the number of documents in the corpus.

>>> pairwise_similarity                                                                                                                                                                                                                                      
<5x5 sparse matrix of type '<class 'numpy.float64'>'
    with 17 stored elements in Compressed Sparse Row format>

You can convert the sparse array to a NumPy array via .toarray() or .A:

>>> pairwise_similarity.toarray()                                                                                                                                                                                                                            
array([[1.        , 0.17668795, 0.27056873, 0.        , 0.        ],
       [0.17668795, 1.        , 0.15439436, 0.        , 0.        ],
       [0.27056873, 0.15439436, 1.        , 0.19635649, 0.16815247],
       [0.        , 0.        , 0.19635649, 1.        , 0.54499756],
       [0.        , 0.        , 0.16815247, 0.54499756, 1.        ]])

Let's say we want to find the document most similar to the final document, "The scikit-learn docs are Orange and Blue". This document has index 4 in corpus. You can find the index of the most similar document by taking the argmax of that row, but first you'll need to mask the 1's, which represent the similarity of each document to itself. You can do the latter through np.fill_diagonal(), and the former through np.nanargmax():

>>> import numpy as np     

>>> arr = pairwise_similarity.toarray()     
>>> np.fill_diagonal(arr, np.nan)                                                                                                                                                                                                                            

>>> input_doc = "The scikit-learn docs are Orange and Blue"                                                                                                                                                                                                  
>>> input_idx = corpus.index(input_doc)                                                                                                                                                                                                                      
>>> input_idx                                                                                                                                                                                                                                                
4

>>> result_idx = np.nanargmax(arr[input_idx])                                                                                                                                                                                                                
>>> corpus[result_idx]                                                                                                                                                                                                                                       
'I prefer scikit-learn to Orange'

Note: the purpose of using a sparse matrix is to save (a substantial amount of space) for a large corpus & vocabulary. Instead of converting to a NumPy array, you could do:

>>> n, _ = pairwise_similarity.shape                                                                                                                                                                                                                         
>>> pairwise_similarity[np.arange(n), np.arange(n)] = -1.0
>>> pairwise_similarity[input_idx].argmax()                                                                                                                                                                                                                  
3

Error handling with try and catch in Laravel

You are inside a namespace so you should use \Exception to specify the global namespace:

try {

  $this->buildXMLHeader();

} catch (\Exception $e) {

    return $e->getMessage();
}

In your code you've used catch (Exception $e) so Exception is being searched in/as:

App\Services\PayUService\Exception

Since there is no Exception class inside App\Services\PayUService so it's not being triggered. Alternatively, you can use a use statement at the top of your class like use Exception; and then you can use catch (Exception $e).

What is the best way to conditionally apply attributes in AngularJS?

To get an attribute to show a specific value based on a boolean check, or be omitted entirely if the boolean check failed, I used the following:

ng-attr-example="{{params.type == 'test' ? 'itWasTest' : undefined }}"

Example usage:

<div ng-attr-class="{{params.type == 'test' ? 'itWasTest' : undefined }}">

Would output <div class="itWasTest"> or <div> based on the value of params.type

How to pass a PHP variable using the URL

All the above answers are correct, but I noticed something very important. Leaving a space between the variable and the equal sign might result in a problem. For example, (?variablename =value)

YouTube iframe API: how do I control an iframe player that's already in the HTML?

My own version of Kim T's code above which combines with some jQuery and allows for targeting of specific iframes.

$(function() {
    callPlayer($('#iframe')[0], 'unMute');
});

function callPlayer(iframe, func, args) {
    if ( iframe.src.indexOf('youtube.com/embed') !== -1) {
        iframe.contentWindow.postMessage( JSON.stringify({
            'event': 'command',
            'func': func,
            'args': args || []
        } ), '*');
    }
}

How to refresh an IFrame using Javascript?

Here is the HTML snippet:

<td><iframe name="idFrame" id="idFrame" src="chat.txt" width="468" height="300"></iframe></td>

And my Javascript code:

window.onload = function(){
setInterval(function(){
    parent.frames['idFrame'].location.href = "chat.txt";
},1000);}

SSRS custom number format

You can use

 =Format(Fields!myField.Value,"F2") 

How to change Bootstrap's global default font size?

Bootstrap uses the variable:

$font-size-base: 1rem; // Assumes the browser default, typically 16px

I don't recommend mucking with this, but you can. Best practice is to override the browser default base font size with:

html {
  font-size: 14px;
}

Bootstrap will then take that value and use it via rems to set values for all kinds of things.

Is there a "between" function in C#?

There is no built in construct in C#/.NET, but you can easily add your own extension method for this:

public static class ExtensionsForInt32
{
    public static bool IsBetween (this int val, int low, int high)
    {
           return val > low && val < high;
    }
}

Which can be used like:

if (5.IsBetween (0, 10)) { /* Do something */ }

find a minimum value in an array of floats

If min value in array, you can try like:

>>> mydict = {"a": -1.5, "b": -1000.44, "c": -3}
>>> min(mydict.values())
-1000.44

Subtract days from a DateTime

The object (i.e. destination variable) for the AddDays method can't be the same as the source.

Instead of:

DateTime today = DateTime.Today;
today.AddDays(-7);

Try this instead:

DateTime today = DateTime.Today;
DateTime sevenDaysEarlier = today.AddDays(-7);

What's the difference between JavaScript and JScript?

As far as I can tell, two things:

  1. ActiveXObject constructor
  2. The idiom f(x) = y, which is roughly equivalent to f[x] = y.

How to add items into a numpy array

np.insert can also be used for the purpose

import numpy as np
a = np.array([[1, 3, 4],
              [1, 2, 3],
              [1, 2, 1]])
x = 5
index = 3 # the position for x to be inserted before
np.insert(a, index, x, axis=1)
array([[1, 3, 4, 5],
       [1, 2, 3, 5],
       [1, 2, 1, 5]])

index can also be a list/tuple

>>> index = [1, 1, 3] # equivalently (1, 1, 3)
>>> np.insert(a, index, x, axis=1)
array([[1, 5, 5, 3, 4, 5],
       [1, 5, 5, 2, 3, 5],
       [1, 5, 5, 2, 1, 5]])

or a slice

>>> index = slice(0, 3)
>>> np.insert(a, index, x, axis=1)
array([[5, 1, 5, 3, 5, 4],
       [5, 1, 5, 2, 5, 3],
       [5, 1, 5, 2, 5, 1]])

How can I execute PHP code from the command line?

You can use:

 echo '<?php if(function_exists("my_func")) echo "function exists"; ' | php

The short tag "< ?=" can be helpful too:

 echo '<?= function_exists("foo") ? "yes" : "no";' | php
 echo '<?= 8+7+9 ;' | php

The closing tag "?>" is optional, but don't forget the final ";"!

Firefox setting to enable cross domain Ajax request

What about using something like mod_proxy? Then it looks to your browser like the requests are going to the same server, but they're really being forwarded to another server.

Can't access 127.0.0.1

Just one command did the work

netsh http add iplisten 127.0.0.1

Excel: Searching for multiple terms in a cell

Try using COUNT function like this

=IF(COUNT(SEARCH({"Romney","Obama","Gingrich"},C1)),1,"")

Note that you don't need the wildcards (as teylyn says) and unless there's a specific reason "1" doesn't need quotes (in fact that makes it a text value)

Enable 'xp_cmdshell' SQL Server

Even if this question has resolved, I want to add my advice about that.... since as developer I ignored.

Is important to know that we're talking about MSSQL xp_cmdshell enabled is critical to security, as indicated in the message warning:

Blockquote SQL Server blocked access to procedure 'sys.xp_cmdshell' of component 'xp_cmdshell' because this component is turned off as part of the security configuration for this server. [...]

Leaving the service enabled is a kind of weakness, that for example in a web-app could reflect and execute commands SQL from an attacker. The popular CWE-89: SQL Injection it could be weakness in the our software, and therefore these type of scenarios could pave the way to possible attacks, such as CAPEC-108: Command Line Execution through SQL Injection

I hope to have done something pleasant, we Developers and Engineer do things with awareness and we will be safer!

Maven parent pom vs modules pom

  1. An independent parent is the best practice for sharing configuration and options across otherwise uncoupled components. Apache has a parent pom project to share legal notices and some common packaging options.

  2. If your top-level project has real work in it, such as aggregating javadoc or packaging a release, then you will have conflicts between the settings needed to do that work and the settings you want to share out via parent. A parent-only project avoids that.

  3. A common pattern (ignoring #1 for the moment) is have the projects-with-code use a parent project as their parent, and have it use the top-level as a parent. This allows core things to be shared by all, but avoids the problem described in #2.

  4. The site plugin will get very confused if the parent structure is not the same as the directory structure. If you want to build an aggregate site, you'll need to do some fiddling to get around this.

  5. Apache CXF is an example the pattern in #2.

How do I start a program with arguments when debugging?

For Visual Studio Code:

  • Open launch.json file
  • Add args to your configuration:

"args": ["some argument", "another one"],

How can I show three columns per row?

This may be what you are looking for:

http://jsfiddle.net/L4L67/

_x000D_
_x000D_
body>div {_x000D_
  background: #aaa;_x000D_
  display: flex;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
body>div>div {_x000D_
  flex-grow: 1;_x000D_
  width: 33%;_x000D_
  height: 100px;_x000D_
}_x000D_
_x000D_
body>div>div:nth-child(even) {_x000D_
  background: #23a;_x000D_
}_x000D_
_x000D_
body>div>div:nth-child(odd) {_x000D_
  background: #49b;_x000D_
}
_x000D_
<div>_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to use XMLReader in PHP?

This Works Better and Faster For Me


<html>
<head>
<script>
function showRSS(str) {
  if (str.length==0) {
    document.getElementById("rssOutput").innerHTML="";
    return;
  }
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else {  // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function() {
    if (this.readyState==4 && this.status==200) {
      document.getElementById("rssOutput").innerHTML=this.responseText;
    }
  }
  xmlhttp.open("GET","getrss.php?q="+str,true);
  xmlhttp.send();
}
</script>
</head>
<body>

<form>
<select onchange="showRSS(this.value)">
<option value="">Select an RSS-feed:</option>
<option value="Google">Google News</option>
<option value="ZDN">ZDNet News</option>
<option value="job">Job</option>
</select>
</form>
<br>
<div id="rssOutput">RSS-feed will be listed here...</div>
</body>
</html> 

**The Backend File **


<?php
//get the q parameter from URL
$q=$_GET["q"];

//find out which feed was selected
if($q=="Google") {
  $xml=("http://news.google.com/news?ned=us&topic=h&output=rss");
} elseif($q=="ZDN") {
  $xml=("https://www.zdnet.com/news/rss.xml");
}elseif($q == "job"){
  $xml=("https://ngcareers.com/feed");
}

$xmlDoc = new DOMDocument();
$xmlDoc->load($xml);

//get elements from "<channel>"
$channel=$xmlDoc->getElementsByTagName('channel')->item(0);
$channel_title = $channel->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$channel_link = $channel->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$channel_desc = $channel->getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;

//output elements from "<channel>"
echo("<p><a href='" . $channel_link
  . "'>" . $channel_title . "</a>");
echo("<br>");
echo($channel_desc . "</p>");

//get and output "<item>" elements
$x=$xmlDoc->getElementsByTagName('item');

$count = $x->length;

// print_r( $x->item(0)->getElementsByTagName('title')->item(0)->nodeValue);
// print_r( $x->item(0)->getElementsByTagName('link')->item(0)->nodeValue);
// print_r( $x->item(0)->getElementsByTagName('description')->item(0)->nodeValue);
// return;

for ($i=0; $i <= $count; $i++) {
  //Title
  $item_title = $x->item(0)->getElementsByTagName('title')->item(0)->nodeValue;
  //Link
  $item_link = $x->item(0)->getElementsByTagName('link')->item(0)->nodeValue;
  //Description
  $item_desc = $x->item(0)->getElementsByTagName('description')->item(0)->nodeValue;
  //Category
  $item_cat = $x->item(0)->getElementsByTagName('category')->item(0)->nodeValue;


  echo ("<p>Title: <a href='" . $item_link
  . "'>" . $item_title . "</a>");
  echo ("<br>");
  echo ("Desc: ".$item_desc);
   echo ("<br>");
  echo ("Category: ".$item_cat . "</p>");
}
?> 

Index of Currently Selected Row in DataGridView

Try the following:

int myIndex = MyDataGrid.SelectedIndex;

This will give the index of the row which is currently selected.

Hope this helps

Check if list<t> contains any of another list

If both the list are too big and when we use lamda expression then it will take a long time to fetch . Better to use linq in this case to fetch parameters list:

var items = (from x in parameters
                join y in myStrings on x.Source equals y
                select x)
            .ToList();

Using sendmail from bash script for multiple recipients

to use sendmail from the shell script

subject="mail subject"
body="Hello World"
from="[email protected]"
to="[email protected],[email protected]"
echo -e "Subject:${subject}\n${body}" | sendmail -f "${from}" -t "${to}"

How to comment and uncomment blocks of code in the Office VBA Editor

  1. Right-click on the toolbar and select Customize...
  2. Select the Commands tab.
  3. Under Categories click on Edit, then select Comment Block in the Commands listbox.
  4. Drag the Comment Block entry onto the Menu Bar (yep! the menu bar)
    Note: You should now see a new icon on the menu bar.
  5. Make sure that the new icon is highlighted (it will have a black square around it) then
    click Modify Selection button on the Customize dialog box.
  6. An interesting menu will popup.
    Under name, add an ampersand (&) to the beginning of the entry.
    So now instead of "Comment Block" it should read &Comment Block.
    Press Enter to save the change.
  7. Click on Modify Selection again and select Image and Text.
  8. Dismiss the Customize dialog box.
  9. Highlight any block of code and press Alt-C. Voila.
  10. Do the same thing for the Uncomment Block or
    any other commands that you find yourself using often.

Postgres "psql not recognized as an internal or external command"

Even if it is a little bit late, i solved the PATH problem by removing every space.

;C:\Program Files\PostgreSQL\9.5\bin;C:\Program Files\PostgreSQL\9.5\lib

works for me now.

Postgres: clear entire database before re-creating / re-populating from bash script

Note: my answer is about really deleting the tables and other database objects; for deleting all data in the tables, i.e. truncating all tables, Endre Both has provided a similarily well-executed (direct execution) statement a month later.

For the cases where you can’t just DROP SCHEMA public CASCADE;, DROP OWNED BY current_user; or something, here’s a stand-alone SQL script I wrote, which is transaction-safe (i.e. you can put it between BEGIN; and either ROLLBACK; to just test it out or COMMIT; to actually do the deed) and cleans up “all” database objects… well, all those used in the database our application uses or I could sensibly add, which is:

  • triggers on tables
  • constraints on tables (FK, PK, CHECK, UNIQUE)
  • indices
  • VIEWs (normal or materialised)
  • tables
  • sequences
  • routines (aggregate functions, functions, procedures)
  • all non-default (i.e. not public or DB-internal) schemata “we” own: the script is useful when run as “not a database superuser”; a superuser can drop all schemata (the really important ones are still explicitly excluded, though)
  • extensions (user-contributed but I normally deliberately leave them in)

Not dropped are (some deliberate; some only because I had no example in our DB):

  • the public schema (e.g. for extension-provided stuff in them)
  • collations and other locale stuff
  • event triggers
  • text search stuff, … (see here for other stuff I might have missed)
  • roles or other security settings
  • composite types
  • toast tables
  • FDW and foreign tables

This is really useful for the cases when the dump you want to restore is of a different database schema version (e.g. with Debian dbconfig-common, Flyway or Liquibase/DB-Manul) than the database you want to restore it into.

I’ve also got a version which deletes “everything except two tables and what belongs to them” (a sequence, tested manually, sorry, I know, boring) in case someone is interested; the diff is small. Contact me or check this repo if interested.

SQL

-- Copyright © 2019, 2020
--      mirabilos <[email protected]>
--
-- Provided that these terms and disclaimer and all copyright notices
-- are retained or reproduced in an accompanying document, permission
-- is granted to deal in this work without restriction, including un-
-- limited rights to use, publicly perform, distribute, sell, modify,
-- merge, give away, or sublicence.
--
-- This work is provided “AS IS” and WITHOUT WARRANTY of any kind, to
-- the utmost extent permitted by applicable law, neither express nor
-- implied; without malicious intent or gross negligence. In no event
-- may a licensor, author or contributor be held liable for indirect,
-- direct, other damage, loss, or other issues arising in any way out
-- of dealing in the work, even if advised of the possibility of such
-- damage or existence of a defect, except proven that it results out
-- of said person’s immediate fault when using the work as intended.
-- -
-- Drop everything from the PostgreSQL database.

DO $$
DECLARE
        q TEXT;
        r RECORD;
BEGIN
        -- triggers
        FOR r IN (SELECT pns.nspname, pc.relname, pt.tgname
                FROM pg_catalog.pg_trigger pt, pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
                WHERE pns.oid=pc.relnamespace AND pc.oid=pt.tgrelid
                    AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
                    AND pt.tgisinternal=false
            ) LOOP
                EXECUTE format('DROP TRIGGER %I ON %I.%I;',
                    r.tgname, r.nspname, r.relname);
        END LOOP;
        -- constraints #1: foreign key
        FOR r IN (SELECT pns.nspname, pc.relname, pcon.conname
                FROM pg_catalog.pg_constraint pcon, pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
                WHERE pns.oid=pc.relnamespace AND pc.oid=pcon.conrelid
                    AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
                    AND pcon.contype='f'
            ) LOOP
                EXECUTE format('ALTER TABLE ONLY %I.%I DROP CONSTRAINT %I;',
                    r.nspname, r.relname, r.conname);
        END LOOP;
        -- constraints #2: the rest
        FOR r IN (SELECT pns.nspname, pc.relname, pcon.conname
                FROM pg_catalog.pg_constraint pcon, pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
                WHERE pns.oid=pc.relnamespace AND pc.oid=pcon.conrelid
                    AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
                    AND pcon.contype<>'f'
            ) LOOP
                EXECUTE format('ALTER TABLE ONLY %I.%I DROP CONSTRAINT %I;',
                    r.nspname, r.relname, r.conname);
        END LOOP;
        -- indices
        FOR r IN (SELECT pns.nspname, pc.relname
                FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
                WHERE pns.oid=pc.relnamespace
                    AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
                    AND pc.relkind='i'
            ) LOOP
                EXECUTE format('DROP INDEX %I.%I;',
                    r.nspname, r.relname);
        END LOOP;
        -- normal and materialised views
        FOR r IN (SELECT pns.nspname, pc.relname
                FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
                WHERE pns.oid=pc.relnamespace
                    AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
                    AND pc.relkind IN ('v', 'm')
            ) LOOP
                EXECUTE format('DROP VIEW %I.%I;',
                    r.nspname, r.relname);
        END LOOP;
        -- tables
        FOR r IN (SELECT pns.nspname, pc.relname
                FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
                WHERE pns.oid=pc.relnamespace
                    AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
                    AND pc.relkind='r'
            ) LOOP
                EXECUTE format('DROP TABLE %I.%I;',
                    r.nspname, r.relname);
        END LOOP;
        -- sequences
        FOR r IN (SELECT pns.nspname, pc.relname
                FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
                WHERE pns.oid=pc.relnamespace
                    AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
                    AND pc.relkind='S'
            ) LOOP
                EXECUTE format('DROP SEQUENCE %I.%I;',
                    r.nspname, r.relname);
        END LOOP;
        -- extensions (only if necessary; keep them normally)
        FOR r IN (SELECT pns.nspname, pe.extname
                FROM pg_catalog.pg_extension pe, pg_catalog.pg_namespace pns
                WHERE pns.oid=pe.extnamespace
                    AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
            ) LOOP
                EXECUTE format('DROP EXTENSION %I;', r.extname);
        END LOOP;
        -- aggregate functions first (because they depend on other functions)
        FOR r IN (SELECT pns.nspname, pp.proname, pp.oid
                FROM pg_catalog.pg_proc pp, pg_catalog.pg_namespace pns, pg_catalog.pg_aggregate pagg
                WHERE pns.oid=pp.pronamespace
                    AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
                    AND pagg.aggfnoid=pp.oid
            ) LOOP
                EXECUTE format('DROP AGGREGATE %I.%I(%s);',
                    r.nspname, r.proname,
                    pg_get_function_identity_arguments(r.oid));
        END LOOP;
        -- routines (functions, aggregate functions, procedures, window functions)
        IF EXISTS (SELECT * FROM pg_catalog.pg_attribute
                WHERE attrelid='pg_catalog.pg_proc'::regclass
                    AND attname='prokind' -- PostgreSQL 11+
            ) THEN
                q := 'CASE pp.prokind
                        WHEN ''p'' THEN ''PROCEDURE''
                        WHEN ''a'' THEN ''AGGREGATE''
                        ELSE ''FUNCTION''
                    END';
        ELSIF EXISTS (SELECT * FROM pg_catalog.pg_attribute
                WHERE attrelid='pg_catalog.pg_proc'::regclass
                    AND attname='proisagg' -- PostgreSQL =10
            ) THEN
                q := 'CASE pp.proisagg
                        WHEN true THEN ''AGGREGATE''
                        ELSE ''FUNCTION''
                    END';
        ELSE
                q := '''FUNCTION''';
        END IF;
        FOR r IN EXECUTE 'SELECT pns.nspname, pp.proname, pp.oid, ' || q || ' AS pt
                FROM pg_catalog.pg_proc pp, pg_catalog.pg_namespace pns
                WHERE pns.oid=pp.pronamespace
                    AND pns.nspname NOT IN (''information_schema'', ''pg_catalog'', ''pg_toast'')
            ' LOOP
                EXECUTE format('DROP %s %I.%I(%s);', r.pt,
                    r.nspname, r.proname,
                    pg_get_function_identity_arguments(r.oid));
        END LOOP;
        -- non-default schemata we own; assume to be run by a not-superuser
        FOR r IN (SELECT pns.nspname
                FROM pg_catalog.pg_namespace pns, pg_catalog.pg_roles pr
                WHERE pr.oid=pns.nspowner
                    AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast', 'public')
                    AND pr.rolname=current_user
            ) LOOP
                EXECUTE format('DROP SCHEMA %I;', r.nspname);
        END LOOP;
        -- voilà
        RAISE NOTICE 'Database cleared!';
END; $$;

Tested, except later additions (extensions contributed by Clément Prévost), on PostgreSQL 9.6 (jessie-backports). Aggregate removal tested on 9.6 and 12.2, procedure removal tested on 12.2 as well. Bugfixes and further improvements welcome!

Display HTML snippets in HTML

A combination of a couple answers that work together here:

_x000D_
_x000D_
function c(s) {_x000D_
    return s.split("&lt;").join("<").split("&gt;").join(">").split("&amp;").join("&")_x000D_
}_x000D_
_x000D_
displayMe.innerHTML = ok.innerHTML;_x000D_
console.log(_x000D_
  c(ok.innerHTML)_x000D_
)
_x000D_
<textarea style="display:none" id="ok">_x000D_
<script>_x000D_
console.log("hello", 5&9);_x000D_
</script>_x000D_
</textarea>_x000D_
<div id="displayMe">_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

200 PORT command successful. Consider using PASV. 425 Failed to establish connection

Actually your Windows firewall is blocking the connection. You need to enter these commands into cmd.exe from Administrator.

netsh advfirewall firewall add rule name="FTP" dir=in action=allow program=%SystemRoot%\System32\ftp.exe enable=yes protocol=tcp
netsh advfirewall firewall add rule name="FTP" dir=in action=allow program=%SystemRoot%\System32\ftp.exe enable=yes protocol=udp

In case something goes wrong then you can revert by this:

netsh advfirewall firewall delete rule name="FTP" program=%SystemRoot%\System32\ftp.exe

Display a tooltip over a button using Windows Forms

You can use the ToolTip class:

Creating a ToolTip for a Control

Example:

private void Form1_Load(object sender, System.EventArgs e)
{
    System.Windows.Forms.ToolTip ToolTip1 = new System.Windows.Forms.ToolTip();
    ToolTip1.SetToolTip(this.Button1, "Hello");
}

Binding Button click to a method

I do this all the time. Here's a look at an example and how you would implement it.

Change your XAML to use the Command property of the button instead of the Click event. I am using the name SaveCommand since it is easier to follow then something named Command.

<Button Command="{Binding Path=SaveCommand}" />

Your CustomClass that the Button is bound to now needs to have a property called SaveCommand of type ICommand. It needs to point to the method on the CustomClass that you want to run when the command is executed.

public MyCustomClass
{
    private ICommand _saveCommand;

    public ICommand SaveCommand
    {
        get
        {
            if (_saveCommand == null)
            {
                _saveCommand = new RelayCommand(
                    param => this.SaveObject(), 
                    param => this.CanSave()
                );
            }
            return _saveCommand;
        }
    }

    private bool CanSave()
    {
        // Verify command can be executed here
    }

    private void SaveObject()
    {
        // Save command execution logic
    }
}

The above code uses a RelayCommand which accepts two parameters: the method to execute, and a true/false value of if the command can execute or not. The RelayCommand class is a separate .cs file with the code shown below. I got it from Josh Smith :)

/// <summary>
/// A command whose sole purpose is to 
/// relay its functionality to other
/// objects by invoking delegates. The
/// default return value for the CanExecute
/// method is 'true'.
/// </summary>
public class RelayCommand : ICommand
{
    #region Fields

    readonly Action<object> _execute;
    readonly Predicate<object> _canExecute;        

    #endregion // Fields

    #region Constructors

    /// <summary>
    /// Creates a new command that can always execute.
    /// </summary>
    /// <param name="execute">The execution logic.</param>
    public RelayCommand(Action<object> execute)
        : this(execute, null)
    {
    }

    /// <summary>
    /// Creates a new command.
    /// </summary>
    /// <param name="execute">The execution logic.</param>
    /// <param name="canExecute">The execution status logic.</param>
    public RelayCommand(Action<object> execute, Predicate<object> canExecute)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");

        _execute = execute;
        _canExecute = canExecute;           
    }

    #endregion // Constructors

    #region ICommand Members

    [DebuggerStepThrough]
    public bool CanExecute(object parameters)
    {
        return _canExecute == null ? true : _canExecute(parameters);
    }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public void Execute(object parameters)
    {
        _execute(parameters);
    }

    #endregion // ICommand Members
}

Best Regular Expression for Email Validation in C#

Email Validation Regex

^[a-z0-9][-a-z0-9._]+@([-a-z0-9]+.)+[a-z]{2,5}$

Or

^[a-z0-9][-a-z0-9._]+@([-a-z0-9]+[.])+[a-z]{2,5}$

Demo Link:

https://regex101.com/r/kN4nJ0/53

Twitter Bootstrap 3.0 how do I "badge badge-important" now

Another possible way, in order to make the colors a bit more intense, is this one:

<span class="badge progress-bar-info">10</span>
<span class="badge progress-bar-success">20</span>
<span class="badge progress-bar-warning">30</span>
<span class="badge progress-bar-danger">40</span>

See Bootply

Control flow in T-SQL SP using IF..ELSE IF - are there other ways?

CASE expression
      WHEN value1 THEN result1
      WHEN value2 THEN result2
      ...
      WHEN valueN THEN resultN

      [
        ELSE elseResult
      ]
END

http://www.4guysfromrolla.com/webtech/102704-1.shtml For more information.

How can I get the application's path in a .NET console application?

You may be looking to do this:

System.IO.Path.GetDirectoryName(
    System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)

How to reload the current route with the angular 2 router

I am using setTimeout and navigationByUrl to solve this issue... And it is working fine for me.

It is redirected to other URL and instead comes again in the current URL...

 setTimeout(() => {
     this.router.navigateByUrl('/dashboard', {skipLocationChange: false}).then(() =>
           this.router.navigate([route]));
     }, 500)

How can I create a small color box using html and css?

If you want to create a small dots, just use icon from font awesome.

fa fa-circle

Git copy changes from one branch to another

Merge the changes from BranchA to BranchB. When you are on BranchB execute git merge BranchA

Count of "Defined" Array Elements

Unfortunately, No. You will you have to go through a loop and count them.

EDIT :

var arrLength = arr.filter(Number);
alert(arrLength);

force Maven to copy dependencies into target/lib

If you want to deliver a bundle of your application jar, together with all its dependencies and some scripts to invoke the MainClass, look at the appassembler-maven-plugin.

The following configuration will generate scripts for Window and Linux to launch the application (with a generated path referencing all the dependency jars, download all dependencies (into a lib folder below target/appassembler). The assembly plugin can then be used to package the whole appassembler directory to a zip which is installed/deployed along with the jar to the repository.

  <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>appassembler-maven-plugin</artifactId>
    <version>1.0</version>
    <executions>
      <execution>
        <id>generate-jsw-scripts</id>
        <phase>package</phase>
        <goals>
          <goal>generate-daemons</goal>
        </goals>
        <configuration>
          <!--declare the JSW config -->
          <daemons>
            <daemon>
              <id>myApp</id>
              <mainClass>name.seller.rich.MyMainClass</mainClass>
              <commandLineArguments>
                <commandLineArgument>start</commandLineArgument>
              </commandLineArguments>
              <platforms>
                <platform>jsw</platform>
              </platforms>              
            </daemon>
          </daemons>
          <target>${project.build.directory}/appassembler</target>
        </configuration>
      </execution>
      <execution>
        <id>assemble-standalone</id>
        <phase>integration-test</phase>
        <goals>
          <goal>assemble</goal>
        </goals>
        <configuration>
          <programs>
            <program>
              <mainClass>name.seller.rich.MyMainClass</mainClass>
              <!-- the name of the bat/sh files to be generated -->
              <name>mymain</name>
            </program>
          </programs>
          <platforms>
            <platform>windows</platform>
            <platform>unix</platform>
          </platforms>
          <repositoryLayout>flat</repositoryLayout>
          <repositoryName>lib</repositoryName>
        </configuration>
      </execution>
    </executions>
  </plugin>
  <plugin>
    <artifactId>maven-assembly-plugin</artifactId>
    <version>2.2-beta-4</version>
    <executions>
      <execution>
        <phase>integration-test</phase>
        <goals>
          <goal>single</goal>
        </goals>
        <configuration>
          <descriptors>
            <descriptor>src/main/assembly/archive.xml</descriptor>
          </descriptors>
        </configuration>
      </execution>
    </executions>
  </plugin> 

The assembly descriptor (in src/main/assembly) to package the direcotry as a zip would be:

<assembly>
  <id>archive</id>
  <formats>
    <format>zip</format>
  </formats>
  <fileSets>
    <fileSet>
     <directory>${project.build.directory}/appassembler</directory>
     <outputDirectory>/</outputDirectory>
    </fileSet>
  </fileSets>
</assembly>

C/C++ maximum stack size of program

In Visual Studio the default stack size is 1 MB i think, so with a recursion depth of 10,000 each stack frame can be at most ~100 bytes which should be sufficient for a DFS algorithm.

Most compilers including Visual Studio let you specify the stack size. On some (all?) linux flavours the stack size isn't part of the executable but an environment variable in the OS. You can then check the stack size with ulimit -s and set it to a new value with for example ulimit -s 16384.

Here's a link with default stack sizes for gcc.

DFS without recursion:

std::stack<Node> dfs;
dfs.push(start);
do {
    Node top = dfs.top();
    if (top is what we are looking for) {
       break;
    }
    dfs.pop();
    for (outgoing nodes from top) {
        dfs.push(outgoing node);
    }
} while (!dfs.empty())

Saving changes after table edit in SQL Server Management Studio

Many changes you can make very easily and visually in the table editor in SQL Server Management Studio actually require SSMS to drop the table in the background and re-create it from scratch. Even simple things like reordering the columns cannot be expressed in standard SQL DDL statement - all SSMS can do is drop and recreate the table.

This operation can be a) very time consuming on a large table, or b) might even fail for various reasons (like FK constraints and stuff). Therefore, SSMS in SQL Server 2008 introduced that new option the other answers have already identified.

It might seem counter-intuitive at first to prevent such changes - and it's certainly a nuisance on a dev server. But on a production server, this option and its default value of preventing such changes becomes a potential life-saver!

Error: allowDefinition='MachineToApplication' beyond application level

In Visual Studio 2013 I struggled with this for a while and it is pretty much easy to solve just follow what the exceptions says "virtual directory not being configured as an application in IIS"

In my case I had WebService planted inside IIS website so

  1. I opened the website in IIS manager
  2. right clicked the WCF folder
  3. clicked Convert to Application
  4. and then submitted with Ok

WCF is back and running.

Get Return Value from Stored procedure in asp.net

Procedure never returns a value.You have to use a output parameter in store procedure.

ALTER PROC TESTLOGIN
@UserName   varchar(50),
@password   varchar(50)
@retvalue int output
 as
 Begin
    declare @return     int 
    set @return  = (Select COUNT(*) 
    FROM    CPUser  
    WHERE   UserName = @UserName AND Password = @password)

   set @retvalue=@return
  End

Then you have to add a sqlparameter from c# whose parameter direction is out. Hope this make sense.

Describe table structure

Highlight table name in the console and press ALT+F1

On a CSS hover event, can I change another div's styling?

A pure solution without jQuery:

Javascript (Head)

function chbg(color) {
    document.getElementById('b').style.backgroundColor = color;
}   

HTML (Body)

<div id="a" onmouseover="chbg('red')" onmouseout="chbg('white')">This is element a</div>
<div id="b">This is element b</div>

JSFiddle: http://jsfiddle.net/YShs2/

How to add a single item to a Pandas Series

You can use the append function to add another element to it. Only, make a series of the new element, before you append it:

test = test.append(pd.Series(200, index=[101]))

Using BeautifulSoup to extract text without tags

I think you can get it using subc1.text.

>>> html = """
<p>
    <strong class="offender">YOB:</strong> 1987<br />
    <strong class="offender">RACE:</strong> WHITE<br />
    <strong class="offender">GENDER:</strong> FEMALE<br />
    <strong class="offender">HEIGHT:</strong> 5'05''<br />
    <strong class="offender">WEIGHT:</strong> 118<br />
    <strong class="offender">EYE COLOR:</strong> GREEN<br />
    <strong class="offender">HAIR COLOR:</strong> BROWN<br />
</p>
"""
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(html)
>>> print soup.text


YOB: 1987
RACE: WHITE
GENDER: FEMALE
HEIGHT: 5'05''
WEIGHT: 118
EYE COLOR: GREEN
HAIR COLOR: BROWN

Or if you want to explore it, you can use .contents :

>>> p = soup.find('p')
>>> from pprint import pprint
>>> pprint(p.contents)
[u'\n',
 <strong class="offender">YOB:</strong>,
 u' 1987',
 <br/>,
 u'\n',
 <strong class="offender">RACE:</strong>,
 u' WHITE',
 <br/>,
 u'\n',
 <strong class="offender">GENDER:</strong>,
 u' FEMALE',
 <br/>,
 u'\n',
 <strong class="offender">HEIGHT:</strong>,
 u" 5'05''",
 <br/>,
 u'\n',
 <strong class="offender">WEIGHT:</strong>,
 u' 118',
 <br/>,
 u'\n',
 <strong class="offender">EYE COLOR:</strong>,
 u' GREEN',
 <br/>,
 u'\n',
 <strong class="offender">HAIR COLOR:</strong>,
 u' BROWN',
 <br/>,
 u'\n']

and filter out the necessary items from the list:

>>> data = dict(zip([x.text for x in p.contents[1::4]], [x.strip() for x in p.contents[2::4]]))
>>> pprint(data)
{u'EYE COLOR:': u'GREEN',
 u'GENDER:': u'FEMALE',
 u'HAIR COLOR:': u'BROWN',
 u'HEIGHT:': u"5'05''",
 u'RACE:': u'WHITE',
 u'WEIGHT:': u'118',
 u'YOB:': u'1987'}

The create-react-app imports restriction outside of src directory

You don't need to eject, you can modify the react-scripts config with the rescripts library

This would work then:

module.exports = config => {
  const scopePluginIndex = config.resolve.plugins.findIndex(
    ({ constructor }) => constructor && constructor.name === "ModuleScopePlugin"
  );

  config.resolve.plugins.splice(scopePluginIndex, 1);

  return config;
};

Get data from JSON file with PHP

Get the content of the JSON file using file_get_contents():

$str = file_get_contents('http://example.com/example.json/');

Now decode the JSON using json_decode():

$json = json_decode($str, true); // decode the JSON into an associative array

You have an associative array containing all the information. To figure out how to access the values you need, you can do the following:

echo '<pre>' . print_r($json, true) . '</pre>';

This will print out the contents of the array in a nice readable format. Note that the second parameter is set to true in order to let print_r() know that the output should be returned (rather than just printed to screen). Then, you access the elements you want, like so:

$temperatureMin = $json['daily']['data'][0]['temperatureMin'];
$temperatureMax = $json['daily']['data'][0]['temperatureMax'];

Or loop through the array however you wish:

foreach ($json['daily']['data'] as $field => $value) {
    // Use $field and $value here
}

Demo!

JavaScript code to stop form submission

You can use the return value of the function to prevent the form submission

<form name="myForm" onsubmit="return validateMyForm();"> 

and function like

<script type="text/javascript">
function validateMyForm()
{
  if(check if your conditions are not satisfying)
  { 
    alert("validation failed false");
    returnToPreviousPage();
    return false;
  }

  alert("validations passed");
  return true;
}
</script>

In case of Chrome 27.0.1453.116 m if above code does not work, please set the event handler's parameter's returnValue field to false to get it to work.

Thanks Sam for sharing information.

EDIT :

Thanks to Vikram for his workaround for if validateMyForm() returns false:

 <form onsubmit="event.preventDefault(); validateMyForm();">

where validateMyForm() is a function that returns false if validation fails. The key point is to use the name event. We cannot use for e.g. e.preventDefault()

Pushing value of Var into an Array

jQuery is not the same as an array. If you want to append something at the end of a jQuery object, use:

$('#fruit').append(veggies);

or to append it to the end of a form value like in your example:

 $('#fruit').val($('#fruit').val()+veggies);

In your case, fruitvegbasket is a string that contains the current value of #fruit, not an array.

jQuery (jquery.com) allows for DOM manipulation, and the specific function you called val() returns the value attribute of an input element as a string. You can't push something onto a string.

How to declare a variable in a template in Angular

I liked the approach of creating a directive to do this (good call @yurzui).

I ended up finding a Medium article Angular "let" Directive which explains this problem nicely and proposes a custom let directive which ended up working great for my use case with minimal code changes.

Here's the gist (at the time of posting) with my modifications:

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core'

interface LetContext <T> {
  appLet: T | null
}

@Directive({
  selector: '[appLet]',
})
export class LetDirective <T> {
  private _context: LetContext <T> = { appLet: null }

  constructor(_viewContainer: ViewContainerRef, _templateRef: TemplateRef <LetContext <T> >) {
    _viewContainer.createEmbeddedView(_templateRef, this._context)
  }

  @Input()
  set appLet(value: T) {
    this._context.appLet = value
  }
}

My main changes were:

  • changing the prefix from 'ng' to 'app' (you should use whatever your app's custom prefix is)
  • changing appLet: T to appLet: T | null

Not sure why the Angular team hasn't just made an official ngLet directive but whatevs.

Original source code credit goes to @AustinMatherne

OnClick in Excel VBA

SelectionChange is the event built into the Excel Object model for this. It should do exactly as you want, firing any time the user clicks anywhere...

I'm not sure that I understand your objections to global variables here, you would only need 1 if you use the Application.SelectionChange event. However, you wouldn't need any if you utilize the Workbook class code behind (to trap the Workbook.SelectionChange event) or the Worksheet class code behind (to trap the Worksheet.SelectionChange) event. (Unless your issue is the "global variable reset" problem in VBA, for which there is only one solution: error handling everywhere. Do not allow any unhandled errors, instead log them and/or "soft-report" an error as a message box to the user.)

You might also need to trap the Worksheet.Activate() and Worksheet.Deactivate() events (or the equivalent in the Workbook class) and/or the Workbook.Activate and Workbook.Deactivate() events so that you know when the user has switched worksheets and/or workbooks. The Window activate and deactivate events should make this approach complete. They could all call the same exact procedure, however, they all denote the same thing: the user changed the "focus", if you will.

If you don't like VBA, btw, you can do the same using VB.NET or C#.

[Edit: Dbb makes a very good point about the SelectionChange event not picking up a click when the user clicks within the currently selected cell. If you need to pick that up, then you would need to use subclassing.]

Beginner Python: AttributeError: 'list' object has no attribute

They are lists because you type them as lists in the dictionary:

bikes = {
    # Bike designed for children"
    "Trike": ["Trike", 20, 100],
    # Bike designed for everyone"
    "Kruzer": ["Kruzer", 50, 165]
    }

You should use the bike-class instead:

bikes = {
    # Bike designed for children"
    "Trike": Bike("Trike", 20, 100),
    # Bike designed for everyone"
    "Kruzer": Bike("Kruzer", 50, 165)
    }

This will allow you to get the cost of the bikes with bike.cost as you were trying to.

for bike in bikes.values():
    profit = bike.cost * margin
    print(bike.name + " : " + str(profit))

This will now print:

Kruzer : 33.0
Trike : 20.0

How to center cell contents of a LaTeX table whose columns have fixed widths?

\usepackage{array} in the preamble

then this:

\begin{tabular}{| >{\centering\arraybackslash}m{1in} | >{\centering\arraybackslash}m{1in} |}

note that the "m" for fixed with column is provided by the array package, and will give you vertical centering (if you don't want this just go back to "p"

Stupid error: Failed to load resource: net::ERR_CACHE_MISS

We get err_cache_miss error while using the bowser. Its mean there may be a problem with your browser. It due the items in the cache may be unusable or some configurations are not configured correctly. You may get the solution to clear browser data or Check browser extensions and remove extensions which you felt cause the problem or Resetting your browser or Update your browser or Disabling cache system. These are some tricks to come out this error.

phpmyadmin - count(): Parameter must be an array or an object that implements Countable

Edit file /usr/share/phpmyadmin/libraries/sql.lib.php

See an error on your error

./libraries/sql.lib.php#2038: PMA_isRememberSortingOrder(array)
./libraries/sql.lib.php#1984: PMA_executeQueryAndGetQueryResponse(

go to this line and remove the function call.

It works for me.

Testing pointers for validity (C/C++)

In general, it's impossible to do. Here's one particularly nasty case:

struct Point2d {
    int x;
    int y;
};

struct Point3d {
    int x;
    int y;
    int z;
};

void dump(Point3 *p)
{
    printf("[%d %d %d]\n", p->x, p->y, p->z);
}

Point2d points[2] = { {0, 1}, {2, 3} };
Point3d *p3 = reinterpret_cast<Point3d *>(&points[0]);
dump(p3);

On many platforms, this will print out:

[0 1 2]

You're forcing the runtime system to incorrectly interpret bits of memory, but in this case it's not going to crash, because the bits all make sense. This is part of the design of the language (look at C-style polymorphism with struct inaddr, inaddr_in, inaddr_in6), so you can't reliably protect against it on any platform.

How can I upgrade NumPy?

If you don't encounter any permission errors with

pip install -U numpy

try:

pip install --user -U numpy

PHP - Merging two arrays into one array (also Remove Duplicates)

try to use the array_unique()

this elminates duplicated data inside the list of your arrays..

How can I calculate divide and modulo for integers in C#?

Division is performed using the / operator:

result = a / b;

Modulo division is done using the % operator:

result = a % b;

How do you remove all the options of a select box and then add one option and select it with jQuery?

Try

mySelect.innerHTML = `<option selected value="whatever">text</option>`

_x000D_
_x000D_
function setOne() {
  console.log({mySelect});
  mySelect.innerHTML = `<option selected value="whatever">text</option>`;
}
_x000D_
<button onclick="setOne()" >set one</button>
<Select id="mySelect" size="9"> 
 <option value="1">old1</option>
 <option value="2">old2</option>
 <option value="3">old3</option>
</Select>
_x000D_
_x000D_
_x000D_

What does java:comp/env/ do?

There is also a property resourceRef of JndiObjectFactoryBean that is, when set to true, used to automatically prepend the string java:comp/env/ if it is not already present.

<bean id="someId" class="org.springframework.jndi.JndiObjectFactoryBean">
  <property name="jndiName" value="jdbc/loc"/>
  <property name="resourceRef" value="true"/>
</bean>

How to add an extra column to a NumPy array

I think:

np.column_stack((a, zeros(shape(a)[0])))

is more elegant.

Find the least number of coins required that can make any change from 1 to 99 cents

What you are looking for is Dynamic Programming.

You don't actually have to enumerate all the possible combinations for every possible values, because you can build it on top of previous answers.

You algorithm need to take 2 parameters:

  • The list of possible coin values, here [1, 5, 10, 25]
  • The range to cover, here [1, 99]

And the goal is to compute the minimal set of coins required for this range.

The simplest way is to proceed in a bottom-up fashion:

Range     Number of coins (in the minimal set)
          1   5   10   25
[1,1]     1
[1,2]     2
[1,3]     3
[1,4]     4
[1,5]     5
[1,5]*    4   1             * two solutions here
[1,6]     4   1
[1,9]     4   1
[1,10]    5   1             * experience tells us it's not the most viable one :p
[1,10]    4   2             * not so viable either
[1,10]    4   1   1
[1,11]    4   1   1
[1,19]    4   1   1
[1,20]    5   1   1         * not viable (in the long run)
[1,20]    4   2   1         * not viable (in the long run)
[1,20]    4   1   2

It is somewhat easy, at each step we can proceed by adding at most one coin, we just need to know where. This boils down to the fact that the range [x,y] is included in [x,y+1] thus the minimal set for [x,y+1] should include the minimal set for [x,y].

As you may have noticed though, sometimes there are indecisions, ie multiple sets have the same number of coins. In this case, it can only be decided later on which one should be discarded.

It should be possible to improve its running time, when noticing that adding a coin usually allows you to cover a far greater range that the one you added it for, I think.

For example, note that:

 [1,5]    4*1  1*5
 [1,9]    4*1  1*5

we add a nickel to cover [1,5] but this gives us up to [1,9] for free!

However, when dealing with outrageous input sets [2,3,5,10,25] to cover [2,99], I am unsure as how to check quickly the range covered by the new set, or it would be actually more efficient.

How to debug Spring Boot application with Eclipse?

The best solution in my opinion is add a plugin in the pom.xml, and you don't need to do anything else all the time:

<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <jvmArguments>
                        -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=9898
                    </jvmArguments>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

Getting GET "?" variable in laravel

I haven't tested on other Laravel versions but on 5.3-5.8 you reference the query parameter as if it were a member of the Request class.

1. Url

http://example.com/path?page=2

2. In a route callback or controller action using magic method Request::__get()

Route::get('/path', function(Request $request){
 dd($request->page);
}); 

//or in your controller
public function foo(Request $request){
 dd($request->page);
}

//NOTE: If you are wondering where the request instance is coming from, Laravel automatically injects the request instance from the IOC container
//output
"2"

3. Default values

We can also pass in a default value which is returned if a parameter doesn't exist. It's much cleaner than a ternary expression that you'd normally use with the request globals

   //wrong way to do it in Laravel
   $page = isset($_POST['page']) ? $_POST['page'] : 1; 

   //do this instead
   $request->get('page', 1);

   //returns page 1 if there is no page
   //NOTE: This behaves like $_REQUEST array. It looks in both the
   //request body and the query string
   $request->input('page', 1);

4. Using request function

$page = request('page', 1);
//returns page 1 if there is no page parameter in the query  string
//it is the equivalent of
$page = 1; 
if(!empty($_GET['page'])
   $page = $_GET['page'];

The default parameter is optional therefore one can omit it

5. Using Request::query()

While the input method retrieves values from entire request payload (including the query string), the query method will only retrieve values from the query string

//this is the equivalent of retrieving the parameter
//from the $_GET global array
$page = $request->query('page');

//with a default
$page = $request->query('page', 1);

6. Using the Request facade

$page = Request::get('page');

//with a default value
$page = Request::get('page', 1);

You can read more in the official documentation https://laravel.com/docs/5.8/requests

Remove whitespaces inside a string in javascript

Probably because you forgot to implement the solution in the accepted answer. That's the code that makes trim() work.

update

This answer only applies to older browsers. Newer browsers apparently support trim() natively.

How to start a background process in Python?

You probably want to start investigating the os module for forking different threads (by opening an interactive session and issuing help(os)). The relevant functions are fork and any of the exec ones. To give you an idea on how to start, put something like this in a function that performs the fork (the function needs to take a list or tuple 'args' as an argument that contains the program's name and its parameters; you may also want to define stdin, out and err for the new thread):

try:
    pid = os.fork()
except OSError, e:
    ## some debug output
    sys.exit(1)
if pid == 0:
    ## eventually use os.putenv(..) to set environment variables
    ## os.execv strips of args[0] for the arguments
    os.execv(args[0], args)

Pandas: how to change all the values of a column?

As @DSM points out, you can do this more directly using the vectorised string methods:

df['Date'].str[-4:].astype(int)

Or using extract (assuming there is only one set of digits of length 4 somewhere in each string):

df['Date'].str.extract('(?P<year>\d{4})').astype(int)

An alternative slightly more flexible way, might be to use apply (or equivalently map) to do this:

df['Date'] = df['Date'].apply(lambda x: int(str(x)[-4:]))
             #  converts the last 4 characters of the string to an integer

The lambda function, is taking the input from the Date and converting it to a year.
You could (and perhaps should) write this more verbosely as:

def convert_to_year(date_in_some_format):
    date_as_string = str(date_in_some_format)  # cast to string
    year_as_string = date_in_some_format[-4:] # last four characters
    return int(year_as_string)

df['Date'] = df['Date'].apply(convert_to_year)

Perhaps 'Year' is a better name for this column...

How to add an item to a drop down list in ASP.NET?

Try following code;

DropDownList1.Items.Add(new ListItem(txt_box1.Text));

How to generate the "create table" sql statement for an existing table in postgreSQL

pg_dump -h XXXXXXXXXXX.us-west-1.rds.amazonaws.com -U anyuser -t tablename -s

Differences between CHMOD 755 vs 750 permissions set

0755 = User:rwx Group:r-x World:r-x

0750 = User:rwx Group:r-x World:--- (i.e. World: no access)

r = read
w = write
x = execute (traverse for directories)

Cancel split window in Vim

To close all splits, I usually place the cursor in the window that shall be the on-ly visible one and then do :on which makes the current window the on-ly visible window. Nice mnemonic to remember.


Edit: :help :on showed me that these commands are the same:

  • :on
  • :only
  • CTRL-w CTRL-o
  • And yes, also CTRL-W o has the same effect (as Nathan answered).

Each of these four closes all windows except the active one.

How to determine if OpenSSL and mod_ssl are installed on Apache2

To determine openssl & ssl_module

# rpm -qa | grep openssl
openssl-libs-1.0.1e-42.el7.9.x86_64
openssl-1.0.1e-42.el7.9.x86_64
openssl098e-0.9.8e-29.el7.centos.2.x86_64
openssl-devel-1.0.1e-42.el7.9.x86_64

mod_ssl

# httpd -M | grep ssl

or

# rpm -qa | grep ssl

Is it possible to use global variables in Rust?

Look at the const and static section of the Rust book.

You can use something as follows:

const N: i32 = 5; 

or

static N: i32 = 5;

in global space.

But these are not mutable. For mutability, you could use something like:

static mut N: i32 = 5;

Then reference them like:

unsafe {
    N += 1;

    println!("N: {}", N);
}

How can I get a random number in Kotlin?

As of kotlin 1.2, you could write:

(1..3).shuffled().last()

Just be aware it's big O(n), but for a small list (especially of unique values) it's alright :D

Check if string contains only digits

c="123".match(/\D/) == null #true
c="a12".match(/\D/) == null #false

If a string contains only digits it will return null

How do I create a timer in WPF?

Adding to the above. You use the Dispatch timer if you want the tick events marshalled back to the UI thread. Otherwise I would use System.Timers.Timer.

Comparing strings by their alphabetical order

For alphabetical order following nationalization, use Collator.

//Get the Collator for US English and set its strength to PRIMARY
Collator usCollator = Collator.getInstance(Locale.US);
usCollator.setStrength(Collator.PRIMARY);
if( usCollator.compare("abc", "ABC") == 0 ) {
    System.out.println("Strings are equivalent");
}

For a list of supported locales, see JDK 8 and JRE 8 Supported Locales.

Init function in javascript and how it works

The way I usually explain this to people is to show how it's similar to other JavaScript patterns.

First, you should know that there are two ways to declare a function (actually, there's at least five, but these are the two main culprits):

function foo() {/*code*/}

and

var foo = function() {/*code*/};

Even if this construction looks strange, you probably use it all the time when attaching events:

window.onload=function(){/*code*/};

You should notice that the second form is not much different from a regular variable declaration:

var bar = 5;
var baz = 'some string';
var foo = function() {/*code*/};

But in JavaScript, you always have the choice between using a value directly or through a variable. If bar is 5, then the next two statements are equivalent:

var myVal = bar * 100; // use 'bar'
var myVal = 5 * 100;   // don't use 'bar'

Well, if you can use 5 on its own, why can't you use function() {\*code*\} on its own too? In fact, you can. And that's called an anonymous function. So these two examples are equivalent as well:

var foo = function() {/*code*/}; // use 'foo'
foo();                           

(function(){/*code*/})();        // don't use 'foo' 

The only difference you should see is in the extra brackets. That's simply because if you start a line with the keyword function, the parser will think you are declaring a function using the very first pattern at the top of this answer and throw a syntax error exception. So wrap your entire anonymous function inside a pair of braces and the problem goes away.

In other words, the following three statements are valid:

5;                        // pointless and stupid
'some string';            // pointless and stupid
(function(){/*code*/})(); // wonderfully powerful

[EDIT in 2020]

The previous version of my answer recommended Douglas Crockford's form of parens-wrapping for these "immediately invoked anonymous functions". User @RayLoveless recommended in 2012 to use the version shown now. Back then, before ES6 and arrow functions, there was no obvious idiomatic difference; you simply had to prevent the statement starting with the function keyword. In fact, there were lots of ways to do that. But using parens, these two statements were syntactically and idiomatically equivalent:

( function() { /* code */}() );
( function() { /* code */} )();

But user @zentechinc's comment below reminds me that arrow functions change all this. So now only one of these statements is correct.

( () => { /* code */ }() ); // Syntax error
( () => { /* code */ } )();

Why on earth does this matter? Actually, it's pretty easy to demonstrate. Remember an arrow function can come in two basic forms:

() => { return 5; };       // With a function body
() => { console.log(5); };

() => 5;                   // Or with a single expression
() => console.log(5);

Without parens wrapping this second type of arrow function, you end up with an idiomatic mess:

() => 5();              // How do you invoke a 5?
() => console.log(5)(); // console.log does not return a function!

jQuery each loop in table row

Use immediate children selector >:

$('#tblOne > tbody  > tr')

Description: Selects all direct child elements specified by "child" of elements specified by "parent".

Sorting a vector of custom objects

Sorting such a vector or any other applicable (mutable input iterator) range of custom objects of type X can be achieved using various methods, especially including the use of standard library algorithms like

Since most of the techniques, to obtain relative ordering of X elements, have already been posted, I'll start by some notes on "why" and "when" to use the various approaches.

The "best" approach will depend on different factors:

  1. Is sorting ranges of X objects a common or a rare task (will such ranges be sorted a mutiple different places in the program or by library users)?
  2. Is the required sorting "natural" (expected) or are there multiple ways the type could be compared to itself?
  3. Is performance an issue or should sorting ranges of X objects be foolproof?

If sorting ranges of X is a common task and the achieved sorting is to be expected (i.e. X just wraps a single fundamental value) then on would probably go for overloading operator< since it enables sorting without any fuzz (like correctly passing proper comparators) and repeatedly yields expected results.

If sorting is a common task or likely to be required in different contexts, but there are multiple criteria which can be used to sort X objects, I'd go for Functors (overloaded operator() functions of custom classes) or function pointers (i.e. one functor/function for lexical ordering and another one for natural ordering).

If sorting ranges of type X is uncommon or unlikely in other contexts I tend to use lambdas instead of cluttering any namespace with more functions or types.

This is especially true if the sorting is not "clear" or "natural" in some way. You can easily get the logic behind the ordering when looking at a lambda that is applied in-place whereas operator< is opague at first sight and you'd have to look the definition up to know what ordering logic will be applied.

Note however, that a single operator< definition is a single point of failure whereas multiple lambas are multiple points of failure and require a more caution.

If the definition of operator< isn't available where the sorting is done / the sort template is compiled, the compiler might be forced to make a function call when comparing objects, instead of inlining the ordering logic which might be a severe drawback (at least when link time optimization/code generation is not applied).

Ways to achieve comparability of class X in order to use standard library sorting algorithms

Let std::vector<X> vec_X; and std::vector<Y> vec_Y;

1. Overload T::operator<(T) or operator<(T, T) and use standard library templates that do not expect a comparison function.

Either overload member operator<:

struct X {
  int i{}; 
  bool operator<(X const &r) const { return i < r.i; } 
};
// ...
std::sort(vec_X.begin(), vec_X.end());

or free operator<:

struct Y {
  int j{}; 
};
bool operator<(Y const &l, Y const &r) { return l.j < r.j; }
// ...
std::sort(vec_Y.begin(), vec_Y.end());

2. Use a function pointer with a custom comparison function as sorting function parameter.

struct X {
  int i{};  
};
bool X_less(X const &l, X const &r) { return l.i < r.i; }
// ...
std::sort(vec_X.begin(), vec_X.end(), &X_less);

3. Create a bool operator()(T, T) overload for a custom type which can be passed as comparison functor.

struct X {
  int i{};  
  int j{};
};
struct less_X_i
{
    bool operator()(X const &l, X const &r) const { return l.i < r.i; }
};
struct less_X_j
{
    bool operator()(X const &l, X const &r) const { return l.j < r.j; }
};
// sort by i
std::sort(vec_X.begin(), vec_X.end(), less_X_i{});
// or sort by j
std::sort(vec_X.begin(), vec_X.end(), less_X_j{});

Those function object definitions can be written a little more generic using C++11 and templates:

struct less_i
{ 
    template<class T, class U>
    bool operator()(T&& l, U&& r) const { return std::forward<T>(l).i < std::forward<U>(r).i; }
};

which can be used to sort any type with member i supporting <.

4. Pass an anonymus closure (lambda) as comparison parameter to the sorting functions.

struct X {
  int i{}, j{};
};
std::sort(vec_X.begin(), vec_X.end(), [](X const &l, X const &r) { return l.i < r.i; });

Where C++14 enables a even more generic lambda expression:

std::sort(a.begin(), a.end(), [](auto && l, auto && r) { return l.i < r.i; });

which could be wrapped in a macro

#define COMPARATOR(code) [](auto && l, auto && r) -> bool { return code ; }

making ordinary comparator creation quite smooth:

// sort by i
std::sort(v.begin(), v.end(), COMPARATOR(l.i < r.i));
// sort by j
std::sort(v.begin(), v.end(), COMPARATOR(l.j < r.j));

CodeIgniter : Unable to load the requested file:

I was getting this error in PyroCMS.

You can improve the error message in the Loader.php file that is in the code of the library.

Open the Loader.php file and find any calls to show_error. I replaced mine with the following:

show_error(sprintf("Unable to load the requested file: \"%s\" with instance title of \"%s\"", $_ci_file, $_ci_data['_ci_vars']['options']['instance_title']));

I was then able to see which file was causing the issues for me.

converting string to long in python

Well, longs can't hold anything but integers.

One option is to use a float: float('234.89')

The other option is to truncate or round. Converting from a float to a long will truncate for you: long(float('234.89'))

>>> long(float('1.1'))
1L
>>> long(float('1.9'))
1L
>>> long(round(float('1.1')))
1L
>>> long(round(float('1.9')))
2L

Loading scripts after page load?

_x000D_
_x000D_
<script type="text/javascript">_x000D_
$(window).bind("load", function() { _x000D_
_x000D_
// your javascript event_x000D_
_x000D_
)};_x000D_
</script>
_x000D_
_x000D_
_x000D_

What do &lt; and &gt; stand for?

In HTML, the less-than sign is used at the beginning of tags. if you use this bracket "<test1>" in content, your bracket content will be unvisible, html renderer is assuming it as a html tag, changing chars with it's ASCI numbers prevents the issue.

with html friendly name:

  &lt;test1&gt; 

or with asci number:

 &#60;test1&#62;

or comple asci:

&#60;&#116;&#101;&#115;&#116;&#49;&#62;

result: <test1>

asci referance: https://www.w3schools.com/charsets/ref_html_ascii.asp

Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

In all these scenarios outerScopeVar is modified or assigned a value asynchronously or happening in a later time(waiting or listening for some event to occur),for which the current execution will not wait.So all these cases current execution flow results in outerScopeVar = undefined

Let's discuss each examples(I marked the portion which is called asynchronously or delayed for some events to occur):

1.

enter image description here

Here we register an eventlistner which will be executed upon that particular event.Here loading of image.Then the current execution continuous with next lines img.src = 'lolcat.png'; and alert(outerScopeVar); meanwhile the event may not occur. i.e, funtion img.onload wait for the referred image to load, asynchrously. This will happen all the folowing example- the event may differ.

2.

2

Here the timeout event plays the role, which will invoke the handler after the specified time. Here it is 0, but still it registers an asynchronous event it will be added to the last position of the Event Queue for execution, which makes the guaranteed delay.

3.

enter image description here This time ajax callback.

4.

enter image description here

Node can be consider as a king of asynchronous coding.Here the marked function is registered as a callback handler which will be executed after reading the specified file.

5.

enter image description here

Obvious promise (something will be done in future) is asynchronous. see What are the differences between Deferred, Promise and Future in JavaScript?

https://www.quora.com/Whats-the-difference-between-a-promise-and-a-callback-in-Javascript

How can I solve ORA-00911: invalid character error?

Remove the semicolon (;), backtick (``) etc. from inside a query

API Gateway CORS: no 'Access-Control-Allow-Origin' header

Got my sample working: I just inserted 'Access-Control-Allow-Origin': '*', inside headers:{} in the generated nodejs Lambda function. I made no changes to the Lambda-generated API layer.

Here's my NodeJS:

'use strict';
const doc = require('dynamodb-doc');
const dynamo = new doc.DynamoDB();
exports.handler = ( event, context, callback ) => {
    const done = ( err, res ) => callback( null, {
        statusCode: err ? '400' : '200',
        body: err ? err.message : JSON.stringify(res),
        headers:{ 'Access-Control-Allow-Origin' : '*' },
    });
    switch( event.httpMethod ) {
        ...
    }
};

Here's my AJAX call

$.ajax({
    url: 'https://x.execute-api.x-x-x.amazonaws.com/prod/fnXx?TableName=x',
    type: 'GET',
    beforeSend: function(){ $( '#loader' ).show();},
    success: function( res ) { alert( JSON.stringify(res) ); },
    error:function(e){ alert('Lambda returned error\n\n' + e.responseText); },
    complete:function(){ $('#loader').hide(); }
});

Difference between "on-heap" and "off-heap"

Not 100%; however, it sounds like the heap is an object or set of allocated space (on RAM) that is built into the functionality of the code either Java itself or more likely functionality from ehcache itself, and the off-heap Ram is there own system as well; however, it sounds like this is one magnitude slower as it is not as organized, meaning it may not use a heap (meaning one long set of space of ram), and instead uses different address spaces likely making it slightly less efficient.

Then of course the next tier lower is hard-drive space itself.

I don't use ehcache, so you may not want to trust me, but that what is what I gathered from their documentation.

How to check if all list items have the same value and return it, or return an “otherValue” if they don’t?

A slight variation on the above simplified approach.

var result = yyy.Distinct().Count() == yyy.Count();

Changing tab bar item image and text color iOS

Swift 3

First of all, make sure you have added the BOOLEAN key "View controller-based status bar appearance" to Info.plist, and set the value to "NO".

Appdelegate.swift

Insert code somewhere after "launchOptions:[UIApplicationLaunchOptionsKey: Any]?) -> Bool {"

  1. Change the color of the tab bar itself with RGB color value:

UITabBar.appearance().barTintColor = UIColor(red: 0.145, green: 0.592, blue: 0.804, alpha: 1.00)

OR one of the default UI colors:

UITabBar.appearance().barTintColor = UIColor.white)


  1. Change the text color of the tab items:

The selected item

UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.white], for: .selected)

The inactive items

UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.black], for: .normal)

  1. To change the color of the image, I believe the easiest approach is to make to separate images, one for each state.

If you don´t make the icons from scratch, alternating black and white versions are relatively easy to make in Photoshop.


Adobe Photoshop (almost any version will do)

Make sure your icon image has transparent background, and the icon itself is solid black (or close).

Open the image file, save it under a different file name (e.g. exampleFilename-Inverted.png)

In the "Adjustments" submenu on the "Image" menu:

Click "Invert"

You now have a negative of your original icon.

In XCode, set one of the images as "Selected Image" under the Tab Bar Properties in your storyboard, and specify the "inactive" version under "Bar Item" image.

Ta-Da

How do you force a makefile to rebuild a target

One trick that used to be documented in a Sun manual for make is to use a (non-existent) target '.FORCE'. You could do this by creating a file, force.mk, that contains:

.FORCE:
$(FORCE_DEPS): .FORCE

Then, assuming your existing makefile is called makefile, you could run:

make FORCE_DEPS=release -f force.mk -f makefile release

Since .FORCE does not exist, anything that depends on it will be out of date and rebuilt.

All this will work with any version of make; on Linux, you have GNU Make and can therefore use the .PHONY target as discussed.

It is also worth considering why make considers release to be up to date. This could be because you have a touch release command in amongst the commands executed; it could be because there is a file or directory called 'release' that exists and has no dependencies and so is up to date. Then there's the actual reason...

Limit number of characters allowed in form input text field

The following code includes a counted...

_x000D_
_x000D_
var count = 1;_x000D_
_x000D_
do {_x000D_
    function count_down(obj, count){_x000D_
_x000D_
    let element = document.getElementById('count'+ count);_x000D_
_x000D_
    element.innerHTML = 80 - obj.value.length;_x000D_
_x000D_
    if(80 - obj.value.length < 5){_x000D_
        element.style.color = "firebrick";_x000D_
    }else{_x000D_
        element.style.color = "#333";_x000D_
    }_x000D_
}_x000D_
count++;_x000D_
} while (count < 20); 
_x000D_
.text-input {_x000D_
    padding: 8px 16px;_x000D_
    width: 50%;_x000D_
    margin-bottom: 5px;_x000D_
    margin-top: 10px;_x000D_
    font-size: 20px;_x000D_
    font-weight: 700;_x000D_
    font-family: Raleway;_x000D_
    border: 1px solid dodgerblue;_x000D_
  }
_x000D_
<p><input placeholder="Title" id="bike-input-title" onkeyup="count_down(this, 3)" maxlength="80"  class="text-input" name="bikeTitle" ></p>_x000D_
        <span id="count3" style="float: right; font-family: Raleway; font-size:20px; font-weight:600; margin-top:-5px;">80</span><br>
_x000D_
_x000D_
_x000D_

MySQL SELECT query string matching

Incorrect:

SELECT * FROM customers WHERE name LIKE '%Bob Smith%';

Instead:

select count(*)
from rearp.customers c
where c.name  LIKE '%Bob smith.8%';

select count will just query (totals)

C will link the db.table to the names row you need this to index

LIKE should be obvs

8 will call all references in DB 8 or less (not really needed but i like neatness)

What are invalid characters in XML

For XSL (on really lazy days) I use:

capture="&amp;(?!amp;)" capturereplace="&amp;amp;"

to translate all &-signs that aren't follwed på amp; to proper ones.

We have cases where the input is in CDATA but the system which uses the XML doesn't take it into account. It's a sloppy fix, beware...

How do you get the magnitude of a vector in Numpy?

The function you're after is numpy.linalg.norm. (I reckon it should be in base numpy as a property of an array -- say x.norm() -- but oh well).

import numpy as np
x = np.array([1,2,3,4,5])
np.linalg.norm(x)

You can also feed in an optional ord for the nth order norm you want. Say you wanted the 1-norm:

np.linalg.norm(x,ord=1)

And so on.

getting the index of a row in a pandas apply function

To answer the original question: yes, you can access the index value of a row in apply(). It is available under the key name and requires that you specify axis=1 (because the lambda processes the columns of a row and not the rows of a column).

Working example (pandas 0.23.4):

>>> import pandas as pd
>>> df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])
>>> df.set_index('a', inplace=True)
>>> df
   b  c
a      
1  2  3
4  5  6
>>> df['index_x10'] = df.apply(lambda row: 10*row.name, axis=1)
>>> df
   b  c  index_x10
a                 
1  2  3         10
4  5  6         40

why $(window).load() is not working in jQuery?

in jquery-3.1.1

_x000D_
_x000D_
$("#id").load(function(){_x000D_
//code goes here});
_x000D_
_x000D_
_x000D_

will not work because load function is no more work

Create a CSV File for a user in PHP

Hey It works very well....!!!! Thanks Peter Mortensen and Connor Burton

<?php
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

ini_set('display_errors',1);
$private=1;
error_reporting(E_ALL ^ E_NOTICE);

mysql_connect("localhost", "user", "pass") or die(mysql_error());
mysql_select_db("db") or die(mysql_error());

$start = $_GET["start"];
$end = $_GET["end"];

$query = "SELECT * FROM customers WHERE created>='{$start} 00:00:00'  AND created<='{$end} 23:59:59'   ORDER BY id";
$select_c = mysql_query($query) or die(mysql_error());

while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
    $result.="{$row['email']},";
    $result.="\n";
    echo $result;
}

?>

wget ssl alert handshake failure

I was having this problem on Ubuntu 12.04.3 LTS (well beyond EOL, I know...) and got around it with:

sudo apt-get update && sudo apt-get install ca-certificates

OTP (token) should be automatically read from the message

I implemented something of that such. But, here is what I did when the message comes in, I retrieve only the six digit code, bundle it in an intent and send it to the activity or fragment needing it and verifies the code. The example shows you the way to get the sms already. Look at the code below for illustration on how to send using LocalBrodcastManager and if your message contains more texts E.g Greetings, standardize it to help you better. E.g "Your verification code is: 84HG73" you can create a regex pattern like this ([0-9]){2}([A-Z]){2}([0-9]){2} which means two ints, two [capital] letters and two ints. Good Luck!

After discarding all un needed info from the message

 Intent intent = new Intent("AddedItem");
 intent.putExtra("items", code);
 LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent); 

And the Fragment/Activity receiving it

@Override
public void onResume() {
    LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver, new IntentFilter("AddedItem"));
    super.onResume();
}

@Override
public void onPause() {
    super.onDestroy();
    LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver);
}

And the code meant to handle the payload you collected

 private BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction()) {
            final String message = intent.getStringExtra("message");
            //Do whatever you want with the code here
        }
    }
};

Does that help a little bit. I did it better by using Callbacks

Browse for a directory in C#

Please don't try and roll your own with a TreeView/DirectoryInfo class. For one thing there are many nice features you get for free (icons/right-click/networks) by using SHBrowseForFolder. For another there are a edge cases/catches you will likely not be aware of.

VueJS conditionally add an attribute for an element

You can pass boolean by coercing it, put !! before the variable.

let isRequired = '' || null || undefined
<input :required="!!isRequired"> // it will coerce value to respective boolean 

But I would like to pull your attention for the following case where the receiving component has defined type for props. In that case, if isRequired has defined type to be string then passing boolean make it type check fails and you will get Vue warning. To fix that you may want to avoid passing that prop, so just put undefined fallback and the prop will not sent to component

let isValue = false
<any-component
  :my-prop="isValue ? 'Hey I am when the value exist' : undefined"
/>

Explanation

I have been through the same problem, and tried above solutions !! Yes, I don't see the prop but that actually does not fulfils what required here.

My problem -

let isValid = false
<any-component
  :my-prop="isValue ? 'Hey I am when the value exist': false"
/>

In the above case, what I expected is not having my-prop get passed to the child component - <any-conponent/> I don't see the prop in DOM but In my <any-component/> component, an error pops out of prop type check failure. As in the child component, I am expecting my-prop to be a String but it is boolean.

myProp : {
 type: String,
 required: false,
 default: ''
}

Which means that child component did receive the prop even if it is false. Tweak here is to let the child component to take the default-value and also skip the check. Passed undefined works though!

<any-component
  :my-prop="isValue ? 'Hey I am when the value exist' : undefined"
/>
 

This works and my child prop is having the default value.

Is it possible to have a HTML SELECT/OPTION value as NULL using PHP?

All you need is a check on the post side of things.

if(empty($_REQUEST['type_id']) && $_REQUEST['type_id'] != 0)
    $_REQUEST['type_id'] = null;

How to add new contacts in android

Here I am posting a piece of code that i use to add a new contact. It works fine for me. I hope it will help you.

 String DisplayName = "XYZ";
 String MobileNumber = "123456";
 String HomeNumber = "1111";
 String WorkNumber = "2222";
 String emailID = "[email protected]";
 String company = "bad";
 String jobTitle = "abcd";

 ArrayList < ContentProviderOperation > ops = new ArrayList < ContentProviderOperation > ();

 ops.add(ContentProviderOperation.newInsert(
 ContactsContract.RawContacts.CONTENT_URI)
     .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
     .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
     .build());

 //------------------------------------------------------ Names
 if (DisplayName != null) {
     ops.add(ContentProviderOperation.newInsert(
     ContactsContract.Data.CONTENT_URI)
         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
         .withValue(ContactsContract.Data.MIMETYPE,
     ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
         .withValue(
     ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
     DisplayName).build());
 }

 //------------------------------------------------------ Mobile Number                     
 if (MobileNumber != null) {
     ops.add(ContentProviderOperation.
     newInsert(ContactsContract.Data.CONTENT_URI)
         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
         .withValue(ContactsContract.Data.MIMETYPE,
     ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
         .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, MobileNumber)
         .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
     ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
         .build());
 }

 //------------------------------------------------------ Home Numbers
 if (HomeNumber != null) {
     ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
         .withValue(ContactsContract.Data.MIMETYPE,
     ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
         .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, HomeNumber)
         .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
     ContactsContract.CommonDataKinds.Phone.TYPE_HOME)
         .build());
 }

 //------------------------------------------------------ Work Numbers
 if (WorkNumber != null) {
     ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
         .withValue(ContactsContract.Data.MIMETYPE,
     ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
         .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, WorkNumber)
         .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
     ContactsContract.CommonDataKinds.Phone.TYPE_WORK)
         .build());
 }

 //------------------------------------------------------ Email
 if (emailID != null) {
     ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
         .withValue(ContactsContract.Data.MIMETYPE,
     ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
         .withValue(ContactsContract.CommonDataKinds.Email.DATA, emailID)
         .withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK)
         .build());
 }

 //------------------------------------------------------ Organization
 if (!company.equals("") && !jobTitle.equals("")) {
     ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
         .withValue(ContactsContract.Data.MIMETYPE,
     ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
         .withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, company)
         .withValue(ContactsContract.CommonDataKinds.Organization.TYPE, ContactsContract.CommonDataKinds.Organization.TYPE_WORK)
         .withValue(ContactsContract.CommonDataKinds.Organization.TITLE, jobTitle)
         .withValue(ContactsContract.CommonDataKinds.Organization.TYPE, ContactsContract.CommonDataKinds.Organization.TYPE_WORK)
         .build());
 }

 // Asking the Contact provider to create a new contact                 
 try {
     getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
 } catch (Exception e) {
     e.printStackTrace();
     Toast.makeText(myContext, "Exception: " + e.getMessage(), Toast.LENGTH_SHORT).show();
 } 

Here is the code. Integrate it according to your need. I hope it will help.

Save Javascript objects in sessionStorage

Either you can use the accessors provided by the Web Storage API or you could write a wrapper/adapter. From your stated issue with defineGetter/defineSetter is sounds like writing a wrapper/adapter is too much work for you.

I honestly don't know what to tell you. Maybe you could reevaluate your opinion of what is a "ridiculous limitation". The Web Storage API is just what it's supposed to be, a key/value store.

How do I add a border to an image in HTML?

CSS

img{border:2px solid black;}

selecting an entire row based on a variable excel vba

I solved the problem for me by addressing also the worksheet first:

ws.rows(x & ":" & y).Select

without the reference to the worksheet (ws) I got an error.

How can I get customer details from an order in WooCommerce?

If you want customer's details that customer had entered while ordering, then you can use the following code:

$order = new WC_Order($order_id);
$billing_address = $order->get_billing_address();
$billing_address_html = $order->get_formatted_billing_address();

// For printing or displaying on the web page
$shipping_address = $order->get_shipping_address();
$shipping_address_html = $order->get_formatted_shipping_address(); // For printing or displaying on web page

Apart from this, $customer = new WC_Customer( $order_id ); can not get you customer details.

First of all, new WC_Customer() doesn't take any arguments.

Secondly, WC_Customer will get customer's details only when the user is logged in and he/she is not on the admin side. Instead he/she should be on website's front-end like the 'My Account', 'Shop', 'Cart', or 'Checkout' page.

How to make an anchor tag refer to nothing?

I know this is tagged as a jQuery question, but you can answer this with AngularJS, also.

in your element, add the ng-click directive and use the $event variable which is the click event... prevent its default behavior:

<a href="#" ng-click="$event.preventDefault()">

You can even pass the $event variable into a function:

<a href="#" ng-click="doSomething($event)">

in that function, you do whatever you want with the click event.

I am receiving warning in Facebook Application using PHP SDK

You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start(). The headers will be sent automatically when any HTML is output.

Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.

Move the session_start() to the top of your document :

<?php    session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php';    // more PHP code here. 

Jquery to change form action

Please, see this answer: https://stackoverflow.com/a/3863869/2096619

Quoting Tamlyn:

jQuery (1.4.2) gets confused if you have any form elements named "action". You can get around this by using the DOM attribute methods or simply avoid having form elements named "action".

<form action="foo">
  <button name="action" value="bar">Go</button>
</form>

<script type="text/javascript">
  $('form').attr('action', 'baz'); //this fails silently
  $('form').get(0).setAttribute('action', 'baz'); //this works
</script>

XAMPP: Couldn't start Apache (Windows 10)

If you have installed SQL Server, some of its services may block the port which XAMPP needs. I solved my problem by disabling SQL Server Reporting Services and now Apache starts without any problems.

Just open the services.msc, scroll down, and find SQL Server Reporting Services. Right click on it and click Stop.

Build and Install unsigned apk on device without the development server?

After you follow the first response, you can run your app using

react-native run-android --variant=debug

And your app will run without need for the packager

Removing address bar from browser (to view on Android)

The one below works for me every time..

This site also has a few other suggestions, but this no-nonsense, no-worry one is available in a github:gist and answers your question (pasted here for convenience):

function hideAddressBar()
{
  if(!window.location.hash)
  {
      if(document.height < window.outerHeight)
      {
          document.body.style.height = (window.outerHeight + 50) + 'px';
      }

      setTimeout( function(){ window.scrollTo(0, 1); }, 50 );
  }
}

window.addEventListener("load", function(){ if(!window.pageYOffset){ hideAddressBar(); } } );
window.addEventListener("orientationchange", hideAddressBar );

As far as I can tell, the combination of extra height added to the page (which caused problems for you) and the scrollTo() statement make the address bar disappear.

From the same site the 'simplest' solution to hiding the address bar is using the scrollTo() method:

window.addEventListener("load", function() { window.scrollTo(0, 1); });

This will hide the address bar until the user scrolls.

This site places the same method inside a timeout function (the justification is not explained, but it claims the code doesn't work well without it):

// When ready...
window.addEventListener("load",function() {
  // Set a timeout...
  setTimeout(function(){
    // Hide the address bar!
     window.scrollTo(0, 1);
  }, 0);
});

fatal: ambiguous argument 'origin': unknown revision or path not in the working tree

This worked for me on win replace REL_PATH_TO_FILE with the relative path to the file to remove Removing sensitive data from a repository The docs say full path - but that errored for me -so I tried rel path and it worked.

<from the repo dir>git filter-branch --force --index-filter "git rm --cached --ignore-unmatch REL_PATH_TO_FILE" --prune-empty --tag-name-filter cat -- --all

How can I fill a column with random numbers in SQL? I get the same value in every row

require_once('db/connect.php');

//rand(1000000 , 9999999);

$products_query = "SELECT id FROM products";
$products_result = mysqli_query($conn, $products_query);
$products_row = mysqli_fetch_array($products_result);
$ids_array = [];

do
{
    array_push($ids_array, $products_row['id']);
}
while($products_row = mysqli_fetch_array($products_result));

/*
echo '<pre>';
print_r($ids_array);
echo '</pre>';
*/
$row_counter = count($ids_array);

for ($i=0; $i < $row_counter; $i++)
{ 
    $current_row = $ids_array[$i];
    $rand = rand(1000000 , 9999999);
    mysqli_query($conn , "UPDATE products SET code='$rand' WHERE id='$current_row'");
}

Where is Python's sys.path initialized from?

"Initialized from the environment variable PYTHONPATH, plus an installation-dependent default"

-- http://docs.python.org/library/sys.html#sys.path

Trying to check if username already exists in MySQL database using PHP

Here's one that i wrote:

$error = false;
$sql= "SELECT username FROM users WHERE username = '$username'";
$checkSQL = mysqli_query($db, $checkSQL);

if(mysqli_num_rows($checkSQL) != 0) {
   $error = true;
   echo '<span class="error">Username taken.</span>';
}

Works like a charm!

Set JavaScript variable = null, or leave undefined?

Generally, I use null for values that I know can have a "null" state; for example

if(jane.isManager == false){
  jane.employees = null
}

Otherwise, if its a variable or function that's not defined yet (and thus, is not "usable" at the moment) but is supposed to be setup later, I usually leave it undefined.

iText - add content to existing PDF file

Gutch's code is close, but it'll only work right if:

  • There are no annotations (links, fields, etc), no Document Structure/Marked Content, no bookmarks, no document-level script, etc, etc, etc...
  • The page size happens to be A.4 (decent odds, but it won't work on any ol' PDF you happen to come across)
  • You don't mind losing all the original document metadata (producer, creation date, possibly author/title/keywords), and maybe the document ID. You can't copy the creation date and doc ID unless you do some pretty deep hackery on iText itself).

The Approved Method is to do it the other way around. Open the existing document with a PdfStamper, and use the returned PdfContentByte from getOverContent() to write text (and whatever else you might need) directly to the page. No second document needed.

And you can use a ColumnText to handle layout and such for you... no need to get down and dirty with beginText(),setFontAndSize(),drawText(),drawText()...,endText().

Run script on mac prompt "Permission denied"

To run in the administrator mode in mac

sudo su

Skip the headers when editing a csv file using Python

Inspired by Martijn Pieters' response.

In case you only need to delete the header from the csv file, you can work more efficiently if you write using the standard Python file I/O library, avoiding writing with the CSV Python library:

with open("tmob_notcleaned.csv", "rb") as infile, open("tmob_cleaned.csv", "wb") as outfile:
   next(infile)  # skip the headers
   outfile.write(infile.read())

search in java ArrayList

Personally I rarely write loops myself now when I can get away with it... I use the Jakarta commons libs:

Customer findCustomerByid(final int id){
    return (Customer) CollectionUtils.find(customers, new Predicate() {
        public boolean evaluate(Object arg0) {
            return ((Customer) arg0).getId()==id;
        }
    });
}

Yay! I saved one line!

JavaScript string and number conversion

To convert a string to a number, subtract 0. To convert a number to a string, add "" (the empty string).

5 + 1 will give you 6

(5 + "") + 1 will give you "51"

("5" - 0) + 1 will give you 6

MySQL query finding values in a comma separated string

FIND_IN_SET is your friend in this case

select * from shirts where FIND_IN_SET(1,colors) 

refresh div with jquery

I tried the first solution and it works but the end user can easily identify that the div's are refreshing as it is fadeIn(), without fade in i tried .toggle().toggle() and it works perfect. you can try like this

_x000D_
_x000D_
$("#panel").toggle().toggle();
_x000D_
_x000D_
_x000D_

it works perfectly for me as i'm developing a messenger and need to minimize and maximize the chat box's and this does it best rather than the above code.

How do I calculate a trendline for a graph?

Given that the trendline is straight, find the slope by choosing any two points and calculating:

(A) slope = (y1-y2)/(x1-x2)

Then you need to find the offset for the line. The line is specified by the equation:

(B) y = offset + slope*x

So you need to solve for offset. Pick any point on the line, and solve for offset:

(C) offset = y - (slope*x)

Now you can plug slope and offset into the line equation (B) and have the equation that defines your line. If your line has noise you'll have to decide on an averaging algorithm, or use curve fitting of some sort.

If your line isn't straight then you'll need to look into Curve fitting, or Least Squares Fitting - non trivial, but do-able. You'll see the various types of curve fitting at the bottom of the least squares fitting webpage (exponential, polynomial, etc) if you know what kind of fit you'd like.

Also, if this is a one-off, use Excel.

Remove the last character in a string in T-SQL?

Try this,

DECLARE @name NVARCHAR(MAX) SET @name='xxxxTHAMIZHMANI****'SELECT Substring(@name, 5, (len(@name)-8)) as UserNames

And the output will be like, THAMIZHMANI

What does 'super' do in Python?

some great answers here, but they do not tackle how to use super() in the case where different classes in the hierarchy have different signatures ... especially in the case of __init__

to answer that part and to be able to effectively use super() i'd suggest reading my answer super() and changing the signature of cooperative methods.

here's just the solution to this scenario:

  1. the top-level classes in your hierarchy must inherit from a custom class like SuperObject:
  2. if classes can take differing arguments, always pass all arguments you received on to the super function as keyword arguments, and, always accept **kwargs.
class SuperObject:        
    def __init__(self, **kwargs):
        print('SuperObject')
        mro = type(self).__mro__
        assert mro[-1] is object
        if mro[-2] is not SuperObject:
            raise TypeError(
                'all top-level classes in this hierarchy must inherit from SuperObject',
                'the last class in the MRO should be SuperObject',
                f'mro={[cls.__name__ for cls in mro]}'
            )

        # super().__init__ is guaranteed to be object.__init__        
        init = super().__init__
        init()

example usage:

class A(SuperObject):
    def __init__(self, **kwargs):
        print("A")
        super(A, self).__init__(**kwargs)

class B(SuperObject):
    def __init__(self, **kwargs):
        print("B")
        super(B, self).__init__(**kwargs)

class C(A):
    def __init__(self, age, **kwargs):
        print("C",f"age={age}")
        super(C, self).__init__(age=age, **kwargs)

class D(B):
    def __init__(self, name, **kwargs):
        print("D", f"name={name}")
        super(D, self).__init__(name=name, **kwargs)

class E(C,D):
    def __init__(self, name, age, *args, **kwargs):
        print( "E", f"name={name}", f"age={age}")
        super(E, self).__init__(name=name, age=age, *args, **kwargs)

E(name='python', age=28)

output:

E name=python age=28
C age=28
A
D name=python
B
SuperObject

Function to Calculate a CRC16 Checksum

crcany will generate efficient C code for any CRC, and includes a library of over one hundred known CRC definitions.

Efficient CRC code uses tables instead of bit-wise calculations. crcany generates both byte-wise routines and word-wise routines, the latter tuned to the architecture they are generated on. Word-wise is the fastest. Byte-wise is still much faster than bit-wise, but the implementation is more easily portable over architectures.

You do not seem to have a protocol definition with a specific CRC definition that you need to match. In this case, you can pick any 16-bit CRC in the catalog, and you will get good performance.

If you have a relatively low bit error rate, e.g. single digit number of errors per packet, and you want to maximize your error detection performance, you would need to look at the packet size you are applying the CRC to, assuming that that is constant or bounded, and look at the performance of the best polynomials in Philip Koopman's extensive research. The classic CRCs, such as the CCITT/Kermit 16-bit CRC or the X.25 16-bit CRC are not the best performers.

One of the good 16-bit performers in Koopman's tables that is also in the catalog of CRCs used in practice is CRC-16/DNP. It has very good performance detecting up to 6-bit errors in a packet. Following is the code generated by crcany for that CRC definition. This code assumes a little-endian architecture for the word-wise calculation, e.g. Intel x86 and x86-64, and it assumes that uintmax_t is 64 bits. crcany can be used to generate alternative code for big-endian and other word sizes.

crc16dnp.h:

// The _bit, _byte, and _word routines return the CRC of the len bytes at mem,
// applied to the previous CRC value, crc. If mem is NULL, then the other
// arguments are ignored, and the initial CRC, i.e. the CRC of zero bytes, is
// returned. Those routines will all return the same result, differing only in
// speed and code complexity. The _rem routine returns the CRC of the remaining
// bits in the last byte, for when the number of bits in the message is not a
// multiple of eight. The low bits bits of the low byte of val are applied to
// crc. bits must be in 0..8.

#include <stddef.h>

// Compute the CRC a bit at a time.
unsigned crc16dnp_bit(unsigned crc, void const *mem, size_t len);

// Compute the CRC of the low bits bits in val.
unsigned crc16dnp_rem(unsigned crc, unsigned val, unsigned bits);

// Compute the CRC a byte at a time.
unsigned crc16dnp_byte(unsigned crc, void const *mem, size_t len);

// Compute the CRC a word at a time.
unsigned crc16dnp_word(unsigned crc, void const *mem, size_t len);

crc16dnp.c:

#include <stdint.h>
#include "crc16dnp.h"

// This code assumes that unsigned is 4 bytes.

unsigned crc16dnp_bit(unsigned crc, void const *mem, size_t len) {
    unsigned char const *data = mem;
    if (data == NULL)
        return 0xffff;
    crc = ~crc;
    crc &= 0xffff;
    while (len--) {
        crc ^= *data++;
        for (unsigned k = 0; k < 8; k++)
            crc = crc & 1 ? (crc >> 1) ^ 0xa6bc : crc >> 1;
    }
    crc ^= 0xffff;
    return crc;
}

unsigned crc16dnp_rem(unsigned crc, unsigned val, unsigned bits) {
    crc = ~crc;
    crc &= 0xffff;
    val &= (1U << bits) - 1;
    crc ^= val;
    while (bits--)
        crc = crc & 1 ? (crc >> 1) ^ 0xa6bc : crc >> 1;
    crc ^= 0xffff;
    return crc;
}

#define table_byte table_word[0]

static unsigned short const table_word[][256] = {
   {0xed35, 0xdb6b, 0x8189, 0xb7d7, 0x344d, 0x0213, 0x58f1, 0x6eaf, 0x12bc, 0x24e2,
    0x7e00, 0x485e, 0xcbc4, 0xfd9a, 0xa778, 0x9126, 0x5f5e, 0x6900, 0x33e2, 0x05bc,
    0x8626, 0xb078, 0xea9a, 0xdcc4, 0xa0d7, 0x9689, 0xcc6b, 0xfa35, 0x79af, 0x4ff1,
    0x1513, 0x234d, 0xc49a, 0xf2c4, 0xa826, 0x9e78, 0x1de2, 0x2bbc, 0x715e, 0x4700,
    0x3b13, 0x0d4d, 0x57af, 0x61f1, 0xe26b, 0xd435, 0x8ed7, 0xb889, 0x76f1, 0x40af,
    0x1a4d, 0x2c13, 0xaf89, 0x99d7, 0xc335, 0xf56b, 0x8978, 0xbf26, 0xe5c4, 0xd39a,
    0x5000, 0x665e, 0x3cbc, 0x0ae2, 0xbe6b, 0x8835, 0xd2d7, 0xe489, 0x6713, 0x514d,
    0x0baf, 0x3df1, 0x41e2, 0x77bc, 0x2d5e, 0x1b00, 0x989a, 0xaec4, 0xf426, 0xc278,
    0x0c00, 0x3a5e, 0x60bc, 0x56e2, 0xd578, 0xe326, 0xb9c4, 0x8f9a, 0xf389, 0xc5d7,
    0x9f35, 0xa96b, 0x2af1, 0x1caf, 0x464d, 0x7013, 0x97c4, 0xa19a, 0xfb78, 0xcd26,
    0x4ebc, 0x78e2, 0x2200, 0x145e, 0x684d, 0x5e13, 0x04f1, 0x32af, 0xb135, 0x876b,
    0xdd89, 0xebd7, 0x25af, 0x13f1, 0x4913, 0x7f4d, 0xfcd7, 0xca89, 0x906b, 0xa635,
    0xda26, 0xec78, 0xb69a, 0x80c4, 0x035e, 0x3500, 0x6fe2, 0x59bc, 0x4b89, 0x7dd7,
    0x2735, 0x116b, 0x92f1, 0xa4af, 0xfe4d, 0xc813, 0xb400, 0x825e, 0xd8bc, 0xeee2,
    0x6d78, 0x5b26, 0x01c4, 0x379a, 0xf9e2, 0xcfbc, 0x955e, 0xa300, 0x209a, 0x16c4,
    0x4c26, 0x7a78, 0x066b, 0x3035, 0x6ad7, 0x5c89, 0xdf13, 0xe94d, 0xb3af, 0x85f1,
    0x6226, 0x5478, 0x0e9a, 0x38c4, 0xbb5e, 0x8d00, 0xd7e2, 0xe1bc, 0x9daf, 0xabf1,
    0xf113, 0xc74d, 0x44d7, 0x7289, 0x286b, 0x1e35, 0xd04d, 0xe613, 0xbcf1, 0x8aaf,
    0x0935, 0x3f6b, 0x6589, 0x53d7, 0x2fc4, 0x199a, 0x4378, 0x7526, 0xf6bc, 0xc0e2,
    0x9a00, 0xac5e, 0x18d7, 0x2e89, 0x746b, 0x4235, 0xc1af, 0xf7f1, 0xad13, 0x9b4d,
    0xe75e, 0xd100, 0x8be2, 0xbdbc, 0x3e26, 0x0878, 0x529a, 0x64c4, 0xaabc, 0x9ce2,
    0xc600, 0xf05e, 0x73c4, 0x459a, 0x1f78, 0x2926, 0x5535, 0x636b, 0x3989, 0x0fd7,
    0x8c4d, 0xba13, 0xe0f1, 0xd6af, 0x3178, 0x0726, 0x5dc4, 0x6b9a, 0xe800, 0xde5e,
    0x84bc, 0xb2e2, 0xcef1, 0xf8af, 0xa24d, 0x9413, 0x1789, 0x21d7, 0x7b35, 0x4d6b,
    0x8313, 0xb54d, 0xefaf, 0xd9f1, 0x5a6b, 0x6c35, 0x36d7, 0x0089, 0x7c9a, 0x4ac4,
    0x1026, 0x2678, 0xa5e2, 0x93bc, 0xc95e, 0xff00},
   {0x740f, 0xdf41, 0x6fea, 0xc4a4, 0x43c5, 0xe88b, 0x5820, 0xf36e, 0x1b9b, 0xb0d5,
    0x007e, 0xab30, 0x2c51, 0x871f, 0x37b4, 0x9cfa, 0xab27, 0x0069, 0xb0c2, 0x1b8c,
    0x9ced, 0x37a3, 0x8708, 0x2c46, 0xc4b3, 0x6ffd, 0xdf56, 0x7418, 0xf379, 0x5837,
    0xe89c, 0x43d2, 0x8726, 0x2c68, 0x9cc3, 0x378d, 0xb0ec, 0x1ba2, 0xab09, 0x0047,
    0xe8b2, 0x43fc, 0xf357, 0x5819, 0xdf78, 0x7436, 0xc49d, 0x6fd3, 0x580e, 0xf340,
    0x43eb, 0xe8a5, 0x6fc4, 0xc48a, 0x7421, 0xdf6f, 0x379a, 0x9cd4, 0x2c7f, 0x8731,
    0x0050, 0xab1e, 0x1bb5, 0xb0fb, 0xdf24, 0x746a, 0xc4c1, 0x6f8f, 0xe8ee, 0x43a0,
    0xf30b, 0x5845, 0xb0b0, 0x1bfe, 0xab55, 0x001b, 0x877a, 0x2c34, 0x9c9f, 0x37d1,
    0x000c, 0xab42, 0x1be9, 0xb0a7, 0x37c6, 0x9c88, 0x2c23, 0x876d, 0x6f98, 0xc4d6,
    0x747d, 0xdf33, 0x5852, 0xf31c, 0x43b7, 0xe8f9, 0x2c0d, 0x8743, 0x37e8, 0x9ca6,
    0x1bc7, 0xb089, 0x0022, 0xab6c, 0x4399, 0xe8d7, 0x587c, 0xf332, 0x7453, 0xdf1d,
    0x6fb6, 0xc4f8, 0xf325, 0x586b, 0xe8c0, 0x438e, 0xc4ef, 0x6fa1, 0xdf0a, 0x7444,
    0x9cb1, 0x37ff, 0x8754, 0x2c1a, 0xab7b, 0x0035, 0xb09e, 0x1bd0, 0x6f20, 0xc46e,
    0x74c5, 0xdf8b, 0x58ea, 0xf3a4, 0x430f, 0xe841, 0x00b4, 0xabfa, 0x1b51, 0xb01f,
    0x377e, 0x9c30, 0x2c9b, 0x87d5, 0xb008, 0x1b46, 0xabed, 0x00a3, 0x87c2, 0x2c8c,
    0x9c27, 0x3769, 0xdf9c, 0x74d2, 0xc479, 0x6f37, 0xe856, 0x4318, 0xf3b3, 0x58fd,
    0x9c09, 0x3747, 0x87ec, 0x2ca2, 0xabc3, 0x008d, 0xb026, 0x1b68, 0xf39d, 0x58d3,
    0xe878, 0x4336, 0xc457, 0x6f19, 0xdfb2, 0x74fc, 0x4321, 0xe86f, 0x58c4, 0xf38a,
    0x74eb, 0xdfa5, 0x6f0e, 0xc440, 0x2cb5, 0x87fb, 0x3750, 0x9c1e, 0x1b7f, 0xb031,
    0x009a, 0xabd4, 0xc40b, 0x6f45, 0xdfee, 0x74a0, 0xf3c1, 0x588f, 0xe824, 0x436a,
    0xab9f, 0x00d1, 0xb07a, 0x1b34, 0x9c55, 0x371b, 0x87b0, 0x2cfe, 0x1b23, 0xb06d,
    0x00c6, 0xab88, 0x2ce9, 0x87a7, 0x370c, 0x9c42, 0x74b7, 0xdff9, 0x6f52, 0xc41c,
    0x437d, 0xe833, 0x5898, 0xf3d6, 0x3722, 0x9c6c, 0x2cc7, 0x8789, 0x00e8, 0xaba6,
    0x1b0d, 0xb043, 0x58b6, 0xf3f8, 0x4353, 0xe81d, 0x6f7c, 0xc432, 0x7499, 0xdfd7,
    0xe80a, 0x4344, 0xf3ef, 0x58a1, 0xdfc0, 0x748e, 0xc425, 0x6f6b, 0x879e, 0x2cd0,
    0x9c7b, 0x3735, 0xb054, 0x1b1a, 0xabb1, 0x00ff},
   {0x7c67, 0x65df, 0x4f17, 0x56af, 0x1a87, 0x033f, 0x29f7, 0x304f, 0xb1a7, 0xa81f,
    0x82d7, 0x9b6f, 0xd747, 0xceff, 0xe437, 0xfd8f, 0xaa9e, 0xb326, 0x99ee, 0x8056,
    0xcc7e, 0xd5c6, 0xff0e, 0xe6b6, 0x675e, 0x7ee6, 0x542e, 0x4d96, 0x01be, 0x1806,
    0x32ce, 0x2b76, 0x9cec, 0x8554, 0xaf9c, 0xb624, 0xfa0c, 0xe3b4, 0xc97c, 0xd0c4,
    0x512c, 0x4894, 0x625c, 0x7be4, 0x37cc, 0x2e74, 0x04bc, 0x1d04, 0x4a15, 0x53ad,
    0x7965, 0x60dd, 0x2cf5, 0x354d, 0x1f85, 0x063d, 0x87d5, 0x9e6d, 0xb4a5, 0xad1d,
    0xe135, 0xf88d, 0xd245, 0xcbfd, 0xf008, 0xe9b0, 0xc378, 0xdac0, 0x96e8, 0x8f50,
    0xa598, 0xbc20, 0x3dc8, 0x2470, 0x0eb8, 0x1700, 0x5b28, 0x4290, 0x6858, 0x71e0,
    0x26f1, 0x3f49, 0x1581, 0x0c39, 0x4011, 0x59a9, 0x7361, 0x6ad9, 0xeb31, 0xf289,
    0xd841, 0xc1f9, 0x8dd1, 0x9469, 0xbea1, 0xa719, 0x1083, 0x093b, 0x23f3, 0x3a4b,
    0x7663, 0x6fdb, 0x4513, 0x5cab, 0xdd43, 0xc4fb, 0xee33, 0xf78b, 0xbba3, 0xa21b,
    0x88d3, 0x916b, 0xc67a, 0xdfc2, 0xf50a, 0xecb2, 0xa09a, 0xb922, 0x93ea, 0x8a52,
    0x0bba, 0x1202, 0x38ca, 0x2172, 0x6d5a, 0x74e2, 0x5e2a, 0x4792, 0x29c0, 0x3078,
    0x1ab0, 0x0308, 0x4f20, 0x5698, 0x7c50, 0x65e8, 0xe400, 0xfdb8, 0xd770, 0xcec8,
    0x82e0, 0x9b58, 0xb190, 0xa828, 0xff39, 0xe681, 0xcc49, 0xd5f1, 0x99d9, 0x8061,
    0xaaa9, 0xb311, 0x32f9, 0x2b41, 0x0189, 0x1831, 0x5419, 0x4da1, 0x6769, 0x7ed1,
    0xc94b, 0xd0f3, 0xfa3b, 0xe383, 0xafab, 0xb613, 0x9cdb, 0x8563, 0x048b, 0x1d33,
    0x37fb, 0x2e43, 0x626b, 0x7bd3, 0x511b, 0x48a3, 0x1fb2, 0x060a, 0x2cc2, 0x357a,
    0x7952, 0x60ea, 0x4a22, 0x539a, 0xd272, 0xcbca, 0xe102, 0xf8ba, 0xb492, 0xad2a,
    0x87e2, 0x9e5a, 0xa5af, 0xbc17, 0x96df, 0x8f67, 0xc34f, 0xdaf7, 0xf03f, 0xe987,
    0x686f, 0x71d7, 0x5b1f, 0x42a7, 0x0e8f, 0x1737, 0x3dff, 0x2447, 0x7356, 0x6aee,
    0x4026, 0x599e, 0x15b6, 0x0c0e, 0x26c6, 0x3f7e, 0xbe96, 0xa72e, 0x8de6, 0x945e,
    0xd876, 0xc1ce, 0xeb06, 0xf2be, 0x4524, 0x5c9c, 0x7654, 0x6fec, 0x23c4, 0x3a7c,
    0x10b4, 0x090c, 0x88e4, 0x915c, 0xbb94, 0xa22c, 0xee04, 0xf7bc, 0xdd74, 0xc4cc,
    0x93dd, 0x8a65, 0xa0ad, 0xb915, 0xf53d, 0xec85, 0xc64d, 0xdff5, 0x5e1d, 0x47a5,
    0x6d6d, 0x74d5, 0x38fd, 0x2145, 0x0b8d, 0x1235},
   {0xf917, 0x3bff, 0x31be, 0xf356, 0x253c, 0xe7d4, 0xed95, 0x2f7d, 0x0c38, 0xced0,
    0xc491, 0x0679, 0xd013, 0x12fb, 0x18ba, 0xda52, 0x5e30, 0x9cd8, 0x9699, 0x5471,
    0x821b, 0x40f3, 0x4ab2, 0x885a, 0xab1f, 0x69f7, 0x63b6, 0xa15e, 0x7734, 0xb5dc,
    0xbf9d, 0x7d75, 0xfa20, 0x38c8, 0x3289, 0xf061, 0x260b, 0xe4e3, 0xeea2, 0x2c4a,
    0x0f0f, 0xcde7, 0xc7a6, 0x054e, 0xd324, 0x11cc, 0x1b8d, 0xd965, 0x5d07, 0x9fef,
    0x95ae, 0x5746, 0x812c, 0x43c4, 0x4985, 0x8b6d, 0xa828, 0x6ac0, 0x6081, 0xa269,
    0x7403, 0xb6eb, 0xbcaa, 0x7e42, 0xff79, 0x3d91, 0x37d0, 0xf538, 0x2352, 0xe1ba,
    0xebfb, 0x2913, 0x0a56, 0xc8be, 0xc2ff, 0x0017, 0xd67d, 0x1495, 0x1ed4, 0xdc3c,
    0x585e, 0x9ab6, 0x90f7, 0x521f, 0x8475, 0x469d, 0x4cdc, 0x8e34, 0xad71, 0x6f99,
    0x65d8, 0xa730, 0x715a, 0xb3b2, 0xb9f3, 0x7b1b, 0xfc4e, 0x3ea6, 0x34e7, 0xf60f,
    0x2065, 0xe28d, 0xe8cc, 0x2a24, 0x0961, 0xcb89, 0xc1c8, 0x0320, 0xd54a, 0x17a2,
    0x1de3, 0xdf0b, 0x5b69, 0x9981, 0x93c0, 0x5128, 0x8742, 0x45aa, 0x4feb, 0x8d03,
    0xae46, 0x6cae, 0x66ef, 0xa407, 0x726d, 0xb085, 0xbac4, 0x782c, 0xf5cb, 0x3723,
    0x3d62, 0xff8a, 0x29e0, 0xeb08, 0xe149, 0x23a1, 0x00e4, 0xc20c, 0xc84d, 0x0aa5,
    0xdccf, 0x1e27, 0x1466, 0xd68e, 0x52ec, 0x9004, 0x9a45, 0x58ad, 0x8ec7, 0x4c2f,
    0x466e, 0x8486, 0xa7c3, 0x652b, 0x6f6a, 0xad82, 0x7be8, 0xb900, 0xb341, 0x71a9,
    0xf6fc, 0x3414, 0x3e55, 0xfcbd, 0x2ad7, 0xe83f, 0xe27e, 0x2096, 0x03d3, 0xc13b,
    0xcb7a, 0x0992, 0xdff8, 0x1d10, 0x1751, 0xd5b9, 0x51db, 0x9333, 0x9972, 0x5b9a,
    0x8df0, 0x4f18, 0x4559, 0x87b1, 0xa4f4, 0x661c, 0x6c5d, 0xaeb5, 0x78df, 0xba37,
    0xb076, 0x729e, 0xf3a5, 0x314d, 0x3b0c, 0xf9e4, 0x2f8e, 0xed66, 0xe727, 0x25cf,
    0x068a, 0xc462, 0xce23, 0x0ccb, 0xdaa1, 0x1849, 0x1208, 0xd0e0, 0x5482, 0x966a,
    0x9c2b, 0x5ec3, 0x88a9, 0x4a41, 0x4000, 0x82e8, 0xa1ad, 0x6345, 0x6904, 0xabec,
    0x7d86, 0xbf6e, 0xb52f, 0x77c7, 0xf092, 0x327a, 0x383b, 0xfad3, 0x2cb9, 0xee51,
    0xe410, 0x26f8, 0x05bd, 0xc755, 0xcd14, 0x0ffc, 0xd996, 0x1b7e, 0x113f, 0xd3d7,
    0x57b5, 0x955d, 0x9f1c, 0x5df4, 0x8b9e, 0x4976, 0x4337, 0x81df, 0xa29a, 0x6072,
    0x6a33, 0xa8db, 0x7eb1, 0xbc59, 0xb618, 0x74f0},
   {0x3108, 0x120e, 0x7704, 0x5402, 0xbd10, 0x9e16, 0xfb1c, 0xd81a, 0x6441, 0x4747,
    0x224d, 0x014b, 0xe859, 0xcb5f, 0xae55, 0x8d53, 0x9b9a, 0xb89c, 0xdd96, 0xfe90,
    0x1782, 0x3484, 0x518e, 0x7288, 0xced3, 0xedd5, 0x88df, 0xabd9, 0x42cb, 0x61cd,
    0x04c7, 0x27c1, 0x2955, 0x0a53, 0x6f59, 0x4c5f, 0xa54d, 0x864b, 0xe341, 0xc047,
    0x7c1c, 0x5f1a, 0x3a10, 0x1916, 0xf004, 0xd302, 0xb608, 0x950e, 0x83c7, 0xa0c1,
    0xc5cb, 0xe6cd, 0x0fdf, 0x2cd9, 0x49d3, 0x6ad5, 0xd68e, 0xf588, 0x9082, 0xb384,
    0x5a96, 0x7990, 0x1c9a, 0x3f9c, 0x01b2, 0x22b4, 0x47be, 0x64b8, 0x8daa, 0xaeac,
    0xcba6, 0xe8a0, 0x54fb, 0x77fd, 0x12f7, 0x31f1, 0xd8e3, 0xfbe5, 0x9eef, 0xbde9,
    0xab20, 0x8826, 0xed2c, 0xce2a, 0x2738, 0x043e, 0x6134, 0x4232, 0xfe69, 0xdd6f,
    0xb865, 0x9b63, 0x7271, 0x5177, 0x347d, 0x177b, 0x19ef, 0x3ae9, 0x5fe3, 0x7ce5,
    0x95f7, 0xb6f1, 0xd3fb, 0xf0fd, 0x4ca6, 0x6fa0, 0x0aaa, 0x29ac, 0xc0be, 0xe3b8,
    0x86b2, 0xa5b4, 0xb37d, 0x907b, 0xf571, 0xd677, 0x3f65, 0x1c63, 0x7969, 0x5a6f,
    0xe634, 0xc532, 0xa038, 0x833e, 0x6a2c, 0x492a, 0x2c20, 0x0f26, 0x507c, 0x737a,
    0x1670, 0x3576, 0xdc64, 0xff62, 0x9a68, 0xb96e, 0x0535, 0x2633, 0x4339, 0x603f,
    0x892d, 0xaa2b, 0xcf21, 0xec27, 0xfaee, 0xd9e8, 0xbce2, 0x9fe4, 0x76f6, 0x55f0,
    0x30fa, 0x13fc, 0xafa7, 0x8ca1, 0xe9ab, 0xcaad, 0x23bf, 0x00b9, 0x65b3, 0x46b5,
    0x4821, 0x6b27, 0x0e2d, 0x2d2b, 0xc439, 0xe73f, 0x8235, 0xa133, 0x1d68, 0x3e6e,
    0x5b64, 0x7862, 0x9170, 0xb276, 0xd77c, 0xf47a, 0xe2b3, 0xc1b5, 0xa4bf, 0x87b9,
    0x6eab, 0x4dad, 0x28a7, 0x0ba1, 0xb7fa, 0x94fc, 0xf1f6, 0xd2f0, 0x3be2, 0x18e4,
    0x7dee, 0x5ee8, 0x60c6, 0x43c0, 0x26ca, 0x05cc, 0xecde, 0xcfd8, 0xaad2, 0x89d4,
    0x358f, 0x1689, 0x7383, 0x5085, 0xb997, 0x9a91, 0xff9b, 0xdc9d, 0xca54, 0xe952,
    0x8c58, 0xaf5e, 0x464c, 0x654a, 0x0040, 0x2346, 0x9f1d, 0xbc1b, 0xd911, 0xfa17,
    0x1305, 0x3003, 0x5509, 0x760f, 0x789b, 0x5b9d, 0x3e97, 0x1d91, 0xf483, 0xd785,
    0xb28f, 0x9189, 0x2dd2, 0x0ed4, 0x6bde, 0x48d8, 0xa1ca, 0x82cc, 0xe7c6, 0xc4c0,
    0xd209, 0xf10f, 0x9405, 0xb703, 0x5e11, 0x7d17, 0x181d, 0x3b1b, 0x8740, 0xa446,
    0xc14c, 0xe24a, 0x0b58, 0x285e, 0x4d54, 0x6e52},
   {0xffb8, 0x4a5f, 0xd90f, 0x6ce8, 0xb2d6, 0x0731, 0x9461, 0x2186, 0x6564, 0xd083,
    0x43d3, 0xf634, 0x280a, 0x9ded, 0x0ebd, 0xbb5a, 0x8779, 0x329e, 0xa1ce, 0x1429,
    0xca17, 0x7ff0, 0xeca0, 0x5947, 0x1da5, 0xa842, 0x3b12, 0x8ef5, 0x50cb, 0xe52c,
    0x767c, 0xc39b, 0x0e3a, 0xbbdd, 0x288d, 0x9d6a, 0x4354, 0xf6b3, 0x65e3, 0xd004,
    0x94e6, 0x2101, 0xb251, 0x07b6, 0xd988, 0x6c6f, 0xff3f, 0x4ad8, 0x76fb, 0xc31c,
    0x504c, 0xe5ab, 0x3b95, 0x8e72, 0x1d22, 0xa8c5, 0xec27, 0x59c0, 0xca90, 0x7f77,
    0xa149, 0x14ae, 0x87fe, 0x3219, 0x51c5, 0xe422, 0x7772, 0xc295, 0x1cab, 0xa94c,
    0x3a1c, 0x8ffb, 0xcb19, 0x7efe, 0xedae, 0x5849, 0x8677, 0x3390, 0xa0c0, 0x1527,
    0x2904, 0x9ce3, 0x0fb3, 0xba54, 0x646a, 0xd18d, 0x42dd, 0xf73a, 0xb3d8, 0x063f,
    0x956f, 0x2088, 0xfeb6, 0x4b51, 0xd801, 0x6de6, 0xa047, 0x15a0, 0x86f0, 0x3317,
    0xed29, 0x58ce, 0xcb9e, 0x7e79, 0x3a9b, 0x8f7c, 0x1c2c, 0xa9cb, 0x77f5, 0xc212,
    0x5142, 0xe4a5, 0xd886, 0x6d61, 0xfe31, 0x4bd6, 0x95e8, 0x200f, 0xb35f, 0x06b8,
    0x425a, 0xf7bd, 0x64ed, 0xd10a, 0x0f34, 0xbad3, 0x2983, 0x9c64, 0xee3b, 0x5bdc,
    0xc88c, 0x7d6b, 0xa355, 0x16b2, 0x85e2, 0x3005, 0x74e7, 0xc100, 0x5250, 0xe7b7,
    0x3989, 0x8c6e, 0x1f3e, 0xaad9, 0x96fa, 0x231d, 0xb04d, 0x05aa, 0xdb94, 0x6e73,
    0xfd23, 0x48c4, 0x0c26, 0xb9c1, 0x2a91, 0x9f76, 0x4148, 0xf4af, 0x67ff, 0xd218,
    0x1fb9, 0xaa5e, 0x390e, 0x8ce9, 0x52d7, 0xe730, 0x7460, 0xc187, 0x8565, 0x3082,
    0xa3d2, 0x1635, 0xc80b, 0x7dec, 0xeebc, 0x5b5b, 0x6778, 0xd29f, 0x41cf, 0xf428,
    0x2a16, 0x9ff1, 0x0ca1, 0xb946, 0xfda4, 0x4843, 0xdb13, 0x6ef4, 0xb0ca, 0x052d,
    0x967d, 0x239a, 0x4046, 0xf5a1, 0x66f1, 0xd316, 0x0d28, 0xb8cf, 0x2b9f, 0x9e78,
    0xda9a, 0x6f7d, 0xfc2d, 0x49ca, 0x97f4, 0x2213, 0xb143, 0x04a4, 0x3887, 0x8d60,
    0x1e30, 0xabd7, 0x75e9, 0xc00e, 0x535e, 0xe6b9, 0xa25b, 0x17bc, 0x84ec, 0x310b,
    0xef35, 0x5ad2, 0xc982, 0x7c65, 0xb1c4, 0x0423, 0x9773, 0x2294, 0xfcaa, 0x494d,
    0xda1d, 0x6ffa, 0x2b18, 0x9eff, 0x0daf, 0xb848, 0x6676, 0xd391, 0x40c1, 0xf526,
    0xc905, 0x7ce2, 0xefb2, 0x5a55, 0x846b, 0x318c, 0xa2dc, 0x173b, 0x53d9, 0xe63e,
    0x756e, 0xc089, 0x1eb7, 0xab50, 0x3800, 0x8de7},
   {0xc20e, 0x9d6c, 0x7cca, 0x23a8, 0xf2ff, 0xad9d, 0x4c3b, 0x1359, 0xa3ec, 0xfc8e,
    0x1d28, 0x424a, 0x931d, 0xcc7f, 0x2dd9, 0x72bb, 0x01ca, 0x5ea8, 0xbf0e, 0xe06c,
    0x313b, 0x6e59, 0x8fff, 0xd09d, 0x6028, 0x3f4a, 0xdeec, 0x818e, 0x50d9, 0x0fbb,
    0xee1d, 0xb17f, 0x08ff, 0x579d, 0xb63b, 0xe959, 0x380e, 0x676c, 0x86ca, 0xd9a8,
    0x691d, 0x367f, 0xd7d9, 0x88bb, 0x59ec, 0x068e, 0xe728, 0xb84a, 0xcb3b, 0x9459,
    0x75ff, 0x2a9d, 0xfbca, 0xa4a8, 0x450e, 0x1a6c, 0xaad9, 0xf5bb, 0x141d, 0x4b7f,
    0x9a28, 0xc54a, 0x24ec, 0x7b8e, 0x1a95, 0x45f7, 0xa451, 0xfb33, 0x2a64, 0x7506,
    0x94a0, 0xcbc2, 0x7b77, 0x2415, 0xc5b3, 0x9ad1, 0x4b86, 0x14e4, 0xf542, 0xaa20,
    0xd951, 0x8633, 0x6795, 0x38f7, 0xe9a0, 0xb6c2, 0x5764, 0x0806, 0xb8b3, 0xe7d1,
    0x0677, 0x5915, 0x8842, 0xd720, 0x3686, 0x69e4, 0xd064, 0x8f06, 0x6ea0, 0x31c2,
    0xe095, 0xbff7, 0x5e51, 0x0133, 0xb186, 0xeee4, 0x0f42, 0x5020, 0x8177, 0xde15,
    0x3fb3, 0x60d1, 0x13a0, 0x4cc2, 0xad64, 0xf206, 0x2351, 0x7c33, 0x9d95, 0xc2f7,
    0x7242, 0x2d20, 0xcc86, 0x93e4, 0x42b3, 0x1dd1, 0xfc77, 0xa315, 0x3e41, 0x6123,
    0x8085, 0xdfe7, 0x0eb0, 0x51d2, 0xb074, 0xef16, 0x5fa3, 0x00c1, 0xe167, 0xbe05,
    0x6f52, 0x3030, 0xd196, 0x8ef4, 0xfd85, 0xa2e7, 0x4341, 0x1c23, 0xcd74, 0x9216,
    0x73b0, 0x2cd2, 0x9c67, 0xc305, 0x22a3, 0x7dc1, 0xac96, 0xf3f4, 0x1252, 0x4d30,
    0xf4b0, 0xabd2, 0x4a74, 0x1516, 0xc441, 0x9b23, 0x7a85, 0x25e7, 0x9552, 0xca30,
    0x2b96, 0x74f4, 0xa5a3, 0xfac1, 0x1b67, 0x4405, 0x3774, 0x6816, 0x89b0, 0xd6d2,
    0x0785, 0x58e7, 0xb941, 0xe623, 0x5696, 0x09f4, 0xe852, 0xb730, 0x6667, 0x3905,
    0xd8a3, 0x87c1, 0xe6da, 0xb9b8, 0x581e, 0x077c, 0xd62b, 0x8949, 0x68ef, 0x378d,
    0x8738, 0xd85a, 0x39fc, 0x669e, 0xb7c9, 0xe8ab, 0x090d, 0x566f, 0x251e, 0x7a7c,
    0x9bda, 0xc4b8, 0x15ef, 0x4a8d, 0xab2b, 0xf449, 0x44fc, 0x1b9e, 0xfa38, 0xa55a,
    0x740d, 0x2b6f, 0xcac9, 0x95ab, 0x2c2b, 0x7349, 0x92ef, 0xcd8d, 0x1cda, 0x43b8,
    0xa21e, 0xfd7c, 0x4dc9, 0x12ab, 0xf30d, 0xac6f, 0x7d38, 0x225a, 0xc3fc, 0x9c9e,
    0xefef, 0xb08d, 0x512b, 0x0e49, 0xdf1e, 0x807c, 0x61da, 0x3eb8, 0x8e0d, 0xd16f,
    0x30c9, 0x6fab, 0xbefc, 0xe19e, 0x0038, 0x5f5a},
   {0x4a8f, 0x5c9d, 0x66ab, 0x70b9, 0x12c7, 0x04d5, 0x3ee3, 0x28f1, 0xfa1f, 0xec0d,
    0xd63b, 0xc029, 0xa257, 0xb445, 0x8e73, 0x9861, 0x66d6, 0x70c4, 0x4af2, 0x5ce0,
    0x3e9e, 0x288c, 0x12ba, 0x04a8, 0xd646, 0xc054, 0xfa62, 0xec70, 0x8e0e, 0x981c,
    0xa22a, 0xb438, 0x123d, 0x042f, 0x3e19, 0x280b, 0x4a75, 0x5c67, 0x6651, 0x7043,
    0xa2ad, 0xb4bf, 0x8e89, 0x989b, 0xfae5, 0xecf7, 0xd6c1, 0xc0d3, 0x3e64, 0x2876,
    0x1240, 0x0452, 0x662c, 0x703e, 0x4a08, 0x5c1a, 0x8ef4, 0x98e6, 0xa2d0, 0xb4c2,
    0xd6bc, 0xc0ae, 0xfa98, 0xec8a, 0xfbeb, 0xedf9, 0xd7cf, 0xc1dd, 0xa3a3, 0xb5b1,
    0x8f87, 0x9995, 0x4b7b, 0x5d69, 0x675f, 0x714d, 0x1333, 0x0521, 0x3f17, 0x2905,
    0xd7b2, 0xc1a0, 0xfb96, 0xed84, 0x8ffa, 0x99e8, 0xa3de, 0xb5cc, 0x6722, 0x7130,
    0x4b06, 0x5d14, 0x3f6a, 0x2978, 0x134e, 0x055c, 0xa359, 0xb54b, 0x8f7d, 0x996f,
    0xfb11, 0xed03, 0xd735, 0xc127, 0x13c9, 0x05db, 0x3fed, 0x29ff, 0x4b81, 0x5d93,
    0x67a5, 0x71b7, 0x8f00, 0x9912, 0xa324, 0xb536, 0xd748, 0xc15a, 0xfb6c, 0xed7e,
    0x3f90, 0x2982, 0x13b4, 0x05a6, 0x67d8, 0x71ca, 0x4bfc, 0x5dee, 0x653e, 0x732c,
    0x491a, 0x5f08, 0x3d76, 0x2b64, 0x1152, 0x0740, 0xd5ae, 0xc3bc, 0xf98a, 0xef98,
    0x8de6, 0x9bf4, 0xa1c2, 0xb7d0, 0x4967, 0x5f75, 0x6543, 0x7351, 0x112f, 0x073d,
    0x3d0b, 0x2b19, 0xf9f7, 0xefe5, 0xd5d3, 0xc3c1, 0xa1bf, 0xb7ad, 0x8d9b, 0x9b89,
    0x3d8c, 0x2b9e, 0x11a8, 0x07ba, 0x65c4, 0x73d6, 0x49e0, 0x5ff2, 0x8d1c, 0x9b0e,
    0xa138, 0xb72a, 0xd554, 0xc346, 0xf970, 0xef62, 0x11d5, 0x07c7, 0x3df1, 0x2be3,
    0x499d, 0x5f8f, 0x65b9, 0x73ab, 0xa145, 0xb757, 0x8d61, 0x9b73, 0xf90d, 0xef1f,
    0xd529, 0xc33b, 0xd45a, 0xc248, 0xf87e, 0xee6c, 0x8c12, 0x9a00, 0xa036, 0xb624,
    0x64ca, 0x72d8, 0x48ee, 0x5efc, 0x3c82, 0x2a90, 0x10a6, 0x06b4, 0xf803, 0xee11,
    0xd427, 0xc235, 0xa04b, 0xb659, 0x8c6f, 0x9a7d, 0x4893, 0x5e81, 0x64b7, 0x72a5,
    0x10db, 0x06c9, 0x3cff, 0x2aed, 0x8ce8, 0x9afa, 0xa0cc, 0xb6de, 0xd4a0, 0xc2b2,
    0xf884, 0xee96, 0x3c78, 0x2a6a, 0x105c, 0x064e, 0x6430, 0x7222, 0x4814, 0x5e06,
    0xa0b1, 0xb6a3, 0x8c95, 0x9a87, 0xf8f9, 0xeeeb, 0xd4dd, 0xc2cf, 0x1021, 0x0633,
    0x3c05, 0x2a17, 0x4869, 0x5e7b, 0x644d, 0x725f}
};

unsigned crc16dnp_byte(unsigned crc, void const *mem, size_t len) {
    unsigned char const *data = mem;
    if (data == NULL)
        return 0xffff;
    crc &= 0xffff;
    while (len--)
        crc = (crc >> 8) ^
              table_byte[(crc ^ *data++) & 0xff];
    return crc;
}

// This code assumes that integers are stored little-endian.

unsigned crc16dnp_word(unsigned crc, void const *mem, size_t len) {
    unsigned char const *data = mem;
    if (data == NULL)
        return 0xffff;
    crc &= 0xffff;
    while (len && ((ptrdiff_t)data & 0x7)) {
        crc = (crc >> 8) ^
              table_byte[(crc ^ *data++) & 0xff];
        len--;
    }
    if (len >= 8) {
        do {
            uintmax_t word = crc ^ *(uintmax_t const *)data;
            crc = table_word[7][word & 0xff] ^
                  table_word[6][(word >> 8) & 0xff] ^
                  table_word[5][(word >> 16) & 0xff] ^
                  table_word[4][(word >> 24) & 0xff] ^
                  table_word[3][(word >> 32) & 0xff] ^
                  table_word[2][(word >> 40) & 0xff] ^
                  table_word[1][(word >> 48) & 0xff] ^
                  table_word[0][word >> 56];
            data += 8;
            len -= 8;
        } while (len >= 8);
    }
    while (len--)
        crc = (crc >> 8) ^
              table_byte[(crc ^ *data++) & 0xff];
    return crc;
}

How to use Lambda in LINQ select statement

Lambda Expression result

var storesList = context.Stores.Select(x => new { Value= x.name,Text= x.ID }).ToList();

Set a request header in JavaScript

@gnarf answer is right . wanted to add more information .

Mozilla Bug Reference : https://bugzilla.mozilla.org/show_bug.cgi?id=627942

Terminate these steps if header is a case-insensitive match for one of the following headers:

Accept-Charset
Accept-Encoding
Access-Control-Request-Headers
Access-Control-Request-Method
Connection
Content-Length
Cookie
Cookie2
Date
DNT
Expect
Host
Keep-Alive
Origin
Referer
TE
Trailer
Transfer-Encoding
Upgrade
User-Agent
Via

Source : https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#dom-xmlhttprequest-setrequestheader

I cannot access tomcat admin console?

If you are running tomcat from eclipse (probably problem exists with another IDEs), it could have a different configuration- not based on files .

The solution is to edit tomcat users file, as you wrote, and then start tomcat from command prompt with

{tomcat-directory}/bin/startup

How do I convert an NSString value to NSData?

Do:

NSData *data = [yourString dataUsingEncoding:NSUTF8StringEncoding];

then feel free to proceed with NSJSONSerialization:JSONObjectWithData.


Correction to the answer regarding the NULL terminator

Following the comments, official documentation, and verifications, this answer was updated regarding the removal of an alleged NULL terminator:

  1. As documented by dataUsingEncoding::

    Return Value

    The result of invoking dataUsingEncoding:allowLossyConversion: with NO as the second argument

  2. As documented by getCString:maxLength:encoding: and cStringUsingEncoding::

    note that the data returned by dataUsingEncoding:allowLossyConversion: is not a strict C-string since it does not have a NULL terminator

Trigger 404 in Spring-MVC controller?

If your controller method is for something like file handling then ResponseEntity is very handy:

@Controller
public class SomeController {
    @RequestMapping.....
    public ResponseEntity handleCall() {
        if (isFound()) {
            return new ResponseEntity(...);
        }
        else {
            return new ResponseEntity(404);
        }
    }
}

How do I convert datetime to ISO 8601 in PHP

If you try set a value in datetime-local

date("Y-m-d\TH:i",strtotime('2010-12-30 23:21:46'));

//output : 2010-12-30T23:21

gcc error: wrong ELF class: ELFCLASS64

sudo apt-get install ia32-libs 

What is the perfect counterpart in Python for "while not EOF"

You can use the following code snippet. readlines() reads in the whole file at once and splits it by line.

line = obj.readlines()

android get all contacts

Improving on the answer of @Adiii - It Will Cleanup The Phone Number and Remove All Duplicates

Declare a Global Variable

// Hash Maps
Map<String, String> namePhoneMap = new HashMap<String, String>();

Then Use The Function Below

private void getPhoneNumbers() {

        Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);

        // Loop Through All The Numbers
        while (phones.moveToNext()) {

            String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

            // Cleanup the phone number
            phoneNumber = phoneNumber.replaceAll("[()\\s-]+", "");

            // Enter Into Hash Map
            namePhoneMap.put(phoneNumber, name);

        }

        // Get The Contents of Hash Map in Log
        for (Map.Entry<String, String> entry : namePhoneMap.entrySet()) {
            String key = entry.getKey();
            Log.d(TAG, "Phone :" + key);
            String value = entry.getValue();
            Log.d(TAG, "Name :" + value);
        }

        phones.close();

    }

Remember in the above example the key is phone number and value is a name so read your contents like 998xxxxx282->Mahatma Gandhi instead of Mahatma Gandhi->998xxxxx282

Hash and salt passwords in C#

 protected void m_GenerateSHA256_Button1_Click(objectSender, EventArgs e)
{
string salt =createSalt(10);
string hashedPassword=GenerateSHA256Hash(m_UserInput_TextBox.Text,Salt);
m_SaltHash_TextBox.Text=Salt;
 m_SaltSHA256Hash_TextBox.Text=hashedPassword;

}
 public string createSalt(int size)
{
 var rng= new System.Security.Cyptography.RNGCyptoServiceProvider();
 var buff= new byte[size];
rng.GetBytes(buff);
 return Convert.ToBase64String(buff);
}


 public string GenerateSHA256Hash(string input,string salt)
{
 byte[]bytes=System.Text.Encoding.UTF8.GetBytes(input+salt);
 new System.Security.Cyptography.SHA256Managed();
 byte[]hash=sha256hashString.ComputedHash(bytes);
 return bytesArrayToHexString(hash);
  }

How do I clear only a few specific objects from the workspace?

You'll find the answer by typing ?rm

rm(data_1, data_2, data_3)

Multi-character constant warnings

If you want to disable this warning it is important to know that there are two related warning parameters in GCC and Clang: GCC Compiler options -wno-four-char-constants and -wno-multichar

Bootstrap datetimepicker is not a function

Try to use datepicker/ timepicker instead of datetimepicker like:

replace:

$('#datetimepicker1').datetimepicker();

with:

$('#datetimepicker1').datepicker(); // or timepicker for time picker

iterating and filtering two lists using java 8

// produce the filter set by streaming the items from list 2
// assume list2 has elements of type MyClass where getStr gets the
// string that might appear in list1
Set<String> unavailableItems = list2.stream()
    .map(MyClass::getStr)
    .collect(Collectors.toSet());

// stream the list and use the set to filter it
List<String> unavailable = list1.stream()
            .filter(e -> unavailableItems.contains(e))
            .collect(Collectors.toList());

Button button = findViewById(R.id.button) always resolves to null in Android Studio

This is because findViewById() searches in the activity_main layout, while the button is located in the fragment's layout fragment_main.

Move that piece of code in the onCreateView() method of the fragment:

//...

View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button buttonClick = (Button)rootView.findViewById(R.id.button);
buttonClick.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        onButtonClick((Button) view);
    }
});

Notice that now you access it through rootView view:

Button buttonClick = (Button)rootView.findViewById(R.id.button);

otherwise you would get again NullPointerException.

Show/Hide Multiple Divs with Jquery

Check This Example

Html:

<div class="buttons">
<a class="button" id="showall">All</a>
<a class="button" id="showdiv1">Div 1</a>
<a class="button" id="showdiv2">Div 2</a>
<a class="button" id="showdiv3">Div 3</a>
<a class="button" id="showdiv4">Div 4</a>
</div>

<div id="div1">1</div>
<div id="div2">2</div>
<div id="div3">3</div>
<div id="div4">4</div>

Javascript:

$('#showall').click(function(){
    $('div').show();
});

$('#showdiv1').click(function(){
    $('div[id^=div]').hide();
    $('#div1').show();
});
$('#showdiv2').click(function(){
    $('div[id^=div]').hide();
    $('#div2').show();
});

$('#showdiv3').click(function(){
    $('div[id^=div]').hide();
    $('#div3').show();
});

$('#showdiv4').click(function(){
    $('div[id^=div]').hide();
    $('#div4').show();

});

How to create a <style> tag with Javascript?

All good, but for styleNode.cssText to work in IE6 with node created by javascipt, you need to append the node to the document before you set the cssText;

further info @ http://msdn.microsoft.com/en-us/library/ms533698%28VS.85%29.aspx

What is a postback?

Postback is essentially when a form is submitted to the same page or script (.php .asp etc) as you are currently on to proccesses the data rather than sending you to a new page.

An example could be a page on a forum (viewpage.php), where you submit a comment and it is submitted to the same page (viewpage.php) and you would then see it with the new content added.

See: http://en.wikipedia.org/wiki/Postback

Angular ngClass and click event for toggling class

Instead of having to create a function in the ts file you can toggle a variable from the template itself. You can then use the variable to apply a specific class to the element. Like so-

<div (click)="status=!status"  
    [ngClass]="status ? 'success' : 'danger'">                
     Some content
</div>

So when status is true the class success is applied. When it is false danger class is applied.

This will work without any additional code in the ts file.

How do I use hexadecimal color strings in Flutter?

You can use this

Color getColorFromColorCode(String code){
  return Color(int.parse(code.substring(1, 7), radix: 16) + 0xFF000000);
}

Specifying and saving a figure with exact size in pixels

Matplotlib doesn't work with pixels directly, but rather physical sizes and DPI. If you want to display a figure with a certain pixel size, you need to know the DPI of your monitor. For example this link will detect that for you.

If you have an image of 3841x7195 pixels it is unlikely that you monitor will be that large, so you won't be able to show a figure of that size (matplotlib requires the figure to fit in the screen, if you ask for a size too large it will shrink to the screen size). Let's imagine you want an 800x800 pixel image just for an example. Here's how to show an 800x800 pixel image in my monitor (my_dpi=96):

plt.figure(figsize=(800/my_dpi, 800/my_dpi), dpi=my_dpi)

So you basically just divide the dimensions in inches by your DPI.

If you want to save a figure of a specific size, then it is a different matter. Screen DPIs are not so important anymore (unless you ask for a figure that won't fit in the screen). Using the same example of the 800x800 pixel figure, we can save it in different resolutions using the dpi keyword of savefig. To save it in the same resolution as the screen just use the same dpi:

plt.savefig('my_fig.png', dpi=my_dpi)

To to save it as an 8000x8000 pixel image, use a dpi 10 times larger:

plt.savefig('my_fig.png', dpi=my_dpi * 10)

Note that the setting of the DPI is not supported by all backends. Here, the PNG backend is used, but the pdf and ps backends will implement the size differently. Also, changing the DPI and sizes will also affect things like fontsize. A larger DPI will keep the same relative sizes of fonts and elements, but if you want smaller fonts for a larger figure you need to increase the physical size instead of the DPI.

Getting back to your example, if you want to save a image with 3841 x 7195 pixels, you could do the following:

plt.figure(figsize=(3.841, 7.195), dpi=100)
( your code ...)
plt.savefig('myfig.png', dpi=1000)

Note that I used the figure dpi of 100 to fit in most screens, but saved with dpi=1000 to achieve the required resolution. In my system this produces a png with 3840x7190 pixels -- it seems that the DPI saved is always 0.02 pixels/inch smaller than the selected value, which will have a (small) effect on large image sizes. Some more discussion of this here.

How to get user agent in PHP

Use the native PHP $_SERVER['HTTP_USER_AGENT'] variable instead.

Auto-indent spaces with C in vim?

and always remember this venerable explanation of Spaces + Tabs:

http://www.jwz.org/doc/tabs-vs-spaces.html

How do I use regular expressions in bash scripts?

It was changed between 3.1 and 3.2:

This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.

Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.

So use it without the quotes thus:

i="test"
if [[ $i =~ 200[78] ]] ; then
    echo "OK"
else
    echo "not OK"
fi

jQuery - replace all instances of a character in a string

You need to use a regular expression, so that you can specify the global (g) flag:

var s = 'some+multi+word+string'.replace(/\+/g, ' ');

(I removed the $() around the string, as replace is not a jQuery method, so that won't work at all.)

Initialize a vector array of strings

same as @Moo-Juice:

const char* args[] = {"01", "02", "03", "04"};
std::vector<std::string> v(args, args + sizeof(args)/sizeof(args[0])); //get array size

RestTemplate: How to send URL and query parameters together

An issue with the answer from Michal Foksa is that it adds the query parameters first, and then expands the path variables. If query parameter contains parenthesis, e.g. {foobar}, this will cause an exception.

The safe way is to expand the path variables first, and then add the query parameters:

String url = "http://test.com/Services/rest/{id}/Identifier";
Map<String, String> params = new HashMap<String, String>();
params.put("id", "1234");
URI uri = UriComponentsBuilder.fromUriString(url)
        .buildAndExpand(params)
        .toUri();
uri = UriComponentsBuilder
        .fromUri(uri)
        .queryParam("name", "myName")
        .build()
        .toUri();
restTemplate.exchange(uri , HttpMethod.PUT, requestEntity, class_p);

How to select option in drop down protractorjs e2e tests

Here is how to do it by either option value or index. This example is a bit crude, but it shows how to do what you want:

html:

<mat-form-field id="your-id">
    <mat-select>
        <mat-option [value]="1">1</mat-option>
        <mat-option [value]="2">2</mat-option>
    </mat-select>
</mat-form-field>

ts:

function selectOptionByOptionValue(selectFormFieldElementId, valueToFind) {

  const formField = element(by.id(selectFormFieldElementId));
  formField.click().then(() => {

    formField.element(by.tagName('mat-select'))
      .getAttribute('aria-owns').then((optionIdsString: string) => {
        const optionIds = optionIdsString.split(' ');    

        for (let optionId of optionIds) {
          const option = element(by.id(optionId));
          option.getText().then((text) => {
            if (text === valueToFind) {
              option.click();
            }
          });
        }
      });
  });
}

function selectOptionByOptionIndex(selectFormFieldElementId, index) {

  const formField = element(by.id(selectFormFieldElementId));
  formField.click().then(() => {

    formField.element(by.tagName('mat-select'))
      .getAttribute('aria-owns').then((optionIdsString: string) => {
        const optionIds = optionIdsString.split(' ');

        const optionId = optionIds[index];
        const option = element(by.id(optionId));
        option.click();
      });
  });
}

selectOptionByOptionValue('your-id', '1'); //selects first option
selectOptionByOptionIndex('your-id', 1); //selects second option

How do SETLOCAL and ENABLEDELAYEDEXPANSION work?

A real problem often exists because any variables set inside will not be exported when that batch file finishes. So its not possible to export, which caused us issues. As a result, I just set the registry to ALWAYS used delayed expansion (I don't know why it's not the default, could be speed or legacy compatibility issue.)

How can I start PostgreSQL server on Mac OS X?

PostgreSQL is integrated in Server.app available through the App Store in Mac OS X v10.8 (Mountain Lion). That means that it is already configured, and you only need to launch it, and then create users and databases.

Tip: Do not start with defining $PGDATA and so on. Take file locations as is.

You would have this file: /Library/Server/PostgreSQL/Config/org.postgresql.postgres.plist

To start:

sudo serveradmin start postgres

Process started with arguments:

/Applications/Server.app/Contents/ServerRoot/usr/bin/postgres_real -D /Library/Server/PostgreSQL/Data -c listen_addresses=127.0.0.1,::1 -c log_connections=on -c log_directory=/Library/Logs/PostgreSQL -c log_filename=PostgreSQL.log -c log_line_prefix=%t -c log_lock_waits=on -c log_statement=ddl -c logging_collector=on -c unix_socket_directory=/private/var/pgsql_socket -c unix_socket_group=_postgres -c unix_socket_permissions=0770

You can sudo:

sudo -u _postgres psql template1

Or connect:

psql -h localhost -U _postgres postgres

You can find the data directory, version, running status and so forth with

sudo serveradmin fullstatus postgres

What is the difference between Bower and npm?

2017-Oct update

Bower has finally been deprecated. End of story.

Older answer

From Mattias Petter Johansson, JavaScript developer at Spotify:

In almost all cases, it's more appropriate to use Browserify and npm over Bower. It is simply a better packaging solution for front-end apps than Bower is. At Spotify, we use npm to package entire web modules (html, css, js) and it works very well.

Bower brands itself as the package manager for the web. It would be awesome if this was true - a package manager that made my life better as a front-end developer would be awesome. The problem is that Bower offers no specialized tooling for the purpose. It offers NO tooling that I know of that npm doesn't, and especially none that is specifically useful for front-end developers. There is simply no benefit for a front-end developer to use Bower over npm.

We should stop using bower and consolidate around npm. Thankfully, that is what is happening:

Module counts - bower vs. npm

With browserify or webpack, it becomes super-easy to concatenate all your modules into big minified files, which is awesome for performance, especially for mobile devices. Not so with Bower, which will require significantly more labor to get the same effect.

npm also offers you the ability to use multiple versions of modules simultaneously. If you have not done much application development, this might initially strike you as a bad thing, but once you've gone through a few bouts of Dependency hell you will realize that having the ability to have multiple versions of one module is a pretty darn great feature. Note that npm includes a very handy dedupe tool that automatically makes sure that you only use two versions of a module if you actually have to - if two modules both can use the same version of one module, they will. But if they can't, you have a very handy out.

(Note that Webpack and rollup are widely regarded to be better than Browserify as of Aug 2016.)

Disable elastic scrolling in Safari

None of the 'overflow' solutions worked for me. I'm coding a parallax effect with JavaScript using jQuery. In Chrome and Safari on OSX the elastic/rubber-band effect was messing up my scroll numbers, since it actually scrolls past the document's height and updates the window variables with out-of-boundary numbers. What I had to do was check if the scrolled amount was larger than the actual document's height, like so:

$(window).scroll(
    function() {
        if ($(window).scrollTop() + $(window).height() > $(document).height()) return;
        updateScroll(); // my own function to do my parallaxing stuff
    }
);

How to copy a selection to the OS X clipboard

command-C? This at least works for the vim launched from within Terminal.app for text selected with mouse.

Using psql how do I list extensions installed in a database?

Additionally if you want to know which extensions are available on your server: SELECT * FROM pg_available_extensions

How can I get the active screen dimensions?

This is a "Center Screen DotNet 4.5 solution", using SystemParameters instead of System.Windows.Forms or My.Compuer.Screen: Since Windows 8 has changed the screen dimension calculation, the only way it works for me looks like that (Taskbar calculation included):

Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
    Dim BarWidth As Double = SystemParameters.VirtualScreenWidth - SystemParameters.WorkArea.Width
    Dim BarHeight As Double = SystemParameters.VirtualScreenHeight - SystemParameters.WorkArea.Height
    Me.Left = (SystemParameters.VirtualScreenWidth - Me.ActualWidth - BarWidth) / 2
    Me.Top = (SystemParameters.VirtualScreenHeight - Me.ActualHeight - BarHeight) / 2         
End Sub

Center Screen WPF XAML

How to get previous page url using jquery

If you are using PHP, you can check previous url using php script rather than javascript. Here is the code:

echo $_SERVER['HTTP_REFERER'];

Hope it helps even out of relevance :)

Parsing Json rest api response in C#

1> Add this namspace. using Newtonsoft.Json.Linq;

2> use this source code.

JObject joResponse = JObject.Parse(response);                   
JObject ojObject = (JObject)joResponse["response"];
JArray array= (JArray)ojObject ["chats"];
int id = Convert.ToInt32(array[0].toString());

Use Invoke-WebRequest with a username and password for basic authentication on the GitHub API

Invoke-WebRequest follows the RFC2617 as @briantist noted, however there are some systems (e.g. JFrog Artifactory) that allow anonymous usage if the Authorization header is absent, but will respond with 401 Forbidden if the header contains invalid credentials.

This can be used to trigger the 401 Forbidden response and get -Credentials to work.

$login = Get-Credential -Message "Enter Credentials for Artifactory"

                              #Basic foo:bar
$headers = @{ Authorization = "Basic Zm9vOmJhcg==" }  

Invoke-WebRequest -Credential $login -Headers $headers -Uri "..."

This will send the invalid header the first time, which will be replaced with the valid credentials in the second request since -Credentials overrides the Authorization header.

Tested with Powershell 5.1

Various ways to remove local Git changes

First of all check is your important change saved or not by:

$ git status

than try

$ git reset --hard

it will reset your branch to default

but if you need just undo:

$ edit (1) $ git add frotz.c filfre.c $ mailx (2) $ git reset
(3) $ git pull git://info.example.com/ nitfol


Read more >> https://git-scm.com/docs/git-reset

Is it ok to scrape data from Google results?

Google will eventually block your IP when you exceed a certain amount of requests.

Resize image with javascript canvas (smoothly)

Since Trung Le Nguyen Nhat's fiddle isn't correct at all (it just uses the original image in the last step)
I wrote my own general fiddle with performance comparison:

FIDDLE

Basically it's:

img.onload = function() {
   var canvas = document.createElement('canvas'),
       ctx = canvas.getContext("2d"),
       oc = document.createElement('canvas'),
       octx = oc.getContext('2d');

   canvas.width = width; // destination canvas size
   canvas.height = canvas.width * img.height / img.width;

   var cur = {
     width: Math.floor(img.width * 0.5),
     height: Math.floor(img.height * 0.5)
   }

   oc.width = cur.width;
   oc.height = cur.height;

   octx.drawImage(img, 0, 0, cur.width, cur.height);

   while (cur.width * 0.5 > width) {
     cur = {
       width: Math.floor(cur.width * 0.5),
       height: Math.floor(cur.height * 0.5)
     };
     octx.drawImage(oc, 0, 0, cur.width * 2, cur.height * 2, 0, 0, cur.width, cur.height);
   }

   ctx.drawImage(oc, 0, 0, cur.width, cur.height, 0, 0, canvas.width, canvas.height);
}

Sending email with attachments from C#, attachments arrive as Part 1.2 in Thunderbird

Completing the solution of Ranadheer, using Server.MapPath to locate the file

System.Net.Mail.Attachment attachment;
attachment = New System.Net.Mail.Attachment(Server.MapPath("~/App_Data/hello.pdf"));
mail.Attachments.Add(attachment);

Is there a CSS selector for elements containing certain text?

I find the attribute option to be your best bet if you don't want to use javascript or jquery.

E.g to style all table cells with the word ready, In HTML do this:

 <td status*="ready">Ready</td>

Then in css:

td[status*="ready"] {
        color: red;
    }

Converting milliseconds to a date (jQuery/JavaScript)

Try using this code:

var datetime = 1383066000000; // anything
var date = new Date(datetime);
var options = {
        year: 'numeric', month: 'numeric', day: 'numeric',
    };

var result = date.toLocaleDateString('en', options); // 10/29/2013

See more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

T-SQL: Deleting all duplicate rows but keeping one

Here's my twist on it, with a runnable example. Note this will only work in the situation where Id is unique, and you have duplicate values in other columns.

DECLARE @SampleData AS TABLE (Id int, Duplicate varchar(20))

INSERT INTO @SampleData
SELECT 1, 'ABC' UNION ALL
SELECT 2, 'ABC' UNION ALL
SELECT 3, 'LMN' UNION ALL
SELECT 4, 'XYZ' UNION ALL
SELECT 5, 'XYZ'

DELETE FROM @SampleData WHERE Id IN (
    SELECT Id FROM (
        SELECT 
            Id
            ,ROW_NUMBER() OVER (PARTITION BY [Duplicate] ORDER BY Id) AS [ItemNumber]
            -- Change the partition columns to include the ones that make the row distinct
        FROM 
            @SampleData
    ) a WHERE ItemNumber > 1 -- Keep only the first unique item
)

SELECT * FROM @SampleData

And the results:

Id          Duplicate
----------- ---------
1           ABC
3           LMN
4           XYZ

Not sure why that's what I thought of first... definitely not the simplest way to go but it works.

Set Background cell color in PHPExcel

  $objPHPExcel->getActiveSheet()->getStyle('B3:B7')->getFill()
->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
->getStartColor()->setARGB('FFFF0000');

It's in the documentation, located here: https://github.com/PHPOffice/PHPExcel/wiki/User-Documentation-Overview-and-Quickstart-Guide

Error in contrasts when defining a linear model in R

The answers by the other authors have already addressed the problem of factors with only one level or NAs.

Today, I stumbled upon the same error when using the rstatix::anova_test() function but my factors were okay (more than one level, no NAs, no character vectors, ...). Instead, I could fix the error by dropping all variables in the dataframe that are not included in the model. I don't know what's the reason for this behavior but just knowing about this might also be helpful when encountering this error.

C#: Waiting for all threads to complete

Possible solution:

var tasks = dataList
    .Select(data => Task.Factory.StartNew(arg => DoThreadStuff(data), TaskContinuationOptions.LongRunning | TaskContinuationOptions.PreferFairness))
    .ToArray();

var timeout = TimeSpan.FromMinutes(1);
Task.WaitAll(tasks, timeout);

Assuming dataList is the list of items and each item needs to be processed in a separate thread.

Python: Convert timedelta to int in a dataframe

The Series class has a pandas.Series.dt accessor object with several useful datetime attributes, including dt.days. Access this attribute via:

timedelta_series.dt.days

You can also get the seconds and microseconds attributes in the same way.

What does the SQL Server Error "String Data, Right Truncation" mean and how do I fix it?

Either the parameter supplied for ZIP_CODE is larger (in length) than ZIP_CODEs column width or the parameter supplied for CITY is larger (in length) than CITYs column width.

It would be interesting to know the values supplied for the two ? placeholders.

Center align with table-cell

Here is a good starting point.

HTML:

<div class="containing-table">
    <div class="centre-align">
        <div class="content"></div>
    </div>
</div>

CSS:

.containing-table {
    display: table;
    width: 100%;
    height: 400px; /* for demo only */
    border: 1px dotted blue;
}
.centre-align {
    padding: 10px;
    border: 1px dashed gray;
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
.content {
    width: 50px;
    height: 50px;
    background-color: red;
    display: inline-block;
    vertical-align: top; /* Removes the extra white space below the baseline */
}

See demo at: http://jsfiddle.net/audetwebdesign/jSVyY/

.containing-table establishes the width and height context for .centre-align (the table-cell).

You can apply text-align and vertical-align to alter .centre-align as needed.

Note that .content needs to use display: inline-block if it is to be centered horizontally using the text-align property.