Programs & Examples On #Cut

A Unix shell command that breaks input into fields, which can be selected for output, based on a delimiter.

Copy and paste content from one file to another file in vi

These remaps work like a charm for me:

vmap <C-c> "*y     " Yank current selection into system clipboard
nmap <C-c> "*Y     " Yank current line into system clipboard (if nothing is selected)
nmap <C-v> "*p     " Paste from system clipboard

So, when I'm at visual mode, I select the lines I want and press Ctrl + c and then Ctrl + v to insert the text in the receiver file. You could use "*y as well, but I think this is hard to remember sometimes.

This is also useful to copy text from Vim to clipboard.

Source: Copy and paste between sessions using a temporary file

Use space as a delimiter with cut command

You can also say:

cut -d\  -f 2

Note that there are two spaces after the backslash.

how to remove the first two columns in a file using shell (awk, sed, whatever)

Thanks for posting the question. I'd also like to add the script that helped me.

awk '{ $1=""; print $0 }' file

How to find the last field using 'cut'

It is not possible using just cut. Here is a way using grep:

grep -o '[^,]*$'

Replace the comma for other delimiters.

How to split a string in shell and get the last field

$ echo "a b c d e" | tr ' ' '\n' | tail -1
e

Simply translate the delimiter into a newline and choose the last entry with tail -1.

How can I remove the extension of a filename in a shell script?

My recommendation is to use basename.
It is by default in Ubuntu, visually simple code and deal with majority of cases.

Here are some sub-cases to deal with spaces and multi-dot/sub-extension:

pathfile="../space fld/space -file.tar.gz"
echo ${pathfile//+(*\/|.*)}

It usually get rid of extension from first ., but fail in our .. path

echo **"$(basename "${pathfile%.*}")"**  
space -file.tar     # I believe we needed exatly that

Here is an important note:

I used double quotes inside double quotes to deal with spaces. Single quote will not pass due to texting the $. Bash is unusual and reads "second "first" quotes" due to expansion.

However, you still need to think of .hidden_files

hidden="~/.bashrc"
echo "$(basename "${hidden%.*}")"  # will produce "~" !!!  

not the expected "" outcome. To make it happen use $HOME or /home/user_path/
because again bash is "unusual" and don't expand "~" (search for bash BashPitfalls)

hidden2="$HOME/.bashrc" ;  echo '$(basename "${pathfile%.*}")'

Rearrange columns using cut

For the cut(1) man page:

Use one, and only one of -b, -c or -f. Each LIST is made up of one range, or many ranges separated by commas. Selected input is written in the same order that it is read, and is written exactly once.

It reaches field 1 first, so that is printed, followed by field 2.

Use awk instead:

awk '{ print $2 " " $1}' file.txt

How to make the 'cut' command treat same sequental delimiters as one?

With versions of cut I know of, no, this is not possible. cut is primarily useful for parsing files where the separator is not whitespace (for example /etc/passwd) and that have a fixed number of fields. Two separators in a row mean an empty field, and that goes for whitespace too.

How to specify more spaces for the delimiter using cut?

I am going to nominate tr -s [:blank:] as the best answer.

Why do we want to use cut? It has the magic command that says "we want the third field and every field after it, omitting the first two fields"

cat log | tr -s [:blank:] |cut -d' ' -f 3- 

I do not believe there is an equivalent command for awk or perl split where we do not know how many fields there will be, ie out put the 3rd field through field X.

bash script use cut command at variable and store result at another variable

The awk solution is what I would use, but if you want to understand your problems with bash, here is a revised version of your script.

#!/bin/bash -vx

##config file with ip addresses like 10.10.10.1:80
file=config.txt

while read line ; do
  ##this line is not correct, should strip :port and store to ip var
  ip=$( echo "$line" |cut -d\: -f1 )
  ping $ip
done < ${file}

You could write your top line as

for line in $(cat $file) ; do ...

(but not recommended).

You needed command substitution $( ... ) to get the value assigned to $ip

reading lines from a file is usually considered more efficient with the while read line ... done < ${file} pattern.

I hope this helps.

Loop through a comma-separated shell variable

Here's my pure bash solution that doesn't change IFS, and can take in a custom regex delimiter.

loop_custom_delimited() {
    local list=$1
    local delimiter=$2
    local item
    if [[ $delimiter != ' ' ]]; then
        list=$(echo $list | sed 's/ /'`echo -e "\010"`'/g' | sed -E "s/$delimiter/ /g")
    fi
    for item in $list; do
        item=$(echo $item | sed 's/'`echo -e "\010"`'/ /g')
        echo "$item"
    done
}

Using the grep and cut delimiter command (in bash shell scripting UNIX) - and kind of "reversing" it?

You don't need to change the delimiter to display the right part of the string with cut.

The -f switch of the cut command is the n-TH element separated by your delimiter : :, so you can just type :

 grep puddle2_1557936 | cut -d ":" -f2

Another solutions (adapt it a bit) if you want fun :

Using :

grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                        
/home/rogers.williams/folderz/puddle2

or still with look around

grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                    
/home/rogers.williams/folderz/puddle2

or with :

perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                      
/home/rogers.williams/folderz/puddle2

or using (thanks to glenn jackman)

ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

awk -F'puddle2_1557936:' '{print $2}'  <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or using only :

IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2

or using in a :

js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2

or using in a :

php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2' 
/home/rogers.williams/folderz/puddle2

cat, grep and cut - translated to python

you need to use os.system module to execute shell command

import os
os.system('command')

if you want to save the output for later use, you need to use subprocess module

import subprocess
child = subprocess.Popen('command',stdout=subprocess.PIPE,shell=True)
output = child.communicate()[0]

Using cut command to remove multiple columns

You should be able to continue the sequences directly in your existing -f specification.

To skip both 5 and 7, try:

cut -d, -f-4,6-6,8-

As you're skipping a single sequential column, this can also be written as:

cut -d, -f-4,6,8-

To keep it going, if you wanted to skip 5, 7, and 11, you would use:

cut -d, -f-4,6-6,8-10,12-

To put it into a more-clear perspective, it is easier to visualize when you use starting/ending columns which go on the beginning/end of the sequence list, respectively. For instance, the following will print columns 2 through 20, skipping columns 5 and 11:

cut -d, -f2-4,6-10,12-20

So, this will print "2 through 4", skip 5, "6 through 10", skip 11, and then "12 through 20".

How to execute the start script with Nodemon

If you have nodemon installed globally, simply running nodemon in your project will automatically run the start script from package.json.

For example:

"scripts": {
  "start": "node src/server.js"
},

From the nodemon documentation:

nodemon will also search for the scripts.start property in package.json (as of nodemon 1.1.x).

How to count digits, letters, spaces for a string in Python?

sample = ("Python 3.2 is very easy") #sample string  
letters = 0  # initiating the count of letters to 0
numeric = 0  # initiating the count of numbers to 0

        for i in sample:  
            if i.isdigit():      
                numeric +=1      
            elif i.isalpha():    
                letters +=1    
            else:    
               pass  
letters  
numeric  

Get size of all tables in database

Riffing on @Mark answer above, added the @updateusage='true' to force the latest size stats (https://msdn.microsoft.com/en-us/library/ms188776.aspx):

        SET NOCOUNT ON
        DECLARE @TableInfo TABLE (tablename varchar(255), rowcounts int, reserved varchar(255), DATA varchar(255), index_size varchar(255), unused varchar(255))
        DECLARE @cmd1 varchar(500)
        SET @cmd1 = 'exec sp_spaceused @objname =''?'', @updateusage =''true'' '

        INSERT INTO @TableInfo (tablename,rowcounts,reserved,DATA,index_size,unused)
        EXEC sp_msforeachtable @command1=@cmd1 
SELECT * FROM @TableInfo ORDER BY Convert(int,Replace(DATA,' KB','')) DESC

Map HTML to JSON

Thank you @Gorge Reith. Working off the solution provided by @George Reith, here is a function that furthers (1) separates out the individual 'hrefs' links (because they might be useful), (2) uses attributes as keys (since attributes are more descriptive), and (3) it's usable within Node.js without needing Chrome by using the 'jsdom' package:

const jsdom = require('jsdom') // npm install jsdom provides in-built Window.js without needing Chrome


// Function to map HTML DOM attributes to inner text and hrefs
function mapDOM(html_string, json) {
    treeObject = {}

    // IMPT: use jsdom because of in-built Window.js
    // DOMParser() does not provide client-side window for element access if coding in Nodejs
    dom = new jsdom.JSDOM(html_string)
    document = dom.window.document
    element = document.firstChild

    // Recursively loop through DOM elements and assign attributes to inner text object
    // Why attributes instead of elements? 1. attributes more descriptive, 2. usually important and lesser
    function treeHTML(element, object) {
        var nodeList = element.childNodes;
        if (nodeList != null) {
           if (nodeList.length) {
               object[element.nodeName] = []  // IMPT: empty [] array for non-text recursivable elements (see below)
               for (var i = 0; i < nodeList.length; i++) {
                   // if final text
                   if (nodeList[i].nodeType == 3) {
                       if (element.attributes != null) {
                           for (var j = 0; j < element.attributes.length; j++) {
                                if (element.attributes[j].nodeValue !== '' && 
                                    nodeList[i].nodeValue !== '') {
                                    if (element.attributes[j].name === 'href') { // separate href
                                        object[element.attributes[j].name] = element.attributes[j].nodeValue;
                                    } else {
                                        object[element.attributes[j].nodeValue] = nodeList[i].nodeValue;
                                    }

                                }
                           }
                       }
                   // else if non-text then recurse on recursivable elements
                   } else {
                       object[element.nodeName].push({}); // if non-text push {} into empty [] array
                       treeHTML(nodeList[i], object[element.nodeName][object[element.nodeName].length -1]);
                   }
               }
           }
        }
    }
    treeHTML(element, treeObject);

    return (json) ? JSON.stringify(treeObject) : treeObject;
}

Executing multiple commands from a Windows cmd script

Using double ampersands will run the second command, only if the first one succeeds:

cd Desktop/project-directory && atom .

Where as, using only one ampersand will attempt to run both commands, even if the first fails:

cd Desktop/project-directory & atom .

Xcode "Device Locked" When iPhone is unlocked

2018

The fastest way for now i found is:

1) Go to Window -> devices (changed the hotkey in xcode to CMD+P for me)
2) Press unpair on the device. enter image description here
3) Press trust in iPhone.
4) Build again or Run without building (Ctrl+CMD+R)

Difference between break and continue statement

The break statement exists the current looping control structure and jumps behind it while the continue exits too but jumping back to the looping condition.

Get each line from textarea

For a <br> on each line, use

<textarea wrap="physical"></textarea>

You will get \ns in the value of the textarea. Then, use the nl2br() function to create <br>s, or you can explode() it for <br> or \n.

Hope this helps

How to create empty constructor for data class in Kotlin Android

If you give default values to all the fields - empty constructor is generated automatically by Kotlin.

data class User(var id: Long = -1,
                var uniqueIdentifier: String? = null)

and you can simply call:

val user = User()

Best cross-browser method to capture CTRL+S with JQuery?

You could use a shortcut library to handle the browser specific stuff.

shortcut.add("Ctrl+S",function() {
    alert("Hi there!");
});

Convert char array to single int?

I'll just leave this here for people interested in an implementation with no dependencies.

inline int
stringLength (char *String)
    {
    int Count = 0;
    while (*String ++) ++ Count;
    return Count;
    }

inline int
stringToInt (char *String)
    {
    int Integer = 0;
    int Length = stringLength(String);
    for (int Caret = Length - 1, Digit = 1; Caret >= 0; -- Caret, Digit *= 10)
        {
        if (String[Caret] == '-') return Integer * -1;
        Integer += (String[Caret] - '0') * Digit;
        }

    return Integer;
    }

Works with negative values, but can't handle non-numeric characters mixed in between (should be easy to add though). Integers only.

How to set height property for SPAN

Why do you need a span in this case? If you want to style the height could you just use a div? You might try a div with display: inline, although that might have the same issue since you'd in effect be doing the same thing as a span.

How can I output a UTF-8 CSV in PHP that Excel will read properly?

Does the problem still occur when you save it as a .txt file and them open that in excel with comma as a delimiter?

The problem might not be the encoding at all, it might just be that the file isn't a perfect CSV according to excel standards.

How to set background color of HTML element using css properties in JavaScript

_x000D_
_x000D_
var element = document.getElementById('element');_x000D_
_x000D_
element.onclick = function() {_x000D_
  element.classList.add('backGroundColor');_x000D_
  _x000D_
  setTimeout(function() {_x000D_
    element.classList.remove('backGroundColor');_x000D_
  }, 2000);_x000D_
};
_x000D_
.backGroundColor {_x000D_
    background-color: green;_x000D_
}
_x000D_
<div id="element">Click Me</div>
_x000D_
_x000D_
_x000D_

Negative matching using grep (match lines that do not contain foo)

You can also use awk for these purposes, since it allows you to perform more complex checks in a clearer way:

Lines not containing foo:

awk '!/foo/'

Lines containing neither foo nor bar:

awk '!/foo/ && !/bar/'

Lines containing neither foo nor bar which contain either foo2 or bar2:

awk '!/foo/ && !/bar/ && (/foo2/ || /bar2/)'

And so on.

How to convert a Java String to an ASCII byte array?

I found the solution. Actually Base64 class is not available in Android. Link is given below for more information.

byte[] byteArray;                                                  
     byteArray= json.getBytes(StandardCharsets.US_ASCII);
    String encoded=Base64.encodeBytes(byteArray);
    userLogin(encoded);

Here is the link for Base64 class: http://androidcodemonkey.blogspot.com/2010/03/how-to-base64-encode-decode-android.html

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

On a Windows machine I was able to log to to ssh from git bash with
ssh vagrant@VAGRANT_SERVER_IP without providing a password

Using Bitvise SSH client on window
Server host: VAGRANT_SERVER_IP
Server port: 22
Username: vagrant
Password: vagrant

Get response from PHP file using AJAX

The good practice is to use like this:

$.ajax({
    type: "POST",
    url: "/ajax/request.html",
    data: {action: 'test'},
    dataType:'JSON', 
    success: function(response){
        console.log(response.blablabla);
        // put on console what server sent back...
    }
});

and the php part is:

<?php
    if(isset($_POST['action']) && !empty($_POST['action'])) {
        echo json_encode(array("blablabla"=>$variable));
    }
?>

Where is shared_ptr?

There are at least three places where you may find shared_ptr:

  1. If your C++ implementation supports C++11 (or at least the C++11 shared_ptr), then std::shared_ptr will be defined in <memory>.

  2. If your C++ implementation supports the C++ TR1 library extensions, then std::tr1::shared_ptr will likely be in <memory> (Microsoft Visual C++) or <tr1/memory> (g++'s libstdc++). Boost also provides a TR1 implementation that you can use.

  3. Otherwise, you can obtain the Boost libraries and use boost::shared_ptr, which can be found in <boost/shared_ptr.hpp>.

File name without extension name VBA

To be verbose it the removal of extension is demonstrated for workbooks.. which now have a variety of extensions . . a new unsaved Book1 has no ext . works the same for files

Function WorkbookIsOpen(FWNa$, Optional AnyExt As Boolean = False) As Boolean

Dim wWB As Workbook, WBNa$, PD%
FWNa = Trim(FWNa)
If FWNa <> "" Then
    For Each wWB In Workbooks
        WBNa = wWB.Name
        If AnyExt Then
            PD = InStr(WBNa, ".")
            If PD > 0 Then WBNa = Left(WBNa, PD - 1)
            PD = InStr(FWNa, ".")
            If PD > 0 Then FWNa = Left(FWNa, PD - 1)
            '
            ' the alternative of using split..  see commented out  below
            ' looks neater but takes a bit longer then the pair of instr and left
            ' VBA does about 800,000  of these small splits/sec
            ' and about 20,000,000  Instr Lefts per sec
            ' of course if not checking for other extensions they do not matter
            ' and to any reasonable program
            ' THIS DISCUSSIONOF TIME TAKEN DOES NOT MATTER
            ' IN doing about doing 2000 of this routine per sec

            ' WBNa = Split(WBNa, ".")(0)
            'FWNa = Split(FWNa, ".")(0)
        End If

        If WBNa = FWNa Then
            WorkbookIsOpen = True
            Exit Function
        End If
    Next wWB
End If

End Function

How to remove leading zeros from alphanumeric text?

If you are using Kotlin This is the only code that you need:

yourString.trimStart('0')

What is the different between RESTful and RESTless

Here are summarized the key differences between RESTful and RESTless web services:

1. Protocol

  • RESTful services use REST architectural style,
  • RESTless services use SOAP protocol.

2. Business logic / Functionality

  • RESTful services use URL to expose business logic,
  • RESTless services use the service interface to expose business logic.

3. Security

  • RESTful inherits security from the underlying transport protocols,
  • RESTless defines its own security layer, thus it is considered as more secure.

4. Data format

  • RESTful supports various data formats such as HTML, JSON, text, etc,
  • RESTless supports XML format.

5. Flexibility

  • RESTful is easier and flexible,
  • RESTless is not as easy and flexible.

6. Bandwidth

  • RESTful services consume less bandwidth and resource,
  • RESTless services consume more bandwidth and resources.

How do I instantiate a Queue object in java?

Queue is an interface. You can't instantiate an interface directly except via an anonymous inner class. Typically this isn't what you want to do for a collection. Instead, choose an existing implementation. For example:

Queue<Integer> q = new LinkedList<Integer>();

or

Queue<Integer> q = new ArrayDeque<Integer>();

Typically you pick a collection implementation by the performance and concurrency characteristics you're interested in.

How to convert a column number (e.g. 127) into an Excel column (e.g. AA)

I wanted to throw in my static class I use, for interoping between col index and col Label. I use a modified accepted answer for my ColumnLabel Method

public static class Extensions
{
    public static string ColumnLabel(this int col)
    {
        var dividend = col;
        var columnLabel = string.Empty;
        int modulo;

        while (dividend > 0)
        {
            modulo = (dividend - 1) % 26;
            columnLabel = Convert.ToChar(65 + modulo).ToString() + columnLabel;
            dividend = (int)((dividend - modulo) / 26);
        } 

        return columnLabel;
    }
    public static int ColumnIndex(this string colLabel)
    {
        // "AD" (1 * 26^1) + (4 * 26^0) ...
        var colIndex = 0;
        for(int ind = 0, pow = colLabel.Count()-1; ind < colLabel.Count(); ++ind, --pow)
        {
            var cVal = Convert.ToInt32(colLabel[ind]) - 64; //col A is index 1
            colIndex += cVal * ((int)Math.Pow(26, pow));
        }
        return colIndex;
    }
}

Use this like...

30.ColumnLabel(); // "AD"
"AD".ColumnIndex(); // 30

How to upload files on server folder using jsp

I found the similar problem and found the solution and i have blogged about how to upload the file using JSP , In that example i have used the absolute path. Note that if you want to route to some other URL based location you can put a ESB like WSO2 ESB

Change first commit of project with Git?

git rebase -i allows you to conveniently edit any previous commits, except for the root commit. The following commands show you how to do this manually.

# tag the old root, "git rev-list ..." will return the hash of first commit
git tag root `git rev-list HEAD | tail -1`

# switch to a new branch pointing at the first commit
git checkout -b new-root root

# make any edits and then commit them with:
git commit --amend

# check out the previous branch (i.e. master)
git checkout @{-1}

# replace old root with amended version
git rebase --onto new-root root

# you might encounter merge conflicts, fix any conflicts and continue with:
# git rebase --continue

# delete the branch "new-root"
git branch -d new-root

# delete the tag "root"
git tag -d root

Android Studio gradle takes too long to build

1) My build time severely increased after i added some new library dependencies to my gradle file, what turned out that i need to use multidex after that. And when i set up multidex correctly then my build times went up to 2-3 minutes. So if you want faster build times, avoid using multidex, and as far as possible, reduce the number of library dependencies.

2) Also you can try enabling "offline work" in android studio, like suggested here, that makes sense. This will not refetch libraries every time you make a build. Perhaps slow connection or proxy/vpn usage with "offline work" disabled may lead to slow build times.

3) google services - as mentioned here, dont use the whole bundle, use only the needed parts of it.

return string with first match Regex

I'd go with:

r = re.search("\d+", ch)
result = return r.group(0) if r else ""

re.search only looks for the first match in the string anyway, so I think it makes your intent slightly more clear than using findall.

HTML-parser on Node.js

If you want to build DOM you can use jsdom.

There's also cheerio, it has the jQuery interface and it's a lot faster than older versions of jsdom, although these days they are similar in performance.

You might wanna have a look at htmlparser2, which is a streaming parser, and according to its benchmark, it seems to be faster than others, and no DOM by default. It can also produce a DOM, as it is also bundled with a handler that creates a DOM. This is the parser that is used by cheerio.

parse5 also looks like a good solution. It's fairly active (11 days since the last commit as of this update), WHATWG-compliant, and is used in jsdom, Angular, and Polymer.

And if you want to parse HTML for web scraping, you can use YQL1. There is a node module for it. YQL I think would be the best solution if your HTML is from a static website, since you are relying on a service, not your own code and processing power. Though note that it won't work if the page is disallowed by the robot.txt of the website, YQL won't work with it.

If the website you're trying to scrape is dynamic then you should be using a headless browser like phantomjs. Also have a look at casperjs, if you're considering phantomjs. And you can control casperjs from node with SpookyJS.

Beside phantomjs there's zombiejs. Unlike phantomjs that cannot be embedded in nodejs, zombiejs is just a node module.

There's a nettuts+ toturial for the latter solutions.


1 Since Aug. 2014, YUI library, which is a requirement for YQL, is no longer actively maintained, source

Convert dictionary to bytes and back again python?

This should work:

s=json.dumps(variables)
variables2=json.loads(s)
assert(variables==variables2)

Get environment value in controller

As @Rajib pointed out, You can't access your env variables using config('myVariable')

  1. You have to add the variable to .env file first.
  2. Add the variable to some config file in config directory. I usually add to config/app.php
  3. Once done, will access them like Config::get('fileWhichContainsVariable.Variable'); using the Config Facade

Probably You will have to clear config cache using php artisan config:clear AND you will also have to restart server.

How do I convert a byte array to Base64 in Java?

Additionally, for our Android friends (API Level 8):

import android.util.Base64

...

Base64.encodeToString(bytes, Base64.DEFAULT);

How to create a library project in Android Studio and an application project that uses the library project

Check out this link about multi project setups.

Some things to point out, make sure you have your settings.gradle updated to reference both the app and library modules.

settings.gradle: include ':app', ':libraries:lib1', ':libraries:lib2'

Also make sure that the app's build.gradle has the followng:

dependencies {
     compile project(':libraries:lib1')
}

You should have the following structure:

 MyProject/
  | settings.gradle
  + app/
    | build.gradle
  + libraries/
    + lib1/
       | build.gradle
    + lib2/
       | build.gradle

The app's build.gradle should use the com.android.application plugin while any libraries' build.gradle should use the com.android.library plugin.

The Android Studio IDE should update if you're able to build from the command line with this setup.

Python "expected an indented block"

Starting with elif option == 2:, you indented one time too many. In a decent text editor, you should be able to highlight these lines and press Shift+Tab to fix the issue.

Additionally, there is no statement after for x in range(x, 1, 1):. Insert an indented pass to do nothing in the for loop.

Also, in the first line, you wrote option == 1. == tests for equality, but you meant = ( a single equals sign), which assigns the right value to the left name, i.e.

option = 1

MSBuild doesn't copy references (DLL files) if using project dependencies in solution

I just had the exact same problem and it turned out to be caused by the fact that 2 projects in the same solution were referencing a different version of the 3rd party library.

Once I corrected all the references everything worked perfectly.

How do I remove accents from characters in a PHP string?

Merged Cazuma Nii Cavalcanti's implementation with Junior Mayhé's char list, hoping to save some time for some of you.

function stripAccents($str) {
    return strtr(utf8_decode($str), utf8_decode('ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïñòóôõöøùúûüýÿAaAaAaCcCcCcCcDdÐdEeEeEeEeEeGgGgGgGgHhHhIiIiIiIiIi??JjKkLlLlLl??LlNnNnNn?OoOoOoŒœRrRrRrSsSsSsŠšTtTtTtUuUuUuUuUuUuWwYyŸZzZzŽž?ƒOoUuAaIiOoUuUuUuUuUu??????'), 'AAAAAAAECEEEEIIIIDNOOOOOOUUUUYsaaaaaaaeceeeeiiiinoooooouuuuyyAaAaAaCcCcCcCcDdDdEeEeEeEeEeGgGgGgGgHhHhIiIiIiIiIiIJijJjKkLlLlLlLlllNnNnNnnOoOoOoOEoeRrRrRrSsSsSsSsTtTtTtUuUuUuUuUuUuWwYyYZzZzZzsfOoUuAaIiOoUuUuUuUuUuAaAEaeOo');
}

How do I remove a substring from the end of a string in Python?

You can use split:

'abccomputer.com'.split('.com',1)[0]
# 'abccomputer'

Find which version of package is installed with pip

The python function returning just the package version in a machine-readable format:

from importlib.metadata import version 
version('numpy')

Prior to python 3.8:

pip install importlib-metadata 
from importlib_metadata import version
version('numpy')

The bash equivalent (here also invoked from python) would be much more complex (but more robust - see caution below):

import subprocess
def get_installed_ver(pkg_name):
    bash_str="pip freeze | grep -w %s= | awk -F '==' {'print $2'} | tr -d '\n'" %(pkg_name)
    return(subprocess.check_output(bash_str, shell=True).decode())

Sample usage:

# pkg_name="xgboost"
# pkg_name="Flask"
# pkg_name="Flask-Caching"
pkg_name="scikit-learn"

print(get_installed_ver(pkg_name))
>>> 0.22

Note that in both cases pkg_name parameter should contain package name in the format as returned by pip freeze and not as used during import, e.g. scikit-learn not sklearn or Flask-Caching, not flask_caching.

Note that while invoking pip freeze in bash version may seem inefficient, only this method proves to be sufficiently robust to package naming peculiarities and inconsistencies (e.g. underscores vs dashes, small vs large caps, and abbreviations such as sklearn vs scikit-learn).

Caution: in complex environments both variants can return surprise version numbers, inconsistent with what you can actually get during import.

One such problem arises when there are other versions of the package hidden in a user site-packages subfolder. As an illustration of the perils of using version() here's a situation I encountered:

$ pip freeze | grep lightgbm
lightgbm==2.3.1

and

$ python -c "import lightgbm; print(lightgbm.__version__)"
2.3.1

vs.

$ python -c "from importlib_metadata import version; print(version(\"lightgbm\"))"
2.2.3

until you delete the subfolder with the old version (here 2.2.3) from the user folder (only one would normally be preserved by `pip` - the one installed as last with the `--user` switch):

$ ls /home/jovyan/.local/lib/python3.7/site-packages/lightgbm*
/home/jovyan/.local/lib/python3.7/site-packages/lightgbm-2.2.3.dist-info
/home/jovyan/.local/lib/python3.7/site-packages/lightgbm-2.3.1.dist-info

Another problem is having some conda-installed packages in the same environment. If they share dependencies with your pip-installed packages, and versions of these dependencies differ, you may get downgrades of your pip-installed dependencies.

To illustrate, the latest version of numpy available in PyPI on 04-01-2020 was 1.18.0, while at the same time Anaconda's conda-forge channel had only 1.17.3 version on numpy as their latest. So when you installed a basemap package with conda (as second), your previously pip-installed numpy would get downgraded by conda to 1.17.3, and version 1.18.0 would become unavailable to the import function. In this case version() would be right, and pip freeze/conda list wrong:

$ python -c "from importlib_metadata import version; print(version(\"numpy\"))"
1.17.3

$ python -c "import numpy; print(numpy.__version__)"
1.17.3

$ pip freeze | grep numpy
numpy==1.18.0

$ conda list | grep numpy
numpy                     1.18.0                   pypi_0    pypi

Large Numbers in Java

Depending on what you're doing you might like to take a look at GMP (gmplib.org) which is a high-performance multi-precision library. To use it in Java you need JNI wrappers around the binary library.

See some of the Alioth Shootout code for an example of using it instead of BigInteger to calculate Pi to an arbitrary number of digits.

https://benchmarksgame-team.pages.debian.net/benchmarksgame/program/pidigits-java-2.html

How to use BeginInvoke C#

I guess your code relates to Windows Forms.
You call BeginInvoke if you need something to be executed asynchronously in the UI thread: change control's properties in most of the cases.
Roughly speaking this is accomplished be passing the delegate to some procedure which is being periodically executed. (message loop processing and the stuff like that)

If BeginInvoke is called for Delegate type the delegate is just invoked asynchronously.
(Invoke for the sync version.)

If you want more universal code which works perfectly for WPF and WinForms you can consider Task Parallel Library and running the Task with the according context. (TaskScheduler.FromCurrentSynchronizationContext())

And to add a little to already said by others: Lambdas can be treated either as anonymous methods or expressions.
And that is why you cannot just use var with lambdas: compiler needs a hint.

UPDATE:

this requires .Net v4.0 and higher

// This line must be called in UI thread to get correct scheduler
var scheduler = System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext();

// this can be called anywhere
var task = new System.Threading.Tasks.Task( () => someformobj.listBox1.SelectedIndex = 0);

// also can be called anywhere. Task  will be scheduled for execution.
// And *IF I'm not mistaken* can be (or even will be executed synchronously)
// if this call is made from GUI thread. (to be checked) 
task.Start(scheduler);

If you started the task from other thread and need to wait for its completition task.Wait() will block calling thread till the end of the task.

Read more about tasks here.

How do I force Internet Explorer to render in Standards Mode and NOT in Quirks?

It's possible that the HTML5 Doctype is causing you problems with those older browsers. It could also be down to something funky related to the HTML5 shiv.

You could try switching to one of the XHTML doctypes and changing your markup accordingly, at least temporarily. This might allow you to narrow the problem down.

Is your design breaking when those IEs switch to quirks mode? If it's your CSS causing things to display strangely, it might be worth working on the CSS so the site looks the same even when the browsers switch modes.

Eclipse C++ : "Program "g++" not found in PATH"

WINDOWS 7

If there is anyone new reading this, make sure to simply try a clean install of mingw before any of this. It will save you sooooo much time if that is your problem.

I opened up wingw installer, selected every program for removal, apply changes (under installation tab, upper left corner), closed out, went back in and installed every file (in "Basic Setup" section) availible. after that eclipse worked fine using "MinGW GCC" toolchain when starting a new C++ project.

I hope this works for someone else. If not, I would do a reinstall of JDK (Java Developer's Kit) and ECLIPSE as well. I have a 64bit system but I could only get the 32bit versions of Eclipse and JDK to work together.

How to use mod operator in bash?

This might be off-topic. But for the wget in for loop, you can certainly do

curl -O http://example.com/search/link[1-600]

AngularJS performs an OPTIONS HTTP request for a cross-origin resource

Your service must answer an OPTIONS request with headers like these:

Access-Control-Allow-Origin: [the same origin from the request]
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: [the same ACCESS-CONTROL-REQUEST-HEADERS from request]

Here is a good doc: http://www.html5rocks.com/en/tutorials/cors/#toc-adding-cors-support-to-the-server

Jenkins - passing variables between jobs?

I figured it out!

With almost 2 hours worth of trial and error, i figured it out.

This WORKS and is what you do to pass variables to remote job:

    def handle = triggerRemoteJob(remoteJenkinsName: 'remoteJenkins', job: 'RemoteJob' paramters: "param1=${env.PARAM1}\nparam2=${env.param2}")

Use \n to separate two parameters, no spaces..

As opposed to parameters: '''someparams'''

we use paramters: "someparams"

the " ... " is what gets us the values of the desired variables. (These are double quotes, not two single quotes)

the ''' ... ''' or ' ... ' will not get us those values. (Three single quotes or just single quotes)

All parameters here are defined in environment{} block at the start of the pipeline and are modified in stages>steps>scripts wherever necessary.

I also tested and found that when you use " ... " you cannot use something like ''' ... "..." ''' or "... '..'..." or any combination of it...

The catch here is that when you are using "..." in parameters section, you cannot pass a string parameter; for example This WILL NOT WORK:

    def handle = triggerRemoteJob(remoteJenkinsName: 'remoteJenkins', job: 'RemoteJob' paramters: "param1=${env.PARAM1}\nparam2='param2'")

if you want to pass something like the one above, you will need to set an environment variable param2='param2' and then use ${env.param2} in the parameters section of remote trigger plugin step

How to install and run phpize

For recent versions of Debian/Ubuntu (Debian 9+ or Ubuntu 16.04+) install the php-dev dependency package, which will automatically install the correct version of php{x}-dev for your distribution:

sudo apt install php-dev

Older versions of Debian/Ubuntu:

For PHP 5, it's in the php5-dev package.

sudo apt-get install php5-dev

For PHP 7.x (from rahilwazir comment):

sudo apt-get install php7.x-dev

RHEL/CentOS/yum

yum install php-devel # see comments

How to update the constant height constraint of a UIView programmatically?

Drag the constraint into your VC as an IBOutlet. Then you can change its associated value (and other properties; check the documentation):

@IBOutlet myConstraint : NSLayoutConstraint!
@IBOutlet myView : UIView!

func updateConstraints() {
    // You should handle UI updates on the main queue, whenever possible
    DispatchQueue.main.async {
        self.myConstraint.constant = 10
        self.myView.layoutIfNeeded()
    }
}

PostgreSQL Autoincrement

You can use any other integer data type, such as smallint.

Example :

CREATE SEQUENCE user_id_seq;
CREATE TABLE user (
    user_id smallint NOT NULL DEFAULT nextval('user_id_seq')
);
ALTER SEQUENCE user_id_seq OWNED BY user.user_id;

Better to use your own data type, rather than user serial data type.

Equivalent of shell 'cd' command to change the working directory?

Further into direction pointed out by Brian and based on sh (1.0.8+)

from sh import cd, ls

cd('/tmp')
print ls()

How to detect Safari, Chrome, IE, Firefox and Opera browser?

Detecting Browser and Its version

This code snippet is based on the article from MDN. Where they gave a brief hint about various keywords that can be used to detect the browser name.

reference

The data shown in the image above is not sufficient for detecting all the browsers e.g. userAgent of Firefox will have Fxios as a keyword rather than Firefox.

A few changes are also done to detect browsers like Edge and UCBrowser

The code is currently tested for the following browsers by changing userAgent with the help of dev-tools (How to change userAgent):

  • FireFox
  • Chrome
  • IE
  • Edge
  • Opera
  • Safari
  • UCBrowser

_x000D_
_x000D_
getBrowser = () => {
    const userAgent = navigator.userAgent;
    let browser = "unkown";
    // Detect browser name
    browser = (/ucbrowser/i).test(userAgent) ? 'UCBrowser' : browser;
    browser = (/edg/i).test(userAgent) ? 'Edge' : browser;
    browser = (/googlebot/i).test(userAgent) ? 'GoogleBot' : browser;
    browser = (/chromium/i).test(userAgent) ? 'Chromium' : browser;
    browser = (/firefox|fxios/i).test(userAgent) && !(/seamonkey/i).test(userAgent) ? 'Firefox' : browser;
    browser = (/; msie|trident/i).test(userAgent) && !(/ucbrowser/i).test(userAgent) ? 'IE' : browser;
    browser = (/chrome|crios/i).test(userAgent) && !(/opr|opera|chromium|edg|ucbrowser|googlebot/i).test(userAgent) ? 'Chrome' : browser;;
    browser = (/safari/i).test(userAgent) && !(/chromium|edg|ucbrowser|chrome|crios|opr|opera|fxios|firefox/i).test(userAgent) ? 'Safari' : browser;
    browser = (/opr|opera/i).test(userAgent) ? 'Opera' : browser;

    // detect browser version
    switch (browser) {
        case 'UCBrowser': return `${browser}/${browserVersion(userAgent,/(ucbrowser)\/([\d\.]+)/i)}`;
        case 'Edge': return `${browser}/${browserVersion(userAgent,/(edge|edga|edgios|edg)\/([\d\.]+)/i)}`;
        case 'GoogleBot': return `${browser}/${browserVersion(userAgent,/(googlebot)\/([\d\.]+)/i)}`;
        case 'Chromium': return `${browser}/${browserVersion(userAgent,/(chromium)\/([\d\.]+)/i)}`;
        case 'Firefox': return `${browser}/${browserVersion(userAgent,/(firefox|fxios)\/([\d\.]+)/i)}`;
        case 'Chrome': return `${browser}/${browserVersion(userAgent,/(chrome|crios)\/([\d\.]+)/i)}`;
        case 'Safari': return `${browser}/${browserVersion(userAgent,/(safari)\/([\d\.]+)/i)}`;
        case 'Opera': return `${browser}/${browserVersion(userAgent,/(opera|opr)\/([\d\.]+)/i)}`;
        case 'IE': const version = browserVersion(userAgent,/(trident)\/([\d\.]+)/i);
            // IE version is mapped using trident version 
            // IE/8.0 = Trident/4.0, IE/9.0 = Trident/5.0
            return version ? `${browser}/${parseFloat(version) + 4.0}` : `${browser}/7.0`;
        default: return `unknown/0.0.0.0`;
    }
}

browserVersion = (userAgent,regex) => {
    return userAgent.match(regex) ? userAgent.match(regex)[2] : null;
}

console.log(getBrowser());
_x000D_
_x000D_
_x000D_

Dictionary with list of strings as value

Just create a new array in your dictionary

Dictionary<string, List<string>> myDic = new Dictionary<string, List<string>>();
myDic.Add(newKey, new List<string>(existingList));

Center a 'div' in the middle of the screen, even when the page is scrolled up or down?

Correct Method is

.PopupPanel
{
    border: solid 1px black;
    position: fixed;
    left: 50%;
    top: 50%;
    background-color: white;
    z-index: 100;
    height: 400px;
    margin-top: -200px;

    width: 600px;
    margin-left: -300px;
}

Set order of columns in pandas dataframe

You can use this:

columnsTitles = ['onething', 'secondthing', 'otherthing']

frame = frame.reindex(columns=columnsTitles)

Reset push notification settings for app

As already noted the approach for resetting the notification state for an app on a device is changed for iOS5 an newer.

This works for me on iOS6:

  • Remove the app from the device
  • Set the device datetime two days or more ahead
  • Restart the device
  • Set the device datetime two days or more ahead
  • Restart the device
  • Install and run the app again

However this will only make the initial prompt appear again - it will not remove any other push state related stuff.

Git reset --hard and push to remote repository

Instead of fixing your "master" branch, it's way easier to swap it with your "desired-master" by renaming the branches. See https://stackoverflow.com/a/2862606/2321594. This way you wouldn't even leave any trace of multiple revert logs.

Multiplying Two Columns in SQL Server

Syntax:

SELECT <Expression>[Arithmetic_Operator]<expression>...
 FROM [Table_Name] 
 WHERE [expression];
  1. Expression : Expression made up of a single constant, variable, scalar function, or column name and can also be the pieces of a SQL query that compare values against other values or perform arithmetic calculations.
  2. Arithmetic_Operator : Plus(+), minus(-), multiply(*), and divide(/).
  3. Table_Name : Name of the table.

Check if not nil and not empty in Rails shortcut?

There's a method that does this for you:

def show
  @city = @user.city.present?
end

The present? method tests for not-nil plus has content. Empty strings, strings consisting of spaces or tabs, are considered not present.

Since this pattern is so common there's even a shortcut in ActiveRecord:

def show
  @city = @user.city?
end

This is roughly equivalent.

As a note, testing vs nil is almost always redundant. There are only two logically false values in Ruby: nil and false. Unless it's possible for a variable to be literal false, this would be sufficient:

if (variable)
  # ...
end

This is preferable to the usual if (!variable.nil?) or if (variable != nil) stuff that shows up occasionally. Ruby tends to wards a more reductionist type of expression.

One reason you'd want to compare vs. nil is if you have a tri-state variable that can be true, false or nil and you need to distinguish between the last two states.

Passing variable from Form to Module in VBA

Don't declare the variable in the userform. Declare it as Public in the module.

Public pass As String

In the Userform

Private Sub CommandButton1_Click()
    pass = UserForm1.TextBox1
    Unload UserForm1
End Sub

In the Module

Public pass As String

Public Sub Login()
    '
    '~~> Rest of the code
    '
    UserForm1.Show
    driver.findElementByName("PASSWORD").SendKeys pass
    '
    '~~> Rest of the code
    '
End Sub

You might want to also add an additional check just before calling the driver.find... line?

If Len(Trim(pass)) <> 0 Then

This will ensure that a blank string is not passed.

REST URI convention - Singular or plural name of resource while creating it

Plural

  • Simple - all urls start with the same prefix
  • Logical - orders/ gets an index list of orders.
  • Standard - Most widely adopted standard followed by the overwhelming majority of public and private APIs.

For example:

GET /resources - returns a list of resource items

POST /resources - creates one or many resource items

PUT /resources - updates one or many resource items

PATCH /resources - partially updates one or many resource items

DELETE /resources - deletes all resource items

And for single resource items:

GET /resources/:id - returns a specific resource item based on :id parameter

POST /resources/:id - creates one resource item with specified id (requires validation)

PUT /resources/:id - updates a specific resource item

PATCH /resources/:id - partially updates a specific resource item

DELETE /resources/:id - deletes a specific resource item

To the advocates of singular, think of it this way: Would you ask a someone for an order and expect one thing, or a list of things? So why would you expect a service to return a list of things when you type /order?

"Active Directory Users and Computers" MMC snap-in for Windows 7?

I'm not allowed to use Turn Windows features on or off, but running all of these commands in an elevated command prompt (Run as Administrator) finally got Active Directory Users and Computers to show up under Administrative Tools on the start menu:

dism /online /enable-feature /featurename:RemoteServerAdministrationTools
dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles
dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD
dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD-DS
dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD-DS-SnapIns
dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD-DS-AdministrativeCenter
dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD-DS-NIS
dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD-LDS
dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD-Powershell

I had downloaded and installed the RSAT (Windows 7 Link, Windows Vista Link) before running these commands.

It's quite likely that this is more than you features than you actually need, but at least it's not too few.

Import CSV file as a pandas DataFrame

%cd C:\Users\asus\Desktop\python
import pandas as pd
df = pd.read_csv('value.txt')
df.head()
    Date    price   factor_1    factor_2
0   2012-06-11  1600.20 1.255   1.548
1   2012-06-12  1610.02 1.258   1.554
2   2012-06-13  1618.07 1.249   1.552
3   2012-06-14  1624.40 1.253   1.556
4   2012-06-15  1626.15 1.258   1.552

Remove Item in Dictionary based on Value

Here is a method you can use:

    public static void RemoveAllByValue<K, V>(this Dictionary<K, V> dictionary, V value)
    {
        foreach (var key in dictionary.Where(
                kvp => EqualityComparer<V>.Default.Equals(kvp.Value, value)).
                Select(x => x.Key).ToArray())
            dictionary.Remove(key);
    }

How to convert Javascript datetime to C# datetime?

You can also send Js time to C# with Moment.js Library :

JavaScript : var dateString = moment(new Date()).format('LLLL')

C# : DateTime.Parse(dateString);

Google server putty connect 'Disconnected: No supported authentication methods available (server sent: publickey)

I got this error because I had forgotten to add my username behind the key in the GCE metadata section. For instance, you are meant to add an entry into the metadata section which looks like this:

sshKeys    username:key

I forgot the username: part and thus when I tried to login with that username, I got the no supported auth methods error.

Or, to turn off the ssh key requirement entirely, check out my other answer.

Eclipse: The resource is not on the build path of a Java project

You can add the src folder to build path by:

  1. Select Java perspective.
  2. Right click on src folder.
  3. Select Build Path > Use a source folder.

And you are done. Hope this help.

EDIT: Refer to the Eclipse documentation

Understanding the set() function

As an unordered collection type, set([8, 1, 6]) is equivalent to set([1, 6, 8]).

While it might be nicer to display the set contents in sorted order, that would make the repr() call more expensive.

Internally, the set type is implemented using a hash table: a hash function is used to separate items into a number of buckets to reduce the number of equality operations needed to check if an item is part of the set.

To produce the repr() output it just outputs the items from each bucket in turn, which is unlikely to be the sorted order.

Swift do-try-catch syntax

enum NumberError: Error {
  case NegativeNumber(number: Int)
  case ZeroNumber
  case OddNumber(number: Int)
}

extension NumberError: CustomStringConvertible {
         var description: String {
         switch self {
             case .NegativeNumber(let number):
                 return "Negative number \(number) is Passed."
             case .OddNumber(let number):
                return "Odd number \(number) is Passed."
             case .ZeroNumber:
                return "Zero is Passed."
      }
   }
}

 func validateEvenNumber(_ number: Int) throws ->Int {
     if number == 0 {
        throw NumberError.ZeroNumber
     } else if number < 0 {
        throw NumberError.NegativeNumber(number: number)
     } else if number % 2 == 1 {
         throw NumberError.OddNumber(number: number)
     }
    return number
}

Now Validate Number :

 do {
     let number = try validateEvenNumber(0)
     print("Valid Even Number: \(number)")
  } catch let error as NumberError {
     print(error.description)
  }

Why is an OPTIONS request sent and can I disable it?

For a developer who understands the reason it exists but needs to access an API that doesn't handle OPTIONS calls without auth, I need a temporary answer so I can develop locally until the API owner adds proper SPA CORS support or I get a proxy API up and running.

I found you can disable CORS in Safari and Chrome on a Mac.

Disable same origin policy in Chrome

Chrome: Quit Chrome, open an terminal and paste this command: open /Applications/Google\ Chrome.app --args --disable-web-security --user-data-dir

Safari: Disabling same-origin policy in Safari

If you want to disable the same-origin policy on Safari (I have 9.1.1), then you only need to enable the developer menu, and select "Disable Cross-Origin Restrictions" from the develop menu.

Getting rid of \n when using .readlines()

I used the strip function to get rid of newline character as split lines was throwing memory errors on 4 gb File.

Sample Code:

with open('C:\\aapl.csv','r') as apple:
    for apps in apple.readlines():
        print(apps.strip())

how to fix the issue "Command /bin/sh failed with exit code 1" in iphone

For me this error was occuring because I changed the version number from 1 to 1.0 and build number from 6 to 1.1 as I pulled the code from source tree. I just changed it back and changed the build number from 6 to 7and it worked fine.

Adding Permissions in AndroidManifest.xml in Android Studio?

It's quite simple.

All you need to do is:

  • Right click above application tag and click on Generate
  • Click on XML tag
  • Click on user-permission
  • Enter the name of your permission.

Delete element in a slice

Rather than thinking of the indices in the [a:]-, [:b]- and [a:b]-notations as element indices, think of them as the indices of the gaps around and between the elements, starting with gap indexed 0 before the element indexed as 0.

enter image description here

Looking at just the blue numbers, it's much easier to see what is going on: [0:3] encloses everything, [3:3] is empty and [1:2] would yield {"B"}. Then [a:] is just the short version of [a:len(arrayOrSlice)], [:b] the short version of [0:b] and [:] the short version of [0:len(arrayOrSlice)]. The latter is commonly used to turn an array into a slice when needed.

How to change default text color using custom theme?

When you create an App, a file called styles.xml will be created in your res/values folder. If you change the styles, you can change the background, text color, etc for all your layouts. That way you don’t have to go into each individual layout and change the it manually.

styles.xml:

<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="Theme.AppBaseTheme" parent="@android:style/Theme.Light">
    <item name="android:editTextColor">#295055</item> 
    <item name="android:textColorPrimary">#295055</item>
    <item name="android:textColorSecondary">#295055</item>
    <item name="android:textColorTertiary">#295055</item>
    <item name="android:textColorPrimaryInverse">#295055</item>
    <item name="android:textColorSecondaryInverse">#295055</item>
    <item name="android:textColorTertiaryInverse">#295055</item>

     <item name="android:windowBackground">@drawable/custom_background</item>        
</style>

<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
    <!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>

parent="@android:style/Theme.Light" is Google’s native colors. Here is a reference of what the native styles are: https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/res/res/values/themes.xml

The default Android style is also called “Theme”. So you calling it Theme probably confused the program.

name="Theme.AppBaseTheme" means that you are creating a style that inherits all the styles from parent="@android:style/Theme.Light". This part you can ignore unless you want to inherit from AppBaseTheme again. = <style name="AppTheme" parent="AppBaseTheme">

@drawable/custom_background is a custom image I put in the drawable’s folder. It is a 300x300 png image.

#295055 is a dark blue color.

My code changes the background and text color. For Button text, please look through Google’s native stlyes (the link I gave u above).

Then in Android Manifest, remember to include the code:

<application
android:theme="@style/Theme.AppBaseTheme">

How to find the last day of the month from date?

Your solution is here..

$lastday = date('t',strtotime('today'));

Visual Studio Code includePath

For everybody that falls off google, in here, this is the fix for VSCode 1.40 (2019):

Open the global settings.json: File > Preferences > Settings

Open the global settings.json: File > Preferences > Settings

Then select the tab 'User', open the section 'Extensions', click on 'C/C++'. Then scroll the right panel till you find a 'Edit in settings.json' button.

Then select the tab 'User', open the section 'Extensions', click on 'C/C++'. Then scroll the right panel till you find a 'Edit in settings.json' button.

Last, you add the "C_Cpp.default.includePath" section. The code provided there is from my own system (Windows 7). You can use it as a base for your own libraries paths. (Remember to change the YOUR USERNAME to your correct system (my case windows) username)
(edit info: There is a problem with the recursion of my approach. VSCode doesn't like multiple definitions for the same thing. I solved it with "C_Cpp.intelliSenseEngine": "Tag Parser" )

Last, you add the "C_Cpp.default.includePath" section. The code provided there is from my own system (Windows 7). You can use it as a base for your own libraries paths. (Remember to change the YOUR USERNAME to your correct system (my case windows) username)

the code before line 7, on the settings.json has nothing to do with arduino or includePath. You may not copy that...

JSON section to add to settings.json:

"C_Cpp.default.includePath": [
        "C:/Program Files (x86)/Arduino/libraries/**",
        "C:/Program Files (x86)/Arduino/hardware/arduino/avr/cores/arduino/**",
        "C:/Program Files (x86)/Arduino/hardware/tools/avr/avr/include/**",
        "C:/Program Files (x86)/Arduino/hardware/tools/avr/lib/gcc/avr/5.4.0/include/**",
        "C:/Program Files (x86)/Arduino/hardware/arduino/avr/variants/standard/**",
        "C:/Users/<YOUR USERNAME>/.platformio/packages/framework-arduinoavr/**",
        "C:/Users/<YOUR USERNAME>/Documents/Arduino/libraries/**",
        "{$workspaceFolder}/libraries/**",
        "{$workspaceFolder}/**"
    ],
"C_Cpp.intelliSenseEngine": "Tag Parser"

Android button background color

Create /res/drawable/button.xml with the following content :

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" android:padding="10dp">
<!-- you can use any color you want I used here gray color-->
 <solid android:color="#90EE90"/> 
    <corners
     android:bottomRightRadius="3dp"
     android:bottomLeftRadius="3dp"
  android:topLeftRadius="3dp"
  android:topRightRadius="3dp"/>
</shape>

And then you can use the following :

<Button
    android:id="@+id/button_save_prefs"
    android:text="@string/save"
    android:background="@drawable/button"/>

How to call a RESTful web service from Android?

Recently discovered that a third party library - Square Retrofit can do the job very well.


Defining REST endpoint

public interface GitHubService {
   @GET("/users/{user}/repos")
   List<Repo> listRepos(@Path("user") String user,Callback<List<User>> cb);
}

Getting the concrete service

RestAdapter restAdapter = new RestAdapter.Builder()
    .setEndpoint("https://api.github.com")
    .build();
GitHubService service = restAdapter.create(GitHubService.class);

Calling the REST endpoint

List<Repo> repos = service.listRepos("octocat",new Callback<List<User>>() { 
    @Override
    public void failure(final RetrofitError error) {
        android.util.Log.i("example", "Error, body: " + error.getBody().toString());
    }
    @Override
    public void success(List<User> users, Response response) {
        // Do something with the List of Users object returned
        // you may populate your adapter here
    }
});

The library handles the json serialization and deserailization for you. You may customize the serialization and deserialization too.

Gson gson = new GsonBuilder()
    .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
    .registerTypeAdapter(Date.class, new DateTypeAdapter())
    .create();

RestAdapter restAdapter = new RestAdapter.Builder()
    .setEndpoint("https://api.github.com")
    .setConverter(new GsonConverter(gson))
    .build();

Sending POST parameters with Postman doesn't work, but sending GET parameters does

Sometimes Version problem in 'Postman' :

I have face the same problem. While sending the data using the oldest version of postman.
That time I have received the empty json data in server side.
And I have fix this problem, Once I uninstall the oldest version of postman and installed with latest version.

How do you monitor network traffic on the iPhone?

Depending on what you want to do runnning it via a Proxy is not ideal. A transparent proxy might work ok as long as the packets do not get tampered with.

I am about to reverse the GPS data that gets transferred from the iPhone to the iPad on iOS 4.3.x to get to the the vanilla data the best way to get a clean Network Dump is to use "tcpdump" and/or "pirni" as already suggested.

In this particular case where we want the Tethered data it needs to be as transparent as possible. Obviously you need your phone to be JailBroken for this to work.

Does a VPN Hide my Location on Android?

Your question can be conveniently divided into several parts:

Does a VPN hide location? Yes, he is capable of this. This is not about GPS determining your location. If you try to change the region via VPN in an application that requires GPS access, nothing will work. However, sites define your region differently. They get an IP address and see what country or region it belongs to. If you can change your IP address, you can change your region. This is exactly what VPNs can do.

How to hide location on Android? There is nothing difficult in figuring out how to set up a VPN on Android, but a couple of nuances still need to be highlighted. Let's start with the fact that not all Android VPNs are created equal. For example, VeePN outperforms many other services in terms of efficiency in circumventing restrictions. It has 2500+ VPN servers and a powerful IP and DNS leak protection system.

You can easily change the location of your Android device by using a VPN. Follow these steps for any device model (Samsung, Sony, Huawei, etc.):

  1. Download and install a trusted VPN.

  2. Install the VPN on your Android device.

  3. Open the application and connect to a server in a different country.

  4. Your Android location will now be successfully changed!

Is it legal? Yes, changing your location on Android is legal. Likewise, you can change VPN settings in Microsoft Edge on your PC, and all this is within the law. VPN allows you to change your IP address, safeguarding your privacy and protecting your actual location from being exposed. However, VPN laws may vary from country to country. There are restrictions in some regions.

Brief summary: Yes, you can change your region on Android and a VPN is a necessary assistant for this. It's simple, safe and legal. Today, VPN is the best way to change the region and unblock sites with regional restrictions.

Return value using String result=Command.ExecuteScalar() error occurs when result returns null

This should work:

var result = cmd.ExecuteScalar();
conn.Close();

return result != null ? result.ToString() : string.Empty;

Also, I'd suggest using Parameters in your query, something like (just a suggestion):

var cmd = new SqlCommand
{
    Connection = conn,
    CommandType = CommandType.Text,
    CommandText = "select COUNT(idemp_atd) absentDayNo from td_atd where absentdate_atd between @sdate and @edate and idemp_atd=@idemp group by idemp_atd"
};

cmd.Parameters.AddWithValue("@sdate", sdate);
cmd.Parameters.AddWithValue("@edate", edate);
// etc ...

Byte[] to ASCII

Encoding.GetString Method (Byte[]) convert bytes to a string.

When overridden in a derived class, decodes all the bytes in the specified byte array into a string.

Namespace: System.Text
Assembly: mscorlib (in mscorlib.dll)

Syntax

public virtual string GetString(byte[] bytes)

Parameters

bytes
    Type: System.Byte[]
    The byte array containing the sequence of bytes to decode.

Return Value

Type: System.String
A String containing the results of decoding the specified sequence of bytes.

Exceptions

ArgumentException        - The byte array contains invalid Unicode code points.
ArgumentNullException    - bytes is null.
DecoderFallbackException - A fallback occurred (see Character Encoding in the .NET Framework for complete explanation) or DecoderFallback is set to DecoderExceptionFallback.

Remarks

If the data to be converted is available only in sequential blocks (such as data read from a stream) or if the amount of data is so large that it needs to be divided into smaller blocks, the application should use the Decoder or the Encoder provided by the GetDecoder method or the GetEncoder method, respectively, of a derived class.

See the Remarks under Encoding.GetChars for more discussion of decoding techniques and considerations.

How to solve the system.data.sqlclient.sqlexception (0x80131904) error

The datasource is by default .\SQLEXPRESS (its the instance where databases are placed by default) or if u changed the name of the instance during installation of sql server so i advise you to do this :

connectionString="Data Source=.\\yourInstance(defaulT Data source is SQLEXPRESS);
       Initial Catalog=databaseName;
       User ID=theuser if u use it;
       Password=thepassword if u use it;
       integrated security=true(if u don t use user and pass; else change it false)"

Without to knowing your instance, I could help with this one. Hope it helped

libstdc++-6.dll not found

I placed the libstdc++-6.dll file in the same folder where exe file is generated.

How to print strings with line breaks in java

private static final String mText = "SHOP MA" + "\n" +
        + "----------------------------" + "\n" +
        + "Pannampitiya" + newline +
        + "09-10-2012 harsha  no: 001" + "\n" +
        + "No  Item  Qty  Price  Amount" + "\n" +
        + "1 Bread 1 50.00  50.00" + "\n" +
        + "____________________________" + "\n";

This should work.

What are the differences between normal and slim package of jquery?

I found a difference when creating a Form Contact: slim (recommended by boostrap 4.5):

  • After sending an email the global variables get stuck, and that makes if the user gives f5 (reload page) it is sent again. min:
  • The previous error will be solved. how i suffered!

Difference between char* and const char*?

Actually, char* name is not a pointer to a constant, but a pointer to a variable. You might be talking about this other question.

What is the difference between char * const and const char *?

Determine if Android app is being used for the first time

You can use the SharedPreferences to identify if it is the "First time" the app is launched. Just use a Boolean variable ("my_first_time") and change its value to false when your task for "first time" is over.

This is my code to catch the first time you open the app:

final String PREFS_NAME = "MyPrefsFile";

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

if (settings.getBoolean("my_first_time", true)) {
    //the app is being launched for first time, do something        
    Log.d("Comments", "First time");

             // first time task

    // record the fact that the app has been started at least once
    settings.edit().putBoolean("my_first_time", false).commit(); 
}

Vertical alignment of text and icon in button

Just wrap the button label in an extra span and add class="align-middle" to both (the icon and the label). This will center your icon with text vertical.

<button id="edit-listing-form-house_Continue" 
    class="btn btn-large btn-primary"
    style=""
    value=""
    name="Continue"
    type="submit">
<span class="align-middle">Continue</span>
<i class="icon-ok align-middle" style="font-size:40px;"></i>

Just get column names from hive table

If you simply want to see the column names this one line should provide it without changing any settings:

describe database.tablename;

However, if that doesn't work for your version of hive this code will provide it, but your default database will now be the database you are using:

use database;
describe tablename;

Call child method from parent

Here my demo: https://stackblitz.com/edit/react-dgz1ee?file=styles.css

I am using useEffect to call the children component's methods. I have tried with Proxy and Setter_Getter but sor far useEffect seems to be the more convenient way to call a child method from parent. To use Proxy and Setter_Getter it seems there is some subtlety to overcome first, because the element firstly rendered is an objectLike's element through the ref.current return => <div/>'s specificity. Concerning useEffect, you can also leverage on this approach to set the parent's state depending on what you want to do with the children.

In the demo's link I have provided, you will find my full ReactJS' code with my draftwork inside's so you can appreciate the workflow of my solution.

Here I am providing you my ReactJS' snippet with the relevant code only. :

import React, {
  Component,
  createRef,
  forwardRef,
  useState,
  useEffect
} from "react"; 

{...}

// Child component
// I am defining here a forwardRef's element to get the Child's methods from the parent
// through the ref's element.
let Child = forwardRef((props, ref) => {
  // I am fetching the parent's method here
  // that allows me to connect the parent and the child's components
  let { validateChildren } = props;
  // I am initializing the state of the children
  // good if we can even leverage on the functional children's state
  let initialState = {
    one: "hello world",
    two: () => {
      console.log("I am accessing child method from parent :].");
      return "child method achieve";
    }
  };
  // useState initialization
  const [componentState, setComponentState] = useState(initialState);
  // useEffect will allow me to communicate with the parent
  // through a lifecycle data flow
  useEffect(() => {
    ref.current = { componentState };
    validateChildren(ref.current.componentState.two);
  });

{...}

});

{...}

// Parent component
class App extends Component {
  // initialize the ref inside the constructor element
  constructor(props) {
    super(props);
    this.childRef = createRef();
  }

  // I am implementing a parent's method
  // in child useEffect's method
  validateChildren = childrenMethod => {
    // access children method from parent
    childrenMethod();
    // or signaling children is ready
    console.log("children active");
  };

{...}
render(){
       return (
          {
            // I am referencing the children
            // also I am implementing the parent logic connector's function
            // in the child, here => this.validateChildren's function
          }
          <Child ref={this.childRef} validateChildren={this.validateChildren} />
        </div>
       )
}

What is the use of hashCode in Java?

hashCode() is a unique code which is generated by the JVM for every object creation.

We use hashCode() to perform some operation on hashing related algorithm like Hashtable, Hashmap etc..

The advantages of hashCode() make searching operation easy because when we search for an object that has unique code, it helps to find out that object.

But we can't say hashCode() is the address of an object. It is a unique code generated by JVM for every object.

That is why nowadays hashing algorithm is the most popular search algorithm.

apache and httpd running but I can't see my website

Did you restart the server after you changed the config file?

Can you telnet to the server from a different machine?

Can you telnet to the server from the server itself?

telnet <ip address> 80

telnet localhost 80

Which maven dependencies to include for spring 3.0?

Use a BOM to solve version issues.

you may find that a third-party library, or another Spring project, pulls in a transitive dependency to an older release. If you forget to explicitly declare a direct dependency yourself, all sorts of unexpected issues can arise.

To overcome such problems Maven supports the concept of a "bill of materials" (BOM) dependency.

https://docs.spring.io/spring/docs/4.3.18.RELEASE/spring-framework-reference/html/overview.html#overview-maven-bom

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-framework-bom</artifactId>
  <version>3.2.12.RELEASE</version>
  <type>pom</type>
</dependency>

How can I programmatically generate keypress events in C#?

The question is tagged WPF but the answers so far are specific WinForms and Win32.

To do this in WPF, simply construct a KeyEventArgs and call RaiseEvent on the target. For example, to send an Insert key KeyDown event to the currently focused element:

var key = Key.Insert;                    // Key to send
var target = Keyboard.FocusedElement;    // Target element
var routedEvent = Keyboard.KeyDownEvent; // Event to send
     target.RaiseEvent(
  new KeyEventArgs(
    Keyboard.PrimaryDevice,
    PresentationSource.FromVisual(target),
    0,
    key)
  { RoutedEvent=routedEvent }
);

This solution doesn't rely on native calls or Windows internals and should be much more reliable than the others. It also allows you to simulate a keypress on a specific element.

Note that this code is only applicable to PreviewKeyDown, KeyDown, PreviewKeyUp, and KeyUp events. If you want to send TextInput events you'll do this instead:

var text = "Hello";
var target = Keyboard.FocusedElement;
var routedEvent = TextCompositionManager.TextInputEvent;

target.RaiseEvent(
  new TextCompositionEventArgs(
    InputManager.Current.PrimaryKeyboardDevice,
    new TextComposition(InputManager.Current, target, text))
  { RoutedEvent = routedEvent }
);

Also note that:

  • Controls expect to receive Preview events, for example PreviewKeyDown should precede KeyDown

  • Using target.RaiseEvent(...) sends the event directly to the target without meta-processing such as accelerators, text composition and IME. This is normally what you want. On the other hand, if you really do what to simulate actual keyboard keys for some reason, you would use InputManager.ProcessInput() instead.

Remove all items from RecyclerView

setAdapter(null);

Useful if RecycleView have different views type

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

For some looking for a solution to this problem, the root of the issue may be where you are setting your list views adapter. After you set the adapter on the listview, it resets the scroll position. Just something to consider. I moved setting the adapter into my onCreateView after we grab the reference to the listview, and it solved the problem for me. =)

Quoting backslashes in Python string literals

Use a raw string:

>>> foo = r'baz "\"'
>>> foo
'baz "\\"'

Note that although it looks wrong, it's actually right. There is only one backslash in the string foo.

This happens because when you just type foo at the prompt, python displays the result of __repr__() on the string. This leads to the following (notice only one backslash and no quotes around the printed string):

>>> foo = r'baz "\"'
>>> foo
'baz "\\"'
>>> print(foo)
baz "\"

And let's keep going because there's more backslash tricks. If you want to have a backslash at the end of the string and use the method above you'll come across a problem:

>>> foo = r'baz \'
  File "<stdin>", line 1
    foo = r'baz \'
                 ^  
SyntaxError: EOL while scanning single-quoted string

Raw strings don't work properly when you do that. You have to use a regular string and escape your backslashes:

>>> foo = 'baz \\'
>>> print(foo)
baz \

However, if you're working with Windows file names, you're in for some pain. What you want to do is use forward slashes and the os.path.normpath() function:

myfile = os.path.normpath('c:/folder/subfolder/file.txt')
open(myfile)

This will save a lot of escaping and hair-tearing. This page was handy when going through this a while ago.

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

The bash script runs in a separate subshell. In order to make this work you will need to source this other script as well.

What is the difference between URI, URL and URN?

URL -- Uniform Resource Locator

Contains information about how to fetch a resource from its location. For example:

  • http://example.com/mypage.html
  • ftp://example.com/download.zip
  • mailto:[email protected]
  • file:///home/user/file.txt
  • http://example.com/resource?foo=bar#fragment
  • /other/link.html (A relative URL, only useful in the context of another URL)

URLs always start with a protocol (http) and usually contain information such as the network host name (example.com) and often a document path (/foo/mypage.html). URLs may have query parameters and fragment identifiers.

URN -- Uniform Resource Name

Identifies a resource by name. It always starts with the prefix urn: For example:

  • urn:isbn:0451450523 to identify a book by its ISBN number.
  • urn:uuid:6e8bc430-9c3a-11d9-9669-0800200c9a66 a globally unique identifier
  • urn:publishing:book - An XML namespace that identifies the document as a type of book.

URNs can identify ideas and concepts. They are not restricted to identifying documents. When a URN does represent a document, it can be translated into a URL by a "resolver". The document can then be downloaded from the URL.

URI -- Uniform Resource Identifier

URIs encompasses both URLs, URNs, and other ways to indicate a resource.

An example of a URI that is neither a URL nor a URN would be a data URI such as data:,Hello%20World. It is not a URL or URN because the URI contains the data. It neither names it, nor tells you how to locate it over the network.

There are also uniform resource citations (URCs) that point to meta data about a document rather than to the document itself. An example of a URC would be an indicator for viewing the source code of a web page: view-source:http://example.com/. A URC is another type of URI that is neither URL nor URN.

Frequently Asked Questions

I've heard that I shouldn't say URL anymore, why?

The w3 spec for HTML says that the href of an anchor tag can contain a URI, not just a URL. You should be able to put in a URN such as <a href="urn:isbn:0451450523">. Your browser would then resolve that URN to a URL and download the book for you.

Do any browsers actually know how to fetch documents by URN?

Not that I know of, but modern web browser do implement the data URI scheme.

Can a URI be both a URL and a URN?

Good question. I've seen lots of places on the web that state this is true. I haven't been able to find any examples of something that is both a URL and a URN. I don't see how it is possible because a URN starts with urn: which is not a valid network protocol.

Does the difference between URL and URI have anything to do with whether it is relative or absolute?

No. Both relative and absolute URLs are URLs (and URIs.)

Does the difference between URL and URI have anything to do with whether it has query parameters?

No. Both URLs with and without query parameters are URLs (and URIs.)

Does the difference between URL and URI have anything to do with whether it has a fragment identifier?

No. Both URLs with and without fragment identifiers are URLs (and URIs.)

Is a tel: URI a URL or a URN?

For example tel:1-800-555-5555. It doesn't start with urn: and it has a protocol for reaching a resource over a network. It must be a URL.

But doesn't the w3C now say that URLs and URIs are the same thing?

Yes. The W3C realized that there is a ton of confusion about this. They issued a URI clarification document that says that it is now OK to use URL and URI interchangeably. It is no longer useful to strictly segment URIs into different types such as URL, URN, and URC.

Remove sensitive files and their commits from Git history

So, It looks something like this:

git rm --cached /config/deploy.rb
echo /config/deploy.rb >> .gitignore

Remove cache for tracked file from git and add that file to .gitignore list

How to write a Python module/package?

Since nobody did cover this question of the OP yet:

What I wanted to do:

Make a python module install-able with "pip install ..."

Here is an absolute minimal example, showing the basic steps of preparing and uploading your package to PyPI using setuptools and twine.

This is by no means a substitute for reading at least the tutorial, there is much more to it than covered in this very basic example.

Creating the package itself is already covered by other answers here, so let us assume we have that step covered and our project structure like this:

.
+-- hellostackoverflow/
    +-- __init__.py
    +-- hellostackoverflow.py

In order to use setuptools for packaging, we need to add a file setup.py, this goes into the root folder of our project:

.
+-- setup.py
+-- hellostackoverflow/
    +-- __init__.py
    +-- hellostackoverflow.py

At the minimum, we specify the metadata for our package, our setup.py would look like this:

from setuptools import setup

setup(
    name='hellostackoverflow',
    version='0.0.1',
    description='a pip-installable package example',
    license='MIT',
    packages=['hellostackoverflow'],
    author='Benjamin Gerfelder',
    author_email='[email protected]',
    keywords=['example'],
    url='https://github.com/bgse/hellostackoverflow'
)

Since we have set license='MIT', we include a copy in our project as LICENCE.txt, alongside a readme file in reStructuredText as README.rst:

.
+-- LICENCE.txt
+-- README.rst
+-- setup.py
+-- hellostackoverflow/
    +-- __init__.py
    +-- hellostackoverflow.py

At this point, we are ready to go to start packaging using setuptools, if we do not have it already installed, we can install it with pip:

pip install setuptools

In order to do that and create a source distribution, at our project root folder we call our setup.py from the command line, specifying we want sdist:

python setup.py sdist

This will create our distribution package and egg-info, and result in a folder structure like this, with our package in dist:

.
+-- dist/
+-- hellostackoverflow.egg-info/
+-- LICENCE.txt
+-- README.rst
+-- setup.py
+-- hellostackoverflow/
    +-- __init__.py
    +-- hellostackoverflow.py

At this point, we have a package we can install using pip, so from our project root (assuming you have all the naming like in this example):

pip install ./dist/hellostackoverflow-0.0.1.tar.gz

If all goes well, we can now open a Python interpreter, I would say somewhere outside our project directory to avoid any confusion, and try to use our shiny new package:

Python 3.5.2 (default, Sep 14 2017, 22:51:06) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from hellostackoverflow import hellostackoverflow
>>> hellostackoverflow.greeting()
'Hello Stack Overflow!'

Now that we have confirmed the package installs and works, we can upload it to PyPI.

Since we do not want to pollute the live repository with our experiments, we create an account for the testing repository, and install twine for the upload process:

pip install twine

Now we're almost there, with our account created we simply tell twine to upload our package, it will ask for our credentials and upload our package to the specified repository:

twine upload --repository-url https://test.pypi.org/legacy/ dist/*

We can now log into our account on the PyPI test repository and marvel at our freshly uploaded package for a while, and then grab it using pip:

pip install --index-url https://test.pypi.org/simple/ hellostackoverflow

As we can see, the basic process is not very complicated. As I said earlier, there is a lot more to it than covered here, so go ahead and read the tutorial for more in-depth explanation.

LINQ to SQL - How to select specific columns and return strongly typed list

Basically you are doing it the right way. However, you should use an instance of the DataContext for querying (it's not obvious that DataContext is an instance or the type name from your query):

var result = (from a in new DataContext().Persons
              where a.Age > 18
              select new Person { Name = a.Name, Age = a.Age }).ToList();

Apparently, the Person class is your LINQ to SQL generated entity class. You should create your own class if you only want some of the columns:

class PersonInformation {
   public string Name {get;set;}
   public int Age {get;set;}
}

var result = (from a in new DataContext().Persons
              where a.Age > 18
              select new PersonInformation { Name = a.Name, Age = a.Age }).ToList();

You can freely swap var with List<PersonInformation> here without affecting anything (as this is what the compiler does).

Otherwise, if you are working locally with the query, I suggest considering an anonymous type:

var result = (from a in new DataContext().Persons
              where a.Age > 18
              select new { a.Name, a.Age }).ToList();

Note that in all of these cases, the result is statically typed (it's type is known at compile time). The latter type is a List of a compiler generated anonymous class similar to the PersonInformation class I wrote above. As of C# 3.0, there's no dynamic typing in the language.

UPDATE:

If you really want to return a List<Person> (which might or might not be the best thing to do), you can do this:

var result = from a in new DataContext().Persons
             where a.Age > 18
             select new { a.Name, a.Age };

List<Person> list = result.AsEnumerable()
                          .Select(o => new Person {
                                           Name = o.Name, 
                                           Age = o.Age
                          }).ToList();

You can merge the above statements too, but I separated them for clarity.

In what cases do I use malloc and/or new?

Unless you are forced to use C, you should never use malloc. Always use new.

If you need a big chunk of data just do something like:

char *pBuffer = new char[1024];

Be careful though this is not correct:

//This is incorrect - may delete only one element, may corrupt the heap, or worse...
delete pBuffer;

Instead you should do this when deleting an array of data:

//This deletes all items in the array
delete[] pBuffer;

The new keyword is the C++ way of doing it, and it will ensure that your type will have its constructor called. The new keyword is also more type-safe whereas malloc is not type-safe at all.

The only way I could think that would be beneficial to use malloc would be if you needed to change the size of your buffer of data. The new keyword does not have an analogous way like realloc. The realloc function might be able to extend the size of a chunk of memory for you more efficiently.

It is worth mentioning that you cannot mix new/free and malloc/delete.

Note: Some answers in this question are invalid.

int* p_scalar = new int(5);  // Does not create 5 elements, but initializes to 5
int* p_array  = new int[5];  // Creates 5 elements

Make Bootstrap 3 Tabs Responsive

enter image description here

There is a new one: http://hayatbiralem.com/blog/2015/05/15/responsive-bootstrap-tabs/

And also Codepen sample available here: http://codepen.io/hayatbiralem/pen/KpzjOL

No needs plugin. It uses just a little css and jquery.

Here's a sample tabs markup:

<ul class="nav nav-tabs nav-tabs-responsive">
    <li class="active">
        <a href="#tab1" data-toggle="tab">
            <span class="text">Tab 1</span>
        </a>
    </li>
    <li class="next">
        <a href="#tab2" data-toggle="tab">
            <span class="text">Tab 2</span>
        </a>
    </li>
    <li>
        <a href="#tab3" data-toggle="tab">
            <span class="text">Tab 3</span>
        </a>
    </li>
    ...
</ul>

.. and jQuery codes are also here:

(function($) {

  'use strict';

  $(document).on('show.bs.tab', '.nav-tabs-responsive [data-toggle="tab"]', function(e) {
    var $target = $(e.target);
    var $tabs = $target.closest('.nav-tabs-responsive');
    var $current = $target.closest('li');
    var $parent = $current.closest('li.dropdown');
        $current = $parent.length > 0 ? $parent : $current;
    var $next = $current.next();
    var $prev = $current.prev();
    var updateDropdownMenu = function($el, position){
      $el
        .find('.dropdown-menu')
        .removeClass('pull-xs-left pull-xs-center pull-xs-right')
        .addClass( 'pull-xs-' + position );
    };

    $tabs.find('>li').removeClass('next prev');
    $prev.addClass('prev');
    $next.addClass('next');

    updateDropdownMenu( $prev, 'left' );
    updateDropdownMenu( $current, 'center' );
    updateDropdownMenu( $next, 'right' );
  });

})(jQuery);

"Large data" workflows using pandas

I'd like to point out the Vaex package.

Vaex is a python library for lazy Out-of-Core DataFrames (similar to Pandas), to visualize and explore big tabular datasets. It can calculate statistics such as mean, sum, count, standard deviation etc, on an N-dimensional grid up to a billion (109) objects/rows per second. Visualization is done using histograms, density plots and 3d volume rendering, allowing interactive exploration of big data. Vaex uses memory mapping, zero memory copy policy and lazy computations for best performance (no memory wasted).

Have a look at the documentation: https://vaex.readthedocs.io/en/latest/ The API is very close to the API of pandas.

How can an html element fill out 100% of the remaining screen height, using css only?

Please let me add my 5 cents here and offer a classical solution:

_x000D_
_x000D_
html {height:100%;}_x000D_
body {height:100%; margin:0;}_x000D_
#idOuter {position:relative; width:100%; height:100%;}_x000D_
#idHeader {position:absolute; left:0; right:0; border:solid 3px red;}_x000D_
#idContent {position:absolute; overflow-y:scroll; left:0; right:0; border:solid 3px green;}
_x000D_
<div id="idOuter">_x000D_
  <div id="idHeader" style="height:30px; top:0;">Header section</div>_x000D_
  <div id="idContent" style="top:36px; bottom:0;">Content section</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

This will work in all browsers, no script, no flex. Open snippet in full page mode and resize browser: desired proportions are preserved even in fullscreen mode.

Note:

  • Elements with different background color can actually cover each other. Here I used solid border to ensure that elements are placed correctly.
  • idHeader.height and idContent.top are adjusted to include border, and should have the same value if border is not used. Otherwise elements will pull out of the viewport, since calculated width does not include border, margin and/or padding.
  • left:0; right:0; can be replaced by width:100% for the same reason, if no border used.
  • Testing in separate page (not as a snippet) does not require any html/body adjustment.
  • In IE6 and earlier versions we must add padding-top and/or padding-bottom attributes to #idOuter element.

To complete my answer, here is the footer layout:

_x000D_
_x000D_
html {height:100%;}_x000D_
body {height:100%; margin:0;}_x000D_
#idOuter {position:relative; width:100%; height:100%;}_x000D_
#idContent {position:absolute; overflow-y:scroll; left:0; right:0; border:solid 3px green;}_x000D_
#idFooter {position:absolute; left:0; right:0; border:solid 3px blue;}
_x000D_
<div id="idOuter">_x000D_
  <div id="idContent" style="bottom:36px; top:0;">Content section</div>_x000D_
  <div id="idFooter" style="height:30px; bottom:0;">Footer section</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

And here is the layout with both header and footer:

_x000D_
_x000D_
html {height:100%;}_x000D_
body {height:100%; margin:0;}_x000D_
#idOuter {position:relative; width:100%; height:100%;}_x000D_
#idHeader {position:absolute; left:0; right:0; border:solid 3px red;}_x000D_
#idContent {position:absolute; overflow-y:scroll; left:0; right:0; border:solid 3px green;}_x000D_
#idFooter {position:absolute; left:0; right:0; border:solid 3px blue;}
_x000D_
<div id="idOuter">_x000D_
  <div id="idHeader" style="height:30px; top:0;">Header section</div>_x000D_
  <div id="idContent" style="top:36px; bottom:36px;">Content section</div>_x000D_
  <div id="idFooter" style="height:30px; bottom:0;">Footer section</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Difference between wait and sleep

One potential big difference between sleep/interrupt and wait/notify is that

Generating an exception when not needed is inefficient. If you have threads communicating with each other at a high rate, then it would be generating a lot of exceptions if you were calling interrupt all the time, which is a total waste of CPU.

How do I change the string representation of a Python class?

The closest equivalent to Java's toString is to implement __str__ for your class. Put this in your class definition:

def __str__(self):
     return "foo"

You may also want to implement __repr__ to aid in debugging.

See here for more information:

jQuery equivalent of JavaScript's addEventListener method

The closest thing would be the bind function:

http://api.jquery.com/bind/

$('#foo').bind('click', function() {
  alert('User clicked on "foo."');
});

How can I use a DLL file from Python?

ctypes will be the easiest thing to use but (mis)using it makes Python subject to crashing. If you are trying to do something quickly, and you are careful, it's great.

I would encourage you to check out Boost Python. Yes, it requires that you write some C++ code and have a C++ compiler, but you don't actually need to learn C++ to use it, and you can get a free (as in beer) C++ compiler from Microsoft.

grabbing first row in a mysql query only

You didn't specify how the order is determined, but this will give you a rank value in MySQL:

SELECT t.*,
       @rownum := @rownum +1 AS rank
  FROM TBL_FOO t
  JOIN (SELECT @rownum := 0) r
 WHERE t.name = 'sarmen'

Then you can pick out what rows you want, based on the rank value.

Query an object array using linq

Add:

using System.Linq;

to the top of your file.

And then:

Car[] carList = ...
var carMake = 
    from item in carList
    where item.Model == "bmw" 
    select item.Make;

or if you prefer the fluent syntax:

var carMake = carList
    .Where(item => item.Model == "bmw")
    .Select(item => item.Make);

Things to pay attention to:

  • The usage of item.Make in the select clause instead if s.Make as in your code.
  • You have a whitespace between item and .Model in your where clause

Get Filename Without Extension in Python

No need for regex. os.path.splitext is your friend:

os.path.splitext('1.1.1.jpg')
>>> ('1.1.1', '.jpg')

How to split an integer into an array of digits?

Another solution that does not involve converting to/from strings:

from math import log10

def decompose(n):
    if n == 0:
        return [0]
    b = int(log10(n)) + 1
    return [(n // (10 ** i)) % 10 for i in reversed(range(b))]

Equivalent function for DATEADD() in Oracle

Method1: ADD_MONTHS

ADD_MONTHS(SYSDATE, -6)

Method 2: Interval

SYSDATE - interval '6' month

Note: if you want to do the operations from start of the current month always, TRUNC(SYSDATE,'MONTH') would give that. And it expects a Date datatype as input.

Calling a JavaScript function returned from an Ajax response

I would like to add that there's an eval function in jQuery allowing you to eval the code globally which should get you rid of any contextual problems. The function is called globalEval() and it worked great for my purposes. Its documentation can be found here.

This is the example code provided by the jQuery API documentation:

function test()
{
  jQuery.globalEval("var newVar = true;")
}

test();
// newVar === true

This function is extremely useful when it comes to loading external scripts dynamically which you apparently were trying to do.

Codeigniter - no input file specified

My site is hosted on MochaHost, i had a tough time to setup the .htaccess file so that i can remove the index.php from my urls. However, after some googling, i combined the answer on this thread and other answers. My final working .htaccess file has the following contents:

<IfModule mod_rewrite.c>
    # Turn on URL rewriting
    RewriteEngine On

    # If your website begins from a folder e.g localhost/my_project then 
    # you have to change it to: RewriteBase /my_project/
    # If your site begins from the root e.g. example.local/ then
    # let it as it is
    RewriteBase /

    # Protect application and system files from being viewed when the index.php is missing
    RewriteCond $1 ^(application|system|private|logs)

    # Rewrite to index.php/access_denied/URL
    RewriteRule ^(.*)$ index.php/access_denied/$1 [PT,L]

    # Allow these directories and files to be displayed directly:
    RewriteCond $1 ^(index\.php|robots\.txt|favicon\.ico|public|app_upload|assets|css|js|images)

    # No rewriting
    RewriteRule ^(.*)$ - [PT,L]

    # Rewrite to index.php/URL
    RewriteRule ^(.*)$ index.php?/$1 [PT,L]
</IfModule>

Where does application data file actually stored on android device?

This is a simple way to identify the application related storage paths of a particular app.

Steps:

  1. Have the android device connected to your mac or android emulator open
  2. Open the terminal
  3. adb shell
  4. find .

The "find ." command will list all the files with their paths in the terminal.

./apex/com.android.media.swcodec
./apex/com.android.media.swcodec/etc
./apex/com.android.media.swcodec/etc/init.rc
./apex/com.android.media.swcodec/etc/seccomp_policy
./apex/com.android.media.swcodec/etc/seccomp_policy/mediaswcodec.policy
./apex/com.android.media.swcodec/etc/ld.config.txt
./apex/com.android.media.swcodec/etc/media_codecs.xml
./apex/com.android.media.swcodec/apex_manifest.json
./apex/com.android.media.swcodec/lib
./apex/com.android.media.swcodec/lib/[email protected]
./apex/com.android.media.swcodec/lib/libcodec2_soft_common.so
./apex/com.android.media.swcodec/lib/[email protected]
./apex/com.android.media.swcodec/lib/libcodec2_soft_vorbisdec.so
./apex/com.android.media.swcodec/lib/libcodec2_soft_h263dec.so
./apex/com.android.media.swcodec/lib/libhidltransport.so
./apex/com.android.media.swcodec/lib/libcodec2_soft_h263enc.so
./apex/com.android.media.swcodec/lib/libcodec2_vndk.so
./apex/com.android.media.swcodec/lib/[email protected]
./apex/com.android.media.swcodec/lib/libmedia_codecserviceregistrant.so
./apex/com.android.media.swcodec/lib/libhidlbase.so
./apex/com.android.media.swcodec/lib/libcodec2_soft_aacdec.so
./apex/com.android.media.swcodec/lib/libcodec2_soft_vp9dec.so
.....

After this, just search for your app with the bundle identifier and you can use adb pull command to download the files to your local directory.

How to deserialize xml to object

The comments above are correct. You're missing the decorators. If you want a generic deserializer you can use this.

public static T DeserializeXMLFileToObject<T>(string XmlFilename)
{
    T returnObject = default(T);
    if (string.IsNullOrEmpty(XmlFilename)) return default(T);

    try
    {
        StreamReader xmlStream = new StreamReader(XmlFilename);
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        returnObject = (T)serializer.Deserialize(xmlStream);
    }
    catch (Exception ex)
    {
        ExceptionLogger.WriteExceptionToConsole(ex, DateTime.Now);
    }
    return returnObject;
}

Then you'd call it like this:

MyObjType MyObj = DeserializeXMLFileToObject<MyObjType>(FilePath);

How can I check if a JSON is empty in NodeJS?

Object.keys(myObj).length === 0;

As there is need to just check if Object is empty it will be better to directly call a native method Object.keys(myObj).length which returns the array of keys by internally iterating with for..in loop.As Object.hasOwnProperty returns a boolean result based on the property present in an object which itself iterates with for..in loop and will have time complexity O(N2).

On the other hand calling a UDF which itself has above two implementations or other will work fine for small object but will block the code which will have severe impact on overall perormance if Object size is large unless nothing else is waiting in the event loop.

OnChange event handler for radio button (INPUT type="radio") doesn't work as one value

I would make two changes:

<input type="radio" name="myRadios" onclick="handleClick(this);" value="1" />
<input type="radio" name="myRadios" onclick="handleClick(this);" value="2" />
  1. Use the onclick handler instead of onchange - you're changing the "checked state" of the radio input, not the value, so there's not a change event happening.
  2. Use a single function, and pass this as a parameter, that will make it easy to check which value is currently selected.

ETA: Along with your handleClick() function, you can track the original / old value of the radio in a page-scoped variable. That is:

var currentValue = 0;
function handleClick(myRadio) {
    alert('Old value: ' + currentValue);
    alert('New value: ' + myRadio.value);
    currentValue = myRadio.value;
}

_x000D_
_x000D_
var currentValue = 0;_x000D_
function handleClick(myRadio) {_x000D_
    alert('Old value: ' + currentValue);_x000D_
    alert('New value: ' + myRadio.value);_x000D_
    currentValue = myRadio.value;_x000D_
}
_x000D_
<input type="radio" name="myRadios" onclick="handleClick(this);" value="1" />_x000D_
<input type="radio" name="myRadios" onclick="handleClick(this);" value="2" />
_x000D_
_x000D_
_x000D_

How to find a text inside SQL Server procedures / triggers?

You can search within the definitions of all database objects using the following SQL:

SELECT 
    o.name, 
    o.id, 
    c.text,
    o.type
FROM 
    sysobjects o 
RIGHT JOIN syscomments c 
    ON o.id = c.id 
WHERE 
    c.text like '%text_to_find%'

How do you display JavaScript datetime in 12 hour AM/PM format?

In modern browsers, use Intl.DateTimeFormat and force 12hr format with options:

    let now = new Date();

    new Intl.DateTimeFormat('default',
        {
            hour12: true,
            hour: 'numeric',
            minute: 'numeric'
        }).format(now);

    // 6:30 AM

Using default will honor browser's default locale if you add more options, yet will still output 12hr format.

What is the difference between statically typed and dynamically typed languages?

Statically typed programming languages do type checking (i.e. the process of verifying and enforcing the constraints of types) at compile-time as opposed to run-time.

Dynamically typed programming languages do type checking at run-time as opposed to compile-time.

Examples of statically typed languages are :- Java, C, C++

Examples of dynamically typed languages are :- Perl, Ruby, Python, PHP, JavaScript

Trigger back-button functionality on button click in Android

Well the answer from @sahhhm didn't work for me, what i needed was to trigger the backKey from a custom button so what I did was I simply called,

backAction.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyRides.super.onBackPressed();

            }
});

and it work like charm. Hope it will help others too.

How to prevent page from reloading after form submit - JQuery

The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:

  1. Use <button type="button"> to override default submission behavior
  2. Use event.preventDefault() in the onSubmit event to prevent form submission

Solution 1:

  • Advantage: simple change to markup
  • Disadvantage: subverts default form behavior, especially when JS is disabled. What if the user wants to hit "enter" to submit?

Insert extra type attribute to your button markup:

<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>

Solution 2:

  • Advantage: form will work even when JS is disabled, and respects standard form UI/UX such that at least one button is used for submission

Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:

$(document).ready(function () {
  // Listen to click event on the submit button
  $('#button').click(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Better variant:

In this improvement, we listen to the submit event emitted from the <form> element:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Even better variant: use .serialize() to serialize your form, but remember to add name attributes to your input:

The name attribute is required for .serialize() to work, as per jQuery's documentation:

For a form element's value to be included in the serialized string, the element must have a name attribute.

<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">

And then in your JS:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    // Prevent form submission which refreshes page
    e.preventDefault();

    // Serialize data
    var formData = $(this).serialize();

    // Make AJAX request
    $.post("process.php", formData).complete(function() {
      console.log("Success");
    });
  });
});

Locking a file in Python

I prefer lockfile — Platform-independent file locking

How to outline text in HTML / CSS

With HTML5's support for svg, you don't need to rely on shadow hacks.

_x000D_
_x000D_
<svg  width="100%" viewBox="0 0 600 100">_x000D_
<text x=0 y=20 font-size=12pt fill=white stroke=black stroke-width=0.75>_x000D_
    This text exposes its vector representation, _x000D_
    making it easy to style shape-wise without hacks. _x000D_
    HTML5 supports it, so no browser issues. Only downside _x000D_
    is that svg has its own quirks and learning curve _x000D_
    (c.f. bounding box issue/no typesetting by default)_x000D_
</text>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

How to set a value for a span using jQuery

You are using jQuery(document).ready(function($) {} means here you are using jQuery instead of $. So to resolve your issue use following code.

jQuery("#submittername").text(submitter_name);

This will resolve your problem.

Count number of rows per group and add result to original data frame

The base R function aggregate will obtain the counts with a one-liner, but adding those counts back to the original data.frame seems to take a bit of processing.

df <- data.frame(name=c('black','black','black','red','red'),
                 type=c('chair','chair','sofa','sofa','plate'),
                 num=c(4,5,12,4,3))
df
#    name  type num
# 1 black chair   4
# 2 black chair   5
# 3 black  sofa  12
# 4   red  sofa   4
# 5   red plate   3

rows.per.group  <- aggregate(rep(1, length(paste0(df$name, df$type))),
                             by=list(df$name, df$type), sum)
rows.per.group
#   Group.1 Group.2 x
# 1   black   chair 2
# 2     red   plate 1
# 3   black    sofa 1
# 4     red    sofa 1

my.summary <- do.call(data.frame, rows.per.group)
colnames(my.summary) <- c(colnames(df)[1:2], 'rows.per.group')
my.data <- merge(df, my.summary, by = c(colnames(df)[1:2]))
my.data
#    name  type num rows.per.group
# 1 black chair   4              2
# 2 black chair   5              2
# 3 black  sofa  12              1
# 4   red plate   3              1
# 5   red  sofa   4              1

How do you create a foreign key relationship in a SQL Server CE (Compact Edition) Database?

I know it's a "very long time" since this question was first asked. Just in case, if it helps someone,

Adding relationships is well supported by MS via SQL Server Compact Tool Box (https://sqlcetoolbox.codeplex.com/). Just install it, then you would get the option to connect to the Compact Database using the Server Explorer Window. Right click on the primary table , select "Table Properties". You should have the following window, which contains "Add Relations" tab allowing you to add relations.

Add Relations Tab - SQL Server Compact Tool Box

Using GSON to parse a JSON array

Gson gson = new Gson();
Wrapper[] arr = gson.fromJson(str, Wrapper[].class);

class Wrapper{
    int number;
    String title;       
}

Seems to work fine. But there is an extra , Comma in your string.

[
    { 
        "number" : "3",
        "title" : "hello_world"
    },
    { 
        "number" : "2",
        "title" : "hello_world"
    }
]

How to get GMT date in yyyy-mm-dd hh:mm:ss in PHP

You are repeating the y,m,d.

Instead of

gmdate('yyyy-mm-dd hh:mm:ss \G\M\T', time());  

You should use it like

gmdate('Y-m-d h:m:s \G\M\T', time());

Developing for Android in Eclipse: R.java not regenerating

In my case, after endlessly shutting down the IDE, cleaning, trying to build, etc., the issue was a "untitled folder" inside my "res" folder that I probably added there by mistake.

I wish those kind of errors would be output by Eclipse, the way the Ant script did:

[null] invalid resource directory name: /Users/gubatron/workspace.android/my-project/res/untitled folder

Css transition from display none to display block, navigation with subnav

As you know the display property cannot be animated BUT just by having it in your CSS it overrides the visibility and opacity transitions.

The solution...just removed the display properties.

_x000D_
_x000D_
nav.main ul ul {_x000D_
  position: absolute;_x000D_
  list-style: none;_x000D_
  opacity: 0;_x000D_
  visibility: hidden;_x000D_
  padding: 10px;_x000D_
  background-color: rgba(92, 91, 87, 0.9);_x000D_
  -webkit-transition: opacity 600ms, visibility 600ms;_x000D_
  transition: opacity 600ms, visibility 600ms;_x000D_
}_x000D_
nav.main ul li:hover ul {_x000D_
  visibility: visible;_x000D_
  opacity: 1;_x000D_
}
_x000D_
<nav class="main">_x000D_
  <ul>_x000D_
    <li>_x000D_
      <a href="">Lorem</a>_x000D_
      <ul>_x000D_
        <li><a href="">Ipsum</a>_x000D_
        </li>_x000D_
        <li><a href="">Dolor</a>_x000D_
        </li>_x000D_
        <li><a href="">Sit</a>_x000D_
        </li>_x000D_
        <li><a href="">Amet</a>_x000D_
        </li>_x000D_
      </ul>_x000D_
    </li>_x000D_
  </ul>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

Linq to SQL how to do "where [column] in (list of values)"

You could also use:

List<int> codes = new List<int>();

codes.add(1);
codes.add(2);

var foo = from codeData in channel.AsQueryable<CodeData>()
          where codes.Any(code => codeData.CodeID.Equals(code))
          select codeData;

CSS class for pointer cursor

There is no classes for that. But you can add inline style for your div or other elements like,

<div class="" style="cursor: pointer;">

Timeout function if it takes too long to finish

The process for timing out an operations is described in the documentation for signal.

The basic idea is to use signal handlers to set an alarm for some time interval and raise an exception once that timer expires.

Note that this will only work on UNIX.

Here's an implementation that creates a decorator (save the following code as timeout.py).

from functools import wraps
import errno
import os
import signal

class TimeoutError(Exception):
    pass

def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):
    def decorator(func):
        def _handle_timeout(signum, frame):
            raise TimeoutError(error_message)

        def wrapper(*args, **kwargs):
            signal.signal(signal.SIGALRM, _handle_timeout)
            signal.alarm(seconds)
            try:
                result = func(*args, **kwargs)
            finally:
                signal.alarm(0)
            return result

        return wraps(func)(wrapper)

    return decorator

This creates a decorator called @timeout that can be applied to any long running functions.

So, in your application code, you can use the decorator like so:

from timeout import timeout

# Timeout a long running function with the default expiry of 10 seconds.
@timeout
def long_running_function1():
    ...

# Timeout after 5 seconds
@timeout(5)
def long_running_function2():
    ...

# Timeout after 30 seconds, with the error "Connection timed out"
@timeout(30, os.strerror(errno.ETIMEDOUT))
def long_running_function3():
    ...

Error: Cannot find module html

Use

res.sendFile()

instead of

res.render().

What your trying to do is send a whole file.

This worked for me.

C++ Error 'nullptr was not declared in this scope' in Eclipse IDE

You are using g++ 4.6 version you must invoke the flag -std=c++0x to compile

g++ -std=c++0x *.cpp -o output

Python: Binding Socket: "Address already in use"

socket.socket() should run before socket.bind() and use REUSEADDR as said

How to draw a circle with given X and Y coordinates as the middle spot of the circle?

The only thing that worked for me:

g.drawOval((getWidth()-200)/2,(getHeight()-200)/2, 200, 200);    

Easy way to dismiss keyboard?

A slightly more robust method I needed to use recently:

- (void) dismissKeyboard {
    NSArray *windows = [UIApplication sharedApplication].windows;

    for(UIWindow *window in windows) [window endEditing:true];

    //  Or if you're only working with one UIWindow:

    [[UIApplication sharedApplication].keyWindow endEditing:true];
}

I found some of the other "global" methods didn't work (for example, UIWebView & WKWebView refused to resign).

MySQLi count(*) always returns 1

I find this way more readable:

$result = $mysqli->query('select count(*) as `c` from `table`');
$count = $result->fetch_object()->c;
echo "there are {$count} rows in the table";

Not that I have anything against arrays...

increase legend font size ggplot2

A simpler but equally effective option would be:

+ theme_bw(base_size=X)

Nginx Different Domains on Same IP

Your "listen" directives are wrong. See this page: http://nginx.org/en/docs/http/server_names.html.

They should be

server {
    listen      80;
    server_name www.domain1.com;
    root /var/www/domain1;
}

server {
    listen       80;
    server_name www.domain2.com;
    root /var/www/domain2;
}

Note, I have only included the relevant lines. Everything else looked okay but I just deleted it for clarity. To test it you might want to try serving a text file from each server first before actually serving php. That's why I left the 'root' directive in there.

Pointer to class data member "::*"

You can use an array of pointer to (homogeneous) member data to enable a dual, named-member (i.e. x.data) and array-subscript (i.e. x[idx]) interface.

#include <cassert>
#include <cstddef>

struct vector3 {
    float x;
    float y;
    float z;

    float& operator[](std::size_t idx) {
        static float vector3::*component[3] = {
            &vector3::x, &vector3::y, &vector3::z
        };
        return this->*component[idx];
    }
};

int main()
{
    vector3 v = { 0.0f, 1.0f, 2.0f };

    assert(&v[0] == &v.x);
    assert(&v[1] == &v.y);
    assert(&v[2] == &v.z);

    for (std::size_t i = 0; i < 3; ++i) {
        v[i] += 1.0f;
    }

    assert(v.x == 1.0f);
    assert(v.y == 2.0f);
    assert(v.z == 3.0f);

    return 0;
}

Serializing to JSON in jQuery

JSON-js - JSON in JavaScript.

To convert an object to a string, use JSON.stringify:

var json_text = JSON.stringify(your_object, null, 2);

To convert a JSON string to object, use JSON.parse:

var your_object = JSON.parse(json_text);

It was recently recommended by John Resig:

...PLEASE start migrating your JSON-using applications over to Crockford's json2.js. It is fully compatible with the ECMAScript 5 specification and gracefully degrades if a native (faster!) implementation exists.

In fact, I just landed a change in jQuery yesterday that utilizes the JSON.parse method if it exists, now that it has been completely specified.

I tend to trust what he says on JavaScript matters :)

All modern browsers (and many older ones which aren't ancient) support the JSON object natively. The current version of Crockford's JSON library will only define JSON.stringify and JSON.parse if they're not already defined, leaving any browser native implementation intact.

How to trigger a file download when clicking an HTML button or JavaScript

If your looking for a vanilla JavaScript (no jQuery) solution and without using the HTML5 attribute you could try this.

_x000D_
_x000D_
const download = document.getElementById("fileRequest");_x000D_
_x000D_
download.addEventListener('click', request);_x000D_
_x000D_
function request() {_x000D_
    window.location = 'document.docx';_x000D_
}
_x000D_
.dwnld-cta {_x000D_
    border-radius: 15px 15px;_x000D_
    width: 100px;_x000D_
    line-height: 22px_x000D_
}
_x000D_
<h1>Download File</h1>_x000D_
<button id="fileRequest" class="dwnld-cta">Download</button>
_x000D_
_x000D_
_x000D_

Duplicate and rename Xcode project & associated folders

For anybody else having issues with storyboard crashes after copying your project, head over to Main.storyboard under Identity Inspector.

Next, check that your current module is the correct renamed module and not the old one.

Center fixed div with dynamic width (CSS)

This approach will not limit element's width when using margins in flexbox

top: 0; left: 0;
transform: translate(calc(50vw - 50%));

Also for centering it vertically

top: 0; left: 0;
transform: translate(calc(50vw - 50%), calc(50vh - 50%));

Is there a way to use shell_exec without waiting for the command to complete?

Sure, for windows you can use:

$WshShell = new COM("WScript.Shell");
$oExec = $WshShell->Run("C:/path/to/php-win.exe -f C:/path/to/script.php", 0, false);

Note:

If you get a COM error, add the extension to your php.ini and restart apache:

[COM_DOT_NET]
extension=php_com_dotnet.dll

Export JAR with Netbeans

It does this by default, you just need to look into the project's /dist folder.

Remove all whitespace from C# string with regex

No need for regex. This will also remove tabs, newlines etc

var newstr = String.Join("",str.Where(c=>!char.IsWhiteSpace(c)));

WhiteSpace chars : 0009 , 000a , 000b , 000c , 000d , 0020 , 0085 , 00a0 , 1680 , 180e , 2000 , 2001 , 2002 , 2003 , 2004 , 2005 , 2006 , 2007 , 2008 , 2009 , 200a , 2028 , 2029 , 202f , 205f , 3000.

How do I create a slug in Django?

You will need to use the slugify function.

>>> from django.template.defaultfilters import slugify
>>> slugify("b b b b")
u'b-b-b-b'
>>>

You can call slugify automatically by overriding the save method:

class Test(models.Model):
    q = models.CharField(max_length=30)
    s = models.SlugField()
    
    def save(self, *args, **kwargs):
        self.s = slugify(self.q)
        super(Test, self).save(*args, **kwargs)

Be aware that the above will cause your URL to change when the q field is edited, which can cause broken links. It may be preferable to generate the slug only once when you create a new object:

class Test(models.Model):
    q = models.CharField(max_length=30)
    s = models.SlugField()
    
    def save(self, *args, **kwargs):
        if not self.id:
            # Newly created object, so set slug
            self.s = slugify(self.q)

        super(Test, self).save(*args, **kwargs)

How to pass data from Javascript to PHP and vice versa?

the other way to exchange data from php to javascript or vice versa is by using cookies, you can save cookies in php and read by your javascript, for this you don't have to use forms or ajax

Method Call Chaining; returning a pointer vs a reference?

Since nullptr is never going to be returned, I recommend the reference approach. It more accurately represents how the return value will be used.

Unit testing private methods in C#

One way to test private methods is through reflection. This applies to NUnit and XUnit, too:

MyObject objUnderTest = new MyObject();
MethodInfo methodInfo = typeof(MyObject).GetMethod("SomePrivateMethod", BindingFlags.NonPublic | BindingFlags.Instance);
object[] parameters = {"parameters here"};
methodInfo.Invoke(objUnderTest, parameters);

What IDE to use for Python?

Results

Spreadsheet version

spreadsheet screenshot

Alternatively, in plain text: (also available as a a screenshot)

                         Bracket Matching -.  .- Line Numbering
                          Smart Indent -.  |  |  .- UML Editing / Viewing
         Source Control Integration -.  |  |  |  |  .- Code Folding
                    Error Markup -.  |  |  |  |  |  |  .- Code Templates
  Integrated Python Debugging -.  |  |  |  |  |  |  |  |  .- Unit Testing
    Multi-Language Support -.  |  |  |  |  |  |  |  |  |  |  .- GUI Designer (Qt, Eric, etc)
   Auto Code Completion -.  |  |  |  |  |  |  |  |  |  |  |  |  .- Integrated DB Support
     Commercial/Free -.  |  |  |  |  |  |  |  |  |  |  |  |  |  |  .- Refactoring
   Cross Platform -.  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |     
                  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Atom              |Y |F |Y |Y*|Y |Y |Y |Y |Y |Y |  |Y |Y |  |  |  |  |*many plugins
Editra            |Y |F |Y |Y |  |  |Y |Y |Y |Y |  |Y |  |  |  |  |  |
Emacs             |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |  |  |  |
Eric Ide          |Y |F |Y |  |Y |Y |  |Y |  |Y |  |Y |  |Y |  |  |  |
Geany             |Y |F |Y*|Y |  |  |  |Y |Y |Y |  |Y |  |  |  |  |  |*very limited
Gedit             |Y |F |Y¹|Y |  |  |  |Y |Y |Y |  |  |Y²|  |  |  |  |¹with plugin; ²sort of
Idle              |Y |F |Y |  |Y |  |  |Y |Y |  |  |  |  |  |  |  |  |
IntelliJ          |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |
JEdit             |Y |F |  |Y |  |  |  |  |Y |Y |  |Y |  |  |  |  |  |
KDevelop          |Y |F |Y*|Y |  |  |Y |Y |Y |Y |  |Y |  |  |  |  |  |*no type inference
Komodo            |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |Y |  |
NetBeans*         |Y |F |Y |Y |Y |  |Y |Y |Y |Y |Y |Y |Y |Y |  |  |Y |*pre-v7.0
Notepad++         |W |F |Y |Y |  |Y*|Y*|Y*|Y |Y |  |Y |Y*|  |  |  |  |*with plugin
Pfaide            |W |C |Y |Y |  |  |  |Y |Y |Y |  |Y |Y |  |  |  |  |
PIDA              |LW|F |Y |Y |  |  |  |Y |Y |Y |  |Y |  |  |  |  |  |VIM based
PTVS              |W |F |Y |Y |Y |Y |Y |Y |Y |Y |  |Y |  |  |Y*|  |Y |*WPF bsed
PyCharm           |Y |CF|Y |Y*|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |*JavaScript
PyDev (Eclipse)   |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |  |  |  |
PyScripter        |W |F |Y |  |Y |Y |  |Y |Y |Y |  |Y |Y |Y |  |  |  |
PythonWin         |W |F |Y |  |Y |  |  |Y |Y |  |  |Y |  |  |  |  |  |
SciTE             |Y |F¹|  |Y |  |Y |  |Y |Y |Y |  |Y |Y |  |  |  |  |¹Mac version is
ScriptDev         |W |C |Y |Y |Y |Y |  |Y |Y |Y |  |Y |Y |  |  |  |  |    commercial
Spyder            |Y |F |Y |  |Y |Y |  |Y |Y |Y |  |  |  |  |  |  |  |
Sublime Text      |Y |CF|Y |Y |  |Y |Y |Y |Y |Y |  |Y |Y |Y*|  |  |  |extensible w/Python,
TextMate          |M |F |  |Y |  |  |Y |Y |Y |Y |  |Y |Y |  |  |  |  |    *PythonTestRunner
UliPad            |Y |F |Y |Y |Y |  |  |Y |Y |  |  |  |Y |Y |  |  |  |
Vim               |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |  |  |
Visual Studio     |W |CF|Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |Y |? |Y |
Visual Studio Code|Y |F |Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |? |? |Y |uses plugins
WingIde           |Y |C |Y |Y*|Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |  |  |*support for C
Zeus              |W |C |  |  |  |  |Y |Y |Y |Y |  |Y |Y |  |  |  |  |
                  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
   Cross Platform -'  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |     
     Commercial/Free -'  |  |  |  |  |  |  |  |  |  |  |  |  |  |  '- Refactoring
   Auto Code Completion -'  |  |  |  |  |  |  |  |  |  |  |  |  '- Integrated DB Support
    Multi-Language Support -'  |  |  |  |  |  |  |  |  |  |  '- GUI Designer (Qt, Eric, etc)
  Integrated Python Debugging -'  |  |  |  |  |  |  |  |  '- Unit Testing
                    Error Markup -'  |  |  |  |  |  |  '- Code Templates
         Source Control Integration -'  |  |  |  |  '- Code Folding
                          Smart Indent -'  |  |  '- UML Editing / Viewing
                         Bracket Matching -'  '- Line Numbering

Acronyms used:

 L  - Linux
 W  - Windows
 M  - Mac
 C  - Commercial
 F  - Free
 CF - Commercial with Free limited edition
 ?  - To be confirmed

I don't mention basics like syntax highlighting as I expect these by default.


This is a just dry list reflecting your feedback and comments, I am not advocating any of these tools. I will keep updating this list as you keep posting your answers.

PS. Can you help me to add features of the above editors to the list (like auto-complete, debugging, etc.)?

We have a comprehensive wiki page for this question https://wiki.python.org/moin/IntegratedDevelopmentEnvironments

Submit edits to the spreadsheet

TCP vs UDP on video stream

Besides all the other reasons, UDP can use multicast. Supporting 1000s of TCP users all transmitting the same data wastes bandwidth. However, there is another important reason for using TCP.

TCP can much more easily pass through firewalls and NATs. Depending on your NAT and operator, you may not even be able to receive a UDP stream due to problems with UDP hole punching.

How can I format date by locale in Java?

Joda-Time

Using the Joda-Time 2.4 library. The DateTimeFormat class is a factory of DateTimeFormatter formatters. That class offers a forStyle method to access formatters appropriate to a Locale.

DateTimeFormatter formatter = DateTimeFormat.forStyle( "MM" ).withLocale( Java.util.Locale.CANADA_FRENCH );
String output = formatter.print( DateTime.now( DateTimeZone.forID( "America/Montreal" ) ) );

The argument with two letters specifies a format for the date portion and the time portion. Specify a character of 'S' for short style, 'M' for medium, 'L' for long, and 'F' for full. A date or time may be ommitted by specifying a style character '-' HYPHEN.

Note that we specified both a Locale and a time zone. Some people confuse the two.

  • A time zone is an offset from UTC and a set of rules for Daylight Saving Time and other anomalies along with their historical changes.
  • A Locale is a human language such as Français, plus a country code such as Canada that represents cultural practices including formatting of date-time strings.

We need all those pieces to properly generate a string representation of a date-time value.

sklearn error ValueError: Input contains NaN, infinity or a value too large for dtype('float64')

dataset = dataset.dropna(axis=0, how='any', thresh=None, subset=None, inplace=False)

This worked for me

Best practices for circular shift (rotate) operations in C++

If x is an 8 bit value, you can use this:

x=(x>>1 | x<<7);

Convert data file to blob

A file object is an instance of Blob but a blob object is not an instance of File

new File([], 'foo.txt').constructor.name === 'File' //true
new File([], 'foo.txt') instanceof File // true
new File([], 'foo.txt') instanceof Blob // true

new Blob([]).constructor.name === 'Blob' //true
new Blob([]) instanceof Blob //true
new Blob([]) instanceof File // false

new File([], 'foo.txt').constructor.name === new Blob([]).constructor.name //false

If you must convert a file object to a blob object, you can create a new Blob object using the array buffer of the file. See the example below.

let file = new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'});
//or let file = document.querySelector('input[type=file]').files[0];
let reader = new FileReader();
reader.onload = function(e) {
    let blob = new Blob([new Uint8Array(e.target.result)], {type: file.type });
    console.log(blob);
};
reader.readAsArrayBuffer(file);

As pointed by @bgh you can also use the arrayBuffer method of the File object. See the example below.

let file = new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'});
//or let file = document.querySelector('input[type=file]').files[0];

file.arrayBuffer().then((arrayBuffer) => {
    let blob = new Blob([new Uint8Array(arrayBuffer)], {type: file.type });
    console.log(blob);
});

If your environment supports async/await you can use a one-liner like below

let fileToBlob = async (file) => new Blob([new Uint8Array(await file.arrayBuffer())], {type: file.type });
console.log(await fileToBlob(new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'})));

Eclipse HotKey: how to switch between tabs?

One way to do it is to use the VI Plugin, and then you just do :n (and :N) to go between files.

That's what I do.

How do I install the Nuget provider for PowerShell on a unconnected machine so I can install a nuget package from the PS command line?

MSDocs state this for your scenario:

In order to execute the first time, PackageManagement requires an internet connection to download the Nuget package provider. However, if your computer does not have an internet connection and you need to use the Nuget or PowerShellGet provider, you can download them on another computer and copy them to your target computer. Use the following steps to do this:

  1. Run Install-PackageProvider -Name NuGet -RequiredVersion 2.8.5.201 -Force to install the provider from a computer with an internet connection.

  2. After the install, you can find the provider installed in $env:ProgramFiles\PackageManagement\ReferenceAssemblies\\\<ProviderName\>\\\<ProviderVersion\> or $env:LOCALAPPDATA\PackageManagement\ProviderAssemblies\\\<ProviderName\>\\\<ProviderVersion\>.

  3. Place the folder, which in this case is the Nuget folder, in the corresponding location on your target computer. If your target computer is a Nano server, you need to run Install-PackageProvider from Nano Server to download the correct Nuget binaries.

  4. Restart PowerShell to auto-load the package provider. Alternatively, run Get-PackageProvider -ListAvailable to list all the package providers available on the computer. Then use Import-PackageProvider -Name NuGet -RequiredVersion 2.8.5.201 to import the provider to the current Windows PowerShell session.

Html: Difference between cell spacing and cell padding

cellspacing and cell padding


Cell padding

is used for formatting purpose which is used to specify the space needed between the edges of the cells and also in the cell contents. The general format of specifying cell padding is as follows:

< table width="100" border="2" cellpadding="5">

The above adds 5 pixels of padding inside each cell .

Cell Spacing:

Cell spacing is one also used f formatting but there is a major difference between cell padding and cell spacing. It is as follows: Cell padding is used to set extra space which is used to separate cell walls from their contents. But in contrast cell spacing is used to set space between cells.

Python mock multiple return values

You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'

Quoting the Mock() documentation:

If side_effect is an iterable then each call to the mock will return the next value from the iterable.

Uploading multiple files using formData()

Adding [] when appending to fd works, but if you prefer to have your data grouped by file then I'd suggest doing it this way:

var files= document.getElementById('inpFile').files
var fd = new FormData()

for (let i = 0; i < files.length; i++) {
  fd.append(i, files[i])
}

Now your data will be sent grouped by file instead of grouped by attribute.

T-SQL Subquery Max(Date) and Joins

SELECT
    MyParts.*,MyPriceDate.Price,MyPriceDate.PriceDate
    FROM MyParts
        INNER JOIN (SELECT Partid, MAX(PriceDate) AS MaxPriceDate FROM MyPrice GROUP BY Partid) dt ON MyParts.Partid = dt.Partid
        INNER JOIN MyPrice ON dt.Partid = MyPrice.Partid AND MyPrice.PriceDate=dt.MaxPriceDate

Java and SSL - java.security.NoSuchAlgorithmException

Try javax.net.ssl.keyStorePassword instead of javax.net.ssl.keyPassword: the latter isn't mentioned in the JSSE ref guide.

The algorithms you mention should be there by default using the default security providers. NoSuchAlgorithmExceptions are often cause by other underlying exceptions (file not found, wrong password, wrong keystore type, ...). It's useful to look at the full stack trace.

You could also use -Djavax.net.debug=ssl, or at least -Djavax.net.debug=ssl,keymanager, to get more debugging information, if the information in the stack trace isn't sufficient.

SQL Server: use CASE with LIKE

Add an END at last before alias name.

CASE WHEN countries LIKE '%'+@selCountry+'%' 
     THEN 'national' ELSE 'regional' 
END AS validity

For example:

SELECT CASE WHEN countries LIKE '%'+@selCountry+'%' 
       THEN 'national' ELSE 'regional' 
       END AS validity
FROM TableName

error CS0234: The type or namespace name 'Script' does not exist in the namespace 'System.Web'

I found this MSDN forum post which suggests two solutions to your problem.

First solution (not recommended):

Find the .Net Framework 3.5 and 2.0 folder

Copy System.Web.Extensions.dll from 3.5 and System.Web.dll from 2.0 to the application folder

Add the reference to these two assemblies

Change the referenced assemblies property, setting "Copy Local" to true And build to test your application to ensure all code can work

Second solution (Use a different class / library):

The user who had posted the question claimed that Uri.EscapeUriString and How to: Serialize and Deserialize JSON Data helped him replicate the behavior of JavaScriptSerializer.

You could also try to use Json.Net. It's a third party library and pretty powerful.

How to create unit tests easily in eclipse

Any unit test you could create by just pressing a button would not be worth anything. How is the tool to know what parameters to pass your method and what to expect back? Unless I'm misunderstanding your expectations.

Close to that is something like FitNesse, where you can set up tests, then separately you set up a wiki page with your test data, and it runs the tests with that data, publishing the results as red/greens.

If you would be happy to make test writing much faster, I would suggest Mockito, a mocking framework that lets you very easily mock the classes around the one you're testing, so there's less setup/teardown, and you know you're really testing that one class instead of a dependent of it.

Renaming branches remotely in Git

First checkout to the branch which you want to rename:

git branch -m old_branch new_branch
git push -u origin new_branch

To remove an old branch from remote:

git push origin :old_branch

Getting new Twitter API consumer and secret keys

consumer_key = API key

consumer_secret = API key secret

Found it hidden in Twitter API Docs

Twitter Docs screenshot

Twitter's naming is just too confusing.

How do I debug "Error: spawn ENOENT" on node.js?

in windows, simply adding shell: true option solved my problem:

incorrect:

const { spawn } = require('child_process');
const child = spawn('dir');

correct:

const { spawn } = require('child_process');
const child = spawn('dir', [], {shell: true});

What is the minimum length of a valid international phone number?

EDIT 2015-06-27: Minimum is actually 8, including country code. My bad.

Original post

The minimum phone number that I use is 10 digits. International users should always be putting their country code, and as far as I know there are no countries with fewer than ten digits if you count country code.

More info here: https://en.wikipedia.org/wiki/Telephone_numbering_plan

PHP ternary operator vs null coalescing operator

The other answers goes deep and give great explanations. For those who look for quick answer,

$a ?: 'fallback' is $a ? $a : 'fallback'

while

$a ?? 'fallback' is $a = isset($a) ? $a : 'fallback'


The main difference would be when the left operator is either:

  • A falsy value that is NOT null (0, '', false, [], ...)
  • An undefined variable

Multiline TextBox multiple newline

When page IsPostback, the following code work correctly. But when page first loading, there is not multiple newline in the textarea. Bug

textBox1.Text = "Line1\r\n\r\n\r\nLine2";

Download and open PDF file using Ajax

What worked for me is the following code, as the server function is retrieving File(memoryStream.GetBuffer(), "application/pdf", "fileName.pdf");:

$http.get( fullUrl, { responseType: 'arraybuffer' })
            .success(function (response) {
                var blob = new Blob([response], { type: 'application/pdf' });

                if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                    window.navigator.msSaveOrOpenBlob(blob); // for IE
                }
                else {
                    var fileURL = URL.createObjectURL(blob);
                    var newWin = window.open(fileURL);
                    newWin.focus();
                    newWin.reload();
                }
});

About the Full Screen And No Titlebar from manifest

If your Manifest.xml has the default android:theme="@style/AppTheme"

Go to res/values/styles.xml and change

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

to

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

And the ActionBar is disappeared!

OS X Terminal Colors

MartinVonMartinsgrün and 4Levels methods confirmed work great on Mac OS X Mountain Lion.

The file I needed to update was ~/.profile.

However, I couldn't leave this question without recommending my favorite application, iTerm 2.

iTerm 2 lets you load global color schemes from a file. Really easy to experiment and try a bunch of color schemes.

Here's a screenshot of the iTerm 2 window and the color preferences. iTerm2 Color Preferences Screenshot Mac

Once I added the following to my ~/.profile file iTerm 2 was able to override the colors.

export CLICOLOR=1
export LSCOLORS=GxFxCxDxBxegedabagaced
export PS1='\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '

Here is a great repository with some nice presets:

iTerm2 Color Schemes on Github by mbadolato

Bonus: Choose "Show/hide iTerm2 with a system-wide hotkey" and bind the key with BetterTouchTool for an instant hide/show the terminal with a mouse gesture.

Using Rsync include and exclude options to include directory and file by pattern

Here's my "teach a person to fish" answer:

Rsync's syntax is definitely non-intuitive, but it is worth understanding.

  1. First, use -vvv to see the debug info for rsync.
$ rsync -nr -vvv --include="**/file_11*.jpg" --exclude="*" /Storage/uploads/ /website/uploads/

[sender] hiding directory 1280000000 because of pattern *
[sender] hiding directory 1260000000 because of pattern *
[sender] hiding directory 1270000000 because of pattern *

The key concept here is that rsync applies the include/exclude patterns for each directory recursively. As soon as the first include/exclude is matched, the processing stops.

The first directory it evaluates is /Storage/uploads. Storage/uploads has 1280000000/, 1260000000/, 1270000000/ dirs/files. None of them match file_11*.jpg to include. All of them match * to exclude. So they are excluded, and rsync ends.

  1. The solution is to include all dirs (*/) first. Then the first dir component will be 1260000000/, 1270000000/, 1280000000/ since they match */. The next dir component will be 1260000000/. In 1260000000/, file_11_00.jpg matches --include="file_11*.jpg", so it is included. And so forth.
$ rsync -nrv --include='*/' --include="file_11*.jpg" --exclude="*" /Storage/uploads/ /website/uploads/

./
1260000000/
1260000000/file_11_00.jpg
1260000000/file_11_01.jpg
1270000000/
1270000000/file_11_00.jpg
1270000000/file_11_01.jpg
1280000000/
1280000000/file_11_00.jpg
1280000000/file_11_01.jpg

https://download.samba.org/pub/rsync/rsync.1

How do I concatenate const/literal strings in C?

Folks, use strncpy(), strncat(), or snprintf().
Exceeding your buffer space will trash whatever else follows in memory!
(And remember to allow space for the trailing null '\0' character!)

Why are my PowerShell scripts not running?

We can bypass execution policy in a nice way (inside command prompt):

type file.ps1 | powershell -command -

Or inside powershell:

gc file.ps1|powershell -c -

Getting the last element of a split string array

var str = "hello,how,are,you,today?";
var pieces = str.split(/[\s,]+/);

At this point, pieces is an array and pieces.length contains the size of the array so to get the last element of the array, you check pieces[pieces.length-1]. If there are no commas or spaces it will simply output the string as it was given.

alert(pieces[pieces.length-1]); // alerts "today?"

Android Studio-No Module

For me the sdk version mentioned in build.gradle wasn't installed. Used SDK Manager to install the right SDK version and it worked

How can I use Async with ForEach?

List<T>.ForEach doesn't play particularly well with async (neither does LINQ-to-objects, for the same reasons).

In this case, I recommend projecting each element into an asynchronous operation, and you can then (asynchronously) wait for them all to complete.

using (DataContext db = new DataLayer.DataContext())
{
    var tasks = db.Groups.ToList().Select(i => GetAdminsFromGroupAsync(i.Gid));
    var results = await Task.WhenAll(tasks);
}

The benefits of this approach over giving an async delegate to ForEach are:

  1. Error handling is more proper. Exceptions from async void cannot be caught with catch; this approach will propagate exceptions at the await Task.WhenAll line, allowing natural exception handling.
  2. You know that the tasks are complete at the end of this method, since it does an await Task.WhenAll. If you use async void, you cannot easily tell when the operations have completed.
  3. This approach has a natural syntax for retrieving the results. GetAdminsFromGroupAsync sounds like it's an operation that produces a result (the admins), and such code is more natural if such operations can return their results rather than setting a value as a side effect.

Bootstrap Carousel Full Screen

I found an answer on the startbootstrap.com. Try this code:

CSS

html,
body {
    height: 100%;
}

.carousel,
.item,
.active {
    height: 100%;
}


.carousel-inner {
    height: 100%;
}

/* Background images are set within the HTML using inline CSS, not here */

.fill {
    width: 100%;
    height: 100%;
    background-position: center;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    background-size: cover;
    -o-background-size: cover;
}

footer {
    margin: 50px 0;
}

HTML

   <div class="carousel-inner">
        <div class="item active">
            <!-- Set the first background image using inline CSS below. -->
            <div class="fill" style="background-image:url('http://placehold.it/1900x1080&text=Slide One');"></div>
            <div class="carousel-caption">
                <h2>Caption 1</h2>
            </div>
        </div>
        <div class="item">
            <!-- Set the second background image using inline CSS below. -->
            <div class="fill" style="background-image:url('http://placehold.it/1900x1080&text=Slide Two');"></div>
            <div class="carousel-caption">
                <h2>Caption 2</h2>
            </div>
        </div>
        <div class="item">
            <!-- Set the third background image using inline CSS below. -->
            <div class="fill" style="background-image:url('http://placehold.it/1900x1080&text=Slide Three');"></div>
            <div class="carousel-caption">
                <h2>Caption 3</h2>
            </div>
        </div>
    </div>

Source

How to install gem from GitHub source?

Try the specific_install gem it allows you you to install a gem from its github repository (like 'edge'), or from an arbitrary URL. Very usefull for forking gems and hacking on them on multiple machines and such.

gem install specific_install
gem specific_install -l <url to a github gem>

e.g.

gem specific_install https://github.com/githubsvnclone/rdoc.git 

Tomcat 8 is not able to handle get request with '|' in query parameters?

The URI is encoded as UTF-8, but Tomcat is decoding them as ISO-8859-1. You need to edit the connector settings in the server.xml and add the URIEncoding="UTF-8" attribute.

or edit this parameter on your application.properties

server.tomcat.uri-encoding=utf-8

Calculating text width

Sometimes you also need to measure additionally height and not only text, but also HTML width. I took @philfreo answer and made it more flexbile and useful:

function htmlDimensions(html, font) {
  if (!htmlDimensions.dummyEl) {
    htmlDimensions.dummyEl = $('<div>').hide().appendTo(document.body);
  }
  htmlDimensions.dummyEl.html(html).css('font', font);
  return {
    height: htmlDimensions.dummyEl.height(),
    width: htmlDimensions.dummyEl.width()
  };
}