Programs & Examples On #Screensaver

A screensaver is a visual program that runs after a period of inactivity.

How to prevent Google Colab from disconnecting?

Well this is working for me -

run the following code in the console and it will prevent you from disconnecting. Ctrl+ Shift + i to open inspector view . Then go to console.

function ClickConnect(){
    console.log("Working"); 
    document.querySelector("colab-toolbar-button#connect").click() 
}
setInterval(ClickConnect,60000)

How to prevent google colab from disconnecting

powershell mouse move does not prevent idle mode

I had a similar situation where a download needed to stay active overnight and required a key press that refreshed my connection. I also found that the mouse move does not work. However, using notepad and a send key function appears to have done the trick. I send a space instead of a "." because if there is a [yes/no] popup, it will automatically click the default response using the spacebar. Here is the code used.

param($minutes = 120)

$myShell = New-Object -com "Wscript.Shell"

for ($i = 0; $i -lt $minutes; $i++) {
  Start-Sleep -Seconds 30
  $myShell.sendkeys(" ")
}

This function will work for the designated 120 minutes (2 Hours), but can be modified for the timing desired by increasing or decreasing the seconds of the input, or increasing or decreasing the assigned value of the minutes parameter.

Just run the script in powershell ISE, or powershell, and open notepad. A space will be input at the specified interval for the desired length of time ($minutes).

Good Luck!

Android disable screen timeout while app is running

This can be done by acquiring a Wake Lock.

I didn't tested it myself, but here is a small tutorial on this.

Multiple commands in an alias for bash

So use a semi-colon:

alias lock='gnome-screensaver; gnome-screen-saver-command --lock'

This doesn't work well if you want to supply arguments to the first command. Alternatively, create a trivial script in your $HOME/bin directory.

Signing a Windows EXE file

The ASP's magazine ASPects has a detailed description on how to sign code (You have to be a member to read the article). You can download it through http://www.asp-shareware.org/

Here's link to a description how you can make your own test certificate.

This might also be interesting.

Failed to resolve: com.android.support:cardview-v7:26.0.0 android

compile 'com.android.support:cardview-v7:+' 

This should pull the most recent version, and allow it to compile.

Response.Redirect with POST instead of Get?

Copy-pasteable code based on Pavlo Neyman's method

RedirectPost(string url, T bodyPayload) and GetPostData() are for those who just want to dump some strongly typed data in the source page and fetch it back in the target one. The data must be serializeable by NewtonSoft Json.NET and you need to reference the library of course.

Just copy-paste into your page(s) or better yet base class for your pages and use it anywhere in you application.

My heart goes out to all of you who still have to use Web Forms in 2019 for whatever reason.

        protected void RedirectPost(string url, IEnumerable<KeyValuePair<string,string>> fields)
        {
            Response.Clear();

            const string template =
@"<html>
<body onload='document.forms[""form""].submit()'>
<form name='form' action='{0}' method='post'>
{1}
</form>
</body>
</html>";

            var fieldsSection = string.Join(
                    Environment.NewLine,
                    fields.Select(x => $"<input type='hidden' name='{HttpUtility.UrlEncode(x.Key)}' value='{HttpUtility.UrlEncode(x.Value)}'>")
                );

            var html = string.Format(template, HttpUtility.UrlEncode(url), fieldsSection);

            Response.Write(html);

            Response.End();
        }

        private const string JsonDataFieldName = "_jsonData";

        protected void RedirectPost<T>(string url, T bodyPayload)
        {
            var json = JsonConvert.SerializeObject(bodyPayload, Formatting.Indented);
            //explicit type declaration to prevent recursion
            IEnumerable<KeyValuePair<string, string>> postFields = new List<KeyValuePair<string, string>>()
                {new KeyValuePair<string, string>(JsonDataFieldName, json)};

            RedirectPost(url, postFields);

        }

        protected T GetPostData<T>() where T: class 
        {
            var urlEncodedFieldData = Request.Params[JsonDataFieldName];
            if (string.IsNullOrEmpty(urlEncodedFieldData))
            {
                return null;// default(T);
            }

            var fieldData = HttpUtility.UrlDecode(urlEncodedFieldData);

            var result = JsonConvert.DeserializeObject<T>(fieldData);
            return result;
        }

How to convert / cast long to String?

1.

long date = curDateFld.getDate();
//convert long to string
String str = String.valueOf(date);

//convert string to long
date = Long.valueOf(str);

2.

 //convert long to string just concat long with empty string
 String str = ""+date;
//convert string to long

date = Long.valueOf(str);

Get a specific bit from byte

Try the code below. The difference with other posts is that you can set/get multiple bits using a mask (field). The mask for the 4th bit can be 1<<3, or 0x10, for example.

    public int SetBits(this int target, int field, bool value)
    {
        if (value) //set value
        {
            return target | field;
        }
        else //clear value
        {
            return target & (~field);
        }
    }

    public bool GetBits(this int target, int field)
    {
        return (target & field) > 0;
    }

** Example **

        bool is_ok = 0x01AF.GetBits(0x10); //false
        int res = 0x01AF.SetBits(0x10, true);
        is_ok = res.GetBits(0x10);  // true

Rounding BigDecimal to *always* have two decimal places

value = value.setScale(2, RoundingMode.CEILING)

Java Replace Character At Specific Position Of String?

Petar Ivanov's answer to replace a character at a specific index in a string question

String are immutable in Java. You can't change them.

You need to create a new string with the character replaced.

String myName = "domanokz";
String newName = myName.substring(0,4)+'x'+myName.substring(5);

Or you can use a StringBuilder:

StringBuilder myName = new StringBuilder("domanokz");
myName.setCharAt(4, 'x');

System.out.println(myName);

How should I copy Strings in Java?

Second case is also inefficient in terms of String pool, you have to explicitly call intern() on return reference to make it intern.

Depend on a branch or tag using a git URL in a package.json?

If you want to use devel or feature branch, or you haven’t published a certain package to the NPM registry, or you can’t because it’s a private module, then you can point to a git:// URI instead of a version number in your package.json:

"dependencies": {
   "public": "git://github.com/user/repo.git#ref",
   "private": "git+ssh://[email protected]:user/repo.git#ref"
}

The #ref portion is optional, and it can be a branch (like master), tag (like 0.0.1) or a partial or full commit id.

Git - What is the difference between push.default "matching" and "simple"

Git v2.0 Release Notes

Backward compatibility notes

When git push [$there] does not say what to push, we have used the traditional "matching" semantics so far (all your branches were sent to the remote as long as there already are branches of the same name over there). In Git 2.0, the default is now the "simple" semantics, which pushes:

  • only the current branch to the branch with the same name, and only when the current branch is set to integrate with that remote branch, if you are pushing to the same remote as you fetch from; or

  • only the current branch to the branch with the same name, if you are pushing to a remote that is not where you usually fetch from.

You can use the configuration variable "push.default" to change this. If you are an old-timer who wants to keep using the "matching" semantics, you can set the variable to "matching", for example. Read the documentation for other possibilities.

When git add -u and git add -A are run inside a subdirectory without specifying which paths to add on the command line, they operate on the entire tree for consistency with git commit -a and other commands (these commands used to operate only on the current subdirectory). Say git add -u . or git add -A . if you want to limit the operation to the current directory.

git add <path> is the same as git add -A <path> now, so that git add dir/ will notice paths you removed from the directory and record the removal. In older versions of Git, git add <path> used to ignore removals. You can say git add --ignore-removal <path> to add only added or modified paths in <path>, if you really want to.

Oracle DB: How can I write query ignoring case?

Select * from table where upper(table.name) like upper('IgNoreCaSe');

Alternatively, substitute lower for upper.

Html.RenderPartial() syntax with Razor

  • RenderPartial() is a void method that writes to the response stream. A void method, in C#, needs a ; and hence must be enclosed by { }.

  • Partial() is a method that returns an MvcHtmlString. In Razor, You can call a property or a method that returns such a string with just a @ prefix to distinguish it from plain HTML you have on the page.

extract date only from given timestamp in oracle sql

In Oracle 11g, To get the complete date from the Timestamp, use this-

Select TRUNC(timestamp) FROM TABLE_NAME;

To get the Year from the Timestamp, use this-

Select EXTRACT(YEAR FROM TRUNC(timestamp)) from TABLE_NAME;

To get the Month from the Timestamp, use this-

Select EXTRACT(MONTH FROM TRUNC(timestamp)) from TABLE_NAME;

To get the Day from the Timestamp, use this-

Select EXTRACT(DAY FROM TRUNC(timestamp)) from TABLE_NAME;

How can I create a self-signed cert for localhost?

In a LAN (Local Area Network) we have a server computer, here named xhost running Windows 10, IIS is activated as WebServer. We must access this computer via Browser like Google Chrome not only from localhost through https://localhost/ from server itsself, but also from other hosts in the LAN with URL https://xhost/ :


https://localhost/
https://xhost/
https://xhost.local/
...

With this manner of accessing, we have not a fully-qualified domain name, but only local computer name xhost here.

Or from WAN:


https://dev.example.org/
...

You shall replace xhost by your real local computer name.

None of above solutions may satisfy us. After days of try, we have adopted the solution openssl.exe. We use 2 certificates - a CA (self certified Authority certificate) RootCA.crt and xhost.crt certified by the former. We use PowerShell.

1. Create and change to a safe directory:

cd C:\users\so\crt

2. Generate RootCA.pem, RootCA.key & RootCA.crt as self-certified Certification Authority:


openssl req -x509 -nodes -new -sha256 -days 10240 -newkey rsa:2048 -keyout RootCA.key -out RootCA.pem -subj "/C=ZA/CN=RootCA-CA"
openssl x509 -outform pem -in RootCA.pem -out RootCA.crt

3. make request for certification: xhost.key, xhost.csr:

C: Country
ST: State
L: locality (city)
O: Organization Name
Organization Unit
CN: Common Name

    

openssl req -new -nodes -newkey rsa:2048 -keyout xhost.key -out xhost.csr -subj "/C=ZA/ST=FREE STATE/L=Golden Gate Highlands National Park/O=WWF4ME/OU=xhost.home/CN=xhost.local"

4. get xhost.crt certified by RootCA.pem:


openssl x509 -req -sha256 -days 1024 -in xhost.csr -CA RootCA.pem -CAkey RootCA.key -CAcreateserial -extfile domains.ext -out xhost.crt

with extfile domains.ext file defining many secured ways of accessing the server website:

authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = localhost
DNS.2 = xhost
DNS.3 = xhost.local
DNS.4 = dev.example.org
DNS.5 = 192.168.1.2

5. Make xhost.pfx PKCS #12,

combinig both private xhost.key and certificate xhost.crt, permitting to import into iis. This step asks for password, please let it empty by pressing [RETURN] key (without password):


openssl pkcs12 -export -out xhost.pfx -inkey xhost.key -in xhost.crt

6. import xhost.pfx in iis10

installed in xhost computer (here localhost). and Restart IIS service.

IIS10 Gestionnaire des services Internet (IIS) (%windir%\system32\inetsrv\InetMgr.exe)

enter image description here

enter image description here

7. Bind ssl with xhost.local certificate on port 443.

enter image description here

Restart IIS Service.

8. Import RootCA.crt into Trusted Root Certification Authorities

via Google Chrome in any computer that will access the website https://xhost/.

\Google Chrome/…/Settings /[Advanced]/Privacy and Security/Security/Manage certificates

Import RootCA.crt

enter image description here

The browser will show this valid certificate tree:


RootCA-CA
  |_____ xhost.local

enter image description here

No Certificate Error will appear through LAN, even through WAN by https://dev.example.org.

enter image description here

Here is the whole Powershell Script socrt.ps1 file to generate all required certificate files from the naught:


#
# Generate:
#   RootCA.pem, RootCA.key RootCA.crt
#
#   xhost.key xhost.csr xhost.crt
#   xhost.pfx
#
# created  15-EEC-2020
# modified 15-DEC-2020
#
#
# change to a safe directory:
#

cd C:\users\so\crt

#
# Generate RootCA.pem, RootCA.key & RootCA.crt as Certification Authority:
#
openssl req -x509 -nodes -new -sha256 -days 10240 -newkey rsa:2048 -keyout RootCA.key -out RootCA.pem -subj "/C=ZA/CN=RootCA-CA"
openssl x509 -outform pem -in RootCA.pem -out RootCA.crt

#
# get RootCA.pfx: permitting to import into iis10: not required.
#
#openssl pkcs12 -export -out RootCA.pfx -inkey RootCA.key -in RootCA.crt

#
# get xhost.key xhost.csr:
#   C: Country
#   ST: State
#   L: locality (city)
#   O: Organization Name
#   OU: Organization Unit
#   CN: Common Name
#
openssl req -new -nodes -newkey rsa:2048 -keyout xhost.key -out xhost.csr -subj "/C=ZA/ST=FREE STATE/L=Golden Gate Highlands National Park/O=WWF4ME/OU=xhost.home/CN=xhost.local"

#
# get xhost.crt certified by RootCA.pem:
# to show content:
#   openssl x509 -in xhost.crt -noout -text
#
openssl x509 -req -sha256 -days 1024 -in xhost.csr -CA RootCA.pem -CAkey RootCA.key -CAcreateserial -extfile domains.ext -out xhost.crt

#
# get xhost.pfx, permitting to import into iis:
#
openssl pkcs12 -export -out xhost.pfx -inkey xhost.key -in xhost.crt

#
# import xhost.pfx in iis10 installed in xhost computer (here localhost).
#

To install openSSL for Windows, please visit https://slproweb.com/products/Win32OpenSSL.html

Convert int to a bit array in .NET

I would achieve it in a one-liner as shown below:

using System;
using System.Collections;

namespace stackoverflowQuestions
{
    class Program
    {
        static void Main(string[] args)
        {    
            //get bit Array for number 20
            var myBitArray = new BitArray(BitConverter.GetBytes(20));
        }
    }
}

Please note that every element of a BitArray is stored as bool as shown in below snapshot:

enter image description here

So below code works:

if (myBitArray[0] == false)
{
    //this code block will execute
}

but below code doesn't compile at all:

if (myBitArray[0] == 0)
{
    //some code
}

How can I combine two commits into one commit?

You want to git rebase -i to perform an interactive rebase.

If you're currently on your "commit 1", and the commit you want to merge, "commit 2", is the previous commit, you can run git rebase -i HEAD~2, which will spawn an editor listing all the commits the rebase will traverse. You should see two lines starting with "pick". To proceed with squashing, change the first word of the second line from "pick" to "squash". Then save your file, and quit. Git will squash your first commit into your second last commit.

Note that this process rewrites the history of your branch. If you are pushing your code somewhere, you'll have to git push -f and anybody sharing your code will have to jump through some hoops to pull your changes.

Note that if the two commits in question aren't the last two commits on the branch, the process will be slightly different.

What is the "-->" operator in C/C++?

It's

#include <stdio.h>

int main(void) {
  int x = 10;
  while (x-- > 0) { // x goes to 0
    printf("%d ", x);
  }
  return 0;
}

Just the space makes the things look funny, -- decrements and > compares.

LISTAGG function: "result of string concatenation is too long"

SELECT RTRIM(XMLAGG(XMLELEMENT(E,colname,',').EXTRACT('//text()') ORDER BY colname).GetClobVal(),',') AS LIST
FROM tablename;

This will return a clob value, so no limit on rows.

Storing integer values as constants in Enum manner in java

I found this to be helpful:

http://dan.clarke.name/2011/07/enum-in-java-with-int-conversion/

public enum Difficulty
{
    EASY(0),
    MEDIUM(1),
    HARD(2);

    /**
    * Value for this difficulty
    */
    public final int Value;

    private Difficulty(int value)
    {
        Value = value;
    }

    // Mapping difficulty to difficulty id
    private static final Map<Integer, Difficulty> _map = new HashMap<Integer, Difficulty>();
    static
    {
        for (Difficulty difficulty : Difficulty.values())
            _map.put(difficulty.Value, difficulty);
    }

    /**
    * Get difficulty from value
    * @param value Value
    * @return Difficulty
    */
    public static Difficulty from(int value)
    {
        return _map.get(value);
    }
}

List supported SSL/TLS versions for a specific OpenSSL build

This worked for me:

openssl s_client -help 2>&1  > /dev/null | egrep "\-(ssl|tls)[^a-z]"

Please let me know if this is wrong.

Why can't Python parse this JSON data?

There are two types in this parsing.

  1. Parsing data from a file from a system path
  2. Parsing JSON from remote URL.

From a file, you can use the following

import json
json = json.loads(open('/path/to/file.json').read())
value = json['key']
print json['value']

This arcticle explains the full parsing and getting values using two scenarios.Parsing JSON using Python

How to force two figures to stay on the same page in LaTeX?

If you want them both on the same page and they'll both take up basically the whole page, then the best idea is to tell LaTeX to put them both on a page of their own!

\begin{figure}[p]

It would probably be against sound typographic principles (e.g., ugly) to have two figures on a page with only a few lines of text above or below them.


By the way, the reason that [!h] works is because it's telling LaTeX to override its usual restrictions on how much space should be devoted to floats on a page with text. As implied above, there's a reason the restrictions are there. Which isn't to say they can be loosened somewhat; see the FAQ on doing that.

Search all the occurrences of a string in the entire project in Android Studio

In Android 3.6 on a Mac if you want to export the results to a text file then do the following

Command+Shift+F then enter the text you want to search

Then on Bottom Right click on "Open In Find Window"

Then Right Click On Found Occurrences

Then Export To Text File

Once in text file you can find and replace to remove, sort lines etc... please see screenshots for assistance.

enter image description here

enter image description here

URL Encode a string in jQuery for an AJAX request

try this one

var query = "{% url accounts.views.instasearch  %}?q=" + $('#tags').val().replace(/ /g, '+');

C++11 thread-safe queue

You may like lfqueue, https://github.com/Taymindis/lfqueue. It’s lock free concurrent queue. I’m currently using it to consuming the queue from multiple incoming calls and works like a charm.

Transparent ARGB hex value

Adding to the other answers and doing nothing more of what @Maleta explained in a comment on https://stackoverflow.com/a/28481374/1626594, doing alpha*255 then round then to hex. Here's a quick converter http://jsfiddle.net/8ajxdLap/4/

_x000D_
_x000D_
function rgb2hex(rgb) {_x000D_
  var rgbm = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?((?:[0-9]*[.])?[0-9]+)[\s+]?\)/i);_x000D_
  if (rgbm && rgbm.length === 5) {_x000D_
    return "#" +_x000D_
      ('0' + Math.round(parseFloat(rgbm[4], 10) * 255).toString(16).toUpperCase()).slice(-2) +_x000D_
      ("0" + parseInt(rgbm[1], 10).toString(16).toUpperCase()).slice(-2) +_x000D_
      ("0" + parseInt(rgbm[2], 10).toString(16).toUpperCase()).slice(-2) +_x000D_
      ("0" + parseInt(rgbm[3], 10).toString(16).toUpperCase()).slice(-2);_x000D_
  } else {_x000D_
    var rgbm = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);_x000D_
    if (rgbm && rgbm.length === 4) {_x000D_
      return "#" +_x000D_
        ("0" + parseInt(rgbm[1], 10).toString(16).toUpperCase()).slice(-2) +_x000D_
        ("0" + parseInt(rgbm[2], 10).toString(16).toUpperCase()).slice(-2) +_x000D_
        ("0" + parseInt(rgbm[3], 10).toString(16).toUpperCase()).slice(-2);_x000D_
    } else {_x000D_
      return "cant parse that";_x000D_
    }_x000D_
  }_x000D_
}_x000D_
_x000D_
$('button').click(function() {_x000D_
  var hex = rgb2hex($('#in_tb').val());_x000D_
  $('#in_tb_result').html(hex);_x000D_
});
_x000D_
body {_x000D_
  padding: 20px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
Convert RGB/RGBA to hex #RRGGBB/#AARRGGBB:<br>_x000D_
<br>_x000D_
<input id="in_tb" type="text" value="rgba(200, 90, 34, 0.75)"> <button>Convert</button><br>_x000D_
<br> Result: <span id="in_tb_result"></span>
_x000D_
_x000D_
_x000D_

$(...).datepicker is not a function - JQuery - Bootstrap

To get rid of the bad looking datepicker you need to add jquery-ui css

<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css">

How can I make the Android emulator show the soft keyboard?

If you're using AVD manager add a hardware property Keyboard support and set it to false.

That should disable the shown keyboard, and show the virtual one.

Casting int to bool in C/C++

There some kind of old school 'Marxismic' way to the cast int -> bool without C4800 warnings of Microsoft's cl compiler - is to use negation of negation.

int  i  = 0;
bool bi = !!i;

int  j  = 1;
bool bj = !!j;

Why ModelState.IsValid always return false in mvc

"ModelState.IsValid" tells you that the model is consumed by the view (i.e. PaymentAdviceEntity) is satisfy all types of validation or not specified in the model properties by DataAnotation.

In this code the view does not bind any model properties. So if you put any DataAnotations or validation in model (i.e. PaymentAdviceEntity). then the validations are not satisfy. say if any properties in model is Name which makes required in model.Then the value of the property remains blank after post.So the model is not valid (i.e. ModelState.IsValid returns false). You need to remove the model level validations.

What is the maximum length of a URL in different browsers?

I have experience with SharePoint 2007, 2010 and there is a limit of the length URL you can create from the server side in this case SharePoint, so it depends mostly on, 1) the client (browser, version, and OS) and 2) the server technology, IIS, Apache, etc.

Get final URL after curl is redirected

curl's -w option and the sub variable url_effective is what you are looking for.

Something like

curl -Ls -o /dev/null -w %{url_effective} http://google.com

More info

-L         Follow redirects
-s         Silent mode. Don't output anything
-o FILE    Write output to <file> instead of stdout
-w FORMAT  What to output after completion

More

You might want to add -I (that is an uppercase i) as well, which will make the command not download any "body", but it then also uses the HEAD method, which is not what the question included and risk changing what the server does. Sometimes servers don't respond well to HEAD even when they respond fine to GET.

How to quit android application programmatically

Try this

int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);

For loop for HTMLCollection elements

Alternative to Array.from is to use Array.prototype.forEach.call

forEach: Array.prototype.forEach.call(htmlCollection, i => { console.log(i) });

map: Array.prototype.map.call(htmlCollection, i => { console.log(i) });

ect...

Prompt for user input in PowerShell

As an alternative, you could add it as a script parameter for input as part of script execution

 param(
      [Parameter(Mandatory = $True,valueFromPipeline=$true)][String] $value1,
      [Parameter(Mandatory = $True,valueFromPipeline=$true)][String] $value2
      )

css 100% width div not taking up full width of parent

Remove the width:100%; declarations.

Block elements should take up the whole available width by default.

Image resizing in React Native

In my case I could not set 'width' and 'height' to null because I'm using TypeScript.

The way I fixed it was by setting them to '100%':

backgroundImage: {
    flex: 1,
    width: '100%',
    height: '100%',
    resizeMode: 'cover',        
}

How to calculate rolling / moving average using NumPy / SciPy?

moving average

iterator method

  • reverse the array at i, and simply take the mean from i to n.

  • use list comprehension to generate mini arrays on the fly.

x = np.random.randint(10, size=20)

def moving_average(arr, n):
    return [ (arr[:i+1][::-1][:n]).mean() for i, ele in enumerate(arr) ]
d = 5

moving_average(x, d)

tensor convolution

moving_average = np.convolve(x, np.ones(d)/d, mode='valid')

WARNING: Exception encountered during context initialization - cancelling refresh attempt

This was my stupidity, but a stupidity that was not easy to identify :).

Problem:

  1. My code is compiled on Jdk 1.8.
  2. My eclipse, had JDK 1.8 as the compiler.
  3. My tomcat in eclipse was using Java 1.7 for its container, hence it was not able to understand the .class files which were compiled using 1.8.
  4. To avoid the problem, ensure in your eclipse, double click on your server -> Open Launch configuration -> Classpath -> JRE System Library -> Give the JDK/JRE of the compiled version of java class, in my case, it had to be JDK 1.8
    1. Post this, clean the server, build and redeploy, start the tomcat.

If you are deploying manually into your server, ensure your JAVA_HOME, JDK_HOME points to the correct JDK which you used to compile the project and build the war.

If you do not like to change JAVA_HOME, JDK_HOME, you can always change the JAVA_HOME and JDK_HOME in catalina.bat(for tomcat server) and that'll enable your life to be easy!

How to convert ActiveRecord results into an array of hashes

For current ActiveRecord (4.2.4+) there is a method to_hash on the Result object that returns an array of hashes. You can then map over it and convert to symbolized hashes:

# Get an array of hashes representing the result (column => value):
result.to_hash
# => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
      {"id" => 2, "title" => "title_2", "body" => "body_2"},
      ...
     ]

result.to_hash.map(&:symbolize_keys)
# => [{:id => 1, :title => "title_1", :body => "body_1"},
      {:id => 2, :title => "title_2", :body => "body_2"},
      ...
     ]

See the ActiveRecord::Result docs for more info.

Convert array of integers to comma-separated string

Use LINQ Aggregate method to convert array of integers to a comma separated string

var intArray = new []{1,2,3,4};
string concatedString = intArray.Aggregate((a, b) =>Convert.ToString(a) + "," +Convert.ToString( b));
Response.Write(concatedString);

output will be

1,2,3,4

This is one of the solution you can use if you have not .net 4 installed.

Splitting a continuous variable into equal sized groups

Alternative without using cut2.

das$wt2 <- as.factor( as.numeric( cut(das$wt,3)))

or

das$wt2 <- as.factor( cut(das$wt,3, labels=F))

As pointed out by @ben-bolker this splits into equal-widths rather occupancy. I think that using quantiles one can approximate equal-occupancy

x = rnorm(10)
x
 [1] -0.1074316  0.6690681 -1.7168853  0.5144931  1.6460280  0.7014368
 [7]  1.1170587 -0.8503069  0.4462932 -0.1089427
bin = 3 #for 1/3 rd, 4 for 1/4, 100 for 1/100th etc
xx = cut(x, quantile(x, breaks=1/bin*c(1:bin)), labels=F, include.lowest=T)
table(xx)
1 2 3 4
3 2 2 3

Forwarding port 80 to 8080 using NGINX

NGINX supports WebSockets by allowing a tunnel to be setup between a client and a backend server. In order for NGINX to send the Upgrade request from the client to the backend server, Upgrade and Connection headers must be set explicitly. For example:

# WebSocket proxying
map $http_upgrade $connection_upgrade {
    default         upgrade;
    ''              close;
}


server {
    listen 80;

    # The host name to respond to
    server_name cdn.domain.com;

    location / {
        # Backend nodejs server
        proxy_pass          http://127.0.0.1:8080;
        proxy_http_version  1.1;
        proxy_set_header    Upgrade     $http_upgrade;
        proxy_set_header    Connection  $connection_upgrade;
    }
}

Source: http://nginx.com/blog/websocket-nginx/

Python error: TypeError: 'module' object is not callable for HeadFirst Python code

You module and class AthleteList have the same name. Change:

import AthleteList

to:

from AthleteList import AthleteList

This now means that you are importing the module object and will not be able to access any module methods you have in AthleteList

react-native - Fit Image in containing View, not the whole screen size

Set the dimensions to the View and make sure your Image is styled with height and width set to 'undefined' like the example below :

    <View style={{width: 10, height:10 }} >
      <Image style= {{flex:1 , width: undefined, height: undefined}}    
       source={require('../yourfolder/yourimage')}
        />
    </View>

This will make sure your image scales and fits perfectly into your view.

Show a number to two decimal places

Try:

$number = 1234545454; 
echo  $english_format_number = number_format($number, 2); 

The output will be:

1,234,545,454.00

Evenly distributing n points on a sphere

The Fibonacci sphere algorithm is great for this. It is fast and gives results that at a glance will easily fool the human eye. You can see an example done with processing which will show the result over time as points are added. Here's another great interactive example made by @gman. And here's a simple implementation in python.

import math


def fibonacci_sphere(samples=1):

    points = []
    phi = math.pi * (3. - math.sqrt(5.))  # golden angle in radians

    for i in range(samples):
        y = 1 - (i / float(samples - 1)) * 2  # y goes from 1 to -1
        radius = math.sqrt(1 - y * y)  # radius at y

        theta = phi * i  # golden angle increment

        x = math.cos(theta) * radius
        z = math.sin(theta) * radius

        points.append((x, y, z))

    return points

1000 samples gives you this:

enter image description here

Android: checkbox listener

You can do this:

satView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

       @Override
       public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {

       }
   }
);     

How to duplicate a whole line in Vim?

Normal mode: see other answers.

The Ex way:

  • :t. will duplicate the line,
  • :t 7 will copy it after line 7,
  • :,+t0 will copy current and next line at the beginning of the file (,+ is a synonym for the range .,.+1),
  • :1,t$ will copy lines from beginning till cursor position to the end (1, is a synonym for the range 1,.).

If you need to move instead of copying, use :m instead of :t.

This can be really powerful if you combine it with :g or :v:

  • :v/foo/m$ will move all lines not matching the pattern “foo” to the end of the file.
  • :+,$g/^\s*class\s\+\i\+/t. will copy all subsequent lines of the form class xxx right after the cursor.

Reference: :help range, :help :t, :help :g, :help :m and :help :v

z-index not working with fixed positioning

I was building a nav menu. I have overflow: hidden in my nav's css which hid everything. I thought it was a z-index problem, but really I was hiding everything outside my nav.

How to enable CORS in apache tomcat

Just to add a bit of extra info over the right solution. Be aware that you'll need this class org.apache.catalina.filters.CorsFilter. So in order to have it, if your tomcat is not 7.0.41 or higher, download 'tomcat-catalina.7.0.41.jar' or higher ( you can do it from http://mvnrepository.com/artifact/org.apache.tomcat/tomcat-catalina ) and put it in the 'lib' folder inside Tomcat installation folders. I actually used 7.0.42 Hope it helps!

Selected tab's color in Bottom Navigation View

Try using android:state_enabled rather than android:state_selected for the selector item attributes.

How to use the 'main' parameter in package.json?

For OpenShift, you only get one PORT and IP pair to bind to (per application). It sounds like you should be able to serve both services from a single nodejs instance by adding internal routes for each service endpoint.

I have some info on how OpenShift uses your project's package.json to start your application here: https://www.openshift.com/blogs/run-your-nodejs-projects-on-openshift-in-two-simple-steps#package_json

How to hide/show div tags using JavaScript?

just use a jquery event listner , click event. let the class of the link is lb... i am considering body as a div as you said...

$('.lb').click(function() {
    $('#body1').show();
    $('#body').hide();
 });

Drop rows containing empty cells from a pandas DataFrame

There's a situation where the cell has white space, you can't see it, use

df['col'].replace('  ', np.nan, inplace=True)

to replace white space as NaN, then

df= df.dropna(subset=['col'])

How to check the extension of a filename in a bash script?

You could also do:

   if [ "${FILE##*.}" = "txt" ]; then
       # operation for txt files here
   fi

Clear data in MySQL table with PHP?

TRUNCATE will blank your table and reset primary key DELETE will also make your table blank but it will not reset primary key.

we can use for truncate

TRUNCATE TABLE tablename

we can use for delete

DELETE FROM tablename

we can also give conditions as below

DELETE FROM tablename WHERE id='xyz'

Making the iPhone vibrate

You can use

1) AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);

for iPhone and few newer iPods.

2) AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

for iPads.

lambda expression for exists within list

var query = list.Where(r => listofIds.Any(id => id == r.Id));

Another approach, useful if the listOfIds array is large:

HashSet<int> hash = new HashSet<int>(listofIds);
var query = list.Where(r => hash.Contains(r.Id));

How to convert a data frame column to numeric type?

If you run into problems with:

as.numeric(as.character(dat$x))

Take a look to your decimal marks. If they are "," instead of "." (e.g. "5,3") the above won't work.

A potential solution is:

as.numeric(gsub(",", ".", dat$x))

I believe this is quite common in some non English speaking countries.

Cannot get a text value from a numeric cell “Poi”

    Cell cell = sheet.getRow(i).getCell(0);
    cell.setCellType ( Cell.CELL_TYPE_STRING );
    String j_username = cell.getStringCellValue();

UPDATE

Ok, as have been said in comments, despite this works it isn't correct method of retrieving data from an Excel's cell.

According to the manual here:

If what you want to do is get a String value for your numeric cell, stop!. This is not the way to do it. Instead, for fetching the string value of a numeric or boolean or date cell, use DataFormatter instead.

And according to the DataFormatter API

DataFormatter contains methods for formatting the value stored in an Cell. This can be useful for reports and GUI presentations when you need to display data exactly as it appears in Excel. Supported formats include currency, SSN, percentages, decimals, dates, phone numbers, zip codes, etc.

So, right way to show numeric cell's value is as following:

 DataFormatter formatter = new DataFormatter(); //creating formatter using the default locale
 Cell cell = sheet.getRow(i).getCell(0);
 String j_username = formatter.formatCellValue(cell); //Returns the formatted value of a cell as a String regardless of the cell type.

Ruby: What is the easiest way to remove the first element from an array?

"pop"ing the first element of an Array is called "shift" ("unshift" being the operation of adding one element in front of the array).

How to set standard encoding in Visual Studio

What

It is possible with EditorConfig.

EditorConfig helps developers define and maintain consistent coding styles between different editors and IDEs.

This also includes file encoding.

EditorConfig is built-in Visual Studio 2017 by default, and I there were plugins available for versions as old as VS2012. Read more from EditorConfig Visual Studio Plugin page.

How

You can set up a EditorConfig configuration file high enough in your folder structure to span all your intended repos (up to your drive root should your files be really scattered everywhere) and configure the setting charset:

charset: set to latin1, utf-8, utf-8-bom, utf-16be or utf-16le to control the character set.

You can add filters and exceptions etc on every folder level or by file name/type should you wish for finer control.

Once configured then compatible IDEs should automatically do it's thing to make matching files comform to set rules. Note that Visual Studio does not automatically convert all your files but do its bit when you work with files in IDE (open and save).

What next

While you could have a Visual-studio-wide setup, I strongly suggest to still include an EditorConfig root to your solution version control, so that explicit settings are automatically synced to all team members as well. Your drive root editorconfig file can be the fallback should some project not have their own editorconfig files set up yet.

UITableView with fixed section headers

to make UITableView sections header not sticky or sticky:

  1. change the table view's style - make it grouped for not sticky & make it plain for sticky section headers - do not forget: you can do it from storyboard without writing code. (click on your table view and change it is style from the right Side/ component menu)

  2. if you have extra components such as custom views or etc. please check the table view's margins to create appropriate design. (such as height of header for sections & height of cell at index path, sections)

Hide text within HTML?

Use the CSS property visibility and set it to hidden.

You can see more here.

DLL load failed error when importing cv2

In my case a major update of Windows 10 removed some Windows packages, so other methods (reinstalling opencv etc.) did not help. To fix it, install:

a) Microsoft Visual C++ Redistributable for Visual Studio 2015, 2017 and 2019

b) Media Feature Pack for N versions - needed only if you have Windows 10 N

Both need restart of PC.

specifying goal in pom.xml

I've bumped into this question because I actually wanted to define a default goal in pom.xml. You can define a default goal under build:

<build>
    <defaultGoal>install</defaultGoal>
...
</build>

After that change, you can then simply run mvn which will do exactly the same as mvn install.

Note: I don't favor this as a default approach. My use case was to define a profile that downloaded a previous version of that project from Artifactory and wanted to tie that profile to a given phase. For convenience, I can run mvn -Pdownload-jar -Dversion=0.0.9 and don't need to specify a goal/phase there. I think it's reasonable to define a defaultGoal in a profile which has a very specific function for a particular phase.

How to apply color in Markdown?

Run the following in zeppelin paragraph

%md ### <span style="color:red">text</span>

Select All checkboxes using jQuery

 jQuery( function($){
    // add multiple select / deselect functionality
    $("#contact_select_all").click(function () {

        if($("#contact_select_all").is(":checked")){
            $('.noborder').prop('checked',true);
        }else
            $('.noborder').prop('checked',false);
    });

    // if all checkbox are selected, check the selectall checkbox
    $(".noborder").click(function(){

    if($(".noborder").length == $(".noborder:checked").length) {
        $("#contact_select_all").attr("checked", "checked");
    } else {
        $("#contact_select_all").removeAttr("checked");
    }

    });

});

C# declare empty string array

Your syntax is wrong:

string[] arr = new string[]{};

or

string[] arr = new string[0];

ValueError: cannot reshape array of size 30470400 into shape (50,1104,104)

It seems that there is a typo, since 1104*1104*50=60940800 and you are trying to reshape to dimensions 50,1104,104. So it seems that you need to change 104 to 1104.

Cannot open backup device. Operating System error 5

I solved the same problem with the following 3 steps:

  1. I store my backup file in other folder path that's worked right.
  2. View different of security tab two folders (as below image).
  3. Edit permission in security tab folder that's not worked right.

enter image description here

Update a table using JOIN in SQL Server?

Try:

UPDATE table1
SET CalculatedColumn = ( SELECT [Calculated Column] 
                         FROM table2 
                         WHERE table1.commonfield = [common field])
WHERE  BatchNO = '110'

How to detect tableView cell touched or clicked in swift

If you want the value from cell then you don't have to recreate cell in the didSelectRowAtIndexPath

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    println(tasks[indexPath.row])
}

Task would be as follows :

let tasks=["Short walk",
    "Audiometry",
    "Finger tapping",
    "Reaction time",
    "Spatial span memory"
]

also you have to check the cellForRowAtIndexPath you have to set identifier.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as UITableViewCell
    var (testName) = tasks[indexPath.row]
    cell.textLabel?.text=testName
    return cell
}

Hope it helps.

ASP.NET MVC controller actions that return JSON or partial html

Flexible approach to produce different outputs based on the request

public class AuctionsController : Controller
{
  public ActionResult Auction(long id)
  {
    var db = new DataContext();
    var auction = db.Auctions.Find(id);

    // Respond to AJAX requests
    if (Request.IsAjaxRequest())
      return PartialView("Auction", auction);

    // Respond to JSON requests
    if (Request.IsJsonRequest())
      return Json(auction);

    // Default to a "normal" view with layout
    return View("Auction", auction);
  }
}

The Request.IsAjaxRequest() method is quite simple: it merely checks the HTTP headers for the incoming request to see if the value of the X-Requested-With header is XMLHttpRequest, which is automatically appended by most browsers and AJAX frameworks.

Custom extension method to check whether the request is for json or not so that we can call it from anywhere, just like the Request.IsAjaxRequest() extension method:

using System;
using System.Web;

public static class JsonRequestExtensions
{
  public static bool IsJsonRequest(this HttpRequestBase request)
  {
    return string.Equals(request["format"], "json");
  }
}

Source : https://www.safaribooksonline.com/library/view/programming-aspnet-mvc/9781449321932/ch06.html#_javascript_rendering

Init function in javascript and how it works

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

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

function foo() {/*code*/}

and

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

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

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

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

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

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

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

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

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

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

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

In other words, the following three statements are valid:

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

[EDIT in 2020]

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

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

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

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

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

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

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

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

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

Copy data into another table

CREATE TABLE `table2` LIKE `table1`;
INSERT INTO `table2` SELECT * FROM `table1`;

the first query will create the structure from table1 to table2 and second query will put the data from table1 to table2

iPad Web App: Detect Virtual Keyboard Using JavaScript in Safari?

I did some searching, and I couldn't find anything concrete for a "on keyboard shown" or "on keyboard dismissed". See the official list of supported events. Also see Technical Note TN2262 for iPad. As you probably already know, there is a body event onorientationchange you can wire up to detect landscape/portrait.

Similarly, but a wild guess... have you tried detecting resize? Viewport changes may trigger that event indirectly from the keyboard being shown / hidden.

window.addEventListener('resize', function() { alert(window.innerHeight); });

Which would simply alert the new height on any resize event....

Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

YES, PUT, DELETE, HEAD etc HTTP methods are available in all modern browsers.

To be compliant with XMLHttpRequest Level 2 browsers must support these methods. To check which browsers support XMLHttpRequest Level 2 I recommend CanIUse:

http://caniuse.com/#feat=xhr2

Only Opera Mini is lacking support atm (juli '15), but Opera Mini lacks support for everything. :)

php function mail() isn't working

I think you are not configured properly,

if you are using XAMPP then you can easily send mail from localhost.

for example you can configure C:\xampp\php\php.ini and c:\xampp\sendmail\sendmail.ini for gmail to send mail.

in C:\xampp\php\php.ini find extension=php_openssl.dll and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.

in php.ini file find [mail function] and change

SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"

(use the above send mail path only and it will work)

Now Open C:\xampp\sendmail\sendmail.ini. Replace all the existing code in sendmail.ini with following code

[sendmail]

smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]

Now you have done!! create php file with mail function and send mail from localhost.

Update

First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()).

You can set the following settings in your PHP.ini:

ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");

Add element to a list In Scala

I will try to explain the results of all the commands you tried.

scala> val l = 1.0 :: 5.5 :: Nil
l: List[Double] = List(1.0, 5.5)

First of all, List is a type alias to scala.collection.immutable.List (defined in Predef.scala).

Using the List companion object is more straightforward way to instantiate a List. Ex: List(1.0,5.5)

scala> l
res0: List[Double] = List(1.0, 5.5)

scala> l ::: List(2.2, 3.7)
res1: List[Double] = List(1.0, 5.5, 2.2, 3.7)

::: returns a list resulting from the concatenation of the given list prefix and this list

The original List is NOT modified

scala> List(l) :+ 2.2
res2: List[Any] = List(List(1.0, 5.5), 2.2)

List(l) is a List[List[Double]] Definitely not what you want.

:+ returns a new list consisting of all elements of this list followed by elem.

The type is List[Any] because it is the common superclass between List[Double] and Double

scala> l
res3: List[Double] = List(1.0, 5.5)

l is left unmodified because no method on immutable.List modified the List.

jQuery: get parent, parent id?

$(this).parent().parent().attr('id');

Is how you would get the id of the parent's parent.

EDIT:

$(this).closest('ul').attr('id');

Is a more foolproof solution for your case.

Jinja2 template variable if None Object set a default value

To avoid throw a exception while "p" or "p.User" is None, you can use:

{{ (p and p.User and p.User['first_name']) or "default_value" }}

Converting NSString to NSDate (and back again)

NSString to NSDate or NSDate to NSString

//This method is used to get NSDate from string 
//Pass the date formate ex-"dd-MM-yyyy hh:mm a"
+ (NSDate*)getDateFromString:(NSString *)dateString withFormate:(NSString *)formate  {

    // Converted date from date string
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [dateFormatter setDateFormat:formate];
    NSDate *convertedDate         = [dateFormatter dateFromString:dateString];
    return convertedDate;
}

//This method is used to get the NSString for NSDate
//Pass the date formate ex-"dd-MM-yyyy hh:mm a"
+ (NSString *)getDateStringFromDate:(NSDate *)date withFormate:(NSString *)formate {

    // Converted date from date string
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [dateFormatter setDateFormat:formate];
    NSString *convertedDate         = [dateFormatter stringFromDate:date];
    return convertedDate;
}

execJs: 'Could not find a JavaScript runtime' but execjs AND therubyracer are in Gemfile

I had this occur to me on my Windows machine, turns out the problem was quite different. I had accidentally removed some paths from my %PATH% variable. Simply restarting the command prompt solved it. It seems as though there was a JS runtime in one of those missing paths.

how to install gcc on windows 7 machine?

Download mingw-get and simply issue:

mingw-get install gcc.

See the Getting Started page.

pip install - locale.Error: unsupported locale setting

The root cause is: your environment variable LC_ALL is missing or invalid somehow

Short answer-

just run the following command:

$ export LC_ALL=C

If you keep getting the error in new terminal windows, add it at the bottom of your .bashrc file.

Long answer-

Here is my locale settings:

$ locale
LANG=en_US.UTF-8
LANGUAGE=
LC_CTYPE="C"
LC_NUMERIC="C"
LC_TIME="C"
LC_COLLATE="C"
LC_MONETARY="C"
LC_MESSAGES="C"
LC_PAPER="C"
LC_NAME="C"
LC_ADDRESS="C"
LC_TELEPHONE="C"
LC_MEASUREMENT="C"
LC_IDENTIFICATION="C"
LC_ALL=C

Python2.7

    $ uname -a
    Linux debian 3.16.0-4-amd64 #1 SMP Debian 3.16.7-ckt11-1+deb8u6 (2015-11-09) x86_64 GNU/Linux
    $ python --version
    Python 2.7.9
    $ pip --version
    pip 8.1.1 from /usr/local/lib/python2.7/dist-packages (python 2.7)
    $ unset LC_ALL
    $ pip install virtualenv
    Traceback (most recent call last):
      File "/usr/local/bin/pip", line 11, in <module>
        sys.exit(main())
      File "/usr/local/lib/python2.7/dist-packages/pip/__init__.py", line 215, in main
        locale.setlocale(locale.LC_ALL, '')
      File "/usr/lib/python2.7/locale.py", line 579, in setlocale
        return _setlocale(category, locale)
    locale.Error: unsupported locale setting
    $ export LC_ALL=C
    $ pip install virtualenv
    Requirement already satisfied (use --upgrade to upgrade): virtualenv in /usr/local/lib/python2.7/dist-packages

how to put image in center of html page?

If:

X is image width,
Y is image height,

then:

img {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -(X/2)px;
    margin-top: -(Y/2)px;
}

But keep in mind this solution is valid only if the only element on your site will be this image. I suppose that's the case here.

Using this method gives you the benefit of fluidity. It won't matter how big (or small) someone's screen is. The image will always stay in the middle.

Android Design Support Library expandable Floating Action Button(FAB) menu

When I tried to create something simillar to inbox floating action button i thought about creating own custom component.

It would be simple frame layout with fixed height (to contain expanded menu) containing FAB button and 3 more placed under the FAB. when you click on FAB you just simply animate other buttons to translate up from under the FAB.

There are some libraries which do that (for example https://github.com/futuresimple/android-floating-action-button), but it's always more fun if you create it by yourself :)

Difference between dangling pointer and memory leak

A dangling pointer is one that has a value (not NULL) which refers to some memory which is not valid for the type of object you expect. For example if you set a pointer to an object then overwrote that memory with something else unrelated or freed the memory if it was dynamically allocated.

A memory leak is when you dynamically allocate memory from the heap but never free it, possibly because you lost all references to it.

They are related in that they are both situations relating to mismanaged pointers, especially regarding dynamically allocated memory. In one situation (dangling pointer) you have likely freed the memory but tried to reference it afterwards; in the other (memory leak), you have forgotten to free the memory entirely!

Read from a gzip file in python

Try gzipping some data through the gzip libary like this...

import gzip
content = "Lots of content here"
f = gzip.open('Onlyfinnaly.log.gz', 'wb')
f.write(content)
f.close()

... then run your code as posted ...

import gzip
f=gzip.open('Onlyfinnaly.log.gz','rb')
file_content=f.read()
print file_content

This method worked for me as for some reason the gzip library fails to read some files.

Excel Formula which places date/time in cell when data is entered in another cell in the same row

Another way to do this is described below.

First, turn on iterative calculations on under File - Options - Formulas - Enable Iterative Calculation. Then set maximum iterations to 1000.

After doing this, use the following formula.

=If(D55="","",IF(C55="",NOW(),C55))

Once anything is typed into cell D55 (for this example) then C55 populates today's date and/or time depending on the cell format. This date/time will not change again even if new data is entered into cell C55 so it shows the date/time that the data was entered originally.

This is a circular reference formula so you will get a warning about it every time you open the workbook. Regardless, the formula works and is easy to use anywhere you would like in the worksheet.

Read/Write 'Extended' file properties (C#)

I'm not sure what types of files you are trying to write the properties for but taglib-sharp is an excellent open source tagging library that wraps up all this functionality nicely. It has a lot of built in support for most of the popular media file types but also allows you to do more advanced tagging with pretty much any file.

EDIT: I've updated the link to taglib sharp. The old link no longer worked.

EDIT: Updated the link once again per kzu's comment.

Differences between time complexity and space complexity?

The time and space complexities are not related to each other. They are used to describe how much space/time your algorithm takes based on the input.

  • For example when the algorithm has space complexity of:

    • O(1) - constant - the algorithm uses a fixed (small) amount of space which doesn't depend on the input. For every size of the input the algorithm will take the same (constant) amount of space. This is the case in your example as the input is not taken into account and what matters is the time/space of the print command.
    • O(n), O(n^2), O(log(n))... - these indicate that you create additional objects based on the length of your input. For example creating a copy of each object of v storing it in an array and printing it after that takes O(n) space as you create n additional objects.
  • In contrast the time complexity describes how much time your algorithm consumes based on the length of the input. Again:

    • O(1) - no matter how big is the input it always takes a constant time - for example only one instruction. Like

      function(list l) {
          print("i got a list");
      }
      
    • O(n), O(n^2), O(log(n)) - again it's based on the length of the input. For example

      function(list l) {
           for (node in l) {
              print(node);
          }
      }
      

Note that both last examples take O(1) space as you don't create anything. Compare them to

function(list l) {
    list c;
    for (node in l) {
        c.add(node);
    }
}

which takes O(n) space because you create a new list whose size depends on the size of the input in linear way.

Your example shows that time and space complexity might be different. It takes v.length * print.time to print all the elements. But the space is always the same - O(1) because you don't create additional objects. So, yes, it is possible that an algorithm has different time and space complexity, as they are not dependent on each other.

Where can I find the .apk file on my device, when I download any app and install?

You can do that I believe. It needs root permission. If you want to know where your apk files are stored, open a emulator and then go to

DDMS>File Explorer-> you can see a directory by name "data" -> Click on it and you will see a "app" folder.

Your apks are stored there. In fact just copying a apk directly to the folder works for me with emulators.

Graph implementation C++

I prefer using an adjacency list of Indices ( not pointers )

typedef std::vector< Vertex > Vertices;
typedef std::set <int> Neighbours;


struct Vertex {
private:
   int data;
public:
   Neighbours neighbours;

   Vertex( int d ): data(d) {}
   Vertex( ): data(-1) {}

   bool operator<( const Vertex& ref ) const {
      return ( ref.data < data );
   }
   bool operator==( const Vertex& ref ) const {
      return ( ref.data == data );
   }
};

class Graph
{
private :
   Vertices vertices;
}

void Graph::addEdgeIndices ( int index1, int index2 ) {
  vertices[ index1 ].neighbours.insert( index2 );
}


Vertices::iterator Graph::findVertexIndex( int val, bool& res )
{
   std::vector<Vertex>::iterator it;
   Vertex v(val);
   it = std::find( vertices.begin(), vertices.end(), v );
   if (it != vertices.end()){
        res = true;
       return it;
   } else {
       res = false;
       return vertices.end();
   }
}

void Graph::addEdge ( int n1, int n2 ) {

   bool foundNet1 = false, foundNet2 = false;
   Vertices::iterator vit1 = findVertexIndex( n1, foundNet1 );
   int node1Index = -1, node2Index = -1;
   if ( !foundNet1 ) {
      Vertex v1( n1 );
      vertices.push_back( v1 );
      node1Index = vertices.size() - 1;
   } else {
      node1Index = vit1 - vertices.begin();
   }
   Vertices::iterator vit2 = findVertexIndex( n2, foundNet2);
   if ( !foundNet2 ) {
      Vertex v2( n2 );
      vertices.push_back( v2 );
      node2Index = vertices.size() - 1;
   } else {
      node2Index = vit2 - vertices.begin();
   }

   assert( ( node1Index > -1 ) && ( node1Index <  vertices.size()));
   assert( ( node2Index > -1 ) && ( node2Index <  vertices.size()));

   addEdgeIndices( node1Index, node2Index );
}

Difference between break and continue in PHP?

break ends a loop completely, continue just shortcuts the current iteration and moves on to the next iteration.

while ($foo) {   <--------------------+
    continue;    --- goes back here --+
    break;       ----- jumps here ----+
}                                     |
                 <--------------------+

This would be used like so:

while ($droid = searchDroids()) {
    if ($droid != $theDroidYoureLookingFor) {
        continue; // ..the search with the next droid
    }

    $foundDroidYoureLookingFor = true;
    break; // ..off the search
}

PHP Session Destroy on Log Out Button

// logout

if(isset($_GET['logout'])) {
    session_destroy();
    unset($_SESSION['username']);
    header('location:login.php');
}

?>

How can I disable a tab inside a TabControl?

I could not find an appropriate answer to the question. There looks to be no solution to disable the specific tab. What I did is to pass the specific tab to a variable and in SelectedIndexChanged event put it back to SelectedIndex:

//variable for your specific tab 
int _TAB = 0;

//here you specify your tab that you want to expose
_TAB = 1;
tabHolder.SelectedIndex = _TAB;

private void tabHolder_SelectedIndexChanged(object sender, EventArgs e)
{
    if (_TAB != 0) tabHolder.SelectedIndex = _TAB;
}

So, you don't actually disable the tab, but when another tab is clicked it always returns you to the selected tab.

Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP

You can try out this one as well as. Because this worked for me and it's simple.

<style>
    <%@ include file="/css/style.css" %>
</style>

How to sort by column in descending order in Spark SQL?

In the case of Java:

If we use DataFrames, while applying joins (here Inner join), we can sort (in ASC) after selecting distinct elements in each DF as:

Dataset<Row> d1 = e_data.distinct().join(s_data.distinct(), "e_id").orderBy("salary");

where e_id is the column on which join is applied while sorted by salary in ASC.

Also, we can use Spark SQL as:

SQLContext sqlCtx = spark.sqlContext();
sqlCtx.sql("select * from global_temp.salary order by salary desc").show();

where

  • spark  -> SparkSession
  • salary -> GlobalTemp View.

How to import JSON File into a TypeScript file?

As stated in this reddit post, after Angular 7, you can simplify things to these 2 steps:

  1. Add those three lines to compilerOptions in your tsconfig.json file:
"resolveJsonModule": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
  1. Import your json data:
import myData from '../assets/data/my-data.json';

And that's it. You can now use myDatain your components/services.

Activating Anaconda Environment in VsCode

As I was not able to solve my problem by suggested ways, I will share how I fixed it.

First of all, even if I was able to activate an environment, the corresponding environment folder was not present in C:\ProgramData\Anaconda3\envs directory.

So I created a new anaconda environment using Anaconda prompt, a new folder named same as your given environment name will be created in the envs folder.

Next, I activated that environment in Anaconda prompt. Installed python with conda install python command.

Then on anaconda navigator, selected the newly created environment in the 'Applications on' menu. Launched vscode through Anaconda navigator.

Now as suggested by other answers, in vscode, opened command palette with Ctrl + Shift + P keyboard shortcut. Searched and selected Python: Select Interpreter

If the interpreter with newly created environment isn't listed out there, select Enter Interpreter Path and choose the newly created python.exe which is located similar to C:\ProgramData\Anaconda3\envs\<your-new-env>\ . So the total path will look like C:\ProgramData\Anaconda3\envs\<your-nev-env>\python.exe

Next time onwards the interpreter will be automatically listed among other interpreters.

Now you might see your selected conda environment at bottom left side in vscode.

htaccess remove index.php from url

To remove index.php from the URL, and to redirect the visitor to the non-index.php version of the page:

RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]

This will cleanly redirect /index.php/myblog to simply /myblog.

Using a 301 redirect will preserve Google search engine rankings.

scrollIntoView Scrolls just too far

I've got this and it works brilliantly for me:

// add a smooth scroll to element
scroll(el) {
el.scrollIntoView({
  behavior: 'smooth',
  block: 'start'});

setTimeout(() => {
window.scrollBy(0, -40);
}, 500);}

Hope it helps.

When to use std::size_t?

When using size_t be careful with the following expression

size_t i = containner.find("mytoken");
size_t x = 99;
if (i-x>-1 && i+x < containner.size()) {
    cout << containner[i-x] << " " << containner[i+x] << endl;
}

You will get false in the if expression regardless of what value you have for x. It took me several days to realize this (the code is so simple that I did not do unit test), although it only take a few minutes to figure the source of the problem. Not sure it is better to do a cast or use zero.

if ((int)(i-x) > -1 or (i-x) >= 0)

Both ways should work. Here is my test run

size_t i = 5;
cerr << "i-7=" << i-7 << " (int)(i-7)=" << (int)(i-7) << endl;

The output: i-7=18446744073709551614 (int)(i-7)=-2

I would like other's comments.

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

A slight variation on the above simplified approach.

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

Re-sign IPA (iPhone)

Thank you, Erik, for posting this. This worked for me. I'd like to add a note about an extra step I needed. Within "Payload/Application.app/" there was a directory named "CACertChains" that contained a file named "cacert.pem". I had to remove the directory and the .pem to complete these steps. Thanks again! –

Python unittest - opposite of assertRaises?

Hi - I want to write a test to establish that an Exception is not raised in a given circumstance.

That's the default assumption -- exceptions are not raised.

If you say nothing else, that's assumed in every single test.

You don't have to actually write an any assertion for that.

How to play YouTube video in my Android application?

Steps

  1. Create a new Activity, for your player(fullscreen) screen with menu options. Run the mediaplayer and UI in different threads.

  2. For playing media - In general to play audio/video there is mediaplayer api in android. FILE_PATH is the path of file - may be url(youtube) stream or local file path

     MediaPlayer mp = new MediaPlayer();
        mp.setDataSource(FILE_PATH);
        mp.prepare();
        mp.start();
    

Also check: Android YouTube app Play Video Intent have already discussed this in detail.

Is there a vr (vertical rule) in html?

No, there is no vertical rule.

It does not make logical sense to have one. HTML is parsed sequentially, meaning you lay out your HTML code from top to bottom, left to right how you want it to appear from top to bottom, left to right (generally)

A vr tag does not follow that paradigm.

This is easy to do using CSS, however. Ex:

<div style="border-left:1px solid #000;height:500px"></div>

Note that you need to specify a height or fill the container with content.

How can I check that JButton is pressed? If the isEnable() is not work?

JButton#isEnabled changes the user interactivity of a component, that is, whether a user is able to interact with it (press it) or not.

When a JButton is pressed, it fires a actionPerformed event.

You are receiving Add button is pressed when you press the confirm button because the add button is enabled. As stated, it has nothing to do with the pressed start of the button.

Based on you code, if you tried to check the "pressed" start of the add button within the confirm button's ActionListener it would always be false, as the button will only be in the pressed state while the add button's ActionListeners are being called.

Based on all this information, I would suggest you might want to consider using a JCheckBox which you can then use JCheckBox#isSelected to determine if it has being checked or not.

Take a closer look at How to Use Buttons for more details

VS Code - Search for text in all files in a directory

  1. Enter Search Keyword in search (CTRL + SHIFT + F)

  2. Exclude unwanted folder's/files by using exclude option (!)

    ex: !Folder/File*

  3. Hit Enter

Search results gives you desired result

Base64 PNG data to HTML5 canvas

Jerryf's answer is fine, except for one flaw.

The onload event should be set before the src. Sometimes the src can be loaded instantly and never fire the onload event.

(Like Totty.js pointed out.)

var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");

var image = new Image();
image.onload = function() {
    ctx.drawImage(image, 0, 0);
};
image.src = "data:image/  png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";

How to display pandas DataFrame of floats using a format string for columns?

I like using pandas.apply() with python format().

import pandas as pd
s = pd.Series([1.357, 1.489, 2.333333])

make_float = lambda x: "${:,.2f}".format(x)
s.apply(make_float)

Also, it can be easily used with multiple columns...

df = pd.concat([s, s * 2], axis=1)

make_floats = lambda row: "${:,.2f}, ${:,.3f}".format(row[0], row[1])
df.apply(make_floats, axis=1)

Short description of the scoping rules?

There was no thorough answer concerning Python3 time, so I made an answer here. Most of what is described here is detailed in the 4.2.2 Resolution of names of the Python 3 documentation.

As provided in other answers, there are 4 basic scopes, the LEGB, for Local, Enclosing, Global and Builtin. In addition to those, there is a special scope, the class body, which does not comprise an enclosing scope for methods defined within the class; any assignments within the class body make the variable from there on be bound in the class body.

Especially, no block statement, besides def and class, create a variable scope. In Python 2 a list comprehension does not create a variable scope, however in Python 3 the loop variable within list comprehensions is created in a new scope.

To demonstrate the peculiarities of the class body

x = 0
class X(object):
    y = x
    x = x + 1 # x is now a variable
    z = x

    def method(self):
        print(self.x) # -> 1
        print(x)      # -> 0, the global x
        print(y)      # -> NameError: global name 'y' is not defined

inst = X()
print(inst.x, inst.y, inst.z, x) # -> (1, 0, 1, 0)

Thus unlike in function body, you can reassign the variable to the same name in class body, to get a class variable with the same name; further lookups on this name resolve to the class variable instead.


One of the greater surprises to many newcomers to Python is that a for loop does not create a variable scope. In Python 2 the list comprehensions do not create a scope either (while generators and dict comprehensions do!) Instead they leak the value in the function or the global scope:

>>> [ i for i in range(5) ]
>>> i
4

The comprehensions can be used as a cunning (or awful if you will) way to make modifiable variables within lambda expressions in Python 2 - a lambda expression does create a variable scope, like the def statement would, but within lambda no statements are allowed. Assignment being a statement in Python means that no variable assignments in lambda are allowed, but a list comprehension is an expression...

This behaviour has been fixed in Python 3 - no comprehension expressions or generators leak variables.


The global really means the module scope; the main python module is the __main__; all imported modules are accessible through the sys.modules variable; to get access to __main__ one can use sys.modules['__main__'], or import __main__; it is perfectly acceptable to access and assign attributes there; they will show up as variables in the global scope of the main module.


If a name is ever assigned to in the current scope (except in the class scope), it will be considered belonging to that scope, otherwise it will be considered to belonging to any enclosing scope that assigns to the variable (it might not be assigned yet, or not at all), or finally the global scope. If the variable is considered local, but it is not set yet, or has been deleted, reading the variable value will result in UnboundLocalError, which is a subclass of NameError.

x = 5
def foobar():
    print(x)  # causes UnboundLocalError!
    x += 1    # because assignment here makes x a local variable within the function

# call the function
foobar()

The scope can declare that it explicitly wants to modify the global (module scope) variable, with the global keyword:

x = 5
def foobar():
    global x
    print(x)
    x += 1

foobar() # -> 5
print(x) # -> 6

This also is possible even if it was shadowed in enclosing scope:

x = 5
y = 13
def make_closure():
    x = 42
    y = 911
    def func():
        global x # sees the global value
        print(x, y)
        x += 1

    return func

func = make_closure()
func()      # -> 5 911
print(x, y) # -> 6 13

In python 2 there is no easy way to modify the value in the enclosing scope; usually this is simulated by having a mutable value, such as a list with length of 1:

def make_closure():
    value = [0]
    def get_next_value():
        value[0] += 1
        return value[0]

    return get_next_value

get_next = make_closure()
print(get_next()) # -> 1
print(get_next()) # -> 2

However in python 3, the nonlocal comes to rescue:

def make_closure():
    value = 0
    def get_next_value():
        nonlocal value
        value += 1
        return value
    return get_next_value

get_next = make_closure() # identical behavior to the previous example.

The nonlocal documentation says that

Names listed in a nonlocal statement, unlike those listed in a global statement, must refer to pre-existing bindings in an enclosing scope (the scope in which a new binding should be created cannot be determined unambiguously).

i.e. nonlocal always refers to the innermost outer non-global scope where the name has been bound (i.e. assigned to, including used as the for target variable, in the with clause, or as a function parameter).


Any variable that is not deemed to be local to the current scope, or any enclosing scope, is a global variable. A global name is looked up in the module global dictionary; if not found, the global is then looked up from the builtins module; the name of the module was changed from python 2 to python 3; in python 2 it was __builtin__ and in python 3 it is now called builtins. If you assign to an attribute of builtins module, it will be visible thereafter to any module as a readable global variable, unless that module shadows them with its own global variable with the same name.


Reading the builtin module can also be useful; suppose that you want the python 3 style print function in some parts of file, but other parts of file still use the print statement. In Python 2.6-2.7 you can get hold of the Python 3 print function with:

import __builtin__

print3 = __builtin__.__dict__['print']

The from __future__ import print_function actually does not import the print function anywhere in Python 2 - instead it just disables the parsing rules for print statement in the current module, handling print like any other variable identifier, and thus allowing the print the function be looked up in the builtins.

Convert a list of objects to an array of one of the object's properties

For everyone who is stuck with .NET 2.0, like me, try the following way (applicable to the example in the OP):

ConfigItemList.ConvertAll<string>(delegate (ConfigItemType ci) 
{ 
   return ci.Name; 
}).ToArray();

where ConfigItemList is your list variable.

SQL select statements with multiple tables

You need to join the two tables:

select p.id, p.first, p.middle, p.last, p.age,
       a.id as address_id, a.street, a.city, a.state, a.zip
from Person p inner join Address a on p.id = a.person_id
where a.zip = '97229';

This will select all of the columns from both tables. You could of course limit that by choosing different columns in the select clause.

How to rename array keys in PHP?

Talking about functional PHP, I have this more generic answer:

    array_map(function($arr){
        $ret = $arr;
        $ret['value'] = $ret['url'];
        unset($ret['url']);
        return $ret;
    }, $tag);
}

Sorting multiple keys with Unix sort

I just want to add some tips, when you using sort , be careful about your locale that effects the order of the key comparison. I usually explicitly use LC_ALL=C to make locale what I want.

How can I subset rows in a data frame in R based on a vector of values?

Really human comprehensible example (as this is the first time I am using %in%), how to compare two data frames and keep only rows containing the equal values in specific column:

# Set seed for reproducibility.
set.seed(1)

# Create two sample data frames.
data_A <- data.frame(id=c(1,2,3), value=c(1,2,3))
data_B <- data.frame(id=c(1,2,3,4), value=c(5,6,7,8))

# compare data frames by specific columns and keep only 
# the rows with equal values 
data_A[data_A$id %in% data_B$id,]   # will keep data in data_A
data_B[data_B$id %in% data_A$id,]   # will keep data in data_b

Results:

> data_A[data_A$id %in% data_B$id,]
  id value
1  1     1
2  2     2
3  3     3

> data_B[data_B$id %in% data_A$id,]
  id value
1  1     5
2  2     6
3  3     7

How do I use MySQL through XAMPP?

XAMPP only offers MySQL (Database Server) & Apache (Webserver) in one setup and you can manage them with the xampp starter.

After the successful installation navigate to your xampp folder and execute the xampp-control.exe

Press the start Button at the mysql row.

enter image description here

Now you've successfully started mysql. Now there are 2 different ways to administrate your mysql server and its databases.

But at first you have to set/change the MySQL Root password. Start the Apache server and type localhost or 127.0.0.1 in your browser's address bar. If you haven't deleted anything from the htdocs folder the xampp status page appears. Navigate to security settings and change your mysql root password.

Now, you can browse to your phpmyadmin under http://localhost/phpmyadmin or download a windows mysql client for example navicat lite or mysql workbench. Install it and log in to your mysql server with your new root password.

enter image description here

Twig ternary operator, Shorthand if-then-else

You can use shorthand syntax as of Twig 1.12.0

{{ foo ?: 'no' }} is the same as {{ foo ? foo : 'no' }}
{{ foo ? 'yes' }} is the same as {{ foo ? 'yes' : '' }}

python setup.py uninstall

For me, the following mostly works:

have pip installed, e.g.:

$ easy_install pip

Check, how is your installed package named from pip point of view:

$ pip freeze

This shall list names of all packages, you have installed (and which were detected by pip). The name can be sometime long, then use just the name of the package being shown at the and after #egg=. You can also in most cases ignore the version part (whatever follows == or -).

Then uninstall the package:

$ pip uninstall package.name.you.have.found

If it asks for confirmation about removing the package, then you are lucky guy and it will be removed.

pip shall detect all packages, which were installed by pip. It shall also detect most of the packages installed via easy_install or setup.py, but this may in some rare cases fail.

Here is real sample from my local test with package named ttr.rdstmc on MS Windows.

$ pip freeze |grep ttr
ttr.aws.s3==0.1.1dev
ttr.aws.utils.s3==0.3.0
ttr.utcutils==0.1.1dev

$ python setup.py develop
.....
.....
Finished processing dependencies for ttr.rdstmc==0.0.1dev

$ pip freeze |grep ttr
ttr.aws.s3==0.1.1dev
ttr.aws.utils.s3==0.3.0
-e hg+https://[email protected]/vlcinsky/ttr.rdstmc@d61a9922920c508862602f7f39e496f7b99315f0#egg=ttr.rdstmc-dev
ttr.utcutils==0.1.1dev

$ pip uninstall ttr.rdstmc
Uninstalling ttr.rdstmc:
  c:\python27\lib\site-packages\ttr.rdstmc.egg-link
Proceed (y/n)? y
  Successfully uninstalled ttr.rdstmc

$ pip freeze |grep ttr
ttr.aws.s3==0.1.1dev
ttr.aws.utils.s3==0.3.0
ttr.utcutils==0.1.1dev

Edit 2015-05-20

All what is written above still applies, anyway, there are small modifications available now.

Install pip in python 2.7.9 and python 3.4

Recent python versions come with a package ensurepip allowing to install pip even when being offline:

$ python -m ensurepip --upgrade

On some systems (like Debian Jessie) this is not available (to prevent breaking system python installation).

Using grep or find

Examples above assume, you have grep installed. I had (at the time I had MS Windows on my machine) installed set of linux utilities (incl. grep). Alternatively, use native MS Windows find or simply ignore that filtering and find the name in a bit longer list of detected python packages.

How can I use the MS JDBC driver with MS SQL Server 2008 Express?

You have the wrong URL.

I don't know what you mean by "JDBC 2005". When I looked on the microsoft site, I found something called the Microsoft SQL Server JDBC Driver 2.0. You're going to want that one - it includes lots of fixes and some perf improvements. [edit: you're probably going to want the latest driver. As of March 2012, the latest JDBC driver from Microsoft is JDBC 4.0]

Check the release notes. For this driver, you want:

URL:  jdbc:sqlserver://server:port;DatabaseName=dbname
Class name: com.microsoft.sqlserver.jdbc.SQLServerDriver

It seems you have the class name correct, but the URL wrong.

Microsoft changed the class name and the URL after its initial release of a JDBC driver. The URL you are using goes with the original JDBC driver from Microsoft, the one MS calls the "SQL Server 2000 version". But that driver uses a different classname.

For all subsequent drivers, the URL changed to the form I have here.

This is in the release notes for the JDBC driver.

Bootstrap Alert Auto Close

This is a good approach to show animation in and out using jQuery

  $(document).ready(function() {
      // show the alert
      $(".alert").first().hide().slideDown(500).delay(4000).slideUp(500, function () {
         $(this).remove(); 
      });
  });

Capturing mobile phone traffic on Wireshark

Here are some suggestions:

  1. For Android phones, any network: Root your phone, then install tcpdump on it. This app is a tcpdump wrapper that will install tcpdump and enable you to start captures using a GUI. Tip: You will need to make sure you supply the right interface name for the capture and this varies from one device to another, eg -i eth0 or -i tiwlan0 - or use -i any to log all interfaces

  2. For Android 4.0+ phones: Android PCAP from Kismet uses the USB OTG interface to support packet capture without requiring root. I haven't tried this app, and there are some restrictions on the type of devices supported (see their page)

  3. For Android phones: tPacketCapture uses the Android VPN service to intercept packets and capture them. I have used this app successfully, but it also seems to affect the performance with large traffic volumes (eg video streaming)

  4. For IOS 5+ devices, any network: iOS 5 added a remote virtual interface (RVI) facility that lets you use Mac OS X packet trace programs to capture traces from an iOS device. See here for more details

  5. For all phones, wi-fi only: Set up your PC as a wireless access point, then run wireshark on the PC

  6. For all phones, wi-fi only: Get a capture device that can sniff wi-fi. This has the advantage of giving you 802.11x headers as well, but you may miss some of the packets

  7. Capture using a VPN server: Its fairly easy to set-up your own VPN server using OpenVPN. You can then route your traffic through your server by setting up the mobile device as a VPN client and capture the traffic on the server end.

"find: paths must precede expression:" How do I specify a recursive search that also finds files in the current directory?

From find manual:

NON-BUGS         

   Operator precedence surprises
   The command find . -name afile -o -name bfile -print will never print
   afile because this is actually equivalent to find . -name afile -o \(
   -name bfile -a -print \).  Remember that the precedence of -a is
   higher than that of -o and when there is no operator specified
   between tests, -a is assumed.

   “paths must precede expression” error message
   $ find . -name *.c -print
   find: paths must precede expression
   Usage: find [-H] [-L] [-P] [-Olevel] [-D ... [path...] [expression]

   This happens because *.c has been expanded by the shell resulting in
   find actually receiving a command line like this:
   find . -name frcode.c locate.c word_io.c -print
   That command is of course not going to work.  Instead of doing things
   this way, you should enclose the pattern in quotes or escape the
   wildcard:
   $ find . -name '*.c' -print
   $ find . -name \*.c -print

Serializing with Jackson (JSON) - getting "No serializer found"?

Add a

getter

and a

setter

and the problem is solved.

Using Server.MapPath in external C# Classes in ASP.NET

The server.mappath("") will work on aspx page,if you want to get the absolute path from a class file you have to use this-

HttpContext.Current.Server.MapPath("~/EmailLogic/RegistrationTemplate.html")

How often does python flush to a file?

For file operations, Python uses the operating system's default buffering unless you configure it do otherwise. You can specify a buffer size, unbuffered, or line buffered.

For example, the open function takes a buffer size argument.

http://docs.python.org/library/functions.html#open

"The optional buffering argument specifies the file’s desired buffer size:"

  • 0 means unbuffered,
  • 1 means line buffered,
  • any other positive value means use a buffer of (approximately) that size.
  • A negative buffering means to use the system default, which is usually line buffered for tty devices and fully buffered for other files.
  • If omitted, the system default is used.

code:

bufsize = 0
f = open('file.txt', 'w', buffering=bufsize)

Ignore mapping one property with Automapper

When mapping a view model back to a domain model, it can be much cleaner to simply validate the source member list rather than the destination member list

Mapper.CreateMap<OrderModel, Orders>(MemberList.Source); 

Now my mapping validation doesn't fail, requiring another Ignore(), every time I add a property to my domain class.

jQuery: checking if the value of a field is null (empty)

The value of a field can not be null, it's always a string value.

The code will check if the string value is the string "NULL". You want to check if it's an empty string instead:

if ($('#person_data[document_type]').val() != ''){}

or:

if ($('#person_data[document_type]').val().length != 0){}

If you want to check if the element exist at all, you should do that before calling val:

var $d = $('#person_data[document_type]');
if ($d.length != 0) {
  if ($d.val().length != 0 ) {...}
}

Mockito : doAnswer Vs thenReturn

doAnswer and thenReturn do the same thing if:

  1. You are using Mock, not Spy
  2. The method you're stubbing is returning a value, not a void method.

Let's mock this BookService

public interface BookService {
    String getAuthor();
    void queryBookTitle(BookServiceCallback callback);
}

You can stub getAuthor() using doAnswer and thenReturn.

BookService service = mock(BookService.class);
when(service.getAuthor()).thenReturn("Joshua");
// or..
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        return "Joshua";
    }
}).when(service).getAuthor();

Note that when using doAnswer, you can't pass a method on when.

// Will throw UnfinishedStubbingException
doAnswer(invocation -> "Joshua").when(service.getAuthor());

So, when would you use doAnswer instead of thenReturn? I can think of two use cases:

  1. When you want to "stub" void method.

Using doAnswer you can do some additionals actions upon method invocation. For example, trigger a callback on queryBookTitle.

BookServiceCallback callback = new BookServiceCallback() {
    @Override
    public void onSuccess(String bookTitle) {
        assertEquals("Effective Java", bookTitle);
    }
};
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        BookServiceCallback callback = (BookServiceCallback) invocation.getArguments()[0];
        callback.onSuccess("Effective Java");
        // return null because queryBookTitle is void
        return null;
    }
}).when(service).queryBookTitle(callback);
service.queryBookTitle(callback);
  1. When you are using Spy instead of Mock

When using when-thenReturn on Spy Mockito will call real method and then stub your answer. This can cause a problem if you don't want to call real method, like in this sample:

List list = new LinkedList();
List spy = spy(list);
// Will throw java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
when(spy.get(0)).thenReturn("java");
assertEquals("java", spy.get(0));

Using doAnswer we can stub it safely.

List list = new LinkedList();
List spy = spy(list);
doAnswer(invocation -> "java").when(spy).get(0);
assertEquals("java", spy.get(0));

Actually, if you don't want to do additional actions upon method invocation, you can just use doReturn.

List list = new LinkedList();
List spy = spy(list);
doReturn("java").when(spy).get(0);
assertEquals("java", spy.get(0));

Best way to test if a row exists in a MySQL table

For non-InnoDB tables you could also use the information schema tables:

http://dev.mysql.com/doc/refman/5.1/en/tables-table.html

Check whether $_POST-value is empty

$username = filter_input(INPUT_POST, 'userName', FILTER_SANITIZE_STRING);
if ($username == '') {$username = 'Anonymous';}

Best practice - always filter inputs, sanitize string is ok, but you're better off using a custom callback function to really filter out what's not acceptable. Then check the now-safe variable if it is null/empty and if it is, set to Anonymous. Does not require 'else' statement as it was set if it existed on the first line.

What is the difference between gravity and layout_gravity in Android?

If a we want to set the gravity of content inside a view then we will use "android:gravity", and if we want to set the gravity of this view (as a whole) within its parent view then we will use "android:layout_gravity".

How to define several include path in Makefile

You need to use -I with each directory. But you can still delimit the directories with whitespace if you use (GNU) make's foreach:

INC=$(DIR1) $(DIR2) ...
INC_PARAMS=$(foreach d, $(INC), -I$d)

How to declare a vector of zeros in R

You have several options

integer(3)
numeric(3)
rep(0, 3)
rep(0L, 3)

How to get duplicate items from a list using LINQ?

  List<String> list = new List<String> { "6", "1", "2", "4", "6", "5", "1" };

    var q = from s in list
            group s by s into g
            where g.Count() > 1
            select g.First();

    foreach (var item in q)
    {
        Console.WriteLine(item);

    }

Comparison of full text search engine - Lucene, Sphinx, Postgresql, MySQL?

Apache Solr


Apart from answering OP's queries, Let me throw some insights on Apache Solr from simple introduction to detailed installation and implementation.

Simple Introduction


Anyone who has had experience with the search engines above, or other engines not in the list -- I would love to hear your opinions.

Solr shouldn't be used to solve real-time problems. For search engines, Solr is pretty much game and works flawlessly.

Solr works fine on High Traffic web-applications (I read somewhere that it is not suited for this, but I am backing up that statement). It utilizes the RAM, not the CPU.

  • result relevance and ranking

The boost helps you rank your results show up on top. Say, you're trying to search for a name john in the fields firstname and lastname, and you want to give relevancy to the firstname field, then you need to boost up the firstname field as shown.

http://localhost:8983/solr/collection1/select?q=firstname:john^2&lastname:john

As you can see, firstname field is boosted up with a score of 2.

More on SolrRelevancy

  • searching and indexing speed

The speed is unbelievably fast and no compromise on that. The reason I moved to Solr.

Regarding the indexing speed, Solr can also handle JOINS from your database tables. A higher and complex JOIN do affect the indexing speed. However, an enormous RAM config can easily tackle this situation.

The higher the RAM, The faster the indexing speed of Solr is.

  • ease of use and ease of integration with Django

Never attempted to integrate Solr and Django, however you can achieve to do that with Haystack. I found some interesting article on the same and here's the github for it.

  • resource requirements - site will be hosted on a VPS, so ideally the search engine wouldn't require a lot of RAM and CPU

Solr breeds on RAM, so if the RAM is high, you don't to have to worry about Solr.

Solr's RAM usage shoots up on full-indexing if you have some billion records, you could smartly make use of Delta imports to tackle this situation. As explained, Solr is only a near real-time solution.

  • scalability

Solr is highly scalable. Have a look on SolrCloud. Some key features of it.

  • Shards (or sharding is the concept of distributing the index among multiple machines, say if your index has grown too large)
  • Load Balancing (if Solrj is used with Solr cloud it automatically takes care of load-balancing using it's Round-Robin mechanism)
  • Distributed Search
  • High Availability
  • extra features such as "did you mean?", related searches, etc

For the above scenario, you could use the SpellCheckComponent that is packed up with Solr. There are a lot other features, The SnowballPorterFilterFactory helps to retrieve records say if you typed, books instead of book, you will be presented with results related to book.


This answer broadly focuses on Apache Solr & MySQL. Django is out of scope.

Assuming that you are under LINUX environment, you could proceed to this article further. (mine was an Ubuntu 14.04 version)

Detailed Installation

Getting Started

Download Apache Solr from here. That would be version is 4.8.1. You could download new versions, I found this stable.

After downloading the archive , extract it to a folder of your choice. Say .. Downloads or whatever.. So it will look like Downloads/solr-4.8.1/

On your prompt.. Navigate inside the directory

shankar@shankar-lenovo: cd Downloads/solr-4.8.1

So now you are here ..

shankar@shankar-lenovo: ~/Downloads/solr-4.8.1$

Start the Jetty Application Server

Jetty is available inside the examples folder of the solr-4.8.1 directory , so navigate inside that and start the Jetty Application Server.

shankar@shankar-lenovo:~/Downloads/solr-4.8.1/example$ java -jar start.jar

Now , do not close the terminal , minimize it and let it stay aside.

( TIP : Use & after start.jar to make the Jetty Server run in the background )

To check if Apache Solr runs successfully, visit this URL on the browser. http://localhost:8983/solr

Running Jetty on custom Port

It runs on the port 8983 as default. You could change the port either here or directly inside the jetty.xml file.

java -Djetty.port=9091 -jar start.jar

Download the JConnector

This JAR file acts as a bridge between MySQL and JDBC , Download the Platform Independent Version here

After downloading it, extract the folder and copy themysql-connector-java-5.1.31-bin.jar and paste it to the lib directory.

shankar@shankar-lenovo:~/Downloads/solr-4.8.1/contrib/dataimporthandler/lib

Creating the MySQL table to be linked to Apache Solr

To put Solr to use, You need to have some tables and data to search for. For that, we will use MySQL for creating a table and pushing some random names and then we could use Solr to connect to MySQL and index that table and it's entries.

1.Table Structure

CREATE TABLE test_solr_mysql
 (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  name VARCHAR(45) NULL,
  created TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id)
 );

2.Populate the above table

INSERT INTO `test_solr_mysql` (`name`) VALUES ('Jean');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Jack');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Jason');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Vego');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Grunt');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Jasper');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Fred');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Jenna');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Rebecca');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Roland');

Getting inside the core and adding the lib directives

1.Navigate to

shankar@shankar-lenovo: ~/Downloads/solr-4.8.1/example/solr/collection1/conf

2.Modifying the solrconfig.xml

Add these two directives to this file..

  <lib dir="../../../contrib/dataimporthandler/lib/" regex=".*\.jar" />
  <lib dir="../../../dist/" regex="solr-dataimporthandler-\d.*\.jar" />

Now add the DIH (Data Import Handler)

<requestHandler name="/dataimport" 
  class="org.apache.solr.handler.dataimport.DataImportHandler" >
    <lst name="defaults">
      <str name="config">db-data-config.xml</str>
    </lst>
</requestHandler>

3.Create the db-data-config.xml file

If the file exists then ignore, add these lines to that file. As you can see the first line, you need to provide the credentials of your MySQL database. The Database name, username and password.

<dataConfig>
    <dataSource type="JdbcDataSource" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost/yourdbname" user="dbuser" password="dbpass"/>
    <document>
   <entity name="test_solr" query="select CONCAT('test_solr-',id) as rid,name from test_solr_mysql WHERE '${dataimporter.request.clean}' != 'false'
      OR `created` > '${dataimporter.last_index_time}'" >
    <field name="id" column="rid" />
    <field name="solr_name" column="name" />
    </entity>
   </document>
</dataConfig>

( TIP : You can have any number of entities but watch out for id field, if they are same then indexing will skipped. )

4.Modify the schema.xml file

Add this to your schema.xml as shown..

<uniqueKey>id</uniqueKey>
<field name="solr_name" type="string" indexed="true" stored="true" />

Implementation

Indexing

This is where the real deal is. You need to do the indexing of data from MySQL to Solr inorder to make use of Solr Queries.

Step 1: Go to Solr Admin Panel

Hit the URL http://localhost:8983/solr on your browser. The screen opens like this.

This is the main Apache Solr Administration Panel

As the marker indicates, go to Logging inorder to check if any of the above configuration has led to errors.

Step 2: Check your Logs

Ok so now you are here, As you can there are a lot of yellow messages (WARNINGS). Make sure you don't have error messages marked in red. Earlier, on our configuration we had added a select query on our db-data-config.xml, say if there were any errors on that query, it would have shown up here.

This is the logging section of your Apache Solr engine

Fine, no errors. We are good to go. Let's choose collection1 from the list as depicted and select Dataimport

Step 3: DIH (Data Import Handler)

Using the DIH, you will be connecting to MySQL from Solr through the configuration file db-data-config.xml from the Solr interface and retrieve the 10 records from the database which gets indexed onto Solr.

To do that, Choose full-import , and check the options Clean and Commit. Now click Execute as shown.

Alternatively, you could use a direct full-import query like this too..

http://localhost:8983/solr/collection1/dataimport?command=full-import&commit=true

The Data Import Handler

After you clicked Execute, Solr begins to index the records, if there were any errors, it would say Indexing Failed and you have to go back to the Logging section to see what has gone wrong.

Assuming there are no errors with this configuration and if the indexing is successfully complete., you would get this notification.

Indexing Success

Step 4: Running Solr Queries

Seems like everything went well, now you could use Solr Queries to query the data that was indexed. Click the Query on the left and then press Execute button on the bottom.

You will see the indexed records as shown.

The corresponding Solr query for listing all the records is

http://localhost:8983/solr/collection1/select?q=*:*&wt=json&indent=true

The indexed data

Well, there goes all 10 indexed records. Say, we need only names starting with Ja , in this case, you need to target the column name solr_name, Hence your query goes like this.

http://localhost:8983/solr/collection1/select?q=solr_name:Ja*&wt=json&indent=true

The JSON data starting with Ja*

That's how you write Solr Queries. To read more about it, Check this beautiful article.

Commenting multiple lines in DOS batch file

If you want to add REM at the beginning of each line instead of using GOTO, you can use Notepad++ to do this easily following these steps:

  1. Select the block of lines
  2. hit Ctrl-Q

Repeat steps to uncomment

How to convert hex to ASCII characters in the Linux shell?

You can use this command (python script) for larger inputs:

echo 58595a | python -c "import sys; import binascii; print(binascii.unhexlify(sys.stdin.read().strip()).decode())"

The result will be:

XYZ

And for more simplicity, define an alias:

alias hexdecoder='python -c "import sys; import binascii; print(binascii.unhexlify(sys.stdin.read().strip()).decode())"'

echo 58595a | hexdecoder

SQL Server - calculate elapsed time between two datetime stamps in HH:MM:SS format

DECLARE @EndTime AS DATETIME, @StartTime AS DATETIME

SELECT @StartTime = '2013-03-08 08:00:00', @EndTime = '2013-03-08 08:30:00'

SELECT CAST(@EndTime - @StartTime AS TIME)

Result: 00:30:00.0000000

Format result as you see fit.

How do I convert from BLOB to TEXT in MySQL?

That's unnecessary. Just use SELECT CONVERT(column USING utf8) FROM..... instead of just SELECT column FROM...

Remove spaces from std::string in C++

From gamedev

string.erase(std::remove_if(string.begin(), string.end(), std::isspace), string.end());

JavaScriptSerializer - JSON serialization of enum as string

The combination of Omer Bokhari and uri 's answers is alsways my solution since the values that I want to provide is usually different from what I have in my enum specially that I would like to be able to change my enums if I need to.

So if anyone is interested, it is something like this:

public enum Gender
{
   [EnumMember(Value = "male")] 
   Male,
   [EnumMember(Value = "female")] 
   Female
}

class Person
{
    int Age { get; set; }
    [JsonConverter(typeof(StringEnumConverter))]
    Gender Gender { get; set; }
}

Can't start hostednetwork

This happen after you disable via Control Panel -> network adapters -> right click button on the virtual connection -> disable

To fix that go to Device Manager (Windows-key + x + m on windows 8, Windows-key + x then m on windows 10), then open the network adapters tree , right click button on Microsoft Hosted Network Virtual Adapter and click on enable.

Try now with the command netsh wlan start hostednetwork with admin privileges. It should work.

Note: If you don't see the network adapter with name 'Microsoft Hosted Network Virtual Adapter' try on menu -> view -> show hidden devices in the Device Manager window.

How to shift a column in Pandas DataFrame

Trying to answer a personal problem and similar to yours I found on Pandas Doc what I think would answer this question:

DataFrame.shift(periods=1, freq=None, axis=0) Shift index by desired number of periods with an optional time freq

Notes

If freq is specified then the index values are shifted but the data is not realigned. That is, use freq if you would like to extend the index when shifting and preserve the original data.

Hope to help future questions in this matter.

Can I escape a double quote in a verbatim string literal?

Use a duplicated double quote.

@"this ""word"" is escaped";

outputs:

this "word" is escaped

How to pass Multiple Parameters from ajax call to MVC Controller

$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "ChnagePassword.aspx/AutocompleteSuggestions",
  data: "{'searchstring':'" + request.term + "','st':'Arb'}",
  dataType: "json",
  success: function (data) {
     response($.map(data.d, function (item) {
         return { value: item }
     }))
  },
  error: function (result) {
      alert("Error");
  }
});

"The import org.springframework cannot be resolved."

In my case I had to delete the jars inside .m2/repository and then did a Maven->Update Maven Project

Looks like the jars were corrupt and deleting and downloading the fresh jar fixed the issue.

Constructing pandas DataFrame from values in variables gives "ValueError: If using all scalar values, you must pass an index"

Pandas magic at work. All logic is out.

The error message "ValueError: If using all scalar values, you must pass an index" Says you must pass an index.

This does not necessarily mean passing an index makes pandas do what you want it to do

When you pass an index, pandas will treat your dictionary keys as column names and the values as what the column should contain for each of the values in the index.

a = 2
b = 3
df2 = pd.DataFrame({'A':a,'B':b}, index=[1])

    A   B
1   2   3

Passing a larger index:

df2 = pd.DataFrame({'A':a,'B':b}, index=[1, 2, 3, 4])

    A   B
1   2   3
2   2   3
3   2   3
4   2   3

An index is usually automatically generated by a dataframe when none is given. However, pandas does not know how many rows of 2 and 3 you want. You can however be more explicit about it

df2 = pd.DataFrame({'A':[a]*4,'B':[b]*4})
df2

    A   B
0   2   3
1   2   3
2   2   3
3   2   3

The default index is 0 based though.

I would recommend always passing a dictionary of lists to the dataframe constructor when creating dataframes. It's easier to read for other developers. Pandas has a lot of caveats, don't make other developers have to experts in all of them in order to read your code.

Enabling error display in PHP via htaccess only

.htaccess:

php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
php_flag  log_errors on
php_value error_log  /home/path/public_html/domain/PHP_errors.log

CSS: fixed to bottom and centered

revised code by Daniel Kanis:

just change the following lines in CSS

.problem {text-align:center}
.enclose {position:fixed;bottom:0px;width:100%;}

and in html:

<p class="enclose problem">
Your footer text here.
</p>

Getting a random value from a JavaScript array

A generic way to get random element(s):

_x000D_
_x000D_
let some_array = ['Jan', 'Feb', 'Mar', 'Apr', 'May'];_x000D_
let months = random_elems(some_array, 3);_x000D_
_x000D_
console.log(months);_x000D_
_x000D_
function random_elems(arr, count) {_x000D_
  let len = arr.length;_x000D_
  let lookup = {};_x000D_
  let tmp = [];_x000D_
_x000D_
  if (count > len)_x000D_
    count = len;_x000D_
_x000D_
  for (let i = 0; i < count; i++) {_x000D_
    let index;_x000D_
    do {_x000D_
      index = ~~(Math.random() * len);_x000D_
    } while (index in lookup);_x000D_
    lookup[index] = null;_x000D_
    tmp.push(arr[index]);_x000D_
  }_x000D_
_x000D_
  return tmp;_x000D_
}
_x000D_
_x000D_
_x000D_

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

In my case, It seems like I wasnt really able to kill the mysql process, when I run

sudo service mysql stop
ps -ef | grep mysql

The mysql process was always there, it looks like it was blocking the socket file and new mysql process wasnt able to create it itself.

so this helped

cd /var/run
sudo cp mysqld/ mysqld.bc -rf
sudo chown mysql:mysql mysqld.bc/
sudo service mysql stop
sudo cp mysqld.bc/ mysqld -rf
sudo chown mysql:mysql mysqld -R
sudo /usr/sbin/mysqld --skip-grant-tables --skip-networking &

Now Im able to log in database using

mysql -u root

Then to update root password:

UPDATE user SET authentication_string=password('YOURPASSWORDHERE') WHERE user='root';
FLUSH PRIVILEGES;

PS: I had trouble updating root passwod, seems like problem with "auth_socket" plugin, so I had to create new user with full privileges

insert into user set `Host` = "localhost", `User` = "super", `plugin` = "mysql_native_password", `authentication_string` = NULL, `password_expired` = "N", `password_lifetime` = NULL, `account_locked` = "N", `Select_priv` = "Y",
`Insert_priv` = "Y", `Update_priv` = "Y", `Delete_priv` = "Y", `Create_priv` = "Y", `Drop_priv` = "Y", `Reload_priv` = "Y", `Shutdown_priv` = "Y", `Process_priv` = "Y", `File_priv` = "Y",
`Grant_priv` = "Y",  `References_priv` = "Y", `Index_priv` = "Y", `Alter_priv` = "Y", `Show_db_priv` = "Y", `Super_priv` = "Y", `Create_tmp_table_priv` = "Y", `Lock_tables_priv` = "Y",
`Execute_priv` = "Y", `Repl_slave_priv` = "Y",  `Repl_client_priv` = "Y",  `Create_view_priv` = "Y", `Show_view_priv` = "Y", `Create_routine_priv` = "Y", `Alter_routine_priv` = "Y",
`Create_user_priv` = "Y",  `Event_priv` = "Y", `Trigger_priv` = "Y", `Create_tablespace_priv` = "Y";

This creates user "super" with no password and then you can connect with mysql -u super

JavaFX FXML controller - constructor vs initialize method

In Addition to the above answers, there probably should be noted that there is a legacy way to implement the initialization. There is an interface called Initializable from the fxml library.

import javafx.fxml.Initializable;

class MyController implements Initializable {
    @FXML private TableView<MyModel> tableView;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        tableView.getItems().addAll(getDataFromSource());
    }
}

Parameters:

location - The location used to resolve relative paths for the root object, or null if the location is not known.
resources - The resources used to localize the root object, or null if the root object was not localized. 

And the note of the docs why the simple way of using @FXML public void initialize() works:

NOTE This interface has been superseded by automatic injection of location and resources properties into the controller. FXMLLoader will now automatically call any suitably annotated no-arg initialize() method defined by the controller. It is recommended that the injection approach be used whenever possible.

How do I clear this setInterval inside a function?

the_int=window.clearInterval(the_int);

How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file?

This code will do what you're looking for. It's based on examples found here and here.

The autofmt_xdate() call is particularly useful for making the x-axis labels readable.

import numpy as np
from matplotlib import pyplot as plt

fig = plt.figure()

width = .35
ind = np.arange(len(OY))
plt.bar(ind, OY, width=width)
plt.xticks(ind + width / 2, OX)

fig.autofmt_xdate()

plt.savefig("figure.pdf")

enter image description here

How do I install and use the ASP.NET AJAX Control Toolkit in my .NET 3.5 web applications?

If you are using MasterPages and Content pages in your app - you also have the option of putting the ScriptManager on the Masterpage and then every ContentPage that uses that MasterPage will NOT need a script manager added. If you need some of the special configurations of the ScriptManager - like javascript file references - you can use a ScriptManagerProxy control on the content page that needs it.

Reversing a string in C

The code looks unnecessarily complicated. Here is my version:

void strrev(char* str) { 
    size_t len = strlen(str);
    char buf[len]; 

    for (size_t i = 0; i < len; i++) { 
        buf[i] = str[len - 1 - i]; 
    }; 

    for (size_t i = 0; i < len; i++) { 
        str[i] = buf[i]; 
    }
}

SQL Transaction Error: The current transaction cannot be committed and cannot support operations that write to the log file

I have encountered this error while updating records from table which has trigger enabled. For example - I have trigger 'Trigger1' on table 'Table1'. When I tried to update the 'Table1' using the update query - it throws the same error. THis is because if you are updating more than 1 record in your query, then 'Trigger1' will throw this error as it doesn't support updating multiple entries if it is enabled on same table. I tried disabling trigger before update and then performed update operation and it was completed without any error.

DISABLE TRIGGER Trigger1 ON Table1;
Update query --------
Enable TRIGGER Trigger1 ON Table1;

Parse v. TryParse

Parse throws an exception if it cannot parse the value, whereas TryParse returns a bool indicating whether it succeeded.

TryParse does not just try/catch internally - the whole point of it is that it is implemented without exceptions so that it is fast. In fact the way it is most likely implemented is that internally the Parse method will call TryParse and then throw an exception if it returns false.

In a nutshell, use Parse if you are sure the value will be valid; otherwise use TryParse.

Working Soap client example

Yes, if you can acquire any WSDL file, then you can use SoapUI to create mock service of that service complete with unit test requests. I created an example of this (using Maven) that you can try out.

angular2: Error: TypeError: Cannot read property '...' of undefined

That's because abc is undefined at the moment of the template rendering. You can use safe navigation operator (?) to "protect" template until HTTP call is completed:

{{abc?.xyz?.name}}

You can read more about safe navigation operator here.

Update:

Safe navigation operator can't be used in arrays, you will have to take advantage of NgIf directive to overcome this problem:

<div *ngIf="arr && arr.length > 0">
    {{arr[0].name}}
</div>

Read more about NgIf directive here.

Get first key in a (possibly) associative array?

You could try

array_keys($data)[0]

Adding backslashes without escaping [Python]

Python treats \ in literal string in a special way.
This is so you can type '\n' to mean newline or '\t' to mean tab
Since '\&' doesn't mean anything special to Python, instead of causing an error, the Python lexical analyser implicitly adds the extra \ for you.

Really it is better to use \\& or r'\&' instead of '\&'

The r here means raw string and means that \ isn't treated specially unless it is right before the quote character at the start of the string.

In the interactive console, Python uses repr to display the result, so that is why you see the double '\'. If you print your string or use len(string) you will see that it is really only the 2 characters

Some examples

>>> 'Here\'s a backslash: \\'
"Here's a backslash: \\"
>>> print 'Here\'s a backslash: \\'
Here's a backslash: \
>>> 'Here\'s a backslash: \\. Here\'s a double quote: ".'
'Here\'s a backslash: \\. Here\'s a double quote: ".'
>>> print 'Here\'s a backslash: \\. Here\'s a double quote: ".'
Here's a backslash: \. Here's a double quote ".

To Clarify the point Peter makes in his comment see this link

Unlike Standard C, all unrecognized escape sequences are left in the string unchanged, i.e., the backslash is left in the string. (This behavior is useful when debugging: if an escape sequence is mistyped, the resulting output is more easily recognized as broken.) It is also important to note that the escape sequences marked as “(Unicode only)” in the table above fall into the category of unrecognized escapes for non-Unicode string literals.

Get webpage contents with Python?

Because you're using Python 3.1, you need to use the new Python 3.1 APIs.

Try:

urllib.request.urlopen('http://www.python.org/')

Alternately, it looks like you're working from Python 2 examples. Write it in Python 2, then use the 2to3 tool to convert it. On Windows, 2to3.py is in \python31\tools\scripts. Can someone else point out where to find 2to3.py on other platforms?

Edit

These days, I write Python 2 and 3 compatible code by using six.

from six.moves import urllib
urllib.request.urlopen('http://www.python.org')

Assuming you have six installed, that runs on both Python 2 and Python 3.

"Large data" workflows using pandas

This is the case for pymongo. I have also prototyped using sql server, sqlite, HDF, ORM (SQLAlchemy) in python. First and foremost pymongo is a document based DB, so each person would be a document (dict of attributes). Many people form a collection and you can have many collections (people, stock market, income).

pd.dateframe -> pymongo Note: I use the chunksize in read_csv to keep it to 5 to 10k records(pymongo drops the socket if larger)

aCollection.insert((a[1].to_dict() for a in df.iterrows()))

querying: gt = greater than...

pd.DataFrame(list(mongoCollection.find({'anAttribute':{'$gt':2887000, '$lt':2889000}})))

.find() returns an iterator so I commonly use ichunked to chop into smaller iterators.

How about a join since I normally get 10 data sources to paste together:

aJoinDF = pandas.DataFrame(list(mongoCollection.find({'anAttribute':{'$in':Att_Keys}})))

then (in my case sometimes I have to agg on aJoinDF first before its "mergeable".)

df = pandas.merge(df, aJoinDF, on=aKey, how='left')

And you can then write the new info to your main collection via the update method below. (logical collection vs physical datasources).

collection.update({primarykey:foo},{key:change})

On smaller lookups, just denormalize. For example, you have code in the document and you just add the field code text and do a dict lookup as you create documents.

Now you have a nice dataset based around a person, you can unleash your logic on each case and make more attributes. Finally you can read into pandas your 3 to memory max key indicators and do pivots/agg/data exploration. This works for me for 3 million records with numbers/big text/categories/codes/floats/...

You can also use the two methods built into MongoDB (MapReduce and aggregate framework). See here for more info about the aggregate framework, as it seems to be easier than MapReduce and looks handy for quick aggregate work. Notice I didn't need to define my fields or relations, and I can add items to a document. At the current state of the rapidly changing numpy, pandas, python toolset, MongoDB helps me just get to work :)

Java: How to access methods from another class

I have another solution. If Alpha and Beta are your only extra class then why not make a static variable with the image of the class.

Like in Alpha class :

public class Alpha{
        public static Alpha alpha;
        public Alpha(){
                this.alpha = this;
}

Now you you can call the function in Beta class by just using these lines :

new Alpha();
Alpha.alpha.DoSomethingAlpha();

Array.sort() doesn't sort numbers correctly

The default sort for arrays in Javascript is an alphabetical search. If you want a numerical sort, try something like this:

var a = [ 1, 100, 50, 2, 5];
a.sort(function(a,b) { return a - b; });

Auto-size dynamic text to fill fixed size container

Here's an improved looping method that uses binary search to find the largest possible size that fits into the parent in the fewest steps possible (this is faster and more accurate than stepping by a fixed font size). The code is also optimized in several ways for performance.

By default, 10 binary search steps will be performed, which will get within 0.1% of the optimal size. You could instead set numIter to some value N to get within 1/2^N of the optimal size.

Call it with a CSS selector, e.g.: fitToParent('.title-span');

/**
 * Fit all elements matching a given CSS selector to their parent elements'
 * width and height, by adjusting the font-size attribute to be as large as
 * possible. Uses binary search.
 */
var fitToParent = function(selector) {
    var numIter = 10;  // Number of binary search iterations
    var regexp = /\d+(\.\d+)?/;
    var fontSize = function(elem) {
        var match = elem.css('font-size').match(regexp);
        var size = match == null ? 16 : parseFloat(match[0]);
        return isNaN(size) ? 16 : size;
    }
    $(selector).each(function() {
        var elem = $(this);
        var parentWidth = elem.parent().width();
        var parentHeight = elem.parent().height();
        if (elem.width() > parentWidth || elem.height() > parentHeight) {
            var maxSize = fontSize(elem), minSize = 0.1;
            for (var i = 0; i < numIter; i++) {
                var currSize = (minSize + maxSize) / 2;
                elem.css('font-size', currSize);
                if (elem.width() > parentWidth || elem.height() > parentHeight) {
                    maxSize = currSize;
                } else {
                    minSize = currSize;
                }
            }
            elem.css('font-size', minSize);
        }
    });
};

Requests -- how to tell if you're getting a 404

Look at the r.status_code attribute:

if r.status_code == 404:
    # A 404 was issued.

Demo:

>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404

If you want requests to raise an exception for error codes (4xx or 5xx), call r.raise_for_status():

>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "requests/models.py", line 664, in raise_for_status
    raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.

You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:

if r:
    # successful response

If you want to be more explicit, use if r.ok:.

Why is datetime.strptime not working in this simple example?

You are importing the module datetime, which doesn't have a strptime function.

That module does have a datetime object with that method though:

import datetime
dtDate = datetime.datetime.strptime(sDate, "%m/%d/%Y")

Alternatively you can import the datetime object from the module:

from datetime import datetime
dtDate = datetime.strptime(sDate, "%m/%d/%Y")

Note that the strptime method was added in python 2.5; if you are using an older version use the following code instead:

import datetime, time
dtDate = datetime.datetime(*time.strptime(sDate, "%m/%d/%Y")[:6])

WPF chart controls

The WPF Toolkit is available. It is free from CodePlex.

It can be downloaded here. There is some commentary here.

Json.net serialize/deserialize derived types?

Use this JsonKnownTypes, it's very similar way to use, it just add discriminator to json:

[JsonConverter(typeof(JsonKnownTypeConverter<BaseClass>))]
[JsonKnownType(typeof(Base), "base")]
[JsonKnownType(typeof(Derived), "derived")]
public class Base
{
    public string Name;
}
public class Derived : Base
{
    public string Something;
}

Now when you serialize object in json will be add "$type" with "base" and "derived" value and it will be use for deserialize

Serialized list example:

[
    {"Name":"some name", "$type":"base"},
    {"Name":"some name", "Something":"something", "$type":"derived"}
]

How to find sum of multiple columns in a table in SQL Server 2005?

SELECT Emp_cd, Val1, Val2, Val3, SUM(Val1 + Val2 + Val3) AS TOTAL 
FROM Emp
GROUP BY Emp_cd, Val1, Val2, Val3

Does WhatsApp offer an open API?

WhatsApp does not have a API available for public use. As you put it, it's a closed system.

However, they provide several other ways in which your iPhone application can interact with WhatsApp: through custom URL schemes, share extension and through the Document Interaction API.

See this WhatsApp FAQ article.

Create Word Document using PHP in Linux

By far the easiest way to create DOC files on Linux, using PHP is with the Zend Framework component phpLiveDocx.

From the project web site:

"phpLiveDocx allows developers to generate documents by combining structured data from PHP with a template, created in a word processor. The resulting document can be saved as a PDF, DOCX, DOC or RTF file. The concept is the same as with mail-merge."

what is the unsigned datatype?

In C and C++

unsigned = unsigned int (Integer type)
signed   = signed int (Integer type)

An unsigned integer containing n bits can have a value between 0 and (2^n-1) , which is 2^n different values.

An unsigned integer is either positive or zero.

Signed integers are stored in a computer using 2's complement.

PHP: Call to undefined function: simplexml_load_string()

For Nginx (without apache) and PHP 7.2, installing php7.2-xml wasn't enough. Had to install php7.2-simplexml package to get it to work

So the commands for debian/ubuntu, update packages and install both packages

apt update
apt install php7.2-xml php7.2-simplexml

And restart both Nginx and php

systemctl restart nginx php7.2-fpm

Android EditText delete(backspace) key event

Here is my easy solution, which works for all the API's:

private int previousLength;
private boolean backSpace;

// ...

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    previousLength = s.length();
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}

@Override
public void afterTextChanged(Editable s) {
    backSpace = previousLength > s.length();

    if (backSpace) {

        // do your stuff ...

    } 
}

UPDATE 17.04.18 .
As pointed out in comments, this solution doesn't track the backspace press if EditText is empty (the same as most of the other solutions).
However, it's enough for most of the use cases.
P.S. If I had to create something similar today, I would do:

public abstract class TextWatcherExtended implements TextWatcher {

    private int lastLength;

    public abstract void afterTextChanged(Editable s, boolean backSpace);

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        lastLength = s.length();
    }

    @Override
    public void afterTextChanged(Editable s) {
        afterTextChanged(s, lastLength > s.length());
    }  
}

Then just use it as a regular TextWatcher:

 editText.addTextChangedListener(new TextWatcherExtended() {
        @Override
        public void afterTextChanged(Editable s, boolean backSpace) {
           // Here you are! You got missing "backSpace" flag
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // Do something useful if you wish.
            // Or override it in TextWatcherExtended class if want to avoid it here 
        }
    });

What is the correct XPath for choosing attributes that contain "foo"?

This XPath will give you all nodes that have attributes containing 'Foo' regardless of node name or attribute name:

//attribute::*[contains(., 'Foo')]/..

Of course, if you're more interested in the contents of the attribute themselves, and not necessarily their parent node, just drop the /..

//attribute::*[contains(., 'Foo')]

Pandas sort by group aggregate and column

One way to do this is to insert a dummy column with the sums in order to sort:

In [10]: sum_B_over_A = df.groupby('A').sum().B

In [11]: sum_B_over_A
Out[11]: 
A
bar    0.253652
baz   -2.829711
foo    0.551376
Name: B

in [12]: df['sum_B_over_A'] = df.A.apply(sum_B_over_A.get_value)

In [13]: df
Out[13]: 
     A         B      C  sum_B_over_A
0  foo  1.624345  False      0.551376
1  bar -0.611756   True      0.253652
2  baz -0.528172  False     -2.829711
3  foo -1.072969   True      0.551376
4  bar  0.865408  False      0.253652
5  baz -2.301539   True     -2.829711

In [14]: df.sort(['sum_B_over_A', 'A', 'B'])
Out[14]: 
     A         B      C   sum_B_over_A
5  baz -2.301539   True      -2.829711
2  baz -0.528172  False      -2.829711
1  bar -0.611756   True       0.253652
4  bar  0.865408  False       0.253652
3  foo -1.072969   True       0.551376
0  foo  1.624345  False       0.551376

and maybe you would drop the dummy row:

In [15]: df.sort(['sum_B_over_A', 'A', 'B']).drop('sum_B_over_A', axis=1)
Out[15]: 
     A         B      C
5  baz -2.301539   True
2  baz -0.528172  False
1  bar -0.611756   True
4  bar  0.865408  False
3  foo -1.072969   True
0  foo  1.624345  False

How to only find files in a given directory, and ignore subdirectories using bash

I got here with a bit more general problem - I wanted to find files in directories matching pattern but not in their subdirectories.

My solution (assuming we're looking for all cpp files living directly in arch directories):

find . -path "*/arch/*/*" -prune -o -path "*/arch/*.cpp" -print

I couldn't use maxdepth since it limited search in the first place, and didn't know names of subdirectories that I wanted to exclude.

How to get cookie's expire time

Putting an encoded json inside the cookie is my favorite method, to get properly formated data out of a cookie. Try that:

$expiry = time() + 12345;
$data = (object) array( "value1" => "just for fun", "value2" => "i'll save whatever I want here" );
$cookieData = (object) array( "data" => $data, "expiry" => $expiry );
setcookie( "cookiename", json_encode( $cookieData ), $expiry );

then when you get your cookie next time:

$cookie = json_decode( $_COOKIE[ "cookiename" ] );

you can simply extract the expiry time, which was inserted as data inside the cookie itself..

$expiry = $cookie->expiry;

and additionally the data which will come out as a usable object :)

$data = $cookie->data;
$value1 = $cookie->data->value1;

etc. I find that to be a much neater way to use cookies, because you can nest as many small objects within other objects as you wish!

Creating a static class with no instances

You could use a classmethod or staticmethod

class Paul(object):
    elems = []

    @classmethod
    def addelem(cls, e):
        cls.elems.append(e)

    @staticmethod
    def addelem2(e):
        Paul.elems.append(e)

Paul.addelem(1)
Paul.addelem2(2)

print(Paul.elems)

classmethod has advantage that it would work with sub classes, if you really wanted that functionality.

module is certainly best though.

Application not picking up .css file (flask/python)

The flask project structure is different. As you mentioned in question the project structure is the same but the only problem is wit the styles folder. Styles folder must come within the static folder.

static/styles/style.css

Android Webview - Webpage should fit the device screen

For reference, this is a Kotlin implementation of @danh32's solution:

private fun getWebviewScale (contentWidth : Int) : Int {
    val dm = DisplayMetrics()
    windowManager.defaultDisplay.getRealMetrics(dm)
    val pixWidth = dm.widthPixels;
    return (pixWidth.toFloat()/contentWidth.toFloat() * 100F)
             .toInt()
}

In my case, width was determined by three images to be 300 pix so:

webview.setInitialScale(getWebviewScale(300))

It took me hours to find this post. Thanks!

Excel: How to check if a cell is empty with VBA?

You could use IsEmpty() function like this:

...
Set rRng = Sheet1.Range("A10")
If IsEmpty(rRng.Value) Then ...

you could also use following:

If ActiveCell.Value = vbNullString Then ...

appending array to FormData and send via AJAX

This is an old question but I ran into this problem with posting objects along with files recently. I needed to be able to post an object, with child properties that were objects and arrays as well.

The function below will walk through an object and create the correct formData object.

// formData - instance of FormData object
// data - object to post
function getFormData(formData, data, previousKey) {
  if (data instanceof Object) {
    Object.keys(data).forEach(key => {
      const value = data[key];
      if (value instanceof Object && !Array.isArray(value)) {
        return this.getFormData(formData, value, key);
      }
      if (previousKey) {
        key = `${previousKey}[${key}]`;
      }
      if (Array.isArray(value)) {
        value.forEach(val => {
          formData.append(`${key}[]`, val);
        });
      } else {
        formData.append(key, value);
      }
    });
  }
}

This will convert the following json -

{
  name: 'starwars',
  year: 1977,
  characters: {
    good: ['luke', 'leia'],
    bad: ['vader'],
  },
}

into the following FormData

 name, starwars
 year, 1977
 characters[good][], luke
 characters[good][], leia
 characters[bad][], vader

Float a div right, without impacting on design

If you don't want the image to affect the layout at all (and float on top of other content) you can apply the following CSS to the image:

position:absolute;
right:0;
top:0;

If you want it to float at the right of a particular parent section, you can add position: relative to that section.

Is Visual Studio Community a 30 day trial?

For VS2019 I was able to signup with my github account:

enter image description here enter image description here enter image description here enter image description here

Then it will send password to your email and you will be able to sign.

Simple CSS Animation Loop – Fading In & Out "Loading" Text

well looking for a simpler variation I found this:

it's truly smart, and I guess you might want to add other browsers variations too although it worked for me both on Chrome and Firefox.

demo and credit => http://codepen.io/Ahrengot/pen/bKdLC

_x000D_
_x000D_
@keyframes fadeIn { _x000D_
  from { opacity: 0; } _x000D_
}_x000D_
_x000D_
.animate-flicker {_x000D_
    animation: fadeIn 1s infinite alternate;_x000D_
}
_x000D_
<h2 class="animate-flicker">Jump in the hole!</h2>
_x000D_
_x000D_
_x000D_

How to draw an overlay on a SurfaceView used by Camera on Android?

SurfaceView probably does not work like a regular View in this regard.

Instead, do the following:

  1. Put your SurfaceView inside of a FrameLayout or RelativeLayout in your layout XML file, since both of those allow stacking of widgets on the Z-axis
  2. Move your drawing logic into a separate custom View class
  3. Add an instance of the custom View class to the layout XML file as a child of the FrameLayout or RelativeLayout, but have it appear after the SurfaceView

This will cause your custom View class to appear to float above the SurfaceView.

See here for a sample project that layers popup panels above a SurfaceView used for video playback.

AngularJS : Initialize service with asynchronous data

Also, you can use the following techniques to provision your service globally, before actual controllers are executed: https://stackoverflow.com/a/27050497/1056679. Just resolve your data globally and then pass it to your service in run block for example.

SQL server query to get the list of columns in a table along with Data types, NOT NULL, and PRIMARY KEY constraints

There is no primary key here, but this can help other users who would just like to have a table name with field name and basic field properties

USE [**YourDB**]
GO
SELECT tbl.name, fld.[Column Name],fld.[Constraint],fld.DataType 
FROM sys.all_objects as tbl left join 
(SELECT c.OBJECT_ID,  c.name AS 'Column Name',
       t.name + '(' + cast(c.max_length as varchar(50)) + ')' As 'DataType',
       case 
         WHEN  c.is_nullable = 0 then 'null' else 'not null'
         END AS 'Constraint'
  FROM sys.columns c
  JOIN sys.types t
    ON c.user_type_id = t.user_type_id
) as fld on tbl.OBJECT_ID = fld.OBJECT_ID
WHERE ( tbl.[type]='U' and tbl.[is_ms_shipped] = 0)
ORDER BY tbl.[name],fld.[Column Name]
GO

Twitter Bootstrap Form File Element Upload Button

No fancy shiz required:

HTML:

<form method="post" action="/api/admin/image" enctype="multipart/form-data">
    <input type="hidden" name="url" value="<%= boxes[i].url %>" />
    <input class="image-file-chosen" type="text" />
    <br />
    <input class="btn image-file-button" value="Choose Image" />
    <input class="image-file hide" type="file" name="image"/> <!-- Hidden -->
    <br />
    <br />
    <input class="btn" type="submit" name="image" value="Upload" />
    <br />
</form>

JS:

$('.image-file-button').each(function() {
      $(this).off('click').on('click', function() {
           $(this).siblings('.image-file').trigger('click');
      });
});
$('.image-file').each(function() {
      $(this).change(function () {
           $(this).siblings('.image-file-chosen').val(this.files[0].name);
      });
});

CAUTION: The three form elements in question MUST be siblings of each other (.image-file-chosen, .image-file-button, .image-file)