Programs & Examples On #Document imaging

Java error: Comparison method violates its general contract

I had to sort on several criterion (date, and, if same date; other things...). What was working on Eclipse with an older version of Java, did not worked any more on Android : comparison method violates contract ...

After reading on StackOverflow, I wrote a separate function that I called from compare() if the dates are the same. This function calculates the priority, according to the criteria, and returns -1, 0, or 1 to compare(). It seems to work now.

Row count on the Filtered data

I have found a way to do this that it requires 2 steps, but it works

' to copy out a filtered selection into a different sheet


number_of_dinosaurs = WorksheetFunction.Count(Worksheets("Dinosaurs").Range("A2", "A3000"))

With Worksheets("Dinosaurs")
    .AutoFilterMode = False
    With .Range("$A$4:$E$" & number_of_dinosaurs)
        .AutoFilter Field:=2, Criteria1:="*teeth*" ' change your criteria to whatever you like
        .SpecialCells(xlCellTypeVisible).Copy Destination:=Worksheets("Bad_Dinosaurs").Range("A1")
    End With
End With


' then do a normal count on the secondary sheet  

number_of_dinosaurs_that_eat_humans = WorksheetFunction.Count(Worksheets("Bad_Dinosaurs").Range("A2", "A30000"))

OR condition in Regex

Try

\d \w |\d

or add a positive lookahead if you don't want to include the trailing space in the match

\d \w(?= )|\d

When you have two alternatives where one is an extension of the other, put the longer one first, otherwise it will have no opportunity to be matched.

WindowsError: [Error 126] The specified module could not be found

problem solved for me. I changed version from pytorch=1.5.1 to pytorch=1.4 and typed the below command in anaconda prompt window

conda install pytorch==1.4.0 torchvision==0.5.0 -c pytorch

Is it possible to install Xcode 10.2 on High Sierra (10.13.6)?

None of the above helped for me.

I was able to install Mojave using this link here: http://dosdude1.com/mojave/ This patch worked beautifully and without a hitch

Proof: here's Mojave running on my (unsupported) 2011 Mac-mini

How to add directory to classpath in an application run profile in IntelliJ IDEA?

Suppose you need only x:target/classes in your classpath. Then you just add this folder to your classpath and %IDEA%\lib\idea_rt.jar. Now it will work. That's it.

When should I use "this" in a class?

With respect to William Brendel's posts and dbconfessions question, regarding case 2. Here is an example:

public class Window {

  private Window parent;

  public Window (Window parent) {
    this.parent = parent;
  }

  public void addSubWindow() {
    Window child = new Window(this);
    list.add(child);
  }

  public void printInfo() {
    if (parent == null) {
      System.out.println("root");
    } else {
      System.out.println("child");
    }
  }

}

I've seen this used, when building parent-child relation's with objects. However, please note that it is simplified for the sake of brevity.

AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https

Adding to @Kirill Fuchs excellent solution and answering @StackUser's doubt - while starting the http-server, set the path till the app folder only, NOT till the html page! http-server C:\location\to\app and access index.html under app folder

Difference between RegisterStartupScript and RegisterClientScriptBlock?

Here's a simplest example from ASP.NET Community, this gave me a clear understanding on the concept....

what difference does this make?

For an example of this, here is a way to put focus on a text box on a page when the page is loaded into the browser—with Visual Basic using the RegisterStartupScript method:

Page.ClientScript.RegisterStartupScript(Me.GetType(), "Testing", _ 
"document.forms[0]['TextBox1'].focus();", True)

This works well because the textbox on the page is generated and placed on the page by the time the browser gets down to the bottom of the page and gets to this little bit of JavaScript.

But, if instead it was written like this (using the RegisterClientScriptBlock method):

Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "Testing", _
"document.forms[0]['TextBox1'].focus();", True)

Focus will not get to the textbox control and a JavaScript error will be generated on the page

The reason for this is that the browser will encounter the JavaScript before the text box is on the page. Therefore, the JavaScript will not be able to find a TextBox1.

SQL server 2008 backup error - Operating system error 5(failed to retrieve text for this error. Reason: 15105)

I've got the same error. I have been trying to fixing this by setting higher permission to account running SQL Client service, however it didnt help. The problem was that I run MS Sql Management studio just within my account. So, next time... assure that you are running it as Run as Administrator, if using Win7 with UAC enabled.

Links not going back a directory?

There are two type of paths: absolute and relative. This is basically the same for files in your hard disc and directories in a URL.

Absolute paths start with a leading slash. They always point to the same location, no matter where you use them:

  • /pages/en/faqs/faq-page1.html

Relative paths are the rest (all that do not start with slash). The location they point to depends on where you are using them

  • index.html is:
    • /pages/en/faqs/index.html if called from /pages/en/faqs/faq-page1.html
    • /pages/index.html if called from /pages/example.html
    • etc.

There are also two special directory names: . and ..:

  • . means "current directory"
  • .. means "parent directory"

You can use them to build relative paths:

  • ../index.html is /pages/en/index.html if called from /pages/en/faqs/faq-page1.html
  • ../../index.html is /pages/index.html if called from /pages/en/faqs/faq-page1.html

Once you're familiar with the terms, it's easy to understand what it's failing and how to fix it. You have two options:

  • Use absolute paths
  • Fix your relative paths

JavaScript and getElementById for multiple elements with the same ID

If you're using d3 for handling multiple objects with the same class / id

You can remove a subset of class elements by using d3.selectAll(".classname");

For example the donut graph here on http://medcorp.co.nz utilizes copies of an arc object with class name "arc" and there's a single line of d3, d3.selectAll(".arc").remove(); to remove all those objects;

using document.getElementById("arc").remove(); only removes a single element and would have to be called multiple times (as is with the suggestions above he creates a loop to remove the objects n times)

"Connection for controluser as defined in your configuration failed" with phpMyAdmin in XAMPP

Have you recently changed your MySQL Server root password? If answer is YES, than this is the cause of the error / warning inside phpMyAdmin console. To fix the problem, simply edit your phpMyAdmin’s config-db.php file and setup the proper database password.

First answer is messing too much in my view and second answer did not work for me. So:

In Linux-based servers the file is usually located in:

/etc/phpmyadmin/config-db.php

or:

/etc/phpMyAdmin/config-db.php

Example: (My File looked like this and I changed the user fromphpmyadmin to admin, the username I created for maintaining my database through phpmyadmin, and put in the appropriate password.

$dbuser='phpmyadmin';
$dbpass=''; // set current password between quotes ' '
$basepath='';
$dbname='phpmyadmin';
$dbserver='';
$dbport='';
$dbtype='mysql';

credits: http://tehnoblog.org/phpmyadmin-error-connection-for-controluser-as-defined-in-your-configuration-failed/

How to get the date and time values in a C program?

strftime (C89)

Martin mentioned it, here's an example:

main.c

#include <assert.h>
#include <stdio.h>
#include <time.h>

int main(void) {
    time_t t = time(NULL);
    struct tm *tm = localtime(&t);
    char s[64];
    assert(strftime(s, sizeof(s), "%c", tm));
    printf("%s\n", s);
    return 0;
}

GitHub upstream.

Compile and run:

gcc -std=c89 -Wall -Wextra -pedantic -o main.out main.c
./main.out

Sample output:

Thu Apr 14 22:39:03 2016

The %c specifier produces the same format as ctime.

One advantage of this function is that it returns the number of bytes written, allowing for better error control in case the generated string is too long:

RETURN VALUE

  Provided  that  the  result string, including the terminating null byte, does not exceed max bytes, strftime() returns the number of bytes (excluding the terminating null byte) placed in the array s.  If the length of the result string (including the terminating null byte) would exceed max bytes, then
   strftime() returns 0, and the contents of the array are undefined.
  Note that the return value 0 does not necessarily indicate an error.  For example, in many locales %p yields an empty string.  An empty format string will likewise yield an empty string.

asctime and ctime (C89, deprecated in POSIX 7)

asctime is a convenient way to format a struct tm:

main.c

#include <stdio.h>
#include <time.h>

int main(void) {
    time_t t = time(NULL);
    struct tm *tm = localtime(&t);
    printf("%s", asctime(tm));
    return 0;
}

Sample output:

Wed Jun 10 16:10:32 2015

And there is also ctime() which the standard says is a shortcut for:

asctime(localtime())

As mentioned by Jonathan Leffler, the format has the shortcoming of not having timezone information.

POSIX 7 marked those functions as "obsolescent" so they could be removed in future versions:

The standard developers decided to mark the asctime() and asctime_r() functions obsolescent even though asctime() is in the ISO C standard due to the possibility of buffer overflow. The ISO C standard also provides the strftime() function which can be used to avoid these problems.

C++ version of this question: How to get current time and date in C++?

Tested in Ubuntu 16.04.

printing a value of a variable in postgresql

You can raise a notice in Postgres as follows:

raise notice 'Value: %', deletedContactId;

Read here

I have filtered my Excel data and now I want to number the rows. How do I do that?

Easiest way do this is to remove filter, fill series from top of total data. Filter your desired data back in, copy list of numbers into a new sheet (this should be only the total lines you want to add numbering to) paste into column A1. Add "1" into column B1, right click and hold then drag down to end of numbers and choose "fill series". Now return to your list with filters and in the next column to the right "VLOOKUP" the filtered number against the list you pasted into a new sheet and return the 2nd value.

Create a copy of a table within the same database DB2

CREATE TABLE NEW_TABLENAME LIKE OLD_TABLENAME;

Works for DB2 V 9.7

How to express a NOT IN query with ActiveRecord/Rails?

Piggybacking off of jonnii:

Topic.find(:all, :conditions => ['forum_id not in (?)', @forums.pluck(:id)])

using pluck rather than mapping over the elements

found via railsconf 2012 10 things you did not know rails could do

Do Swift-based applications work on OS X 10.9/iOS 7 and lower?

Quick Update, effective from February 15th, 2015, we cannot submit apps to the store that were developed using an SDK prior to iOS 8. So, keeping that in mind , its better to not to worry about this issue as many people have suggested that apps made in Swift can be deployed to OS X 10.9 and iOS 7.0 as well.

WampServer orange icon

If you are using wampserver 3 (recommended, works with no configuration usually)

  • click wampserver icon > apache > service administration > install service
  • click wampserver icon > mysql > service administration > install service
  • click wampserver icon > mariadb > service administration > install service
  • click wampserver icon > restart all services

if this doesnt fix it, try:

  • right click wampserver icon > Tools > Check httpd.conf syntax (then fix the issue it identifies and restart all services, likely it's bad syntax in your virtual hosts file)

  • right click wampserver icon > Tools > test port 80 (you likely have skype turned on or something else, turn it off and restart all services)

If this doesnt fix it, maybe have a windows conflict:

If this doesnt fix it:

  • right click wampserver icon > tools
    • check all of those for clues

How to store an array into mysql?

I'd prefer to normalize your table structure more, something like;

COMMENTS
-------
id (pk)
title
comment
userId


USERS
-----
id (pk)
name
email


COMMENT_VOTE
------------
commentId (pk)
userId (pk)
rating (float)

Now it's easier to maintain! And MySQL only accept one vote per user and comment.

Clearing _POST array fully

To answer "why" someone might use it, I was tempted to use it since I had the $_POST values stored after the page refresh or while going from one page to another. My sense tells me this is not a good practice, but it works nevertheless.

Android Intent Cannot resolve constructor

Or you can simply start the activity as shown below;

startActivity( new Intent(currentactivity.this, Tostartactivity.class));

Comparing object properties in c#

If you are only comparing objects of the same type or further down the inheritance chain, why not specify the parameter as your base type, rather than object ?

Also do null checks on the parameter as well.

Furthermore I'd make use of 'var' just to make the code more readable (if its c#3 code)

Also, if the object has reference types as properties then you are just calling ToString() on them which doesn't really compare values. If ToString isn't overwridden then its just going to return the type name as a string which could return false-positives.

LEFT function in Oracle

There is no documented LEFT() function in Oracle. Find the full set here.

Probably what you have is a user-defined function. You can check that easily enough by querying the data dictionary:

select * from all_objects
where object_name = 'LEFT'

But there is the question of why the stored procedure works and the query doesn't. One possible solution is that the stored procedure is owned by another schema, which also owns the LEFT() function. They have granted rights on the procedure but not its dependencies. This works because stored procedures run with DEFINER privileges by default, so you run the stored procedure as if you were its owner.

If this is so then the data dictionary query I listed above won't help you: it will only return rows for objects you have rights on. In which case you will need to run the query as the stored procedure's owner or connect as a user with the rights to query DBA_OBJECTS instead.

Split function in oracle to comma separated values with automatic sequence

Oracle Setup:

CREATE OR REPLACE FUNCTION split_String(
  i_str    IN  VARCHAR2,
  i_delim  IN  VARCHAR2 DEFAULT ','
) RETURN SYS.ODCIVARCHAR2LIST DETERMINISTIC
AS
  p_result       SYS.ODCIVARCHAR2LIST := SYS.ODCIVARCHAR2LIST();
  p_start        NUMBER(5) := 1;
  p_end          NUMBER(5);
  c_len CONSTANT NUMBER(5) := LENGTH( i_str );
  c_ld  CONSTANT NUMBER(5) := LENGTH( i_delim );
BEGIN
  IF c_len > 0 THEN
    p_end := INSTR( i_str, i_delim, p_start );
    WHILE p_end > 0 LOOP
      p_result.EXTEND;
      p_result( p_result.COUNT ) := SUBSTR( i_str, p_start, p_end - p_start );
      p_start := p_end + c_ld;
      p_end := INSTR( i_str, i_delim, p_start );
    END LOOP;
    IF p_start <= c_len + 1 THEN
      p_result.EXTEND;
      p_result( p_result.COUNT ) := SUBSTR( i_str, p_start, c_len - p_start + 1 );
    END IF;
  END IF;
  RETURN p_result;
END;
/

Query

SELECT ROWNUM AS ID,
       COLUMN_VALUE AS Data
FROM   TABLE( split_String( 'A,B,C,D' ) );

Output:

ID DATA
-- ----
 1 A
 2 B
 3 C
 4 D

How do you create different variable names while in a loop?

I would use a list:

string = []
for i in range(0, 9):
  string.append("Hello")

This way, you would have 9 "Hello" and you could get them individually like this:

string[x]

Where x would identify which "Hello" you want.

So, print(string[1]) would print Hello.

PHP's array_map including keys

This is how I've implemented this in my project.

function array_map_associative(callable $callback, $array) {
    /* map original array keys, and call $callable with $key and value of $key from original array. */
    return array_map(function($key) use ($callback, $array){
        return $callback($key, $array[$key]);
    }, array_keys($array));
}

Set Canvas size using javascript

Try this:

var setCanvasSize = function() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}

Multiple INNER JOIN SQL ACCESS

Access requires parentheses in the FROM clause for queries which include more than one join. Try it this way ...

FROM
    ((tbl_employee
    INNER JOIN tbl_netpay
    ON tbl_employee.emp_id = tbl_netpay.emp_id)
    INNER JOIN tbl_gross
    ON tbl_employee.emp_id = tbl_gross.emp_ID)
    INNER JOIN tbl_tax
    ON tbl_employee.emp_id = tbl_tax.emp_ID;

If possible, use the Access query designer to set up your joins. The designer will add parentheses as required to keep the db engine happy.

How to concatenate strings in a Windows batch file?

What about:

@echo off
set myvar="the list: "
for /r %%i in (*.doc) DO call :concat %%i
echo %myvar%
goto :eof

:concat
set myvar=%myvar% %1;
goto :eof

How to reverse MD5 to get the original string?

Its not possible thats the whole point of hashing. You can however bruteforce by going through all possibilities (using all possible digits characters in every possible order) and hashing them and checking for a collision.

for more information on hashing and MD5 etc see: http://en.wikipedia.org/wiki/MD5 , http://en.wikipedia.org/wiki/Hash_function , http://en.wikipedia.org/wiki/Cryptographic_hash_function and http://onin.com/hhh/hhhexpl.html

I myself created my own app to do this, its open source you can check the link: http://sourceforge.net/projects/jpassrecovery/ and of course the source. Here is the source for easy access it has a basic implementation in the comments:

Bruter.java:

import java.util.ArrayList;

public class Bruter {

    public ArrayList<String> characters = new ArrayList<>();
    public boolean found = false;
    public int maxLength;
    public int minLength;
    public int count;
    long starttime, endtime;
    public int minutes, seconds, hours, days;
    public char[] specialCharacters = {'~', '`', '!', '@', '#', '$', '%', '^',
        '&', '*', '(', ')', '_', '-', '+', '=', '{', '}', '[', ']', '|', '\\',
        ';', ':', '\'', '"', '<', '.', ',', '>', '/', '?', ' '};
    public boolean done = false;
    public boolean paused = false;

    public boolean isFound() {
        return found;
    }

    public void setPaused(boolean paused) {
        this.paused = paused;
    }

    public boolean isPaused() {
        return paused;
    }

    public void setFound(boolean found) {
        this.found = found;
    }

    public synchronized void setEndtime(long endtime) {
        this.endtime = endtime;
    }

    public int getCounter() {
        return count;
    }

    public long getRemainder() {
        return getNumberOfPossibilities() - count;
    }

    public long getNumberOfPossibilities() {
        long possibilities = 0;
        for (int i = minLength; i <= maxLength; i++) {
            possibilities += (long) Math.pow(characters.size(), i);
        }
        return possibilities;
    }

    public void addExtendedSet() {
        for (char c = (char) 0; c <= (char) 31; c++) {
            characters.add(String.valueOf(c));
        }
    }

    public void addStandardCharacterSet() {
        for (char c = (char) 32; c <= (char) 127; c++) {
            characters.add(String.valueOf(c));
        }
    }

    public void addLowerCaseLetters() {
        for (char c = 'a'; c <= 'z'; c++) {
            characters.add(String.valueOf(c));
        }
    }

    public void addDigits() {
        for (int c = 0; c <= 9; c++) {
            characters.add(String.valueOf(c));
        }
    }

    public void addUpperCaseLetters() {
        for (char c = 'A'; c <= 'Z'; c++) {
            characters.add(String.valueOf(c));
        }
    }

    public void addSpecialCharacters() {
        for (char c : specialCharacters) {
            characters.add(String.valueOf(c));
        }
    }

    public void setMaxLength(int i) {
        maxLength = i;
    }

    public void setMinLength(int i) {
        minLength = i;
    }

    public int getPerSecond() {
        int i;
        try {
            i = (int) (getCounter() / calculateTimeDifference());
        } catch (Exception ex) {
            return 0;
        }
        return i;

    }

    public String calculateTimeElapsed() {
        long timeTaken = calculateTimeDifference();
        seconds = (int) timeTaken;
        if (seconds > 60) {
            minutes = (int) (seconds / 60);
            if (minutes * 60 > seconds) {
                minutes = minutes - 1;
            }

            if (minutes > 60) {
                hours = (int) minutes / 60;
                if (hours * 60 > minutes) {
                    hours = hours - 1;
                }
            }

            if (hours > 24) {
                days = (int) hours / 24;
                if (days * 24 > hours) {
                    days = days - 1;
                }
            }
            seconds -= (minutes * 60);
            minutes -= (hours * 60);
            hours -= (days * 24);
            days -= (hours * 24);
        }
        return "Time elapsed: " + days + "days " + hours + "h " + minutes + "min " + seconds + "s";
    }

    private long calculateTimeDifference() {
        long timeTaken = (long) ((endtime - starttime) * (1 * Math.pow(10, -9)));
        return timeTaken;
    }

    public boolean excludeChars(String s) {
        char[] arrayChars = s.toCharArray();
        for (int i = 0; i < arrayChars.length; i++) {
            characters.remove(arrayChars[i] + "");
        }
        if (characters.size() < maxLength) {
            return false;
        } else {
            return true;

        }
    }

    public int getMaxLength() {
        return maxLength;
    }

    public int getMinLength() {
        return minLength;
    }

    public void setIsDone(Boolean b) {
        done = b;
    }

    public boolean isDone() {
        return done;
    }
}

HashBruter.java:

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.zip.Adler32;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
import javax.swing.JOptionPane;

public class HashBruter extends Bruter {
    /*
     * public static void main(String[] args) {
     *
     * final HashBruter hb = new HashBruter();
     *
     * hb.setMaxLength(5); hb.setMinLength(1);
     *
     * hb.addSpecialCharacters(); hb.addUpperCaseLetters();
     * hb.addLowerCaseLetters(); hb.addDigits();
     *
     * hb.setType("sha-512");
     *
     * hb.setHash("282154720ABD4FA76AD7CD5F8806AA8A19AEFB6D10042B0D57A311B86087DE4DE3186A92019D6EE51035106EE088DC6007BEB7BE46994D1463999968FBE9760E");
     *
     * Thread thread = new Thread(new Runnable() {
     *
     * @Override public void run() { hb.tryBruteForce(); } });
     *
     * thread.start();
     *
     * while (!hb.isFound()) { System.out.println("Hash: " +
     * hb.getGeneratedHash()); System.out.println("Number of Possibilities: " +
     * hb.getNumberOfPossibilities()); System.out.println("Checked hashes: " +
     * hb.getCounter()); System.out.println("Estimated hashes left: " +
     * hb.getRemainder()); }
     *
     * System.out.println("Found " + hb.getType() + " hash collision: " +
     * hb.getGeneratedHash() + " password is: " + hb.getPassword());
     *
     * }
     */

    public String hash, generatedHash, password;
    public String type;

    public String getType() {
        return type;
    }

    public String getPassword() {
        return password;
    }

    public void setHash(String p) {
        hash = p;
    }

    public void setType(String digestType) {
        type = digestType;
    }

    public String getGeneratedHash() {
        return generatedHash;
    }

    public void tryBruteForce() {
        starttime = System.nanoTime();
        for (int size = minLength; size <= maxLength; size++) {
            if (found == true || done == true) {
                break;
            } else {
                while (paused) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                }
                generateAllPossibleCombinations("", size);
            }
        }
        done = true;
    }

    private void generateAllPossibleCombinations(String baseString, int length) {
        while (paused) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
        if (found == false || done == false) {
            if (baseString.length() == length) {
                if(type.equalsIgnoreCase("crc32")) {
                generatedHash = generateCRC32(baseString);
                } else if(type.equalsIgnoreCase("adler32")) {
                generatedHash = generateAdler32(baseString);
                } else if(type.equalsIgnoreCase("crc16")) {
                    generatedHash=generateCRC16(baseString);
                } else if(type.equalsIgnoreCase("crc64")) {
                    generatedHash=generateCRC64(baseString.getBytes());
                }
                else {
                generatedHash = generateHash(baseString.toCharArray());
                }
                    password = baseString;
                if (hash.equals(generatedHash)) {
                    password = baseString;
                    found = true;
                    done = true;
                }
                count++;
            } else if (baseString.length() < length) {
                for (int n = 0; n < characters.size(); n++) {
                    generateAllPossibleCombinations(baseString + characters.get(n), length);
                }
            }
        }
    }

    private String generateHash(char[] passwordChar) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance(type);
        } catch (NoSuchAlgorithmException e1) {
            JOptionPane.showMessageDialog(null, "No such algorithm for hashes exists", "Error", JOptionPane.ERROR_MESSAGE);
        }
        String passwordString = new String(passwordChar);
        byte[] passwordByte = passwordString.getBytes();
        md.update(passwordByte, 0, passwordByte.length);
        byte[] encodedPassword = md.digest();
        String encodedPasswordInString = toHexString(encodedPassword);
        return encodedPasswordInString;
    }

    private void byte2hex(byte b, StringBuffer buf) {
        char[] hexChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
            '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        int high = ((b & 0xf0) >> 4);
        int low = (b & 0x0f);
        buf.append(hexChars[high]);
        buf.append(hexChars[low]);
    }

    private String toHexString(byte[] block) {
        StringBuffer buf = new StringBuffer();
        int len = block.length;
        for (int i = 0; i < len; i++) {
            byte2hex(block[i], buf);
        }
        return buf.toString();
    }

    private String generateCRC32(String baseString) {

                //Convert string to bytes
                byte bytes[] = baseString.getBytes();

                Checksum checksum = new CRC32();

                /*
                 * To compute the CRC32 checksum for byte array, use
                 *
                 * void update(bytes[] b, int start, int length)
                 * method of CRC32 class.
                 */

                checksum.update(bytes,0,bytes.length);

                /*
                 * Get the generated checksum using
                 * getValue method of CRC32 class.
                 */
                return String.valueOf(checksum.getValue());
    }   
    private String generateAdler32(String baseString) {

                //Convert string to bytes
                byte bytes[] = baseString.getBytes();

                Checksum checksum = new Adler32();

                /*
                 * To compute the CRC32 checksum for byte array, use
                 *
                 * void update(bytes[] b, int start, int length)
                 * method of CRC32 class.
                 */

                checksum.update(bytes,0,bytes.length);

                /*
                 * Get the generated checksum using
                 * getValue method of CRC32 class.
                 */
                return String.valueOf(checksum.getValue());
    }
/*************************************************************************
 *  Compilation:  javac CRC16.java
 *  Execution:    java CRC16 s
 *  
 *  Reads in a string s as a command-line argument, and prints out
 *  its 16-bit Cyclic Redundancy Check (CRC16). Uses a lookup table.
 *
 *  Reference:  http://www.gelato.unsw.edu.au/lxr/source/lib/crc16.c
 *
 *  % java CRC16 123456789
 *  CRC16 = bb3d
 *
 * Uses irreducible polynomial:  1 + x^2 + x^15 + x^16
 *
 *
 *************************************************************************/
    private String generateCRC16(String baseString) {
                int[] table = {
            0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
            0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
            0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
            0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
            0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
            0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
            0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
            0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
            0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
            0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
            0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
            0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
            0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
            0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
            0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
            0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
            0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
            0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
            0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
            0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
            0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
            0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
            0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
            0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
            0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
            0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
            0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
            0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
            0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
            0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
            0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
            0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040,
        };


        byte[] bytes = baseString.getBytes();
        int crc = 0x0000;
        for (byte b : bytes) {
            crc = (crc >>> 8) ^ table[(crc ^ b) & 0xff];
        }

        return Integer.toHexString(crc);
    }
    /*******************************************************************************
 * Copyright (c) 2009, 2012 Mountainminds GmbH & Co. KG and Contributors
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Marc R. Hoffmann - initial API and implementation
 *    
 *******************************************************************************/

/**
 * CRC64 checksum calculator based on the polynom specified in ISO 3309. The
 * implementation is based on the following publications:
 * 
 * <ul>
 * <li>http://en.wikipedia.org/wiki/Cyclic_redundancy_check</li>
 * <li>http://www.geocities.com/SiliconValley/Pines/8659/crc.htm</li>
 * </ul>
 */
    private static final long POLY64REV = 0xd800000000000000L;

    private static final long[] LOOKUPTABLE;

    static {
        LOOKUPTABLE = new long[0x100];
        for (int i = 0; i < 0x100; i++) {
            long v = i;
            for (int j = 0; j < 8; j++) {
                if ((v & 1) == 1) {
                    v = (v >>> 1) ^ POLY64REV;
                } else {
                    v = (v >>> 1);
                }
            }
            LOOKUPTABLE[i] = v;
        }
    }

    /**
     * Calculates the CRC64 checksum for the given data array.
     * 
     * @param data
     *            data to calculate checksum for
     * @return checksum value
     */
    public static String generateCRC64(final byte[] data) {
        long sum = 0;
        for (int i = 0; i < data.length; i++) {
            final int lookupidx = ((int) sum ^ data[i]) & 0xff;
            sum = (sum >>> 8) ^ LOOKUPTABLE[lookupidx];
        }
        return String.valueOf(sum);
    }
}

you would use it like:

      final HashBruter hb = new HashBruter();

      hb.setMaxLength(5); hb.setMinLength(1);

     hb.addSpecialCharacters(); hb.addUpperCaseLetters();
     hb.addLowerCaseLetters(); hb.addDigits();

      hb.setType("sha-512");

                   hb.setHash("282154720ABD4FA76AD7CD5F8806AA8A19AEFB6D10042B0D57A311B86087DE4DE3186A92019D6EE51035106EE088DC6007BEB7BE46994D1463999968FBE9760E");

      Thread thread = new Thread(new Runnable() {

      @Override public void run() { hb.tryBruteForce(); } });

      thread.start();

      while (!hb.isFound()) { System.out.println("Hash: " +
      hb.getGeneratedHash()); System.out.println("Number of Possibilities: " +
      hb.getNumberOfPossibilities()); System.out.println("Checked hashes: " +
     hb.getCounter()); System.out.println("Estimated hashes left: " +
     hb.getRemainder()); }

     System.out.println("Found " + hb.getType() + " hash collision: " +
     hb.getGeneratedHash() + " password is: " + hb.getPassword());

How to create separate AngularJS controller files?

Using the angular.module API with an array at the end will tell angular to create a new module:

myApp.js

// It is like saying "create a new module"
angular.module('myApp.controllers', []); // Notice the empty array at the end here

Using it without the array is actually a getter function. So to seperate your controllers, you can do:

Ctrl1.js

// It is just like saying "get this module and create a controller"
angular.module('myApp.controllers').controller('Ctrlr1', ['$scope', '$http', function($scope, $http) {}]);

Ctrl2.js

angular.module('myApp.controllers').controller('Ctrlr2', ['$scope', '$http', function($scope, $http) {}]);

During your javascript imports, just make sure myApp.js is after AngularJS but before any controllers / services / etc...otherwise angular won't be able to initialize your controllers.

BASH Syntax error near unexpected token 'done'

Sometimes this error happens because of unexpected CR characters in file, usually because the file was generated on a Windows system which uses CR line endings. You can fix this by running os2unix or tr, for example:

tr -d '\015' < yourscript.sh > newscript.sh

This removes any CR characters from the file.

oracle - what statements need to be committed?

And a key point - although TRUNCATE TABLE seems like a DELETE with no WHERE clause, TRUNCATE is not DML, it is DDL. DELETE requires a COMMIT, but TRUNCATE does not.

How to extract duration time from ffmpeg output?

If you want to retrieve the length (and possibly all other metadata) from your media file with ffmpeg by using a python script you could try this:

import subprocess
import json

input_file  = "< path to your input file here >"

metadata = subprocess.check_output(f"ffprobe -i {input_file} -v quiet -print_format json -show_format -hide_banner".split(" "))

metadata = json.loads(metadata)
print(f"Length of file is: {float(metadata['format']['duration'])}")
print(metadata)

Output:

Length of file is: 7579.977143

{
  "streams": [
    {
      "index": 0,
      "codec_name": "mp3",
      "codec_long_name": "MP3 (MPEG audio layer 3)",
      "codec_type": "audio",
      "codec_time_base": "1/44100",
      "codec_tag_string": "[0][0][0][0]",
      "codec_tag": "0x0000",
      "sample_fmt": "fltp",
      "sample_rate": "44100",
      "channels": 2,
      "channel_layout": "stereo",
      "bits_per_sample": 0,
      "r_frame_rate": "0/0",
      "avg_frame_rate": "0/0",
      "time_base": "1/14112000",
      "start_pts": 353600,
      "start_time": "0.025057",
      "duration_ts": 106968637440,
      "duration": "7579.977143",
      "bit_rate": "320000",
      ...
      ...

Move_uploaded_file() function is not working

maybe you need to grant more permissions to your files.

suppose your code are under /var/www/my_project

try chmod -R 777 /var/www/my_project

How do I declare an array with a custom class?

To default-initialize an array of Ts, T must be default constructible. Normally the compiler gives you a default constructor for free. However, since you declared a constructor yourself, the compiler does not generate a default constructor.

Your options:

  • add a default constructor to name, if that makes sense (I don't think so, but I don't know the problem domain);
  • initialize all the elements of the array upon declaration (you can do this because name is an aggregate);

      name someName[4] = { { "Arthur", "Dent" },
                           { "Ford", "Prefect" },
                           { "Tricia", "McMillan" },
                           { "Zaphod", "Beeblebrox" }
                         };
    
  • use a std::vector instead, and only add element when you have them constructed.

How can I remove a character from a string using JavaScript?

There's always the string functions, if you know you're always going to remove the fourth character:

str.slice(0, 4) + str.slice(5, str.length))

How do I repair an InnoDB table?

Step 1.

Stop MySQL server

Step 2.

add this line to my.cnf ( In windows it is called my.ini )

set-variable=innodb_force_recovery=6

Step 3.

delete ib_logfile0 and ib_logfile1

Step 4.

Start MySQL server

Step 5.

Run this command:

mysqlcheck --database db_name table_name -uroot -p

After you have successfully fixed the crashed innodb table, don't forget to remove #set-variable=innodb_force_recovery=6 from my.cnf and then restart MySQL server again.

Gradle version 2.2 is required. Current version is 2.10

Here's what I did to fix this:

1) Create a new project

2) open the gradle-wrapper.properties file and copy the distributionUrl to your project e.g.:

distributionUrl=https\://services.gradle.org/distributions/gradle-3.2-all.zip

3) open the build.gradle (Project) and copy the gradle dependency to your project e.g.:

classpath 'com.android.tools.build:gradle:2.3.0-beta1'

4) File --> Invalidate Caches / Restart (I think a re-sync may have sufficed, but didn't try it)

5) Delete that project you made (optional)

Look, this is a silly way to do things, but Android Studio is free so who am I to complain...

IOError: [Errno 2] No such file or directory trying to open a file

Just as an FYI, here is my working code:

src_dir = "C:\\temp\\CSV\\"
target_dir = "C:\\temp\\output2\\"
keyword = "KEYWORD"

for f in os.listdir(src_dir):
    file_name = os.path.join(src_dir, f)
    out_file = os.path.join(target_dir, f)
    with open(file_name, "r+") as fi, open(out_file, "w") as fo:
        for line in fi:
            if keyword not in line:
                fo.write(line)

Thanks again to everyone for all the great feedback!

How can I read an input string of unknown length?

Take a character pointer to store required string.If you have some idea about possible size of string then use function

char *fgets (char *str, int size, FILE* file);`

else you can allocate memory on runtime too using malloc() function which dynamically provides requested memory.

Error: Could not find or load main class

java -verbose:class HelloWorld might help you understand which classes are being loaded.

Also, as mentioned before, remember to call the full qualified name (i.e. include package).

Apache HttpClient Android (Gradle)

Try adding this to your dependencies:

compile 'org.apache.httpcomponents:httpclient:4.4-alpha1'

And generally if you want to use a library and you are searching for the Gradle dependency line you can use Gradle Please

EDIT: Check this one too.

How to uninstall with msiexec using product id guid without .msi file present

you need /q at the end

MsiExec.exe /x {2F808931-D235-4FC7-90CD-F8A890C97B2F} /q

Python module for converting PDF to text

You can also quite easily use pdfminer as a library. You have access to the pdf's content model, and can create your own text extraction. I did this to convert pdf contents to semi-colon separated text, using the code below.

The function simply sorts the TextItem content objects according to their y and x coordinates, and outputs items with the same y coordinate as one text line, separating the objects on the same line with ';' characters.

Using this approach, I was able to extract text from a pdf that no other tool was able to extract content suitable for further parsing from. Other tools I tried include pdftotext, ps2ascii and the online tool pdftextonline.com.

pdfminer is an invaluable tool for pdf-scraping.


def pdf_to_csv(filename):
    from pdflib.page import TextItem, TextConverter
    from pdflib.pdfparser import PDFDocument, PDFParser
    from pdflib.pdfinterp import PDFResourceManager, PDFPageInterpreter

    class CsvConverter(TextConverter):
        def __init__(self, *args, **kwargs):
            TextConverter.__init__(self, *args, **kwargs)

        def end_page(self, i):
            from collections import defaultdict
            lines = defaultdict(lambda : {})
            for child in self.cur_item.objs:
                if isinstance(child, TextItem):
                    (_,_,x,y) = child.bbox
                    line = lines[int(-y)]
                    line[x] = child.text

            for y in sorted(lines.keys()):
                line = lines[y]
                self.outfp.write(";".join(line[x] for x in sorted(line.keys())))
                self.outfp.write("\n")

    # ... the following part of the code is a remix of the 
    # convert() function in the pdfminer/tools/pdf2text module
    rsrc = PDFResourceManager()
    outfp = StringIO()
    device = CsvConverter(rsrc, outfp, "ascii")

    doc = PDFDocument()
    fp = open(filename, 'rb')
    parser = PDFParser(doc, fp)
    doc.initialize('')

    interpreter = PDFPageInterpreter(rsrc, device)

    for i, page in enumerate(doc.get_pages()):
        outfp.write("START PAGE %d\n" % i)
        interpreter.process_page(page)
        outfp.write("END PAGE %d\n" % i)

    device.close()
    fp.close()

    return outfp.getvalue()

UPDATE:

The code above is written against an old version of the API, see my comment below.

Append an array to another array in JavaScript

If you want to modify the original array instead of returning a new array, use .push()...

array1.push.apply(array1, array2);
array1.push.apply(array1, array3);

I used .apply to push the individual members of arrays 2 and 3 at once.

or...

array1.push.apply(array1, array2.concat(array3));

To deal with large arrays, you can do this in batches.

for (var n = 0, to_add = array2.concat(array3); n < to_add.length; n+=300) {
    array1.push.apply(array1, to_add.slice(n, n+300));
}

If you do this a lot, create a method or function to handle it.

var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);

Object.defineProperty(Array.prototype, "pushArrayMembers", {
    value: function() {
        for (var i = 0; i < arguments.length; i++) {
            var to_add = arguments[i];
            for (var n = 0; n < to_add.length; n+=300) {
                push_apply(this, slice_call(to_add, n, n+300));
            }
        }
    }
});

and use it like this:

array1.pushArrayMembers(array2, array3);

_x000D_
_x000D_
var push_apply = Function.apply.bind([].push);_x000D_
var slice_call = Function.call.bind([].slice);_x000D_
_x000D_
Object.defineProperty(Array.prototype, "pushArrayMembers", {_x000D_
    value: function() {_x000D_
        for (var i = 0; i < arguments.length; i++) {_x000D_
            var to_add = arguments[i];_x000D_
            for (var n = 0; n < to_add.length; n+=300) {_x000D_
                push_apply(this, slice_call(to_add, n, n+300));_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
});_x000D_
_x000D_
var array1 = ['a','b','c'];_x000D_
var array2 = ['d','e','f'];_x000D_
var array3 = ['g','h','i'];_x000D_
_x000D_
array1.pushArrayMembers(array2, array3);_x000D_
_x000D_
document.body.textContent = JSON.stringify(array1, null, 4);
_x000D_
_x000D_
_x000D_

Emulate Samsung Galaxy Tab

UPDATED:
Matt provided a great link on how to add emulators for all Samsung devices.

OLD:
To get the official Samsung Galaxy Tab emulator do the following:

  1. Open the Android SDK and AVD Manager
  2. Click on Available packages
  3. Expand the Third party Add-ons. There you will see Samsung Electronics add-ons.
  4. Once the add-on is installed create a new emulator. Under Target you will see the new Samsung Tab settings, select that.

That's it!

Node.js Port 3000 already in use but it actually isn't?

I have spent 2h on finding out why EADDRINUSE wasn't allowing me to sart an app (other node-express servers were ok)... it started working after adding lazyConnect: true, to datasource configuration.

Don't ask me why it helped. I do not know. I am putting this info here just for people having the same issue.

html div onclick event

Change your jQuery code with this. It will alert the id of the a.

$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
markActiveLink();    
     alert('123');
 });

function markActiveLink(el) {   
var el = $('a').attr("id")
    alert(el);
} 

Demo

How to debug a GLSL shader?

You can try this: https://github.com/msqrt/shader-printf which is an implementation called appropriately "Simple printf functionality for GLSL."

You might also want to try ShaderToy, and maybe watch a video like this one (https://youtu.be/EBrAdahFtuo) from "The Art of Code" YouTube channel where you can see some of the techniques that work well for debugging and visualising. I can strongly recommend his channel as he writes some really good stuff and he also has a knack for presenting complex ideas in novel, highly engaging and and easy to digest formats (His Mandelbrot video is a superb example of exactly that : https://youtu.be/6IWXkV82oyY)

I hope nobody minds this late reply, but the question ranks high on Google searches for GLSL debugging and much has of course changed in 9 years :-)

PS: Other alternatives could also be NVIDIA nSight and AMD ShaderAnalyzer which offer a full stepping debugger for shaders.

How should I print types like off_t and size_t?

To print off_t:

printf("%jd\n", (intmax_t)x);

To print size_t:

printf("%zu\n", x);

To print ssize_t:

printf("%zd\n", x);

See 7.19.6.1/7 in the C99 standard, or the more convenient POSIX documentation of formatting codes:

http://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html

If your implementation doesn't support those formatting codes (for example because you're on C89), then you have a bit of a problem since AFAIK there aren't integer types in C89 that have formatting codes and are guaranteed to be as big as these types. So you need to do something implementation-specific.

For example if your compiler has long long and your standard library supports %lld, you can confidently expect that will serve in place of intmax_t. But if it doesn't, you'll have to fall back to long, which would fail on some other implementations because it's too small.

Word wrap for a label in Windows Forms

From MSDN, Automatically Wrap Text in Label:

using System;
using System.Text;
using System.Drawing;
using System.Windows.Forms;

public class GrowLabel : Label {
    private bool mGrowing;
    public GrowLabel() {
        this.AutoSize = false;
    }
    private void resizeLabel() {
        if (mGrowing) 
            return;
        try {
            mGrowing = true;
            Size sz = new Size(this.Width, Int32.MaxValue);
            sz = TextRenderer.MeasureText(this.Text, this.Font, sz, TextFormatFlags.WordBreak);
            this.Height = sz.Height;
        }
        finally {
            mGrowing = false;
        }
    }
    protected override void OnTextChanged(EventArgs e) {
        base.OnTextChanged(e);
        resizeLabel();
    }
    protected override void OnFontChanged(EventArgs e) {
        base.OnFontChanged(e);
        resizeLabel();
    }
    protected override void OnSizeChanged(EventArgs e) {
        base.OnSizeChanged(e);
        resizeLabel();
    }
}

Can't compile C program on a Mac after upgrade to Mojave

I was having this issue and nothing worked. I ran xcode-select --install and also installed /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg.

BACKGROUND

Since I was having issues with App Store on a new laptop, I was forced to download the Xcode Beta installer from the Apple website to install Xcode outside App Store. So I only had Xcode Beta installed.

SOLUTION

This, (I think), was making clang to not find the SDKROOT directory /Applications/Xcode.app/...., because there is no Beta in the path, or maybe Xcode Beta simply doesn't install it (I don't know). To fix the issue, I had to remove Xcode Beta and resolve the App Store issue to install the release version.

tldr;

If you have Xcode Beta, try cleaning up everything and installing the release version before trying out the solutions that are working for other people.

The target ... overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig

In your project, find Target -> Build Settings -> Other Linker Flags, select Other Linker Flags, press delete(Mac Keyboard)/Backspace(Normal keyboard) to recover the setting. It works for me.

Example:

Before enter image description here

After enter image description here

How to print jquery object/array

_x000D_
_x000D_
var arrofobject = [{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}];_x000D_
var data = arrofobject.map(arrofobject => arrofobject);_x000D_
console.log(data)
_x000D_
_x000D_
_x000D_

for more details please look at jQuery.map()

How can I declare dynamic String array in Java

Maybe you are looking for Vector. It's capacity is automatically expanded if needed. It's not the best choice but will do in simple situations. It's worth your time to read up on ArrayList instead.

HTML Code for text checkbox '?'

This will do:

&#x25a2;

It is ?
(known as a "WHITE SQUARE WITH ROUNDED CORNERS" on fileformat.info)

Or

&#x25fb;

as ?
(known as a "WHITE MEDIUM SQUARE" on the same website)

Two with shadow:

&#x274f;
&#x2751;

as ? and ? . The difference between them is the shadows' shape. You can see it if you zoom in or if you print it out. (They are known as "LOWER RIGHT DROP-SHADOWED WHITE SQUARE" and "LOWER RIGHT SHADOWED WHITE SQUARE", respectively).

You can also use

&#x2610;

which is ?
(known as a "BALLOT BOX").

A sample is at http://jsfiddle.net/S2QCt/267/

(a note: on the Mac, &#x25a2; is quite nice, because it is bigger and somewhat more elegant than &#x2610; On Windows, &#x2610; looks more standard, while &#x25a2; is somewhat small.)

UTF-8 byte[] to String

Java String class has a built-in-constructor for converting byte array to string.

byte[] byteArray = new byte[] {87, 79, 87, 46, 46, 46};

String value = new String(byteArray, "UTF-8");

How to sign an android apk file

APK Signing Process

To manually sign an Android APK file run these three commands:

  1. Generate Keystore file

    keytool -genkey -v -keystore YOUR_KEYSTORE_NAME.keystore -alias ALIAS_NAME -keyalg RSA -keysize 2048 -validity 10000
    
  2. Sign Your APK file using jarsigner

    jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore KEYSTORE_FILE_PATH UNSIGNED_APK_PATH ALIAS_NAME
    
  3. Align Signed APK using zipalign tool

    zipalign -v 4 JARSIGNED_APK_FILE_PATH ZIPALIGNED_SIGNED_APK_FILE_PATH
    

STEP 1


Generate Keystore file

keytool -genkey -v -keystore YOUR_KEYSTORE_NAME.keystore -alias ALIAS_NAME -keyalg RSA -keysize 2048 -validity 10000

Example:

keytool -genkey -v -keystore id.keystore -alias MySignedApp -keyalg RSA -keysize 2048 -validity 10000

keystore password : yourApp@123 key password : yourApp@123

CMD O/P

D:\ru\SignedBuilds\MySignedApp>keytool -genkey -v -keystore id.keystore
 -alias MySignedApp -keyalg RSA -keysize 2048 -validity 10000
Enter keystore password:
Re-enter new password:
What is your first and last name?
  [Unknown]:  MySignedApp Sample
What is the name of your organizational unit?
  [Unknown]:  Information Technology
What is the name of your organization?
  [Unknown]:  MySignedApp Demo
What is the name of your City or Locality?
  [Unknown]:  Mumbai
What is the name of your State or Province?
  [Unknown]:  Maharashtra
What is the two-letter country code for this unit?
  [Unknown]:  IN
Is CN=MySignedApp Demo, OU=Information Technology, O=MySignedApp Demo, L=Mumbai, ST=Maharashtra, C=IN corr
ect?
  [no]:  y

Generating 2,048 bit RSA key pair and self-signed certificate (SHA256withRSA) with a validity of 10,
000 days
        for: CN=MySignedApp Demo, OU=Information Technology, O=MySignedApp Demo, L=Mumbai, ST=Maharashtra,
 C=IN
Enter key password for <MySignedApp>
        (RETURN if same as keystore password):
Re-enter new password:
[Storing id.keystore]

D:\ru\SignedBuilds\MySignedApp>

STEP 2


Sign your app with your private keystore using jarsigner

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore KEYSTORE_FILE_PATH UNSIGNED_APK_PATH ALIAS_NAME

Example

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore D:\ru\SignedBuilds\MySignedApp\id.keystore D:\ru\SignedBuilds\MySignedApp\MySignedAppS1-release-unsigned.apk id

CMD O/P

D:\ru\SignedBuilds\MySignedApp>jarsigner -verbose -sigalg SHA1withRSA -
digestalg SHA1 -keystore D:\ru\SignedBuilds\MySignedApp\id.keystore D:\ru\SignedBuilds\MySignedApp\MySignedAppS1-release-unsigned.apk id ---
ect
Enter Passphrase for keystore:
   adding: META-INF/MANIFEST.MF
   adding: META-INF/---.SF
   adding: META-INF/---.RSA
  signing: AndroidManifest.xml
  ..... 
    signing: classes.dex
  signing: lib/commons-codec-1.6.jar
  signing: lib/armeabi/libkonyjsvm.so
jar signed.

Warning:
No -tsa or -tsacert is provided and this jar is not timestamped. Without a timestamp, users may not
be able to validate this jar after the signer certificate's expiration date (2044-02-07) or after an
y future revocation date.

D:\ru\SignedBuilds\MySignedApp>

Verify that your APK is signed

jarsigner -verify -verbose -certs JARSIGNED_APK_FILE_PATH

Example

jarsigner -verify -verbose -certs MySignedAppS1-release-unsigned.apk

CMD O/P

D:\ru\SignedBuilds\MySignedApp>jarsigner -verify -verbose -certs MySignedAppS1-release-unsigned.apk
 s = signature was verified
  m = entry is listed in manifest
  k = at least one certificate was found in keystore
  i = at least one certificate was found in identity scope

jar verified.

Warning:
This jar contains entries whose certificate chain is not validated.
This jar contains signatures that does not include a timestamp. Without a timestamp, users may not b
e able to validate this jar after the signer certificate's expiration date (2044-02-09) or after any
 future revocation date.

D:\ru\SignedBuilds\MySignedApp>

STEP 3


Align the final APK package using zipalign

zipalign -v 4 JARSIGNED_APK_FILE_PATH ZIPALIGNED_SIGNED_APK_FILE_PATH_WITH_NAME_ofSignedAPK

Example

zipalign -v 4 D:\ru\SignedBuilds\MySignedApp\MySignedAppS1-release-unsigned.apk D:\ru\SignedBuilds\MySignedApp\MySignedApp.apk

CMD O/P

D:\Android\android-sdk\build-tools\19.1.0>zipalign -v 4 D:\ru\ru_doc\Signed_apk\MySignedApp\28.09.16
_prod_playstore\MySignedAppS1-release-unsigned.apk D:\ru\ru_doc\Signed_apk\MySignedApp\28.09.16_prod
_playstore\MySignedApp.apk
Verifying alignment of D:\ru\SignedBuilds\MySignedApp\MySignedApp.apk (
4)...

  4528613 classes.dex (OK - compressed)
 5656594 lib/commons-codec-1.6.jar (OK - compressed)
 5841869 lib/armeabi/libkonyjsvm.so (OK - compressed)
Verification succesful

D:\Android\android-sdk\build-tools\19.1.0>

Verify that your APK is Aligned successfully

zipalign -c -v 4 YOUR_APK_PATH

Example

zipalign -c -v 4 D:\ru\SignedBuilds\MySignedApp\MySignedApp.apk

CMD O/P

D:\Android\android-sdk\build-tools\19.1.0>zipalign -c -v 4 D:\ru\SignedBuilds\MySignedApp\MySignedApp.apk
Verifying alignment of D:\ru\SignedBuilds\MySignedApp\MySignedApp.apk (
4)...

 4453984 res/drawable/zoomout.png (OK)
 4454772 res/layout/tabview.xml (OK - compressed)
 4455243 res/layout/wheel_item.xml (OK - compressed)
 4455608 resources.arsc (OK)
 4470161 classes.dex (OK - compressed)
 5597923 lib/commons-codec-1.6.jar (OK - compressed)
 5783198 lib/armeabi/libkonyjsvm.so (OK - compressed)
Verification succesful

D:\Android\android-sdk\build-tools\19.1.0>

Note:

The verify command is just to check whether APK is built and signed correctly!

References

I hope this will help one and all :)

How to terminate the script in JavaScript?

If you are using Firefox or a Browser it cannot be done with most of these Console methods once you have started an iterator ( as you can see I have ). You can go to source and manually pause the execution of the script. ( This still does not Stop it completely per say)

Screenshot of Developer Mode

ExecuteReader requires an open and available Connection. The connection's current state is Connecting

I caught this error a few days ago.

IN my case it was because I was using a Transaction on a Singleton.

.Net does not work well with Singleton as stated above.

My solution was this:

public class DbHelper : DbHelperCore
{
    public DbHelper()
    {
        Connection = null;
        Transaction = null;
    }

    public static DbHelper instance
    {
        get
        {
            if (HttpContext.Current is null)
                return new DbHelper();
            else if (HttpContext.Current.Items["dbh"] == null)
                HttpContext.Current.Items["dbh"] = new DbHelper();

            return (DbHelper)HttpContext.Current.Items["dbh"];
        }
    }

    public override void BeginTransaction()
    {
        Connection = new SqlConnection(Entity.Connection.getCon);
        if (Connection.State == System.Data.ConnectionState.Closed)
            Connection.Open();
        Transaction = Connection.BeginTransaction();
    }
}

I used HttpContext.Current.Items for my instance. This class DbHelper and DbHelperCore is my own class

Equivalent to AssemblyInfo in dotnet core/csproj

You can always add your own AssemblyInfo.cs, which comes in handy for InternalsVisibleToAttribute, CLSCompliantAttribute and others that are not automatically generated.

Adding AssemblyInfo.cs to a Project

  1. In Solution Explorer, right click on <project name> > Add > New Folder.

Add New Folder

  1. Name the folder "Properties".

Name folder Properties

  1. Right click on the "Properties" folder, and click Add > New Item....

Add New Item

  1. Select "Class" and name it "AssemblyInfo.cs".

Name file AssemblyInfo.cs

Suppressing Auto-Generated Attributes

If you want to move your attributes back to AssemblyInfo.cs instead of having them auto-generated, you can suppress them in MSBuild as natemcmaster pointed out in his answer.

Converting List<String> to String[] in Java

I've designed and implemented Dollar for this kind of tasks:

String[] strarray= $(strlist).toArray();

Using ffmpeg to change framerate

With re-encoding:

ffmpeg -y -i seeing_noaudio.mp4 -vf "setpts=1.25*PTS" -r 24 seeing.mp4

Without re-encoding:

First step - extract video to raw bitstream

ffmpeg -y -i seeing_noaudio.mp4 -c copy -f h264 seeing_noaudio.h264

Remux with new framerate

ffmpeg -y -r 24 -i seeing_noaudio.h264 -c copy seeing.mp4

Python: get key of index in dictionary

By definition dictionaries are unordered, and therefore cannot be indexed. For that kind of functionality use an ordered dictionary. Python Ordered Dictionary

How do I properly set the Datetimeindex for a Pandas datetime object in a dataframe?

To simplify Kirubaharan's answer a bit:

df['Datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'])
df = df.set_index('Datetime')

And to get rid of unwanted columns (as OP did but did not specify per se in the question):

df = df.drop(['date','time'], axis=1)

How to align td elements in center

Give a style inside the td element or in your scss file, like this:

vertical-align: 
    middle;

python catch exception and continue try block

While the other answers and the accepted one are correct and should be followed in real code, just for completeness and humor, you can try the fuckitpy ( https://github.com/ajalt/fuckitpy ) module.

Your code can be changed to the following:

@fuckitpy
def myfunc():
    do_smth1()
    do_smth2()

Then calling myfunc() would call do_smth2() even if there is an exception in do_smth1())

Note: Please do not try it in any real code, it is blasphemy

How do I catch an Ajax query post error?

jQuery 1.5 added deferred objects that handle this nicely. Simply call $.post and attach any handlers you'd like after the call. Deferred objects even allow you to attach multiple success and error handlers.

Example:

$.post('status.ajax.php', {deviceId: id})
    .done( function(msg) { ... } )
    .fail( function(xhr, textStatus, errorThrown) {
        alert(xhr.responseText);
    });

Prior to jQuery 1.8, the function done was called success and fail was called error.

Properties file with a list as the value for an individual key

There's probably a another way or better. But this is how I do this in Spring Boot.

My property file contains the following lines. "," is the delimiter in each line.

mml.pots=STDEP:DETY=LI3;,STDEP:DETY=LIMA;
mml.isdn.grunntengingar=STDEP:DETY=LIBAE;,STDEP:DETY=LIBAMA;
mml.isdn.stofntengingar=STDEP:DETY=LIPRAE;,STDEP:DETY=LIPRAM;,STDEP:DETY=LIPRAGS;,STDEP:DETY=LIPRVGS;

My server config

@Configuration
public class ServerConfig {

    @Inject
    private Environment env;

    @Bean
    public MMLProperties mmlProperties() {
        MMLProperties properties = new MMLProperties();
        properties.setMmmlPots(env.getProperty("mml.pots"));
        properties.setMmmlPots(env.getProperty("mml.isdn.grunntengingar"));
        properties.setMmmlPots(env.getProperty("mml.isdn.stofntengingar"));
        return properties;
    }
}

MMLProperties class.

public class MMLProperties {
    private String mmlPots;
    private String mmlIsdnGrunntengingar;
    private String mmlIsdnStofntengingar;

    public MMLProperties() {
        super();
    }

    public void setMmmlPots(String mmlPots) {
        this.mmlPots = mmlPots;
    }

    public void setMmlIsdnGrunntengingar(String mmlIsdnGrunntengingar) {
        this.mmlIsdnGrunntengingar = mmlIsdnGrunntengingar;
    }

    public void setMmlIsdnStofntengingar(String mmlIsdnStofntengingar) {
        this.mmlIsdnStofntengingar = mmlIsdnStofntengingar;
    }

    // These three public getXXX functions then take care of spliting the properties into List
    public List<String> getMmmlCommandForPotsAsList() {
        return getPropertieAsList(mmlPots);
    }

    public List<String> getMmlCommandsForIsdnGrunntengingarAsList() {
        return getPropertieAsList(mmlIsdnGrunntengingar);
    }

    public List<String> getMmlCommandsForIsdnStofntengingarAsList() {
        return getPropertieAsList(mmlIsdnStofntengingar);
    }

    private List<String> getPropertieAsList(String propertie) {
        return ((propertie != null) || (propertie.length() > 0))
        ? Arrays.asList(propertie.split("\\s*,\\s*"))
        : Collections.emptyList();
    }
}

Then in my Runner class I Autowire MMLProperties

@Component
public class Runner implements CommandLineRunner {

    @Autowired
    MMLProperties mmlProperties;

    @Override
    public void run(String... arg0) throws Exception {
        // Now I can call my getXXX function to retrieve the properties as List
        for (String command : mmlProperties.getMmmlCommandForPotsAsList()) {
            System.out.println(command);
        }
    }
}

Hope this helps

How does data binding work in AngularJS?

Obviously there is no periodic checking of Scope whether there is any change in the Objects attached to it. Not all the objects attached to scope are watched . Scope prototypically maintains a $$watchers . Scope only iterates through this $$watchers when $digest is called .

Angular adds a watcher to the $$watchers for each of these

  1. {{expression}} — In your templates (and anywhere else where there’s an expression) or when we define ng-model.
  2. $scope.$watch(‘expression/function’) — In your JavaScript we can just attach a scope object for angular to watch.

$watch function takes in three parameters:

  1. First one is a watcher function which just returns the object or we can just add an expression.

  2. Second one is a listener function which will be called when there is a change in the object. All the things like DOM changes will be implemented in this function.

  3. The third being an optional parameter which takes in a boolean . If its true , angular deep watches the object & if its false Angular just does a reference watching on the object. Rough Implementation of $watch looks like this

Scope.prototype.$watch = function(watchFn, listenerFn) {
   var watcher = {
       watchFn: watchFn,
       listenerFn: listenerFn || function() { },
       last: initWatchVal  // initWatchVal is typically undefined
   };
   this.$$watchers.push(watcher); // pushing the Watcher Object to Watchers  
};

There is an interesting thing in Angular called Digest Cycle. The $digest cycle starts as a result of a call to $scope.$digest(). Assume that you change a $scope model in a handler function through the ng-click directive. In that case AngularJS automatically triggers a $digest cycle by calling $digest().In addition to ng-click, there are several other built-in directives/services that let you change models (e.g. ng-model, $timeout, etc) and automatically trigger a $digest cycle. The rough implementation of $digest looks like this.

Scope.prototype.$digest = function() {
      var dirty;
      do {
          dirty = this.$$digestOnce();
      } while (dirty);
}
Scope.prototype.$$digestOnce = function() {
   var self = this;
   var newValue, oldValue, dirty;
   _.forEach(this.$$watchers, function(watcher) {
          newValue = watcher.watchFn(self);
          oldValue = watcher.last;   // It just remembers the last value for dirty checking
          if (newValue !== oldValue) { //Dirty checking of References 
   // For Deep checking the object , code of Value     
   // based checking of Object should be implemented here
             watcher.last = newValue;
             watcher.listenerFn(newValue,
                  (oldValue === initWatchVal ? newValue : oldValue),
                   self);
          dirty = true;
          }
     });
   return dirty;
 };

If we use JavaScript’s setTimeout() function to update a scope model, Angular has no way of knowing what you might change. In this case it’s our responsibility to call $apply() manually, which triggers a $digest cycle. Similarly, if you have a directive that sets up a DOM event listener and changes some models inside the handler function, you need to call $apply() to ensure the changes take effect. The big idea of $apply is that we can execute some code that isn't aware of Angular, that code may still change things on the scope. If we wrap that code in $apply , it will take care of calling $digest(). Rough implementation of $apply().

Scope.prototype.$apply = function(expr) {
       try {
         return this.$eval(expr); //Evaluating code in the context of Scope
       } finally {
         this.$digest();
       }
};

How can I select all children of an element except the last child?

Nick Craver's solution works but you can also use this:

:nth-last-child(n+2) { /* Your code here */ }

Chris Coyier of CSS Tricks made a nice :nth tester for this.

how to load CSS file into jsp

You can write like that. This is for whenever you change context path you don't need to modify your jsp file.

<link rel="stylesheet" href="${pageContext.request.contextPath}/css/styles.css" />

Returning JSON object as response in Spring Boot

you can also use a hashmap for this

@GetMapping
public HashMap<String, Object> get() {
    HashMap<String, Object> map = new HashMap<>();
    map.put("key1", "value1");
    map.put("results", somePOJO);
    return map;
}

Maven: How to run a .java file from command line passing arguments

You could run: mvn exec:exec -Dexec.args="arg1".

This will pass the argument arg1 to your program.

You should specify the main class fully qualified, for example, a Main.java that is in a package test would need

mvn exec:java  -Dexec.mainClass=test.Main

By using the -f parameter, as decribed here, you can also run it from other directories.

mvn exec:java -Dexec.mainClass=test.Main -f folder/pom.xm

For multiple arguments, simply separate them with a space as you would at the command line.

mvn exec:java -Dexec.mainClass=test.Main -Dexec.args="arg1 arg2 arg3"

For arguments separated with a space, you can group using 'argument separated with space' inside the quotation marks.

mvn exec:java -Dexec.mainClass=test.Main -Dexec.args="'argument separated with space' 'another one'"

On design patterns: When should I use the singleton?

An example with code, perhaps.

Here, the ConcreteRegistry is a singleton in a poker game that allows the behaviours all the way up the package tree access the few, core interfaces of the game (i.e., the facades for the model, view, controller, environment, etc.):

http://www.edmundkirwan.com/servlet/fractal/cs1/frac-cs40.html

Ed.

How do I serialize a C# anonymous type to a JSON string?

Assuming you are using this for a web service, you can just apply the following attribute to the class:

[System.Web.Script.Services.ScriptService]

Then the following attribute to each method that should return Json:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]

And set the return type for the methods to be "object"

How to get previous month and year relative to today, using strtotime and date?

If you want the previous year and month relative to a specific date and have DateTime available then you can do this:

$d = new DateTime('2013-01-01', new DateTimeZone('UTC')); 
$d->modify('first day of previous month');
$year = $d->format('Y'); //2012
$month = $d->format('m'); //12

Finding row index containing maximum value using R

See ?which.max

> which.max( matrix[,2] )
[1] 2

Composer - the requested PHP extension mbstring is missing from your system

I set the PHPRC variable and uncommented zend_extension=php_opcache.dll in php.ini and all works well.

How can you get the first digit in an int (C#)?

Very easy method to get the Last digit:

int myInt = 1821;

int lastDigit = myInt - ((myInt/10)*10); // 1821 - 1820 = 1

What’s the best way to check if a file exists in C++? (cross platform)

Use boost::filesystem:

#include <boost/filesystem.hpp>

if ( !boost::filesystem::exists( "myfile.txt" ) )
{
  std::cout << "Can't find my file!" << std::endl;
}

How to change a package name in Eclipse?

Android app package name?

Just for the record, my case concerned an android app so if it concerns renaming the package name in an android application, then you can do it directly from the AndroidManifest.xml file, it's the first field in the android manifest, you change your package name and update it. Then if it shows you errors, so just "clean" your project in the "project" menu.

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

Goal: save a piece of one file to another file.

Solution:

  1. Select the text you want to save:
    • Position the cursor where you want to start selection
    • Press v to select characters OR uppercase V to select whole lines
    • Move the cursor to the end of what you want to select
  2. Save selected text to the new file. Type :wSpace and the name of the new file. Actually you'll see

    :'<,'>w new.txt

    Then press Enter

How to pass command line arguments to a rake task

Options and dependencies need to be inside arrays:

namespace :thing do
  desc "it does a thing"
  task :work, [:option, :foo, :bar] do |task, args|
    puts "work", args
  end
  
  task :another, [:option, :foo, :bar] do |task, args|
    puts "another #{args}"
    Rake::Task["thing:work"].invoke(args[:option], args[:foo], args[:bar])
    # or splat the args
    # Rake::Task["thing:work"].invoke(*args)
  end

end

Then

rake thing:work[1,2,3]
=> work: {:option=>"1", :foo=>"2", :bar=>"3"}

rake thing:another[1,2,3]
=> another {:option=>"1", :foo=>"2", :bar=>"3"}
=> work: {:option=>"1", :foo=>"2", :bar=>"3"}

NOTE: variable task is the task object, not very helpful unless you know/care about Rake internals.

RAILS NOTE:

If running the task from Rails, it's best to preload the environment by adding => [:environment] which is a way to setup dependent tasks.

  task :work, [:option, :foo, :bar] => [:environment] do |task, args|
    puts "work", args
  end

Difference between Width:100% and width:100vw?

You can solve this issue be adding max-width:

#element {
   width: 100vw;
   height: 100vw;
   max-width: 100%;
}

When you using CSS to make the wrapper full width using the code width: 100vw; then you will notice a horizontal scroll in the page, and that happened because the padding and margin of html and body tags added to the wrapper size, so the solution is to add max-width: 100%

How to access accelerometer/gyroscope data from Javascript?

There are currently three distinct events which may or may not be triggered when the client devices moves. Two of them are focused around orientation and the last on motion:

  • ondeviceorientation is known to work on the desktop version of Chrome, and most Apple laptops seems to have the hardware required for this to work. It also works on Mobile Safari on the iPhone 4 with iOS 4.2. In the event handler function, you can access alpha, beta, gamma values on the event data supplied as the only argument to the function.

  • onmozorientation is supported on Firefox 3.6 and newer. Again, this is known to work on most Apple laptops, but might work on Windows or Linux machines with accelerometer as well. In the event handler function, look for x, y, z fields on the event data supplied as first argument.

  • ondevicemotion is known to work on iPhone 3GS + 4 and iPad (both with iOS 4.2), and provides data related to the current acceleration of the client device. The event data passed to the handler function has acceleration and accelerationIncludingGravity, which both have three fields for each axis: x, y, z

The "earthquake detecting" sample website uses a series of if statements to figure out which event to attach to (in a somewhat prioritized order) and passes the data received to a common tilt function:

if (window.DeviceOrientationEvent) {
    window.addEventListener("deviceorientation", function () {
        tilt([event.beta, event.gamma]);
    }, true);
} else if (window.DeviceMotionEvent) {
    window.addEventListener('devicemotion', function () {
        tilt([event.acceleration.x * 2, event.acceleration.y * 2]);
    }, true);
} else {
    window.addEventListener("MozOrientation", function () {
        tilt([orientation.x * 50, orientation.y * 50]);
    }, true);
}

The constant factors 2 and 50 are used to "align" the readings from the two latter events with those from the first, but these are by no means precise representations. For this simple "toy" project it works just fine, but if you need to use the data for something slightly more serious, you will have to get familiar with the units of the values provided in the different events and treat them with respect :)

Difference between a user and a schema in Oracle?

User: Access to resource of the database. Like a key to enter a house.

Schema: Collection of information about database objects. Like Index in your book which contains the short information about the chapter.

Look here for details

How can I upgrade NumPy?

After installing pytorch, I got a similar error when I used:

import torch

Removing NumPy didn't help (I actually renamed NumPy, so I reverted back after it didn't work). The following commands worked for me:

sudo pip install numpy --upgrade
sudo easy_install numpy

how to use a like with a join in sql?

In MySQL you could try:

SELECT * FROM A INNER JOIN B ON B.MYCOL LIKE CONCAT('%', A.MYCOL, '%');

Of course this would be a massively inefficient query because it would do a full table scan.

Update: Here's a proof


create table A (MYCOL varchar(255));
create table B (MYCOL varchar(255));
insert into A (MYCOL) values ('foo'), ('bar'), ('baz');
insert into B (MYCOL) values ('fooblah'), ('somethingfooblah'), ('foo');
insert into B (MYCOL) values ('barblah'), ('somethingbarblah'), ('bar');
SELECT * FROM A INNER JOIN B ON B.MYCOL LIKE CONCAT('%', A.MYCOL, '%');
+-------+------------------+
| MYCOL | MYCOL            |
+-------+------------------+
| foo   | fooblah          |
| foo   | somethingfooblah |
| foo   | foo              |
| bar   | barblah          |
| bar   | somethingbarblah |
| bar   | bar              |
+-------+------------------+
6 rows in set (0.38 sec)

How do I put variables inside javascript strings?

Note, from 2015 onwards, just use backticks for templating

https://stackoverflow.com/a/37245773/294884

let a = `hello ${name}`    // NOTE!!!!!!!! ` not ' or "

Note that it is a backtick, not a quote.


If you want to have something similar, you could create a function:

function parse(str) {
    var args = [].slice.call(arguments, 1),
        i = 0;

    return str.replace(/%s/g, () => args[i++]);
}

Usage:

s = parse('hello %s, how are you doing', my_name);

This is only a simple example and does not take into account different kinds of data types (like %i, etc) or escaping of %s. But I hope it gives you some idea. I'm pretty sure there are also libraries out there which provide a function like this.

In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric

The error happens because of you are trying to map a numeric vector to data in geom_errorbar: GVW[1:64,3]. ggplot only works with data.frame.

In general, you shouldn't subset inside ggplot calls. You are doing so because your standard errors are stored in four separate objects. Add them to your original data.frame and you will be able to plot everything in one call.

Here with a dplyr solution to summarise the data and compute the standard error beforehand.

library(dplyr)
d <- GVW %>% group_by(Genotype,variable) %>%
    summarise(mean = mean(value),se = sd(value) / sqrt(n()))

ggplot(d, aes(x = variable, y = mean, fill = Genotype)) + 
  geom_bar(position = position_dodge(), stat = "identity", 
      colour="black", size=.3) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se), 
      size=.3, width=.2, position=position_dodge(.9)) +
  xlab("Time") +
  ylab("Weight [g]") +
  scale_fill_hue(name = "Genotype", breaks = c("KO", "WT"), 
      labels = c("Knock-out", "Wild type")) +
  ggtitle("Effect of genotype on weight-gain") +
  scale_y_continuous(breaks = 0:20*4) +
  theme_bw()

setting JAVA_HOME & CLASSPATH in CentOS 6

Providing javac is set up through /etc/alternatives/javac, you can add to your .bash_profile:

JAVA_HOME=$(l=$(which javac) ; while : ; do nl=$(readlink ${l}) ; [ "$nl" ] || break ; l=$nl ; done ; echo $(cd $(dirname $l)/.. ; pwd) )
export JAVA_HOME

Excel 2007: How to display mm:ss format not as a DateTime (e.g. 73:07)?

as text:

=CONCATENATE(TEXT(cell;"d");" days ";TEXT(cell;"t");" hours ";MID(TEXT(cell;"hh:mm:ss");4;2);" minutes ";TEXT(cell;"s");" seconds")

Animation CSS3: display + opacity

display: is not transitionable. You'll probably need to use jQuery to do what you want to do.

How can I check if a user is logged-in in php?

Logins are not too complicated, but there are some specific pieces that almost all login processes need.

First, make sure you enable the session variable on all pages that require knowledge of logged-in status by putting this at the beginning of those pages:

session_start();

Next, when the user submits their username and password via the login form, you will typically check their username and password by querying a database containing username and password information, such as MySQL. If the database returns a match, you can then set a session variable to contain that fact. You might also want to include other information:

if (match_found_in_database()) {
    $_SESSION['loggedin'] = true;
    $_SESSION['username'] = $username; // $username coming from the form, such as $_POST['username']
                                       // something like this is optional, of course
}

Then, on the page that depends on logged-in status, put the following (don't forget the session_start()):

if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
    echo "Welcome to the member's area, " . $_SESSION['username'] . "!";
} else {
    echo "Please log in first to see this page.";
}

Those are the basic components. If you need help with the SQL aspect, there are tutorials-a-plenty around the net.

How to unzip a list of tuples into individual lists?

If you want a list of lists:

>>> [list(t) for t in zip(*l)]
[[1, 3, 8], [2, 4, 9]]

If a list of tuples is OK:

>>> zip(*l)
[(1, 3, 8), (2, 4, 9)]

Display last git commit comment

If you want to see just the subject (first line) of the commit message:

git log -1 --format=%s

This was not previously documented in any answer. Alternatively, the approach by nos also shows it.

Reference:

Removing elements from array Ruby

You may do:

a= [1,1,1,2,2,3]
delete_list = [1,3]
delete_list.each do |del|
    a.delete_at(a.index(del))
end

result : [1, 1, 2, 2]

range() for floats

There several answers here that don't handle simple edge cases like negative step, wrong start, stop etc. Here's the version that handles many of these cases correctly giving same behaviour as native range():

def frange(start, stop=None, step=1):
  if stop is None:
    start, stop = 0, start
  steps = int((stop-start)/step)
  for i in range(steps):
    yield start
    start += step  

Note that this would error out step=0 just like native range. One difference is that native range returns object that is indexable and reversible while above doesn't.

You can play with this code and test cases here.

<hr> tag in Twitter Bootstrap not functioning correctly?

Instead of writing

<hr>

Write

<hr class="col-xs-12">

And it will display full width as normal.

Reading Excel file using node.js

You can also use this node module called js-xlsx

1) Install module
npm install xlsx

2) Import module + code snippet

var XLSX = require('xlsx')
var workbook = XLSX.readFile('Master.xlsx');
var sheet_name_list = workbook.SheetNames;
var xlData = XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]);
console.log(xlData);

Read from file in eclipse

Did you try refreshing (right click -> refresh) the project folder after copying the file in there? That will SYNC your file system with Eclipse's internal file system.

When you run Eclipse projects, the CWD (current working directory) is project's root directory. Not bin's directory. Not src's directory, but the root dir.

Also, if you're in Linux, remember that its file systems are usually case sensitive.

How do I tell matplotlib that I am done with a plot?

If none of them are working then check this.. say if you have x and y arrays of data along respective axis. Then check in which cell(jupyter) you have initialized x and y to empty. This is because , maybe you are appending data to x and y without re-initializing them. So plot has old data too. So check that..

How to create JSON string in C#

Encode Usage

Simple object to JSON Array EncodeJsObjectArray()

public class dummyObject
{
    public string fake { get; set; }
    public int id { get; set; }

    public dummyObject()
    {
        fake = "dummy";
        id = 5;
    }

    public override string ToString()
    {
        StringBuilder sb = new StringBuilder();
        sb.Append('[');
        sb.Append(id);
        sb.Append(',');
        sb.Append(JSONEncoders.EncodeJsString(fake));
        sb.Append(']');

        return sb.ToString();
    }
}

dummyObject[] dummys = new dummyObject[2];
dummys[0] = new dummyObject();
dummys[1] = new dummyObject();

dummys[0].fake = "mike";
dummys[0].id = 29;

string result = JSONEncoders.EncodeJsObjectArray(dummys);

Result: [[29,"mike"],[5,"dummy"]]

Pretty Usage

Pretty print JSON Array PrettyPrintJson() string extension method

string input = "[14,4,[14,\"data\"],[[5,\"10.186.122.15\"],[6,\"10.186.122.16\"]]]";
string result = input.PrettyPrintJson();

Results is:

[
   14,
   4,
   [
      14,
      "data"
   ],
   [
      [
         5,
         "10.186.122.15"
      ],
      [
         6,
         "10.186.122.16"
      ]
   ]
]

java.lang.NoClassDefFoundError: org/json/JSONObject

Please add the following dependency http://mvnrepository.com/artifact/org.json/json/20080701

<dependency>
   <groupId>org.json</groupId>
   <artifactId>json</artifactId>
   <version>20080701</version>
</dependency>

Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation

I had a similar requirement; documenting my approach here for anyone with a similar scenario...

Scenario

  • I have a database from a clean install with the correct collations.
  • I have another database which has the wrong collations.
  • I need to update the latter to use the collations defined on the former.

Solution

Use SQL Server Schema Comparison (from SQL Server Data Tools / Visual Studio) to compare source (clean install) with destination (the db with invalid collation).

In my case I compared the two DBs directly; though you could work via a project to allow you to manually tweak pieces in between...

  • Run Visual Studio
  • Create a new SQL Server Data Project
  • Click Tools, SQL Server, New Schema Comparison
  • Select the source database
  • Select the target database
  • Click options (?)
    • Under Object Types select only those types you're interested in (for me it was only Views and Tables)
    • Under General select:
      • Block on possible data loss
      • Disable & reenable DDL triggers
      • Ignore cryptographic provider file path
      • Ignore File & Log File Path
      • Ignore file size
      • Ignore filegroup placement
      • Ignore full text catalog file path
      • Ignore keyword casing
      • Ignore login SIDs
      • Ignore quoted identifiers
      • Ignore route lifetime
      • Ignore semicolon between statements
      • Ignore whitespace
      • Script refresh module
      • Script validation for new constraints
      • Verify collation compatibility
      • Verify deployment
  • Click Compare
    • Uncheck any objects flagged for deletion (NB: those may still have collation issues; but since they're not defined in our source/template db we don't know; either way, we don't want to lose things if we're only targeting collation changes). You can unchceck all at once by right clicking on the DELETE folder and selecting EXCLUDE.
    • Likewise exclude for any CREATE objects (here since they don't exist in the target they can't have the wrong collation there; whether they should exist is a question for another topic).
    • Click on each object under CHANGE to see the script for that object. Use the diff to ensure that we're only changing the collation (anything other differences manually detected you'll likely want to exclude / handle those objects manually).
  • Click Update to push changes

This does still involve some manual effort (e.g. checking that you're only impacting the collation) - but it handles dependencies for you.

Also you can keep a database project of the valid schema so you can use a universal template for your DBs should you have more than 1 to update, assuming all target DBs should end up with the same schema.

You can also use find/replace on the files in a database project should you wish to mass amend settings there (e.g. so you could create the project from the invalid database using schema compare, amend the project files, then toggle the source/target in the schema compare to push your changes back to the DB).

Assigning a function to a variable

when you perform y=x() you are actually assigning y to the result of calling the function object x and the function has a return value of None. Function calls in python are performed using (). To assign x to y so you can call y just like you would x you assign the function object x to y like y=x and call the function using y()

Install opencv for Python 3.3

EDIT: first try the new pip method:

Windows: pip3 install opencv-python opencv-contrib-python

Ubuntu: sudo apt install python3-opencv

or continue below for build instructions

Note: The original question was asking for OpenCV + Python 3.3 + Windows. Since then, Python 3.5 has been released. In addition, I use Ubuntu for most development so this answer will focus on that setup, unfortunately

OpenCV 3.1.0 + Python 3.5.2 + Ubuntu 16.04 is possible! Here's how.

These steps are copied (and slightly modified) from:

Prerequisites

Install the required dependencies and optionally install/update some libraries on your system:

# Required dependencies
sudo apt install build-essential cmake git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev
# Dependencies for Python bindings
# If you use a non-system copy of Python (eg. with pyenv or virtualenv), then you probably don't need to do this part
sudo apt install python3.5-dev libpython3-dev python3-numpy
# Optional, but installing these will ensure you have the latest versions compiled with OpenCV
sudo apt install libtbb2 libtbb-dev libjpeg-dev libpng-dev libtiff-dev libjasper-dev libdc1394-22-dev

Building OpenCV

CMake Flags

There are several flags and options to tweak your build of OpenCV. There might be comprehensive documentation about them, but here are some interesting flags that may be of use. They should be included in the cmake command:

# Builds in TBB, a threading library
-D WITH_TBB=ON
# Builds in Eigen, a linear algebra library
-D WITH_EIGEN=ON

Using non-system level Python versions

If you have multiple versions of Python (eg. from using pyenv or virtualenv), then you may want to build against a certain Python version. By default OpenCV will build for the system's version of Python. You can change this by adding these arguments to the cmake command seen later in the script. Actual values will depend on your setup. I use pyenv:

-D PYTHON_DEFAULT_EXECUTABLE=$HOME/.pyenv/versions/3.5.2/bin/python3.5
-D PYTHON_INCLUDE_DIRS=$HOME/.pyenv/versions/3.5.2/include/python3.5m
-D PYTHON_EXECUTABLE=$HOME/.pyenv/versions/3.5.2/bin/python3.5
-D PYTHON_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython3.5m.so.1

CMake Python error messages

The CMakeLists file will try to detect various versions of Python to build for. If you've got different versions here, it might get confused. The above arguments may only "fix" the issue for one version of Python but not the other. If you only care about that specific version, then there's nothing else to worry about.

This is the case for me so unfortunately, I haven't looked into how to resolve the issues with other Python versions.

Install script

# Clone OpenCV somewhere
# I'll put it into $HOME/code/opencv
OPENCV_DIR="$HOME/code/opencv"
OPENCV_VER="3.1.0"
git clone https://github.com/opencv/opencv "$OPENCV_DIR"
# This'll take a while...

# Now lets checkout the specific version we want
cd "$OPENCV_DIR"
git checkout "$OPENCV_VER"

# First OpenCV will generate the files needed to do the actual build.
# We'll put them in an output directory, in this case "release"
mkdir release
cd release

# Note: This is where you'd add build options, like TBB support or custom Python versions. See above sections.
cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local "$OPENCV_DIR"

# At this point, take a look at the console output.
# OpenCV will print a report of modules and features that it can and can't support based on your system and installed libraries.
# The key here is to make sure it's not missing anything you'll need!
# If something's missing, then you'll need to install those dependencies and rerun the cmake command.

# OK, lets actually build this thing!
# Note: You can use the "make -jN" command, which will run N parallel jobs to speed up your build. Set N to whatever your machine can handle (usually <= the number of concurrent threads your CPU can run).
make
# This will also take a while...

# Now install the binaries!
sudo make install

By default, the install script will put the Python bindings in some system location, even if you've specified a custom version of Python to use. The fix is simple: Put a symlink to the bindings in your local site-packages:

ln -s /usr/local/lib/python3.5/site-packages/cv2.cpython-35m-x86_64-linux-gnu.so $HOME/.pyenv/versions/3.5.2/lib/python3.5/site-packages/

The first path will depend on the Python version you setup to build. The second depends on where your custom version of Python is located.

Test it!

OK lets try it out!

ipython

Python 3.5.2 (default, Sep 24 2016, 13:13:17) 
Type "copyright", "credits" or "license" for more information.

IPython 5.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import cv2

In [2]: img = cv2.imread('derp.png')
i
In [3]: img[0]
Out[3]: 
array([[26, 30, 31],
       [27, 31, 32],
       [27, 31, 32],
       ..., 
       [16, 19, 20],
       [16, 19, 20],
       [16, 19, 20]], dtype=uint8)

How to see the actual Oracle SQL statement that is being executed

Sorry for the short answer but it is late. Google "oracle event 10046 sql trace". It would be best to trace an individual session because figuring which SQL belongs to which session from v$sql is no easy if it is shared sql and being used by multiple users.

If you want to impress your Oracle DBA friends, learn how to set an oracle trace with event 10046, interpret the meaning of the wait events and find the top cpu consumers.

Quest had a free product that allowed you to capture the SQL as it went out from the client side but not sure if it works with your product/version of Oracle. Google "quest oracle sql monitor" for this.

Good night.

Babel 6 regeneratorRuntime is not defined

There are so many answers up there, I will post my answer for my reference. I use webpack and react, here is my solution without the .babelrc file

I am working on this in Aug 2020

Install react and babel

npm i @babel/core babel-loader @babel/preset-env @babel/preset-react react react-dom @babel/plugin-transform-runtime --save-dev

Then in my webpack.config.js

// other stuff
module.exports = {
// other stuff

   module: {
   rules: [
  
   {
    test: /\.m?js$/,
    exclude: /(node_modules|bower_components)/,
    use: {
      loader: 'babel-loader',
      options: {
        presets: ['@babel/preset-env',"@babel/preset-react"],
        plugins: ['@babel/plugin-proposal-class-properties', '@babel/plugin-transform-runtime'],
        //npm install --save-dev @babel/plugin-transform-runtime
          }
        }
      },
    ],
  },

};

I just don't know why I dont need to install the async package for the moment

LaTeX: Multiple authors in a two-column article

I put together a little test here:

\documentclass[10pt,twocolumn]{article}

\title{Article Title}
\author{
    First Author\\
    Department\\
    school\\
    email@edu
  \and
    Second Author\\
    Department\\
    school\\
    email@edu
    \and
    Third Author\\
    Department\\
    school\\
    email@edu
    \and
    Fourth Author\\
    Department\\
    school\\
    email@edu
}
\date{\today}

\begin{document}

\maketitle

\begin{abstract}
\ldots
\end{abstract}

\section{Introduction}
\ldots

\end{document}

Things to note, the title, author and date fields are declared before \begin{document}. Also, the multicol package is likely unnecessary in this case since you have declared twocolumn in the document class.

This example puts all four authors on the same line, but if your authors have longer names, departments or emails, this might cause it to flow over onto another line. You might be able to change the font sizes around a little bit to make things fit. This could be done by doing something like {\small First Author}. Here's a more detailed article on \LaTeX font sizes:

https://engineering.purdue.edu/ECN/Support/KB/Docs/LaTeXChangingTheFont

To italicize you can use {\it First Name} or \textit{First Name}.

Be careful though, if the document is meant for publication often times journals or conference proceedings have their own formatting guidelines so font size trickery might not be allowed.

Storing and displaying unicode string (??????) using PHP and MySQL

For Those who are facing difficulty just got to php admin and change collation to utf8_general_ci Select Table go to Operations>> table options>> collations should be there

How to link html pages in same or different folders?

Also, this will go up a directory and then back down to another subfolder.

<a href = "../subfolder/page.html">link</a>

To go up multiple directories you can do this.

<a href = "../../page.html">link</a>

To go the root, I use this

<a href = "~/page.html">link</a>

Bootstrap 3 collapsed menu doesn't close on click

I did

$(".navbar-toggle").click(function(event) {
    $(".navbar-collapse").toggle('in');
});

How to declare an array of objects in C#

The reason this is happening is because initializing an array does not initialize each element in that array. You need to first set houses[0] = new GameObject() and then it will work.

How to multiply a BigDecimal by an integer in Java

You have a lot of type-mismatches in your code such as trying to put an int value where BigDecimal is required. The corrected version of your code:

public class Payment
{
    BigDecimal itemCost  = BigDecimal.ZERO;
    BigDecimal totalCost = BigDecimal.ZERO;

    public BigDecimal calculateCost(int itemQuantity, BigDecimal itemPrice)
    {
        itemCost  = itemPrice.multiply(new BigDecimal(itemQuantity));
        totalCost = totalCost.add(itemCost);
        return totalCost;
    }
}

git with IntelliJ IDEA: Could not read from remote repository

  1. Go to Settings->Git->Select Native in SSH executable dropdown. (If it is not selected)
  2. Copy HTTPS link from your Github repository.
  3. Go to VCS->Git->Remotes..
  4. Edit the origin and Paste HTTPS link in the URL field.
  5. Press Ctrl+Shift+k and push the project to repository. It works.

How to enable LogCat/Console in Eclipse for Android?

In the "Window" menu, open "Open Perspective" -> "Debug".

alt text click On the plus image icon(you see the below image at status bar), and then select "Logcat"....

Get img src with PHP

There could be two easy solutions:

  1. HTML it self is an xml so you can use any XML parsing method if u load the tag as XML and get its attribute tottally dynamically even dom data attribute (like data-time or anything).....
  2. Use any html parser for php like http://mbe.ro/2009/06/21/php-html-to-array-working-one/ or php parse html to array Google this

What is a blob URL and why it is used?

What is blob url? Why it is used?

BLOB is just byte sequence. Browser recognize it as byte stream. It is used to get byte stream from source.

A Blob object represents a file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.

Can i make my own blob url on a server?

Yes you can there are serveral ways to do so for example try http://php.net/manual/en/function.ibase-blob-echo.php

Read more on

How can I change the color of a Google Maps marker?

enter image description here enter image description here Material Design

EDITED MARCH 2019 now with programmatic pin color,

PURE JAVASCRIPT, NO IMAGES, SUPPORTS LABELS

no longer relies on deprecated Charts API

    var pinColor = "#FFFFFF";
    var pinLabel = "A";

    // Pick your pin (hole or no hole)
    var pinSVGHole = "M12,11.5A2.5,2.5 0 0,1 9.5,9A2.5,2.5 0 0,1 12,6.5A2.5,2.5 0 0,1 14.5,9A2.5,2.5 0 0,1 12,11.5M12,2A7,7 0 0,0 5,9C5,14.25 12,22 12,22C12,22 19,14.25 19,9A7,7 0 0,0 12,2Z";
    var labelOriginHole = new google.maps.Point(12,15);
    var pinSVGFilled = "M 12,2 C 8.1340068,2 5,5.1340068 5,9 c 0,5.25 7,13 7,13 0,0 7,-7.75 7,-13 0,-3.8659932 -3.134007,-7 -7,-7 z";
    var labelOriginFilled =  new google.maps.Point(12,9);


    var markerImage = {  // https://developers.google.com/maps/documentation/javascript/reference/marker#MarkerLabel
        path: pinSVGFilled,
        anchor: new google.maps.Point(12,17),
        fillOpacity: 1,
        fillColor: pinColor,
        strokeWeight: 2,
        strokeColor: "white",
        scale: 2,
        labelOrigin: labelOriginFilled
    };
    var label = {
        text: pinLabel,
        color: "white",
        fontSize: "12px",
    }; // https://developers.google.com/maps/documentation/javascript/reference/marker#Symbol
    this.marker        = new google.maps.Marker({
        map: map.MapObject,
        //OPTIONAL: label: label,
        position: this.geographicCoordinates,
        icon: markerImage,
        //OPTIONAL: animation: google.maps.Animation.DROP,
    });

An example of how to use getopts in bash

Use getopt

Why getopt?

To parse elaborated command-line arguments to avoid confusion and clarify the options we are parsing so that reader of the commands can understand what's happening.

What is getopt?

getopt is used to break up (parse) options in command lines for easy parsing by shell procedures, and to check for legal options. It uses the GNU getopt(3) routines to do this.

getopt can have following types of options.

  1. No-value options
  2. key-value pair options

Note: In this document, during explaining syntax:

  • Anything inside [ ] is optional parameter in the syntax/examples.
  • is a place holder, which mean it should be substituted with an actual value.

HOW TO USE getopt?

Syntax: First Form

getopt optstring parameters

Examples:

# This is correct
getopt "hv:t::" "-v 123 -t123"  
getopt "hv:t::" "-v123 -t123"  # -v and 123 doesn't have whitespace

# -h takes no value.
getopt "hv:t::" "-h -v123"


# This is wrong. after -t can't have whitespace.
# Only optional params cannot have whitespace between key and value
getopt "hv:t::" "-v 123 -t 123"

# Multiple arguments that takes value.
getopt "h:v:t::g::" "-h abc -v 123 -t21"

# Multiple arguments without value
# All of these are correct
getopt "hvt" "-htv"
getopt "hvt" "-h -t -v"
getopt "hvt" "-tv -h"

Here h,v,t are the options and -h -v -t is how options should be given in command-line.

  1. 'h' is a no-value option.
  2. 'v:' implies that option -v has value and is a mandatory option. ':' means has a value.
  3. 't::' implies that option -t has value but is optional. '::' means optional.

In optional param, value cannot have whitespace separation with the option. So, in "-t123" example, -t is option 123 is value.

Syntax: Second Form

getopt [getopt_options] [--] [optstring] [parameters]

Here after getopt is split into five parts

  • The command itself i.e. getopt
  • The getopt_options, it describes how to parse the arguments. single dash long options, double dash options.
  • --, separates out the getopt_options from the options you want to parse and the allowed short options
  • The short options, is taken immediately after -- is found. Just like the Form first syntax.
  • The parameters, these are the options that you have passed into the program. The options you want to parse and get the actual values set on them.

Examples

getopt -l "name:,version::,verbose" -- "n:v::V" "--name=Karthik -version=5.2 -verbose"

Syntax: Third Form

getopt [getopt_options] [-o options] [--] [optstring] [parameters]

Here after getopt is split into five parts

  • The command itself i.e. getopt
  • The getopt_options, it describes how to parse the arguments. single dash long options, double dash options.
  • The short options i.e. -o or --options. Just like the Form first syntax but with option "-o" and before the "--" (double dash).
  • --, separates out the getopt_options from the options you want to parse and the allowed short options
  • The parameters, these are the options that you have passed into the program. The options you want to parse and get the actual values set on them.

Examples

getopt -l "name:,version::,verbose" -a -o "n:v::V" -- "-name=Karthik -version=5.2 -verbose"

GETOPT_OPTIONS

getopt_options changes the way command-line params are parsed.

Below are some of the getopt_options

Option: -l or --longoptions

Means getopt command should allow multi-character options to be recognised. Multiple options are separated by comma.

For example, --name=Karthik is a long option sent in command line. In getopt, usage of long options are like

getopt "name:,version" "--name=Karthik"

Since name: is specified, the option should contain a value

Option: -a or --alternative

Means getopt command should allow long option to have a single dash '-' rather than double dash '--'.

Example, instead of --name=Karthik you could use just -name=Karthik

getopt "name:,version" "-name=Karthik"

A complete script example with the code:

#!/bin/bash

# filename: commandLine.sh
# author: @theBuzzyCoder

showHelp() {
# `cat << EOF` This means that cat should stop reading when EOF is detected
cat << EOF  
Usage: ./installer -v <espo-version> [-hrV]
Install Pre-requisites for EspoCRM with docker in Development mode

-h, -help,          --help                  Display help

-v, -espo-version,  --espo-version          Set and Download specific version of EspoCRM

-r, -rebuild,       --rebuild               Rebuild php vendor directory using composer and compiled css using grunt

-V, -verbose,       --verbose               Run script in verbose mode. Will print out each step of execution.

EOF
# EOF is found above and hence cat command stops reading. This is equivalent to echo but much neater when printing out.
}


export version=0
export verbose=0
export rebuilt=0

# $@ is all command line parameters passed to the script.
# -o is for short options like -v
# -l is for long options with double dash like --version
# the comma separates different long options
# -a is for long options with single dash like -version
options=$(getopt -l "help,version:,verbose,rebuild,dryrun" -o "hv:Vrd" -a -- "$@")

# set --:
# If no arguments follow this option, then the positional parameters are unset. Otherwise, the positional parameters 
# are set to the arguments, even if some of them begin with a ‘-’.
eval set -- "$options"

while true
do
case $1 in
-h|--help) 
    showHelp
    exit 0
    ;;
-v|--version) 
    shift
    export version=$1
    ;;
-V|--verbose)
    export verbose=1
    set -xv  # Set xtrace and verbose mode.
    ;;
-r|--rebuild)
    export rebuild=1
    ;;
--)
    shift
    break;;
esac
shift
done

Running this script file:

# With short options grouped together and long option
# With double dash '--version'

bash commandLine.sh --version=1.0 -rV
# With short options grouped together and long option
# With single dash '-version'

bash commandLine.sh -version=1.0 -rV

# OR with short option that takes value, value separated by whitespace
# by key

bash commandLine.sh -v 1.0 -rV

# OR with short option that takes value, value without whitespace
# separation from key.

bash commandLine.sh -v1.0 -rV

# OR Separating individual short options

bash commandLine.sh -v1.0 -r -V

Where does Git store files?

usually it goes to Documents folder in windows : C:\Users\<"name of user account">\Documents\GitHub

How to set env variable in Jupyter notebook

To set an env variable in a jupyter notebook, just use a % magic commands, either %env or %set_env, e.g., %env MY_VAR=MY_VALUE or %env MY_VAR MY_VALUE. (Use %env by itself to print out current environmental variables.)

See: http://ipython.readthedocs.io/en/stable/interactive/magics.html

How to check if dropdown is disabled?

The legacy solution, before 1.6, was to use .attr and handle the returned value as a bool. The main problem is that the returned type of .attr has changed to string, and therefore the comparison with == true is broken (see http://jsfiddle.net/2vene/1/ (and switch the jquery-version)).

With 1.6 .prop was introduced, which returns a bool.

Nevertheless, I suggest to use .is(), as the returned type is intrinsically bool, like:

$('#dropUnit').is(':disabled');
$('#dropUnit').is(':enabled');

Furthermore .is() is much more natural (in terms of "natural language") and adds more conditions than a simple attribute-comparison (eg: .is(':last'), .is(':visible'), ... please see documentation on selectors).

How to test REST API using Chrome's extension "Advanced Rest Client"

Add authorization header and click pencil button to enter username and passwords

enter image description here

How to add custom Http Header for C# Web Service Client consuming Axis 1.4 Web service

user334291's answer was a life saver for me. Just want to add how you can add what the OP originally intended to do (what I ended up using):

Overriding the GetWebRequest function on the generated webservice code:

protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
    System.Net.WebRequest request = base.GetWebRequest(uri);          
    string auth = "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(this.Credentials.GetCredential(uri, "Basic").UserName + ":" + this.Credentials.GetCredential(uri, "Basic").Password));
    request.Headers.Add("Authorization", auth);
    return request;
}

and setting the credentials before calling the webservice:

  client.Credentials = new NetworkCredential(user, password);       

elasticsearch bool query combine must with OR

I recently had to solve this problem too, and after a LOT of trial and error I came up with this (in PHP, but maps directly to the DSL):

'query' => [
    'bool' => [
        'should' => [
            ['prefix' => ['name_first' => $query]],
            ['prefix' => ['name_last' => $query]],
            ['prefix' => ['phone' => $query]],
            ['prefix' => ['email' => $query]],
            [
                'multi_match' => [
                    'query' => $query,
                    'type' => 'cross_fields',
                    'operator' => 'and',
                    'fields' => ['name_first', 'name_last']
                ]
            ]
        ],
        'minimum_should_match' => 1,
        'filter' => [
            ['term' => ['state' => 'active']],
            ['term' => ['company_id' => $companyId]]
        ]
    ]
]

Which maps to something like this in SQL:

SELECT * from <index> 
WHERE (
    name_first LIKE '<query>%' OR
    name_last LIKE '<query>%' OR
    phone LIKE  '<query>%' OR
    email LIKE '<query>%'
)
AND state = 'active'
AND company_id = <query>

The key in all this is the minimum_should_match setting. Without this the filter totally overrides the should.

Hope this helps someone!

Correlation between two vectors?

Given:

A_1 = [10 200 7 150]';
A_2 = [0.001 0.450 0.007 0.200]';

(As others have already pointed out) There are tools to simply compute correlation, most obviously corr:

corr(A_1, A_2);  %Returns 0.956766573975184  (Requires stats toolbox)

You can also use base Matlab's corrcoef function, like this:

M = corrcoef([A_1 A_2]):  %Returns [1 0.956766573975185; 0.956766573975185 1];
M(2,1);  %Returns 0.956766573975184 

Which is closely related to the cov function:

cov([condition(A_1) condition(A_2)]);

As you almost get to in your original question, you can scale and adjust the vectors yourself if you want, which gives a slightly better understanding of what is going on. First create a condition function which subtracts the mean, and divides by the standard deviation:

condition = @(x) (x-mean(x))./std(x);  %Function to subtract mean AND normalize standard deviation

Then the correlation appears to be (A_1 * A_2)/(A_1^2), like this:

(condition(A_1)' * condition(A_2)) / sum(condition(A_1).^2);  %Returns 0.956766573975185

By symmetry, this should also work

(condition(A_1)' * condition(A_2)) / sum(condition(A_2).^2); %Returns 0.956766573975185

And it does.

I believe, but don't have the energy to confirm right now, that the same math can be used to compute correlation and cross correlation terms when dealing with multi-dimensiotnal inputs, so long as care is taken when handling the dimensions and orientations of the input arrays.

How to specify the JDK version in android studio?

This is old question but still my answer may help someone

For checking Java version in android studio version , simply open Terminal of Android Studio and type

java -version 

This will display java version installed in android studio

Find out who is locking a file on a network share

On Windows 2008 R2 servers you have two means of viewing what files are open and closing those connections.

Via Share and Storage Management

Server Manager > Roles > File Services > Share and Storage Management > right-click on SaSM > Manage Open File

Via OpenFiles

CMD > Openfiles.exe /query /s SERVERNAME

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

Vuejs: v-model array in multiple input

Here's a demo of the above:https://jsfiddle.net/sajadweb/mjnyLm0q/11

_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  data: {_x000D_
    users: [{ name: 'sajadweb',email:'[email protected]' }] _x000D_
  },_x000D_
  methods: {_x000D_
    addUser: function () {_x000D_
      this.users.push({ name: '',email:'' });_x000D_
    },_x000D_
    deleteUser: function (index) {_x000D_
      console.log(index);_x000D_
      console.log(this.finds);_x000D_
      this.users.splice(index, 1);_x000D_
      if(index===0)_x000D_
      this.addUser()_x000D_
    }_x000D_
  }_x000D_
});
_x000D_
<script src="https://unpkg.com/vue/dist/vue.js"></script>_x000D_
<div id="app">_x000D_
  <h1>Add user</h1>_x000D_
  <div v-for="(user, index) in users">_x000D_
    <input v-model="user.name">_x000D_
    <input v-model="user.email">_x000D_
    <button @click="deleteUser(index)">_x000D_
      delete_x000D_
    </button>_x000D_
  </div>_x000D_
  _x000D_
  <button @click="addUser">_x000D_
    New User_x000D_
  </button>_x000D_
  _x000D_
  <pre>{{ $data }}</pre>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to pull remote branch from somebody else's repo

No, you don't need to add them as a remote. That would be clumbersome and a pain to do each time.

Grabbing their commits:

git fetch [email protected]:theirusername/reponame.git theirbranch:ournameforbranch

This creates a local branch named ournameforbranch which is exactly the same as what theirbranch was for them. For the question example, the last argument would be foo:foo.

Note :ournameforbranch part can be further left off if thinking up a name that doesn't conflict with one of your own branches is bothersome. In that case, a reference called FETCH_HEAD is available. You can git log FETCH_HEAD to see their commits then do things like cherry-picked to cherry pick their commits.

Pushing it back to them:

Oftentimes, you want to fix something of theirs and push it right back. That's possible too:

git fetch [email protected]:theirusername/reponame.git theirbranch
git checkout FETCH_HEAD

# fix fix fix

git push [email protected]:theirusername/reponame.git HEAD:theirbranch

If working in detached state worries you, by all means create a branch using :ournameforbranch and replace FETCH_HEAD and HEAD above with ournameforbranch.

Convert unix time stamp to date in java

You need to convert it to milliseconds by multiplying the timestamp by 1000:

java.util.Date dateTime=new java.util.Date((long)timeStamp*1000);

What should be the package name of android app?

package name with 0 may cause problem for sharedPreference.

(OK) con = createPackageContext("com.example.android.sf1", 0);

(Problem but no error)

con = createPackageContext("com.example.android.sf01", 0);

Ternary operator (?:) in Bash

The following seems to work for my use cases:

Examples

$ tern 1 YES NO                                                                             
YES
    
$ tern 0 YES NO                                                                             
NO
    
$ tern 52 YES NO                                                                            
YES
    
$ tern 52 YES NO 52                                                                         
NO

and can be used in a script like so:

RESULT=$(tern 1 YES NO)
echo "The result is $RESULT"

tern

function show_help()
{
  echo ""
  echo "usage: BOOLEAN VALUE_IF_TRUE VALUE_IF_FALSE {FALSE_VALUE}"
  echo ""
  echo "e.g. "
  echo ""
  echo "tern 1 YES NO                            => YES"
  echo "tern 0 YES NO                            => NO"
  echo "tern "" YES NO                           => NO"
  echo "tern "ANY STRING THAT ISNT 1" YES NO     => NO"
  echo "ME=$(tern 0 YES NO)                      => ME contains NO"
  echo ""

  exit
}

if [ "$1" == "help" ]
then
  show_help
fi
if [ -z "$3" ]
then
  show_help
fi

# Set a default value for what is "false" -> 0
FALSE_VALUE=${4:-0}

function main
{
  if [ "$1" == "$FALSE_VALUE" ]; then
    echo $3
    exit;
  fi;

  echo $2
}

main "$1" "$2" "$3"

Cannot read property 'length' of null (javascript)

From the code that you have provided, not knowing the language that you are programming in. The variable capital is null. When you are trying to read the property length, the system cant as it is trying to deference a null variable. You need to define capital.

Merge unequal dataframes and replace missing rows with 0

Another alternative with data.table.

EXAMPLE DATA

dt1 <- data.table(df1)
dt2 <- data.table(df2)
setkey(dt1,x)
setkey(dt2,x)

CODE

dt2[dt1,list(y=ifelse(is.na(y),0,y))]

How to save the contents of a div as a image?

Do something like this:

A <div> with ID of #imageDIV, another one with ID #download and a hidden <div> with ID #previewImage.

Include the latest version of jquery, and jspdf.debug.js from the jspdf CDN

Then add this script:

var element = $("#imageDIV"); // global variable
var getCanvas; // global variable
$('document').ready(function(){
  html2canvas(element, {
    onrendered: function (canvas) {
      $("#previewImage").append(canvas);
      getCanvas = canvas;
    }
  });
});
$("#download").on('click', function () {
  var imgageData = getCanvas.toDataURL("image/png");
  // Now browser starts downloading it instead of just showing it
  var newData = imageData.replace(/^data:image\/png/, "data:application/octet-stream");
  $("#download").attr("download", "image.png").attr("href", newData);
});

The div will be saved as a PNG on clicking the #download

PHP PDO with foreach and fetch

A PDOStatement (which you have in $users) is a forward-cursor. That means, once consumed (the first foreach iteration), it won't rewind to the beginning of the resultset.

You can close the cursor after the foreach and execute the statement again:

$users       = $dbh->query($sql);
foreach ($users as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}

$users->execute();

foreach ($users as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}

Or you could cache using tailored CachingIterator with a fullcache:

$users       = $dbh->query($sql);

$usersCached = new CachedPDOStatement($users);

foreach ($usersCached as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}
foreach ($usersCached as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}

You find the CachedPDOStatement class as a gist. The caching itertor is probably more sane than storing the resultset into an array because it still offers all properties and methods of the PDOStatement object it has wrapped.

How to overwrite files with Copy-Item in PowerShell

As I understand Copy-Item -Exclude then you are doing it correct. What I usually do, get 1'st, and then do after, so what about using Get-Item as in

Get-Item -Path $copyAdmin -Exclude $exclude |
Copy-Item  -Path $copyAdmin -Destination $AdminPath -Recurse -force

How to set the project name/group/version, plus {source,target} compatibility in the same file?

I found the solution to a similar problem. I am using Gradle 1.11 (as April, 2014). The project name can be changed directly in settings.gradle file as following:

  rootProject.name='YourNewName'

This takes care of uploading to repository (Artifactory w/ its plugin for me) with the correct artifactId.

JavaScript equivalent to printf/String.Format

I want to share my solution for the 'problem'. I haven't re-invented the wheel but tries to find a solution based on what JavaScript already does. The advantage is, that you get all implicit conversions for free. Setting the prototype property $ of String gives a very nice and compact syntax (see examples below). It is maybe not the most efficient way, but in most cases dealing with output it does not have to be super optimized.

String.form = function(str, arr) {
    var i = -1;
    function callback(exp, p0, p1, p2, p3, p4) {
        if (exp=='%%') return '%';
        if (arr[++i]===undefined) return undefined;
        exp  = p2 ? parseInt(p2.substr(1)) : undefined;
        var base = p3 ? parseInt(p3.substr(1)) : undefined;
        var val;
        switch (p4) {
            case 's': val = arr[i]; break;
            case 'c': val = arr[i][0]; break;
            case 'f': val = parseFloat(arr[i]).toFixed(exp); break;
            case 'p': val = parseFloat(arr[i]).toPrecision(exp); break;
            case 'e': val = parseFloat(arr[i]).toExponential(exp); break;
            case 'x': val = parseInt(arr[i]).toString(base?base:16); break;
            case 'd': val = parseFloat(parseInt(arr[i], base?base:10).toPrecision(exp)).toFixed(0); break;
        }
        val = typeof(val)=='object' ? JSON.stringify(val) : val.toString(base);
        var sz = parseInt(p1); /* padding size */
        var ch = p1 && p1[0]=='0' ? '0' : ' '; /* isnull? */
        while (val.length<sz) val = p0 !== undefined ? val+ch : ch+val; /* isminus? */
       return val;
    }
    var regex = /%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g;
    return str.replace(regex, callback);
}

String.prototype.$ = function() {
    return String.form(this, Array.prototype.slice.call(arguments));
}

Here are a few examples:

String.format("%s %s", [ "This is a string", 11 ])
console.log("%s %s".$("This is a string", 11))
var arr = [ "12.3", 13.6 ]; console.log("Array: %s".$(arr));
var obj = { test:"test", id:12 }; console.log("Object: %s".$(obj));
console.log("%c", "Test");
console.log("%5d".$(12)); // '   12'
console.log("%05d".$(12)); // '00012'
console.log("%-5d".$(12)); // '12   '
console.log("%5.2d".$(123)); // '  120'
console.log("%5.2f".$(1.1)); // ' 1.10'
console.log("%10.2e".$(1.1)); // '   1.10e+0'
console.log("%5.3p".$(1.12345)); // ' 1.12'
console.log("%5x".$(45054)); // ' affe'
console.log("%20#2x".$("45054")); // '    1010111111111110'
console.log("%6#2d".$("111")); // '     7'
console.log("%6#16d".$("affe")); // ' 45054'

Where is my .vimrc file?

on unix vim --version tells you the various locations of the vim config files :

   system vimrc file: "$VIM/vimrc"
     user vimrc file: "$HOME/.vimrc"
 2nd user vimrc file: "~/.vim/vimrc"
      user exrc file: "$HOME/.exrc"
       defaults file: "$VIMRUNTIME/defaults.vim"
  fall-back for $VIM: "/usr/share/vim"

How to determine total number of open/active connections in ms sql server 2005

SELECT
[DATABASE] = DB_NAME(DBID), 
OPNEDCONNECTIONS =COUNT(DBID),
[USER] =LOGINAME
FROM SYS.SYSPROCESSES
GROUP BY DBID, LOGINAME
ORDER BY DB_NAME(DBID), LOGINAME

PHP using Gettext inside <<<EOF string

As far as I can see, you just added heredoc by mistake
No need to use ugly heredoc syntax here.
Just remove it and everything will work:

<p>Hello</p>
<p><?= _("World"); ?></p>

What do we mean by Byte array?

I assume you know what a byte is. A byte array is simply an area of memory containing a group of contiguous (side by side) bytes, such that it makes sense to talk about them in order: the first byte, the second byte etc..

Just as bytes can encode different types and ranges of data (numbers from 0 to 255, numbers from -128 to 127, single characters using ASCII e.g. 'a' or '%', CPU op-codes), each byte in a byte array may be any of these things, or contribute to some multi-byte values such as numbers with larger range (e.g. 16-bit unsigned int from 0..65535), international character sets, textual strings ("hello"), or part/all of a compiled computer programs.

The crucial thing about a byte array is that it gives indexed (fast), precise, raw access to each 8-bit value being stored in that part of memory, and you can operate on those bytes to control every single bit. The bad thing is the computer just treats every entry as an independent 8-bit number - which may be what your program is dealing with, or you may prefer some powerful data-type such as a string that keeps track of its own length and grows as necessary, or a floating point number that lets you store say 3.14 without thinking about the bit-wise representation. As a data type, it is inefficient to insert or remove data near the start of a long array, as all the subsequent elements need to be shuffled to make or fill the gap created/required.

connect to host localhost port 22: Connection refused

What worked for me is:

sudo mkdir /var/run/sshd
sudo apt-get install --reinstall openssh-server

I tried all the above mentioned solutions but somehow this directory /var/run/sshd was still missing for me. I have Ubuntu 16.04.4 LTS. Hope my answer helps if someone has the same issue.

WebSockets vs. Server-Sent events/EventSource

Opera, Chrome, Safari supports SSE, Chrome, Safari supports SSE inside of SharedWorker Firefox supports XMLHttpRequest readyState interactive, so we can make EventSource polyfil for Firefox

Mocking static methods with Mockito

For those who use JUnit 5, Powermock is not an option. You'll require the following dependencies to successfully mock a static method with just Mockito.

testCompile    group: 'org.mockito', name: 'mockito-core',           version: '3.6.0'
testCompile    group: 'org.mockito', name: 'mockito-junit-jupiter',  version: '3.6.0'
testCompile    group: 'org.mockito', name: 'mockito-inline',         version: '3.6.0'

mockito-junit-jupiter add supports for JUnit 5.

And support for mocking static methods is provided by mockito-inline dependency.

Example:

@Test
void returnUtilTest() {
    assertEquals("foo", UtilClass.staticMethod("foo"));

    try (MockedStatic<UtilClass> classMock = mockStatic(UtilClass.class)) {

        classMock.when(() -> UtilClass.staticMethod("foo")).thenReturn("bar");

        assertEquals("bar", UtilClass.staticMethod("foo"));
     }

     assertEquals("foo", UtilClass.staticMethod("foo"));
}

The try-with-resource block is used to make the static mock remains temporary, so it's mocked only within that scope.

When not using a try block, make sure to close the scoped mock, once you are done with the assertions.

MockedStatic<UtilClass> classMock = mockStatic(UtilClass.class)
classMock.when(() -> UtilClass.staticMethod("foo")).thenReturn("bar");
assertEquals("bar", UtilClass.staticMethod("foo"));
classMock.close();

Mocking void methods:

When mockStatic is called on a class, all the static void methods in that class automatically get mocked to doNothing().

How to save password when using Subversion from the console

All methods mention here are not working for me. I built Subversion from source, and I found out, I must run configure with --enable-plaintext-password-storage to support this feature.

How to get current url in view in asp.net core 1.0

You need scheme, host, path and queryString

@string.Format("{0}://{1}{2}{3}", Context.Request.Scheme, Context.Request.Host, Context.Request.Path, Context.Request.QueryString)

or using new C#6 feature "String interpolation"

@($"{Context.Request.Scheme}://{Context.Request.Host}{Context.Request.Path}{Context.Request.QueryString}")

Find files and tar them (with spaces)

Big warning on several of the solutions (and your own test) :

When you do : anything | xargs something

xargs will try to fit "as many arguments as possible" after "something", but then you may end up with multiple invocations of "something".

So your attempt: find ... | xargs tar czvf file.tgz may end up overwriting "file.tgz" at each invocation of "tar" by xargs, and you end up with only the last invocation! (the chosen solution uses a GNU -T special parameter to avoid the problem, but not everyone has that GNU tar available)

You could do instead:

find . -type f -print0 | xargs -0 tar -rvf backup.tar
gzip backup.tar

Proof of the problem on cygwin:

$ mkdir test
$ cd test
$ seq 1 10000 | sed -e "s/^/long_filename_/" | xargs touch 
    # create the files
$ seq 1 10000 | sed -e "s/^/long_filename_/" | xargs tar czvf archive.tgz
    # will invoke tar several time as it can'f fit 10000 long filenames into 1
$ tar tzvf archive.tgz | wc -l
60
    # in my own machine, I end up with only the 60 last filenames, 
    # as the last invocation of tar by xargs overwrote the previous one(s)

# proper way to invoke tar: with -r  (which append to an existing tar file, whereas c would overwrite it)
# caveat: you can't have it compressed (you can't add to a compressed archive)
$ seq 1 10000 | sed -e "s/^/long_filename_/" | xargs tar rvf archive.tar #-r, and without z
$ gzip archive.tar
$ tar tzvf archive.tar.gz | wc -l
10000 
  # we have all our files, despite xargs making several invocations of the tar command

 

Note: that behavior of xargs is a well know diccifulty, and it is also why, when someone wants to do :

find .... | xargs grep "regex"

they intead have to write it:

find ..... | xargs grep "regex" /dev/null

That way, even if the last invocation of grep by xargs appends only 1 filename, grep sees at least 2 filenames (as each time it has: /dev/null, where it won't find anything, and the filename(s) appended by xargs after it) and thus will always display the file names when something maches "regex". Otherwise you may end up with the last results showing matches without a filename in front.

Is it possible to run an .exe or .bat file on 'onclick' in HTML

You can not run/execute an .exe file that is in the users local machine or through a site. The user must first download the exe file and then run the executable file.
So there is no possible way

The following code works only when the EXE is Present in the User's Machine.

<a href = "C:\folder_name\program.exe">

How to get child process from parent process

Just use :

pgrep -P $your_process1_pid

CSS float right not working correctly

you need to wrap your text inside div and float it left while wrapper div should have height, and I've also added line height for vertical alignment

<div style="border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: gray;height:30px;">
   <div style="float:left;line-height:30px;">Contact Details</div>

    <button type="button" class="edit_button" style="float: right;">My Button</button>

</div>

also js fiddle here =) http://jsfiddle.net/xQgSm/

How to use onResume()?

After an activity started, restarted (onRestart() happens before onStart()), or paused (onPause()), onResume() called. When the activity is in the state of onResume(), the activity is ready to be used by the app user.

I have studied the activity lifecycle a little bit, and here's my understanding of this topic: If you want to restart the activity (A) at the end of the execution of another, there could be a few different cases.

  1. The other activity (B) has been paused and/or stopped or destroyed, and the activity A possibly had been paused (onPause()), in this case, activity A will call onResume()

  2. The activity B has been paused and/or stopped or destroyed, the activity A possibly had been stopped (onStop()) due to memory thing, in this case, activity A will call onRestart() first, onStart() second, then onResume()

  3. The activity B has been paused and/or stopped or destroyed, the activity A has been destroyed, the programmer can call onStart() manually to start the activity first, then onResume() because when an activity is in the destroyed status the activity has not started, and this happens before the activity being completely removed. If the activity is removed, the activity needs to be created again. Manually calling onStart() I think it's because if the activity not started and it is created, onStart() will be called after onCreate().

If you want to update data, make a data update function and put the function inside the onResume(). Or put a loadData function inside onResume()

It's better to understand the lifecycle with the help of the Activity lifecycle diagram.

Retrieving the last record in each group - MySQL

select * from messages group by name desc

Developing for Android in Eclipse: R.java not regenerating

I found this happening to me with a broken layout and everything blows up. Relax, it's like that old mistake when you first learned programming C where you forget one semicolon and it generates a hundred errors. Many panic, press all the buttons, and makes things worse.

Solution

  • Make sure that anything the R. links to is not broken. Fix all errors in your XML files. If anything in the ADKs are broken, R will not regenerate.
  • If you somehow hit something and created import android.R in your activity, remove it.
  • Run Project -> Clean. This will delete and regenerate R and BuildConfig.
  • Make sure Project -> Build Automatically is ticked. If not, build it manually via Menu -> Project -> Build Project .
  • Wait a few seconds for the errors to disappear.
  • If it doesn't work, delete everything inside the /gen/ folder
  • If it still doesn't work, try right-clicking your project -> Android Tools -> Fix Project Properties.
  • Check your *.properties files (in the root folder of your app folder) and make sure that the links in there are not broken.
  • Right-click your project > properties > Android. Look at the Project Build Target and Library sections on the right side of the page. Your Build Target should match the target in your AndroidManifest.xml. So if it's set to target 17 in AndroidManifest, make sure that the Target Name is Android 4.2. If your Library has an X under the reference, remove and re-add the library until there's a green tick. This might happen if you've moved a few files and folders around.

What to do if R doesn't regenerate

This usually happens when you have a broken XML file.

  • Check errors inside your XML files, mainly within the /res/ folder
  • Common places are /layout/ and /values/, especially if you've changed one of them recently
  • Check AndroidManifest.xml. I find that often I change a string and forget to change the string name from AndroidManifest.xml.
  • Check that Android SDK Build-tools is installed. Window -> Android SDK Manager -> Tools -> Android SDK Build-tools
  • Make sure when you update the Android SDK Tools, you also update the Android SDK Platform-tools and Android ADK Build-tools. Build fails silently if they don't match.
  • If you can't find the issue, right click /gen/ -> Restore from local history... -> tick R.java -> click Restore. Even if it doesn't solve the problem, it will clear out the extra errors to make the problem easier to find.

How do I compare a value to a backslash?

Use following code to perform if-else conditioning in python: Here, I am checking the length of the string. If the length is less than 3 then do nothing, if more then 3 then I check the last 3 characters. If last 3 characters are "ing" then I add "ly" at the end otherwise I add "ing" at the end.

Code-

if (len(s)<=3):
    return s
elif s[-3:]=="ing":
    return s+"ly"
else: return s + "ing"

Jquery Setting Value of Input Field

If the input field has a class name formData use this : $(".formData").val("data")

If the input field has an id attribute name formData use this : $("#formData").val("data")

If the input name is given use this : $("input[name='formData']").val("data")

You can also mention the type. Then it will refer to all the inputs of that type and the given class name: $("input[type='text'].formData").val("data")

Should I use SVN or Git?

I would probably choose Git because I feel it's much more powerful than SVN. There are cheap Code Hosting services available which work just great for me - you don't have to do backups or any maintenance work - GitHub is the most obvious candidate.

That said, I don't know anything regarding the integration of Visual Studio and the different SCM systems. I imagine the integration with SVN to notably better.

Case statement with multiple values in each 'when' block

You might take advantage of ruby's "splat" or flattening syntax.

This makes overgrown when clauses — you have about 10 values to test per branch if I understand correctly — a little more readable in my opinion. Additionally, you can modify the values to test at runtime. For example:

honda  = ['honda', 'acura', 'civic', 'element', 'fit', ...]
toyota = ['toyota', 'lexus', 'tercel', 'rx', 'yaris', ...]
...

if include_concept_cars
  honda += ['ev-ster', 'concept c', 'concept s', ...]
  ...
end

case car
when *toyota
  # Do something for Toyota cars
when *honda
  # Do something for Honda cars
...
end

Another common approach would be to use a hash as a dispatch table, with keys for each value of car and values that are some callable object encapsulating the code you wish to execute.

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

This is a feature, not a bug.

See http://docs.python.org/howto/unicode.html, specifically the 'unicode type' section.

Unclosed Character Literal error

String y = "hello";

would work (note the double quotes).

char y = 'h'; this will work for chars (note the single quotes)

but the type is the key: '' (single quotes) for one char, "" (double quotes) for string.

Nesting CSS classes

Not directly. But you can use extensions such as LESS to help you achieve the same.

selecting unique values from a column

Use the DISTINCT operator in MySQL:

SELECT DISTINCT(Date) AS Date FROM buy ORDER BY Date DESC;

Using an Alias in a WHERE clause

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

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

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

Kudos to Syed Mehroz Alam.

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse

This needs to be used as of 2020

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.18</version>
    </dependency>

System.IO.IOException: file used by another process

My reputation being too small to comment an answer, here is my feedback concerning roquen answer (using settings on xmlwriter to force the stream to close): it works perfectly and it made me save a lot of time. roquen's example requires some adjustment, here is the code that works on .NET framework 4.8 :

    XmlWriterSettings settings = new XmlWriterSettings();
    settings.CloseOutput = true;
    writer = XmlWriter.Create(stream, settings);

Find PHP version on windows command line

In command prompt type below

set PATH=%PATH%;C:\path\to\php

Where C:\path\to\php is the folder where your php.exe file is located. After this run

C:\>php -v

than you will see something like

PHP 7.3.6 (cli) (built: May 29 2019 12:11:00) 

UPDATE:

If you find that when you restart your computer, this solution will not work anymore:

Set the Path like as following:

Step 1 - Click on the Windows icon

enter image description here

Step 2 - Click on the Settings icon

enter image description here

Step 3 - Click on System

enter image description here

Step 4 - Click on About

enter image description here

Step 5 - Click on System info

enter image description here

Step 6 - Click on Advanced system settings

enter image description here

Step 7 - Click on Environment variables...

enter image description here

Step 8 - Select Path row and then click Edit

enter image description here

Step 9 - Click New and then click Browse, then in the next panel which will open you need to select the folder you want in the Path. For the initial premise of this guide i will add the folder C:\Users\NewFolderInPath?

Note: Replace your PHP installed path(e.g:C:\Program Files\php) with the above path ?.

enter image description here

Step 10 - Click OK and click every OK button you will encounter to close every previous windows.

enter image description here

Accessing private member variables from prototype-defined functions

There's a simpler way by leveraging the use of bind and call methods.

By setting private variables to an object, you can leverage that object's scope.

Example

function TestClass (value) {
    // The private value(s)
    var _private = {
        value: value
    };

    // `bind` creates a copy of `getValue` when the object is instantiated
    this.getValue = TestClass.prototype.getValue.bind(_private);

    // Use `call` in another function if the prototype method will possibly change
    this.getValueDynamic = function() {
        return TestClass.prototype.getValue.call(_private);
    };
};

TestClass.prototype.getValue = function() {
    return this.value;
};

This method isn't without drawbacks. Since the scope context is effectively being overridden, you don't have access outside of the _private object. However, it isn't impossible though to still give access to the instance object's scope. You can pass in the object's context (this) as the second argument to bind or call to still have access to it's public values in the prototype function.

Accessing public values

function TestClass (value) {
    var _private = {
        value: value
    };

    this.message = "Hello, ";

    this.getMessage = TestClass.prototype.getMessage.bind(_private, this);

}

TestClass.prototype.getMessage = function(_public) {

    // Can still access passed in arguments
    // e.g. – test.getValues('foo'), 'foo' is the 2nd argument to the method
    console.log([].slice.call(arguments, 1));
    return _public.message + this.value;
};

var test = new TestClass("World");
test.getMessage(1, 2, 3); // [1, 2, 3]         (console.log)
                          // => "Hello, World" (return value)

test.message = "Greetings, ";
test.getMessage(); // []                    (console.log)
                   // => "Greetings, World" (return value)

How to see full query from SHOW PROCESSLIST

Show Processlist fetches the information from another table. Here is how you can pull the data and look at 'INFO' column which contains the whole query :

select * from INFORMATION_SCHEMA.PROCESSLIST where db = 'somedb';

You can add any condition or ignore based on your requirement.

The output of the query is resulted as :

+-------+------+-----------------+--------+---------+------+-----------+----------------------------------------------------------+
| ID    | USER | HOST            | DB     | COMMAND | TIME | STATE     | INFO                                                     |
+-------+------+-----------------+--------+---------+------+-----------+----------------------------------------------------------+
|     5 | ssss | localhost:41060 | somedb | Sleep   |    3 |           | NULL                                                     |
| 58169 | root | localhost       | somedb | Query   |    0 | executing | select * from sometable where tblColumnName = 'someName' |

What does %>% function mean in R?

%>% is similar to pipe in Unix. For example, in

a <- combined_data_set %>% group_by(Outlet_Identifier) %>% tally()

the output of combined_data_set will go into group_by and its output will go into tally, then the final output is assigned to a.

This gives you handy and easy way to use functions in series without creating variables and storing intermediate values.

SQL to add column and comment in table in single command

No, you can't.

There's no reason why you would need to. This is a one-time operation and so takes only an additional second or two to actually type and execute.

If you're adding columns in your web application this is more indicative of a flaw in your data-model as you shouldn't need to be doing it.


In response to your comment that a comment is a column attribute; it may seem so but behind the scenes Oracle stores this as an attribute of an object.

SQL> desc sys.com$
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 OBJ#                                      NOT NULL NUMBER
 COL#                                               NUMBER
 COMMENT$                                           VARCHAR2(4000)

SQL>

The column is optional and sys.col$ does not contain comment information.

I assume, I have no knowledge, that this was done in order to only have one system of dealing with comments rather than multiple.

How to resolve the error on 'react-native start'

I found the regexp.source changed from node v12.11.0, maybe the new v8 engine caused. see more on https://github.com/nodejs/node/releases/tag/v12.11.0.

D:\code\react-native>nvm use 12.10.0
Now using node v12.10.0 (64-bit)

D:\code\react-native>node
Welcome to Node.js v12.10.0.
Type ".help" for more information.
> /node_modules[/\\]react[/\\]dist[/\\].*/.source
'node_modules[\\/\\\\]react[\\/\\\\]dist[\\/\\\\].*'
> /node_modules[/\\]react[/\\]dist[/\\].*/.source.replace(/\//g, path.sep)
'node_modules[\\\\\\\\]react[\\\\\\\\]dist[\\\\\\\\].*'
>
(To exit, press ^C again or ^D or type .exit)
>

D:\code\react-native>nvm use 12.11.0
Now using node v12.11.0 (64-bit)

D:\code\react-native>node
Welcome to Node.js v12.11.0.
Type ".help" for more information.
> /node_modules[/\\]react[/\\]dist[/\\].*/.source
'node_modules[/\\\\]react[/\\\\]dist[/\\\\].*'
> /node_modules[/\\]react[/\\]dist[/\\].*/.source.replace(/\//g, path.sep)
'node_modules[\\\\\\]react[\\\\\\]dist[\\\\\\].*'
>
(To exit, press ^C again or ^D or type .exit)
>

D:\code\react-native>nvm use 12.13.0
Now using node v12.13.0 (64-bit)

D:\code\react-native>node
Welcome to Node.js v12.13.0.
Type ".help" for more information.
> /node_modules[/\\]react[/\\]dist[/\\].*/.source
'node_modules[/\\\\]react[/\\\\]dist[/\\\\].*'
> /node_modules[/\\]react[/\\]dist[/\\].*/.source.replace(/\//g, path.sep)
'node_modules[\\\\\\]react[\\\\\\]dist[\\\\\\].*'
>
(To exit, press ^C again or ^D or type .exit)
>

D:\code\react-native>nvm use 13.3.0
Now using node v13.3.0 (64-bit)

D:\code\react-native>node
Welcome to Node.js v13.3.0.
Type ".help" for more information.
> /node_modules[/\\]react[/\\]dist[/\\].*/.source
'node_modules[/\\\\]react[/\\\\]dist[/\\\\].*'
> /node_modules[/\\]react[/\\]dist[/\\].*/.source.replace(/\//g, path.sep)
'node_modules[\\\\\\]react[\\\\\\]dist[\\\\\\].*'
>

Detecting installed programs via registry

On 64-bit systems the x64 key is:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall

Most programs are listed there. Look at the keys: DisplayName DisplayVersion

Note that the last is not always set!

On 64-bit systems the x86 key (usually with more entries) is:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall

syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING

You have extra spaces after END; that cause the heredoc not terminated.

FIFO based Queue implementations?

Here is example code for usage of java's built-in FIFO queue:

public static void main(String[] args) {
    Queue<Integer> myQ = new LinkedList<Integer>();
    myQ.add(1);
    myQ.add(6);
    myQ.add(3);
    System.out.println(myQ);   // 1 6 3
    int first = myQ.poll();    // retrieve and remove the first element
    System.out.println(first); // 1
    System.out.println(myQ);   // 6 3
}

Make xargs execute the command once for each line of input

The following will only work if you do not have spaces in your input:

xargs -L 1
xargs --max-lines=1 # synonym for the -L option

from the man page:

-L max-lines
          Use at most max-lines nonblank input lines per command line.
          Trailing blanks cause an input line to be logically continued  on
          the next input line.  Implies -x.

maven... Failed to clean project: Failed to delete ..\org.ow2.util.asm-asm-tree-3.1.jar

I had similar issue. Earlier I was using Maven 3 to build the project. After switching to maven 2 , I had the above error.

Solved it by switching to Maven 3.

Update one MySQL table with values from another

It depends what is a use of those tables, but you might consider putting trigger on original table on insert and update. When insert or update is done, update the second table based on only one item from the original table. It will be quicker.

Typescript input onchange event.target.value

This is when you're working with a FileList Object:

onChange={(event: React.ChangeEvent<HTMLInputElement>): void => {
  const fileListObj: FileList | null = event.target.files;
  if (Object.keys(fileListObj as Object).length > 3) {
    alert('Only three images pleaseeeee :)');
  } else {
    // Do something
  }

  return;
}}

Getting "conflicting types for function" in C, why?

C Commandment #3:

K&R #3 Thou shalt always prototype your functions or else the C compiler will extract vengence. 

http://www.ee.ryerson.ca:8080/~elf/hack/God.vs.K+R.html

How can I match a string with a regex in Bash?

if [[ $STR == *pattern* ]]
then
    echo "It is the string!"
else
    echo "It's not him!"
fi

Works for me! GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)

Contain an image within a div?

Use max width and max height. It will keep the aspect ratio

#container img 
{
 max-width: 250px;
 max-height: 250px;
}

http://jsfiddle.net/rV77g/

How can I access localhost from another computer in the same network?

You need to find what your local network's IP of that computer is. Then other people can access to your site by that IP.

You can find your local network's IP by go to Command Prompt or press Windows + R then type in ipconfig. It will give out some information and your local IP should look like 192.168.1.x.

Fatal error compiling: invalid target release: 1.8 -> [Help 1]

This question wasn't asking explicitly about Docker, but I received the same error when I had a pom.xml file that was targeting 1.9...

<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <maven.compiler.source>1.9</maven.compiler.source>
  <maven.compiler.target>1.9</maven.compiler.target>
</properties>

... but then tried to run tests against a Docker container by specifying "maven" by itself.

docker run -t --rm -v m2_repository:/root/.m2/repository -v $(pwd):/work -w /work maven mvn -e test

For me, the fix was to target the exact version I needed.

docker run -t --rm -v m2_repository:/root/.m2/repository -v $(pwd):/work -w /work maven:3.5.2-jdk-9 mvn test

(You can learn more here.)

Efficient way to do batch INSERTS with JDBC

This is a mix of the two previous answers:

  PreparedStatement ps = c.prepareStatement("INSERT INTO employees VALUES (?, ?)");

  ps.setString(1, "John");
  ps.setString(2,"Doe");
  ps.addBatch();

  ps.clearParameters();
  ps.setString(1, "Dave");
  ps.setString(2,"Smith");
  ps.addBatch();

  ps.clearParameters();
  int[] results = ps.executeBatch();

Using ls to list directories and their total sizes

Hmm, best way is to use this command:

du -h -x / | sort -hr >> /home/log_size.txt

Then you will be able to get all sizes folders over all your server. Easy to help to you to find the biggest sizes.

XPath using starts-with function

Use:

/*/ITEM[starts-with(REVENUE_YEAR,'2552')]/REGION

Note: Unless your host language can't handle element instance as result, do not use text nodes specially in mixed content data model. Do not start expressions with // operator when the schema is well known.

Using SED with wildcard

The asterisk (*) means "zero or more of the previous item".

If you want to match any single character use

sed -i 's/string-./string-0/g' file.txt

If you want to match any string (i.e. any single character zero or more times) use

sed -i 's/string-.*/string-0/g' file.txt

Changing the color of a clicked table row using jQuery

To change color of a cell:

$(document).on('click', '#table tbody td', function (event) {


    var selected = $(this).hasClass("obstacle");
    $("#table tbody td").removeClass("obstacle");
    if (!selected)
        $(this).addClass("obstacle");

});

Failed to install Python Cryptography package with PIP and setup.py

i downloaded paramiko full source code from pypi and did

python setup.py install

it worked flawlessly

all default pythondev / openssl /libffi packages are already present in rhel.

downloading rpms have rpm mismatch and more trouble

How do I delete a local repository in git?

To piggyback on rkj's answer, to avoid endless prompts (and force the command recursively), enter the following into the command line, within the project folder:

$ rm -rf .git

Or to delete .gitignore and .gitmodules if any (via @aragaer):

$ rm -rf .git*

Then from the same ex-repository folder, to see if hidden folder .git is still there:

$ ls -lah

If it's not, then congratulations, you've deleted your local git repo, but not a remote one if you had it. You can delete GitHub repo on their site (github.com).

To view hidden folders in Finder (Mac OS X) execute these two commands in your terminal window:

defaults write com.apple.finder AppleShowAllFiles TRUE
killall Finder

Source: http://lifehacker.com/188892/show-hidden-files-in-finder.

Image Greyscale with CSS & re-color on mouse-over?

I use the following code on http://www.diagnomics.com/

Smooth transition from b/w to color with magnifying effect (scale)

    img.color_flip {
      filter: url(filters.svg#grayscale); /* Firefox 3.5+ */
      filter: gray; /* IE5+ */
      -webkit-filter: grayscale(1); /* Webkit Nightlies & Chrome Canary */
      -webkit-transition: all .5s ease-in-out;
    }

    img.color_flip:hover {
      filter: none;
      -webkit-filter: grayscale(0);
      -webkit-transform: scale(1.1);
    }