Programs & Examples On #Array initialization

All possible array initialization syntaxes

Trivial solution with expressions. Note that with NewArrayInit you can create just one-dimensional array.

NewArrayExpression expr = Expression.NewArrayInit(typeof(int), new[] { Expression.Constant(2), Expression.Constant(3) });
int[] array = Expression.Lambda<Func<int[]>>(expr).Compile()(); // compile and call callback

Array initializing in Scala

scala> val arr = Array("Hello","World")
arr: Array[java.lang.String] = Array(Hello, World)

How can I declare a two dimensional string array?

string[][] is not a two-dimensional array, it's an array of arrays (a jagged array). That's something different.

To declare a two-dimensional array, use this syntax:

string[,] tablero = new string[3, 3];

If you really want a jagged array, you need to initialize it like this:

string[][] tablero = new string[][] { new string[3], 
                                      new string[3], 
                                      new string[3] };

How organize uploaded media in WP?

Best is Enhanced Media Library plugin http://wordpress.org/plugins/enhanced-media-library/ It's adding as many category/ taxonomies you want. Works just great. You can filter media everywhere, plus have the categories in the menu choices, can be usefull also.

How to find the path of the local git repository when I am possibly in a subdirectory

git rev-parse --show-toplevel

could be enough if executed within a git repo.
From git rev-parse man page:

--show-toplevel

Show the absolute path of the top-level directory.

For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":

git rev-parse --git-dir

That would give the path of the .git directory.


The OP mentions:

git rev-parse --show-prefix

which returns the local path under the git repo root. (empty if you are at the git repo root)


Note: for simply checking if one is in a git repo, I find the following command quite expressive:

git rev-parse --is-inside-work-tree

And yes, if you need to check if you are in a .git git-dir folder:

git rev-parse --is-inside-git-dir

What can MATLAB do that R cannot do?

As a user of both MATLAB and R, I think they are very different applications. I myself have a background in computer science, etc. and I can't help thinking that R is by statisticians for statisticians whereas MATLAB is by programmers for programmers.

R makes it very easy to visualize and compute all sorts of statistical stuff but I wouldn't use it to implement anything signal processing related if it was up to me.

To sum up, if you want to do statistics, use R. If you want to program, use MATLAB or some programming language.

MySQL limit from descending order

Let's say we have a table with a column time and you want the last 5 entries, but you want them returned to you in asc order, not desc, this is how you do it:

select * from ( select * from `table` order by `time` desc limit 5 ) t order by `time` asc

Android Fastboot devices not returning device

If you got nothing when inputted fastboot devices, it meaned you devices fail to enter fastboot model. Make sure that you enter fastboot model via press these three button simultaneously, power key, volume key(both '+' and '-'). Then you can see you devices via fastboot devices and continue to flash your devices.

note:I entered fastboot model only pressed 'power key' and '-' key before, and present the same problem.

warning: assignment makes integer from pointer without a cast

What Jeremiah said, plus the compiler issues the warning because the production:

*src ="anotherstring";

says: take the address of "anotherstring" -- "anotherstring" IS a char pointer -- and store that pointer indirect through src (*src = ... ) into the first char of the string "abcdef..." The warning might be baffling because there is nowhere in your code any mention of any integer: the warning seems nonsensical. But, out of sight behind the curtain, is the rule that "int" and "char" are synonymous in terms of storage: both occupy the same number of bits. The compiler doesn't differentiate when it issues the warning that you are storing into an integer. Which, BTW, is perfectly OK and legal but probably not exactly what you want in this code.

-- pete

Updating .class file in jar

Editing properties/my_app.properties file inside jar:

"zip -u /var/opt/my-jar-with-dependencies.jar properties/my_app.properties". Basically "zip -u <source> <dest>", where dest is relative to the jar extract folder.

How can I nullify css property?

I had an issue that even when I did overwrite "height" to "unset" or "initial", it behaved differently from when I removed the previous setting.

It turned out I needed to remove the min-height property too!

height: unset;
min-height: none

Edit: I tested on IE 7 and it doesn't recognize "unset", so "auto" works better".

What does it mean when Statement.executeUpdate() returns -1?

This doesn't explain why it should be like that, but it explains why it could happen. The following byte-code sets -1 to the internal updateCount flag in the SQLServerStatement constructor:

// Method descriptor #401 (Lcom/microsoft/sqlserver/jdbc/SQLServerConnection;II)V
// Stack: 5, Locals: 8
SQLServerStatement(
  com.microsoft.sqlserver.jdbc.SQLServerConnection arg0, int arg1, int arg2) 
throws com.microsoft.sqlserver.jdbc.SQLServerException;

// [...]

34 aload_0 [this]
35 iconst_m1
36 putfield com.microsoft.sqlserver.jdbc.SQLServerStatement.updateCount:int [27]

Now, I will not analyse all possible control-flows, but I'd just say that this is the internal default initialisation value that somehow leaks out to client code. Note, this is also done in other methods:

// Method descriptor #383 ()V
// Stack: 2, Locals: 1
final void resetForReexecute() 
throws com.microsoft.sqlserver.jdbc.SQLServerException;

// [...]

10 aload_0 [this]
11 iconst_m1
12 putfield com.microsoft.sqlserver.jdbc.SQLServerStatement.updateCount:int [27]

// Method descriptor #383 ()V
// Stack: 3, Locals: 3
final void clearLastResult();
0 aload_0 [this]
1 iconst_m1
2 putfield com.microsoft.sqlserver.jdbc.SQLServerStatement.updateCount:int [27]

In other words, you're probably safe interpreting -1 as being the same as 0. If you rely on this result value, maybe stay on the safe side and do your checks as follows:

// No rows affected
if (stmt.executeUpdate() <= 0) {
}
// Rows affected
else {
}

UPDATE: While reading Mark Rotteveel's answer, I tend to agree with him, assuming that -1 is the JDBC-compliant value for "unknown update counts". Even if this isn't documented on the relevant method's Javadoc, it's documented in the JDBC specs, chapter 13.1.2.3 Returning Unknown or Multiple Results. In this very case, it could be said that an IF .. INSERT .. statement will have an "unknown update count", as this statement isn't SQL-standard compliant anyway.

I want to execute shell commands from Maven's pom.xml

Thanks! Tomer Ben David. it helped me. as I am doing pip install in demo folder as you mentioned npm install

<groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.3.2</version>
            <executions>
              <execution>
                <goals>
                  <goal>exec</goal>
                </goals>
              </execution>
            </executions>
            <configuration>
              <executable>pip</executable>
              <arguments><argument>install</argument></arguments>                            
             <workingDirectory>${project.build.directory}/Demo</workingDirectory>
            </configuration>

Adding items to end of linked list

class Node {
    Object data;
    Node next;
    Node(Object d,Node n) {
        data = d ;
        next = n ;
       }

   public static Node addLast(Node header, Object x) {
       // save the reference to the header so we can return it.
       Node ret = header;

       // check base case, header is null.
       if (header == null) {
           return new Node(x, null);
       }

       // loop until we find the end of the list
       while ((header.next != null)) {
           header = header.next;
       }

       // set the new node to the Object x, next will be null.
       header.next = new Node(x, null);
       return ret;
   }
}

Load content of a div on another page

You just need to add a jquery selector after the url.

See: http://api.jquery.com/load/

Example straight from the API:

$('#result').load('ajax/test.html #container');

So what that does is it loads the #container element from the specified url.

How to compile LEX/YACC files on Windows?

I was having the same problem, it has a very simple solution.
Steps for executing the 'Lex' program:

  1. Tools->'Lex File Compiler'
  2. Tools->'Lex Build'
  3. Tools->'Open CMD'
  4. Then in command prompt type 'name_of_file.exe' example->'1.exe'
  5. Then entering the whole input press Ctrl + Z and press Enter.

Example

Directory.GetFiles: how to get only filename, not full path?

Have a look at using FileInfo.Name Property

something like

string[] files = Directory.GetFiles(dir); 

for (int iFile = 0; iFile < files.Length; iFile++)
    string fn = new FileInfo(files[iFile]).Name;

Also have a look at using DirectoryInfo Class and FileInfo Class

How do I set the figure title and axes labels font size in Matplotlib?

7 (best solution)

 from numpy import*
 import matplotlib.pyplot as plt
 X = linspace(-pi, pi, 1000)

class Crtaj:

    def nacrtaj(self,x,y):
         self.x=x
         self.y=y
         return plt.plot (x,y,"om")

def oznaci(self):
    return plt.xlabel("x-os"), plt.ylabel("y-os"), plt.grid(b=True)

6 (slightly worse solution)

from numpy import*
M = array([[3,2,3],[1,2,6]])
class AriSred(object):
    def __init__(self,m):
    self.m=m
    
def srednja(self):
    redovi = len(M)
    stupci = len (M[0])
    lista=[]
    a=0
    suma=0
    while a<stupci:
        for i in range (0,redovi):
            suma=suma+ M[i,a]
        lista.append(suma)
        a=a+1
        suma=0
    b=array(lista) 
    b=b/redovi
    return b



OBJ = AriSred(M)
sr = OBJ.srednja()

how to count the spaces in a java string?

A solution using java.util.regex.Pattern / java.util.regex.Matcher

String test = "foo bar baz ";
Pattern pattern = Pattern.compile(" ");
Matcher matcher = pattern.matcher(test);
int count = 0;
while (matcher.find()) {
    count++;
}
System.out.println(count);

Check if two unordered lists are equal

If elements are always nearly sorted as in your example then builtin .sort() (timsort) should be fast:

>>> a = [1,1,2]
>>> b = [1,2,2]
>>> a.sort()
>>> b.sort()
>>> a == b
False

If you don't want to sort inplace you could use sorted().

In practice it might always be faster then collections.Counter() (despite asymptotically O(n) time being better then O(n*log(n)) for .sort()). Measure it; If it is important.

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

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

You can create a Unicode string multiple ways:

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

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

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

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

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

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

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

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

but not on Python 3:

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

'int' object has no attribute '__getitem__'

I had a similar issue recently while working on recursion and nested lists. I declared:

print(r_sum([1,2,3[1,2,3],]))

instead of

print(r_sum([1,2,3,[1,2,3],]))

Note the comma after the number 3

How can I simulate an anchor click via jquery?

JQuery('#left').triggerHandler('click'); works fine in Firefox and IE7. I haven't tested it on other browsers.

If want to trigger automatic user clicks do the following:

window.setInterval(function() 
    {
        $('#left').triggerHandler('click');
    }, 1000);

How to find out when a particular table was created in Oracle?

You copy and paste the following code. It will display all the tables with Name and Created Date

SELECT object_name,created FROM user_objects
WHERE object_name LIKE  '%table_name%'
AND object_type = 'TABLE'; 

Note: Replace '%table_name%' with the table name you are looking for.

Break a previous commit into multiple commits

I think that the best way i use git rebase -i. I created a video to show the steps to split a commit: https://www.youtube.com/watch?v=3EzOz7e1ADI

Dynamically fill in form values with jQuery

Automatically fill all form fields from an array

http://jsfiddle.net/brynner/wf0rk7tz/2/

JS

function fill(a){
    for(var k in a){
        $('[name="'+k+'"]').val(a[k]);
    }
}

array_example = {"God":"Jesus","Holy":"Spirit"};

fill(array_example);

HTML

<form>
<input name="God">
<input name="Holy">
</form>

How to check if an element of a list is a list (in Python)?

Use isinstance:

if isinstance(e, list):

If you want to check that an object is a list or a tuple, pass several classes to isinstance:

if isinstance(e, (list, tuple)):

How to access full source of old commit in BitBucket?

  1. The easiest way is to click on that commit and add a tag to that commit. I have included the tag 'last_commit' with this commit

  2. Than go to downloads in the left corner of the side nav in bit bucket. Click on download in the left side

  3. Now click on tags in the nav bar and download the zip from the UI. Find your tag and download the zip

How to track down a "double free or corruption" error

You can use gdb, but I would first try Valgrind. See the quick start guide.

Briefly, Valgrind instruments your program so it can detect several kinds of errors in using dynamically allocated memory, such as double frees and writes past the end of allocated blocks of memory (which can corrupt the heap). It detects and reports the errors as soon as they occur, thus pointing you directly to the cause of the problem.

Running powershell script within python script, how to make python print the powershell output while it is running

  1. Make sure you can run powershell scripts (it is disabled by default). Likely you have already done this. http://technet.microsoft.com/en-us/library/ee176949.aspx

    Set-ExecutionPolicy RemoteSigned
    
  2. Run this python script on your powershell script helloworld.py:

    # -*- coding: iso-8859-1 -*-
    import subprocess, sys
    
    p = subprocess.Popen(["powershell.exe", 
                  "C:\\Users\\USER\\Desktop\\helloworld.ps1"], 
                  stdout=sys.stdout)
    p.communicate()
    

This code is based on python3.4 (or any 3.x series interpreter), though it should work on python2.x series as well.

C:\Users\MacEwin\Desktop>python helloworld.py
Hello World

How to change the buttons text using javascript

I know this question has been answered but I also see there is another way missing which I would like to cover it.There are multiple ways to achieve this.

1- innerHTML

document.getElementById("ShowButton").innerHTML = 'Show Filter';

You can insert HTML into this. But the disadvantage of this method is, it has cross site security attacks. So for adding text, its better to avoid this for security reasons.

2- innerText

document.getElementById("ShowButton").innerText = 'Show Filter';

This will also achieve the result but its heavy under the hood as it requires some layout system information, due to which the performance decreases. Unlike innerHTML, you cannot insert the HTML tags with this. Check Performance Here

3- textContent

document.getElementById("ShowButton").textContent = 'Show Filter';

This will also achieve the same result but it doesn't have security issues like innerHTML as it doesn't parse HTML like innerText. Besides, it is also light due to which performance increases.

So if a text has to be added like above, then its better to use textContent.

How to fast get Hardware-ID in C#?

I got here looking for the same thing and I found another solution. If you guys are interested I share this class:

using System;
using System.Management;
using System.Security.Cryptography;
using System.Security;
using System.Collections;
using System.Text;
namespace Security
{
    /// <summary>
    /// Generates a 16 byte Unique Identification code of a computer
    /// Example: 4876-8DB5-EE85-69D3-FE52-8CF7-395D-2EA9
    /// </summary>
    public class FingerPrint  
    {
        private static string fingerPrint = string.Empty;
        public static string Value()
        {
            if (string.IsNullOrEmpty(fingerPrint))
            {
                fingerPrint = GetHash("CPU >> " + cpuId() + "\nBIOS >> " + 
            biosId() + "\nBASE >> " + baseId() +
                            //"\nDISK >> "+ diskId() + "\nVIDEO >> " + 
            videoId() +"\nMAC >> "+ macId()
                                     );
            }
            return fingerPrint;
        }
        private static string GetHash(string s)
        {
            MD5 sec = new MD5CryptoServiceProvider();
            ASCIIEncoding enc = new ASCIIEncoding();
            byte[] bt = enc.GetBytes(s);
            return GetHexString(sec.ComputeHash(bt));
        }
        private static string GetHexString(byte[] bt)
        {
            string s = string.Empty;
            for (int i = 0; i < bt.Length; i++)
            {
                byte b = bt[i];
                int n, n1, n2;
                n = (int)b;
                n1 = n & 15;
                n2 = (n >> 4) & 15;
                if (n2 > 9)
                    s += ((char)(n2 - 10 + (int)'A')).ToString();
                else
                    s += n2.ToString();
                if (n1 > 9)
                    s += ((char)(n1 - 10 + (int)'A')).ToString();
                else
                    s += n1.ToString();
                if ((i + 1) != bt.Length && (i + 1) % 2 == 0) s += "-";
            }
            return s;
        }
        #region Original Device ID Getting Code
        //Return a hardware identifier
        private static string identifier
        (string wmiClass, string wmiProperty, string wmiMustBeTrue)
        {
            string result = "";
            System.Management.ManagementClass mc = 
        new System.Management.ManagementClass(wmiClass);
            System.Management.ManagementObjectCollection moc = mc.GetInstances();
            foreach (System.Management.ManagementObject mo in moc)
            {
                if (mo[wmiMustBeTrue].ToString() == "True")
                {
                    //Only get the first one
                    if (result == "")
                    {
                        try
                        {
                            result = mo[wmiProperty].ToString();
                            break;
                        }
                        catch
                        {
                        }
                    }
                }
            }
            return result;
        }
        //Return a hardware identifier
        private static string identifier(string wmiClass, string wmiProperty)
        {
            string result = "";
            System.Management.ManagementClass mc = 
        new System.Management.ManagementClass(wmiClass);
            System.Management.ManagementObjectCollection moc = mc.GetInstances();
            foreach (System.Management.ManagementObject mo in moc)
            {
                //Only get the first one
                if (result == "")
                {
                    try
                    {
                        result = mo[wmiProperty].ToString();
                        break;
                    }
                    catch
                    {
                    }
                }
            }
            return result;
        }
        private static string cpuId()
        {
            //Uses first CPU identifier available in order of preference
            //Don't get all identifiers, as it is very time consuming
            string retVal = identifier("Win32_Processor", "UniqueId");
            if (retVal == "") //If no UniqueID, use ProcessorID
            {
                retVal = identifier("Win32_Processor", "ProcessorId");
                if (retVal == "") //If no ProcessorId, use Name
                {
                    retVal = identifier("Win32_Processor", "Name");
                    if (retVal == "") //If no Name, use Manufacturer
                    {
                        retVal = identifier("Win32_Processor", "Manufacturer");
                    }
                    //Add clock speed for extra security
                    retVal += identifier("Win32_Processor", "MaxClockSpeed");
                }
            }
            return retVal;
        }
        //BIOS Identifier
        private static string biosId()
        {
            return identifier("Win32_BIOS", "Manufacturer")
            + identifier("Win32_BIOS", "SMBIOSBIOSVersion")
            + identifier("Win32_BIOS", "IdentificationCode")
            + identifier("Win32_BIOS", "SerialNumber")
            + identifier("Win32_BIOS", "ReleaseDate")
            + identifier("Win32_BIOS", "Version");
        }
        //Main physical hard drive ID
        private static string diskId()
        {
            return identifier("Win32_DiskDrive", "Model")
            + identifier("Win32_DiskDrive", "Manufacturer")
            + identifier("Win32_DiskDrive", "Signature")
            + identifier("Win32_DiskDrive", "TotalHeads");
        }
        //Motherboard ID
        private static string baseId()
        {
            return identifier("Win32_BaseBoard", "Model")
            + identifier("Win32_BaseBoard", "Manufacturer")
            + identifier("Win32_BaseBoard", "Name")
            + identifier("Win32_BaseBoard", "SerialNumber");
        }
        //Primary video controller ID
        private static string videoId()
        {
            return identifier("Win32_VideoController", "DriverVersion")
            + identifier("Win32_VideoController", "Name");
        }
        //First enabled network card ID
        private static string macId()
        {
            return identifier("Win32_NetworkAdapterConfiguration", 
                "MACAddress", "IPEnabled");
        }
        #endregion
    }
}

I won't take any credit for this because I found it here It worked faster than I expected for me. Without the graphic card, mac and drive id's I got the unique ID in about 2-3 seconds. With those above included I got it in about 4-5 seconds.

Note: Add reference to System.Management.

How to replace multiple white spaces with one white space

You can try this:

    /// <summary>
    /// Remove all extra spaces and tabs between words in the specified string!
    /// </summary>
    /// <param name="str">The specified string.</param>
    public static string RemoveExtraSpaces(string str)
    {
        str = str.Trim();
        StringBuilder sb = new StringBuilder();
        bool space = false;
        foreach (char c in str)
        {
            if (char.IsWhiteSpace(c) || c == (char)9) { space = true; }
            else { if (space) { sb.Append(' '); }; sb.Append(c); space = false; };
        }
        return sb.ToString();
    }

Format JavaScript date as yyyy-mm-dd

This code change the order of DD MM YYYY

function convertDate(format, date) {
    let formatArray = format.split('/');
    if (formatArray.length != 3) {
        console.error('Use a valid Date format');
        return;
    }
    function getType(type) { return type == 'DD' ? d.getDate() : type == 'MM' ? d.getMonth() + 1 : type == 'YYYY' && d.getFullYear(); }
    function pad(s) { return (s < 10) ? '0' + s : s; }
    var d = new Date(date);
    return [pad(getType(formatArray[0])), pad(getType(formatArray[1])), getType(formatArray[2])].join('/');
}

How can I remove all my changes in my SVN working directory?

If you are on windows, the following for loop will revert all uncommitted changes made to your workspace:

for /F "tokens=1,*" %%d in ('svn st') do (
  svn revert "%%e"
)

If you want to remove all uncommitted changes and all unversioned objects, it will require 2 loops:

for /F "tokens=1,*" %%d in ('svn st') do (
  svn revert "%%e"
)
for /F "tokens=1,*" %%d in ('svn st') do (
  svn rm --force "%%e"
)

Declare variable in SQLite and use it

SQLite doesn't support native variable syntax, but you can achieve virtually the same using an in-memory temp table.

I've used the below approach for large projects and works like a charm.

/* Create in-memory temp table for variables */
BEGIN;

PRAGMA temp_store = 2;
CREATE TEMP TABLE _Variables(Name TEXT PRIMARY KEY, RealValue REAL, IntegerValue INTEGER, BlobValue BLOB, TextValue TEXT);

/* Declaring a variable */
INSERT INTO _Variables (Name) VALUES ('VariableName');

/* Assigning a variable (pick the right storage class) */
UPDATE _Variables SET IntegerValue = ... WHERE Name = 'VariableName';

/* Getting variable value (use within expression) */
... (SELECT coalesce(RealValue, IntegerValue, BlobValue, TextValue) FROM _Variables WHERE Name = 'VariableName' LIMIT 1) ...

DROP TABLE _Variables;
END;

How do I implement basic "Long Polling"?

I've got a really simple chat example as part of slosh.

Edit: (since everyone's pasting their code in here)

This is the complete JSON-based multi-user chat using long-polling and slosh. This is a demo of how to do the calls, so please ignore the XSS problems. Nobody should deploy this without sanitizing it first.

Notice that the client always has a connection to the server, and as soon as anyone sends a message, everyone should see it roughly instantly.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- Copyright (c) 2008 Dustin Sallings <[email protected]> -->
<html lang="en">
  <head>
    <title>slosh chat</title>
    <script type="text/javascript"
      src="http://code.jquery.com/jquery-latest.js"></script>
    <link title="Default" rel="stylesheet" media="screen" href="style.css" />
  </head>

  <body>
    <h1>Welcome to Slosh Chat</h1>

    <div id="messages">
      <div>
        <span class="from">First!:</span>
        <span class="msg">Welcome to chat. Please don't hurt each other.</span>
      </div>
    </div>

    <form method="post" action="#">
      <div>Nick: <input id='from' type="text" name="from"/></div>
      <div>Message:</div>
      <div><textarea id='msg' name="msg"></textarea></div>
      <div><input type="submit" value="Say it" id="submit"/></div>
    </form>

    <script type="text/javascript">
      function gotData(json, st) {
        var msgs=$('#messages');
        $.each(json.res, function(idx, p) {
          var from = p.from[0]
          var msg = p.msg[0]
          msgs.append("<div><span class='from'>" + from + ":</span>" +
            " <span class='msg'>" + msg + "</span></div>");
        });
        // The jQuery wrapped msgs above does not work here.
        var msgs=document.getElementById("messages");
        msgs.scrollTop = msgs.scrollHeight;
      }

      function getNewComments() {
        $.getJSON('/topics/chat.json', gotData);
      }

      $(document).ready(function() {
        $(document).ajaxStop(getNewComments);
        $("form").submit(function() {
          $.post('/topics/chat', $('form').serialize());
          return false;
        });
        getNewComments();
      });
    </script>
  </body>
</html>

Convert command line argument to string

I'm not sure if this is 100% portable but the way the OS SHOULD parse the args is to scan through the console command string and insert a nil-term char at the end of each token, and int main(int,char**) doesn't use const char** so we can just iterate through the args starting from the third argument (@note the first arg is the working directory) and scan backward to the nil-term char and turn it into a space rather than start from beginning of the second argument and scanning forward to the nil-term char. Here is the function with test script, and if you do need to un-nil-ify more than one nil-term char then please comment so I can fix it; thanks.

#include <cstdio>
#include <iostream>

using namespace std;

namespace _ {
/* Converts int main(int,char**) arguments back into a string.
@return false if there are no args to convert.
@param arg_count The number of arguments.
@param args      The arguments. */
bool ArgsToString(int args_count, char** args) {
  if (args_count <= 1) return false;
  if (args_count == 2) return true;
  for (int i = 2; i < args_count; ++i) {
    char* cursor = args[i];
    while (*cursor) --cursor;
    *cursor = ' ';
  }
  return true;
}
}  // namespace _

int main(int args_count, char** args) {
  cout << "\n\nTesting ArgsToString...\n";

  if (args_count <= 1) return 1;
  cout << "\nArguments:\n";
  for (int i = 0; i < args_count; ++i) {
    char* arg = args[i];
    printf("\ni:%i\"%s\" 0x%p", i, arg, arg);
  }
  cout << "\n\nContiguous Args:\n";
  char* end = args[args_count - 1];
  while (*end) ++end;
  cout << "\n\nContiguous Args:\n";
  char* cursor = args[0];
  while (cursor != end) {
    char c = *cursor++;
    if (c == 0)
      cout << '`';
    else if (c < ' ')
      cout << '~';
    else
      cout << c;
  }
  cout << "\n\nPrinting argument string...\n";
  _::ArgsToString(args_count, args);
  cout << "\n" << args[1];
  return 0;
}

WPF Application that only has a tray icon

I recently had this same problem. Unfortunately, NotifyIcon is only a Windows.Forms control at the moment, if you want to use it you are going to have to include that part of the framework. I guess that depends how much of a WPF purist you are.

If you want a quick and easy way of getting started check out this WPF NotifyIcon control on the Code Project which does not rely on the WinForms NotifyIcon at all. A more recent version seems to be available on the author's website and as a NuGet package. This seems like the best and cleanest way to me so far.

  • Rich ToolTips rather than text
  • WPF context menus and popups
  • Command support and routed events
  • Flexible data binding
  • Rich balloon messages rather than the default messages provides by the OS

Check it out. It comes with an amazing sample app too, very easy to use, and you can have great looking Windows Live Messenger style WPF popups, tooltips, and context menus. Perfect for displaying an RSS feed, I am using it for a similar purpose.

Passing the argument to CMAKE via command prompt

In the CMakeLists.txt file, create a cache variable, as documented here:

SET(FAB "po" CACHE STRING "Some user-specified option")

Source: http://cmake.org/cmake/help/v2.8.8/cmake.html#command:set

Then, either use the GUI (ccmake or cmake-gui) to set the cache variable, or specify the value of the variable on the cmake command line:

cmake -DFAB:STRING=po

Source: http://cmake.org/cmake/help/v2.8.8/cmake.html#opt:-Dvar:typevalue

Modify your cache variable to a boolean if, in fact, your option is boolean.

PyCharm shows unresolved references error for valid code

None of the above solutions worked for me!
If you are using virtual environment for your project make sure to apply the python.exe file that is inside your virtual environment directory as interpreter for the project (Alt + Ctrl + Shift + S) this solved the issue for me.

How to send json data in POST request using C#

You can do it with HttpWebRequest:

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://yourUrl");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = new JavaScriptSerializer().Serialize(new
            {
                Username = "myusername",
                Password = "pass"
            });
    streamWriter.Write(json);
    streamWriter.Flush();
    streamWriter.Close();
}

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}

Setting background-image using jQuery CSS property

Here is my code:

$('body').css('background-image', 'url("/apo/1.jpg")');

Enjoy, friend

Checking Maven Version

Open command prompt go inside the maven folder and execute mvn -version, it will show you maven vesrion al

Create a batch file to copy and rename file

type C:\temp\test.bat>C:\temp\test.log

How to sleep for five seconds in a batch file/cmd

Two answers:

Firstly, to delay in a batch file, simply without all the obtuse methods people have been proposing:

timeout /t <TimeoutInSeconds> [/nobreak] 

http://technet.microsoft.com/en-us/library/cc754891.aspx

Secondly, worth mentioning that while it may not do exactly what you want, using the inbuilt Windows snipping tool, you can trigger a snip on it without using the mouse. Run the snipping tool, escape out of the current snip but leave the tool running, and hit Control + Print Screen when you want the snip to occur. This shouldn't interfere with whatever it is you're trying to snip.

TensorFlow not found using pip

I have experienced the same error while I tried to install tensorflow in an anaconda package. After struggling a lot, I finally found an easy way to install any package without running into an error. First create an environment in your anaconda administrator using this command

conda create -n packages

Now activate that environment

activate packages 

and try running

pip install tensorflow 

After a successful installation, we need to make this environment accessible to jupyter notebook. For that, you need to install a package called ipykernel using this command

pip install ipykernel

After installing ipykernel enter the following command

python -m ipykernel install --user --name=packages

After running this command, this environment will be added to jupyter notebook and that's it. Just go to your jupyter notebook, click on new notebook, and you can see your environment. Select that environment and try importing tensorflow and in case if you want to install any other packages, just activate the environment and install those packages and use that environment in your jupyter

How to switch activity without animation in Android?

You can also just do this in all the activities that you dont want to transition from:

@Override
public void onPause() {
    super.onPause();
    overridePendingTransition(0, 0);
}

I like this approach because you do not have to mess with the style of your activity.

Best way to represent a fraction in Java?

There are several ways to improve this or any value type:

  • Make your class immutable, including making numerator and denominator final
  • Automatically convert fractions to a canonical form, e.g. 2/4 -> 1/2
  • Implement toString()
  • Implement "public static Fraction valueOf(String s)" to convert from strings to fractions. Implement similar factory methods for converting from int, double, etc.
  • Implement addition, multiplication, etc
  • Add constructor from whole numbers
  • Override equals/hashCode
  • Consider making Fraction an interface with an implementation that switches to BigInteger as necessary
  • Consider sub-classing Number
  • Consider including named constants for common values like 0 and 1
  • Consider making it serializable
  • Test for division by zero
  • Document your API

Basically, take a look at the API for other value classes like Double, Integer and do what they do :)

wkhtmltopdf: cannot connect to X server

Just made it:

1- To download wkhtmltopdf dependencies

# apt-get install wkhtmltopdf

2- Download from source

# wget http://downloads.sourceforge.net/project/wkhtmltopdf/xxx.deb

# dpkg -i xxx.deb

3- Try

# wkhtmltopdf http://google.com google.pdf

Its working fine

It works!

When should I use "this" in a class?

Unless you have overlapping variable names, its really just for clarity when you're reading the code.

set serveroutput on in oracle procedure

Actually, you need to call SET SERVEROUTPUT ON; before the BEGIN call.

Everyone suggested this but offers no advice where to actually place the line:

SET SERVEROUTPUT ON;

BEGIN
    FOR rec in (SELECT * FROM EMPLOYEES) LOOP
        DBMS_OUTPUT.PUT_LINE(rec.EmployeeName);
    ENDLOOP;
END;

Otherwise, you won't see any output.

How to push elements in JSON from javascript array

You can directly access BODY.values:

for (var ln = 0; ln < names.length; ln++) {
  var item1 = {
    "person": {
      "_path": "/people/"+names[ln],
    },
  };

  BODY.values.push(item1);
}

Javascript window.print() in chrome, closing new window or tab instead of cancelling print leaves javascript blocked in parent window

I can confirm that I have the same bug on Windows 7 using Chrome Version 35 but I share my partial solution who is open a new tab on Chrome and showing a dialog.

For other browser when the user click on cancel automatically close the new print window.

//Chrome's versions > 34 is some bug who stop all javascript when is show a prints preview
//http://stackoverflow.com/questions/23071291/javascript-window-print-in-chrome-closing-new-window-or-tab-instead-of-cancel
if(navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
    var popupWin = window.open();
    popupWin.window.focus();
    popupWin.document.write('<!DOCTYPE html><html><head>' +
        '<link rel="stylesheet" type="text/css" href="style.css" />' +
        '</head><body onload="window.print()"><div class="reward-body">' + printContents + '</div></html>');
    popupWin.onbeforeunload = function (event) {
        return 'Please use the cancel button on the left side of the print preview to close this window.\n';
    };
}else {
    var popupWin = window.open('', '_blank', 'width=600,height=600,scrollbars=no,menubar=no,toolbar=no,location=no,status=no,titlebar=no');
    popupWin.document.write('<!DOCTYPE html><html><head>' +
        '<link rel="stylesheet" type="text/css" href="style.css" />' +
        '</head><body onload="window.print()"><div class="reward-body">' + printContents + '</div>' +
        '<script>setTimeout(function(){ window.parent.focus(); window.close() }, 100)</script></html>');
}
popupWin.document.close();

How to call a method in another class in Java?

Instead of using this in your current class setClassRoomName("aClassName"); you have to use classroom.setClassRoomName("aClassName");

You have to add the class' and at a point like

yourClassNameWhereTheMethodIs.theMethodsName();

I know it's a really late answer but if someone starts learning Java and randomly sees this post he knows what to do.

strdup() - what does it do in C?

strdup() does dynamic memory allocation for the character array including the end character '\0' and returns the address of the heap memory:

char *strdup (const char *s)
{
    char *p = malloc (strlen (s) + 1);   // allocate memory
    if (p != NULL)
        strcpy (p,s);                    // copy string
    return p;                            // return the memory
}

So, what it does is give us another string identical to the string given by its argument, without requiring us to allocate memory. But we still need to free it, later.

Connection pooling options with JDBC: DBCP vs C3P0

DBCP is out of date and not production grade. Some time back we conducted an in-house analysis of the two, creating a test fixture which generated load and concurrency against the two to assess their suitability under real life conditions.

DBCP consistently generated exceptions into our test application and struggled to reach levels of performance which C3P0 was more than capable of handling without any exceptions.

C3P0 also robustly handled DB disconnects and transparent reconnects on resume whereas DBCP never recovered connections if the link was taken out from beneath it. Worse still DBCP was returning Connection objects to the application for which the underlying transport had broken.

Since then we have used C3P0 in 4 major heavy-load consumer web apps and have never looked back.

UPDATE: It turns out that after many years of sitting on a shelf, the Apache Commons folk have taken DBCP out of dormancy and it is now, once again, an actively developed project. Thus my original post may be out of date.

That being said, I haven't yet experienced this new upgraded library's performance, nor heard of it being de-facto in any recent app framework, yet.

Is it possible to create a 'link to a folder' in a SharePoint document library?

i couldn't change the permissions on the sharepoint i'm using but got a round it by uploading .url files with the drag and drop multiple files uploader.

Using the normal upload didn't work because they are intepreted by the file open dialog when you try to open them singly so it just tries to open the target not the .url file.

.url files can be made by saving a favourite with internet exploiter.

Is JavaScript's "new" keyword considered harmful?

The rationale behind not using the new keyword, is simple:

By not using it at all, you avoid the pitfall that comes with accidentally omitting it. The construction pattern that YUI uses, is an example of how you can avoid the new keyword altogether"

var foo = function () {
    var pub= { };
    return pub;
}
var bar = foo();

Alternatively you could so this:

function foo() { }
var bar = new foo();

But by doing so you run risk of someone forgetting to use the new keyword, and the this operator being all fubar. AFAIK there is no advantage to doing this (other than you are used to it).

At The End Of The Day: It's about being defensive. Can you use the new statement? Yes. Does it make your code more dangerous? Yes.

If you have ever written C++, it's akin to setting pointers to NULL after you delete them.

How to use log4net in Asp.net core 2.0

Still looking for a solution? I got mine from this link .

All I had to do was add this two lines of code at the top of "public static void Main" method in the "program class".

 var logRepo = LogManager.GetRepository(Assembly.GetEntryAssembly());
 XmlConfigurator.Configure(logRepo, new FileInfo("log4net.config"));

Yes, you have to add:

  1. Microsoft.Extensions.Logging.Log4Net.AspNetCore using NuGet.
  2. A text file with the name of log4net.config and change the property(Copy to Output Directory) of the file to "Copy if Newer" or "Copy always".

You can also configure your asp.net core application in such a way that everything that is logged in the output console will be logged in the appender of your choice. You can also download this example code from github and see how i configured it.

JSF rendered multiple combined conditions

Assuming that "a" and "b" are bean properties

rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"

You may look at JSF EL operators

ORA-01461: can bind a LONG value only for insert into a LONG column-Occurs when querying

This ORA-01461 does not occur only while inserting into a Long column. This error can occur when binding a long string for insert into a VARCHAR2 column and most commonly occurs when there is a multi byte(means single char can take more than one byte space in oracle) character conversion issue.

If the database is UTF-8 then, because of the fact that each character can take up to 3 bytes, conversion of 3 applied to check and so actually limited to use 1333 characters to insert into varchar2(4000).

Another solution would be change the datatype from varchar2(4000) to CLOB.

How do I watch a file for changes?

If you're using windows, create this POLL.CMD file

@echo off
:top
xcopy /m /y %1 %2 | find /v "File(s) copied"
timeout /T 1 > nul
goto :top

then you can type "poll dir1 dir2" and it will copy all the files from dir1 to dir2 and check for updates once per second.

The "find" is optional, just to make the console less noisy.

This is not recursive. Maybe you could make it recursive using /e on the xcopy.

/usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

I encounter this problem when trying to use matlab eng to call m functions from c code. which occurs with command mex -f .. ..

My solution:

strings /usr/lib/i386-<tab>/libstdc++.so.6 | grep GLIBC

I found it includes 3.4.15

so my system has the newest libs.

the problem comes from matlab itself, it calls its own libstdc++.so.6 from {MATLAB}/bin

so, just replace it with the updated system lib.

how to reference a YAML "setting" from elsewhere in the same YAML file?

That your example is invalid is only because you chose a reserved character to start your scalars with. If you replace the * with some other non-reserved character (I tend to use non-ASCII characters for that as they are seldom used as part of some specification), you end up with perfectly legal YAML:

paths:
  root: /path/to/root/
  patha: ?root? + a
  pathb: ?root? + b
  pathc: ?root? + c

This will load into the standard representation for mappings in the language your parser uses and does not magically expand anything.
To do that use a locally default object type as in the following Python program:

# coding: utf-8

from __future__ import print_function

import ruamel.yaml as yaml

class Paths:
    def __init__(self):
        self.d = {}

    def __repr__(self):
        return repr(self.d).replace('ordereddict', 'Paths')

    @staticmethod
    def __yaml_in__(loader, data):
        result = Paths()
        loader.construct_mapping(data, result.d)
        return result

    @staticmethod
    def __yaml_out__(dumper, self):
        return dumper.represent_mapping('!Paths', self.d)

    def __getitem__(self, key):
        res = self.d[key]
        return self.expand(res)

    def expand(self, res):
        try:
            before, rest = res.split(u'?', 1)
            kw, rest = rest.split(u'? +', 1)
            rest = rest.lstrip() # strip any spaces after "+"
            # the lookup will throw the correct keyerror if kw is not found
            # recursive call expand() on the tail if there are multiple
            # parts to replace
            return before + self.d[kw] + self.expand(rest)
        except ValueError:
            return res

yaml_str = """\
paths: !Paths
  root: /path/to/root/
  patha: ?root? + a
  pathb: ?root? + b
  pathc: ?root? + c
"""

loader = yaml.RoundTripLoader
loader.add_constructor('!Paths', Paths.__yaml_in__)

paths = yaml.load(yaml_str, Loader=yaml.RoundTripLoader)['paths']

for k in ['root', 'pathc']:
    print(u'{} -> {}'.format(k, paths[k]))

which will print:

root -> /path/to/root/
pathc -> /path/to/root/c

The expanding is done on the fly and handles nested definitions, but you have to be careful about not invoking infinite recursion.

By specifying the dumper, you can dump the original YAML from the data loaded in, because of the on-the-fly expansion:

dumper = yaml.RoundTripDumper
dumper.add_representer(Paths, Paths.__yaml_out__)
print(yaml.dump(paths, Dumper=dumper, allow_unicode=True))

this will change the mapping key ordering. If that is a problem you have to make self.d a CommentedMap (imported from ruamel.yaml.comments.py)

Ignore .pyc files in git repository

You should add a line with:

*.pyc 

to the .gitignore file in the root folder of your git repository tree right after repository initialization.

As ralphtheninja said, if you forgot to to do it beforehand, if you just add the line to the .gitignore file, all previously committed .pyc files will still be tracked, so you'll need to remove them from the repository.

If you are on a Linux system (or "parents&sons" like a MacOSX), you can quickly do it with just this one line command that you need to execute from the root of the repository:

find . -name "*.pyc" -exec git rm -f "{}" \;

This just means:

starting from the directory i'm currently in, find all files whose name ends with extension .pyc, and pass file name to the command git rm -f

After *.pyc files deletion from git as tracked files, commit this change to the repository, and then you can finally add the *.pyc line to the .gitignore file.

(adapted from http://yuji.wordpress.com/2010/10/29/git-remove-all-pyc/)

sqlalchemy filter multiple columns

There are number of ways to do it:

Using filter() (and operator)

query = meta.Session.query(User).filter(
    User.firstname.like(search_var1),
    User.lastname.like(search_var2)
    )

Using filter_by() (and operator)

query = meta.Session.query(User).filter_by(
    firstname.like(search_var1),
    lastname.like(search_var2)
    )

Chaining filter() or filter_by() (and operator)

query = meta.Session.query(User).\
    filter_by(firstname.like(search_var1)).\
    filter_by(lastname.like(search_var2))

Using or_(), and_(), and not()

from sqlalchemy import and_, or_, not_

query = meta.Session.query(User).filter(
    and_(
        User.firstname.like(search_var1),
        User.lastname.like(search_var2)
    )
)

Difference between break and continue statement

Continue Statment stop the itration and start next ittration Ex:

System.out.println("continue when i is 2:");
    for (int i = 1; i <= 3; i++) {
        if (i == 2) {
            System.out.print("[continue]");
            continue;
        }
        System.out.print("[i:" + i + "]");
    }

and Break Statment stop the loop or Exit from the loop

What's the difference between including files with JSP include directive, JSP include action and using JSP Tag Files?

According to: Java Revisited

  1. Resources included by include directive are loaded during jsp translation time, while resources included by include action are loaded during request time.

  2. Any change on included resources will not be visible in case of include directive until jsp file compiles again. While in case of include action, any change in included resource will be visible in the next request.

  3. Include directive is static import, while include action is dynamic import.

  4. Include directive uses file attribute to specify resources to be included while include action uses page attribute for the same purpose.

What's the difference between compiled and interpreted language?

As other have said, compiled and interpreted are specific to an implementation of a programming language; they are not inherent in the language. For example, there are C interpreters.

However, we can (and in practice we do) classify programming languages based on its most common (sometimes canonical) implementation. For example, we say C is compiled.

First, we must define without ambiguity interpreters and compilers:

An interpreter for language X is a program (or a machine, or just some kind of mechanism in general) that executes any program p written in language X such that it performs the effects and evaluates the results as prescribed by the specification of X.

A compiler from X to Y is a program (or a machine, or just some kind of mechanism in general) that translates any program p from some language X into a semantically equivalent program p' in some language Y in such a way that interpreting p' with an interpreter for Y will yield the same results and have the same effects as interpreting p with an interpreter for X.

Notice that from a programmer point of view, CPUs are machine interpreters for their respective native machine language.

Now, we can do a tentative classification of programming languages into 3 categories depending on its most common implementation:

  • Hard Compiled languages: When the programs are compiled entirely to machine language. The only interpreter used is a CPU. Example: Usually, to run a program in C, the source code is compiled to machine language, which is then executed by a CPU.
  • Interpreted languages: When there is no compilation of any part of the original program to machine language. In other words, no new machine code is generated; only existing machine code is executed. An interpreter other than the CPU must also be used (usually a program).Example: In the canonical implementation of Python, the source code is compiled first to Python bytecode and then that bytecode is executed by CPython, an interpreter program for Python bytecode.
  • Soft Compiled languages: When an interpreter other than the CPU is used but also parts of the original program may be compiled to machine language. This is the case of Java, where the source code is compiled to bytecode first and then, the bytecode may be interpreted by the Java Interpreter and/or further compiled by the JIT compiler.

Sometimes, soft and hard compiled languages are refered to simply compiled, thus C#, Java, C, C++ are said to be compiled.

Within this categorization, JavaScript used to be an interpreted language, but that was many years ago. Nowadays, it is JIT-compiled to native machine language in most major JavaScript implementations so I would say that it falls into soft compiled languages.

How do I connect to a specific Wi-Fi network in Android programmatically?

This is an activity you can subclass to force the connecting to a specific wifi: https://github.com/zoltanersek/android-wifi-activity/blob/master/app/src/main/java/com/zoltanersek/androidwifiactivity/WifiActivity.java

You will need to subclass this activity and implement its methods:

public class SampleActivity extends WifiBaseActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
  }

  @Override
  protected int getSecondsTimeout() {
      return 10;
  }

  @Override
  protected String getWifiSSID() {
      return "WifiNetwork";
  }

  @Override
  protected String getWifiPass() {
      return "123456";
  }
}

No notification sound when sending notification from firebase in android

try this....

  public  void buildPushNotification(Context ctx, String content, int icon, CharSequence text, boolean silent) {
    Intent intent = new Intent(ctx, Activity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 1410, intent, PendingIntent.FLAG_ONE_SHOT);

    Bitmap bm = BitmapFactory.decodeResource(ctx.getResources(), //large drawable);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(ctx)
            .setSmallIcon(icon)
            .setLargeIcon(bm)
            .setContentTitle(content)
            .setContentText(text)
            .setAutoCancel(true)
            .setContentIntent(pendingIntent);

    if(!silent)
       notificationBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

 NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(1410, notificationBuilder.build());
    }

and in onMessageReceived, call it

 @Override
public void onMessageReceived(RemoteMessage remoteMessage) {


    Log.d("Msg", "Message received [" + remoteMessage.getNotification().getBody() + "]");

    buildPushNotification(/*your param*/);
}

or follow KongJing, Is also correct as he says, but you can use a Firebase Console.

Passing additional variables from command line to make

Say you have a makefile like this:

action:
    echo argument is $(argument)

You would then call it make action argument=something

Intercept page exit event

Instead of an annoying confirmation popup, it would be nice to delay leaving just a bit (matter of milliseconds) to manage successfully posting the unsaved data to the server, which I managed for my site using writing dummy text to the console like this:

window.onbeforeunload=function(e){
  // only take action (iterate) if my SCHEDULED_REQUEST object contains data        
  for (var key in SCHEDULED_REQUEST){   
    postRequest(SCHEDULED_REQUEST); // post and empty SCHEDULED_REQUEST object
    for (var i=0;i<1000;i++){
      // do something unnoticable but time consuming like writing a lot to console
      console.log('buying some time to finish saving data'); 
    };
    break;
  };
}; // no return string --> user will leave as normal but data is send to server

Edit: See also Synchronous_AJAX and how to do that with jquery

Unexpected token < in first line of HTML

Well... I flipped the internet upside down three times but did not find anything that might help me because it was a Drupal project rather than other scenarios people described.

My problem was that someone in the project added a js which his address was: <script src="http://base_url/?p4sxbt"></script> and it was attached in this way:

drupal_add_js('',
    array('scope' => 'footer', 'weight' => 5)
  );

Hope this will help someone in the future.

Run C++ in command prompt - Windows

  1. Download MinGW form : https://sourceforge.net/projects/mingw-w64/
  2. use notepad++ to write the C++ source code.
  3. using command line change the directory/folder where the source code is saved(using notepad++)
  4. compile: g++ file_name.cpp -o file_name.exe
  5. run the executable: file_name.exe

Permanently adding a file path to sys.path in Python

There are a few ways. One of the simplest is to create a my-paths.pth file (as described here). This is just a file with the extension .pth that you put into your system site-packages directory. On each line of the file you put one directory name, so you can put a line in there with /path/to/the/ and it will add that directory to the path.

You could also use the PYTHONPATH environment variable, which is like the system PATH variable but contains directories that will be added to sys.path. See the documentation.

Note that no matter what you do, sys.path contains directories not files. You can't "add a file to sys.path". You always add its directory and then you can import the file.

How do I kill a process using Vb.NET or C#?

Something like this will work:

foreach ( Process process in Process.GetProcessesByName( "winword" ) )
{
    process.Kill();
    process.WaitForExit();
}

Hashcode and Equals for Hashset

according jdk source code from javasourcecode.org, HashSet use HashMap as its inside implementation, the code about put method of HashSet is below :

public V put(K key, V value) {
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key.hashCode());
        int i = indexFor(hash, table.length);
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }

        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }

The rule is firstly check the hash, then check the reference and then call equals method of the object will be putted in.

Pro JavaScript programmer interview questions (with answers)

Ask them how they ensure their pages continue to be usable when the user has JavaScript turned off or JavaScript isn't available.

There's no One True Answer, but you're fishing for an answer talking about some strategies for Progressive Enhancement.

Progressive Enhancement consists of the following core principles:

  • basic content should be accessible to all browsers
  • basic functionality should be accessible to all browsers
  • sparse, semantic markup contains all content
  • enhanced layout is provided by externally linked CSS
  • enhanced behavior is provided by [[Unobtrusive JavaScript|unobtrusive]], externally linked JavaScript
  • end user browser preferences are respected

Access an arbitrary element in a dictionary in Python

For both Python 2 and 3:

import six

six.next(six.itervalues(d))

Closure in Java 7

Here is Neal Gafter's blog one of the pioneers introducing closures in Java. His post on closures from January 28, 2007 is named A Definition of Closures On his blog there is lots of information to get you started as well as videos. An here is an excellent Google talk - Advanced Topics In Programming Languages - Closures For Java with Neal Gafter, as well.

Why is a div with "display: table-cell;" not affected by margin?

Table cells don't respect margin, but you could use transparent borders instead:

div {
  display: table-cell;
  border: 5px solid transparent;
}

Note: you can't use percentages here... :(

How to make a 3D scatter plot in Python?

Use the following code it worked for me:

# Create the figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Generate the values
x_vals = X_iso[:, 0:1]
y_vals = X_iso[:, 1:2]
z_vals = X_iso[:, 2:3]

# Plot the values
ax.scatter(x_vals, y_vals, z_vals, c = 'b', marker='o')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')

plt.show()

while X_iso is my 3-D array and for X_vals, Y_vals, Z_vals I copied/used 1 column/axis from that array and assigned to those variables/arrays respectively.

Wait for shell command to complete

Add the following Sub:

Sub SyncShell(ByVal Cmd As String, ByVal WindowStyle As VbAppWinStyle)
VBA.CreateObject("WScript.Shell").Run Cmd, WindowStyle, True
End Sub

If you add a reference to C:\Windows\system32\wshom.ocx you can also use:

Sub SyncShell(ByVal Cmd As String, ByVal WindowStyle As VbAppWinStyle)
Static wsh As New WshShell
wsh.Run Cmd, WindowStyle, True
End Sub

This version should be more efficient.

Jersey Exception : SEVERE: A message body reader for Java class

We also decided to use jersey as a solution. But as we are using org.JSON in most of the cases this dependency is unecessary and we felt not good.

Therefore we used the String representation to get a org.JSON object, instead of

JSONObject output = response.getEntity(JSONObject.class); 

we use it this way now:

JSONObject output = new JSONObject(response.getEntity(String.class)); 

where JSONObject comes from org.JSON and the imports could be changed from:

-import org.codehaus.jettison.json.JSONArray;
-import org.codehaus.jettison.json.JSONException;
-import org.codehaus.jettison.json.JSONObject;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;

How to convert CharSequence to String?

There is a subtle issue here that is a bit of a gotcha.

The toString() method has a base implementation in Object. CharSequence is an interface; and although the toString() method appears as part of that interface, there is nothing at compile-time that will force you to override it and honor the additional constraints that the CharSequence toString() method's javadoc puts on the toString() method; ie that it should return a string containing the characters in the order returned by charAt().

Your IDE won't even help you out by reminding that you that you probably should override toString(). For example, in intellij, this is what you'll see if you create a new CharSequence implementation: http://puu.sh/2w1RJ. Note the absence of toString().

If you rely on toString() on an arbitrary CharSequence, it should work provided the CharSequence implementer did their job properly. But if you want to avoid any uncertainty altogether, you should use a StringBuilder and append(), like so:

final StringBuilder sb = new StringBuilder(charSequence.length());
sb.append(charSequence);
return sb.toString();

How to get time (hour, minute, second) in Swift 3 using NSDate?

Swift 4

    let calendar = Calendar.current
    let time=calendar.dateComponents([.hour,.minute,.second], from: Date())
    print("\(time.hour!):\(time.minute!):\(time.second!)")

How to get a password from a shell script without echoing

This link is help in defining, * How to read password from use without echo-ing it back to terminal * How to replace each character with * -character.

https://www.tutorialkart.com/bash-shell-scripting/bash-read-username-and-password/

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

If you have a look at the source: github/v8, it seems that you try to reserve a very big object.According to my experience it happens if you try to parse a huge JSON object, but when I try to parse your output with JSON and node0.11.13, it just works fine.

You don't need more --stack-size, you need more memory: --max_new_space_size and/or --max_old_space_size.

The only hint I can give you beside that is trying another JSON-parser and/or try to change the input format to JSON line instead of JSON only.

What does -Xmn jvm option stands for

From here:

-Xmn : the size of the heap for the young generation

Young generation represents all the objects which have a short life of time. Young generation objects are in a specific location into the heap, where the garbage collector will pass often. All new objects are created into the young generation region (called "eden"). When an object survive is still "alive" after more than 2-3 gc cleaning, then it will be swap has an "old generation" : they are "survivor".

And a more "official" source from IBM:

-Xmn

Sets the initial and maximum size of the new (nursery) heap to the specified value when using -Xgcpolicy:gencon. Equivalent to setting both -Xmns and -Xmnx. If you set either -Xmns or -Xmnx, you cannot set -Xmn. If you attempt to set -Xmn with either -Xmns or -Xmnx, the VM will not start, returning an error. By default, -Xmn is selected internally according to your system's capability. You can use the -verbose:sizes option to find out the values that the VM is currently using.

querySelectorAll with multiple conditions

According to the documentation, just like with any css selector, you can specify as many conditions as you want, and they are treated as logical 'OR'.

This example returns a list of all div elements within the document with a class of either "note" or "alert":

var matches = document.querySelectorAll("div.note, div.alert");

source: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

Meanwhile to get the 'AND' functionality you can for example simply use a multiattribute selector, as jquery says:

https://api.jquery.com/multiple-attribute-selector/

ex. "input[id][name$='man']" specifies both id and name of the element and both conditions must be met. For classes it's as obvious as ".class1.class2" to require object of 2 classes.

All possible combinations of both are valid, so you can easily get equivalent of more sophisticated 'OR' and 'AND' expressions.

How to print star pattern in JavaScript in a very simple manner?

for(var a=1;a<8;a++){   
    var o="";  
    for(var b=1;b<=a;b++){  
        o +="#";    
    }   
    debug(o);   
}

Try above code.

Output:

--> #
--> ##
--> ###
--> ####
--> #####
--> ######

What is the optimal way to compare dates in Microsoft SQL server?

Converting to a DATE or using an open-ended date range in any case will yield the best performance. FYI, convert to date using an index are the best performers. More testing a different techniques in article: What is the most efficient way to trim time from datetime? Posted by Aaron Bertrand

From that article:

DECLARE @dateVar datetime = '19700204';

-- Quickest when there is an index on t.[DateColumn], 
-- because CONVERT can still use the index.
SELECT t.[DateColumn]
FROM MyTable t
WHERE = CONVERT(DATE, t.[DateColumn]) = CONVERT(DATE, @dateVar);

-- Quicker when there is no index on t.[DateColumn]
DECLARE @dateEnd datetime = DATEADD(DAY, 1, @dateVar);
SELECT t.[DateColumn] 
FROM MyTable t
WHERE t.[DateColumn] >= @dateVar AND 
      t.[DateColumn] < @dateEnd;

Also from that article: using BETWEEN, DATEDIFF or CONVERT(CHAR(8)... are all slower.

R: invalid multibyte string

I had a similarly strange problem with a file from the program e-prime (edat -> SPSS conversion), but then I discovered that there are many additional encodings you can use. this did the trick for me:

tbl <- read.delim("dir/file.txt", fileEncoding="UCS-2LE")

How to open a local disk file with JavaScript?

Because I have no life and I want those 4 reputation points so I can show my love to (upvote answers by) people who are actually good at coding I've shared my adaptation of Paolo Moretti's code. Just use openFile(function to be executed with file contents as first parameter).

_x000D_
_x000D_
function dispFile(contents) {_x000D_
  document.getElementById('contents').innerHTML=contents_x000D_
}_x000D_
function clickElem(elem) {_x000D_
 // Thx user1601638 on Stack Overflow (6/6/2018 - https://stackoverflow.com/questions/13405129/javascript-create-and-save-file )_x000D_
 var eventMouse = document.createEvent("MouseEvents")_x000D_
 eventMouse.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)_x000D_
 elem.dispatchEvent(eventMouse)_x000D_
}_x000D_
function openFile(func) {_x000D_
 readFile = function(e) {_x000D_
  var file = e.target.files[0];_x000D_
  if (!file) {_x000D_
   return;_x000D_
  }_x000D_
  var reader = new FileReader();_x000D_
  reader.onload = function(e) {_x000D_
   var contents = e.target.result;_x000D_
   fileInput.func(contents)_x000D_
   document.body.removeChild(fileInput)_x000D_
  }_x000D_
  reader.readAsText(file)_x000D_
 }_x000D_
 fileInput = document.createElement("input")_x000D_
 fileInput.type='file'_x000D_
 fileInput.style.display='none'_x000D_
 fileInput.onchange=readFile_x000D_
 fileInput.func=func_x000D_
 document.body.appendChild(fileInput)_x000D_
 clickElem(fileInput)_x000D_
}
_x000D_
Click the button then choose a file to see its contents displayed below._x000D_
<button onclick="openFile(dispFile)">Open a file</button>_x000D_
<pre id="contents"></pre>
_x000D_
_x000D_
_x000D_

How to upgrade Angular CLI to the latest version

First time users:

npm install -g @angular/cli

Update/upgrade:

npm install -g @angular/cli@latest

Check:

ng --version

See documentation.

SeekBar and media player in android

To create a 'connection' between SeekBar and MediaPlayer you need first to get your current recording max duration and set it to your seek bar.

mSeekBar.setMax(mFileDuration/1000); // where mFileDuration is mMediaPlayer.getDuration();

After you initialise your MediaPlayer and for example press play button, you should create handler and post runnable so you can update your SeekBar (in the UI thread itself) with the current position of your MediaPlayer like this :

private Handler mHandler = new Handler();
//Make sure you update Seekbar on UI thread
MainActivity.this.runOnUiThread(new Runnable() {

    @Override
    public void run() {
        if(mMediaPlayer != null){
            int mCurrentPosition = mMediaPlayer.getCurrentPosition() / 1000;
            mSeekBar.setProgress(mCurrentPosition);
        }
        mHandler.postDelayed(this, 1000);
    }
});

and update that value every second.

If you need to update the MediaPlayer's position while user drag your SeekBar you should add OnSeekBarChangeListener to your SeekBar and do it there :

        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {                
                if(mMediaPlayer != null && fromUser){
                    mMediaPlayer.seekTo(progress * 1000);
                }
            }
    });

And that should do the trick! : )

EDIT: One thing which I've noticed in your code, don't do :

public MainActivity() {
    mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
    mFileName += "/audiorecordtest.3gp";
}

make all initialisations in your onCreate(); , do not create constructors of your Activity.

iPhone: Setting Navigation Bar Title

If you want to change navbar title (not navbar back button title!) this code will be work.

self.navigationController.topViewController.title = @"info";

Combination of async function + await + setTimeout

Made a util inspired from Dave's answer

Basically passed in a done callback to call when the operation is finished.

// Function to timeout if a request is taking too long
const setAsyncTimeout = (cb, timeout = 0) => new Promise((resolve, reject) => {
  cb(resolve);
  setTimeout(() => reject('Request is taking too long to response'), timeout);
});

This is how I use it:

try {
  await setAsyncTimeout(async done => {
    const requestOne = await someService.post(configs);
    const requestTwo = await someService.get(configs);
    const requestThree = await someService.post(configs);
    done();
  }, 5000); // 5 seconds max for this set of operations
}
catch (err) {
  console.error('[Timeout] Unable to complete the operation.', err);
}

Java Desktop application: SWT vs. Swing

SWT was created as a response to the sluggishness of Swing around the turn of the century. Now that the differences in performance are becoming negligable, I think Swing is a better option for your standard applications. SWT/Eclipse has a nice framework which helps with a lot of boiler plate code.

Checking that a List is not empty in Hamcrest

Create your own custom IsEmpty TypeSafeMatcher:

Even if the generics problems are fixed in 1.3 the great thing about this method is it works on any class that has an isEmpty() method! Not just Collections!

For example it will work on String as well!

/* Matches any class that has an <code>isEmpty()</code> method
 * that returns a <code>boolean</code> */ 
public class IsEmpty<T> extends TypeSafeMatcher<T>
{
    @Factory
    public static <T> Matcher<T> empty()
    {
        return new IsEmpty<T>();
    }

    @Override
    protected boolean matchesSafely(@Nonnull final T item)
    {
        try { return (boolean) item.getClass().getMethod("isEmpty", (Class<?>[]) null).invoke(item); }
        catch (final NoSuchMethodException e) { return false; }
        catch (final InvocationTargetException | IllegalAccessException e) { throw new RuntimeException(e); }
    }

    @Override
    public void describeTo(@Nonnull final Description description) { description.appendText("is empty"); }
}

if statements matching multiple values

In vb.net or C# I would expect that the fastest general approach to compare a variable against any reasonable number of separately-named objects (as opposed to e.g. all the things in a collection) will be to simply compare each object against the comparand much as you have done. It is certainly possible to create an instance of a collection and see if it contains the object, and doing so may be more expressive than comparing the object against all items individually, but unless one uses a construct which the compiler can explicitly recognize, such code will almost certainly be much slower than simply doing the individual comparisons. I wouldn't worry about speed if the code will by its nature run at most a few hundred times per second, but I'd be wary of the code being repurposed to something that's run much more often than originally intended.

An alternative approach, if a variable is something like an enumeration type, is to choose power-of-two enumeration values to permit the use of bitmasks. If the enumeration type has 32 or fewer valid values (e.g. starting Harry=1, Ron=2, Hermione=4, Ginny=8, Neville=16) one could store them in an integer and check for multiple bits at once in a single operation ((if ((thisOne & (Harry | Ron | Neville | Beatrix)) != 0) /* Do something */. This will allow for fast code, but is limited to enumerations with a small number of values.

A somewhat more powerful approach, but one which must be used with care, is to use some bits of the value to indicate attributes of something, while other bits identify the item. For example, bit 30 could indicate that a character is male, bit 29 could indicate friend-of-Harry, etc. while the lower bits distinguish between characters. This approach would allow for adding characters who may or may not be friend-of-Harry, without requiring the code that checks for friend-of-Harry to change. One caveat with doing this is that one must distinguish between enumeration constants that are used to SET an enumeration value, and those used to TEST it. For example, to set a variable to indicate Harry, one might want to set it to 0x60000001, but to see if a variable IS Harry, one should bit-test it with 0x00000001.

One more approach, which may be useful if the total number of possible values is moderate (e.g. 16-16,000 or so) is to have an array of flags associated with each value. One could then code something like "if (((characterAttributes[theCharacter] & chracterAttribute.Male) != 0)". This approach will work best when the number of characters is fairly small. If array is too large, cache misses may slow down the code to the point that testing against a small number of characters individually would be faster.

Displaying splash screen for longer than default seconds

The simplest solution here is to add sleep() to didFinishLaunchingWithOptions method in your AppDelegate class.

Swift 4:

sleep(1)
  • delays the LaunchScreen by 1 second.

If you wanna do something fancier you can also extend the current RunLoop in the same method:

Swift 4:

RunLoop.current.run(until: Date(timeIntervalSinceNow: 1))

How do I pass an object to HttpClient.PostAsync and serialize as a JSON body?

There's now a simpler way with .NET Standard or .NET Core:

var client = new HttpClient();
var response = await client.PostAsync(uri, myRequestObject, new JsonMediaTypeFormatter());

NOTE: In order to use the JsonMediaTypeFormatter class, you will need to install the Microsoft.AspNet.WebApi.Client NuGet package, which can be installed directly, or via another such as Microsoft.AspNetCore.App.

Using this signature of HttpClient.PostAsync, you can pass in any object and the JsonMediaTypeFormatter will automatically take care of serialization etc.

With the response, you can use HttpContent.ReadAsAsync<T> to deserialize the response content to the type that you are expecting:

var responseObject = await response.Content.ReadAsAsync<MyResponseType>();

Multiple distinct pages in one HTML file

It is, in theory, possible using data: scheme URIs and frames, but that is rather a long way from practical.

You can fake it by hiding some content with JS and then revealing it when something is clicked (in the style of tabtastic).

Oracle: how to set user password unexpire?

While applying the new profile to the user,you should also check for resource limits are "turned on" for the database as a whole i.e.RESOURCE_LIMIT = TRUE

Let check the parameter value.
If in Case it is :

SQL> show parameter resource_limit
NAME                                 TYPE        VALUE
------------------------------------ ----------- ---------
resource_limit                       boolean     FALSE
Its mean resource limit is off,we ist have to enable it. 

Use the ALTER SYSTEM statement to turn on resource limits. 

SQL> ALTER SYSTEM SET RESOURCE_LIMIT = TRUE;
System altered.

Angular: How to update queryParams without changing route

I ended up combining urlTree with location.go

const urlTree = this.router.createUrlTree([], {
       relativeTo: this.route,
       queryParams: {
           newParam: myNewParam,
       },
       queryParamsHandling: 'merge',
    });

    this.location.go(urlTree.toString());

Not sure if toString can cause problems, but unfortunately location.go, seems to be string based.

PATH issue with pytest 'ImportError: No module named YadaYadaYada'

We have fixed the issue by adding the following environment variable.

PYTHONPATH=${PYTHONPATH}:${PWD}/src:${PWD}/test

Show Console in Windows Application?

And yet another belated answer. I couldn't get any output to the console created with AllocConsole as per earlier suggestions, so instead I'm starting with Console application. Then, if the console is not needed:

        [DllImport("kernel32.dll")]
        private static extern IntPtr GetConsoleWindow();

        [DllImport("user32.dll")]
        private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        private const int SW_HIDE = 0;
        private const int SW_SHOW = 5;

        [DllImport("user32.dll", SetLastError = true)]
        static extern uint GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);

        public static bool HideConsole()
        {
            var hwnd = GetConsoleWindow();
            GetWindowThreadProcessId(hwnd, out var pid);

            if (pid != Process.GetCurrentProcess().Id) // It's not our console - don't mess with it.
                return false;

            ShowWindow(hwnd, SW_HIDE);

            return true;
        }

How to select only 1 row from oracle sql?

we have 3 choices to get the first row in Oracle DB table.

1) select * from table_name where rownum= 1 is the best way

2) select * from table_name where id = ( select min(id) from table_name)

3)

select * from 
    (select * from table_name order by id)
where rownum = 1

Javascript use variable as object name

Global:

myObject = { value: 0 };
anObjectName = "myObject";
this[anObjectName].value++;

console.log(this[anObjectName]);

Global: v2

var anObjectName = "myObject";
this[anObjectName] = "myvalue"

console.log(myObject)

Local: v1

(function() {
    var scope = this;

    if (scope != arguments.callee) {
        arguments.callee.call(arguments.callee);
        return false;
    }

    scope.myObject = { value: 0 };
    scope.anObjectName = "myObject";
    scope[scope.anObjectName].value++;

    console.log(scope.myObject.value);
})();

Local: v2

(function() {  
    var scope = this;

    scope.myObject = { value: 0 };
    scope.anObjectName = "myObject";
    scope[scope.anObjectName].value++;

    console.log(scope.myObject.value);    
}).call({});

How to add a new schema to sql server 2008?

Here's a trick to easily check if the schema already exists, and then create it, in it's own batch, to avoid the error message of trying to create a schema when it's not the only command in a batch.

IF NOT EXISTS (SELECT schema_name 
    FROM information_schema.schemata 
    WHERE schema_name = 'newSchemaName' )
BEGIN
    EXEC sp_executesql N'CREATE SCHEMA NewSchemaName;';
END

Filter Excel pivot table using VBA

In Excel 2007 onwards, you can use the much simpler code using a more precise reference:

dim pvt as PivotTable
dim pvtField as PivotField

set pvt = ActiveSheet.PivotTables("PivotTable2")
set pvtField = pvt.PivotFields("SavedFamilyCode")

pvtField.PivotFilters.Add xlCaptionEquals, Value1:= "K123223"

Is it ok to scrape data from Google results?

Google disallows automated access in their TOS, so if you accept their terms you would break them.

That said, I know of no lawsuit from Google against a scraper. Even Microsoft scraped Google, they powered their search engine Bing with it. They got caught in 2011 red handed :)

There are two options to scrape Google results:

1) Use their API

UPDATE 2020: Google has reprecated previous APIs (again) and has new prices and new limits. Now (https://developers.google.com/custom-search/v1/overview) you can query up to 10k results per day at 1,500 USD per month, more than that is not permitted and the results are not what they display in normal searches.

  • You can issue around 40 requests per hour You are limited to what they give you, it's not really useful if you want to track ranking positions or what a real user would see. That's something you are not allowed to gather.

  • If you want a higher amount of API requests you need to pay.

  • 60 requests per hour cost 2000 USD per year, more queries require a custom deal.

2) Scrape the normal result pages

  • Here comes the tricky part. It is possible to scrape the normal result pages. Google does not allow it.
  • If you scrape at a rate higher than 8 (updated from 15) keyword requests per hour you risk detection, higher than 10/h (updated from 20) will get you blocked from my experience.
  • By using multiple IPs you can up the rate, so with 100 IP addresses you can scrape up to 1000 requests per hour. (24k a day) (updated)
  • There is an open source search engine scraper written in PHP at http://scraping.compunect.com It allows to reliable scrape Google, parses the results properly and manages IP addresses, delays, etc. So if you can use PHP it's a nice kickstart, otherwise the code will still be useful to learn how it is done.

3) Alternatively use a scraping service (updated)

  • Recently a customer of mine had a huge search engine scraping requirement but it was not 'ongoing', it's more like one huge refresh per month.
    In this case I could not find a self-made solution that's 'economic'.
    I used the service at http://scraping.services instead. They also provide open source code and so far it's running well (several thousand resultpages per hour during the refreshes)
  • The downside is that such a service means that your solution is "bound" to one professional supplier, the upside is that it was a lot cheaper than the other options I evaluated (and faster in our case)
  • One option to reduce the dependency on one company is to make two approaches at the same time. Using the scraping service as primary source of data and falling back to a proxy based solution like described at 2) when required.

How to force Docker for a clean build of an image

There's a --no-cache option:

docker build --no-cache -t u12_core -f u12_core .

In older versions of Docker you needed to pass --no-cache=true, but this is no longer the case.

surface plots in matplotlib

I just came across this same problem. I have evenly spaced data that is in 3 1-D arrays instead of the 2-D arrays that matplotlib's plot_surface wants. My data happened to be in a pandas.DataFrame so here is the matplotlib.plot_surface example with the modifications to plot 3 1-D arrays.

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np

X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
    linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)

ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

fig.colorbar(surf, shrink=0.5, aspect=5)
plt.title('Original Code')

That is the original example. Adding this next bit on creates the same plot from 3 1-D arrays.

# ~~~~ MODIFICATION TO EXAMPLE BEGINS HERE ~~~~ #
import pandas as pd
from scipy.interpolate import griddata
# create 1D-arrays from the 2D-arrays
x = X.reshape(1600)
y = Y.reshape(1600)
z = Z.reshape(1600)
xyz = {'x': x, 'y': y, 'z': z}

# put the data into a pandas DataFrame (this is what my data looks like)
df = pd.DataFrame(xyz, index=range(len(xyz['x']))) 

# re-create the 2D-arrays
x1 = np.linspace(df['x'].min(), df['x'].max(), len(df['x'].unique()))
y1 = np.linspace(df['y'].min(), df['y'].max(), len(df['y'].unique()))
x2, y2 = np.meshgrid(x1, y1)
z2 = griddata((df['x'], df['y']), df['z'], (x2, y2), method='cubic')

fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(x2, y2, z2, rstride=1, cstride=1, cmap=cm.coolwarm,
    linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)

ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

fig.colorbar(surf, shrink=0.5, aspect=5)
plt.title('Meshgrid Created from 3 1D Arrays')
# ~~~~ MODIFICATION TO EXAMPLE ENDS HERE ~~~~ #

plt.show()

Here are the resulting figures:

enter image description here enter image description here

How to count TRUE values in a logical vector

I've been doing something similar a few weeks ago. Here's a possible solution, it's written from scratch, so it's kind of beta-release or something like that. I'll try to improve it by removing loops from code...

The main idea is to write a function that will take 2 (or 3) arguments. First one is a data.frame which holds the data gathered from questionnaire, and the second one is a numeric vector with correct answers (this is only applicable for single choice questionnaire). Alternatively, you can add third argument that will return numeric vector with final score, or data.frame with embedded score.

fscore <- function(x, sol, output = 'numeric') {
    if (ncol(x) != length(sol)) {
        stop('Number of items differs from length of correct answers!')
    } else {
        inc <- matrix(ncol=ncol(x), nrow=nrow(x))
        for (i in 1:ncol(x)) {
            inc[,i] <- x[,i] == sol[i]
        }
        if (output == 'numeric') {
            res <- rowSums(inc)
        } else if (output == 'data.frame') {
            res <- data.frame(x, result = rowSums(inc))
        } else {
            stop('Type not supported!')
        }
    }
    return(res)
}

I'll try to do this in a more elegant manner with some *ply function. Notice that I didn't put na.rm argument... Will do that

# create dummy data frame - values from 1 to 5
set.seed(100)
d <- as.data.frame(matrix(round(runif(200,1,5)), 10))
# create solution vector
sol <- round(runif(20, 1, 5))

Now apply a function:

> fscore(d, sol)
 [1] 6 4 2 4 4 3 3 6 2 6

If you pass data.frame argument, it will return modified data.frame. I'll try to fix this one... Hope it helps!

How to set HTTP header to UTF-8 using PHP which is valid in W3C validator?

This is a problem with your web server sending out an HTTP header that does not match the one you define. For instructions on how to make the server send the correct headers, see this page.

Otherwise, you can also use PHP to modify the headers, but this has to be done before outputting any text using this code:

header('Content-Type: text/html; charset=utf-8');

More information on how to send out headers using PHP can be found in the documentation for the header function.

date format yyyy-MM-ddTHH:mm:ssZ

"o" format is different for DateTime vs DateTimeOffset :(

DateTime.UtcNow.ToString("o") -> "2016-03-09T03:30:25.1263499Z"

DateTimeOffset.UtcNow.ToString("o") -> "2016-03-09T03:30:46.7775027+00:00"

My final answer is

DateTimeOffset.UtcDateTime.ToString("o")   //for DateTimeOffset type
DateTime.UtcNow.ToString("o")              //for DateTime type

unix - count of columns in file

You could try

cat FILE | awk '{print NF}'

How do you change Background for a Button MouseOver in WPF?

This worked well for me.

Button Style

<Style x:Key="TransparentStyle" TargetType="{x:Type Button}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Border>
                    <Border.Style>
                        <Style TargetType="{x:Type Border}">
                            <Style.Triggers>
                                <Trigger Property="IsMouseOver" Value="True">
                                    <Setter Property="Background" Value="DarkGoldenrod"/>
                                </Trigger>
                            </Style.Triggers>
                        </Style>
                    </Border.Style>
                    <Grid Background="Transparent">
                        <ContentPresenter></ContentPresenter>
                    </Grid>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Button

<Button Style="{StaticResource TransparentStyle}" VerticalAlignment="Top" HorizontalAlignment="Right" Width="25" Height="25"
        Command="{Binding CloseWindow}">
    <Button.Content >
        <Grid Margin="0 0 0 0">
            <Path Data="M0,7 L10,17 M0,17 L10,7" Stroke="Blue" StrokeThickness="2" HorizontalAlignment="Center" Stretch="None" />
        </Grid>
    </Button.Content>
</Button>

Notes

  • The button displays a little blue cross, much like the one used to close a window.
  • By setting the background of the grid to "Transparent", it adds a hittest, which means that if the mouse is anywhere over the button, then it will work. Omit this tag, and the button will only light up if the mouse is over one of the vector lines in the icon (this is not very usable).

Angular 2: Passing Data to Routes?

It changes in angular 2.1.0

In something.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BlogComponent } from './blog.component';
import { AddComponent } from './add/add.component';
import { EditComponent } from './edit/edit.component';
import { RouterModule } from '@angular/router';
import { MaterialModule } from '@angular/material';
import { FormsModule } from '@angular/forms';
const routes = [
  {
    path: '',
    component: BlogComponent
  },
  {
    path: 'add',
    component: AddComponent
  },
  {
    path: 'edit/:id',
    component: EditComponent,
    data: {
      type: 'edit'
    }
  }

];
@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(routes),
    MaterialModule.forRoot(),
    FormsModule
  ],
  declarations: [BlogComponent, EditComponent, AddComponent]
})
export class BlogModule { }

To get the data or params in edit component

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params, Data } from '@angular/router';
@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
    private router: Router

  ) { }
  ngOnInit() {

    this.route.snapshot.params['id'];
    this.route.snapshot.data['type'];

  }
}

Loop and get key/value pair for JSON array using jQuery

The following should work for a JSON returned string. It will also work for an associative array of data.

for (var key in data)
     alert(key + ' is ' + data[key]);

How to add a touch event to a UIView?

In Swift 4.2 and Xcode 10

Use UITapGestureRecognizer for to add touch event

//Add tap gesture to your view
let tap = UITapGestureRecognizer(target: self, action: #selector(handleGesture))
yourView.addGestureRecognizer(tap)

// GestureRecognizer
@objc func handleGesture(gesture: UITapGestureRecognizer) -> Void {
//Write your code here
}

If you want to use SharedClass

//This is my shared class
import UIKit

class SharedClass: NSObject {

    static let sharedInstance = SharedClass()

    //Tap gesture function
    func addTapGesture(view: UIView, target: Any, action: Selector) {
        let tap = UITapGestureRecognizer(target: target, action: action)
        view.addGestureRecognizer(tap)
    }
} 

I have 3 views in my ViewController called view1, view2 and view3.

override func viewDidLoad() {
    super.viewDidLoad()
    //Add gestures to your views
    SharedClass.sharedInstance.addTapGesture(view: view1, target: self, action: #selector(handleGesture))
    SharedClass.sharedInstance.addTapGesture(view: view2, target: self, action: #selector(handleGesture))
    SharedClass.sharedInstance.addTapGesture(view: view3, target: self, action: #selector(handleGesture2))

}

// GestureRecognizer
@objc func handleGesture(gesture: UITapGestureRecognizer) -> Void {
    print("printed 1&2...")
}
// GestureRecognizer
@objc func handleGesture2(gesture: UITapGestureRecognizer) -> Void {
    print("printed3...")
}

Why am I getting an OPTIONS request instead of a GET request?

According to MDN,

Preflighted requests

Unlike simple requests (discussed above), "preflighted" requests first send an HTTP OPTIONS request header to the resource on the other domain, in order to determine whether the actual request is safe to send. Cross-site requests are preflighted like this since they may have implications to user data. In particular, a request is preflighted if:

  • It uses methods other than GET or POST. Also, if POST is used to send request data with a Content-Type other than application/x-www-form-urlencoded, multipart/form-data, or text/plain, e.g. if the POST request sends an XML payload to the server using application/xml or text/xml, then the request is preflighted.
  • It sets custom headers in the request (e.g. the request uses a header such as X-PINGOTHER)

How do I evenly add space between a label and the input field regardless of length of text?

You can always use the 'pre' tag inside the label, and just enter the blank spaces in it, So you can always add the same or different number of spaces you require

<form>
<label>First Name :<pre>Here just enter number of spaces you want to use(I mean using spacebar to enter blank spaces)</pre>
<input type="text"></label>
<label>Last Name :<pre>Now Enter enter number of spaces to match above number of 
spaces</pre>
<input type="text"></label>
</form>

Hope you like my answer, It's a simple and efficient hack

AngularJS - Attribute directive input value change

Since this must have an input element as a parent, you could just use

<input type="text" ng-model="foo" ng-change="myOnChangeFunction()">

Alternatively, you could use the ngModelController and add a function to $formatters, which executes functions on input change. See http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController

.directive("myDirective", function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attr, ngModel) {
      ngModel.$formatters.push(function(value) {
        // Do stuff here, and return the formatted value.
      });
  };
};

Use PHP to create, edit and delete crontab jobs?

We recently prepared a mini project (PHP>=5.3) to manage the cron files for private and individual tasks. This tool connects and manages the cron files so you can use them, for example per project. Unit Tests available :-)

Sample from command line:

bin/cronman --enable /var/www/myproject/.cronfile --user www-data

Sample from API:

use php\manager\crontab\CrontabManager;

$crontab = new CrontabManager();
$crontab->enableOrUpdate('/tmp/my/crontab.txt');
$crontab->save();

Managing individual tasks from API:

use php\manager\crontab\CrontabManager;

$crontab = new CrontabManager();
$job = $crontab->newJob();
$job->on('* * * * *');
$job->onMinute('20-30')->doJob("echo foo");
$crontab->add($job);
$job->onMinute('35-40')->doJob("echo bar");
$crontab->add($job);
$crontab->save();

github: php-crontab-manager

function is not defined error in Python

Yes, but in what file is pyth_test's definition declared in? Is it also located before it's called?

Edit:

To put it into perspective, create a file called test.py with the following contents:

def pyth_test (x1, x2):
    print x1 + x2

pyth_test(1,2)

Now run the following command:

python test.py

You should see the output you desire. Now if you are in an interactive session, it should go like this:

>>> def pyth_test (x1, x2):
...     print x1 + x2
... 
>>> pyth_test(1,2)
3
>>> 

I hope this explains how the declaration works.


To give you an idea of how the layout works, we'll create a few files. Create a new empty folder to keep things clean with the following:

myfunction.py

def pyth_test (x1, x2):
    print x1 + x2 

program.py

#!/usr/bin/python

# Our function is pulled in here
from myfunction import pyth_test

pyth_test(1,2)

Now if you run:

python program.py

It will print out 3. Now to explain what went wrong, let's modify our program this way:

# Python: Huh? where's pyth_test?
# You say it's down there, but I haven't gotten there yet!
pyth_test(1,2)

# Our function is pulled in here
from myfunction import pyth_test

Now let's see what happens:

$ python program.py 
Traceback (most recent call last):
  File "program.py", line 3, in <module>
    pyth_test(1,2)
NameError: name 'pyth_test' is not defined

As noted, python cannot find the module for the reasons outlined above. For that reason, you should keep your declarations at top.

Now then, if we run the interactive python session:

>>> from myfunction import pyth_test
>>> pyth_test(1,2)
3

The same process applies. Now, package importing isn't all that simple, so I recommend you look into how modules work with Python. I hope this helps and good luck with your learnings!

Why Visual Studio 2015 can't run exe file (ucrtbased.dll)?

rdtsc solution did not work for me.

Firstly, I use Visual Studio 2015 Express, for which installer "modify" query does not propose any "Common Tools for Visual C++ 2015" option you could uncheck.

Secondly, even after 2 uninstall/reinstall (many hours waiting for them to complete...), the problem still remains.

I finally fixed the issue by reinstalling the whole Windows SDK from a standalone installer (independently from Visual C++ 2015 install): https://developer.microsoft.com/fr-fr/windows/downloads/windows-8-1-sdk or https://developer.microsoft.com/fr-fr/windows/downloads/windows-10-sdk

This fixed the issue for me.

Spring Hibernate - Could not obtain transaction-synchronized Session for current thread

My solution was (using Spring) putting the method that fails inside another method that creates and commits the transaction.

To do that I first injected the following:

@Autowired
private PlatformTransactionManager transactionManager;

And finally did this:

public void newMethod() {
    DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
    TransactionStatus transaction = transactionManager.getTransaction(definition);

    oldMethod();

    transactionManager.commit(transaction);
}

how to write procedure to insert data in to the table in phpmyadmin?

Try this-

CREATE PROCEDURE simpleproc (IN name varchar(50),IN user_name varchar(50),IN branch varchar(50))
BEGIN
    insert into student (name,user_name,branch) values (name ,user_name,branch);
END

CSS3 Spin Animation

You haven't specified any keyframes. I made it work here.

div {
    margin: 20px;
    width: 100px; 
    height: 100px;    
    background: #f00;
    -webkit-animation: spin 4s infinite linear;
}

@-webkit-keyframes spin {
    0%  {-webkit-transform: rotate(0deg);}
    100% {-webkit-transform: rotate(360deg);}   
}

You can actually do lots of really cool stuff with this. Here is one I made earlier.

:)

N.B. You can skip having to write out all the prefixes if you use -prefix-free.

How does bitshifting work in Java?

byte x = 51; //00101011
byte y = (byte) (x >> 2); //00001010 aka Base(10) 10

The network adapter could not establish the connection - Oracle 11g

First check your listener is on or off. Go to net manager then Local -> service naming -> orcl. Then change your HOST NAME and put your PC name. Now go to LISTENER and change the HOST and put your PC name.

Can not run Java Applets in Internet Explorer 11 using JRE 7u51

I know Mickey S. solved his issue with Java 8, but Pavel S. was on to something. If you're working locally with an applet, setting your Intranet Zone to Low security and then setting Java security in Control Panel -> Java -> Security setting to Medium from High does solve the problem of running local applets with Java 7u51 (and u55) on Win 7 with IE 11.

(Specifically, I have a little test tool for barcode generation from IDAutomation that is crafted as an applet which wouldn't work on the above config, until I performed the listed steps.)

HTML 5 Favicon - Support?

No, not all browsers support the sizes attribute:

Note that some platforms define specific sizes:

Selectors in Objective-C?

You have to be very careful about the method names. In this case, the method name is just "lowercaseString", not "lowercaseString:" (note the absence of the colon). That's why you're getting NO returned, because NSString objects respond to the lowercaseString message but not the lowercaseString: message.

How do you know when to add a colon? You add a colon to the message name if you would add a colon when calling it, which happens if it takes one argument. If it takes zero arguments (as is the case with lowercaseString), then there is no colon. If it takes more than one argument, you have to add the extra argument names along with their colons, as in compare:options:range:locale:.

You can also look at the documentation and note the presence or absence of a trailing colon.

How to change color of SVG image using CSS (jQuery SVG image replacement)?

If you can include files (PHP include or include via your CMS of choice) in your page, you can add the SVG code and include it into your page. This works the same as pasting the SVG source into the page, but makes the page markup cleaner.

The benefit is that you can target parts of your SVG via CSS for hover -- no javascript required.

http://codepen.io/chriscoyier/pen/evcBu

You just have to use a CSS rule like this:

#pathidorclass:hover { fill: #303 !important; }

Note that the !important bit is necessary to override the fill color.

How do I make case-insensitive queries on Mongodb?

I just solved this problem a few hours ago.

var thename = 'Andrew'
db.collection.find({ $text: { $search: thename } });
  • Case sensitivity and diacritic sensitivity are set to false by default when doing queries this way.

You can even expand upon this by selecting on the fields you need from Andrew's user object by doing it this way:

db.collection.find({ $text: { $search: thename } }).select('age height weight');

Reference: https://docs.mongodb.org/manual/reference/operator/query/text/#text

Query to get only numbers from a string

For the hell of it...

This solution is different to all earlier solutions, viz:

  • There is no need to create a function
  • There is no need to use pattern matching
  • There is no need for a temporary table
  • This solution uses a recursive common table expression (CTE)

But first - note the question does not specify where such strings are stored. In my solution below, I create a CTE as a quick and dirty way to put these strings into some kind of "source table".

Note also - this solution uses a recursive common table expression (CTE) - so don't get confused by the usage of two CTEs here. The first is simply to make the data avaliable to the solution - but it is only the second CTE that is required in order to solve this problem. You can adapt the code to make this second CTE query your existing table, view, etc.

Lastly - my coding is verbose, trying to use column and CTE names that explain what is going on and you might be able to simplify this solution a little. I've added in a few pseudo phone numbers with some (expected and atypical, as the case may be) formatting for the fun of it.

with SOURCE_TABLE as (
    select '003Preliminary Examination Plan' as numberString
    union all select 'Coordination005' as numberString
    union all select 'Balance1000sheet' as numberString
    union all select '1300 456 678' as numberString
    union all select '(012) 995 8322  ' as numberString
    union all select '073263 6122,' as numberString
),
FIRST_CHAR_PROCESSED as (
    select
        len(numberString) as currentStringLength,
        isNull(cast(try_cast(replace(left(numberString, 1),' ','z') as tinyint) as nvarchar),'') as firstCharAsNumeric,
        cast(isNull(cast(try_cast(nullIf(left(numberString, 1),'') as tinyint) as nvarchar),'') as nvarchar(4000)) as newString,
        cast(substring(numberString,2,len(numberString)) as nvarchar) as remainingString
    from SOURCE_TABLE
    union all
    select
        len(remainingString) as currentStringLength,
        cast(try_cast(replace(left(remainingString, 1),' ','z') as tinyint) as nvarchar) as firstCharAsNumeric,
        cast(isNull(newString,'') as nvarchar(3999)) + isNull(cast(try_cast(nullIf(left(remainingString, 1),'') as tinyint) as nvarchar(1)),'') as newString,
        substring(remainingString,2,len(remainingString)) as remainingString
    from FIRST_CHAR_PROCESSED fcp2
    where fcp2.currentStringLength > 1
)
select 
    newString
    ,* -- comment this out when required
from FIRST_CHAR_PROCESSED 
where currentStringLength = 1

So what's going on here?

Basically in our CTE we are selecting the first character and using try_cast (see docs) to cast it to a tinyint (which is a large enough data type for a single-digit numeral). Note that the type-casting rules in SQL Server say that an empty string (or a space, for that matter) will resolve to zero, so the nullif is added to force spaces and empty strings to resolve to null (see discussion) (otherwise our result would include a zero character any time a space is encountered in the source data).

The CTE also returns everything after the first character - and that becomes the input to our recursive call on the CTE; in other words: now let's process the next character.

Lastly, the field newString in the CTE is generated (in the second SELECT) via concatenation. With recursive CTEs the data type must match between the two SELECT statements for any given column - including the column size. Because we know we are adding (at most) a single character, we are casting that character to nvarchar(1) and we are casting the newString (so far) as nvarchar(3999). Concatenated, the result will be nvarchar(4000) - which matches the type casting we carry out in the first SELECT.

If you run this query and exclude the WHERE clause, you'll get a sense of what's going on - but the rows may be in a strange order. (You won't necessarily see all rows relating to a single input value grouped together - but you should still be able to follow).

Hope it's an interesting option that may help a few people wanting a strictly expression-based solution.

How to improve Netbeans performance?

Is it a corporate Windows machine? If so aggressive virus scanners can really slow down modern IDEs. Check your task manager for processes that are using a lot of CPU or disk reads.

How to store directory files listing into an array?

You may be tempted to use (*) but what if a directory contains the * character? It's very difficult to handle special characters in filenames correctly.

You can use ls -ls. However, it fails to handle newline characters.

# Store la -ls as an array
readarray -t files <<< $(ls -ls)
for (( i=1; i<${#files[@]}; i++ ))
{
    # Convert current line to an array
    line=(${files[$i]})
    # Get the filename, joining it together any spaces
    fileName=${line[@]:9}
    echo $fileName
}

If all you want is the file name, then just use ls:

for fileName in $(ls); do
    echo $fileName
done

See this article or this this post for more information about some of the difficulties of dealing with special characters in file names.

How to generate a Dockerfile from an image?

To understand how a docker image was built, use the docker history --no-trunc command.

You can build a docker file from an image, but it will not contain everything you would want to fully understand how the image was generated. Reasonably what you can extract is the MAINTAINER, ENV, EXPOSE, VOLUME, WORKDIR, ENTRYPOINT, CMD, and ONBUILD parts of the dockerfile.

The following script should work for you:

#!/bin/bash
docker history --no-trunc "$1" | \
sed -n -e 's,.*/bin/sh -c #(nop) \(MAINTAINER .*[^ ]\) *0 B,\1,p' | \
head -1
docker inspect --format='{{range $e := .Config.Env}}
ENV {{$e}}
{{end}}{{range $e,$v := .Config.ExposedPorts}}
EXPOSE {{$e}}
{{end}}{{range $e,$v := .Config.Volumes}}
VOLUME {{$e}}
{{end}}{{with .Config.User}}USER {{.}}{{end}}
{{with .Config.WorkingDir}}WORKDIR {{.}}{{end}}
{{with .Config.Entrypoint}}ENTRYPOINT {{json .}}{{end}}
{{with .Config.Cmd}}CMD {{json .}}{{end}}
{{with .Config.OnBuild}}ONBUILD {{json .}}{{end}}' "$1"

I use this as part of a script to rebuild running containers as images: https://github.com/docbill/docker-scripts/blob/master/docker-rebase

The Dockerfile is mainly useful if you want to be able to repackage an image.

The thing to keep in mind, is a docker image can actually just be the tar backup of a real or virtual machine. I have made several docker images this way. Even the build history shows me importing a huge tar file as the first step in creating the image...

number_format() with MySQL

At least as far back as MySQL 5.5 you can use format:

SELECT FORMAT(123456789.123456789,2);
/* produces 123,456,789.12 */

SELECT FORMAT(123456789.123456789,2,'de_DE');
/* 
    produces 123.456.789,12
    note the swapped . and , for the de_DE locale (German-Germany) 
*/

From the MySQL docs: https://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_format

Available locales are listed elsewhere in the docs: https://dev.mysql.com/doc/refman/5.5/en/locale-support.html

pip broke. how to fix DistributionNotFound error?

I was able to resolve this like so:

$ brew update
$ brew doctor
$ brew uninstall python
$ brew install python --build-from-source    # took ~5 mins
$ python --version                           # => Python 2.7.9
$ pip install --upgrade pip

I'm running w/ the following stuff (as of Jan 2, 2015):

OS X Yosemite
Version 10.10.1

$ brew -v
Homebrew 0.9.5

$ python --version
Python 2.7.9

$ ipython --version
2.2.0

$ pip --version
pip 6.0.3 from /usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip-6.0.3-py2.7.egg (python 2.7)

$ which pip
/usr/local/bin/pip

How do I debug error ECONNRESET in Node.js?

I also get ECONNRESET error during my development, the way I solve it is by not using nodemon to start my server, just use "node server.js" to start my server fixed my problem.

It's weird, but it worked for me, now I never see the ECONNRESET error again.

Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve?

Righ Click on info.plist and select open as and then click on Source Code Add this line in last of file before </dict> tag

<key>ITSAppUsesNonExemptEncryption</key>
    <false/>

and save file.

Python truncate a long string

You could use this one-liner:

data = (data[:75] + '..') if len(data) > 75 else data

Embed HTML5 YouTube video without iframe?

Yes. Youtube API is the best resource for this.

There are 3 way to embed a video:

  • IFrame embeds using <iframe> tags
  • IFrame embeds using the IFrame Player API
  • AS3 (and AS2*) object embeds DEPRECATED

I think you are looking for the second one of them:

IFrame embeds using the IFrame Player API

The HTML and JavaScript code below shows a simple example that inserts a YouTube player into the page element that has an id value of ytplayer. The onYouTubePlayerAPIReady() function specified here is called automatically when the IFrame Player API code has loaded. This code does not define any player parameters and also does not define other event handlers.

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

<script>
  // Load the IFrame Player API code asynchronously.
  var tag = document.createElement('script');
  tag.src = "https://www.youtube.com/player_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  // Replace the 'ytplayer' element with an <iframe> and
  // YouTube player after the API code downloads.
  var player;
  function onYouTubePlayerAPIReady() {
    player = new YT.Player('ytplayer', {
      height: '390',
      width: '640',
      videoId: 'M7lc1UVf-VE'
    });
  }
</script>

Here are some instructions where you may take a look when starting using the API.


An embed example without using iframe is to use <object> tag:

<object width="640" height="360">
    <param name="movie" value="http://www.youtube.com/embed/yt-video-id?html5=1&amp;rel=0&amp;hl=en_US&amp;version=3"/
    <param name="allowFullScreen" value="true"/>
    <param name="allowscriptaccess" value="always"/>
    <embed width="640" height="360" src="http://www.youtube.com/embed/yt-video-id?html5=1&amp;rel=0&amp;hl=en_US&amp;version=3" class="youtube-player" type="text/html" allowscriptaccess="always" allowfullscreen="true"/>
</object>

(replace yt-video-id with your video id)

JSFIDDLE

Can a normal Class implement multiple interfaces?

It is true that a java class can implement multiple interfaces at the same time, but there is a catch here. If in a class, you are trying to implement two java interfaces, which contains methods with same signature but diffrent return type, in that case you will get compilation error.

interface One
{
    int m1();
}
interface Two
{
    float m1();
}
public class MyClass implements One, Two{
    int m1() {}
    float m1() {}
    public static void main(String... args) {

    }
}

output :

prog.java:14: error: method m1() is already defined in class MyClass
    public float m1() {}
                 ^
prog.java:11: error: MyClass is not abstract and does not override abstract method m1() in Two
public class MyClass implements One, Two{
       ^
prog.java:13: error: m1() in MyClass cannot implement m1() in Two
    public int m1() {}
               ^
  return type int is not compatible with float
3 errors

Python Function to test ping

Here is a simplified function that returns a boolean and has no output pushed to stdout:

import subprocess, platform
def pingOk(sHost):
    try:
        output = subprocess.check_output("ping -{} 1 {}".format('n' if platform.system().lower()=="windows" else 'c', sHost), shell=True)

    except Exception, e:
        return False

    return True

Solution to INSTALL_FAILED_INSUFFICIENT_STORAGE error on Android

The solution is simple.

Open up the AVD Manager. Edit your AVD.

Down in the hardware section, there are some properties listed with "New..." and "Delete" to the right of it.

Press New. Select Data Partition size. Set to "512MB" (the MB is required). And you're done. if you still get issues, increase your system and cache partitions too using the same method.

It's all documented right here: http://developer.android.com/guide/developing/devices/managing-avds.html

Visual Studio keyboard shortcut to automatically add the needed 'using' statement

I can highly recommend checking out the Visual Studio plugin ReSharper. It has a QuickFix feature that does the same (and a lot more).

But ReSharper doesn't require the cursor to be located on the actual code that requires a new namespace. Say, you copy/paste some code into the source file, and just a few clicks of Alt + Enter, and all the required usings are included.

Oh, and it also makes sure that the required assembly reference is added to your project. Say for example, you create a new project containing NUnit unit tests. The first class you write, you add the [TestFixture] attribute. If you already have one project in your solution that references the NUnit DLL file, then ReSharper is able to see that the TestFixtureAttribute comes from that DLL file, so it will automatically add that assembly reference to your new project.

And it also adds required namespaces for extension methods. At least the ReSharper version 5 beta does. I'm pretty sure that Visual Studio's built-in resolve function doesn't do that.

On the down side, it's a commercial product, so you have to pay for it. But if you work with software commercially, the gained productivity (the plug in does a lot of other cool stuff) outweighs the price tag.

Yes, I'm a fan ;)

How to complete the RUNAS command in one line

The runas command does not allow a password on its command line. This is by design (and also the reason you cannot pipe a password to it as input). Raymond Chen says it nicely:

The RunAs program demands that you type the password manually. Why doesn't it accept a password on the command line?

This was a conscious decision. If it were possible to pass the password on the command line, people would start embedding passwords into batch files and logon scripts, which is laughably insecure.

In other words, the feature is missing to remove the temptation to use the feature insecurely.

How to find distinct rows with field in list using JPA and Spring?

@Query("SELECT DISTINCT name FROM people WHERE name NOT IN (:names)")
List<String> findNonReferencedNames(@Param("names") List<String> names);

Converting file size in bytes to human-readable string

Here's one I wrote:

_x000D_
_x000D_
/**
 * Format bytes as human-readable text.
 * 
 * @param bytes Number of bytes.
 * @param si True to use metric (SI) units, aka powers of 1000. False to use 
 *           binary (IEC), aka powers of 1024.
 * @param dp Number of decimal places to display.
 * 
 * @return Formatted string.
 */
function humanFileSize(bytes, si=false, dp=1) {
  const thresh = si ? 1000 : 1024;

  if (Math.abs(bytes) < thresh) {
    return bytes + ' B';
  }

  const units = si 
    ? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] 
    : ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
  let u = -1;
  const r = 10**dp;

  do {
    bytes /= thresh;
    ++u;
  } while (Math.round(Math.abs(bytes) * r) / r >= thresh && u < units.length - 1);


  return bytes.toFixed(dp) + ' ' + units[u];
}


console.log(humanFileSize(1551859712))  // 1.4 GiB
console.log(humanFileSize(5000, true))  // 5.0 kB
console.log(humanFileSize(5000, false))  // 4.9 KiB
console.log(humanFileSize(-10000000000000000000000000000))  // -8271.8 YiB
console.log(humanFileSize(999949, true))  // 999.9 kB
console.log(humanFileSize(999950, true))  // 1.0 MB
console.log(humanFileSize(999950, true, 2))  // 999.95 kB
console.log(humanFileSize(999500, true, 0))  // 1 MB
_x000D_
_x000D_
_x000D_

'LIKE ('%this%' OR '%that%') and something=else' not working

Do you have something against splitting it up?

...FROM <blah> 
   WHERE 
     (fieldA LIKE '%THIS%' OR fieldA LIKE '%THAT%') 
     AND something = else

How to Create a real one-to-one relationship in SQL Server

I'm pretty sure it is technically impossible in SQL Server to have a True 1 to 1 relationship, as that would mean you would have to insert both records at the same time (otherwise you'd get a constraint error on insert), in both tables, with both tables having a foreign key relationship to each other.

That being said, your database design described with a foreign key is a 1 to 0..1 relationship. There is no constrain possible that would require a record in tableB. You can have a pseudo-relationship with a trigger that creates the record in tableB.

So there are a few pseudo-solutions

First, store all the data in a single table. Then you'll have no issues in EF.

Or Secondly, your entity must be smart enough to not allow an insert unless it has an associated record.

Or thirdly, and most likely, you have a problem you are trying to solve, and you are asking us why your solution doesn't work instead of the actual problem you are trying to solve (an XY Problem).

UPDATE

To explain in REALITY how 1 to 1 relationships don't work, I'll use the analogy of the Chicken or the egg dilemma. I don't intend to solve this dilemma, but if you were to have a constraint that says in order to add a an Egg to the Egg table, the relationship of the Chicken must exist, and the chicken must exist in the table, then you couldn't add an Egg to the Egg table. The opposite is also true. You cannot add a Chicken to the Chicken table without both the relationship to the Egg and the Egg existing in the Egg table. Thus no records can be every made, in a database without breaking one of the rules/constraints.

Database nomenclature of a one-to-one relationship is misleading. All relationships I've seen (there-fore my experience) would be more descriptive as one-to-(zero or one) relationships.

ISO C++ forbids comparison between pointer and integer [-fpermissive]| [c++]

char a[2] defines an array of char's. a is a pointer to the memory at the beginning of the array and using == won't actually compare the contents of a with 'ab' because they aren't actually the same types, 'ab' is integer type. Also 'ab' should be "ab" otherwise you'll have problems here too. To compare arrays of char you'd want to use strcmp.

Something that might be illustrative is looking at the typeid of 'ab':

#include <iostream>
#include <typeinfo>
using namespace std;
int main(){
    int some_int =5;
    std::cout << typeid('ab').name() << std::endl;
    std::cout << typeid(some_int).name() << std::endl;
    return 0;
}

on my system this returns:

i
i

showing that 'ab' is actually evaluated as an int.

If you were to do the same thing with a std::string then you would be dealing with a class and std::string has operator == overloaded and will do a comparison check when called this way.

If you wish to compare the input with the string "ab" in an idiomatic c++ way I suggest you do it like so:

#include <iostream>
#include <string>
using namespace std;
int main(){
    string a;
    cout<<"enter ab ";
    cin>>a;
    if(a=="ab"){
         cout<<"correct";
    }
    return 0;
}

This one is due to:

if(a=='ab') , here, a is const char* type (ie : array of char)

'ab' is a constant value,which isn't evaluated as string (because of single quote) but will be evaluated as integer.

Since char is a primitive type inherited from C, no operator == is defined.

the good code should be:

if(strcmp(a,"ab")==0) , then you'll compare a const char* to another const char* using strcmp.

error: expected declaration or statement at end of input in c

You probably have syntax error. You most likely forgot to put a } or ; somewhere above this function.

Eclipse "Server Locations" section disabled and need to change to use Tomcat installation

Ok, sorry for my previous answer, I had never seen that Overview screen before.

Here is how I did it:

  1. Right click on my tomcat server in "Servers" view, select "Properties…"
  2. In the "General" panel, click on the "Switch Location" button
  3. The "Location: [workspace metadata]" bit should have been replaced by something else.
  4. Open (or close and reopen) the Overview screen for the server.

HAProxy redirecting http to https (ssl)

redirect statement is legacy

use http-request redirect instead

acl http      ssl_fc,not
http-request redirect scheme https if http

Reset the database (purge all), then seed a database

You can use rake db:reset when you want to drop the local database and start fresh with data loaded from db/seeds.rb. This is a useful command when you are still figuring out your schema, and often need to add fields to existing models.

Once the reset command is used it will do the following: Drop the database: rake db:drop Load the schema: rake db:schema:load Seed the data: rake db:seed

But if you want to completely drop your database you can use rake db:drop. Dropping the database will also remove any schema conflicts or bad data. If you want to keep the data you have, be sure to back it up before running this command.

This is a detailed article about the most important rake database commands.

How do I UPDATE from a SELECT in SQL Server?

UPDATE TQ
SET TQ.IsProcessed = 1, TQ.TextName = 'bla bla bla'
FROM TableQueue TQ
INNER JOIN TableComment TC ON TC.ID = TQ.TCID
WHERE TQ.IsProcessed = 0

To make sure you are updating what you want, select first

SELECT TQ.IsProcessed, 1 AS NewValue1, TQ.TextName, 'bla bla bla' AS NewValue2
FROM TableQueue TQ
INNER JOIN TableComment TC ON TC.ID = TQ.TCID
WHERE TQ.IsProcessed = 0

ASP.NET Setting width of DataBound column in GridView

add HeaderStyle in your bound field:

    <asp:BoundField HeaderText="UserId"
                DataField="UserId" 
                SortExpression="UserId">

                <HeaderStyle Width="200px" />

</asp:BoundField>

undefined reference to `std::ios_base::Init::Init()'

You can resolve this in several ways:

  • Use g++ in stead of gcc: g++ -g -o MatSim MatSim.cpp
  • Add -lstdc++: gcc -g -o MatSim MatSim.cpp -lstdc++
  • Replace <string.h> by <string>

This is a linker problem, not a compiler issue. The same problem is covered in the question iostream linker error – it explains what is going on.

Preferred way to create a Scala list

Uhmm.. these seem too complex to me. May I propose

def listTestD = (0 to 3).toList

or

def listTestE = for (i <- (0 to 3).toList) yield i

How to upload image in CodeIgniter?

It seems the problem is you send the form request to welcome/do_upload, and call the Welcome::do_upload() method in another one by $this->do_upload().

Hence when you call the $this->do_upload(); within your second method, the $_FILES array would be empty.

And that's why var_dump($data['upload_data']); returns NULL.

If you want to upload the file from welcome/second_method, send the form request to the welcome/second_method where you call $this->do_upload();.

Then change the form helper function (within the View) as follows1:

// Change the 'second_method' to your method name
echo form_open_multipart('welcome/second_method');

File Uploading with CodeIgniter

CodeIgniter has documented the Uploading process very well, by using the File Uploading library.

You could take a look at the sample code in the user guide; And also, in order to get a better understanding of the uploading configs, Check the Config items Explanation section at the end of the manual page.

Also there are couple of articles/samples about the file uploading in CodeIgniter, you might want to consider:

Just as a side-note: Make sure that you've loaded the url and form helper functions before using the CodeIgniter sample code:

// Load the helper files within the Controller
$this->load->helper('form');
$this->load->helper('url');

1. The form must be "multipart" type for file uploading. Hence you should use form_open_multipart() helper function which returns:
<form method="post" action="controller/method" enctype="multipart/form-data" />

C++ undefined reference to defined function

The declaration and definition of insertLike are different

In your header file:

void insertLike(const char sentence[], const int lengthTo, const int length, const char writeTo[]);

In your 'function file':

void insertLike(const char sentence[], const int lengthTo, const int length,char writeTo[]);

C++ allows function overloading, where you can have multiple functions/methods with the same name, as long as they have different arguments. The argument types are part of the function's signature.

In this case, insertLike which takes const char* as its fourth parameter and insertLike which takes char * as its fourth parameter are different functions.

Secure hash and salt for PHP passwords

SHA1 and a salt should suffice (depending, naturally, on whether you are coding something for Fort Knox or a login system for your shopping list) for the foreseeable future. If SHA1 isn't good enough for you, use SHA256.

The idea of a salt is to throw the hashing results off balance, so to say. It is known, for example, that the MD5-hash of an empty string is d41d8cd98f00b204e9800998ecf8427e. So, if someone with good enough a memory would see that hash and know that it's the hash of an empty string. But if the string is salted (say, with the string "MY_PERSONAL_SALT"), the hash for the 'empty string' (i.e. "MY_PERSONAL_SALT") becomes aeac2612626724592271634fb14d3ea6, hence non-obvious to backtrace. What I'm trying to say, that it's better to use any salt, than not to. Therefore, it's not too much of an importance to know which salt to use.

There are actually websites that do just this - you can feed it a (md5) hash, and it spits out a known plaintext that generates that particular hash. If you would get access to a database that stores plain md5-hashes, it would be trivial for you to enter the hash for the admin to such a service, and log in. But, if the passwords were salted, such a service would become ineffective.

Also, double-hashing is generally regarded as bad method, because it diminishes the result space. All popular hashes are fixed-length. Thus, you can have only a finite values of this fixed length, and the results become less varied. This could be regarded as another form of salting, but I wouldn't recommend it.

Firebase Permission Denied

Go to database, next to title there are 2 options:

Cloud Firestore, Realtime database

Select Realtime database and go to rules

Change rules to true.

Subtract two dates in SQL and get days of the result

EDIT: It seems I was wrong about the performance on the code example. The best performer is whichever snippet runs second in the posted case. This demonstrates what I was trying to explain, and the time differences are not as dramatic:

----------------------------------
--  Monitor time differences
----------------------------------
CREATE CLUSTERED INDEX dtIDX ON #ArbDates (MyDate)
DECLARE @Stopwatch DATETIME 
SET @Stopwatch = GETDATE()
    -- SARGABLE
    SELECT *
    FROM #ArbDates
    WHERE MyDate > DATEADD(DAY, -364, '2010-01-01')


PRINT DATEDIFF(MS, @Stopwatch, GETDATE())
SET @Stopwatch = GETDATE()
    -- NOT SARGABLE
    SELECT *
    FROM #ArbDates
    WHERE DATEDIFF(DAY, MyDate, '2010-01-01') < 365
PRINT DATEDIFF(MS, @Stopwatch, GETDATE())

Excuse me for posting late and my crudely commented example, but I think it important to mention SARG.

SELECT I.Fee
FROM Item I
WHERE  I.DateCreated > DATEADD(DAY, -364, GETDATE())

Although the temp table in the code below has no index, the performance is still enhanced by the fact that a comparison is done between an expression and a value in the table and not an expression that modifies the value in the table and a constant. Hope this is found to be useful.

USE tempdb
GO

IF OBJECT_ID('tempdb.dbo.#ArbDates') IS NOT NULL DROP TABLE #ArbDates
DECLARE @Stopwatch DATETIME 

----------------------------------
--  Build test data: 100000 rows
----------------------------------
;WITH Base10 (n) AS
(
    SELECT 1 UNION ALL  SELECT 1 UNION ALL  SELECT 1 UNION ALL
    SELECT 1 UNION ALL  SELECT 1 UNION ALL  SELECT 1 UNION ALL
    SELECT 1 UNION ALL  SELECT 1 UNION ALL  SELECT 1 UNION ALL
    SELECT 1
)
,Base100000 (n) AS
(
    SELECT 1
    FROM Base10 T1, Base10 T3, Base10 T4, Base10 T5, Base10 T6
)
SELECT MyDate = CAST(RAND(CHECKSUM(NEWID()))*3653.0+36524.0 AS DATETIME) 
INTO #ArbDates 
FROM Base100000

----------------------------------
--  Monitor time differences
----------------------------------
SET @Stopwatch = GETDATE()

    -- NOT SARGABLE
    SELECT *
    FROM #ArbDates
    WHERE DATEDIFF(DAY, MyDate, '2010-01-01') < 365

PRINT DATEDIFF(MS, @Stopwatch, GETDATE())
SET @Stopwatch = GETDATE()

    -- SARGABLE
    SELECT *
    FROM #ArbDates
    WHERE MyDate > DATEADD(DAY, -364, '2010-01-01')

PRINT DATEDIFF(MS, @Stopwatch, GETDATE())

golang why don't we have a set datastructure

Another possibility is to use bit sets, for which there is at least one package or you can use the built-in big package. In this case, basically you need to define a way to convert your object to an index.

<ng-container> vs <template>

The documentation (https://angular.io/guide/template-syntax#!#star-template) gives the following example. Say we have template code like this:

<hero-detail *ngIf="currentHero" [hero]="currentHero"></hero-detail>

Before it will be rendered, it will be "de-sugared". That is, the asterix notation will be transcribed to the notation:

<template [ngIf]="currentHero">
  <hero-detail [hero]="currentHero"></hero-detail>
</template>

If 'currentHero' is truthy this will be rendered as

<hero-detail> [...] </hero-detail>

But what if you want an conditional output like this:

<h1>Title</h1><br>
<p>text</p>

.. and you don't want the output be wrapped in a container.

You could write the de-sugared version directly like so:

<template [ngIf]="showContent">
  <h1>Title</h1>
  <p>text</p><br>
</template>

And this will work fine. However, now we need ngIf to have brackets [] instead of an asterix *, and this is confusing (https://github.com/angular/angular.io/issues/2303)

For that reason a different notation was created, like so:

<ng-container *ngIf="showContent"><br>
  <h1>Title</h1><br>
  <p>text</p><br>
</ng-container>

Both versions will produce the same results (only the h1 and p tag will be rendered). The second one is preferred because you can use *ngIf like always.

What is the difference between rb and r+b modes in file objects

My understanding is that adding r+ opens for both read and write (just like w+, though as pointed out in the comment, will truncate the file). The b just opens it in binary mode, which is supposed to be less aware of things like line separators (at least in C++).

How to go to each directory and execute a command?

for p in [0-9][0-9][0-9];do
    (
        cd $p
        for f in [0-9][0-9][0-9][0-9]*.txt;do
            ls $f; # Your operands
        done
    )
done

How to change color of the back arrow in the new material theme?

Another solution that might work for you is to not declare your toolbar as the app's action bar ( by setActionBar or setSupportActionBar ) and set the back icon in your onActivityCreated using the code mentioned in another answer on this page

final Drawable upArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
upArrow.setColorFilter(getResources().getColor(R.color.grey), PorterDuff.Mode.SRC_ATOP);
toolbar.setNavigationIcon(upArrow);

Now, you will not get the onOptionItemSelected callback when you press the back button. However, you can register for that using setNavigationOnClickListener. This is what i do:

toolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        getActivity().onBackPressed(); //or whatever you used to do on your onOptionItemSelected's android.R.id.home callback
    }
});

I'm not sure if it will work if you work with menu items.

Warp \ bend effect on a UIView?

What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.

I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)

Nexus 7 (2013) and Win 7 64 - cannot install USB driver despite checking many forums and online resources

SkipSoft.net has some great toolkits. I ran into a similar problem with my Galaxy Nexus.... Ran the corresponding toolkit, which configured my system and downloaded the correct drivers. I then went into Windows Hardware manager after connecting the phone... Windows reported the exclamation that it couldn't find the device driver, so I ran update, and gave it the drivers directory the toolkit had created... and everything started working great. Hope this helps :)

Symbolicating iPhone App Crash Reports

I prefer a script that will symbolicate all my crash logs.

Preconditions

Create a folder and put there 4 things:

  1. symbolicatecrash perl script - there are many SO answers that tells it's location

  2. The archive of the build that match the crashes (from Xcode Organizer. simple as Show in Finder and copy) [I don't sure this is necessery]

  3. All the xccrashpoint packages - (from Xcode Organizer. Show in Finder, you may copy all the packages in the directory, or the single xccrashpoint you would like to symbolicate)

  4. Add that short script to the directory:

    #!/bin/sh
    
    echo "cleaning old crashes from directory"
    rm -P *.crash
    rm -P *.xccrashpoint
    rm -r allCrashes
    echo "removed!"
    echo ""
    echo "--- START ---"
    echo ""
    
    mkdir allCrashes
    mkdir symboledCrashes
    find `ls -d *.xccrashpoint` -name "*.crash" -print -exec cp {} allCrashes/ \;
    
    cd allCrashes
    for crash in *.crash; do
        ../symbolicatecrash $crash > ../symboledCrashes/V$crash
    done
    cd ..
    
    echo ""
    echo "--- DONE ---"
    echo ""
    

The Script

When you run the script, you'll get 2 directories.

  1. allCrashes - all the crashes from all the xccrashpoint will be there.

  2. symboledCrashes - the same crashes but now with all the symbols.

  3. you DON'T need to clean the directory from old crashes before running the script. it will clean automatically. good luck!

Text vertical alignment in WPF TextBlock

A Textblock itself can't do vertical alignment

The best way to do this that I've found is to put the textblock inside a border, so the border does the alignment for you.

<Border BorderBrush="{x:Null}" Height="50">
    <TextBlock TextWrapping="Wrap" Text="Some Text" VerticalAlignment="Center"/>
</Border>

Note: This is functionally equivalent to using a grid, it just depends how you want the controls to fit in with the rest of your layout as to which one is more suitable

How to make Scrollable Table with fixed headers using CSS

What you want to do is separate the content of the table from the header of the table. You want only the <th> elements to be scrolled. You can easily define this separation in HTML with the <tbody> and the <thead> elements.
Now the header and the body of the table are still connected to each other, they will still have the same width (and same scroll properties). Now to let them not 'work' as a table anymore you can set the display: block. This way <thead> and <tbody> are separated.

table tbody, table thead
{
    display: block;
}

Now you can set the scroll to the body of the table:

table tbody 
{
   overflow: auto;
   height: 100px;
}

And last, because the <thead> doesn't share the same width as the body anymore, you should set a static width to the header of the table:

th
{
    width: 72px;
}

You should also set a static width for <td>. This solves the issue of the unaligned columns.

td
{
    width: 72px;
}


Note that you are also missing some HTML elements. Every row should be in a <tr> element, that includes the header row:

<tr>
     <th>head1</th>
     <th>head2</th>
     <th>head3</th>
     <th>head4</th>
</tr>

I hope this is what you meant.

jsFiddle

Addendum

If you would like to have more control over the column widths, have them to vary in width between each other, and course keep the header and body columns aligned, you can use the following example:

    table th:nth-child(1), td:nth-child(1) { min-width: 50px;  max-width: 50px; }
    table th:nth-child(2), td:nth-child(2) { min-width: 100px; max-width: 100px; }
    table th:nth-child(3), td:nth-child(3) { min-width: 150px; max-width: 150px; }
    table th:nth-child(4), td:nth-child(4) { min-width: 200px; max-width: 200px; }

How to assign a value to a TensorFlow variable?

First of all you can assign values to variables/constants just by feeding values into them the same way you do it with placeholders. So this is perfectly legal to do:

import tensorflow as tf
x = tf.Variable(0)
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print sess.run(x, feed_dict={x: 3})

Regarding your confusion with the tf.assign() operator. In TF nothing is executed before you run it inside of the session. So you always have to do something like this: op_name = tf.some_function_that_create_op(params) and then inside of the session you run sess.run(op_name). Using assign as an example you will do something like this:

import tensorflow as tf
x = tf.Variable(0)
y = tf.assign(x, 1)
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print sess.run(x)
    print sess.run(y)
    print sess.run(x)

Hive cast string to date dd-MM-yyyy

If I have understood it correctly, you are trying to convert a String representing a given date, to another type.

Note: (As @Samson Scharfrichter has mentioned)

  • the default representation of a date is ISO8601
  • a date is stored in binary (not as a string)

There are a few ways to do it. And you are close to the solution. I would use the CAST (which converts to a DATE_TYPE):

SELECT cast('2018-06-05' as date); 

Result: 2018-06-05 DATE_TYPE

or (depending on your pattern)

select cast(to_date(from_unixtime(unix_timestamp('05-06-2018', 'dd-MM-yyyy'))) as date)

Result: 2018-06-05 DATE_TYPE

And if you decide to convert ISO8601 to a date type:

select cast(to_date(from_unixtime(unix_timestamp(regexp_replace('2018-06-05T08:02:59Z', 'T',' ')))) as date);

Result: 2018-06-05 DATE_TYPE

Hive has its own functions, I have written some examples for the sake of illustration of these date- and cast- functions:

Date and timestamp functions examples:

Convert String/Timestamp/Date to DATE

SELECT cast(date_format('2018-06-05 15:25:42.23','yyyy-MM-dd') as date); -- 2018-06-05 DATE_TYPE
SELECT cast(date_format(current_date(),'yyyy-MM-dd') as date); -- 2018-06-05 DATE_TYPE
SELECT cast(date_format(current_timestamp(),'yyyy-MM-dd') as date);  -- 2018-06-05 DATE_TYPE

Convert String/Timestamp/Date to BIGINT_TYPE

SELECT to_unix_timestamp('2018/06/05 15:25:42.23','yyyy/MM/dd HH:mm:ss'); -- 1528205142 BIGINT_TYPE
SELECT to_unix_timestamp(current_date(),'yyyy/MM/dd HH:mm:ss'); -- 1528205000 BIGINT_TYPE
SELECT to_unix_timestamp(current_timestamp(),'yyyy/MM/dd HH:mm:ss'); -- 1528205142 BIGINT_TYPE

Convert String/Timestamp/Date to STRING

SELECT date_format('2018-06-05 15:25:42.23','yyyy-MM-dd'); -- 2018-06-05 STRING_TYPE
SELECT date_format(current_timestamp(),'yyyy-MM-dd'); -- 2018-06-05 STRING_TYPE
SELECT date_format(current_date(),'yyyy-MM-dd'); -- 2018-06-05 STRING_TYPE

Convert BIGINT unixtime to STRING

SELECT to_date(from_unixtime(unixtime,'yyyy/MM/dd HH:mm:ss')); -- 2018-06-05 STRING_TYPE

Convert String to BIGINT unixtime

SELECT unix_timestamp('2018-06-05 15:25:42.23','yyyy-MM-dd') as TIMESTAMP; -- 1528149600 BIGINT_TYPE

Convert String to TIMESTAMP

SELECT cast(unix_timestamp('2018-06-05 15:25:42.23','yyyy-MM-dd') as TIMESTAMP); -- 1528149600 TIMESTAMP_TYPE

Idempotent (String -> String)

SELECT from_unixtime(to_unix_timestamp('2018/06/05 15:25:42.23','yyyy/MM/dd HH:mm:ss')); -- 2018-06-05 15:25:42 STRING_TYPE

Idempotent (Date -> Date)

SELECT cast(current_date() as date); -- 2018-06-26 DATE_TYPE

Current date / timestamp

SELECT current_date(); -- 2018-06-26 DATE_TYPE
SELECT current_timestamp(); -- 2018-06-26 14:03:38.285 TIMESTAMP_TYPE

How to use OUTPUT parameter in Stored Procedure

The SQL in your SP is wrong. You probably want

Select @code = RecItemCode from Receipt where RecTransaction = @id

In your statement, you are not setting @code, you are trying to use it for the value of RecItemCode. This would explain your NullReferenceException when you try to use the output parameter, because a value is never assigned to it and you're getting a default null.

The other issue is that your SQL statement if rewritten as

Select @code = RecItemCode, RecUsername from Receipt where RecTransaction = @id

It is mixing variable assignment and data retrieval. This highlights a couple of points. If you need the data that is driving @code in addition to other parts of the data, forget the output parameter and just select the data.

Select RecItemCode, RecUsername from Receipt where RecTransaction = @id

If you just need the code, use the first SQL statement I showed you. On the offhand chance you actually need the output and the data, use two different statements

Select @code = RecItemCode from Receipt where RecTransaction = @id
Select RecItemCode, RecUsername from Receipt where RecTransaction = @id

This should assign your value to the output parameter as well as return two columns of data in a row. However, this strikes me as terribly redundant.

If you write your SP as I have shown at the very top, simply invoke cmd.ExecuteNonQuery(); and then read the output parameter value.


Another issue with your SP and code. In your SP, you have declared @code as varchar. In your code, you specify the parameter type as Int. Either change your SP or your code to make the types consistent.


Also note: If all you are doing is returning a single value, there's another way to do it that does not involve output parameters at all. You could write

 Select RecItemCode from Receipt where RecTransaction = @id

And then use object obj = cmd.ExecuteScalar(); to get the result, no need for an output parameter in the SP or in your code.

Why my regexp for hyphenated words doesn't work?

This regex should do it.

\b[a-z]+-[a-z]+\b 

\b indicates a word-boundary.

Detect if string contains any spaces

var inValid = new RegExp('^[_A-z0-9]{1,}$');
var value = "test string";
var k = inValid.test(value);
alert(k);

Is there an online application that automatically draws tree structures for phrases/sentences?

In short, yes. I assume you're looking to parse English: for that you can use the Link Parser from Carnegie Mellon.

It is important to remember that there are many theories of syntax, that can give completely different-looking phrase structure trees; further, the trees are different for each language, and tools may not exist for those languages.

As a note for the future: if you need a sentence parsed out and tag it as linguistics (and syntax or whatnot, if that's available), someone can probably parse it out for you and guide you through it.

Open an html page in default browser with VBA?

If you want a more robust solution with ShellExecute that will open ANY file, folder or URL using the default OS associated program to do so, here is a function taken from http://access.mvps.org/access/api/api0018.htm:

'************ Code Start **********
' This code was originally written by Dev Ashish.
' It is not to be altered or distributed,
' except as part of an application.
' You are free to use it in any application,
' provided the copyright notice is left unchanged.
'
' Code Courtesy of
' Dev Ashish
'
Private Declare Function apiShellExecute Lib "shell32.dll" _
    Alias "ShellExecuteA" _
    (ByVal hwnd As Long, _
    ByVal lpOperation As String, _
    ByVal lpFile As String, _
    ByVal lpParameters As String, _
    ByVal lpDirectory As String, _
    ByVal nShowCmd As Long) _
    As Long

'***App Window Constants***
Public Const WIN_NORMAL = 1         'Open Normal
Public Const WIN_MAX = 3            'Open Maximized
Public Const WIN_MIN = 2            'Open Minimized

'***Error Codes***
Private Const ERROR_SUCCESS = 32&
Private Const ERROR_NO_ASSOC = 31&
Private Const ERROR_OUT_OF_MEM = 0&
Private Const ERROR_FILE_NOT_FOUND = 2&
Private Const ERROR_PATH_NOT_FOUND = 3&
Private Const ERROR_BAD_FORMAT = 11&

'***************Usage Examples***********************
'Open a folder:     ?fHandleFile("C:\TEMP\",WIN_NORMAL)
'Call Email app:    ?fHandleFile("mailto:[email protected]",WIN_NORMAL)
'Open URL:          ?fHandleFile("http://home.att.net/~dashish", WIN_NORMAL)
'Handle Unknown extensions (call Open With Dialog):
'                   ?fHandleFile("C:\TEMP\TestThis",Win_Normal)
'Start Access instance:
'                   ?fHandleFile("I:\mdbs\CodeNStuff.mdb", Win_NORMAL)
'****************************************************

Function fHandleFile(stFile As String, lShowHow As Long)
Dim lRet As Long, varTaskID As Variant
Dim stRet As String
    'First try ShellExecute
    lRet = apiShellExecute(hWndAccessApp, vbNullString, _
            stFile, vbNullString, vbNullString, lShowHow)

    If lRet > ERROR_SUCCESS Then
        stRet = vbNullString
        lRet = -1
    Else
        Select Case lRet
            Case ERROR_NO_ASSOC:
                'Try the OpenWith dialog
                varTaskID = Shell("rundll32.exe shell32.dll,OpenAs_RunDLL " _
                        & stFile, WIN_NORMAL)
                lRet = (varTaskID <> 0)
            Case ERROR_OUT_OF_MEM:
                stRet = "Error: Out of Memory/Resources. Couldn't Execute!"
            Case ERROR_FILE_NOT_FOUND:
                stRet = "Error: File not found.  Couldn't Execute!"
            Case ERROR_PATH_NOT_FOUND:
                stRet = "Error: Path not found. Couldn't Execute!"
            Case ERROR_BAD_FORMAT:
                stRet = "Error:  Bad File Format. Couldn't Execute!"
            Case Else:
        End Select
    End If
    fHandleFile = lRet & _
                IIf(stRet = "", vbNullString, ", " & stRet)
End Function
'************ Code End **********

Just put this into a separate module and call fHandleFile() with the right parameters.

React img tag issue with url and class

Remember that your img is not really a DOM element but a javascript expression.

  1. This is a JSX attribute expression. Put curly braces around the src string expression and it will work. See http://facebook.github.io/react/docs/jsx-in-depth.html#attribute-expressions

  2. In javascript, the class attribute is reference using className. See the note in this section: http://facebook.github.io/react/docs/jsx-in-depth.html#react-composite-components

    /** @jsx React.DOM */
    
    var Hello = React.createClass({
        render: function() {
            return <div><img src={'http://placehold.it/400x20&text=slide1'} alt="boohoo" className="img-responsive"/><span>Hello {this.props.name}</span></div>;
        }
    });
    
    React.renderComponent(<Hello name="World" />, document.body);
    

How can I make git accept a self signed certificate?

Check your antivirus and firewall settings.

From one day to the other, git did not work anymore. With what is described above, I found that Kaspersky puts a self-signed Anti-virus personal root certificate in the middle. I did not manage to let Git accept that certificate following the instructions above. I gave up on that. What works for me is to disable the feature to Scan encrypted connections.

  1. Open Kaspersky
  2. Settings > Additional > Network > Do not scan encrypted connections

After this, git works again with sslVerify enabled.

Note. This is still not satisfying for me, because I would like to have that feature of my Anti-Virus active. In the advanced settings, Kaspersky shows a list of websites that will not work with that feature. Github is not listed as one of them. I will check it at the Kaspersky forum. There seem to be some topics, e.g. https://forum.kaspersky.com/index.php?/topic/395220-kis-interfering-with-git/&tab=comments#comment-2801211

Global keyboard capture in C# application

If a global hotkey would suffice, then RegisterHotKey would do the trick

Postgres error on insert - ERROR: invalid byte sequence for encoding "UTF8": 0x00

This kind of error can also happen when using COPY and having an escaped string containing NULL values(00) such as:

"H\x00\x00\x00tj\xA8\x9E#D\x98+\xCA\xF0\xA7\xBBl\xC5\x19\xD7\x8D\xB6\x18\xEDJ\x1En"

If you use COPY without specifying the format 'CSV' postgres by default will assume format 'text'. This has a different interaction with backlashes, see text format.

If you're using COPY or a file_fdw make sure to specify format 'CSV' to avoid this kind of errors.

Why am I getting error for apple-touch-icon-precomposed.png

Note that this can happen even when the user has NOT bookmarked the site to their iOS home screen - for example, any time you open a page using Chrome for iOS, it does a GET "/apple-touch-icon-precomposed.png".

I've handled this and other non-HTML 404 requests in my ApplicationController as follows:

respond_to do |format|
  format.html { render :template => "error_404", :layout => "errors", :status => 404 }
  format.all { render :nothing => true, :status => 404 }
end

The format.all response takes care of images such as this PNG file (which does not exist for my site).

Call a Subroutine from a different Module in VBA

Prefix the call with Module2 (ex. Module2.IDLE). I'm assuming since you asked this that you have IDLE defined multiple times in the project, otherwise this shouldn't be necessary.

Array of an unknown length in C#

var yummy = new List<string>();
while(person.FeelsHappy()) {
    yummy.Add(person.GetNewFavoriteFood());
}
Console.WriteLine("Sweet! I have a list of size {0}.", list.Count);
Console.WriteLine("I didn't even need to know how big to make it " +
    "until I finished making it!");

Multiple line comment in Python

Try this

'''
This is a multiline
comment. I can type here whatever I want.
'''

Python does have a multiline string/comment syntax in the sense that unless used as docstrings, multiline strings generate no bytecode -- just like #-prepended comments. In effect, it acts exactly like a comment.

On the other hand, if you say this behavior must be documented in the official docs to be a true comment syntax, then yes, you would be right to say it is not guaranteed as part of the language specification.

In any case your editor should also be able to easily comment-out a selected region (by placing a # in front of each line individually). If not, switch to an editor that does.

Programming in Python without certain text editing features can be a painful experience. Finding the right editor (and knowing how to use it) can make a big difference in how the Python programming experience is perceived.

Not only should the editor be able to comment-out selected regions, it should also be able to shift blocks of code to the left and right easily, and should automatically place the cursor at the current indentation level when you press Enter. Code folding can also be useful.

Bootstrap trying to load map file. How to disable it? Do I need to do it?

From bootstrap.css remove remove last line /*# sourceMappingURL=bootstrap-theme.css.map */