Programs & Examples On #Decode

To convert some encoded data (e.g. bytes, electrical signals) to some representation ready for further processing (e.g. string, object, picture)

Android - How to decode and decompile any APK file?

To decompile APK Use APKTool.
You can learn how APKTool works on http://www.decompileandroid.com/ or by reading the documentation.

How to decode a QR-code image in (preferably pure) Python?

You can try the following steps and code using qrtools:

  • Create a qrcode file, if not already existing

    • I used pyqrcode for doing this, which can be installed using pip install pyqrcode
    • And then use the code:

      >>> import pyqrcode
      >>> qr = pyqrcode.create("HORN O.K. PLEASE.")
      >>> qr.png("horn.png", scale=6)
      
  • Decode an existing qrcode file using qrtools

    • Install qrtools using sudo apt-get install python-qrtools
    • Now use the following code within your python prompt

      >>> import qrtools
      >>> qr = qrtools.QR()
      >>> qr.decode("horn.png")
      >>> print qr.data
      u'HORN O.K. PLEASE.'
      

Here is the complete code in a single run:

In [2]: import pyqrcode
In [3]: qr = pyqrcode.create("HORN O.K. PLEASE.")
In [4]: qr.png("horn.png", scale=6)
In [5]: import qrtools
In [6]: qr = qrtools.QR()
In [7]: qr.decode("horn.png")
Out[7]: True
In [8]: print qr.data
HORN O.K. PLEASE.

Caveats

  • You might need to install PyPNG using pip install pypng for using pyqrcode
  • In case you have PIL installed, you might get IOError: decoder zip not available. In that case, try uninstalling and reinstalling PIL using:

    pip uninstall PIL
    pip install PIL
    
  • If that doesn't work, try using Pillow instead

    pip uninstall PIL
    pip install pillow
    

Write Base64-encoded image to file

No need to use BufferedImage, as you already have the image file in a byte array

    byte dearr[] = Base64.decodeBase64(crntImage);
    FileOutputStream fos = new FileOutputStream(new File("c:/decode/abc.bmp")); 
    fos.write(dearr); 
    fos.close();

How to decode encrypted wordpress admin password?

MD5 encrypting is possible, but decrypting is still unknown (to me). However, there are many ways to compare these things.

  1. Using compare methods like so:

    <?php
      $db_pass = $P$BX5675uhhghfhgfhfhfgftut/0;
      $my_pass = "mypass";
      if ($db_pass === md5($my_pass)) {
        // password is matched
      } else {
        // password didn't match
      }
    
  2. Only for WordPress users. If you have access to your PHPMyAdmin, focus you have because you paste that hashing here: $P$BX5675uhhghfhgfhfhfgftut/0, WordPress user_pass is not only MD5 format it also uses utf8_mb4_cli charset so what to do?

    That's why I use another Approach if I forget my WordPress password I use

    I install other WordPress with new password :P, and I then go to PHPMyAdmin and copy that hashing from the database and paste that hashing to my current PHPMyAdmin password ( which I forget )

    EASY is use this :

    1. password = "ARJUNsingh@123"
    2. password_hasing = " $P$BDSdKx2nglM.5UErwjQGeVtVWvjEvD1 "
    3. Replace your $P$BX5675uhhghfhgfhfhfgftut/0 with my $P$BDSdKx2nglM.5UErwjQGeVtVWvjEvD1

I USE THIS APPROACH FOR MY SELF WHEN I DESIGN THEMES AND PLUGINS

WORDPRESS USE THIS

https://developer.wordpress.org/reference/functions/wp_hash_password/

Python base64 data decode

i used chardet to detect possible encoding of this data ( if its text ), but get {'confidence': 0.0, 'encoding': None}. Then i tried to use pickle.load and get nothing again. I tried to save this as file , test many different formats and failed here too. Maybe you tell us what type have this 16512 bytes of mysterious data?

How do I decode a string with escaped unicode?

UPDATE: Please note that this is a solution that should apply to older browsers or non-browser platforms, and is kept alive for instructional purposes. Please refer to @radicand 's answer below for a more up to date answer.


This is a unicode, escaped string. First the string was escaped, then encoded with unicode. To convert back to normal:

var x = "http\\u00253A\\u00252F\\u00252Fexample.com";
var r = /\\u([\d\w]{4})/gi;
x = x.replace(r, function (match, grp) {
    return String.fromCharCode(parseInt(grp, 16)); } );
console.log(x);  // http%3A%2F%2Fexample.com
x = unescape(x);
console.log(x);  // http://example.com

To explain: I use a regular expression to look for \u0025. However, since I need only a part of this string for my replace operation, I use parentheses to isolate the part I'm going to reuse, 0025. This isolated part is called a group.

The gi part at the end of the expression denotes it should match all instances in the string, not just the first one, and that the matching should be case insensitive. This might look unnecessary given the example, but it adds versatility.

Now, to convert from one string to the next, I need to execute some steps on each group of each match, and I can't do that by simply transforming the string. Helpfully, the String.replace operation can accept a function, which will be executed for each match. The return of that function will replace the match itself in the string.

I use the second parameter this function accepts, which is the group I need to use, and transform it to the equivalent utf-8 sequence, then use the built - in unescape function to decode the string to its proper form.

AJAX POST and Plus Sign ( + ) -- How to Encode?

In JavaScript try:

encodeURIComponent() 

and in PHP:

urldecode($_POST['field']);

Using an Alias in a WHERE clause

It's possible to effectively define a variable that can be used in both the SELECT, WHERE and other clauses.

A subquery doesn't necessarily allow for appropriate binding to the referenced table columns, however OUTER APPLY does.

SELECT A.identifier
     , A.name
     , vars.MONTH_NO
     , TO_NUMBER(TO_CHAR(B.last_update_date, 'YYYYMM')) as UPD_DATE
FROM table_a A
     , table_b B ON A.identifier = B.identifier
OUTER APPLY (
   SELECT
        -- variables
        MONTH_NO = TO_NUMBER(DECODE( A.month_no
                     , 1, 200803 
                     , 2, 200804 
                     , 3, 200805 
                     , 4, 200806 
                     , 5, 200807 
                     , 6, 200808 
                     , 7, 200809 
                     , 8, 200810 
                     , 9, 200811 
                     , 10, 200812 
                     , 11, 200701 
                     , 12, 200702
                     , NULL))
) vars
WHERE vars.MONTH_NO > UPD_DATE

Kudos to Syed Mehroz Alam.

UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>

The file in question is not using the CP1252 encoding. It's using another encoding. Which one you have to figure out yourself. Common ones are Latin-1 and UTF-8. Since 0x90 doesn't actually mean anything in Latin-1, UTF-8 (where 0x90 is a continuation byte) is more likely.

You specify the encoding when you open the file:

file = open(filename, encoding="utf8")

UnicodeDecodeError, invalid continuation byte

In this case, I tried to execute a .py which active a path/file.sql.

My solution was to modify the codification of the file.sql to "UTF-8 without BOM" and it works!

You can do it with Notepad++.

i will leave a part of my code.

/Code/

con=psycopg2.connect(host = sys.argv[1], port = sys.argv[2],dbname = sys.argv[3],user = sys.argv[4], password = sys.argv[5])

cursor = con.cursor() sqlfile = open(path, 'r')

PHP replacing special characters like à->a, è->e

Here is a way to have some flexibility in what should be discarded and what should be replaced. This is how I currently do it.

$string = 'À some string with junk I Ä ';

$replace = [
    '&lt;' => '', '&gt;' => '', '&#039;' => '', '&amp;' => '',
    '&quot;' => '', 'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'Ae',
    '&Auml;' => 'A', 'Å' => 'A', 'A' => 'A', 'A' => 'A', 'A' => 'A', 'Æ' => 'Ae',
    'Ç' => 'C', 'C' => 'C', 'C' => 'C', 'C' => 'C', 'C' => 'C', 'D' => 'D', 'Ð' => 'D',
    'Ð' => 'D', 'È' => 'E', 'É' => 'E', 'Ê' => 'E', 'Ë' => 'E', 'E' => 'E',
    'E' => 'E', 'E' => 'E', 'E' => 'E', 'E' => 'E', 'G' => 'G', 'G' => 'G',
    'G' => 'G', 'G' => 'G', 'H' => 'H', 'H' => 'H', 'Ì' => 'I', 'Í' => 'I',
    'Î' => 'I', 'Ï' => 'I', 'I' => 'I', 'I' => 'I', 'I' => 'I', 'I' => 'I',
    'I' => 'I', '?' => 'IJ', 'J' => 'J', 'K' => 'K', 'L' => 'K', 'L' => 'K',
    'L' => 'K', 'L' => 'K', '?' => 'K', 'Ñ' => 'N', 'N' => 'N', 'N' => 'N',
    'N' => 'N', '?' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O',
    'Ö' => 'Oe', '&Ouml;' => 'Oe', 'Ø' => 'O', 'O' => 'O', 'O' => 'O', 'O' => 'O',
    'Œ' => 'OE', 'R' => 'R', 'R' => 'R', 'R' => 'R', 'S' => 'S', 'Š' => 'S',
    'S' => 'S', 'S' => 'S', '?' => 'S', 'T' => 'T', 'T' => 'T', 'T' => 'T',
    '?' => 'T', 'Ù' => 'U', 'Ú' => 'U', 'Û' => 'U', 'Ü' => 'Ue', 'U' => 'U',
    '&Uuml;' => 'Ue', 'U' => 'U', 'U' => 'U', 'U' => 'U', 'U' => 'U', 'U' => 'U',
    'W' => 'W', 'Ý' => 'Y', 'Y' => 'Y', 'Ÿ' => 'Y', 'Z' => 'Z', 'Ž' => 'Z',
    'Z' => 'Z', 'Þ' => 'T', 'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a',
    'ä' => 'ae', '&auml;' => 'ae', 'å' => 'a', 'a' => 'a', 'a' => 'a', 'a' => 'a',
    'æ' => 'ae', 'ç' => 'c', 'c' => 'c', 'c' => 'c', 'c' => 'c', 'c' => 'c',
    'd' => 'd', 'd' => 'd', 'ð' => 'd', 'è' => 'e', 'é' => 'e', 'ê' => 'e',
    'ë' => 'e', 'e' => 'e', 'e' => 'e', 'e' => 'e', 'e' => 'e', 'e' => 'e',
    'ƒ' => 'f', 'g' => 'g', 'g' => 'g', 'g' => 'g', 'g' => 'g', 'h' => 'h',
    'h' => 'h', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'i' => 'i',
    'i' => 'i', 'i' => 'i', 'i' => 'i', 'i' => 'i', '?' => 'ij', 'j' => 'j',
    'k' => 'k', '?' => 'k', 'l' => 'l', 'l' => 'l', 'l' => 'l', 'l' => 'l',
    '?' => 'l', 'ñ' => 'n', 'n' => 'n', 'n' => 'n', 'n' => 'n', '?' => 'n',
    '?' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ö' => 'oe',
    '&ouml;' => 'oe', 'ø' => 'o', 'o' => 'o', 'o' => 'o', 'o' => 'o', 'œ' => 'oe',
    'r' => 'r', 'r' => 'r', 'r' => 'r', 'š' => 's', 'ù' => 'u', 'ú' => 'u',
    'û' => 'u', 'ü' => 'ue', 'u' => 'u', '&uuml;' => 'ue', 'u' => 'u', 'u' => 'u',
    'u' => 'u', 'u' => 'u', 'u' => 'u', 'w' => 'w', 'ý' => 'y', 'ÿ' => 'y',
    'y' => 'y', 'ž' => 'z', 'z' => 'z', 'z' => 'z', 'þ' => 't', 'ß' => 'ss',
    '?' => 'ss', '??' => 'iy', '?' => 'A', '?' => 'B', '?' => 'V', '?' => 'G',
    '?' => 'D', '?' => 'E', '?' => 'YO', '?' => 'ZH', '?' => 'Z', '?' => 'I',
    '?' => 'Y', '?' => 'K', '?' => 'L', '?' => 'M', '?' => 'N', '?' => 'O',
    '?' => 'P', '?' => 'R', '?' => 'S', '?' => 'T', '?' => 'U', '?' => 'F',
    '?' => 'H', '?' => 'C', '?' => 'CH', '?' => 'SH', '?' => 'SCH', '?' => '',
    '?' => 'Y', '?' => '', '?' => 'E', '?' => 'YU', '?' => 'YA', '?' => 'a',
    '?' => 'b', '?' => 'v', '?' => 'g', '?' => 'd', '?' => 'e', '?' => 'yo',
    '?' => 'zh', '?' => 'z', '?' => 'i', '?' => 'y', '?' => 'k', '?' => 'l',
    '?' => 'm', '?' => 'n', '?' => 'o', '?' => 'p', '?' => 'r', '?' => 's',
    '?' => 't', '?' => 'u', '?' => 'f', '?' => 'h', '?' => 'c', '?' => 'ch',
    '?' => 'sh', '?' => 'sch', '?' => '', '?' => 'y', '?' => '', '?' => 'e',
    '?' => 'yu', '?' => 'ya'
];

echo str_replace(array_keys($replace), $replace, $string);  

Base64 Java encode and decode a string

import javax.xml.bind.DatatypeConverter;

public class f{

   public static void main(String a[]){

      String str = new String(DatatypeConverter.printBase64Binary(new String("user:123").getBytes()));
      String res = DatatypeConverter.parseBase64Binary(str);
      System.out.println(res);
   }
}

How to unescape HTML character entities in Java?

The libraries mentioned in other answers would be fine solutions, but if you already happen to be digging through real-world html in your project, the Jsoup project has a lot more to offer than just managing "ampersand pound FFFF semicolon" things.

// textValue: <p>This is a&nbsp;sample. \"Granny\" Smith &#8211;.<\/p>\r\n
// becomes this: This is a sample. "Granny" Smith –.
// with one line of code:
// Jsoup.parse(textValue).getText(); // for older versions of Jsoup
Jsoup.parse(textValue).text();

// Another possibility may be the static unescapeEntities method:
boolean strictMode = true;
String unescapedString = org.jsoup.parser.Parser.unescapeEntities(textValue, strictMode);

And you also get the convenient API for extracting and manipulating data, using the best of DOM, CSS, and jquery-like methods. It's open source and MIT licence.

UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

I dug deeper into this and found the best solutions are here.

http://blog.notdot.net/2010/07/Getting-unicode-right-in-Python

In my case I solved "UnicodeEncodeError: 'charmap' codec can't encode character "

original code:

print("Process lines, file_name command_line %s\n"% command_line))

New code:

print("Process lines, file_name command_line %s\n"% command_line.encode('utf-8'))  

Git commit with no commit message

I found the simplest solution:

git commit -am'save'

That's all,you will work around git commit message stuff.

you can even save that commend to a bash or other stuff to make it more simple.

Our team members always write those messages,but almost no one will see those message again.

Commit message is a time-kill stuff at least in our team,so we ignore it.

Can I use an image from my local file system as background in HTML?

Jeff Bridgman is correct. All you need is
background: url('pic.jpg')
and this assumes that pic is in the same folder as your html.

Also, Roberto's answer works fine. Tested in Firefox, and IE. Thanks to Raptor for adding formatting that displays full picture fit to screen, and without scrollbars... In a folder f, on the desktop is this html and a picture, pic.jpg, using your userid. Make those substitutions in the below:

<html>
<head>
    <style>
        body {

        background: url('file:///C:/Users/userid/desktop/f/pic.jpg') no-repeat center center fixed;

        background-size: cover; /* for IE9+, Safari 4.1+, Chrome 3.0+, Firefox 3.6+ */
        -webkit-background-size: cover; /* for Safari 3.0 - 4.0 , Chrome 1.0 - 3.0 */
        -moz-background-size: cover; /* optional for Firefox 3.6 */ 
        -o-background-size: cover; /* for Opera 9.5 */
        margin: 0; /* to remove the default white margin of body */
        padding: 0; /* to remove the default white margin of body */
        overflow: hidden;
             }
    </style>
</head>
<body>
hello
</body>
</html>

After installation of Gulp: “no command 'gulp' found”

I solved the issue without reinstalling node using the commands below:

$ npm uninstall --global gulp gulp-cli
$ rm /usr/local/share/man/man1/gulp.1
$ npm install --global gulp-cli

Spring schemaLocation fails when there is no internet connection

If you are using eclipse for your development , it helps if you install STS plugin for Eclipse [ from the marketPlace for the specific version of eclipse .

Now When you try to create a new configuration file in a folder(normally resources) inside the project , the options would have a "Spring Folder" and you can choose a "Spring Bean Definition File " option Spring > Spring Bean Configuation File .

With this option selected , when you follow steps , it asks you to select for namespaces and the specific versions :

And so the possibility of having a non-existent jar Or old version can be eliminated .

Would have posted images as well , but my reputation is pretty low.. :(

Saving changes after table edit in SQL Server Management Studio

Rather than unchecking the box (a poor solution), you should STOP editing data that way. If data must be changed, then do it with a script, so that you can easily port it to production and so that it is under source control. This also makes it easier to refresh testing changes after production has been pushed down to dev to enable developers to be working against fresher data.

How to calculate the sum of the datatable column in asp.net?

You can do like..

DataRow[] dr = dtbl.Select("SUM(Amount)");
txtTotalAmount.Text = Convert.ToString(dr[0]);

sudo in php exec()

I had a similar situation trying to exec() a backend command and also getting no tty present and no askpass program specified in the web server error log. Original (bad) code:

$output = array();
$return_var = 0;
exec('sudo my_command', $output, $return_var);

A bash wrapper solved this issue, such as:

$output = array();
$return_var = 0;
exec('sudo bash -c "my_command"', $output, $return_var);

Not sure if this will work in every case. Also, be sure to apply the appropriate quoting/escaping rules on my_command portion.

How do I tokenize a string in C++?

Here is a sample tokenizer class that might do what you want

//Header file
class Tokenizer 
{
    public:
        static const std::string DELIMITERS;
        Tokenizer(const std::string& str);
        Tokenizer(const std::string& str, const std::string& delimiters);
        bool NextToken();
        bool NextToken(const std::string& delimiters);
        const std::string GetToken() const;
        void Reset();
    protected:
        size_t m_offset;
        const std::string m_string;
        std::string m_token;
        std::string m_delimiters;
};

//CPP file
const std::string Tokenizer::DELIMITERS(" \t\n\r");

Tokenizer::Tokenizer(const std::string& s) :
    m_string(s), 
    m_offset(0), 
    m_delimiters(DELIMITERS) {}

Tokenizer::Tokenizer(const std::string& s, const std::string& delimiters) :
    m_string(s), 
    m_offset(0), 
    m_delimiters(delimiters) {}

bool Tokenizer::NextToken() 
{
    return NextToken(m_delimiters);
}

bool Tokenizer::NextToken(const std::string& delimiters) 
{
    size_t i = m_string.find_first_not_of(delimiters, m_offset);
    if (std::string::npos == i) 
    {
        m_offset = m_string.length();
        return false;
    }

    size_t j = m_string.find_first_of(delimiters, i);
    if (std::string::npos == j) 
    {
        m_token = m_string.substr(i);
        m_offset = m_string.length();
        return true;
    }

    m_token = m_string.substr(i, j - i);
    m_offset = j;
    return true;
}

Example:

std::vector <std::string> v;
Tokenizer s("split this string", " ");
while (s.NextToken())
{
    v.push_back(s.GetToken());
}

Thread-safe List<T> property

If you are targetting .Net 4 there are a few options in System.Collections.Concurrent Namespace

You could use ConcurrentBag<T> in this case instead of List<T>

TypeError: a bytes-like object is required, not 'str' in python and CSV

You are opening the csv file in binary mode, it should be 'w'

import csv

# open csv file in write mode with utf-8 encoding
with open('output.csv','w',encoding='utf-8',newline='')as w:
    fieldnames = ["SNo", "States", "Dist", "Population"]
    writer = csv.DictWriter(w, fieldnames=fieldnames)
    # write list of dicts
    writer.writerows(list_of_dicts) #writerow(dict) if write one row at time

Using sed, Insert a line above or below the pattern?

The following adds one line after SearchPattern.

sed -i '/SearchPattern/aNew Text' SomeFile.txt

It inserts New Text one line below each line that contains SearchPattern.

To add two lines, you can use a \ and enter a newline while typing New Text.

POSIX sed requires a \ and a newline after the a sed function. [1] Specifying the text to append without the newline is a GNU sed extension (as documented in the sed info page), so its usage is not as portable.

[1] https://unix.stackexchange.com/questions/52131/sed-on-osx-insert-at-a-certain-line/

Merge two dataframes by index

Use merge, which is inner join by default:

pd.merge(df1, df2, left_index=True, right_index=True)

Or join, which is left join by default:

df1.join(df2)

Or concat, which is outer join by default:

pd.concat([df1, df2], axis=1)

Samples:

df1 = pd.DataFrame({'a':range(6),
                    'b':[5,3,6,9,2,4]}, index=list('abcdef'))

print (df1)
   a  b
a  0  5
b  1  3
c  2  6
d  3  9
e  4  2
f  5  4

df2 = pd.DataFrame({'c':range(4),
                    'd':[10,20,30, 40]}, index=list('abhi'))

print (df2)
   c   d
a  0  10
b  1  20
h  2  30
i  3  40

#default inner join
df3 = pd.merge(df1, df2, left_index=True, right_index=True)
print (df3)
   a  b  c   d
a  0  5  0  10
b  1  3  1  20

#default left join
df4 = df1.join(df2)
print (df4)
   a  b    c     d
a  0  5  0.0  10.0
b  1  3  1.0  20.0
c  2  6  NaN   NaN
d  3  9  NaN   NaN
e  4  2  NaN   NaN
f  5  4  NaN   NaN

#default outer join
df5 = pd.concat([df1, df2], axis=1)
print (df5)
     a    b    c     d
a  0.0  5.0  0.0  10.0
b  1.0  3.0  1.0  20.0
c  2.0  6.0  NaN   NaN
d  3.0  9.0  NaN   NaN
e  4.0  2.0  NaN   NaN
f  5.0  4.0  NaN   NaN
h  NaN  NaN  2.0  30.0
i  NaN  NaN  3.0  40.0

Limit the output of the TOP command to a specific process name

Suppose .. if we have more than 20 process running on the server with the same name ... this will not help

top -p pgrep oracle | head -n 20 | tr "\\n" "," | sed 's/,$//'

It will try to list and provide real time output of 20 process where we have good chance of missing other prcesses which consumes more resource ....

I am still looking for better option on this

Bootstrap 3 2-column form layout

You could use the bootstrap grid system :

<div class="col-md-6 form-group">
    <label for="textbox1">Label1</label>
    <input class="form-control" id="textbox1" type="text"/>
</div>
<div class="col-md-6 form-group">
    <label for="textbox2">Label2</label>
    <input class="form-control" id="textbox2" type="text"/>
</div>
<span class="clearfix">

http://getbootstrap.com/css/#grid

Is that what you want to achieve?

jQuery return ajax result into outside variable

I solved it by doing like that:

var return_first = (function () {
        var tmp = $.ajax({
            'type': "POST",
            'dataType': 'html',
            'url': "ajax.php?first",
            'data': { 'request': "", 'target': arrange_url, 'method': 
                    method_target },
            'success': function (data) {
                tmp = data;
            }
        }).done(function(data){
                return data;
        });
      return tmp;
    });
  • Be careful 'async':fale javascript will be asynchronous.

What is “assert” in JavaScript?

Word or function "assert" is mostly used in testing parts of application.

Assert functions are a short way of instructing the program to check the condition (also called "assertion") and if the condition is not True, it will throw error.

So let's see how it would look like in "normal code"

if (typeof "string" === "array") { throw Error('Error: "string" !== "array"'); }

With assert you can simply write:

assert(typeof "string" === "array")

In Javascript, there's no native assert function, so you have to use one from some library.

For simple introduction, you can check this article:

http://fredkschott.com/post/2014/05/nodejs-testing-essentials/

I hope it helps.

Creating stored procedure and SQLite?

SQLite has had to sacrifice other characteristics that some people find useful, such as high concurrency, fine-grained access control, a rich set of built-in functions, stored procedures, esoteric SQL language features, XML and/or Java extensions, tera- or peta-byte scalability, and so forth

Source : Appropriate Uses For SQLite

Unable to find the requested .Net Framework Data Provider. It may not be installed. - when following mvc3 asp.net tutorial

This happened to me because I created a new project which was trying to use System.Web.Providers DefaultMembershipProvider for membership. My DB and application was set up to use System.Web.Security.SqlMembershipProvider instead. I had to update the provider and connection string (since this provider seems to have some weird connection string requirements) to get it working.

Docker compose port mapping

It seems like the other answers here all misunderstood your question. If I understand correctly, you want to make requests to localhost:6379 (the default for redis) and have them be forwarded, automatically, to the same port on your redis container.

https://unix.stackexchange.com/a/101906/38639 helped me get to the right answer.

First, you'll need to install the nc command on your image. On CentOS, this package is called nmap-ncat, so in the example below, just replace this with the appropriate package if you are using a different OS as your base image.

Next, you'll need to tell it to run a certain command each time the container boots up. You can do this using CMD.

# Add this to your Dockerfile
RUN yum install -y --setopt=skip_missing_names_on_install=False nmap-ncat
COPY cmd.sh /usr/local/bin/cmd.sh
RUN chmod +x /usr/local/bin/cmd.sh
CMD ["/usr/local/bin/cmd.sh"]

Finally, we'll need to set up port-forwarding in cmd.sh. I found that nc, even with the -l and -k options, will occasionally terminate when a request is completed, so I'm using a while-loop to ensure that it's always running.

# cmd.sh
#! /usr/bin/env bash

while nc -l -p 6379 -k -c "nc redis 6379" || true; do true; done &

tail -f /dev/null # Or any other command that never exits

Saving lists to txt file

Assuming your Generic List is of type String:

TextWriter tw = new StreamWriter("SavedList.txt");

foreach (String s in Lists.verbList)
   tw.WriteLine(s);

tw.Close();

Alternatively, with the using keyword:

using(TextWriter tw = new StreamWriter("SavedList.txt"))
{
   foreach (String s in Lists.verbList)
      tw.WriteLine(s);
}

How to get the android Path string to a file on Assets folder?

Have a look at the ReadAsset.java from API samples that come with the SDK.

       try {
        InputStream is = getAssets().open("read_asset.txt");

        // We guarantee that the available method returns the total
        // size of the asset...  of course, this does mean that a single
        // asset can't be more than 2 gigs.
        int size = is.available();

        // Read the entire asset into a local byte buffer.
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();

        // Convert the buffer into a string.
        String text = new String(buffer);

        // Finally stick the string into the text view.
        TextView tv = (TextView)findViewById(R.id.text);
        tv.setText(text);
    } catch (IOException e) {
        // Should never happen!
        throw new RuntimeException(e);
    }

Laravel 5.4 redirection to custom url after login

For newer versions of Laravel, please replace protected $redirectTo = RouteServiceProvider::HOME; with protected $redirectTo = '/newurl'; and replace newurl accordingly.

Tested with Laravel version-6

Convert a String to a byte array and then back to the original String

I would suggest using the members of string, but with an explicit encoding:

byte[] bytes = text.getBytes("UTF-8");
String text = new String(bytes, "UTF-8");

By using an explicit encoding (and one which supports all of Unicode) you avoid the problems of just calling text.getBytes() etc:

  • You're explicitly using a specific encoding, so you know which encoding to use later, rather than relying on the platform default.
  • You know it will support all of Unicode (as opposed to, say, ISO-Latin-1).

EDIT: Even though UTF-8 is the default encoding on Android, I'd definitely be explicit about this. For example, this question only says "in Java or Android" - so it's entirely possible that the code will end up being used on other platforms.

Basically given that the normal Java platform can have different default encodings, I think it's best to be absolutely explicit. I've seen way too many people using the default encoding and losing data to take that risk.

EDIT: In my haste I forgot to mention that you don't have to use the encoding's name - you can use a Charset instead. Using Guava I'd really use:

byte[] bytes = text.getBytes(Charsets.UTF_8);
String text = new String(bytes, Charsets.UTF_8);

MVC razor form with multiple different submit buttons?

The cleanest solution I've found is as follows:

This example is to perform two very different actions; the basic premise is to use the value to pass data to the action.

In your view:

@using (Html.BeginForm("DliAction", "Dli", FormMethod.Post, new { id = "mainForm" }))
{
    if (isOnDli)
    {
        <button name="removeDli" value="@result.WeNo">Remove From DLI</button>
    }
    else
    {
        <button name="performDli" value="@result.WeNo">Perform DLI</button>
    }
}

Then in your action:

    public ActionResult DliAction(string removeDli, string performDli)
    {
        if (string.IsNullOrEmpty(performDli))
        {
            ...
        }
        else if (string.IsNullOrEmpty(removeDli))
        {
            ...
        }

        return View();
    }

This code should be easy to alter in order to achieve variations along the theme, e.g. change the button's name to be the same, then you only need one parameter on the action etc, as can be seen below:

In your view:

@using (Html.BeginForm("DliAction", "Dli", FormMethod.Post, new { id = "mainForm" }))
{

        <button name="weNo" value="@result.WeNo">Process This WeNo</button>

        <button name="weNo" value="@result.WeNo">Process A Different WeNo This Item</button>
}

Then in your action:

    public ActionResult DliAction(string weNo)
    {
        // Process the weNo...

        return View();
    }

PHP Session Destroy on Log Out Button

The folder being password protected has nothing to do with PHP!

The method being used is called "Basic Authentication". There are no cross-browser ways to "logout" from it, except to ask the user to close and then open their browser...

Here's how you you could do it in PHP instead (fully remove your Apache basic auth in .htaccess or wherever it is first):

login.php:

<?php
session_start();
//change 'valid_username' and 'valid_password' to your desired "correct" username and password
if (! empty($_POST) && $_POST['user'] === 'valid_username' && $_POST['pass'] === 'valid_password')
{
    $_SESSION['logged_in'] = true;
    header('Location: /index.php');
}
else
{
    ?>

    <form method="POST">
    Username: <input name="user" type="text"><br>
    Password: <input name="pass" type="text"><br><br>
    <input type="submit" value="submit">
    </form>

    <?php
}

index.php

<?php
session_start();
if (! empty($_SESSION['logged_in']))
{
    ?>

    <p>here is my super-secret content</p>
    <a href='logout.php'>Click here to log out</a>

    <?php
}
else
{
    echo 'You are not logged in. <a href="login.php">Click here</a> to log in.';
}

logout.php:

<?php
session_start();
session_destroy();
echo 'You have been logged out. <a href="/">Go back</a>';

Obviously this is a very basic implementation. You'd expect the usernames and passwords to be in a database, not as a hardcoded comparison. I'm just trying to give you an idea of how to do the session thing.

Hope this helps you understand what's going on.

How to map an array of objects in React

@FurkanO has provided the right approach. Though to go for a more cleaner approach (es6 way) you can do something like this

[{
    name: 'Sam',
    email: '[email protected]'
 },
 {
    name: 'Ash',
    email: '[email protected]'
 }
].map( ( {name, email} ) => {
    return <p key={email}>{name} - {email}</p>
})

Cheers!

Using GCC to produce readable assembly?

use -Wa,-adhln as option on gcc or g++ to produce a listing output to stdout.

-Wa,... is for command line options for the assembler part (execute in gcc/g++ after C/++ compilation). It invokes as internally (as.exe in Windows). See

>as --help

as command line to see more help for the assembler tool inside gcc

Calculate mean and standard deviation from a vector of samples in C++ using Boost

I don't know if Boost has more specific functions, but you can do it with the standard library.

Given std::vector<double> v, this is the naive way:

#include <numeric>

double sum = std::accumulate(v.begin(), v.end(), 0.0);
double mean = sum / v.size();

double sq_sum = std::inner_product(v.begin(), v.end(), v.begin(), 0.0);
double stdev = std::sqrt(sq_sum / v.size() - mean * mean);

This is susceptible to overflow or underflow for huge or tiny values. A slightly better way to calculate the standard deviation is:

double sum = std::accumulate(v.begin(), v.end(), 0.0);
double mean = sum / v.size();

std::vector<double> diff(v.size());
std::transform(v.begin(), v.end(), diff.begin(),
               std::bind2nd(std::minus<double>(), mean));
double sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);
double stdev = std::sqrt(sq_sum / v.size());

UPDATE for C++11:

The call to std::transform can be written using a lambda function instead of std::minus and std::bind2nd(now deprecated):

std::transform(v.begin(), v.end(), diff.begin(), [mean](double x) { return x - mean; });

Refreshing data in RecyclerView and keeping its scroll position

Keep scroll position by using @DawnYu answer to wrap notifyDataSetChanged() like this:

val recyclerViewState = recyclerView.layoutManager?.onSaveInstanceState() 
adapter.notifyDataSetChanged() 
recyclerView.layoutManager?.onRestoreInstanceState(recyclerViewState)

CSS opacity only to background color, not the text on it?

A great way to do this would be to use CSS 3 indeed.

Create a div width a class - e.g. supersizer on top of your page:

Then set following CSS properties:

_x000D_
_x000D_
  .supersizer {_x000D_
    background: url("http://fc06.deviantart.net/fs70/f/2012/099/d/f/stackoverflow_16x16_icon_by_muntoo_stock-d4vl2v4.png") no-repeat center center fixed;_x000D_
    width: 100%;_x000D_
    height: 100%;_x000D_
    position: fixed;_x000D_
    z-index: -1;_x000D_
    opacity: 0.5;_x000D_
    -webkit-background-size: cover;_x000D_
    -moz-background-size: cover;_x000D_
    -o-background-size: cover;_x000D_
    background-size: cover;_x000D_
    top: 0;_x000D_
  }
_x000D_
<div class="supersizer"></div>
_x000D_
_x000D_
_x000D_

What is an AssertionError? In which case should I throw it from my own code?

Of course the "You shall not instantiate an item of this class" statement has been violated, but if this is the logic behind that, then we should all throw AssertionErrors everywhere, and that is obviously not what happens.

The code isn't saying the user shouldn't call the zero-args constructor. The assertion is there to say that as far as the programmer is aware, he/she has made it impossible to call the zero-args constructor (in this case by making it private and not calling it from within Example's code). And so if a call occurs, that assertion has been violated, and so AssertionError is appropriate.

error: Unable to find vcvarsall.bat

Go here: http://docs.continuum.io/anaconda/install.html#windows-install

There are instructions to install anaconda which will provide a GUI and a silent install of a majority of the packages that seem to be causing this issue from http://www.scipy.org/. I am aware of the solution for 2.7 here https://www.microsoft.com/en-us/download/details.aspx?id=44266 but I did not see an option for Python 3.4. After downloading and installing Anaconda you should be able to import a majority of the packages you need from scipy.

Hope this helps some people. Took me 45 minutes of scouring posts and sites.

EDIT: Just wanted to note there is a Python34 link on the GUI page next to the OS symbols.

What is the difference between <%, <%=, <%# and -%> in ERB in Rails?

<% %> and <%- and -%> are for any Ruby code, but doesn't output the results (e.g. if statements). the two are the same.

<%= %> is for outputting the results of Ruby code

<%# %> is an ERB comment

Here's a good guide: http://api.rubyonrails.org/classes/ActionView/Base.html

What is /dev/null 2>&1?

Edit /etc/conf.apf. Set DEVEL_MODE="0". DEVEL_MODE set to 1 will add a cron job to stop apf after 5 minutes.

! [rejected] master -> master (fetch first)

Please try this command to solve it -

git push origin master --force

Or

 git push origin master -f

Send JavaScript variable to PHP variable

It depends on the way your page behaves. If you want this to happens asynchronously, you have to use AJAX. Try out "jQuery post()" on Google to find some tuts.

In other case, if this will happen when a user submits a form, you can send the variable in an hidden field or append ?variableName=someValue" to then end of the URL you are opening. :

http://www.somesite.com/send.php?variableName=someValue

or

http://www.somesite.com/send.php?variableName=someValue&anotherVariable=anotherValue

This way, from PHP you can access this value as:

$phpVariableName = $_POST["variableName"];

for forms using POST method or:

$phpVariableName = $_GET["variableName"];

for forms using GET method or the append to url method I've mentioned above (querystring).

Bizarre Error in Chrome Developer Console - Failed to load resource: net::ERR_CACHE_MISS

Check for the presence of words like "ad", "banner" or "popup" within your file. I removed these and it worked. Based on this post here: Failed to load resource under Chrome it seems like Ad Block Plus was the culprit in my case.

How do I create a view controller file after creating a new view controller?

Correct, when you drag a view controller object onto your storyboard in order to create a new scene, it doesn't automatically make the new class for you, too.

Having added a new view controller scene to your storyboard, you then have to:

  1. Create a UIViewController subclass. For example, go to your target's folder in the project navigator panel on the left and then control-click and choose "New File...". Choose a "Cocoa Touch Class":

    Cocoa Touch Class

    And then select a unique name for the new view controller subclass:

    UIViewController subclass

  2. Specify this new subclass as the base class for the scene you just added to the storyboard.

    enter image description here

  3. Now hook up any IBOutlet and IBAction references for this new scene with the new view controller subclass.

Disabled href tag

Here are various ways to disable the a tag :

<a >Link Text</a> remove the href from your anchor tag
<a href=”javascript:void(0)”/>Link text</a> put javascript:void(0) in href
<a href="/" onclick="return false;">Link text</a> using return false

As there is no disabled attributes for anchor tag. If you want to stop anchor tag behavior inside a jQuery function than you can use the the below line in the start of the function :

$( "a" ).click(function( e ) {
e.preventDefault();
$( "<div>" )
.append( "default " + e.type + " prevented" )
.appendTo( "#log" );
});

event.preventDefault()

How do I split a string on a delimiter in Bash?

In Android shell, most of the proposed methods just do not work:

$ IFS=':' read -ra ADDR <<<"$PATH"                             
/system/bin/sh: can't create temporary file /sqlite_stmt_journals/mksh.EbNoR10629: No such file or directory

What does work is:

$ for i in ${PATH//:/ }; do echo $i; done
/sbin
/vendor/bin
/system/sbin
/system/bin
/system/xbin

where // means global replacement.

Build Maven Project Without Running Unit Tests

If you want to skip running and compiling tests:

mvn -Dmaven.test.skip=true install

If you want to compile but not run tests:

mvn install -DskipTests

How to convert String to DOM Document object in java?

Either escape the double quotes with \

String xmlString = "<element attribname=\"value\" attribname1=\"value1\"> pcdata</element>"

or use single quotes instead

String xmlString = "<element attribname='value' attribname1='value1'> pcdata</element>"

adding css class to multiple elements

try this:

.button input, .button a {
//css here
}

That will apply the style to all a tags nested inside of <p class="button"></p>

How to print a two dimensional array?

Something like this that i answer in another question

public class Snippet {
    public static void main(String[] args) {
        int [][]lst = new int[10][10];

        for (int[] arr : lst) {
            System.out.println(Arrays.toString(arr));
        }
    }

}

How to write console output to a txt file

to preserve the console output, that is, write to a file and also have it displayed on the console, you could use a class like:

    public class TeePrintStream extends PrintStream {
        private final PrintStream second;

        public TeePrintStream(OutputStream main, PrintStream second) {
            super(main);
            this.second = second;
        }

        /**
         * Closes the main stream. 
         * The second stream is just flushed but <b>not</b> closed.
         * @see java.io.PrintStream#close()
         */
        @Override
        public void close() {
            // just for documentation
            super.close();
        }

        @Override
        public void flush() {
            super.flush();
            second.flush();
        }

        @Override
        public void write(byte[] buf, int off, int len) {
            super.write(buf, off, len);
            second.write(buf, off, len);
        }

        @Override
        public void write(int b) {
            super.write(b);
            second.write(b);
        }

        @Override
        public void write(byte[] b) throws IOException {
            super.write(b);
            second.write(b);
        }
    }

and used as in:

    FileOutputStream file = new FileOutputStream("test.txt");
    TeePrintStream tee = new TeePrintStream(file, System.out);
    System.setOut(tee);

(just an idea, not complete)

Is there a Python equivalent of the C# null-coalescing operator?

For those like me that stumbled here looking for a viable solution to this issue, when the variable might be undefined, the closest i got is:

if 'variablename' in globals() and ((variablename or False) == True):
  print('variable exists and it\'s true')
else:
  print('variable doesn\'t exist, or it\'s false')

Note that a string is needed when checking in globals, but afterwards the actual variable is used when checking for value.

More on variable existence: How do I check if a variable exists?

how can get index & count in vuejs

Why its printing 0,1,2...?

Because those are indexes of the items in array, and index always starts from 0 to array.length-1.

To print the item count instead of index, use index+1. Like this:

<li v-for="(catalog, index) in catalogs">this index : {{index + 1}}</li>

And to show the total count use array.length, Like this:

<p>Total Count: {{ catalogs.length }}</p>

As per DOC:

v-for also supports an optional second argument (not first) for the index of the current item.

How can I get the nth character of a string?

char* str = "HELLO";
char c = str[1];

Keep in mind that arrays and strings in C begin indexing at 0 rather than 1, so "H" is str[0], "E" is str[1], the first "L" is str[2] and so on.

C error: undefined reference to function, but it IS defined

Add the "extern" keyword to the function definitions in point.h

<hr> tag in Twitter Bootstrap not functioning correctly?

I was able to customize the hrTag by editing the inline styling as such:

<div class="row"> <!-- You can also position the row if need be. -->
<div class="col-md-12 col-lg-12"><!-- set width of column I wanted mine to stretch most of the screen-->
<hr style="min-width:85%; background-color:#a1a1a1 !important; height:1px;"/>
</div>
 </div>

The hrTag is now thicker and more visible; it's also a darker gray color. The bootstrap code is actually very flexible. As the snippet demonstrates above, you can use inline styling or your own custom code. Hope this helps someone.

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

Others have answered so I'll add my 2-cents.

You can either use autoconfiguration (i.e. don't use a @Configuration to create a datasource) or java configuration.

Auto-configuration:

define your datasource type then set the type properties. E.g.

spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.hikari.driver-class-name=org.h2.Driver
spring.datasource.hikari.jdbc-url=jdbc:h2:mem:testdb
spring.datasource.hikari.username=sa
spring.datasource.hikari.password=password
spring.datasource.hikari.max-wait=10000
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.idle-timeout=600000
spring.datasource.hikari.max-lifetime=1800000
spring.datasource.hikari.leak-detection-threshold=600000
spring.datasource.hikari.maximum-pool-size=100
spring.datasource.hikari.pool-name=MyDataSourcePoolName

Java configuration:

Choose a prefix and define your data source

spring.mysystem.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.mysystem.datasource.jdbc- 
url=jdbc:sqlserver://databaseserver.com:18889;Database=MyDatabase;
spring.mysystem.datasource.username=dsUsername
spring.mysystem.datasource.password=dsPassword
spring.mysystem.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.mysystem.datasource.max-wait=10000
spring.mysystem.datasource.connection-timeout=30000
spring.mysystem.datasource.idle-timeout=600000
spring.mysystem.datasource.max-lifetime=1800000
spring.mysystem.datasource.leak-detection-threshold=600000
spring.mysystem.datasource.maximum-pool-size=100
spring.mysystem.datasource.pool-name=MySystemDatasourcePool

Create your datasource bean:

@Bean(name = { "dataSource", "mysystemDataSource" })
@ConfigurationProperties(prefix = "spring.mysystem.datasource")
public DataSource dataSource() {
    return DataSourceBuilder.create().build();
}

You can leave the datasource type out, but then you risk spring guessing what datasource type to use.

How to get Rails.logger printing to the console/stdout when running rspec?

Tail the log as a background job (&) and it will interleave with rspec output.

tail -f log/test.log &
bundle exec rspec

Format price in the current locale and currency

Unformatted and formatted:

$price = $product->getPrice();
$formatted = Mage::helper('core')->currency($price, true, false);

Or use:

Mage::helper('core')->formatPrice($price, true);

SVN repository backup strategies

Detailed reference in the SVNBook: "Repository data migration using svnadmin"

Reload .profile in bash shell script (in unix)?

Try this to reload your current shell:

source ~/.profile

Where does PHP's error log reside in XAMPP?

As said above you can find PHP error log in windows. In c:\xampp\apache\logs\error.log. You can easily display the last logs by tail -f .\error.log

iOS app 'The application could not be verified' only on one device

I had changed the team but I forgot to change it in my Tests target it so it caused that. Maybe this helps someone.

How to git ignore subfolders / subdirectories?

To ignore all subdirectories you can simply use:

**/

This works as of version 1.8.2 of git.

Zipping a file in bash fails

Run dos2unix or similar utility on it to remove the carriage returns (^M).

This message indicates that your file has dos-style lineendings:

-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory 

Utilities like dos2unix will fix it:

 dos2unix <backup.bash >improved-backup.sh 

Or, if no such utility is installed, you can accomplish the same thing with translate:

tr -d "\015\032" <backup.bash >improved-backup.sh 

As for how those characters got there in the first place, @MadPhysicist had some good comments.

Passing a local variable from one function to another

You can very easily use this to re-use the value of the variable in another function.

// Use this in source window.var1= oEvent.getSource().getBindingContext();

// Get value of var1 in destination var var2= window.var1;

How to print SQL statement in codeigniter model

I read all answers here, but cannot get

echo $this->db->get_compiled_select();

to work, It gave me error like,

Call to protected method CI_DB_active_record::_compile_select() from context 'Welcome'in controllers on line xx

So i removed protected from the below line from file \system\database\DB_active_rec.php and it worked

protected function _compile_select($select_override = FALSE)

How do I correctly clean up a Python object?

Here is a minimal working skeleton:

class SkeletonFixture:

    def __init__(self):
        pass

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        pass

    def method(self):
        pass


with SkeletonFixture() as fixture:
    fixture.method()

Important: return self


If you're like me, and overlook the return self part (of Clint Miller's correct answer), you will be staring at this nonsense:

Traceback (most recent call last):
  File "tests/simplestpossible.py", line 17, in <module>                                                                                                                                                          
    fixture.method()                                                                                                                                                                                              
AttributeError: 'NoneType' object has no attribute 'method'

Hope it helps the next person.

Unable to compile class for JSP

In my case, I was using the 6.0.24 Tomcat version (with JDK 1.8) and resolved the problem by upgrading to the 6.0.37 version.

Also, if you install the new tomcat version in a different folder, do not forget to copy your previous version /conf folder to the new installation folder.

Setting different color for each series in scatter plot on matplotlib

This question is a bit tricky before Jan 2013 and matplotlib 1.3.1 (Aug 2013), which is the oldest stable version you can find on matpplotlib website. But after that it is quite trivial.

Because present version of matplotlib.pylab.scatter support assigning: array of colour name string, array of float number with colour map, array of RGB or RGBA.

this answer is dedicate to @Oxinabox's endless passion for correcting the 2013 version of myself in 2015.


you have two option of using scatter command with multiple colour in a single call.

  1. as pylab.scatter command support use RGBA array to do whatever colour you want;

  2. back in early 2013, there is no way to do so, since the command only support single colour for the whole scatter point collection. When I was doing my 10000-line project I figure out a general solution to bypass it. so it is very tacky, but I can do it in whatever shape, colour, size and transparent. this trick also could be apply to draw path collection, line collection....

the code is also inspired by the source code of pyplot.scatter, I just duplicated what scatter does without trigger it to draw.

the command pyplot.scatter return a PatchCollection Object, in the file "matplotlib/collections.py" a private variable _facecolors in Collection class and a method set_facecolors.

so whenever you have a scatter points to draw you can do this:

# rgbaArr is a N*4 array of float numbers you know what I mean
# X is a N*2 array of coordinates
# axx is the axes object that current draw, you get it from
# axx = fig.gca()

# also import these, to recreate the within env of scatter command 
import matplotlib.markers as mmarkers
import matplotlib.transforms as mtransforms
from matplotlib.collections import PatchCollection
import matplotlib.markers as mmarkers
import matplotlib.patches as mpatches


# define this function
# m is a string of scatter marker, it could be 'o', 's' etc..
# s is the size of the point, use 1.0
# dpi, get it from axx.figure.dpi
def addPatch_point(m, s, dpi):
    marker_obj = mmarkers.MarkerStyle(m)
    path = marker_obj.get_path()
    trans = mtransforms.Affine2D().scale(np.sqrt(s*5)*dpi/72.0)
    ptch = mpatches.PathPatch(path, fill = True, transform = trans)
    return ptch

patches = []
# markerArr is an array of maker string, ['o', 's'. 'o'...]
# sizeArr is an array of size float, [1.0, 1.0. 0.5...]

for m, s in zip(markerArr, sizeArr):
    patches.append(addPatch_point(m, s, axx.figure.dpi))

pclt = PatchCollection(
                patches,
                offsets = zip(X[:,0], X[:,1]),
                transOffset = axx.transData)

pclt.set_transform(mtransforms.IdentityTransform())
pclt.set_edgecolors('none') # it's up to you
pclt._facecolors = rgbaArr

# in the end, when you decide to draw
axx.add_collection(pclt)
# and call axx's parent to draw_idle()

Getting Integer value from a String using javascript/jquery

Is this logically possible??.. I guess the approach that you must take is this way :

Str1 ="test123.00"
Str2 ="yes50.00"

This will be impossible to tackle unless you have delimiter in between test and 123.00

eg: Str1 = "test-123.00" 

Then you can split this way

Str2 = Str1.split("-"); 

This will return you an array of words split with "-"

Then you can do parseFloat(Str2[1]) to get the floating value i.e 123.00

Bootstrap 3: Offset isn't working?

Which version of bootstrap are you using? The early versions of Bootstrap 3 (3.0, 3.0.1) didn't work with this functionality.

col-md-offset-0 should be working as seen in this bootstrap example found here (http://getbootstrap.com/css/#grid-responsive-resets):

<div class="row">
   <div class="col-sm-5 col-md-6">.col-sm-5 .col-md-6</div>
   <div class="col-sm-5 col-sm-offset-2 col-md-6 col-md-offset-0">.col-sm-5 .col-sm-offset-2 .col-md-6 .col-md-offset-0</div>
</div>

XCOPY switch to create specified directory if it doesn't exist?

I tried this on the command.it is working for me.

if "$(OutDir)"=="bin\Debug\"  goto Visual
:TFSBuild
goto exit
:Visual
xcopy /y "$(TargetPath)$(TargetName).dll" "$(ProjectDir)..\Demo"
xcopy /y "$(TargetDir)$(TargetName).pdb" "$(ProjectDir)..\Demo"
goto exit
:exit

Console app arguments, how arguments are passed to Main method

The Main method is the Entry point of your application. If you checkout via ildasm then

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint

This is what helps in calling the method

The arguments are passed as say C:\AppName arg1 arg2 arg3

What is pipe() function in Angular

You have to look to official ReactiveX documentation: https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md.

This is a good article about piping in RxJS: https://blog.hackages.io/rxjs-5-5-piping-all-the-things-9d469d1b3f44.

In short .pipe() allows chaining multiple pipeable operators.

Starting in version 5.5 RxJS has shipped "pipeable operators" and renamed some operators:

do -> tap
catch -> catchError
switch -> switchAll
finally -> finalize

Method has the same erasure as another method in type

The problem is that Set<Integer> and Set<String> are actually treated as a Set from the JVM. Selecting a type for the Set (String or Integer in your case) is only syntactic sugar used by the compiler. The JVM can't distinguish between Set<String> and Set<Integer>.

Best way to find the intersection of multiple sets?

Jean-François Fabre set.intesection(*list_of_sets) answer is definetly the most Pyhtonic and is rightly the accepted answer.

For those that want to use reduce, the following will also work:

reduce(set.intersection, list_of_sets)

Python DNS module import error

In my case, I hava writen the code in the file named "dns.py", it's conflict for the package, I have to rename the script filename.

HTML - How to do a Confirmation popup to a Submit button and then send the request?

Another option that you can use is:

onclick="if(confirm('Do you have sure ?')){}else{return false;};"

using this function on submit button you will get what you expect.

Regex replace uppercase with lowercase letters

You may:

Find: (\w) Replace With: \L$1

Or select the text, ctrl+K+L.

How to increment an iterator by 2?

If you don't know wether you have enough next elements in your container or not, you need to check against the end of your container between each increment. Neither ++ nor std::advance will do it for you.

if( ++iter == collection.end())
  ... // stop

if( ++iter == collection.end())
  ... // stop

You may even roll your own bound-secure advance function.

If you are sure that you will not go past the end, then std::advance( iter, 2 ) is the best solution.

SQL Server: Importing database from .mdf?

To perform this operation see the next images:

enter image description here

and next step is add *.mdf file,

very important, the .mdf file must be located in C:......\MSSQL12.SQLEXPRESS\MSSQL\DATA

enter image description here

Now remove the log file

enter image description here

What does "dereferencing" a pointer mean?

In simple words, dereferencing means accessing the value from a certain memory location against which that pointer is pointing.

Proper way to use **kwargs in Python

**kwargs gives the freedom to add any number of keyword arguments. One may have a list of keys for which he can set default values. But setting default values for an indefinite number of keys seems unnecessary. Finally, it may be important to have the keys as instance attributes. So, I would do this as follows:

class Person(object):
listed_keys = ['name', 'age']

def __init__(self, **kwargs):
    _dict = {}
    # Set default values for listed keys
    for item in self.listed_keys: 
        _dict[item] = 'default'
    # Update the dictionary with all kwargs
    _dict.update(kwargs)

    # Have the keys of kwargs as instance attributes
    self.__dict__.update(_dict)

Remove .php extension with .htaccess

I found 100% working Concept for me:

# Options is required by Many Hosting
Options +MultiViews

RewriteEngine on

# For .php & .html URL's:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
RewriteRule ^([^\.]+)$ $1.html [NC,L]

Use this code in Root of your website .htaccess file like :

offline - wamp\www\YourWebDir

online - public_html/

If it doesn't work correct, then change the settings of your Wamp Server: 1) Left click WAMP icon 2) Apache 3) Apache Modules 4) Left click rewrite_module

Error: "an object reference is required for the non-static field, method or property..."

The error message means that you need to invoke volteado and siprimo on an instance of the Program class. E.g.:

...
Program p = new Program();
long av = p.volteado(a); // av is "a" but swapped

if (p.siprimo(a) == false && p.siprimo(av) == false)
...

They cannot be invoked directly from the Main method because Main is static while volteado and siprimo are not.

The easiest way to fix this is to make the volteado and siprimo methods static:

private static bool siprimo(long a)
{
    ...
}

private static bool volteado(long a)
{
   ...
}

How to do a logical OR operation for integer comparison in shell scripting?

This should work:

#!/bin/bash

if [ "$#" -eq 0 ] || [ "$#" -gt 1 ] ; then
    echo "hello"
fi

I'm not sure if this is different in other shells but if you wish to use <, >, you need to put them inside double parenthesis like so:

if (("$#" > 1))
 ...

How to mute an html5 video player using jQuery

Are you using the default controls boolean attribute on the video tag? If so, I believe all the supporting browsers have mute buttons. If you need to wire it up, set .muted to true on the element in javascript (use .prop for jquery because it's an IDL attribute.) The speaker icon on the volume control is the mute button on chrome,ff, safari, and opera for example

Fill Combobox from database

string query = "SELECT column_name FROM table_name";      //query the database
SqlCommand queryStatus = new SqlCommand(query, myConnection);
sqlDataReader reader = queryStatus.ExecuteReader();                               
            
while (reader.Read())   //loop reader and fill the combobox
{
ComboBox1.Items.Add(reader["column_name"].ToString());
}

Soft keyboard open and close listener in an activity in Android

You can try it:

private void initKeyBoardListener() {
    // ??????????? ???????? ??????????. 
    // Threshold for minimal keyboard height.
    final int MIN_KEYBOARD_HEIGHT_PX = 150;
    // ???? ???????? ?????? view. 
    // Top-level window decor view.
    final View decorView = getWindow().getDecorView();
    // ???????????? ?????????? ?????????. Register global layout listener.
    decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        // ??????? ????????????? ?????? ????. 
        // Retrieve visible rectangle inside window.
        private final Rect windowVisibleDisplayFrame = new Rect();
        private int lastVisibleDecorViewHeight;

        @Override
        public void onGlobalLayout() {
            decorView.getWindowVisibleDisplayFrame(windowVisibleDisplayFrame);
            final int visibleDecorViewHeight = windowVisibleDisplayFrame.height();

            if (lastVisibleDecorViewHeight != 0) {
                if (lastVisibleDecorViewHeight > visibleDecorViewHeight + MIN_KEYBOARD_HEIGHT_PX) {
                    Log.d("Pasha", "SHOW");
                } else if (lastVisibleDecorViewHeight + MIN_KEYBOARD_HEIGHT_PX < visibleDecorViewHeight) {
                    Log.d("Pasha", "HIDE");
                }
            }
            // ????????? ??????? ?????? view ?? ?????????? ??????.
            // Save current decor view height for the next call.
            lastVisibleDecorViewHeight = visibleDecorViewHeight;
        }
    });
}

Getting around the Max String size in a vba function?

I may have missed something here, but why can't you just declare your string with the desired size? For example, in my VBA code I often use something like:

Dim AString As String * 1024

which provides for a 1k string. Obviously, you can use whatever declaration you like within the larger limits of Excel and available memory etc.

This may be a little inefficient in some cases, and you will probably wish to use Trim(AString) like constructs to obviate any superfluous trailing blanks. Still, it easily exceeds 256 chars.

How to make this Header/Content/Footer layout using CSS?

Try This

<!DOCTYPE html>

<html>

<head>

<title>Sticky Header and Footer</title>

<style type="text/css">

/* Reset body padding and margins */

body {
    margin:0;

    padding:0;
}

/* Make Header Sticky */

#header_container {

    background:#eee;

    border:1px solid #666;

    height:60px;

    left:0;

    position:fixed;

    width:100%;

    top:0;
}

#header {

    line-height:60px;

    margin:0 auto;

    width:940px;

    text-align:center;
}

/* CSS for the content of page. I am giving top and bottom padding of 80px to make sure the header and footer do not overlap the content.*/

#container {

    margin:0 auto;

    overflow:auto;

    padding:80px 0;

    width:940px;

}

#content {

}

/* Make Footer Sticky */

#footer_container {

    background:#eee;

    border:1px solid #666;

    bottom:0;

    height:60px;

    left:0;

    position:fixed;

    width:100%;
}

#footer {

    line-height:60px;

    margin:0 auto;

    width:940px;

    text-align:center;

}

</style>

</head>

<body>

<!-- BEGIN: Sticky Header -->
<div id="header_container">

    <div id="header">
        Header Content
    </div>

</div>
<!-- END: Sticky Header -->

<!-- BEGIN: Page Content -->
<div id="container">

    <div id="content">

            content
        <br /><br />
            blah blah blah..
        ...
    </div>

</div>
<!-- END: Page Content -->

<!-- BEGIN: Sticky Footer -->
<div id="footer_container">

    <div id="footer">

        Footer Content

    </div>

</div>

<!-- END: Sticky Footer -->

</body>

</html>

How to get file_get_contents() to work with HTTPS?

I was stuck with non functional https on IIS. Solved with:

file_get_contents('https.. ) wouldn't load.

  • download https://curl.haxx.se/docs/caextract.html
  • install under ..phpN.N/extras/ssl
  • edit php.ini with:

    curl.cainfo = "C:\Program Files\PHP\v7.3\extras\ssl\cacert.pem" openssl.cafile="C:\Program Files\PHP\v7.3\extras\ssl\cacert.pem"

finally!

SQL Server principal "dbo" does not exist,

Go to the Properties - Files. The owner name must be blank. Just put "sa" in the user name and the issue will be resolved.

Auto Increment after delete in MySQL

here is a function that fix your problem

    public static void fixID(Connection conn, String table) {

    try {
        Statement myStmt = conn.createStatement();
        ResultSet myRs;
        int i = 1, id = 1, n = 0;
        boolean b;
        String sql;

        myRs = myStmt.executeQuery("select max(id) from " + table);
        if (myRs.next()) {
            n = myRs.getInt(1);
        }
        while (i <= n) {
            b = false;
            myRs = null;
            while (!b) {
                myRs = myStmt.executeQuery("select id from " + table + " where id=" + id);
                if (!myRs.next()) {
                    id++;
                } else {
                    b = true;
                }
            }

            sql = "UPDATE " + table + " set id =" + i + " WHERE id=" + id;
            myStmt.execute(sql);
            i++;
            id++;
        }

    } catch (SQLException e) {
        e.printStackTrace();
    }
}

Using Environment Variables with Vue.js

In addition to the previous answers, if you're looking to access VUE_APP_* env variables in your sass (either the sass section of a vue component or a scss file), then you can add the following to your vue.config.js (which you may need to create if you don't have one):

let sav = "";
for (let e in process.env) {
    if (/VUE_APP_/i.test(e)) {
        sav += `$${e}: "${process.env[e]}";`;
    }
}

module.exports = {
    css: {
        loaderOptions: {
            sass: {
                data: sav,
            },
        },
    },
}

The string sav seems to be prepended to every sass file that before processing, which is fine for variables. You could also import mixins at this stage to make them available for the sass section of each vue component.

You can then use these variables in your sass section of a vue file:

<style lang="scss">
.MyDiv {
    margin: 1em 0 0 0;
    background-image: url($VUE_APP_CDN+"/MyImg.png");
}
</style>

or in a .scss file:

.MyDiv {
    margin: 1em 0 0 0;
    background-image: url($VUE_APP_CDN+"/MyImg.png");
}

from https://www.matt-helps.com/post/expose-env-variables-vue-cli-sass/

Undefined reference to `sin`

You need to link with the math library, libm:

$ gcc -Wall foo.c -o foo -lm 

Nested objects in javascript, best practices

var defaultsettings = {
    ajaxsettings: {
        ...
    },
    uisettings: {
        ...
    }
};

How can I get the number of records affected by a stored procedure?

@@RowCount will give you the number of records affected by a SQL Statement.

The @@RowCount works only if you issue it immediately afterwards. So if you are trapping errors, you have to do it on the same line. If you split it up, you will miss out on whichever one you put second.

SELECT @NumRowsChanged = @@ROWCOUNT, @ErrorCode = @@ERROR

If you have multiple statements, you will have to capture the number of rows affected for each one and add them up.

SELECT @NumRowsChanged = @NumRowsChanged  + @@ROWCOUNT, @ErrorCode = @@ERROR

nginx missing sites-available directory

I tried sudo apt install nginx-full. You will get all the required packages.

How to tell if a string contains a certain character in JavaScript?

String's search function is useful too. It searches for a character as well as a sub_string in a given string.

'apple'.search('pl') returns 2

'apple'.search('x') return -1

Python - Create list with numbers between 2 values?

Try:

range(x1,x2+1)  

That is a list in Python 2.x and behaves mostly like a list in Python 3.x. If you are running Python 3 and need a list that you can modify, then use:

list(range(x1,x2+1))

How to check if multiple array keys exists

The above solutions are clever, but very slow. A simple foreach loop with isset is more than twice as fast as the array_intersect_key solution.

function array_keys_exist($keys, $array){
    foreach($keys as $key){
        if(!array_key_exists($key, $array))return false;
    }
    return true;
}

(344ms vs 768ms for 1000000 iterations)

The representation of if-elseif-else in EL using JSF

You can use "ELSE IF" using conditional operator in expression language as below:

 <p:outputLabel value="#{transaction.status.equals('PNDNG')?'Pending':
                                     transaction.status.equals('RJCTD')?'Rejected':
                                     transaction.status.equals('CNFRMD')?'Confirmed':
                                     transaction.status.equals('PSTD')?'Posted':''}"/>

Limit length of characters in a regular expression?

Limit the length of characters in a regular expression? ^[a-z]{6,15}$'

Limit length of characters or Numbers in a regular expression? ^[a-z | 0-9]{6,15}$'

jQuery Validate Plugin - How to create a simple custom rule?

Thanks, it worked!

Here's the final code:

$.validator.addMethod("greaterThanZero", function(value, element) {
    var the_list_array = $("#some_form .super_item:checked");
    return the_list_array.length > 0;
}, "* Please check at least one check box");

What datatype should be used for storing phone numbers in SQL Server 2005?

Use CHAR(10) if you are storing US Phone numbers only. Remove everything but the digits.

open cv error: (-215) scn == 3 || scn == 4 in function cvtColor

This code for those who are experiencing the same problem trying to accessing the camera could be written with a safety check.

if ret is True:
   gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
else:
   continue

OR in case you want to close the camera/ discontinue if there will be some problem with the frame itself

if ret is True:
   gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
else:
   break

For reference https://github.com/HackerShackOfficial/AI-Smart-Mirror/issues/36

I can't install intel HAXM

Note: this is not an answer because I could not find a solution. But I think the information may be useful for others (and it wouldn't be practical as a comment). I have tried all of the steps detailed in the various docs but I could not get Android Emulator to work on my AMD Ryzen 7 :(


Most answers work only for Intel CPUs. If you have an AMD CPU (like me, an AMD Ryzen 7) you need to know about some restrictions and you have to use WHPX instead of HAXM.

I found this on MS's site: Because the Android emulator currently supports AMD hardware acceleration only on Linux, hardware acceleration is not available for AMD-based computers running Windows.

Fortunatelly there is a way to make it work but configuring hardware acceleration for an AMD CPU is a bit more complex:

Requirements and recommendations: - AMD CPU recommendation: AMD Ryzen CPU - Android Studio 3.2 Beta 1 or higher - Android Emulator version 27.3.8 or higher - Windows 10 with April 2018 Update or higher

To use WHPX acceleration on Windows, you must enable the Windows Hypervisor Platform option in the Turn Windows features on or off dialog box. For changes to this option to take effect, restart your computer.

Additionally, the following changes must be made in the BIOS settings: - AMD CPU: Virtualization or SVM must be enabled.

Note that there are further restrictions as well:

  • You can't run a VM-accelerated emulator inside another VM, such as a VM hosted by VirtualBox, VMWare, or Docker. You must run the emulator directly on your system hardware.
  • You can't run software that uses another virtualization technology at the same time that you run the accelerated emulator. For example, VirtualBox, VMWare, and Docker currently use a different virtualization technology, so you can't run them at the same time as the accelerated emulator.

Some more info: Android Emulator - AMD Processor & Hyper-V Support

This recommendation did not help either:

Please note: More recent versions of the emulator (27.2.8, 27.3.0, or later), require an emulator flag while the feature is in the preview. To do this, create or edit the file C:\Users\.android\advancedFeatures.ini and add the line “WindowsHypervisorPlatform = on”, or start the emulator from the command line with “-feature WindowsHypervisorPlatform”.

Query for array elements inside JSON type

Create a table with column as type json

CREATE TABLE friends ( id serial primary key, data jsonb);

Now let's insert json data

INSERT INTO friends(data) VALUES ('{"name": "Arya", "work": ["Improvements", "Office"], "available": true}');
INSERT INTO friends(data) VALUES ('{"name": "Tim Cook", "work": ["Cook", "ceo", "Play"], "uses": ["baseball", "laptop"], "available": false}');

Now let's make some queries to fetch data

select data->'name' from friends;
select data->'name' as name, data->'work' as work from friends;

You might have noticed that the results comes with inverted comma( " ) and brackets ([ ])

    name    |            work            
------------+----------------------------
 "Arya"     | ["Improvements", "Office"]
 "Tim Cook" | ["Cook", "ceo", "Play"]
(2 rows)

Now to retrieve only the values just use ->>

select data->>'name' as name, data->'work'->>0 as work from friends;
select data->>'name' as name, data->'work'->>0 as work from friends where data->>'name'='Arya';

jQuery serialize does not register checkboxes

Just to expand on the answer(s) above, in my case, I required sending a yes/no against a single ID serialized to my backend catch.

I set the checkbox elements to contain the ID of a particular database column, aka (default checked):

(Laravel Blade)

<div class="checkbox">
    <label>
        <input type="checkbox" value="{{ $heading->id }}" checked> {{ $heading->name }}
    </label>
</div>

When I did my submission, I grabbed the data with:

(jQuery)

let form = $('#formID input[type="checkbox"]').map(function() {
                return { id: this.value, value: this.checked ? 1 : 0 };
           }).get();

var data = JSON.stringify(form);
$.post( "/your/endpoint", data );

Easiest way to pass an AngularJS scope variable from directive to controller?

Wait until angular has evaluated the variable

I had a lot of fiddling around with this, and couldn't get it to work even with the variable defined with "=" in the scope. Here's three solutions depending on your situation.


Solution #1


I found that the variable was not evaluated by angular yet when it was passed to the directive. This means that you can access it and use it in the template, but not inside the link or app controller function unless we wait for it to be evaluated.

If your variable is changing, or is fetched through a request, you should use $observe or $watch:

app.directive('yourDirective', function () {
    return {
        restrict: 'A',
        // NB: no isolated scope!!
        link: function (scope, element, attrs) {
            // observe changes in attribute - could also be scope.$watch
            attrs.$observe('yourDirective', function (value) {
                if (value) {
                    console.log(value);
                    // pass value to app controller
                    scope.variable = value;
                }
            });
        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: ['$scope', '$element', '$attrs',
            function ($scope, $element, $attrs) {
                // observe changes in attribute - could also be scope.$watch
                $attrs.$observe('yourDirective', function (value) {
                    if (value) {
                        console.log(value);
                        // pass value to app controller
                        $scope.variable = value;
                    }
                });
            }
        ]
    };
})
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$watch('variable', function (value) {
        if (value) {
            console.log(value);
        }
    });
}]);

And here's the html (remember the brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="{{ someObject.someVariable }}"></div>
    <!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

Note that you should not set the variable to "=" in the scope, if you are using the $observe function. Also, I found that it passes objects as strings, so if you're passing objects use solution #2 or scope.$watch(attrs.yourDirective, fn) (, or #3 if your variable is not changing).


Solution #2


If your variable is created in e.g. another controller, but just need to wait until angular has evaluated it before sending it to the app controller, we can use $timeout to wait until the $apply has run. Also we need to use $emit to send it to the parent scope app controller (due to the isolated scope in the directive):

app.directive('yourDirective', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        // NB: isolated scope!!
        scope: {
            yourDirective: '='
        },
        link: function (scope, element, attrs) {
            // wait until after $apply
            $timeout(function(){
                console.log(scope.yourDirective);
                // use scope.$emit to pass it to controller
                scope.$emit('notification', scope.yourDirective);
            });
        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: [ '$scope', function ($scope) {
            // wait until after $apply
            $timeout(function(){
                console.log($scope.yourDirective);
                // use $scope.$emit to pass it to controller
                $scope.$emit('notification', scope.yourDirective);
            });
        }]
    };
}])
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$on('notification', function (evt, value) {
        console.log(value);
        $scope.variable = value;
    });
}]);

And here's the html (no brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="someObject.someVariable"></div>
    <!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

Solution #3


If your variable is not changing and you need to evaluate it in your directive, you can use the $eval function:

app.directive('yourDirective', function () {
    return {
        restrict: 'A',
        // NB: no isolated scope!!
        link: function (scope, element, attrs) {
            // executes the expression on the current scope returning the result
            // and adds it to the scope
            scope.variable = scope.$eval(attrs.yourDirective);
            console.log(scope.variable);

        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: ['$scope', '$element', '$attrs',
            function ($scope, $element, $attrs) {
                // executes the expression on the current scope returning the result
                // and adds it to the scope
                scope.variable = scope.$eval($attrs.yourDirective);
                console.log($scope.variable);
            }
         ]
    };
})
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$watch('variable', function (value) {
        if (value) {
            console.log(value);
        }
    });
}]);

And here's the html (remember the brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="{{ someObject.someVariable }}"></div>
    <!-- use ng-bind instead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

Also, have a look at this answer: https://stackoverflow.com/a/12372494/1008519

Reference for FOUC (flash of unstyled content) issue: http://deansofer.com/posts/view/14/AngularJs-Tips-and-Tricks-UPDATED

For the interested: here's an article on the angular life cycle

Using HttpClient and HttpPost in Android with post parameters

I've just checked and i have the same code as you and it works perferctly. The only difference is how i fill my List for the params :

I use a : ArrayList<BasicNameValuePair> params

and fill it this way :

 params.add(new BasicNameValuePair("apikey", apikey);

I do not use any JSONObject to send params to the webservices.

Are you obliged to use the JSONObject ?

Using Jquery Datatable with AngularJs

Adding a new answer just as a reference for future researchers and as nobody mentioned that yet I think it's valid.

Another good option is ng-grid http://angular-ui.github.io/ng-grid/.

And there's a beta version (http://ui-grid.info/) available already with some improvements:

  • Native AngularJS implementation, no jQuery
  • Performs well with large data sets; even 10,000+ rows
  • Plugin architecture allows you to use only the features you need

UPDATE:

It seems UI GRID is not beta anymore.

With the 3.0 release, the repository has been renamed from "ng-grid" to "ui-grid".

how to sort an ArrayList in ascending order using Collections and Comparator

Two ways to get this done:

Collections.sort(myArray)

given elements inside myArray implements Comparable

Second

Collections.sort(myArray, new MyArrayElementComparator());

where MyArrayElementComparator is Comparator for elements inside myArray

CustomErrors mode="Off"

Make sure you add right after the system.web

I put it toward the end of the node and didn't work.

Is it possible to have a multi-line comments in R?

if(FALSE) {
...
}

precludes multiple lines from being executed. However, these lines still have to be syntactically correct, i.e., can't be comments in the proper sense. Still helpful for some cases though.

Search and replace a line in a file in Python

Based on the answer by Thomas Watnedal. However, this does not answer the line-to-line part of the original question exactly. The function can still replace on a line-to-line basis

This implementation replaces the file contents without using temporary files, as a consequence file permissions remain unchanged.

Also re.sub instead of replace, allows regex replacement instead of plain text replacement only.

Reading the file as a single string instead of line by line allows for multiline match and replacement.

import re

def replace(file, pattern, subst):
    # Read contents from file as a single string
    file_handle = open(file, 'r')
    file_string = file_handle.read()
    file_handle.close()

    # Use RE package to allow for replacement (also allowing for (multiline) REGEX)
    file_string = (re.sub(pattern, subst, file_string))

    # Write contents to file.
    # Using mode 'w' truncates the file.
    file_handle = open(file, 'w')
    file_handle.write(file_string)
    file_handle.close()

urllib2.HTTPError: HTTP Error 403: Forbidden

This will work in Python 3

import urllib.request

user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'

url = "http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers"
headers={'User-Agent':user_agent,} 

request=urllib.request.Request(url,None,headers) #The assembled request
response = urllib.request.urlopen(request)
data = response.read() # The data u need

How to extract the nth word and count word occurrences in a MySQL string?

The field's value is:

 "- DE-HEB 20% - DTopTen 1.2%"
SELECT ....
SUBSTRING_INDEX(SUBSTRING_INDEX(DesctosAplicados, 'DE-HEB ',  -1), '-', 1) DE-HEB ,
SUBSTRING_INDEX(SUBSTRING_INDEX(DesctosAplicados, 'DTopTen ',  -1), '-', 1) DTopTen ,

FROM TABLA 

Result is:

  DE-HEB       DTopTEn
    20%          1.2%

HTTP get with headers using RestTemplate

The RestTemplate getForObject() method does not support setting headers. The solution is to use the exchange() method.

So instead of restTemplate.getForObject(url, String.class, param) (which has no headers), use

HttpHeaders headers = new HttpHeaders();
headers.set("Header", "value");
headers.set("Other-Header", "othervalue");
...

HttpEntity entity = new HttpEntity(headers);

ResponseEntity<String> response = restTemplate.exchange(
    url, HttpMethod.GET, entity, String.class, param);

Finally, use response.getBody() to get your result.

This question is similar to this question.

Convert a Map<String, String> to a POJO

@Hamedz if use many data, use Jackson to convert light data, use apache... TestCase:

import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; import org.apache.commons.beanutils.BeanUtils; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; public class TestPerf { public static final int LOOP_MAX_COUNT = 1000; public static void main(String[] args) { Map<String, Object> map = new HashMap<>(); map.put("success", true); map.put("number", 1000); map.put("longer", 1000L); map.put("doubler", 1000D); map.put("data1", "testString"); map.put("data2", "testString"); map.put("data3", "testString"); map.put("data4", "testString"); map.put("data5", "testString"); map.put("data6", "testString"); map.put("data7", "testString"); map.put("data8", "testString"); map.put("data9", "testString"); map.put("data10", "testString"); runBeanUtilsPopulate(map); runJacksonMapper(map); } private static void runBeanUtilsPopulate(Map<String, Object> map) { long t1 = System.currentTimeMillis(); for (int i = 0; i < LOOP_MAX_COUNT; i++) { try { TestClass bean = new TestClass(); BeanUtils.populate(bean, map); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } long t2 = System.currentTimeMillis(); System.out.println("BeanUtils t2-t1 = " + String.valueOf(t2 - t1)); } private static void runJacksonMapper(Map<String, Object> map) { long t1 = System.currentTimeMillis(); for (int i = 0; i < LOOP_MAX_COUNT; i++) { ObjectMapper mapper = new ObjectMapper(); TestClass testClass = mapper.convertValue(map, TestClass.class); } long t2 = System.currentTimeMillis(); System.out.println("Jackson t2-t1 = " + String.valueOf(t2 - t1)); } @Data @AllArgsConstructor @NoArgsConstructor public static class TestClass { private Boolean success; private Integer number; private Long longer; private Double doubler; private String data1; private String data2; private String data3; private String data4; private String data5; private String data6; private String data7; private String data8; private String data9; private String data10; } }

Inverse dictionary lookup in Python

Make a reverse dictionary

reverse_dictionary = {v:k for k,v in dictionary.items()} 

If you have a lot of reverse lookups to do

How to POST raw whole JSON in the body of a Retrofit request?

I wanted to compare speed of volley and retrofit for sending and receiving data I wrote below code (for retrofit part)

first dependency:

dependencies {
     implementation 'com.squareup.retrofit2:retrofit:2.4.0'
     implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
}

Then interface:

 public interface IHttpRequest {

    String BaseUrl="https://example.com/api/";

    @POST("NewContract")
    Call<JsonElement> register(@Body HashMap registerApiPayload);
}

and a function to set parameters to post data to server(In MainActivity):

private void Retrofit(){

    Retrofit retrofitRequest = new Retrofit.Builder()
            .baseUrl(IHttpRequest.BaseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    // set data to send
    HashMap<String,String> SendData =new HashMap<>();
    SendData.put("token","XYXIUNJHJHJHGJHGJHGRTYTRY");
    SendData.put("contract_type","0");
    SendData.put("StopLess","37000");
    SendData.put("StopProfit","48000");

    final IHttpRequest request=retrofitRequest.create(IHttpRequest.class);

    request.register(SendData).enqueue(new Callback<JsonElement>() {
        @Override
        public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
            if (response.isSuccessful()){
                Toast.makeText(getApplicationContext(),response.body().toString(),Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onFailure(Call<JsonElement> call, Throwable t) {

        }
    });

}

And I found Retrofit faster than volley in my case.

Forms authentication timeout vs sessionState timeout

The difference is that one (Forms timeout) has to do with authenticating the user and the other (Session timeout) has to do with how long cached data is stored on the server. So they are very independent things, so one does not take precedence over the other.

Bootstrap 4 Change Hamburger Toggler Color

If you work with sass version of bootstrap in _variables.scss you can find $navbar-inverse-toggler-bg or $navbar-light-toggler-bg where you can change the color and style of your toggle button.

In html you have to use navbar-inverse or navbar-light depending on which version you want to use.

How to draw a rounded Rectangle on HTML Canvas?

I needed to do the same thing and created a method to do it.

_x000D_
_x000D_
// Now you can just call
var ctx = document.getElementById("rounded-rect").getContext("2d");
// Draw using default border radius, 
// stroke it but no fill (function's default values)
roundRect(ctx, 5, 5, 50, 50);
// To change the color on the rectangle, just manipulate the context
ctx.strokeStyle = "rgb(255, 0, 0)";
ctx.fillStyle = "rgba(255, 255, 0, .5)";
roundRect(ctx, 100, 5, 100, 100, 20, true);
// Manipulate it again
ctx.strokeStyle = "#0f0";
ctx.fillStyle = "#ddd";
// Different radii for each corner, others default to 0
roundRect(ctx, 300, 5, 200, 100, {
  tl: 50,
  br: 25
}, true);

/**
 * Draws a rounded rectangle using the current state of the canvas.
 * If you omit the last three params, it will draw a rectangle
 * outline with a 5 pixel border radius
 * @param {CanvasRenderingContext2D} ctx
 * @param {Number} x The top left x coordinate
 * @param {Number} y The top left y coordinate
 * @param {Number} width The width of the rectangle
 * @param {Number} height The height of the rectangle
 * @param {Number} [radius = 5] The corner radius; It can also be an object 
 *                 to specify different radii for corners
 * @param {Number} [radius.tl = 0] Top left
 * @param {Number} [radius.tr = 0] Top right
 * @param {Number} [radius.br = 0] Bottom right
 * @param {Number} [radius.bl = 0] Bottom left
 * @param {Boolean} [fill = false] Whether to fill the rectangle.
 * @param {Boolean} [stroke = true] Whether to stroke the rectangle.
 */
function roundRect(ctx, x, y, width, height, radius, fill, stroke) {
  if (typeof stroke === 'undefined') {
    stroke = true;
  }
  if (typeof radius === 'undefined') {
    radius = 5;
  }
  if (typeof radius === 'number') {
    radius = {tl: radius, tr: radius, br: radius, bl: radius};
  } else {
    var defaultRadius = {tl: 0, tr: 0, br: 0, bl: 0};
    for (var side in defaultRadius) {
      radius[side] = radius[side] || defaultRadius[side];
    }
  }
  ctx.beginPath();
  ctx.moveTo(x + radius.tl, y);
  ctx.lineTo(x + width - radius.tr, y);
  ctx.quadraticCurveTo(x + width, y, x + width, y + radius.tr);
  ctx.lineTo(x + width, y + height - radius.br);
  ctx.quadraticCurveTo(x + width, y + height, x + width - radius.br, y + height);
  ctx.lineTo(x + radius.bl, y + height);
  ctx.quadraticCurveTo(x, y + height, x, y + height - radius.bl);
  ctx.lineTo(x, y + radius.tl);
  ctx.quadraticCurveTo(x, y, x + radius.tl, y);
  ctx.closePath();
  if (fill) {
    ctx.fill();
  }
  if (stroke) {
    ctx.stroke();
  }

}
_x000D_
<canvas id="rounded-rect" width="500" height="200">
  <!-- Insert fallback content here -->
</canvas>
_x000D_
_x000D_
_x000D_

Where is my m2 folder on Mac OS X Mavericks

It's in your home folder but it's hidden by default.

Typing the below commands in the terminal made it visible for me (only the .m2 folder that is, not all the other hidden folders).

> mv ~/.m2 ~/m2
> ln -s ~/m2 ~/.m2         

Source

Div Background Image Z-Index Issue

Set your header and footer position to "absolute" and that should do the trick. Hope it helps and good luck with your project!

PDO get the last ID inserted

That's because that's an SQL function, not PHP. You can use PDO::lastInsertId().

Like:

$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();

If you want to do it with SQL instead of the PDO API, you would do it like a normal select query:

$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetchColumn();

How do I quickly rename a MySQL database (change schema name)?

For your convenience, below is a small shellscript that has to be executed with two parameters: db-name and new db-name.

You might need to add login-parameters to the mysql-lines if you don't use the .my.cnf-file in your home-directory. Please make a backup before executing this script.


#!/usr/bin/env bash

mysql -e "CREATE DATABASE $2 DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;"
for i in $(mysql -Ns $1 -e "show tables");do
    echo "$1.$i -> $2.$i"
    mysql -e "rename TABLE $1.$i to $2.$i"
done
mysql -e "DROP DATABASE $1"

How to uninstall Jenkins?

Keep in mind, that in Terminal you need to add backslash before space, so the proper copy/paste will be

/Library/Application\ Support/Jenkins/Uninstall.command

p.s. sorry for the late answer :)

How to assign multiple classes to an HTML container?

you need to put a dot between the class like

class="column.wrapper">

Why do we need to install gulp globally and locally?

When installing a tool globally it's to be used by a user as a command line utility anywhere, including outside of node projects. Global installs for a node project are bad because they make deployment more difficult.

npm 5.2+

The npx utility bundled with npm 5.2 solves this problem. With it you can invoke locally installed utilities like globally installed utilities (but you must begin the command with npx). For example, if you want to invoke a locally installed eslint, you can do:

npx eslint .

npm < 5.2

When used in a script field of your package.json, npm searches node_modules for the tool as well as globally installed modules, so the local install is sufficient.

So, if you are happy with (in your package.json):

"devDependencies": {
    "gulp": "3.5.2"
}
"scripts": {
    "test": "gulp test"
}

etc. and running with npm run test then you shouldn't need the global install at all.

Both methods are useful for getting people set up with your project since sudo isn't needed. It also means that gulp will be updated when the version is bumped in the package.json, so everyone will be using the same version of gulp when developing with your project.

Addendum:

It appears that gulp has some unusual behaviour when used globally. When used as a global install, gulp looks for a locally installed gulp to pass control to. Therefore a gulp global install requires a gulp local install to work. The answer above still stands though. Local installs are always preferable to global installs.

How to check if PHP array is associative or sequential?

As stated by the OP:

PHP treats all arrays as associative

it is not quite sensible (IMHO) to write a function that checks if an array is associative. So first thing first: what is a key in a PHP array?:

The key can either be an integer or a string.

That means there are 3 possible cases:

  • Case 1. all keys are numeric / integers.
  • Case 2. all keys are strings.
  • Case 3. some keys are strings, some keys are numeric / integers.

We can check each case with the following functions.

Case 1: all keys are numeric / integers.

Note: This function returns true for empty arrays too.

//! Check whether the input is an array whose keys are all integers.
/*!
    \param[in] $InputArray          (array) Input array.
    \return                         (bool) \b true iff the input is an array whose keys are all integers.
*/
function IsArrayAllKeyInt($InputArray)
{
    if(!is_array($InputArray))
    {
        return false;
    }

    if(count($InputArray) <= 0)
    {
        return true;
    }

    return array_unique(array_map("is_int", array_keys($InputArray))) === array(true);
}

Case 2: all keys are strings.

Note: This function returns true for empty arrays too.

//! Check whether the input is an array whose keys are all strings.
/*!
    \param[in] $InputArray          (array) Input array.
    \return                         (bool) \b true iff the input is an array whose keys are all strings.
*/
function IsArrayAllKeyString($InputArray)
{
    if(!is_array($InputArray))
    {
        return false;
    }

    if(count($InputArray) <= 0)
    {
        return true;
    }

    return array_unique(array_map("is_string", array_keys($InputArray))) === array(true);
}

Case 3. some keys are strings, some keys are numeric / integers.

Note: This function returns true for empty arrays too.

//! Check whether the input is an array with at least one key being an integer and at least one key being a string.
/*!
    \param[in] $InputArray          (array) Input array.
    \return                         (bool) \b true iff the input is an array with at least one key being an integer and at least one key being a string.
*/
function IsArraySomeKeyIntAndSomeKeyString($InputArray)
{
    if(!is_array($InputArray))
    {
        return false;
    }

    if(count($InputArray) <= 0)
    {
        return true;
    }

    return count(array_unique(array_map("is_string", array_keys($InputArray)))) >= 2;
}

It follows that:


Now, for an array to be a "genuine" array that we are all accustomed to, meaning:

  • Its keys are all numeric / integers.
  • Its keys are sequential (i.e. increasing by step 1).
  • Its keys start from zero.

We can check with the following function.

Case 3a. keys are numeric / integers, sequential, and zero-based.

Note: This function returns true for empty arrays too.

//! Check whether the input is an array whose keys are numeric, sequential, and zero-based.
/*!
    \param[in] $InputArray          (array) Input array.
    \return                         (bool) \b true iff the input is an array whose keys are numeric, sequential, and zero-based.
*/
function IsArrayKeyNumericSequentialZeroBased($InputArray)
{
    if(!is_array($InputArray))
    {
        return false;
    }

    if(count($InputArray) <= 0)
    {
        return true;
    }

    return array_keys($InputArray) === range(0, count($InputArray) - 1);
}

Caveats / Pitfalls (or, even more peculiar facts about array keys in PHP)

Integer keys

The keys for these arrays are integers:

array(0 => "b");
array(13 => "b");
array(-13 => "b");          // Negative integers are also integers.
array(0x1A => "b");         // Hexadecimal notation.

String keys

The keys for these arrays are strings:

array("fish and chips" => "b");
array("" => "b");                                   // An empty string is also a string.
array("[email protected]" => "b");    // Strings may contain non-alphanumeric characters.
array("stack\t\"over\"\r\nflow's cool" => "b");     // Strings may contain special characters.
array('$ta€k?øv?rflöw?' => "b");                    // Strings may contain all kinds of symbols.
array("funct?on" => "b");                           // You think this looks fine? Think again! (see https://stackoverflow.com/q/9246051/1402846)
array("?????L" => "b");                         // How about Japanese/Korean/Chinese/Russian/Polish?
array("fi\x0sh" => "b");                            // Strings may contain null characters.
array(file_get_contents("https://www.google.com/images/nav_logo114.png") => "b");   // Strings may even be binary!

Integer keys that look like strings

If you think the key in array("13" => "b") is a string, you are wrong. From the doc here:

Strings containing valid integers will be cast to the integer type. E.g. the key "8" will actually be stored under 8. On the other hand "08" will not be cast, as it isn't a valid decimal integer.

For example, the key for these arrays are integers:

array("13" => "b");
array("-13" => "b");                        // Negative, ok.

But the key for these arrays are strings:

array("13." => "b");
array("+13" => "b");                        // Positive, not ok.
array("-013" => "b");
array("0x1A" => "b");                       // Not converted to integers even though it's a valid hexadecimal number.
array("013" => "b");                        // Not converted to integers even though it's a valid octal number.
array("18446744073709551616" => "b");       // Not converted to integers as it can't fit into a 64-bit integer.

What's more, according to the doc,

The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18, except for Windows, which is always 32 bit. PHP does not support unsigned integers.

So the key for this array may or may not be an integer - it depends on your platform.

array("60000000000" => "b");                // Array key could be integer or string, it can fit into a 64-bit (but not 32-bit) integer.

Even worse, PHP tends to be buggy if the integer is near the 231 = 2,147,483,648 boundary (see bug 51430, bug 52899). For example, on my local environment (PHP 5.3.8 on XAMPP 1.7.7 on Windows 7), var_dump(array("2147483647" => "b")) gives

array(1) {
    [2147483647]=>
    string(1) "b"
}   

but on this live demo on codepad (PHP 5.2.5), the same expression gives

array(1) {
    ["2147483647"]=>
    string(1) "b"
}

So the key is an integer in one environment but a string in another, even though 2147483647 is a valid signed 32-bit integer.

javascript return true or return false when and how to use it?

Your code makes no sense, maybe because it's out of context.

If you mean code like this:

$('a').click(function () {
    callFunction();
    return false;
});

The return false will return false to the click-event. That tells the browser to stop following events, like follow a link. It has nothing to do with the previous function call. Javascript runs from top to bottom more or less, so a line cannot affect a previous line.

Return outside function error in Python

You have a return statement that isn't in a function. Functions are started by the def keyword:

def function(argument):
    return "something"

print function("foo")  #prints "something"

return has no meaning outside of a function, and so python raises an error.

Type List vs type ArrayList in Java

When you write List, you actually tell, that your object implements List interface only, but you don't specify what class your object belongs to.

When you write ArrayList, you specify that your object class is a resizable-array.

So, the first version makes your code more flexible in future.

Look at Java docs:

Class ArrayList - Resizable-array implementation of the List interface.

Interface List - An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted.

Array - container object that holds a fixed number of values of a single type.

Regex for parsing directory and filename

What language? and why use regex for this simple task?

If you must:

^(.*)/([^/]*)$

gives you the two parts you wanted. You might need to quote the parentheses:

^\(.*\)/\([^/]*\)$

depending on your preferred language syntax.

But I suggest you just use your language's string search function that finds the last "/" character, and split the string on that index.

AngularJS passing data to $http.get request

You can even simply add the parameters to the end of the url:

$http.get('path/to/script.php?param=hello').success(function(data) {
    alert(data);
});

Paired with script.php:

<? var_dump($_GET); ?>

Resulting in the following javascript alert:

array(1) {  
    ["param"]=>  
    string(4) "hello"
}

Javascript Array.sort implementation?

The ECMAscript standard does not specify which sort algorithm is to be used. Indeed, different browsers feature different sort algorithms. For example, Mozilla/Firefox's sort() is not stable (in the sorting sense of the word) when sorting a map. IE's sort() is stable.

FileNotFoundError: [Errno 2] No such file or directory

Lets say we have a script in "c:\script.py" that contain :

result = open("index.html","r")
print(result.read())

Lets say that the index.html file is also in the same directory "c:\index.html" when i execute the script from cmd (or shell)

C:\Users\Amine>python c:\script.py

You will get error:

FileNotFoundError: [Errno 2] No such file or directory: 'index.html'

And that because "index.html" is not in working directory which is "C:\Users\Amine>". so in order to make it work you have to change the working directory

C:\python script.py

'<html><head></head><body></body></html>'

This is why is it preferable to use absolute path.

How to set a header in an HTTP response?

First of all you have to understand the nature of

response.sendRedirect(newUrl);

It is giving the client (browser) 302 http code response with an URL. The browser then makes a separate GET request on that URL. And that request has no knowledge of headers in the first one.

So sendRedirect won't work if you need to pass a header from Servlet A to Servlet B.

If you want this code to work - use RequestDispatcher in Servlet A (instead of sendRedirect). Also, it is always better to use relative path.

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
    String userName=request.getParameter("userName");
    String newUrl = "ServletB";
    response.addHeader("REMOTE_USER", userName);
    RequestDispatcher view = request.getRequestDispatcher(newUrl);
    view.forward(request, response);
}

========================

public void doPost(HttpServletRequest request, HttpServletResponse response)
{
    String sss = response.getHeader("REMOTE_USER");
}

Twitter Bootstrap scrollable table rows and fixed header

<table class="table table-striped table-condensed table-hover rsk-tbl vScrollTHead">
            <thead>
            <tr>
                <th>Risk Element</th>
                <th>Description</th>
                <th>Risk Value</th>
                <th>&nbsp;</th>
            </tr>
            </thead>
        </table>
<div class="vScrollTable">
            <table class="table table-striped table-condensed table-hover rsk-tbl vScrollTBody">
                <tbody>
                <tr class="">
                    <td>JEWELLERY</td>
                    <td>Jewellery business</td>

                </tr><tr class="">
                    <td>NGO</td>
                    <td>none-governmental organizations</td>
                    </tr>
                </tbody>
            </table>
        </div>





.vScrollTBody{
  height:15px;
}

.vScrollTHead {
  height:15px;
}

.vScrollTable{
  height:100px;
  overflow-y:scroll;
}

having two tables for head and body worked for me

how to check for special characters php

<?php

$string = 'foo';

if (preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $string))
{
    // one or more of the 'special characters' found in $string
}

What is the difference between an expression and a statement in Python?

An expression is a combination of values, variables, and operators. A value all by itself is considered an expression, and so is a variable, so the following are all legal expressions:

>>> 42
42
>>> n
17
>>> n + 25
42

When you type an expression at the prompt, the interpreter evaluates it, which means that it finds the value of the expression. In this example, n has the value 17 and n + 25 has the value 42.


A statement is a unit of code that has an effect, like creating a variable or displaying a value.

>>> n = 17
>>> print(n)

The first line is an assignment statement that gives a value to n. The second line is a print statement that displays the value of n. When you type a statement, the interpreter executes it, which means that it does whatever the statement says. In general, statements don’t have values.

This can be useful - thinkpython2 by Allen B. Downey

basic authorization command for curl

One way, provide --user flag as part of curl, as follows:

curl --user username:password http://example.com

Another way is to get Base64 encoded token of "username:password" from any online website like - https://www.base64encode.org/ and pass it as Authorization header of curl as follows:

curl -i -H 'Authorization:Basic dXNlcm5hbWU6cGFzc3dvcmQ=' http://localhost:8080/

Here, dXNlcm5hbWU6cGFzc3dvcmQ= is Base64 encoded token of username:password.

BATCH file asks for file or folder

The /i switch might be what your after.

From xcopy /?

/I If destination does not exist and copying more than one file, assumes that destination must be a directory.

getResourceAsStream returns null

Don't use absolute paths, make them relative to the 'resources' directory in your project. Quick and dirty code that displays the contents of MyTest.txt from the directory 'resources'.

@Test
public void testDefaultResource() {
    // can we see default resources
    BufferedInputStream result = (BufferedInputStream) 
         Config.class.getClassLoader().getResourceAsStream("MyTest.txt");
    byte [] b = new byte[256];
    int val = 0;
    String txt = null;
    do {
        try {
            val = result.read(b);
            if (val > 0) {
                txt += new String(b, 0, val);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } 
    } while (val > -1);
    System.out.println(txt);
}

How to change the URI (URL) for a remote Git repository?

If your repository is private then

  1. Open Control Panel from the Start menu
  2. Select User Accounts
  3. Select "Manage your credentials" in the left hand menu
  4. Delete any credentials related to Git or GitHub

Reference

What is the meaning of {...this.props} in Reactjs

It will compile to this:

React.createElement('div', this.props, 'Content Here');

As you can see above, it passes all it's props to the div.

CSS3 Continuous Rotate Animation (Just like a loading sundial)

I made a small library that lets you easily use a throbber without images.

It uses CSS3 but falls back onto JavaScript if the browser doesn't support it.

// First argument is a reference to a container element in which you
// wish to add a throbber to.
// Second argument is the duration in which you want the throbber to
// complete one full circle.
var throbber = throbbage(document.getElementById("container"), 1000);

// Start the throbber.
throbber.play();

// Pause the throbber.
throbber.pause();

Example.

How to detect if CMD is running as Administrator/has elevated privileges?

I know I'm really late to this party, but here's my one liner to determine admin-hood.

It doesn't rely on error level, just on systeminfo:

for /f "tokens=1-6" %%a in ('"net user "%username%" | find /i "Local Group Memberships""') do (set admin=yes & if not "%%d" == "*Administrators" (set admin=no) & echo %admin%)

It returns either yes or no, depending on the user's admin status...

It also sets the value of the variable "admin" to equal yes or no accordingly.

getResources().getColor() is deprecated

You need to use ContextCompat.getColor(), which is part of the Support V4 Library (so it will work for all the previous API).

ContextCompat.getColor(context, R.color.my_color)

As specified in the documentation, "Starting in M, the returned color will be styled for the specified Context's theme". SO no need to worry about it.

You can add the Support V4 library by adding the following to the dependencies array inside your app build.gradle:

compile 'com.android.support:support-v4:23.0.1'

How to disable a ts rule for a specific line?

You can use /* tslint:disable-next-line */ to locally disable tslint. However, as this is a compiler error disabling tslint might not help.

You can always temporarily cast $ to any:

delete ($ as any).summernote.options.keyMap.pc.TAB

which will allow you to access whatever properties you want.


Edit: As of Typescript 2.6, you can now bypass a compiler error/warning for a specific line:

if (false) {
    // @ts-ignore: Unreachable code error
    console.log("hello");
}

Note that the official docs "recommend you use [this] very sparingly". It is almost always preferable to cast to any instead as that better expresses intent.

Error on line 2 at column 1: Extra content at the end of the document

On each loop of the result set, you're appending a new root element to the document, creating an XML document like this:

<?xml version="1.0"?>
<mycatch>...</mycatch>
<mycatch>...</mycatch>
...

An XML document can only have one root element, which is why the error is stating there is "extra content". Create a single root element and add all the mycatch elements to that:

$root = $dom->createElement("root");
$dom->appendChild($root);
// ...
while ($row = @mysql_fetch_assoc($result)){
  $node = $dom->createElement("mycatch");
  $root->appendChild($node);

How do I make a newline after a twitter bootstrap element?

You're using span6 and span2. Both of these classes are "float:left" meaning, if possible they will always try to sit next to each other. Twitter bootstrap is based on a 12 grid system. So you should generally always get the span**#** to add up to 12.

E.g.: span4 + span4 + span4 OR span6 + span6 OR span4 + span3 + span5.

To force a span down though, without listening to the previous float you can use twitter bootstraps clearfix class. To do this, your code should look like this:

<ul class="nav nav-tabs span2">
  <li><a href="./index.html"><i class="icon-black icon-music"></i></a></li>
  <li><a href="./about.html"><i class="icon-black icon-eye-open"></i></a></li>
  <li><a href="./team.html"><i class="icon-black icon-user"></i></a></li>
  <li><a href="./contact.html"><i class="icon-black icon-envelope"></i></a></li>
</ul>
<!-- Notice this following line -->
<div class="clearfix"></div>
<div class="well span6">
  <h3>I wish this appeared on the next line without having to gratuitously use BR!</h3>
</div>

Determine if an element has a CSS class with jQuery

from the FAQ

elem = $("#elemid");
if (elem.is (".class")) {
   // whatever
}

or:

elem = $("#elemid");
if (elem.hasClass ("class")) {
   // whatever
}

how to implement regions/code collapse in javascript

Microsoft now has an extension for VS 2010 that provides this functionality:

JScript Editor Extensions

Cannot kill Python script with Ctrl-C

An improved version of @Thomas K's answer:

  • Defining an assistant function is_any_thread_alive() according to this gist, which can terminates the main() automatically.

Example codes:

import threading

def job1():
    ...

def job2():
    ...

def is_any_thread_alive(threads):
    return True in [t.is_alive() for t in threads]

if __name__ == "__main__":
    ...
    t1 = threading.Thread(target=job1,daemon=True)
    t2 = threading.Thread(target=job2,daemon=True)
    t1.start()
    t2.start()

    while is_any_thread_alive([t1,t2]):
        time.sleep(0)

req.query and req.param in ExpressJS

req.query is the query string sent to the server, example /page?test=1, req.param is the parameters passed to the handler.

app.get('/user/:id', handler);, going to /user/blah, req.param.id would return blah;

how does Request.QueryString work?

The QueryString collection is used to retrieve the variable values in the HTTP query string.

The HTTP query string is specified by the values following the question mark (?), like this:

Link with a query string

The line above generates a variable named txt with the value "this is a query string test".

Query strings are also generated by form submission, or by a user typing a query into the address bar of the browser.

And see this sample : http://www.codeproject.com/Articles/5876/Passing-variables-between-pages-using-QueryString

refer this : http://www.dotnetperls.com/querystring

you can collect More details in google .

Find row in datatable with specific id

Make a string criteria to search for, like this:

string searchExpression = "ID = 5"

Then use the .Select() method of the DataTable object, like this:

DataRow[] foundRows = YourDataTable.Select(searchExpression);

Now you can loop through the results, like this:

int numberOfCalls;
bool result;
foreach(DataRow dr in foundRows)
{
    // Get value of Calls here
    result = Int32.TryParse(dr["Calls"], out numberOfCalls);

    // Optionally, you can check the result of the attempted try parse here
    // and do something if you wish
    if(result)
    {
        // Try parse to 32-bit integer worked

    }
    else
    {
        // Try parse to 32-bit integer failed

    }
}

change directory in batch file using variable

simple way to do this... here are the example

cd program files
cd poweriso
piso mount D:\<Filename.iso> <Virtual Drive>
Pause

this will mount the ISO image to the specific drive...use

Maintain/Save/Restore scroll position when returning to a ListView

use this below code :

int index,top;

@Override
protected void onPause() {
    super.onPause();
    index = mList.getFirstVisiblePosition();

    View v = challengeList.getChildAt(0);
    top = (v == null) ? 0 : (v.getTop() - mList.getPaddingTop());
}

and whenever your refresh your data use this below code :

adapter.notifyDataSetChanged();
mList.setSelectionFromTop(index, top);

Difference between JE/JNE and JZ/JNZ

JE and JZ are just different names for exactly the same thing: a conditional jump when ZF (the "zero" flag) is equal to 1.

(Similarly, JNE and JNZ are just different names for a conditional jump when ZF is equal to 0.)

You could use them interchangeably, but you should use them depending on what you are doing:

  • JZ/JNZ are more appropriate when you are explicitly testing for something being equal to zero:

    dec  ecx
    jz   counter_is_now_zero
    
  • JE and JNE are more appropriate after a CMP instruction:

    cmp  edx, 42
    je   the_answer_is_42
    

    (A CMP instruction performs a subtraction, and throws the value of the result away, while keeping the flags; which is why you get ZF=1 when the operands are equal and ZF=0 when they're not.)

HTML form submit to PHP script

Assuming you've fixed the syntax errors (you've closed the select box before the name attribute), you're using the same name for the select box as the submit button. Give the select box a different name.

Query comparing dates in SQL

please try with below query

select id,numbers_from,created_date,amount_numbers,SMS_text 
from Test_Table
where 
convert(datetime, convert(varchar(10), created_date, 102))  <= convert(datetime,'2013-04-12')

How to get JavaScript caller function line number? How to get JavaScript caller source URL?

This works for me in chrome/QtWebView

function getErrorObject(){
    try { throw Error('') } catch(err) { return err; }
}

var err = getErrorObject();
var caller_line = err.stack.split("\n")[4];
var index = caller_line.indexOf("at ");
var clean = caller_line.slice(index+2, caller_line.length);

Remove DEFINER clause from MySQL Dumps

I don't think there is a way to ignore adding DEFINERs to the dump. But there are ways to remove them after the dump file is created.

  1. Open the dump file in a text editor and replace all occurrences of DEFINER=root@localhost with an empty string ""

  2. Edit the dump (or pipe the output) using perl:

    perl -p -i.bak -e "s/DEFINER=\`\w.*\`@\`\d[0-3].*[0-3]\`//g" mydatabase.sql
    
  3. Pipe the output through sed:

    mysqldump ... | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' > triggers_backup.sql
    

How to select the first element in the dropdown using jquery?

    var arr_select_val=[];

    $("select").each(function() { 
        var name=this.name;
            arr_select_val[name]=$('select option:first-child').val();
    });


// Process the array object
     $('.orders_status_summary_div').print(arr_select_val);

How to "perfectly" override a dict?

My requirements were a bit stricter:

  • I had to retain case info (the strings are paths to files displayed to the user, but it's a windows app so internally all operations must be case insensitive)
  • I needed keys to be as small as possible (it did make a difference in memory performance, chopped off 110 mb out of 370). This meant that caching lowercase version of keys is not an option.
  • I needed creation of the data structures to be as fast as possible (again made a difference in performance, speed this time). I had to go with a builtin

My initial thought was to substitute our clunky Path class for a case insensitive unicode subclass - but:

  • proved hard to get that right - see: A case insensitive string class in python
  • turns out that explicit dict keys handling makes code verbose and messy - and error prone (structures are passed hither and thither, and it is not clear if they have CIStr instances as keys/elements, easy to forget plus some_dict[CIstr(path)] is ugly)

So I had finally to write down that case insensitive dict. Thanks to code by @AaronHall that was made 10 times easier.

class CIstr(unicode):
    """See https://stackoverflow.com/a/43122305/281545, especially for inlines"""
    __slots__ = () # does make a difference in memory performance

    #--Hash/Compare
    def __hash__(self):
        return hash(self.lower())
    def __eq__(self, other):
        if isinstance(other, CIstr):
            return self.lower() == other.lower()
        return NotImplemented
    def __ne__(self, other):
        if isinstance(other, CIstr):
            return self.lower() != other.lower()
        return NotImplemented
    def __lt__(self, other):
        if isinstance(other, CIstr):
            return self.lower() < other.lower()
        return NotImplemented
    def __ge__(self, other):
        if isinstance(other, CIstr):
            return self.lower() >= other.lower()
        return NotImplemented
    def __gt__(self, other):
        if isinstance(other, CIstr):
            return self.lower() > other.lower()
        return NotImplemented
    def __le__(self, other):
        if isinstance(other, CIstr):
            return self.lower() <= other.lower()
        return NotImplemented
    #--repr
    def __repr__(self):
        return '{0}({1})'.format(type(self).__name__,
                                 super(CIstr, self).__repr__())

def _ci_str(maybe_str):
    """dict keys can be any hashable object - only call CIstr if str"""
    return CIstr(maybe_str) if isinstance(maybe_str, basestring) else maybe_str

class LowerDict(dict):
    """Dictionary that transforms its keys to CIstr instances.
    Adapted from: https://stackoverflow.com/a/39375731/281545
    """
    __slots__ = () # no __dict__ - that would be redundant

    @staticmethod # because this doesn't make sense as a global function.
    def _process_args(mapping=(), **kwargs):
        if hasattr(mapping, 'iteritems'):
            mapping = getattr(mapping, 'iteritems')()
        return ((_ci_str(k), v) for k, v in
                chain(mapping, getattr(kwargs, 'iteritems')()))
    def __init__(self, mapping=(), **kwargs):
        # dicts take a mapping or iterable as their optional first argument
        super(LowerDict, self).__init__(self._process_args(mapping, **kwargs))
    def __getitem__(self, k):
        return super(LowerDict, self).__getitem__(_ci_str(k))
    def __setitem__(self, k, v):
        return super(LowerDict, self).__setitem__(_ci_str(k), v)
    def __delitem__(self, k):
        return super(LowerDict, self).__delitem__(_ci_str(k))
    def copy(self): # don't delegate w/ super - dict.copy() -> dict :(
        return type(self)(self)
    def get(self, k, default=None):
        return super(LowerDict, self).get(_ci_str(k), default)
    def setdefault(self, k, default=None):
        return super(LowerDict, self).setdefault(_ci_str(k), default)
    __no_default = object()
    def pop(self, k, v=__no_default):
        if v is LowerDict.__no_default:
            # super will raise KeyError if no default and key does not exist
            return super(LowerDict, self).pop(_ci_str(k))
        return super(LowerDict, self).pop(_ci_str(k), v)
    def update(self, mapping=(), **kwargs):
        super(LowerDict, self).update(self._process_args(mapping, **kwargs))
    def __contains__(self, k):
        return super(LowerDict, self).__contains__(_ci_str(k))
    @classmethod
    def fromkeys(cls, keys, v=None):
        return super(LowerDict, cls).fromkeys((_ci_str(k) for k in keys), v)
    def __repr__(self):
        return '{0}({1})'.format(type(self).__name__,
                                 super(LowerDict, self).__repr__())

Implicit vs explicit is still a problem, but once dust settles, renaming of attributes/variables to start with ci (and a big fat doc comment explaining that ci stands for case insensitive) I think is a perfect solution - as readers of the code must be fully aware that we are dealing with case insensitive underlying data structures. This will hopefully fix some hard to reproduce bugs, which I suspect boil down to case sensitivity.

Comments/corrections welcome :)

Folder is locked and I can't unlock it

Right click on your Subversion working directory folder, and select TortoiseSVN->Clean Up from the Context Menu. This will recurse it's way through your working directory and cleanup any incomplete actions, remove the local locks (which is different from using Subversion locking of a file in the repository which lets everyone know about the lock).

If that doesn't work, see if you can find the names of the files that were changed, but not yet committed, save them, and redo the checkout.

How can I create an error 404 in PHP?

try putting

ErrorDocument 404 /(root directory)/(error file) 

in .htaccess file.

Do this for any error but substitute 404 for your error.

Item frequency count in Python

The Counter class in the collections module is purpose built to solve this type of problem:

from collections import Counter
words = "apple banana apple strawberry banana lemon"
Counter(words.split())
# Counter({'apple': 2, 'banana': 2, 'strawberry': 1, 'lemon': 1})

Python module for converting PDF to text

pyPDF works fine (assuming that you're working with well-formed PDFs). If all you want is the text (with spaces), you can just do:

import pyPdf
pdf = pyPdf.PdfFileReader(open(filename, "rb"))
for page in pdf.pages:
    print page.extractText()

You can also easily get access to the metadata, image data, and so forth.

A comment in the extractText code notes:

Locate all text drawing commands, in the order they are provided in the content stream, and extract the text. This works well for some PDF files, but poorly for others, depending on the generator used. This will be refined in the future. Do not rely on the order of text coming out of this function, as it will change if this function is made more sophisticated.

Whether or not this is a problem depends on what you're doing with the text (e.g. if the order doesn't matter, it's fine, or if the generator adds text to the stream in the order it will be displayed, it's fine). I have pyPdf extraction code in daily use, without any problems.

how do I use an enum value on a switch statement in C++

#include <iostream>
using namespace std;

int main() {

    enum level {EASY = 1, NORMAL, HARD};

    // Present menu
    int choice;
    cout << "Choose your level:\n\n";
    cout << "1 - Easy.\n";
    cout << "2 - Normal.\n";
    cout << "3 - Hard.\n\n";
    cout << "Choice --> ";
    cin >> choice;
    cout << endl;

    switch (choice) {
    case EASY:
        cout << "You chose Easy.\n";
        break;
    case NORMAL:
        cout << "You chose Normal.\n";
        break;
    case HARD:
        cout << "You chose Hard.\n";
        break;
    default:
        cout << "Invalid choice.\n";
    }

    return 0;
}

How to show all shared libraries used by executables in Linux?

With ldd you can get the libraries that tools use. To rank the usage of libraries for a set of tool you can use something like the following command.

ldd /bin/* /usr/bin/* ... | sed -e '/^[^\t]/ d; s/^\t\(.* => \)\?\([^ ]*\) (.*/\2/g' | sort | uniq -c

(Here sed strips all lines that do not start with a tab and the filters out only the actual libraries. With sort | uniq -c you get each library with a count indicating the number of times it occurred.)

You might want to add sort -g at the end to get the libraries in order of usage.

Note that you probably get lines two non-library lines with the above command. One of static executables ("not a dynamic executable") and one without any library. The latter is the result of linux-gate.so.1 which is not a library in your file system but one "supplied" by the kernel.

How to subtract date/time in JavaScript?

You can just substract two date objects.

var d1 = new Date(); //"now"
var d2 = new Date("2011/02/01")  // some date
var diff = Math.abs(d1-d2);  // difference in milliseconds

How do you set a JavaScript onclick event to a class with css

You can do this by thinking of it a little bit differently. Detect when the body is clicked (document.body.onclick - i.e. anything on the page) and then check if the element clicked (event.srcElement / e.target) has a class and that that class name is the one you want:

document.body.onclick = function(e) {   //when the document body is clicked
    if (window.event) {
        e = event.srcElement;           //assign the element clicked to e (IE 6-8)
    }
    else {
        e = e.target;                   //assign the element clicked to e
    }

    if (e.className && e.className.indexOf('someclass') != -1) {
        //if the element has a class name, and that is 'someclass' then...
        alert('hohoho');
    }
}

Or a more concise version of the above:

document.body.onclick= function(e){
   e=window.event? event.srcElement: e.target;
   if(e.className && e.className.indexOf('someclass')!=-1)alert('hohoho');
}

Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved

In my case my problem was that I was using an older version of NetBeans. The Maven repository removed an http reference, but the embedded Maven in Netbeans had that http reference hard-coded. I was really confused at first because my pom.xml referenced the proper https://repo.maven.apache.org/maven2.

Fixing it was pretty simple. I downloaded the latest zip archive of Maven from the following location and extracted it to my machine: https://maven.apache.org/download.cgi

Within Netbeans at Tools -> Options -> Java -> Maven on the "Execution" section I set "Maven Home" to the newly extracted zip file location.

Now I could build my project....

Print a div using javascript in angularJS single page application

This is what worked for me in Chrome and Firefox! This will open the little print window and close it automatically once you've clicked print.

var printContents = document.getElementById('div-id-selector').innerHTML;
            var popupWin = window.open('', '_blank', 'width=800,height=800,scrollbars=no,menubar=no,toolbar=no,location=no,status=no,titlebar=no,top=50');
            popupWin.window.focus();
            popupWin.document.open();
            popupWin.document.write('<!DOCTYPE html><html><head><title>TITLE OF THE PRINT OUT</title>' 
                                    +'<link rel="stylesheet" type="text/css" href="app/directory/file.css" />' 
                                    +'</head><body onload="window.print(); window.close();"><div>' 
                                    + printContents + '</div></html>');
            popupWin.document.close();

JavaScript regex for alphanumeric string with length of 3-5 chars

You'd have to define alphanumerics exactly, but

/^(\w{3,5})$/ 

Should match any digit/character/_ combination of length 3-5.

If you also need the dash, make sure to escape it (\-) add it, like this: :

/^([\w\-]{3,5})$/ 

Also: the ^ anchor means that the sequence has to start at the beginning of the line (character string), and the $ that it ends at the end of the line (character string). So your value string mustn't contain anything else, or it won't match.

variable is not declared it may be inaccessible due to its protection level

I got this error briefly after renaming the App_Code folder. Actually, I accidentally dragged the whole folder to the App_data folder. VS 2015 didn't complain it was difficult to spot what had gone wrong.

How to remove "disabled" attribute using jQuery?

I think you are trying to toggle the disabled state, in witch case you should use this (from this question):

$(".inputDisabled").prop('disabled', function (_, val) { return ! val; });

Here is a working fiddle.

How to use classes from .jar files?

As workmad3 says, you need the jar file to be in your classpath. If you're compiling from the commandline, that will mean using the -classpath flag. (Avoid the CLASSPATH environment variable; it's a pain in the neck IMO.)

If you're using an IDE, please let us know which one and we can help you with the steps specific to that IDE.

What is SYSNAME data type in SQL Server?

sysname is used by sp_send_dbmail, a stored procedure that "Sends an e-mail message to the specified recipients" and located in the msdb database.

According to Microsoft,

[ @profile_name = ] 'profile_name'  

Is the name of the profile to send the message from. The profile_name is of type sysname, with a default of NULL. The profile_name must be the name of an existing Database Mail profile. When no profile_name is specified, sp_send_dbmail uses the default private profile for the current user. If the user does not have a default private profile, sp_send_dbmail uses the default public profile for the msdb database. If the user does not have a default private profile and there is no default public profile for the database, @profile_name must be specified.

How can I mix LaTeX in with Markdown?

Hey, this might not be the most ideal solution, but it works for me. I ended up creating a Python-Markdown LaTeX extension.

https://github.com/justinvh/Markdown-LaTeX

It adds support for inline math and text expressions using a $math$ and %text% syntax. The extension is a preprocessor that will use latex/dvipng to generate pngs for the respective equations/text and then base64 encode the data to inline the images directly, rather than have external images.

The data is then put in a simple-delimited cache file that encodes the expression to the base64 representation. This limits the number of times latex actually has to be run.

Here is an example:

%Hello, world!% This is regular text, but this: $y = mx + b$ is not.

The output:

$ markdown -x latex test.markdown
<p><img class='latex-inline math-false' alt='Hello, world!' id='Helloworld' src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFwAAAAQBAMAAABpWwV8AAAAMFBMVEX///8iIiK6urpUVFTu7u6YmJgQEBDc3NxERESqqqqIiIgyMjJ2dnZmZmbMzMwAAAAbX03YAAAAAXRSTlMAQObYZgAAAVpJREFUKM9jYICDOgb2BwzYAVji8AQg8fb/PZ79u4AMvv0Mrz/gUA6W8F7AmcLAsJuBYT7Y1PcMfLiUgyWYF/B8Z2DYAVReABKrZ2DHpZwdopzrA0nKOeHKj66CKOcKPQJWwJo2NVFhfwCQyymhYwCUYD0avIApgYFh2927/QUcE3gDwMpvMhRCDJzNMIPhKZg7UW8DUOIMg9sCPgGo6e8ZODeAlAP9xLEArNy/IIwhAMx9D3IM+3cgi70BqnxZaNQFkHJWAQbeBrByjgURExaAuc9AyjnB5hjAlEO9ygVXzrplpskEMPchQvkBmGMcGApgjjkAVs7yhyWVAcwFK2f/AlJeAI0m5gMsEK+aMhQ6aDuA1DcDIZirBg7IOwxlB5g2QBJBF8OZVUz95hqfC3hOXWGYrwBSHskwk4EByGXab8QAlOBaGizFKYAtUlgUGEgBTCSpZnDCLQUA+y6MXeYnPDgAAAAASUVORK5CYII='> This is regular text, but this: <img class='latex-inline math-true' alt='y = mx + b' id='ymxb' src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFIAAAAOBAMAAABOTlYkAAAAMFBMVEX///9ERETu7u4yMjK6urp2dnZUVFSIiIjMzMwQEBDc3NwiIiJmZmaYmJiqqqoAAADS00rKAAAAAXRSTlMAQObYZgAAAOtJREFUKM9jYCAACsCk4wYGgiABTLInEKuS+QGxKvkVGBj47jBwI8tcffI84e45BoZ7GVcLECo9751iWLeSoRPITBQEggMMDBy9sxj2MDgz8DIE8yCpPMxwjWFBGUMMkpFcbAEMvxjKGLgYxIE8NkHBiYIyQMY+hmoGhi0Mdsi2czawbGCQBTJ+ILvzE0MaA9MHIIWwnWE9A+sBpk8LGDgmMCnAVXJNYPgCJHhRQvUiA/cDXoECZx4DXoSZTBtYgaaEPw5AVnkOGBRc5xTcbsReQrL9+nWwyxbgC88DcJZ+QygDcYD1+QPiFAIAtLA8KPZOGFEAAAAASUVORK5CYII='> is not.</p>

As you can see it is a verbose output, but that really isn't an issue since you're already using Markdown :)

Measure string size in Bytes in php

Do you mean byte size or string length?

Byte size is measured with strlen(), whereas string length is queried using mb_strlen(). You can use substr() to trim a string to X bytes (note that this will break the string if it has a multi-byte encoding - as pointed out by Darhazer in the comments) and mb_substr() to trim it to X characters in the encoding of the string.

Plain Old CLR Object vs Data Transfer Object

I wrote an article for that topic: DTO vs Value Object vs POCO.

In short:

  • DTO != Value Object
  • DTO ? POCO
  • Value Object ? POCO

How to configure Chrome's Java plugin so it uses an existing JDK in the machine

On Ubuntu, You can follow these steps to resolve the issue:

  1. Create a directory named plugins inside $HOME/.mozilla, if it doesn't exist already
  2. Create a symlink to libnpjp2.so inside this directory using this command:

    ln -s $JAVA_HOME/jre/lib/i386/libnpjp2.so $MOZILLA_HOME/plugins
    

    -or-

    ln -s $JAVA_HOME/jre/lib/amd64/libnpjp2.so $MOZILLA_HOME/plugins
    

    depending on whether you're using a 32 or 64 bit JVM installation. Moreover, $JAVA_HOME is the location of your JVM installation.

More detailed instructions can be found here.

What is the error "Every derived table must have its own alias" in MySQL?

I think it's asking you to do this:

SELECT ID
FROM (SELECT ID,
             msisdn 
      FROM (SELECT * FROM TT2) as myalias
     ) as anotheralias;

But why would you write this query in the first place?

How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?

In .NET4.5, MVC 5 no need for widgets.

Javascript:

object in JS: enter image description here

mechanism that does post.

    $('.button-green-large').click(function() {
        $.ajax({
            url: 'Quote',
            type: "POST",
            dataType: "json",
            data: JSON.stringify(document.selectedProduct),
            contentType: 'application/json; charset=utf-8',
        });
    });

C#

Objects:

public class WillsQuoteViewModel
{
    public string Product { get; set; }

    public List<ClaimedFee> ClaimedFees { get; set; }
}

public partial class ClaimedFee //Generated by EF6
{
    public long Id { get; set; }
    public long JourneyId { get; set; }
    public string Title { get; set; }
    public decimal Net { get; set; }
    public decimal Vat { get; set; }
    public string Type { get; set; }

    public virtual Journey Journey { get; set; }
}

Controller:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Quote(WillsQuoteViewModel data)
{
....
}

Object received:

enter image description here

Hope this saves you some time.

Change/Get check state of CheckBox

var val = $("#checkboxId").is(":checked");

Start systemd service after specific service?

After= dependency is only effective when service including After= and service included by After= are both scheduled to start as part of your boot up.

Ex:

a.service
[Unit]
After=b.service

This way, if both a.service and b.service are enabled, then systemd will order b.service after a.service.

If I am not misunderstanding, what you are asking is how to start b.service when a.service starts even though b.service is not enabled.

The directive for this is Wants= or Requires= under [Unit].

website.service
[Unit]
Wants=mongodb.service
After=mongodb.service

The difference between Wants= and Requires= is that with Requires=, a failure to start b.service will cause the startup of a.service to fail, whereas with Wants=, a.service will start even if b.service fails. This is explained in detail on the man page of .unit.

SVN undo delete before commit

svn revert deletedDirectory

Here's the documentation for the svn revert command.


EDIT

If deletedDirectory was deleted using rmdir and not svn rm, you'll need to do

svn update deletedDirectory

instead.

How can I check if a MySQL table exists with PHP?

The cleanest way to achieve this in PHP is to simply use DESCRIBE statement.

if ( mysql_query( "DESCRIBE `my_table`" ) ) {
    // my_table exists
}

I'm not sure why others are posting complicated queries for a such a straight forward problem.

Update

Using PDO

// assuming you have already setup $pdo
$sh = $pdo->prepare( "DESCRIBE `my_table`");
if ( $sh->execute() ) {
    // my_table exists
} else {
    // my_table does not exist    
}

Grep to find item in Perl array

The first arg that you give to grep needs to evaluate as true or false to indicate whether there was a match. So it should be:

# note that grep returns a list, so $matched needs to be in brackets to get the 
# actual value, otherwise $matched will just contain the number of matches
if (my ($matched) = grep $_ eq $match, @array) {
    print "found it: $matched\n";
}

If you need to match on a lot of different values, it might also be worth for you to consider putting the array data into a hash, since hashes allow you to do this efficiently without having to iterate through the list.

# convert array to a hash with the array elements as the hash keys and the values are simply 1
my %hash = map {$_ => 1} @array;

# check if the hash contains $match
if (defined $hash{$match}) {
    print "found it\n";
}

C++ error 'Undefined reference to Class::Function()'

This part has problems:

Card* cardArray;
void Deck() {
    cardArray = new Card[NUM_TOTAL_CARDS];
    int cardCount = 0;
    for (int i = 0; i > NUM_SUITS; i++) {  //Error
        for (int j = 0; j > NUM_RANKS; j++) { //Error
            cardArray[cardCount] = Card(Card::Rank(i), Card::Suit(j) );
            cardCount++;
         }
    }
 }
  1. cardArray is a dynamic array, but not a member of Card class. It is strange if you would like to initialize a dynamic array which is not member of the class
  2. void Deck() is not constructor of class Deck since you missed the scope resolution operator. You may be confused with defining the constructor and the function with name Deck and return type void.
  3. in your loops, you should use < not > otherwise, loop will never be executed.

What is the maximum size of a web browser's cookie's key?

A cookie key(used to identify a session) and a cookie are the same thing being used in different ways. So the limit would be the same. According to Microsoft its 4096 bytes.

MSDN

cookies are usually limited to 4096 bytes and you can't store more than 20 cookies per site. By using a single cookie with subkeys, you use fewer of those 20 cookies that your site is allotted. In addition, a single cookie takes up about 50 characters for overhead (expiration information, and so on), plus the length of the value that you store in it, all of which counts toward the 4096-byte limit. If you store five subkeys instead of five separate cookies, you save the overhead of the separate cookies and can save around 200 bytes.

Run cmd commands through Java

Here the value adder is use of ampersands to batch commands and correct format for change drive with cd.

public class CmdCommander {

public static void main(String[] args) throws Exception {
    //easyway to start native windows command prompt from Intellij

    /*
    Rules are:
    1.baseStart must be dual start
    2.first command must not have &.
    3.subsequent commands must be prepended with &
    4.drive change needs extra &
    5.use quotes at start and end of command batch
    */
    String startQuote = "\"";
    String endQuote = "\"";
    //String baseStart_not_taking_commands = " cmd  /K start ";
    String baseStart = " cmd  /K start cmd /K ";//dual start is must

    String first_command_chcp = " chcp 1251 ";
    String dirList = " &dir ";//& in front of commands after first command means enter
    //change drive....to yours
    String changeDir = " &cd &I: ";//extra & makes changing drive happen

    String javaLaunch = " &java ";//just another command
    String javaClass = " Encodes ";//parameter for java needs no &

    String javaCommand = javaLaunch + javaClass;
    //build batch command
    String totalCommand =
            baseStart +
                    startQuote +
                    first_command_chcp +
                    //javaCommand +
                    changeDir +
                    dirList +
                    endQuote;

    System.out.println(totalCommand);//prints into Intellij terminal
    runCmd(totalCommand);
    //Thread t = Thread.currentThread();
    //t.sleep(3000);
    System.out.println("loppu hep");//prints into Intellij terminal

}


public static void runCmd(String command) throws Exception {

    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec(command);


}

}

Configure Flask dev server to be visible across the network

Add below lines to your project

if __name__ == '__main__':
    app.debug = True
    app.run(host = '0.0.0.0',port=5005)

MySQL select one column DISTINCT, with corresponding other columns

To avoid potentially unexpected results when using GROUP BY without an aggregate function, as is used in the accepted answer, because MySQL is free to retrieve ANY value within the data set being grouped when not using an aggregate function [sic] and issues with ONLY_FULL_GROUP_BY. Please consider using an exclusion join.

Exclusion Join - Unambiguous Entities

Assuming the firstname and lastname are uniquely indexed (unambiguous), an alternative to GROUP BY is to sort using a LEFT JOIN to filter the result set, otherwise known as an exclusion JOIN.

See Demonstration

Ascending order (A-Z)

To retrieve the distinct firstname ordered by lastname from A-Z

Query

SELECT t1.*
FROM table_name AS t1
LEFT JOIN table_name AS t2
ON t1.firstname = t2.firstname
AND t1.lastname > t2.lastname
WHERE t2.id IS NULL;

Result

| id | firstname | lastname |
|----|-----------|----------|
|  2 |      Bugs |    Bunny |
|  1 |      John |      Doe |

Descending order (Z-A)

To retrieve the distinct firstname ordered by lastname from Z-A

Query

SELECT t1.*
FROM table_name AS t1
LEFT JOIN table_name AS t2
ON t1.firstname = t2.firstname
AND t1.lastname < t2.lastname
WHERE t2.id IS NULL;

Result

| id | firstname | lastname |
|----|-----------|----------|
|  2 |      Bugs |    Bunny |
|  3 |      John |  Johnson |

You can then order the resulting data as desired.


Exclusion Join - Ambiguous Entities

If the first and last name combination are not unique (ambiguous) and you have multiple rows of the same values, you can filter the result set by including an OR condition on the JOIN criteria to also filter by id.

See Demonstration

table_name data

(1, 'John', 'Doe'),
(2, 'Bugs', 'Bunny'),
(3, 'John', 'Johnson'),
(4, 'John', 'Doe'),
(5, 'John', 'Johnson')

Query

SELECT t1.*
FROM table_name AS t1
LEFT JOIN table_name AS t2
ON t1.firstname = t2.firstname
AND (t1.lastname > t2.lastname
OR (t1.firstname = t1.firstname AND t1.lastname = t2.lastname AND t1.id > t2.id))
WHERE t2.id IS NULL;

Result

| id | firstname | lastname |
|----|-----------|----------|
|  1 |      John |      Doe |
|  2 |      Bugs |    Bunny |

Ordered Subquery

EDIT

My original answer using an ordered subquery, was written prior to MySQL 5.7.5, which is no longer applicable, due to the changes with ONLY_FULL_GROUP_BY. Please use the exclusion join examples above instead.

It is also important to note; when ONLY_FULL_GROUP_BY is disabled (original behavior prior to MySQL 5.7.5), the use of GROUP BY without an aggregate function may yield unexpected results, because MySQL is free to choose ANY value within the data set being grouped [sic].

Meaning an ID or lastname value may be retrieved that is not associated with the retrieved firstname row.


WARNING

With MySQL GROUP BY may not yield the expected results when used with ORDER BY

See Test Case Example

The best method of implementation, to ensure expected results, is to filter the result set scope using an ordered subquery.

table_name data

(1, 'John', 'Doe'),
(2, 'Bugs', 'Bunny'),
(3, 'John', 'Johnson')

Query

SELECT * FROM (
    SELECT * FROM table_name ORDER BY ID DESC
) AS t1
GROUP BY FirstName

Result

| ID | first |    last |
|----|-------|---------|
|  2 |  Bugs |   Bunny |
|  3 |  John | Johnson |

Comparison

To demonstrate the unexpected results when using GROUP BY in combination with ORDER BY

Query

SELECT * FROM table_name GROUP BY FirstName ORDER BY ID DESC

Result

| ID | first |  last |
|----|-------|-------|
|  2 |  Bugs | Bunny |
|  1 |  John |   Doe |

Should a function have only one return statement?

The only important question is "How is the code simpler, better readable, easier to understand?" If it is simpler with multiple returns, then use them.

How do I add 1 day to an NSDate?

Swift 4.0

extension Date {
    func add(_ unit: Calendar.Component, value: Int) -> Date? {
        return Calendar.current.date(byAdding: unit, value: value, to: self)
    }
}

Usage

date.add(.day, 3)!   // adds 3 days
date.add(.day, -14)!   // subtracts 14 days

Note: If you don't know why the lines of code end with an exclamation point, look up "Swift Optionals" on Google.