Programs & Examples On #Lidgren

Lidgren.Network is an open source networking library for .NET Framework with a simple API used mainly in client/server games.

How do I generate a stream from a string?

A good combination of String extensions:

public static byte[] GetBytes(this string str)
{
    byte[] bytes = new byte[str.Length * sizeof(char)];
    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
    return bytes;
}

public static Stream ToStream(this string str)
{
    Stream StringStream = new MemoryStream();
    StringStream.Read(str.GetBytes(), 0, str.Length);
    return StringStream;
}

How to implement a material design circular progress bar in android

Was looking for a way to do this using simple xml, but couldn't find any helpful answers, so came up with this.

This works on pre-lollipop versions too, and is pretty close to the material design progress bar. You just need to use this drawable as the indeterminate drawable in the ProgressBar layout.

<?xml version="1.0" encoding="utf-8"?><!--<layer-list>-->
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:toDegrees="360">
    <layer-list>
        <item>
            <rotate xmlns:android="http://schemas.android.com/apk/res/android"
                android:fromDegrees="-90"
                android:toDegrees="-90">
                <shape
                    android:innerRadiusRatio="2.5"
                    android:shape="ring"
                    android:thickness="2dp"
                    android:useLevel="true"><!-- this line fixes the issue for lollipop api 21 -->

                    <gradient
                        android:angle="0"
                        android:endColor="#007DD6"
                        android:startColor="#007DD6"
                        android:type="sweep"
                        android:useLevel="false" />
                </shape>
            </rotate>
        </item>
        <item>
            <rotate xmlns:android="http://schemas.android.com/apk/res/android"
                android:fromDegrees="0"
                android:toDegrees="270">
                <shape
                    android:innerRadiusRatio="2.6"
                    android:shape="ring"
                    android:thickness="4dp"
                    android:useLevel="true"><!-- this line fixes the issue for lollipop api 21 -->
                    <gradient
                        android:angle="0"
                        android:centerColor="#FFF"
                        android:endColor="#FFF"
                        android:startColor="#FFF"
                        android:useLevel="false" />
                </shape>
            </rotate>
        </item>
    </layer-list>
</rotate>

set the above drawable in ProgressBar as follows:

  android:indeterminatedrawable="@drawable/above_drawable"

whitespaces in the path of windows filepath

(WINDOWS - AWS solution)
Solved for windows by putting tripple quotes around files and paths.
Benefits:
1) Prevents excludes that quietly were getting ignored.
2) Files/folders with spaces in them, will no longer kick errors.

    aws_command = 'aws s3 sync """D:/""" """s3://mybucket/my folder/"  --exclude """*RECYCLE.BIN/*""" --exclude """*.cab""" --exclude """System Volume Information/*""" '

    r = subprocess.run(f"powershell.exe {aws_command}", shell=True, capture_output=True, text=True)

Excel CSV. file with more than 1,048,576 rows of data

Use MS Access. I have a file of 2,673,404 records. It will not open in notepad++ and excel will not load more than 1,048,576 records. It is tab delimited since I exported the data from a mysql database and I need it in csv format. So I imported it into Access. Change the file extension to .txt so MS Access will take you through the import wizard.

MS Access will link to your file so for the database to stay intact keep the csv file

How to "comment-out" (add comment) in a batch/cmd?

No, plain old batch files use REM as a comment. ECHO is the command that prints something on the screen.

To "comment out" sections of the file you could use GOTO. An example of all these commands/techniques:

REM it starts here the section below can be safely erased once the file is customised
ECHO Hey you need to edit this file before running it!  Check the instructions inside
ECHO Now press ctrl-c to interrupt execution or enter to continue
PAUSE
REM erase the section above once you have customised the file
python executed1.py
ECHO Skipping some stuff now
GOTO End
python skipped1.py
python skipped2.py
:END
python executed2.py

What can I say? batch files are a relic of times long gone, they're clunky and ugly.

You can read more on this website.

EDIT: modified the example a bit to have it contain the elements you are apparently looking for.

TypeScript or JavaScript type casting

You can cast like this:

return this.createMarkerStyle(<MarkerSymbolInfo> symbolInfo);

Or like this if you want to be compatible with tsx mode:

return this.createMarkerStyle(symbolInfo as MarkerSymbolInfo);

Just remember that this is a compile-time cast, and not a runtime cast.

How do I add to the Windows PATH variable using setx? Having weird problems

Without admin rights the only way that worked for me is a bat file that contains the following code:

for /F "tokens=2* delims= " %%f IN ('reg query HKCU\Environment /v PATH ^| findstr /i path') do set OLD_SYSTEM_PATH=%%g
setx PATH "%USERPROFILE%\wev-tools;%OLD_SYSTEM_PATH%"

The code is the combination of the answers https://stackoverflow.com/a/45566845/4717152 and https://stackoverflow.com/a/10292113/4717152

Can you split a stream into two streams?

Shorter version that uses Lombok

import java.util.function.Consumer;
import java.util.function.Predicate;

import lombok.RequiredArgsConstructor;

/**
 * Forks a Stream using a Predicate into postive and negative outcomes.
 */
@RequiredArgsConstructor
@FieldDefaults(makeFinal = true, level = AccessLevel.PROTECTED)
public class StreamForkerUtil<T> implements Consumer<T> {
    Predicate<T> predicate;
    Consumer<T> positiveConsumer;
    Consumer<T> negativeConsumer;

    @Override
    public void accept(T t) {
        (predicate.test(t) ? positiveConsumer : negativeConsumer).accept(t);
    }
}

Is Java a Compiled or an Interpreted programming language ?

Java is a byte-compiled language targeting a platform called the Java Virtual Machine which is stack-based and has some very fast implementations on many platforms.

How to check if input file is empty in jQuery

Just check the length of files property, which is a FileList object contained on the input element

if( document.getElementById("videoUploadFile").files.length == 0 ){
    console.log("no files selected");
}

How do I prevent CSS inheritance?

You can use the * selector to change the child styles back to the default

example

#parent {
    white-space: pre-wrap;
}

#parent * {
    white-space: initial;
}

How do I get the current username in .NET using C#?

For a Windows Forms app that was to be distributed to several users, many of which log in over vpn, I had tried several ways which all worked for my local machine testing but not for others. I came across a Microsoft article that I adapted and works.

using System;
using System.Security.Principal;

namespace ManageExclusion
{
    public static class UserIdentity

    {
        // concept borrowed from 
        // https://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity(v=vs.110).aspx

        public static string GetUser()
        {
            IntPtr accountToken = WindowsIdentity.GetCurrent().Token;
            WindowsIdentity windowsIdentity = new WindowsIdentity(accountToken);
            return windowsIdentity.Name;
        }
    }
}

Prevent Android activity dialog from closing on outside touch

When using dialog as an activity in the onCreate add this

setFinishOnTouchOutside(false);

How can I create a memory leak in Java?

Create a static Map and keep adding hard references to it. Those will never be garbage collected.

public class Leaker {
    private static final Map<String, Object> CACHE = new HashMap<String, Object>();

    // Keep adding until failure.
    public static void addToCache(String key, Object value) { Leaker.CACHE.put(key, value); }
}

How can I find the version of php that is running on a distinct domain name?

THE ANSWER IS : NMAP PROGRAM

THANKS FOR YOUR ATTENTIONS ...

another way is getting HTTP Headers by this site (http://web-sniffer.net/) or firefox add-on for getting HTTP Headers...

Best Regards

Uninitialized constant ActiveSupport::Dependencies::Mutex (NameError)

I have faced this problem in many occassions when I try to start an old rails 2.3.5 project after having worked with rails 3>. In my case to solve the problem, I must do a rubygems update to version 1.4.2, this is:

sudo gem update --system 1.4.2

List tables in a PostgreSQL schema

For those coming across this in the future:

If you would like to see a list of relations for several schemas:

$psql mydatabase
mydatabase=# SET search_path TO public, usa;   #schema examples
SET
mydatabase=# \dt
              List of relations
 Schema |      Name       | Type  |  Owner
--------+-----------------+-------+----------
 public | counties        | table | postgres
 public | spatial_ref_sys | table | postgres
 public | states          | table | postgres
 public | us_cities       | table | postgres
 usa    | census2010      | table | postgres

Creating a .p12 file

I'm debugging an issue I'm having with SSL connecting to a database (MySQL RDS) using an ORM called, Prisma. The database connection string requires a PKCS12 (.p12) file (if interested, described here), which brought me here.

I know the question has been answered, but I found the following steps (in Github Issue#2676) to be helpful for creating a .p12 file and wanted to share. Good luck!

  1. Generate 2048-bit RSA private key:

    openssl genrsa -out key.pem 2048

  2. Generate a Certificate Signing Request:

    openssl req -new -sha256 -key key.pem -out csr.csr

  3. Generate a self-signed x509 certificate suitable for use on web servers.

    openssl req -x509 -sha256 -days 365 -key key.pem -in csr.csr -out certificate.pem

  4. Create SSL identity file in PKCS12 as mentioned here

    openssl pkcs12 -export -out client-identity.p12 -inkey key.pem -in certificate.pem

Oracle Age calculation from Date of birth and Today

Suppose that you want to have the age (number of years only, a fixed number) of someone born on June 4, 1996, execute this command :

SELECT TRUNC(TO_NUMBER(SYSDATE - TO_DATE('04-06-1996')) / 365.25) AS AGE FROM DUAL;

Result : (Executed May 28, 2019)

       AGE
----------
        22

Explanation :

  • SYSDATE : Get system's (OS) actual date.
  • TO_DATE('04-06-1996') : Convert VARCHAR (string) birthdate into DATE (SQL type).
  • TO_NUMBER(...) : Convert a date to NUMBER (SQL type)
  • Devide per 365.25 : To have a bissextile year every four years (4 * 0.25 = 1 more day).
  • Trunc(...) : Retrieve the entire part only from a number.

How to annotate MYSQL autoincrement field with JPA annotations

To use a MySQL AUTO_INCREMENT column, you are supposed to use an IDENTITY strategy:

@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;

Which is what you'd get when using AUTO with MySQL:

@Id @GeneratedValue(strategy=GenerationType.AUTO)
private Long id;

Which is actually equivalent to

@Id @GeneratedValue
private Long id;

In other words, your mapping should work. But Hibernate should omit the id column in the SQL insert statement, and it is not. There must be a kind of mismatch somewhere.

Did you specify a MySQL dialect in your Hibernate configuration (probably MySQL5InnoDBDialect or MySQL5Dialect depending on the engine you're using)?

Also, who created the table? Can you show the corresponding DDL?

Follow-up: I can't reproduce your problem. Using the code of your entity and your DDL, Hibernate generates the following (expected) SQL with MySQL:

insert 
into
    Operator
    (active, password, username) 
values
    (?, ?, ?)

Note that the id column is absent from the above statement, as expected.

To sum up, your code, the table definition and the dialect are correct and coherent, it should work. If it doesn't for you, maybe something is out of sync (do a clean build, double check the build directory, etc) or something else is just wrong (check the logs for anything suspicious).

Regarding the dialect, the only difference between MySQL5Dialect or MySQL5InnoDBDialect is that the later adds ENGINE=InnoDB to the table objects when generating the DDL. Using one or the other doesn't change the generated SQL.

Why isn't textarea an input[type="textarea"]?

Maybe this is going a bit too far back but…

Also, I’d like to suggest that multiline text fields have a different type (e.g. “textarea") than single-line fields ("text"), as they really are different types of things, and imply different issues (semantics) for client-side handling.

Marc Andreessen, 11 October 1993

Ring Buffer in Java

I had the same problem some time ago and was disappointed because I couldn't find any solution that suites my needs so I wrote my own class. Honestly, I did found some code back then, but even that wasn't what I was searching for so I adapted it and now I'm sharing it, just like the author of that piece of code did.

EDIT: This is the original (although slightly different) code: CircularArrayList for java

I don't have the link of the source because it was time ago, but here's the code:

import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.RandomAccess;

public class CircularArrayList<E> extends AbstractList<E> implements RandomAccess {

private final int n; // buffer length
private final List<E> buf; // a List implementing RandomAccess
private int leader = 0;
private int size = 0;


public CircularArrayList(int capacity) {
    n = capacity + 1;
    buf = new ArrayList<E>(Collections.nCopies(n, (E) null));
}

public int capacity() {
    return n - 1;
}

private int wrapIndex(int i) {
    int m = i % n;
    if (m < 0) { // modulus can be negative
        m += n;
    }
    return m;
}

@Override
public int size() {
    return this.size;
}

@Override
public E get(int i) {
    if (i < 0 || i >= n-1) throw new IndexOutOfBoundsException();

    if(i > size()) throw new NullPointerException("Index is greater than size.");

    return buf.get(wrapIndex(leader + i));
}

@Override
public E set(int i, E e) {
    if (i < 0 || i >= n-1) {
        throw new IndexOutOfBoundsException();
    }
    if(i == size()) // assume leader's position as invalid (should use insert(e))
        throw new IndexOutOfBoundsException("The size of the list is " + size() + " while the index was " + i
                +". Please use insert(e) method to fill the list.");
    return buf.set(wrapIndex(leader - size + i), e);
}

public void insert(E e)
{
    int s = size();     
    buf.set(wrapIndex(leader), e);
    leader = wrapIndex(++leader);
    buf.set(leader, null);
    if(s == n-1)
        return; // we have replaced the eldest element.
    this.size++;

}

@Override
public void clear()
{
    int cnt = wrapIndex(leader-size());
    for(; cnt != leader; cnt = wrapIndex(++cnt))
        this.buf.set(cnt, null);
    this.size = 0;      
}

public E removeOldest() {
    int i = wrapIndex(leader+1);

    for(;;i = wrapIndex(++i)) {
        if(buf.get(i) != null) break;
        if(i == leader)
            throw new IllegalStateException("Cannot remove element."
                    + " CircularArrayList is empty.");
    }

    this.size--;
    return buf.set(i, null);
}

@Override
public String toString()
{
    int i = wrapIndex(leader - size());
    StringBuilder str = new StringBuilder(size());

    for(; i != leader; i = wrapIndex(++i)){
        str.append(buf.get(i));
    }
    return str.toString();
}

public E getOldest(){
    int i = wrapIndex(leader+1);

    for(;;i = wrapIndex(++i)) {
        if(buf.get(i) != null) break;
        if(i == leader)
            throw new IllegalStateException("Cannot remove element."
                    + " CircularArrayList is empty.");
    }

    return buf.get(i);
}

public E getNewest(){
    int i = wrapIndex(leader-1);
    if(buf.get(i) == null)
        throw new IndexOutOfBoundsException("Error while retrieving the newest element. The Circular Array list is empty.");
    return buf.get(i);
}
}

I get conflicting provisioning settings error when I try to archive to submit an iOS app

Please make sure the "Product Bundle Identifier" in Build settings name matches actual bundle identifier.This worked for me.

Python conversion between coordinates

There is a better way to write polar(), here it is:

def polar(x,y):
  `returns r, theta(degrees)`
  return math.hypot(x,y),math.degrees(math.atan2(y,x))

How do I include negative decimal numbers in this regular expression?

This will allow a - or + character only when followed by a number:

 ^([+-](?=\.?\d))?(\d+)?(\.\d+)?$

Git - fatal: Unable to create '/path/my_project/.git/index.lock': File exists

DO NOT USE the Atom platformio-atom-ide-terminal Plugin to do this. USE THE TERMINAL OF YOUR DISTRO DIRECTLY.

I kept getting this error while rebasing/squishing commits and didn't know why because I had done it before several times.

Didn't matter how many times I would delete the index.lock file, every time it would fail.

Turns out it was because I was using the ATOM EDITOR terminal plugin. Once I used the terminal that ships with Ubuntu it worked like a charm.

ReCaptcha API v2 Styling

A bit late but I tried this and it worked to make the Recaptcha responsive on screens smaller than 460px width. You can't use css selector to select elements inside the iframe. So, better use the outermost parent element which is the class g-recaptcha to basically zoom-out i.e transform the size of the entire container. Here's my code which worked:

@media(max-width:459.99px) {
    .modal .g-recaptcha {
        transform:scale(0.75);
        -webkit-transform:scale(0.75); }
    }
}

MySQL skip first 10 results

There is an OFFSET as well that should do the trick:

SELECT column FROM table
LIMIT 10 OFFSET 10

How do I get the size of a java.sql.ResultSet?

[Speed consideration]

Lot of ppl here suggests ResultSet.last() but for that you would need to open connection as a ResultSet.TYPE_SCROLL_INSENSITIVE which for Derby embedded database is up to 10 times SLOWER than ResultSet.TYPE_FORWARD_ONLY.

According to my micro-tests for embedded Derby and H2 databases it is significantly faster to call SELECT COUNT(*) before your SELECT.

Here is in more detail my code and my benchmarks

Batch files - number of command line arguments

The function :getargc below may be what you're looking for.

@echo off
setlocal enableextensions enabledelayedexpansion
call :getargc argc %*
echo Count is %argc%
echo Args are %*
endlocal
goto :eof

:getargc
    set getargc_v0=%1
    set /a "%getargc_v0% = 0"
:getargc_l0
    if not x%2x==xx (
        shift
        set /a "%getargc_v0% = %getargc_v0% + 1"
        goto :getargc_l0
    )
    set getargc_v0=
    goto :eof

It basically iterates once over the list (which is local to the function so the shifts won't affect the list back in the main program), counting them until it runs out.

It also uses a nifty trick, passing the name of the return variable to be set by the function.

The main program just illustrates how to call it and echos the arguments afterwards to ensure that they're untouched:

C:\Here> xx.cmd 1 2 3 4 5
    Count is 5
    Args are 1 2 3 4 5
C:\Here> xx.cmd 1 2 3 4 5 6 7 8 9 10 11
    Count is 11
    Args are 1 2 3 4 5 6 7 8 9 10 11
C:\Here> xx.cmd 1
    Count is 1
    Args are 1
C:\Here> xx.cmd
    Count is 0
    Args are
C:\Here> xx.cmd 1 2 "3 4 5"
    Count is 3
    Args are 1 2 "3 4 5"

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

Just do System.out.println(e.getActionCommand()); inside actionPerformed(ActionEvent e) function. This will tell you which command is just performed.

or

if(e.getActionCommand().equals("Add")){

   System.out.println("Add button pressed");
}

How to check if a file exists in a folder?

This helped me:

bool fileExists = (System.IO.File.Exists(filePath) ? true : false);

Connecting to SQL Server using windows authentication

use this code

Data Source=.;Initial Catalog=master;Integrated Security=True

What are the rules for JavaScript's automatic semicolon insertion (ASI)?

Straight from the ECMA-262, Fifth Edition ECMAScript Specification:

7.9.1 Rules of Automatic Semicolon Insertion

There are three basic rules of semicolon insertion:

  1. When, as the program is parsed from left to right, a token (called the offending token) is encountered that is not allowed by any production of the grammar, then a semicolon is automatically inserted before the offending token if one or more of the following conditions is true:
    • The offending token is separated from the previous token by at least one LineTerminator.
    • The offending token is }.
  2. When, as the program is parsed from left to right, the end of the input stream of tokens is encountered and the parser is unable to parse the input token stream as a single complete ECMAScript Program, then a semicolon is automatically inserted at the end of the input stream.
  3. When, as the program is parsed from left to right, a token is encountered that is allowed by some production of the grammar, but the production is a restricted production and the token would be the first token for a terminal or nonterminal immediately following the annotation "[no LineTerminator here]" within the restricted production (and therefore such a token is called a restricted token), and the restricted token is separated from the previous token by at least one LineTerminator, then a semicolon is automatically inserted before the restricted token.

However, there is an additional overriding condition on the preceding rules: a semicolon is never inserted automatically if the semicolon would then be parsed as an empty statement or if that semicolon would become one of the two semicolons in the header of a for statement (see 12.6.3).

PHP combine two associative arrays into one array

array_merge() is more efficient but there are a couple of options:

$array1 = array("id1" => "value1");

$array2 = array("id2" => "value2", "id3" => "value3", "id4" => "value4");

$array3 = array_merge($array1, $array2/*, $arrayN, $arrayN*/);
$array4 = $array1 + $array2;

echo '<pre>';
var_dump($array3);
var_dump($array4);
echo '</pre>';


// Results:
    array(4) {
      ["id1"]=>
      string(6) "value1"
      ["id2"]=>
      string(6) "value2"
      ["id3"]=>
      string(6) "value3"
      ["id4"]=>
      string(6) "value4"
    }
    array(4) {
      ["id1"]=>
      string(6) "value1"
      ["id2"]=>
      string(6) "value2"
      ["id3"]=>
      string(6) "value3"
      ["id4"]=>
      string(6) "value4"
    }

How to make HTTP Post request with JSON body in Swift

SWIFT 5 People Here :

let json: [String: Any] = ["key": "value"]

        let jsonData = try? JSONSerialization.data(withJSONObject: json)

        // create post request
        let url = URL(string: "http://localhost:1337/postrequest/addData")! //PUT Your URL
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("\(String(describing: jsonData?.count))", forHTTPHeaderField: "Content-Length")
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        // insert json data to the request
        request.httpBody = jsonData

        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {
                print(error?.localizedDescription ?? "No data")
                return
            }
            let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
            if let responseJSON = responseJSON as? [String: Any] {
                print(responseJSON) //Code after Successfull POST Request
            }
        }

        task.resume()

How to add header row to a pandas DataFrame

Alternatively you could read you csv with header=None and then add it with df.columns:

Cov = pd.read_csv("path/to/file.txt", sep='\t', header=None)
Cov.columns = ["Sequence", "Start", "End", "Coverage"]

How to remove &quot; from my Json in javascript?

i used replace feature in Notepad++ and replaced &quot; (without quotes) with " and result was valid json

Run a batch file with Windows task scheduler

For those whose bat files are still not working in Windows 8+ Task Scheduler , one thing I would like to add to Ghazi's answer - after much suffering:

1) Under Actions, Choose "Create BASIC task", not "Create Task"

That did it for me, plus the other issues not to forget:

  1. Use the Start In path to your batch file, even though it says optional
  2. use quotes, if you need to, in your Start a program > program/script entry i.e "C:\my scripts\runme.bat" ...
  3. BUT DON'T use quotes in your Start in field. (Crazy but true!)

This worked without any need to trigger a command prompt.

(Sorry my rep is too low to add my Basic Task tip to Ghazi's comments)

jQuery: keyPress Backspace won't fire?

I came across this myself. I used .on so it looks a bit different but I did this:

 $('#element').on('keypress', function() {
   //code to be executed
 }).on('keydown', function(e) {
   if (e.keyCode==8)
     $('element').trigger('keypress');
 });

Adding my Work Around here. I needed to delete ssn typed by user so i did this in jQuery

  $(this).bind("keydown", function (event) {
        // Allow: backspace, delete
        if (event.keyCode == 46 || event.keyCode == 8) 
        {
            var tempField = $(this).attr('name');
            var hiddenID = tempField.substr(tempField.indexOf('_') + 1);
            $('#' + hiddenID).val('');
            $(this).val('')
            return;
        }  // Allow: tab, escape, and enter
        else if (event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
        // Allow: Ctrl+A
        (event.keyCode == 65 && event.ctrlKey === true) ||
        // Allow: home, end, left, right
        (event.keyCode >= 35 && event.keyCode <= 39)) {
            // let it happen, don't do anything
            return;
        }
        else 
        {
            // Ensure that it is a number and stop the keypress
            if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) &&       (event.keyCode < 96 || event.keyCode > 105)) 
            {
                event.preventDefault();
            }
        }
    });

Integer division with remainder in JavaScript?

Alex Moore-Niemi's comment as an answer:

For Rubyists here from Google in search of divmod, you can implement it as such:

function divmod(x, y) {
  var div = Math.trunc(x/y);
  var rem = x % y;
  return [div, rem];
}

Result:

// [2, 33]

How to add an image to the emulator gallery in android studio?

After trying to add an image via the Device Monitor or via drop, I could find it when exploring, but it was still not shown in the Gallery.

For me, it helped to eject the (virtual) sdcard from Settings > Storage & USB and reinserting it.

Is there a Google Voice API?

I needed a C# API and after spending hours looking for it (all I found was outdated and non-working) and unsuccessfully trying to port the PHP/Python/Java versions listed here (none worked either) I decided to create my own. It's SMS-only for now...

https://bitbucket.org/jitbit/sharpgooglevoice/wiki/Home

Visual Studio 2010 shortcut to find classes and methods?

Ctrl+K,Ctrl+R opens the Object Browser in Visual Studio 2010. Find what you're looking for by searching and browsing and filtering the results. See also Ctrl+Alt+J. ^K ^R is better because it puts your caret right in the search box, ready to type your new search, even when the Object Browser is already open.

Set the Browse list on the top left to where you want to look to get started. From there you can use the search box (2nd text box from the top, goes all the way across the Object Browser window) or you can just go through everything from the tree on the left. Searches are temporary but the "selected components" set by the Browse list persists. Set a custom set with the little "..." button just to the right of the list.

Objects, packages, namespaces, types, etc. on the left; fields, methods, constants, etc. on the top right, docstrings on the lower right.

The display mode of a pane can be changed by right-clicking in the empty space of the window; tree organized by assembly/container or by namespace and other preferences.

Items can be right-clicked to find, copy and filter.

For keyboard navigation, use Ctrl+K,Ctrl+R from anywhere to start a new search, Enter to execute the search you just typed or pasted and Ctrl+F6 to make the Object Browser close. ALT+<-- to go back and ALT+--> to go forward through the search history. More can be set; search for "ObjectBrowser" in the keyboard shortcut config.

If the key shortcuts above don't work, Object Browser should be in the View menu somewhere with a different shortcut. If all else fails, search for "ObjectBrowser" under Tools->Options->Environment->Keyboard->"Show commands containing".

How do I catch a PHP fatal (`E_ERROR`) error?

I developed this function to make it possible to "sandbox" code that could cause a fatal error. Since exceptions thrown from the closure register_shutdown_function don't get emitted from the pre-fatal error call stack, I'm forced to exit after this function to provide a uniform way of using it.

function superTryCatchFinallyAndExit( Closure $try, Closure $catch = NULL, Closure $finally )
{
    $finished = FALSE;
    register_shutdown_function( function() use ( &$finished, $catch, $finally ) {
        if( ! $finished ) {
            $finished = TRUE;
            print "EXPLODE!".PHP_EOL;
            if( $catch ) {
                superTryCatchFinallyAndExit( function() use ( $catch ) {
                    $catch( new Exception( "Fatal Error!!!" ) );
                }, NULL, $finally );                
            } else {
                $finally();                
            }
        }
    } );
    try {
        $try();
    } catch( Exception $e ) {
        if( $catch ) {
            try {
                $catch( $e );
            } catch( Exception $e ) {}
        }
    }
    $finished = TRUE;
    $finally();
    exit();
}

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

I opened one Word file, 2. Now I open another word file through vb.net runtime programmatically. 3. I want to kill the second process alone through programmatically. 4. Do not kill first process

Display a table/list data dynamically in MVC3/Razor from a JsonResult?

As Mystere Man suggested, getting just a view first and then again making an ajax call again to get the json result is unnecessary in this case. that is 2 calls to the server. I think you can directly return an HTML table of Users in the first call.

We will do this in this way. We will have a strongly typed view which will return the markup of list of users to the browser and this data is being supplied by an action method which we will invoke from our browser using an http request.

Have a ViewModel for the User

public class UserViewModel
{
  public int UserID { set;get;}
  public string FirstName { set;get;}
   //add remaining properties as per your requirement

}

and in your controller have a method to get a list of Users

public class UserController : Controller
{

   [HttpGet]
   public ActionResult List()
   {
     List<UserViewModel> objList=UserService.GetUsers();  // this method should returns list of  Users
     return View("users",objList)        
   }
}

Assuming that UserService.GetUsers() method will return a List of UserViewModel object which represents the list of usres in your datasource (Tables)

and in your users.cshtml ( which is under Views/User folder),

 @model List<UserViewModel>

 <table>

 @foreach(UserViewModel objUser in Model)
 {
   <tr>
      <td>@objUser.UserId.ToString()</td>
      <td>@objUser.FirstName</td>
   </tr>
 }
 </table>

All Set now you can access the url like yourdomain/User/List and it will give you a list of users in an HTML table.

Python 3 TypeError: must be str, not bytes with sys.stdout.write()

Python 3 handles strings a bit different. Originally there was just one type for strings: str. When unicode gained traction in the '90s the new unicode type was added to handle Unicode without breaking pre-existing code1. This is effectively the same as str but with multibyte support.

In Python 3 there are two different types:

  • The bytes type. This is just a sequence of bytes, Python doesn't know anything about how to interpret this as characters.
  • The str type. This is also a sequence of bytes, but Python knows how to interpret those bytes as characters.
  • The separate unicode type was dropped. str now supports unicode.

In Python 2 implicitly assuming an encoding could cause a lot of problems; you could end up using the wrong encoding, or the data may not have an encoding at all (e.g. it’s a PNG image).
Explicitly telling Python which encoding to use (or explicitly telling it to guess) is often a lot better and much more in line with the "Python philosophy" of "explicit is better than implicit".

This change is incompatible with Python 2 as many return values have changed, leading to subtle problems like this one; it's probably the main reason why Python 3 adoption has been so slow. Since Python doesn't have static typing2 it's impossible to change this automatically with a script (such as the bundled 2to3).

  • You can convert str to bytes with bytes('h€llo', 'utf-8'); this should produce b'H\xe2\x82\xacllo'. Note how one character was converted to three bytes.
  • You can convert bytes to str with b'H\xe2\x82\xacllo'.decode('utf-8').

Of course, UTF-8 may not be the correct character set in your case, so be sure to use the correct one.

In your specific piece of code, nextline is of type bytes, not str, reading stdout and stdin from subprocess changed in Python 3 from str to bytes. This is because Python can't be sure which encoding this uses. It probably uses the same as sys.stdin.encoding (the encoding of your system), but it can't be sure.

You need to replace:

sys.stdout.write(nextline)

with:

sys.stdout.write(nextline.decode('utf-8'))

or maybe:

sys.stdout.write(nextline.decode(sys.stdout.encoding))

You will also need to modify if nextline == '' to if nextline == b'' since:

>>> '' == b''
False

Also see the Python 3 ChangeLog, PEP 358, and PEP 3112.


1 There are some neat tricks you can do with ASCII that you can't do with multibyte character sets; the most famous example is the "xor with space to switch case" (e.g. chr(ord('a') ^ ord(' ')) == 'A') and "set 6th bit to make a control character" (e.g. ord('\t') + ord('@') == ord('I')). ASCII was designed in a time when manipulating individual bits was an operation with a non-negligible performance impact.

2 Yes, you can use function annotations, but it's a comparatively new feature and little used.

In laymans terms, what does 'static' mean in Java?

The static keyword can be used in several different ways in Java and in almost all cases it is a modifier which means the thing it is modifying is usable without an enclosing object instance.

Java is an object oriented language and by default most code that you write requires an instance of the object to be used.

public class SomeObject {
    public int someField;
    public void someMethod() { };
    public Class SomeInnerClass { };
}

In order to use someField, someMethod, or SomeInnerClass I have to first create an instance of SomeObject.

public class SomeOtherObject {
    public void doSomeStuff() {
        SomeObject anInstance = new SomeObject();
        anInstance.someField = 7;
        anInstance.someMethod();
        //Non-static inner classes are usually not created outside of the
        //class instance so you don't normally see this syntax
        SomeInnerClass blah = anInstance.new SomeInnerClass();
    }
}

If I declare those things static then they do not require an enclosing instance.

public class SomeObjectWithStaticStuff {
    public static int someField;
    public static void someMethod() { };
    public static Class SomeInnerClass { };
}

public class SomeOtherObject {
    public void doSomeStuff() {
        SomeObjectWithStaticStuff.someField = 7;
        SomeObjectWithStaticStuff.someMethod();
        SomeObjectWithStaticStuff.SomeInnerClass blah = new SomeObjectWithStaticStuff.SomeInnerClass();
        //Or you can also do this if your imports are correct
        SomeInnerClass blah2 = new SomeInnerClass();
    }
}

Declaring something static has several implications.

First, there can only ever one value of a static field throughout your entire application.

public class SomeOtherObject {
    public void doSomeStuff() {
        //Two objects, two different values
        SomeObject instanceOne = new SomeObject();
        SomeObject instanceTwo = new SomeObject();
        instanceOne.someField = 7;
        instanceTwo.someField = 10;
        //Static object, only ever one value
        SomeObjectWithStaticStuff.someField = 7;
        SomeObjectWithStaticStuff.someField = 10; //Redefines the above set
    }
}

The second issue is that static methods and inner classes cannot access fields in the enclosing object (since there isn't one).

public class SomeObjectWithStaticStuff {
    private int nonStaticField;
    private void nonStaticMethod() { };

    public static void someStaticMethod() {
        nonStaticField = 7; //Not allowed
        this.nonStaticField = 7; //Not allowed, can never use *this* in static
        nonStaticMethod(); //Not allowed
        super.someSuperMethod(); //Not allowed, can never use *super* in static
    }

    public static class SomeStaticInnerClass {

        public void doStuff() {
            someStaticField = 7; //Not allowed
            nonStaticMethod(); //Not allowed
            someStaticMethod(); //This is ok
        }

    }
}

The static keyword can also be applied to inner interfaces, annotations, and enums.

public class SomeObject {
    public static interface SomeInterface { };
    public static @interface SomeAnnotation { };
    public static enum SomeEnum { };
}

In all of these cases the keyword is redundant and has no effect. Interfaces, annotations, and enums are static by default because they never have a relationship to an inner class.

This just describes what they keyword does. It does not describe whether the use of the keyword is a bad idea or not. That can be covered in more detail in other questions such as Is using a lot of static methods a bad thing?

There are also a few less common uses of the keyword static. There are static imports which allow you to use static types (including interfaces, annotations, and enums not redundantly marked static) unqualified.

//SomeStaticThing.java
public class SomeStaticThing {
    public static int StaticCounterOne = 0;
}

//SomeOtherStaticThing.java
public class SomeOtherStaticThing {
    public static int StaticCounterTwo = 0;
}

//SomeOtherClass.java
import static some.package.SomeStaticThing.*;
import some.package.SomeOtherStaticThing.*;

public class SomeOtherClass {
    public void doStuff() {
        StaticCounterOne++; //Ok
        StaticCounterTwo++; //Not ok
        SomeOtherStaticThing.StaticCounterTwo++; //Ok
    }
}

Lastly, there are static initializers which are blocks of code that are run when the class is first loaded (which is usually just before a class is instantiated for the first time in an application) and (like static methods) cannot access non-static fields or methods.

public class SomeObject {

    private static int x;

    static {
        x = 7;
    }
}

How to retrieve current workspace using Jenkins Pipeline Groovy script?

In Jenkins pipeline script, I am using

targetDir = workspace

Works perfect for me. No need to use ${WORKSPACE}

Test for multiple cases in a switch, like an OR (||)

Forget switch and break, lets play with if. And instead of asserting

if(pageid === "listing-page" || pageid === "home-page")

lets create several arrays with cases and check it with Array.prototype.includes()

var caseA = ["listing-page", "home-page"];
var caseB = ["details-page", "case04", "case05"];

if(caseA.includes(pageid)) {
    alert("hello");
}
else if (caseB.includes(pageid)) {
    alert("goodbye");
}
else {
    alert("there is no else case");
}

SQLite equivalent to ISNULL(), NVL(), IFNULL() or COALESCE()

For the equivalent of NVL() and ISNULL() use:

IFNULL(column, altValue)

column : The column you are evaluating.

altValue : The value you want to return if 'column' is null.

Example:

SELECT IFNULL(middle_name, 'N/A') FROM person;

*Note: The COALESCE() function works the same as it does for other databases.

Sources:

Convert string to Boolean in javascript

I would like to answer this to improve upon the accepted answer.

To improve performance, and in real world cases where form inputs might be passing values like 'true', or 'false', this method will produce the best results.

function stringToBool(val) {
    return (val + '').toLowerCase() === 'true';
}

JSPerf

enter image description here

c# datatable insert column at position 0

    //Example to define how to do :

    DataTable dt = new DataTable();   

    dt.Columns.Add("ID");
    dt.Columns.Add("FirstName");
    dt.Columns.Add("LastName");
    dt.Columns.Add("Address");
    dt.Columns.Add("City");
           //  The table structure is:
            //ID    FirstName   LastName    Address     City

       //Now we want to add a PhoneNo column after the LastName column. For this we use the                               
             //SetOrdinal function, as iin:
        dt.Columns.Add("PhoneNo").SetOrdinal(3);

            //3 is the position number and positions start from 0.`enter code here`

               //Now the table structure will be:
              // ID      FirstName   LastName    PhoneNo    Address     City

How to save an activity state using save instance state?

To get activity state data stored in onCreate(), first you have to save data in savedInstanceState by overriding SaveInstanceState(Bundle savedInstanceState) method.

When activity destroy SaveInstanceState(Bundle savedInstanceState) method gets called and there you save data you want to save. And you get same in onCreate() when activity restart.(savedInstanceState wont be null since you have saved some data in it before activity get destroyed)

Is it acceptable and safe to run pip install under sudo?

It looks like your permissions are messed up. Type chown -R markwalker ~ in the Terminal and try pip again? Let me know if you're sorted.

How to get the xml node value in string

The problem in your code is xml.LoadXml(filePath);

LoadXml method take parameter as xml data not the xml file path

Try this code

   string xmlFile = File.ReadAllText(@"D:\Work_Time_Calculator\10-07-2013.xml");
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.LoadXml(xmlFile);
                XmlNodeList nodeList = xmldoc.GetElementsByTagName("Short_Fall");
                string Short_Fall=string.Empty;
                foreach (XmlNode node in nodeList)
                {
                    Short_Fall = node.InnerText;
                }

Edit

Seeing the last edit of your question i found the solution,

Just replace the below 2 lines

XmlNode node = xml.SelectSingleNode("/Data[@*]/Short_Fall");
string id = node["Short_Fall"].InnerText; // Exception occurs here ("Object reference not set to an instance of an object.")

with

string id = xml.SelectSingleNode("Data/Short_Fall").InnerText;

It should solve your problem or you can use the solution i provided earlier.

SQL Server - Return value after INSERT

INSERT INTO files (title) VALUES ('whatever'); 
SELECT * FROM files WHERE id = SCOPE_IDENTITY();

Is the safest bet since there is a known issue with OUTPUT Clause conflict on tables with triggers. Makes this quite unreliable as even if your table doesn't currently have any triggers - someone adding one down the line will break your application. Time Bomb sort of behaviour.

See msdn article for deeper explanation:

http://blogs.msdn.com/b/sqlprogrammability/archive/2008/07/11/update-with-output-clause-triggers-and-sqlmoreresults.aspx

Import pfx file into particular certificate store from command line

Anchoring my findings here for future readers.

Import certificate to Trusted Root Certification Authorities on Local Machine:

CERTUTIL -addstore -enterprise -f -v root "somCertificat.cer"

Import pfx to Personal on local machine

CERTUTIL -f -p somePassword -importpfx "somePfx.pfx"

Import pfx to Trusted People on local machine - Link to importpfx.exe

importpfx.exe -f "somePfx.pfx" -p "somePassword" -t MACHINE -s "TRUSTEDPEOPLE"

Import certificate to Trusted People on local machine

Certutil -addstore -f "TRUSTEDPEOPLE" "someCertificate.cer"

Notification not showing in Oreo

Try this Code :

_x000D_
_x000D_
public class FirebaseMessagingServices extends com.google.firebase.messaging.FirebaseMessagingService {_x000D_
    private static final String TAG = "MY Channel";_x000D_
    Bitmap bitmap;_x000D_
_x000D_
    @Override_x000D_
    public void onMessageReceived(RemoteMessage remoteMessage) {_x000D_
        super.onMessageReceived(remoteMessage);_x000D_
        Utility.printMessage(remoteMessage.getNotification().getBody());_x000D_
_x000D_
        // Check if message contains a data payload._x000D_
        if (remoteMessage.getData().size() > 0) {_x000D_
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());_x000D_
_x000D_
            String title = remoteMessage.getData().get("title");_x000D_
            String body = remoteMessage.getData().get("body");_x000D_
            String message = remoteMessage.getData().get("message");_x000D_
            String imageUri = remoteMessage.getData().get("image");_x000D_
            String msg_id = remoteMessage.getData().get("msg-id");_x000D_
          _x000D_
_x000D_
            Log.d(TAG, "1: " + title);_x000D_
            Log.d(TAG, "2: " + body);_x000D_
            Log.d(TAG, "3: " + message);_x000D_
            Log.d(TAG, "4: " + imageUri);_x000D_
          _x000D_
_x000D_
            if (imageUri != null)_x000D_
                bitmap = getBitmapfromUrl(imageUri);_x000D_
_x000D_
            }_x000D_
_x000D_
            sendNotification(message, bitmap, title, msg_id);_x000D_
                    _x000D_
        }_x000D_
_x000D_
_x000D_
    }_x000D_
_x000D_
    private void sendNotification(String message, Bitmap image, String title,String msg_id) {_x000D_
        int notifyID = 0;_x000D_
        try {_x000D_
            notifyID = Integer.parseInt(msg_id);_x000D_
        } catch (NumberFormatException e) {_x000D_
            e.printStackTrace();_x000D_
        }_x000D_
_x000D_
        String CHANNEL_ID = "my_channel_01";            // The id of the channel._x000D_
        Intent intent = new Intent(this, HomeActivity.class);_x000D_
        intent.putExtra("title", title);_x000D_
        intent.putExtra("message", message);_x000D_
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);_x000D_
_x000D_
_x000D_
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,_x000D_
                PendingIntent.FLAG_ONE_SHOT);_x000D_
_x000D_
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);_x000D_
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "01")_x000D_
                .setContentTitle(title)_x000D_
                .setSmallIcon(R.mipmap.ic_notification)_x000D_
                .setStyle(new NotificationCompat.BigTextStyle()_x000D_
                        .bigText(message))_x000D_
                .setContentText(message)_x000D_
                .setAutoCancel(true)_x000D_
                .setSound(defaultSoundUri)_x000D_
                .setChannelId(CHANNEL_ID)_x000D_
                .setContentIntent(pendingIntent);_x000D_
_x000D_
        if (image != null) {_x000D_
            notificationBuilder.setStyle(new NotificationCompat.BigPictureStyle()   //Set the Image in Big picture Style with text._x000D_
                    .bigPicture(image)_x000D_
                    .setSummaryText(message)_x000D_
                    .bigLargeIcon(null));_x000D_
        }_x000D_
_x000D_
_x000D_
        NotificationManager notificationManager =_x000D_
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);_x000D_
_x000D_
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {       // For Oreo and greater than it, we required Notification Channel._x000D_
           CharSequence name = "My New Channel";                   // The user-visible name of the channel._x000D_
            int importance = NotificationManager.IMPORTANCE_HIGH;_x000D_
_x000D_
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID,name, importance); //Create Notification Channel_x000D_
            notificationManager.createNotificationChannel(channel);_x000D_
        }_x000D_
_x000D_
        notificationManager.notify(notifyID /* ID of notification */, notificationBuilder.build());_x000D_
    }_x000D_
_x000D_
    public Bitmap getBitmapfromUrl(String imageUrl) {     //This method returns the Bitmap from Url;_x000D_
        try {_x000D_
            URL url = new URL(imageUrl);_x000D_
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();_x000D_
            connection.setDoInput(true);_x000D_
            connection.connect();_x000D_
            InputStream input = connection.getInputStream();_x000D_
            Bitmap bitmap = BitmapFactory.decodeStream(input);_x000D_
            return bitmap;_x000D_
_x000D_
        } catch (Exception e) {_x000D_
            // TODO Auto-generated catch block_x000D_
            e.printStackTrace();_x000D_
            return null;_x000D_
_x000D_
        }_x000D_
_x000D_
    }_x000D_
_x000D_
}
_x000D_
_x000D_
_x000D_

How to stop BackgroundWorker correctly

I agree with guys. But sometimes you have to add more things.

IE

1) Add this worker.WorkerSupportsCancellation = true;

2) Add to you class some method to do the following things

public void KillMe()
{
   worker.CancelAsync();
   worker.Dispose();
   worker = null;
   GC.Collect();
}

So before close your application your have to call this method.

3) Probably you can Dispose, null all variables and timers which are inside of the BackgroundWorker.

Android: Internet connectivity change listener

Try this

public class NetworkUtil {
    public static final int TYPE_WIFI = 1;
    public static final int TYPE_MOBILE = 2;
    public static final int TYPE_NOT_CONNECTED = 0;
    public static final int NETWORK_STATUS_NOT_CONNECTED = 0;
    public static final int NETWORK_STATUS_WIFI = 1;
    public static final int NETWORK_STATUS_MOBILE = 2;

    public static int getConnectivityStatus(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (null != activeNetwork) {
            if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
                return TYPE_WIFI;

            if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
                return TYPE_MOBILE;
        } 
        return TYPE_NOT_CONNECTED;
    }

    public static int getConnectivityStatusString(Context context) {
        int conn = NetworkUtil.getConnectivityStatus(context);
        int status = 0;
        if (conn == NetworkUtil.TYPE_WIFI) {
            status = NETWORK_STATUS_WIFI;
        } else if (conn == NetworkUtil.TYPE_MOBILE) {
            status = NETWORK_STATUS_MOBILE;
        } else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
            status = NETWORK_STATUS_NOT_CONNECTED;
        }
        return status;
    }
}

And for the BroadcastReceiver

public class NetworkChangeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, final Intent intent) {

        int status = NetworkUtil.getConnectivityStatusString(context);
        Log.e("Sulod sa network reciever", "Sulod sa network reciever");
        if ("android.net.conn.CONNECTIVITY_CHANGE".equals(intent.getAction())) {
            if (status == NetworkUtil.NETWORK_STATUS_NOT_CONNECTED) {
                new ForceExitPause(context).execute();
            } else {
                new ResumeForceExitPause(context).execute();
            }
       }
    }
}

Don't forget to put this into your AndroidManifest.xml

 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 <uses-permission android:name="android.permission.INTERNET" />
 <receiver
        android:name="NetworkChangeReceiver"
        android:label="NetworkChangeReceiver" >
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
        </intent-filter>
    </receiver>

Hope this will help you Cheers!

setup android on eclipse but don't know SDK directory

Search (Ctrl+F) your harddrive(s) for: SDK Manager.exe or adb.exe

How to install pip for Python 3.6 on Ubuntu 16.10?

This answer assumes that you have python3.6 installed. For python3.7, replace 3.6 with 3.7. For python3.8, replace 3.6 with 3.8, but it may also first require the python3.8-distutils package.

Installation with sudo

With regard to installing pip, using curl (instead of wget) avoids writing the file to disk.

curl https://bootstrap.pypa.io/get-pip.py | sudo -H python3.6

The -H flag is evidently necessary with sudo in order to prevent errors such as the following when installing pip for an updated python interpreter:

The directory '/home/someuser/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.

The directory '/home/someuser/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.

Installation without sudo

curl https://bootstrap.pypa.io/get-pip.py | python3.6 - --user

This may sometimes give a warning such as:

WARNING: The script wheel is installed in '/home/ubuntu/.local/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.

Verification

After this, pip, pip3, and pip3.6 can all be expected to point to the same target:

$ (pip -V && pip3 -V && pip3.6 -V) | uniq
pip 18.0 from /usr/local/lib/python3.6/dist-packages (python 3.6)

Of course you can alternatively use python3.6 -m pip as well.

$ python3.6 -m pip -V
pip 18.0 from /usr/local/lib/python3.6/dist-packages (python 3.6)

Shortcut to comment out a block of code with sublime text

Just in case someone is using the Portuguese ABNT keyboard layout The shortcut is

Ctrl + ;

How to detect orientation change in layout in Android?

Use the onConfigurationChanged method of Activity. See the following code:

@Override
public void onConfigurationChanged(@NotNull Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    }
}

You also have to edit the appropriate element in your manifest file to include the android:configChanges Just see the code below:

<activity android:name=".MyActivity"
          android:configChanges="orientation|keyboardHidden"
          android:label="@string/app_name">

NOTE: with Android 3.2 (API level 13) or higher, the "screen size" also changes when the device switches between portrait and landscape orientation. Thus, if you want to prevent runtime restarts due to orientation change when developing for API level 13 or higher, you must declare android:configChanges="orientation|screenSize" for API level 13 or higher.

Hope this will help you... :)

The infamous java.sql.SQLException: No suitable driver found

In my case I was working on a Java project with Maven and encountered this error. In your pom.xml file make sure you have this dependencies

<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.11</version>
    </dependency>
  </dependencies>

and where you create connection have something like this

public Connection createConnection() {
        try {
            String url = "jdbc:mysql://localhost:3306/yourDatabaseName";
            String username = "root"; //your my sql username here
            String password = "1234"; //your mysql password here

            Class.forName("com.mysql.cj.jdbc.Driver");
            return DriverManager.getConnection(url, username, password);
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        return null;
    }

Can't find @Nullable inside javax.annotation.*

I am using Guava which has annotation included:

(Gradle code )

compile 'com.google.guava:guava:23.4-jre'

How to pick element inside iframe using document.getElementById

document.getElementById('myframe1').contentWindow.document.getElementById('x')

Fiddle

contentWindow is supported by all browsers including the older versions of IE.

Note that if the iframe's src is from another domain, you won't be able to access its content due to the Same Origin Policy.

Inserting values to SQLite table in Android

okk this is fully working code edit it as per your requirement

public class TestProjectActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    SQLiteDatabase db;
    db = openOrCreateDatabase( "Temp.db"        , SQLiteDatabase.CREATE_IF_NECESSARY        , null          );
    try {
        final String CREATE_TABLE_CONTAIN = "CREATE TABLE IF NOT EXISTS tbl_Contain ("
                + "ID INTEGER primary key AUTOINCREMENT,"
                + "DESCRIPTION TEXT,"
                + "expirydate DATETIME,"
                + "AMOUNT TEXT,"
                + "TRNS TEXT," + "isdefault TEXT);";
        db.execSQL(CREATE_TABLE_CONTAIN);
        Toast.makeText(TestProjectActivity.this, "table created ", Toast.LENGTH_LONG).show();
        String sql =
            "INSERT or replace INTO tbl_Contain (DESCRIPTION, expirydate, AMOUNT, TRNS,isdefault) VALUES('this is','03/04/2005','5000','tran','y')" ;       
                db.execSQL(sql);
    }
    catch (Exception e) {
        Toast.makeText(TestProjectActivity.this, "ERROR "+e.toString(), Toast.LENGTH_LONG).show();  
}}}

Hope this is useful for you..
do not use TEXT for date field may be that was casing problem still getting problem let me know :)Pragna

$.ajax( type: "POST" POST method to php

You need to use data: {title: title} to POST it correctly.

In the PHP code you need to echo the value instead of returning it.

How to resolve ORA-011033: ORACLE initialization or shutdown in progress

What worked for me is that i hadn't set the local_listener, to see if the local listener is set login to sqlplus / as sysdba, make sure the database is open and run the following command show parameter local_listener, if the value is empty, then you will have to set the local_listener with the following SQL command ALTER SYSTEM SET LOCAL_LISTENER='<LISTENER_NAME_GOES_HERE>'

AngularJS Dropdown required validation

You need to add a name attribute to your dropdown list, then you need to add a required attribute, and then you can reference the error using myForm.[input name].$error.required:

HTML:

        <form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
        <input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
          <select name="service_id" class="Sitedropdown" style="width: 220px;"          
                  ng-model="ServiceID" 
                  ng-options="service.ServiceID as service.ServiceName for service in services"
                  required> 
            <option value="">Select Service</option> 
          </select> 
          <span ng-show="myForm.service_id.$error.required">Select service</span>

        </form>

    Controller:

        function Ctrl($scope) {
          $scope.services = [
            {ServiceID: 1, ServiceName: 'Service1'},
            {ServiceID: 2, ServiceName: 'Service2'},
            {ServiceID: 3, ServiceName: 'Service3'}
          ];

    $scope.save = function(myForm) {
    console.log('Selected Value: '+ myForm.service_id.$modelValue);
    alert('Data Saved! without validate');
    };
        }

Here's a working plunker.

Fatal error: Call to undefined function curl_init()

$ch = curl_init('http://api.imgur.com/2/upload.xml'); //initialising our url

curl_setopt($ch, CURLOPT_MUTE, 1);

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);  //used for https headers 

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);  //used for https headers

curl_setopt($ch, CURLOPT_POST, 1);

curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode($pvars));  
//the value we post

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //waiting for reponse, default value in php is zero ie, curls normally do not wait for a response

curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0'); 

$output = curl_exec($ch); //the real execution 
curl_close($ch);

echo $output;

Try this code. I am not sure about it. But i used it to send xml data to a remote url.

javascript get x and y coordinates on mouse click

simple solution is this:

game.js:

document.addEventListener('click', printMousePos, true);
function printMousePos(e){

      cursorX = e.pageX;
      cursorY= e.pageY;
      $( "#test" ).text( "pageX: " + cursorX +",pageY: " + cursorY );
}

Set cookie and get cookie with JavaScript

These are much much better references than w3schools (the most awful web reference ever made):

Examples derived from these references:

// sets the cookie cookie1
document.cookie = 'cookie1=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'

// sets the cookie cookie2 (cookie1 is *not* overwritten)
document.cookie = 'cookie2=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'

// remove cookie2
document.cookie = 'cookie2=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/'

The Mozilla reference even has a nice cookie library you can use.

Is there an API to get bank transaction and bank balance?

I use GNU Cash and it uses Open Financial Exchange (ofx) http://www.ofx.net/ to download complete transactions and balances from each account of each bank.

Let me emphasize that again, you get a huge list of transactions with OFX into the GNU Cash. Depending on the account type these transactions can be very detailed description of your transactions (purchases+paycheques), investments, interests, etc.

In my case, even though I have Chase debit card I had to choose Chase Credit to make it work. But Chase wants you to enable this OFX feature by logging into your online banking and enable Quicken/MS Money/etc. somewhere in your profile or preferences. Don't call Chase customer support because they know nothing about it.

This service for OFX and GNU Cash is free. I have heard that they charge $10 a month for other platforms.

OFX can download transactions from 348 banks so far. http://www.ofxhome.com/index.php/home/directory

Actualy, OFX also supports making bill payments, stop a check, intrabank and interbank transfers etc. It is quite extensive. See it here: http://ofx.net/AboutOFX/ServicesSupported.aspx

Create a remote branch on GitHub

It looks like github has a simple UI for creating branches. I opened the branch drop-down and it prompts me to "Find or create a branch ...". Type the name of your new branch, then click the "create" button that appears.

To retrieve your new branch from github, use the standard git fetch command.

create branch github ui

I'm not sure this will help your underlying problem, though, since the underlying data being pushed to the server (the commit objects) is the same no matter what branch it's being pushed to.

Uncaught TypeError: Cannot read property 'value' of undefined

Seems like one of your values, with a property key of 'value' is undefined. Test that i1, i2and __i are defined before executing the if statements:

var i1 = document.getElementById('i1');
var i2 = document.getElementById('i2');
var __i = {'user' : document.getElementsByName("username")[0], 'pass' : document.getElementsByName("password")[0] };
if(i1 && i2 && __i.user && __i.pass)
{
    if(  __i.user.value.length >= 1 ) { i1.value = ''; } else { i1.value = 'Acc'; }

    if(  __i.pass.value.length >= 1 ) { i2.value = ''; } else { i2.value = 'Pwd'; }
}

Advantage of switch over if-else statement

Compiler will optimise it anyway - go for the switch as it's the most readable.

How do I fix a compilation error for unhandled exception on call to Thread.sleep()?

Thread.sleep can throw an InterruptedException which is a checked exception. All checked exceptions must either be caught and handled or else you must declare that your method can throw it. You need to do this whether or not the exception actually will be thrown. Not declaring a checked exception that your method can throw is a compile error.

You either need to catch it:

try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    e.printStackTrace();
    // handle the exception...        
    // For example consider calling Thread.currentThread().interrupt(); here.
}

Or declare that your method can throw an InterruptedException:

public static void main(String[]args) throws InterruptedException

Related

How to include duplicate keys in HashMap?

hashMaps can't have duplicate keys. That said, you can create a map with list values:

Map<Integer, List<String>>

However, using this approach will have performance implications.

ArrayBuffer to base64 encoded string

var blob = new Blob([arrayBuffer])

var reader = new FileReader();
reader.onload = function(event){
   var base64 =   event.target.result
};

reader.readAsDataURL(blob);

Can I replace groups in Java regex?

Here is a different solution, that also allows the replacement of a single group in multiple matches. It uses stacks to reverse the execution order, so the string operation can be safely executed.

private static void demo () {

    final String sourceString = "hello world!";

    final String regex = "(hello) (world)(!)";
    final Pattern pattern = Pattern.compile(regex);

    String result = replaceTextOfMatchGroup(sourceString, pattern, 2, world -> world.toUpperCase());
    System.out.println(result);  // output: hello WORLD!
}

public static String replaceTextOfMatchGroup(String sourceString, Pattern pattern, int groupToReplace, Function<String,String> replaceStrategy) {
    Stack<Integer> startPositions = new Stack<>();
    Stack<Integer> endPositions = new Stack<>();
    Matcher matcher = pattern.matcher(sourceString);

    while (matcher.find()) {
        startPositions.push(matcher.start(groupToReplace));
        endPositions.push(matcher.end(groupToReplace));
    }
    StringBuilder sb = new StringBuilder(sourceString);
    while (! startPositions.isEmpty()) {
        int start = startPositions.pop();
        int end = endPositions.pop();
        if (start >= 0 && end >= 0) {
            sb.replace(start, end, replaceStrategy.apply(sourceString.substring(start, end)));
        }
    }
    return sb.toString();       
}

Loading .sql files from within PHP

I hope the following code will solve your problem pretty well.

//Empty all tables' contents

$result_t = mysql_query("SHOW TABLES");
while($row = mysql_fetch_assoc($result_t))
{
mysql_query("TRUNCATE " . $row['Tables_in_' . $mysql_database]);
}
// Temporary variable, used to store current query
$templine = '';
// Read in entire file
$lines = file($filename);
// Loop through each line
foreach ($lines as $line)
{
// Skip it if it's a comment
if (substr($line, 0, 2) == '--' || $line == '')
    continue;

// Add this line to the current segment
$templine .= $line;
// If it has a semicolon at the end, it's the end of the query
if (substr(trim($line), -1, 1) == ';')
{
    // Perform the query
    mysql_query($templine) or print('Error performing query \'<strong>' . $templine . '\': ' . mysql_error() . '<br /><br />');
    // Reset temp variable to empty
    $templine = '';
}
}

?>

cannot be cast to java.lang.Comparable

  • the object which implements Comparable is Fegan.

The method compareTo you are overidding in it should have a Fegan object as a parameter whereas you are casting it to a FoodItems. Your compareTo implementation should describe how a Fegan compare to another Fegan.

  • To actually do your sorting, you might want to make your FoodItems implement Comparable aswell and copy paste your actual compareTo logic in it.

Equivalent of *Nix 'which' command in PowerShell?

A quick-and-dirty match to Unix which is

New-Alias which where.exe

But it returns multiple lines if they exist so then it becomes

function which {where.exe command | select -first 1}

Dynamically update values of a chartjs chart

You also can use destroy() function. Like this

 if( window.myBar!==undefined)
     window.myBar.destroy();
 var ctx = document.getElementById("canvas").getContext("2d");
 window.myBar = new Chart(ctx).Bar(barChartData, {
     responsive : true,
 });

InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately

If you are not able to upgrade your Python version to 2.7.9, and want to suppress warnings,

you can downgrade your 'requests' version to 2.5.3:

pip install requests==2.5.3

Bugfix disclosure / Warning introduced in 2.6.0

Limit the height of a responsive image with css

I set the below 3 styles to my img tag

max-height: 500px;
height: 70%;
width: auto;

What it does that for desktop screen img doesn't grow beyond 500px but for small mobile screens, it will shrink to 70% of the outer container. Works like a charm.

It also works width property.

Build query string for System.Net.HttpClient get

If I wish to submit a http get request using System.Net.HttpClient there seems to be no api to add parameters, is this correct?

Yes.

Is there any simple api available to build the query string that doesn't involve building a name value collection and url encoding those and then finally concatenating them?

Sure:

var query = HttpUtility.ParseQueryString(string.Empty);
query["foo"] = "bar<>&-baz";
query["bar"] = "bazinga";
string queryString = query.ToString();

will give you the expected result:

foo=bar%3c%3e%26-baz&bar=bazinga

You might also find the UriBuilder class useful:

var builder = new UriBuilder("http://example.com");
builder.Port = -1;
var query = HttpUtility.ParseQueryString(builder.Query);
query["foo"] = "bar<>&-baz";
query["bar"] = "bazinga";
builder.Query = query.ToString();
string url = builder.ToString();

will give you the expected result:

http://example.com/?foo=bar%3c%3e%26-baz&bar=bazinga

that you could more than safely feed to your HttpClient.GetAsync method.

Ansible: Set variable to file content

You can use lookups in Ansible in order to get the contents of a file, e.g.

user_data: "{{ lookup('file', user_data_file) }}"

Caveat: This lookup will work with local files, not remote files.

Here's a complete example from the docs:

- hosts: all
  vars:
     contents: "{{ lookup('file', '/etc/foo.txt') }}"
  tasks:
     - debug: msg="the value of foo.txt is {{ contents }}"

sql query distinct with Row_Number

Using DISTINCT causes issues as you add fields and it can also mask problems in your select. Use GROUP BY as an alternative like this:

SELECT id
      ,ROW_NUMBER() OVER (ORDER BY  id) AS RowNum
  FROM table
 where fid = 64
 group by id

Then you can add other interesting information from your select like this:

,count(*) as thecount

or

,max(description) as description

Exporting the values in List to excel

Using the CSV idea, if it's just a list of Strings. Assuming l is your list:

using System.IO;

using(StreamWriter sw = File.CreateText("list.csv"))
{
  for(int i = 0; i < l.Count; i++)
  {
    sw.WriteLine(l[i]);
  }
}

How to convert unsigned long to string

For a long value you need to add the length info 'l' and 'u' for unsigned decimal integer,

as a reference of available options see sprintf

#include <stdio.h>

    int main ()
    {
      unsigned long lval = 123;
      char buffer [50];
      sprintf (buffer, "%lu" , lval );
     }

ASP.NET MVC3 Razor - Html.ActionLink style

VB sample:

 @Html.ActionLink("Home", "Index", Nothing, New With {.style = "font-weight:bold;", .class = "someClass"})

Sample Css:

.someClass
{
    color: Green !important;
}

In my case, I found that I need the !important attribute to over ride the site.css a:link css class

How to rollback a specific migration?

In Addition

When migration you deployed long ago does not let you migrate new one.

What happened is, I work in a larger Rails app with more than a thousand of migration files. And, it takes a month for us to ship a medium-sized feature. I was working on a feature and I had deployed a migration a month ago then in the review process the structure of migration and filename changed, now I try to deploy my new code, the build failed saying

ActiveRecord::StatementInvalid: PG::DuplicateColumn: ERROR:  column "my_new_field" of relation "accounts" already exists

none of the above-mentioned solutions worked for me because the old migration file was missing and the field I intended to create in my new migration file already existed in the DB. The only solution that worked for me is:

  1. I scped the file to the server
  2. I opened the rails console
  3. I required the file in the IRB session
  4. then AddNewMyNewFieldToAccounts.new.down

then I could run the deploy build again.

Hope it helps you too.

How to change button text or link text in JavaScript?

document.getElementById(button_id).innerHTML = 'Lock';

data.table vs dplyr: can one do something well the other can't or does poorly?

Here's my attempt at a comprehensive answer from the dplyr perspective, following the broad outline of Arun's answer (but somewhat rearranged based on differing priorities).

Syntax

There is some subjectivity to syntax, but I stand by my statement that the concision of data.table makes it harder to learn and harder to read. This is partly because dplyr is solving a much easier problem!

One really important thing that dplyr does for you is that it constrains your options. I claim that most single table problems can be solved with just five key verbs filter, select, mutate, arrange and summarise, along with a "by group" adverb. That constraint is a big help when you're learning data manipulation, because it helps order your thinking about the problem. In dplyr, each of these verbs is mapped to a single function. Each function does one job, and is easy to understand in isolation.

You create complexity by piping these simple operations together with %>%. Here's an example from one of the posts Arun linked to:

diamonds %>%
  filter(cut != "Fair") %>%
  group_by(cut) %>%
  summarize(
    AvgPrice = mean(price),
    MedianPrice = as.numeric(median(price)),
    Count = n()
  ) %>%
  arrange(desc(Count))

Even if you've never seen dplyr before (or even R!), you can still get the gist of what's happening because the functions are all English verbs. The disadvantage of English verbs is that they require more typing than [, but I think that can be largely mitigated by better autocomplete.

Here's the equivalent data.table code:

diamondsDT <- data.table(diamonds)
diamondsDT[
  cut != "Fair", 
  .(AvgPrice = mean(price),
    MedianPrice = as.numeric(median(price)),
    Count = .N
  ), 
  by = cut
][ 
  order(-Count) 
]

It's harder to follow this code unless you're already familiar with data.table. (I also couldn't figure out how to indent the repeated [ in a way that looks good to my eye). Personally, when I look at code I wrote 6 months ago, it's like looking at a code written by a stranger, so I've come to prefer straightforward, if verbose, code.

Two other minor factors that I think slightly decrease readability:

  • Since almost every data table operation uses [ you need additional context to figure out what's happening. For example, is x[y] joining two data tables or extracting columns from a data frame? This is only a small issue, because in well-written code the variable names should suggest what's happening.

  • I like that group_by() is a separate operation in dplyr. It fundamentally changes the computation so I think should be obvious when skimming the code, and it's easier to spot group_by() than the by argument to [.data.table.

I also like that the the pipe isn't just limited to just one package. You can start by tidying your data with tidyr, and finish up with a plot in ggvis. And you're not limited to the packages that I write - anyone can write a function that forms a seamless part of a data manipulation pipe. In fact, I rather prefer the previous data.table code rewritten with %>%:

diamonds %>% 
  data.table() %>% 
  .[cut != "Fair", 
    .(AvgPrice = mean(price),
      MedianPrice = as.numeric(median(price)),
      Count = .N
    ), 
    by = cut
  ] %>% 
  .[order(-Count)]

And the idea of piping with %>% is not limited to just data frames and is easily generalised to other contexts: interactive web graphics, web scraping, gists, run-time contracts, ...)

Memory and performance

I've lumped these together, because, to me, they're not that important. Most R users work with well under 1 million rows of data, and dplyr is sufficiently fast enough for that size of data that you're not aware of processing time. We optimise dplyr for expressiveness on medium data; feel free to use data.table for raw speed on bigger data.

The flexibility of dplyr also means that you can easily tweak performance characteristics using the same syntax. If the performance of dplyr with the data frame backend is not good enough for you, you can use the data.table backend (albeit with a somewhat restricted set of functionality). If the data you're working with doesn't fit in memory, then you can use a database backend.

All that said, dplyr performance will get better in the long-term. We'll definitely implement some of the great ideas of data.table like radix ordering and using the same index for joins & filters. We're also working on parallelisation so we can take advantage of multiple cores.

Features

A few things that we're planning to work on in 2015:

  • the readr package, to make it easy to get files off disk and in to memory, analogous to fread().

  • More flexible joins, including support for non-equi-joins.

  • More flexible grouping like bootstrap samples, rollups and more

I'm also investing time into improving R's database connectors, the ability to talk to web apis, and making it easier to scrape html pages.

What is the purpose of the var keyword and when should I use it (or omit it)?

There's a difference.

var x = 1 declares variable x in current scope (aka execution context). If the declaration appears in a function - a local variable is declared; if it's in global scope - a global variable is declared.

x = 1, on the other hand, is merely a property assignment. It first tries to resolve x against scope chain. If it finds it anywhere in that scope chain, it performs assignment; if it doesn't find x, only then does it creates x property on a global object (which is a top level object in a scope chain).

Now, notice that it doesn't declare a global variable, it creates a global property.

The difference between the two is subtle and might be confusing unless you understand that variable declarations also create properties (only on a Variable Object) and that every property in Javascript (well, ECMAScript) have certain flags that describe their properties - ReadOnly, DontEnum and DontDelete.

Since variable declaration creates property with the DontDelete flag, the difference between var x = 1 and x = 1 (when executed in global scope) is that the former one - variable declaration - creates the DontDelete'able property, and latter one doesn't. As a consequence, the property created via this implicit assignment can then be deleted from the global object, and the former one - the one created via variable declaration - cannot be deleted.

But this is just theory of course, and in practice there are even more differences between the two, due to various bugs in implementations (such as those from IE).

Hope it all makes sense : )


[Update 2010/12/16]

In ES5 (ECMAScript 5; recently standardized, 5th edition of the language) there's a so-called "strict mode" — an opt-in language mode, which slightly changes the behavior of undeclared assignments. In strict mode, assignment to an undeclared identifier is a ReferenceError. The rationale for this was to catch accidental assignments, preventing creation of undesired global properties. Some of the newer browsers have already started rolling support for strict mode. See, for example, my compat table.

How do I use regular expressions in bash scripts?

It was changed between 3.1 and 3.2:

This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.

Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.

So use it without the quotes thus:

i="test"
if [[ $i =~ 200[78] ]] ; then
    echo "OK"
else
    echo "not OK"
fi

ALTER TABLE on dependent column

you can drop the Constraint which is restricting you. If the column has access to other table. suppose a view is accessing the column which you are altering then it wont let you alter the column unless you drop the view. and after making changes you can recreate the view.

enter image description here

how to convert rgb color to int in java

First of all, android.graphics.Color is a class thats composed of only static methods. How and why did you create a new android.graphics.Color object? (This is completely useless and the object itself stores no data)

But anyways... I'm going to assume your using some object that actually stores data...

A integer is composed of 4 bytes (in java). Looking at the function getRGB() from the standard java Color object we can see java maps each color to one byte of the integer in the order ARGB (Alpha-Red-Green-Blue). We can replicate this behavior with a custom method as follows:

public int getIntFromColor(int Red, int Green, int Blue){
    Red = (Red << 16) & 0x00FF0000; //Shift red 16-bits and mask out other stuff
    Green = (Green << 8) & 0x0000FF00; //Shift Green 8-bits and mask out other stuff
    Blue = Blue & 0x000000FF; //Mask out anything not blue.

    return 0xFF000000 | Red | Green | Blue; //0xFF000000 for 100% Alpha. Bitwise OR everything together.
}

This assumes you can somehow retrieve the individual red, green and blue colour components and that all the values you passed in for the colours are 0-255.

If your RGB values are in form of a float percentage between 0 and 1 consider the following method:

public int getIntFromColor(float Red, float Green, float Blue){
    int R = Math.round(255 * Red);
    int G = Math.round(255 * Green);
    int B = Math.round(255 * Blue);

    R = (R << 16) & 0x00FF0000;
    G = (G << 8) & 0x0000FF00;
    B = B & 0x000000FF;

    return 0xFF000000 | R | G | B;
}

As others have stated, if you're using a standard java object, just use getRGB();

If you decide to use the android color class properly you can also do:

int RGB = android.graphics.Color.argb(255, Red, Green, Blue); //Where Red, Green, Blue are the RGB components. The number 255 is for 100% Alpha

or

int RGB = android.graphics.Color.rgb(Red, Green, Blue); //Where Red, Green, Blue are the RGB components.

as others have stated... (Second function assumes 100% alpha)

Both methods basically do the same thing as the first method created above.

this in equals method

You are comparing two objects for equality. The snippet:

if (obj == this) {     return true; } 

is a quick test that can be read

"If the object I'm comparing myself to is me, return true"

. You usually see this happen in equals methods so they can exit early and avoid other costly comparisons.

calling a function from class in python - different way

you have to use self as the first parameters of a method

in the second case you should use

class MathOperations:
    def testAddition (self,x, y):
        return x + y

    def testMultiplication (self,a, b):
        return a * b

and in your code you could do the following

tmp = MathOperations
print tmp.testAddition(2,3)

if you use the class without instantiating a variable first

print MathOperation.testAddtion(2,3)

it gives you an error "TypeError: unbound method"

if you want to do that you will need the @staticmethod decorator

For example:

class MathsOperations:
    @staticmethod
    def testAddition (x, y):
        return x + y

    @staticmethod
    def testMultiplication (a, b):
        return a * b

then in your code you could use

print MathsOperations.testAddition(2,3)

Laravel eloquent update record without loading from database

Post::where('id',3)->update(['title'=>'Updated title']);

Get position/offset of element relative to a parent container?

I got another Solution. Subtract parent property value from child property value

$('child-div').offset().top - $('parent-div').offset().top;

Python 3 string.join() equivalent?

Visit https://www.tutorialspoint.com/python/string_join.htm

s=" "
seq=["ab", "cd", "ef"]
print(s.join(seq))

ab cd ef

s="."
print(s.join(seq))

ab.cd.ef

How to select the Date Picker In Selenium WebDriver

Do not inject javascript. That is a bad practice.

I would model the DatePicker as an element like textbox / select as shown below.

For the detailed answer - check here- http://www.testautomationguru.com/selenium-webdriver-automating-custom-controls-datepicker/

public class DatePicker {

    private static final String dateFormat = "dd MMM yyyy";

    @FindBy(css = "a.ui-datepicker-prev")
    private WebElement prev;

    @FindBy(css = "a.ui-datepicker-next")
    private WebElement next;

    @FindBy(css = "div.ui-datepicker-title")
    private WebElement curDate;

    @FindBy(css = "a.ui-state-default")
    private List < WebElement > dates;

    public void setDate(String date) {

        long diff = this.getDateDifferenceInMonths(date);
        int day = this.getDay(date);

        WebElement arrow = diff >= 0 ? next : prev;
        diff = Math.abs(diff);

        //click the arrows
        for (int i = 0; i < diff; i++)
            arrow.click();

        //select the date
        dates.stream()
            .filter(ele - > Integer.parseInt(ele.getText()) == day)
            .findFirst()
            .ifPresent(ele - > ele.click());

    }

    private int getDay(String date) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(dateFormat);
        LocalDate dpToDate = LocalDate.parse(date, dtf);
        return dpToDate.getDayOfMonth();
    }

    private long getDateDifferenceInMonths(String date) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(dateFormat);
        LocalDate dpCurDate = LocalDate.parse("01 " + this.getCurrentMonthFromDatePicker(), dtf);
        LocalDate dpToDate = LocalDate.parse(date, dtf);
        return YearMonth.from(dpCurDate).until(dpToDate, ChronoUnit.MONTHS);
    }

    private String getCurrentMonthFromDatePicker() {
        return this.curDate.getText();
    }

}

SELECT where row value contains string MySQL

My suggestion would be

$value = $_POST["myfield"];

$Query = Database::Prepare("SELECT * FROM TABLE WHERE MYFIELD LIKE ?");
$Query->Execute(array("%".$value."%"));

Structs data type in php?

A public class is one option, if you want something more encapsulated you can use an abstract/anonymous class combination. My favorite part is that autocomplete still works (for PhpStorm) for this but I don't have a public class sitting around.

<?php

final class MyParentClass
{
    /**
     * @return MyStruct[]
     */
    public function getData(): array
    {
        return array(
            $this->createMyObject("One", 1.0, new DateTime("now")),
            $this->createMyObject("Two", 2.0, new DateTime("tommorow"))
        );
    }

    private function createMyObject(string $description, float $magnitude, DateTime $timeStamp): MyStruct
    {
        return new class(func_get_args()) extends MyStruct {
            protected function __construct(array $args)
            {
                $this->description = $args[0];
                $this->magnitude = $args[1];
                $this->timeStamp = $args[2];
            }
        };
    }
}

abstract class MyStruct
{
    public string $description;
    public float $magnitude;
    public DateTime $timeStamp;
}

How to get numbers after decimal point?

Another example using modf

from math import modf
number = 1.0124584

# [0] decimal, [1] integer
result = modf(number)
print(result[0])
# output = 0124584
print(result[1])
# output = 1

Java 8 lambda get and remove element from list

Although the thread is quite old, still thought to provide solution - using Java8.

Make the use of removeIf function. Time complexity is O(n)

producersProcedureActive.removeIf(producer -> producer.getPod().equals(pod));

API reference: removeIf docs

Assumption: producersProcedureActive is a List

NOTE: With this approach you won't be able to get the hold of the deleted item.

How to prevent http file caching in Apache httpd (MAMP)

Based on the example here: http://drupal.org/node/550488

The following will probably work in .htaccess

 <IfModule mod_expires.c>
   # Enable expirations.
   ExpiresActive On

   # Cache all files for 2 weeks after access (A).
   ExpiresDefault A1209600

  <FilesMatch (\.js|\.html)$>
     ExpiresActive Off
  </FilesMatch>
 </IfModule>

How do I get the max and min values from a set of numbers entered?

This is what I did and it works try and play around with it. It calculates total,avarage,minimum and maximum.

public static void main(String[] args) {
   int[] score= {56,90,89,99,59,67};
   double avg;
   int sum=0;
   int maxValue=0;
   int minValue=100;

   for(int i=0;i<6;i++){
       sum=sum+score[i];
   if(score[i]<minValue){
    minValue=score[i];
   }
   if(score[i]>maxValue){
    maxValue=score[i];
   }
   }
   avg=sum/6.0;
System.out.print("Max: "+maxValue+"," +" Min: "+minValue+","+" Avarage: "+avg+","+" Sum: "+sum);}

 }

JUnit test for System.out.println()

You cannot directly print by using system.out.println or using logger api while using JUnit. But if you want to check any values then you simply can use

Assert.assertEquals("value", str);

It will throw below assertion error:

java.lang.AssertionError: expected [21.92] but found [value]

Your value should be 21.92, Now if you will test using this value like below your test case will pass.

 Assert.assertEquals(21.92, str);

How do I temporarily disable triggers in PostgreSQL?

SET session_replication_role = replica; 

It doesn't work with PostgreSQL 9.4 on my Linux machine if i change a table through table editor in pgAdmin and works if i change table through ordinary query. Manual changes in pg_trigger table also don't work without server restart but dynamic query like on postgresql.nabble.com ENABLE / DISABLE ALL TRIGGERS IN DATABASE works. It could be useful when you need some tuning.

For example if you have tables in a particular namespace it could be:

create or replace function disable_triggers(a boolean, nsp character varying) returns void as
$$
declare 
act character varying;
r record;
begin
    if(a is true) then
        act = 'disable';
    else
        act = 'enable';
    end if;

    for r in select c.relname from pg_namespace n
        join pg_class c on c.relnamespace = n.oid and c.relhastriggers = true
        where n.nspname = nsp
    loop
        execute format('alter table %I %s trigger all', r.relname, act); 
    end loop;
end;
$$
language plpgsql;

If you want to disable all triggers with certain trigger function it could be:

create or replace function disable_trigger_func(a boolean, f character varying) returns void as
$$
declare 
act character varying;
r record;
begin
    if(a is true) then
        act = 'disable';
    else
        act = 'enable';
    end if;

    for r in select c.relname from pg_proc p 
        join pg_trigger t on t.tgfoid = p.oid
        join pg_class c on c.oid = t.tgrelid
        where p.proname = f
    loop
        execute format('alter table %I %s trigger all', r.relname, act); 
    end loop;
end;
$$
language plpgsql;

PostgreSQL documentation for system catalogs


There are another control options of trigger firing process:

ALTER TABLE ... ENABLE REPLICA TRIGGER ... - trigger will fire in replica mode only.

ALTER TABLE ... ENABLE ALWAYS TRIGGER ... - trigger will fire always (obviously)

Cannot start GlassFish 4.1 from within Netbeans 8.0.1 Service area

I also had this problem, it is because there is an application LISTENING to 8080 port. To solve this problem I followed the below steps:

  1. Open cmd.exe then type

    netstat -aon | find ":8080" | find "LISTENING"

  2. You will see like this result

    TCP 0.0.0.0:8080 0.0.0.0:0 LISTENING 1464

  3. Copy PID "1464".

  4. Open Task Manager (Ctrl+Alt+del), go to the details tag, then find the program or service via PID that is listening to the port 8080 then STOP it or End process.

How to Initialize char array from a string

Here is obscure solution: define macro function:

#define Z(x) \
        (x==0 ? 'A' : \
        (x==1 ? 'B' : \
        (x==2 ? 'C' : '\0')))

char x[] = { Z(0), Z(1), Z(2) };

Run / Open VSCode from Mac Terminal

Somehow using Raja's approach worked for me only once, after a reboot, it seems gone. To make it persistent across Mac OS reboot, I added this line into my ~/.zshrc since I'm using zsh:

export PATH=/Applications/Visual\ Studio\ Code.app/Contents/Resources/app/bin:$PATH then

source ~/.zshrc now, I could just do

code .

even after I reboot my Mac.

How does the Spring @ResponseBody annotation work?

@RequestBody annotation binds the HTTPRequest body to the domain object. Spring automatically deserializes incoming HTTP Request to object using HttpMessageConverters. HttpMessageConverter converts body of request to resolve the method argument depending on the content type of the request. Many examples how to use converters https://upcodein.com/search/jc/mg/ResponseBody/page/0

How do I get the dialer to open with phone number displayed?

<TextView
 android:id="@+id/phoneNumber"
 android:autoLink="phone"
 android:linksClickable="true"
 android:text="+91 22 2222 2222"
 />

This is how you can open EditText label assigned number on dialer directly.

Checking if a list of objects contains a property with a specific value

using System.Linq;    
list.Where(x=> x.Name == nameToExtract);

Edit: misread question (now all matches)

How can I print out all possible letter combinations a given phone number can represent?

/**
 * Simple Java implementation without any input/error checking 
 * (expects all digits as input)
 **/
public class PhoneSpeller
{

    private static final char[][] _letters = new char[][]{
            {'0'},
            {'1'},
            {'A', 'B', 'C'},
            {'D', 'E', 'F'},
            {'G', 'H', 'I'},
            {'J', 'K', 'L'},
            {'M', 'N', 'O'},
            {'P', 'Q', 'R', 'S'},
            {'T', 'U', 'V'},
            {'W', 'X', 'Y', 'Z'}
    };

    public static void main(String[] args)
    {
        if (args.length != 1)
        {
            System.out.println("Please run again with your phone number (no dashes)");
            System.exit(0);
        }
        recursive_phoneSpell(args[0], 0, new ArrayList<String>());

    }


    private static void recursive_phoneSpell(String arg, int index, List<String> results)
    {
        if (index == arg.length())
        {
            printResults(results);
            return;
        }
        int num = Integer.parseInt(arg.charAt(index)+"");

        if (index==0)
        {
            for (int j = 0; j<_letters[num].length; j++)
            {
                results.add(_letters[num][j]+"");
            }
            recursive_phoneSpell(arg, index+1, results);
        }
        else
        {
            List<String> combos = new ArrayList<String>();
            for (int j = 0; j<_letters[num].length; j++)
            {
                 for (String result : results)
                 {
                     combos.add(result+_letters[num][j]);
                 }
            }
            recursive_phoneSpell(arg, index+1, combos);
        }
    }

    private static void printResults(List<String> results)
    {
        for (String result : results)
        {
            System.out.println(result);
        }
    }
}

How can I make my custom objects Parcelable?

Create Parcelable class without plugin in Android Studio

implements Parcelable in your class and then put cursor on "implements Parcelable" and hit Alt+Enter and select Add Parcelable implementation (see image). that's it.

enter image description here

Uninstall Django completely

The Issue is with pip --version or python --version.

try solving issue with pip2.7 uninstall Django command

If you are not able to uninstall using the above command then for sure your pip2.7 version is not installed so you can follow the below steps:

1)which pip2.7 it should give you an output like this :

/usr/local/bin/pip2.7

2) If you have not got this output please install pip using following commands

$ wget https://bootstrap.pypa.io/get-pip.py
$ sudo python2.7 get-pip.py

3) Now check your pip version : which pip2.7 Now you will get

/usr/local/bin/pip2.7 as output 

4) uninstall Django using pip2.7 uninstall Django command.

Problem can also be related to Python version. I had a similar problem, this is how I uninstalled Django.

Issue occurred because I had multiple python installed in my virtual environment.

$ ls

activate       activate_this.py  easy_install-3.4  pip2.7  python     python3        wheel
activate.csh   easy_install      pip               pip3    python2    python3.4
activate.fish  easy_install-2.7  pip2              pip3.4  python2.7  python-config

Now when I tried to un-install using pip uninstall Django Django got uninstalled from python 2.7 but not from python 3.4 so I followed the following steps to resolve the issue :

1)alias python=/usr/bin/python3

2) Now check your python version using python -V command

3) If you have switched to your required python version now you can simply uninstall Django using pip3 uninstall Django command

Hope this answer helps.

What's a concise way to check that environment variables are set in a Unix shell script?

We can write a nice assertion to check a bunch of variables all at once:

#
# assert if variables are set (to a non-empty string)
# if any variable is not set, exit 1 (when -f option is set) or return 1 otherwise
#
# Usage: assert_var_not_null [-f] variable ...
#
function assert_var_not_null() {
  local fatal var num_null=0
  [[ "$1" = "-f" ]] && { shift; fatal=1; }
  for var in "$@"; do
    [[ -z "${!var}" ]] &&
      printf '%s\n' "Variable '$var' not set" >&2 &&
      ((num_null++))
  done

  if ((num_null > 0)); then
    [[ "$fatal" ]] && exit 1
    return 1
  fi
  return 0
}

Sample invocation:

one=1 two=2
assert_var_not_null one two
echo test 1: return_code=$?
assert_var_not_null one two three
echo test 2: return_code=$?
assert_var_not_null -f one two three
echo test 3: return_code=$? # this code shouldn't execute

Output:

test 1: return_code=0
Variable 'three' not set
test 2: return_code=1
Variable 'three' not set

More such assertions here: https://github.com/codeforester/base/blob/master/lib/assertions.sh

Vlookup referring to table data in a different sheet

This lookup only features exact matches. If you have an extra space in one of the columns or something similar it will not recognize it.

When do you use map vs flatMap in RxJava?

The way I think about it is that you use flatMap when the function you wanted to put inside of map() returns an Observable. In which case you might still try to use map() but it would be unpractical. Let me try to explain why.

If in such case you decided to stick with map, you would get an Observable<Observable<Something>>. For example in your case, if we used an imaginary RxGson library, that returned an Observable<String> from it's toJson() method (instead of simply returning a String) it would look like this:

Observable.from(jsonFile).map(new Func1<File, Observable<String>>() {
    @Override public Observable<String>> call(File file) {
        return new RxGson().toJson(new FileReader(file), Object.class);
    }
}); // you get Observable<Observable<String>> here

At this point it would be pretty tricky to subscribe() to such an observable. Inside of it you would get an Observable<String> to which you would again need to subscribe() to get the value. Which is not practical or nice to look at.

So to make it useful one idea is to "flatten" this observable of observables (you might start to see where the name _flat_Map comes from). RxJava provides a few ways to flatten observables and for sake of simplicity lets assume merge is what we want. Merge basically takes a bunch of observables and emits whenever any of them emits. (Lots of people would argue switch would be a better default. But if you're emitting just one value, it doesn't matter anyway.)

So amending our previous snippet we would get:

Observable.from(jsonFile).map(new Func1<File, Observable<String>>() {
    @Override public Observable<String>> call(File file) {
        return new RxGson().toJson(new FileReader(file), Object.class);
    }
}).merge(); // you get Observable<String> here

This is a lot more useful, because subscribing to that (or mapping, or filtering, or...) you just get the String value. (Also, mind you, such variant of merge() does not exist in RxJava, but if you understand the idea of merge then I hope you also understand how that would work.)

So basically because such merge() should probably only ever be useful when it succeeds a map() returning an observable and so you don't have to type this over and over again, flatMap() was created as a shorthand. It applies the mapping function just as a normal map() would, but later instead of emitting the returned values it also "flattens" (or merges) them.

That's the general use case. It is most useful in a codebase that uses Rx allover the place and you've got many methods returning observables, which you want to chain with other methods returning observables.

In your use case it happens to be useful as well, because map() can only transform one value emitted in onNext() into another value emitted in onNext(). But it cannot transform it into multiple values, no value at all or an error. And as akarnokd wrote in his answer (and mind you he's much smarter than me, probably in general, but at least when it comes to RxJava) you shouldn't throw exceptions from your map(). So instead you can use flatMap() and

return Observable.just(value);

when all goes well, but

return Observable.error(exception);

when something fails.
See his answer for a complete snippet: https://stackoverflow.com/a/30330772/1402641

SSIS expression: convert date to string

Something simpler than what @Milen proposed but it gives YYYY-MM-DD instead of the DD-MM-YYYY you wanted :

SUBSTRING((DT_STR,30, 1252) GETDATE(), 1, 10)

Expression builder screen:

enter image description here

Can I add a custom attribute to an HTML tag?

In HTML5: yes: use the data- attribute.

 <ul>
  <li data-animal-type="bird">Owl</li>
  <li data-animal-type="fish">Salmon</li>
  <li data-animal-type="spider">Tarantula</li>
</ul> 

How to view changes made to files on a certain revision in Subversion

With this command you will see all changes in the repository path/to/repo that were committed in revision <revision>:

svn diff -c <revision> path/to/repo

The -c indicates that you would like to look at a changeset, but there are many other ways you can look at diffs and changesets. For example, if you would like to know which files were changed (but not how), you can issue

svn log -v -r <revision>

Or, if you would like to show at the changes between two revisions (and not just for one commit):

svn diff -r <revA>:<revB> path/to/repo

ASP.NET MVC Html.DropDownList SelectedValue

I managed to get the desired result, but with a slightly different approach. In the Dropdownlist i used the Model and then referenced it. Not sure if this was what you were looking for.

@Html.DropDownList("Example", new SelectList(Model.FeeStructures, "Id", "NameOfFeeStructure", Model.Matters.FeeStructures))

Model.Matters.FeeStructures in above is my id, which could be your value of the item that should be selected.

How can I remove a substring from a given String?

You can use Substring also for replacing with existing string:

var str = "abc awwwa";
var Index = str.indexOf('awwwa');
str = str.substring(0, Index);

What to do with "Unexpected indent" in python?

Run the following command to get it solved :

autopep8 -i <filename>.py

This will update your code and solve all indentation Errors :)

Hope this will solve

Java: Convert String to TimeStamp

DateFormat formatter;
formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = (Date) formatter.parse(str_date);
java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());

How to kill a child process after a given timeout in Bash?

Here's the third answer I've submitted here. This one handles signal interrupts and cleans up background processes when SIGINT is received. It uses the $BASHPID and exec trick used in the top answer to get the PID of a process (in this case $$ in a sh invocation). It uses a FIFO to communicate with a subshell that is responsible for killing and cleanup. (This is like the pipe in my second answer, but having a named pipe means that the signal handler can write into it too.)

run_with_timeout ()
{
  t=$1 ; shift

  trap cleanup 2

  F=$$.fifo ; rm -f $F ; mkfifo $F

  # first, run main process in background
  "$@" & pid=$!

  # sleeper process to time out
  ( sh -c "echo \$\$ >$F ; exec sleep $t" ; echo timeout >$F ) &
  read sleeper <$F

  # control shell. read from fifo.
  # final input is "finished".  after that
  # we clean up.  we can get a timeout or a
  # signal first.
  ( exec 0<$F
    while : ; do
      read input
      case $input in
        finished)
          test $sleeper != 0 && kill $sleeper
          rm -f $F
          exit 0
          ;;
        timeout)
          test $pid != 0 && kill $pid
          sleeper=0
          ;;
        signal)
          test $pid != 0 && kill $pid
          ;;
      esac
    done
  ) &

  # wait for process to end
  wait $pid
  status=$?
  echo finished >$F
  return $status
}

cleanup ()
{
  echo signal >$$.fifo
}

I've tried to avoid race conditions as far as I can. However, one source of error I couldn't remove is when the process ends near the same time as the timeout. For example, run_with_timeout 2 sleep 2 or run_with_timeout 0 sleep 0. For me, the latter gives an error:

timeout.sh: line 250: kill: (23248) - No such process

as it is trying to kill a process that has already exited by itself.

'was not declared in this scope' error

The scope of a variable is always the block it is inside. For example if you do something like

if(...)
{
     int y = 5; //y is created
} //y leaves scope, since the block ends.
else
{
     int y = 8; //y is created
} //y leaves scope, since the block ends.

cout << y << endl; //Gives error since y is not defined.

The solution is to define y outside of the if blocks

int y; //y is created

if(...)
{
     y = 5;
} 
else
{
     y = 8;
} 

cout << y << endl; //Ok

In your program you have to move the definition of y and c out of the if blocks into the higher scope. Your Function then would look like this:

//Using the Gaussian algorithm
int dayofweek(int date, int month, int year )
{
    int y, c;
    int d=date;

    if (month==1||month==2)
    {
         y=((year-1)%100);
         c=(year-1)/100;
    }
    else
    {
         y=year%100;
         c=year/100;
    }
int m=(month+9)%12+1;
int product=(d+(2.6*m-0.2)+y+y/4+c/4-2*c);
return product%7;
}

Hibernate: Automatically creating/updating the db tables based on entity classes

In applicationContext.xml file:

<bean id="entityManagerFactoryBean" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
      <property name="dataSource" ref="dataSource" />
      <!-- This makes /META-INF/persistence.xml is no longer necessary -->
      <property name="packagesToScan" value="com.howtodoinjava.demo.model" />
      <!-- JpaVendorAdapter implementation for Hibernate EntityManager.
           Exposes Hibernate's persistence provider and EntityManager extension interface -->
      <property name="jpaVendorAdapter">
         <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
      </property>
      <property name="jpaProperties">
         <props>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
         </props>
      </property>
   </bean>

Regular Expression for matching parentheses

  • You can escape any meta-character by using a backslash, so you can match ( with the pattern \(.
  • Many languages come with a build-in escaping function, for example, .Net's Regex.Escape or Java's Pattern.quote
  • Some flavors support \Q and \E, with literal text between them.
  • Some flavors (VIM, for example) match ( literally, and require \( for capturing groups.

See also: Regular Expression Basic Syntax Reference

JBoss debugging in Eclipse

VonC mentioned in his answer how to remote debug from Eclipse.

I would like to add that the JAVA_OPTS settings are already in run.conf.bat. You just have to uncomment them:

in JBOSS_HOME\bin\run.conf.bat on Windows:

rem # Sample JPDA settings for remote socket debugging
set "JAVA_OPTS=%JAVA_OPTS% -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n"

The Linux version is similar and is located at JBOSS_HOME/bin/run.conf

java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject Error

you have to include two more jar files.

xmlbeans-2.3.0.jar and dom4j-1.6.1.jar Add try it will work.

Note: It is required for the files with .xlsx formats only, not for just .xlt formats.

socket programming multiple client to one server

See O'Reilly "Java Cookbook", Ian Darwin - recipe 17.4 Handling Multiple Clients.

Pay attention that accept() is not thread safe, so the call is wrapped within synchronized.

64: synchronized(servSock) {
65:     clientSocket = servSock.accept();
66: }

For loop in Objective-C

The traditional for loop in Objective-C is inherited from standard C and takes the following form:

for (/* Instantiate local variables*/ ; /* Condition to keep looping. */ ; /* End of loop expressions */)
{
    // Do something.
}

For example, to print the numbers from 1 to 10, you could use the for loop:

for (int i = 1; i <= 10; i++)
{
    NSLog(@"%d", i);
}

On the other hand, the for in loop was introduced in Objective-C 2.0, and is used to loop through objects in a collection, such as an NSArray instance. For example, to loop through a collection of NSString objects in an NSArray and print them all out, you could use the following format.

for (NSString* currentString in myArrayOfStrings)
{
    NSLog(@"%@", currentString);
}

This is logically equivilant to the following traditional for loop:

for (int i = 0; i < [myArrayOfStrings count]; i++)
{
    NSLog(@"%@", [myArrayOfStrings objectAtIndex:i]);
}

The advantage of using the for in loop is firstly that it's a lot cleaner code to look at. Secondly, the Objective-C compiler can optimize the for in loop so as the code runs faster than doing the same thing with a traditional for loop.

Hope this helps.

adb command not found

Type the below command in terminal:

nano .bash_profile

And add the following lines (replace USERNAME with your own user name).

export ANDROID_HOME=/Users/USERNAME/Library/Android/sdk 
export PATH=${PATH}:${ANDROID_HOME}/tools 
export PATH=${PATH}:${ANDROID_HOME}/platform-tools

Close the text editor, and then enter the command below:

source .bash_profile

how to query for a list<String> in jdbctemplate

To populate a List of String, you need not use custom row mapper. Implement it using queryForList.

List<String>data=jdbcTemplate.queryForList(query,String.class)

Passing variables through handlebars partial

Handlebars partials take a second parameter which becomes the context for the partial:

{{> person this}}

In versions v2.0.0 alpha and later, you can also pass a hash of named parameters:

{{> person headline='Headline'}}

You can see the tests for these scenarios: https://github.com/wycats/handlebars.js/blob/ce74c36118ffed1779889d97e6a2a1028ae61510/spec/qunit_spec.js#L456-L462 https://github.com/wycats/handlebars.js/blob/e290ec24f131f89ddf2c6aeb707a4884d41c3c6d/spec/partials.js#L26-L32

How to merge two json string in Python?

To append key-value pairs to a json string, you can use dict.update: dictA.update(dictB).

For your case, this will look like this:

dictA = json.loads(jsonStringA)
dictB = json.loads('{"error_1395952167":"Error Occured on machine h1 in datacenter dc3 on the step2 of process test"}')

dictA.update(dictB)
jsonStringA = json.dumps(dictA)

Note that key collisions will cause values in dictB overriding dictA.

android studio 0.4.2: Gradle project sync failed error

same here, updating to 0.4.2 also broke everything in my case... It has nothing to do with memory usage : I've got 8 gig of memory and I have 3.5 gig free atm, so not having enough memory to start up a JVM is bullocks...

Actually it might have something to do with Gradle versions, I looked into the error log and found this :

2014-01-14 09:00:30,918 [ 61112] WARN - nal.AbstractExternalSystemTask - Project is using an old version of the Android Gradle plug-in. The minimum supported version is 0.7.0. Please update the version of the dependency 'com.android.tools.build:gradle' in your build.gradle files.

You are using Gradle version 1.8, which is not supported. Please use version 1.9. Please point to a supported Gradle version in the project's Gradle settings or in the project's Gradle wrapper (if applicable.) com.intellij.openapi.externalSystem.model.ExternalSystemException: Project is using an old version of the Android Gradle plug-in. The minimum supported version is 0.7.0. Please update the version of the dependency 'com.android.tools.build:gradle' in your build.gradle files

-

You are using Gradle version 1.8, which is not supported. Please use version 1.9.

Please point to a supported Gradle version in the project's Gradle settings or in the project's Gradle wrapper (if applicable.)

OK, I fixed it myself... In the project directory go to /gradle/wrapper directory and edit the gradle-wrapper properties file to this :

distributionUrl=http\://services.gradle.org/distributions/gradle-1.9-all.zip

After open your project in Android Studio and select the build.gradle file in the /src directory and edit it to this :

dependencies {
        classpath 'com.android.tools.build:gradle:0.7.+'
    }

After fixing it like this I discovered this article : http://tools.android.com/recent/androidstudio040released

Delete terminal history in Linux

You can clear your bash history like this:

history -cw

how to use DEXtoJar

Step 1 extract the contents of dex2jar.*.*.zip file 
Step 2 copy your .dex file to the extracted directory
Step 3 execute dex2jar.bat <.dex filename> on windows, or ./dex2jar.sh <.dex filename> on linux

Optimum way to compare strings in JavaScript?

Well in JavaScript you can check two strings for values same as integers so yo can do this:

  • "A" < "B"
  • "A" == "B"
  • "A" > "B"

And therefore you can make your own function that checks strings the same way as the strcmp().

So this would be the function that does the same:

function strcmp(a, b)
{   
    return (a<b?-1:(a>b?1:0));  
}

How to create jobs in SQL Server Express edition

The functionality of creating SQL Agent Jobs is not available in SQL Server Express Edition. An alternative is to execute a batch file that executes a SQL script using Windows Task Scheduler.

In order to do this first create a batch file named sqljob.bat

sqlcmd -S servername -U username -P password -i <path of sqljob.sql>

Replace the servername, username, password and path with yours.

Then create the SQL Script file named sqljob.sql

USE [databasename]
--T-SQL commands go here
GO

Replace the [databasename] with your database name. The USE and GO is necessary when you write the SQL script.

sqlcmd is a command-line utility to execute SQL scripts. After creating these two files execute the batch file using Windows Task Scheduler.

NB: An almost same answer was posted for this question before. But I felt it was incomplete as it didn't specify about login information using sqlcmd.

What is the purpose of the "role" attribute in HTML?

Most of the roles you see were defined as part of ARIA 1.0, and then later incorporated into HTML via supporting specs like HTML-AAM. Some of the new HTML5 elements (dialog, main, etc.) are even based on the original ARIA roles.

http://www.w3.org/TR/wai-aria/

There are a few primary reasons to use roles in addition to your native semantic element.

Reason #1. Overriding the role where no host language element is appropriate or, for various reasons, a less semantically appropriate element was used.

In this example, a link was used, even though the resulting functionality is more button-like than a navigation link.

<a href="#" role="button" aria-label="Delete item 1">Delete</a>
<!-- Note: href="#" is just a shorthand here, not a recommended technique. Use progressive enhancement when possible. -->

Screen readers users will hear this as a button (as opposed to a link), and you can use a CSS attribute selector to avoid class-itis and div-itis.

[role="button"] {
  /* style these as buttons w/o relying on a .button class */
}

[Update 7 years later: removed the * selector to make some commenters happy, since the old browser quirk that required universal selector on attribute selectors is unnecessary in 2020.]

Reason #2. Backing up a native element's role, to support browsers that implemented the ARIA role but haven't yet implemented the native element's role.

For example, the "main" role has been supported in browsers for many years, but it's a relatively recent addition to HTML5, so many browsers don't yet support the semantic for <main>.

<main role="main">…</main>

This is technically redundant, but helps some users and doesn't harm any. In a few years, this technique will likely become unnecessary for main.

Reason #3. Update 7 years later (2020): As at least one commenter pointed out, this is now very useful for custom elements, and some spec work is underway to define the default accessibility role of a web component. Even if/once that API is standardized, there may be need to override the default role of a component.

Note/Reply

You also wrote:

I see some people make up their own. Is that allowed or a correct use of the role attribute?

That's an allowed use of the attribute unless a real role is not included. Browsers will apply the first recognized role in the token list.

<span role="foo link note bar">...</a>

Out of the list, only link and note are valid roles, and so the link role will be applied in the platform accessibility API because it comes first. If you use custom roles, make sure they don't conflict with any defined role in ARIA or the host language you're using (HTML, SVG, MathML, etc.)

-bash: syntax error near unexpected token `newline'

The characters '<', and '>', are to indicate a place-holder, you should remove them to read:

php /usr/local/solusvm/scripts/pass.php --type=admin --comm=change --username=ADMINUSERNAME

Create a new database with MySQL Workbench

Those who are new to MySQL & Mac users; Note that, Connection is different than Database.

Steps to create a database.

Step 1: Create connection and click to go inside

Step 1

Step 2: Click on database icon

Step 2

Step 3: Name your database schema

Step 3

Step 4: Apply query

Step 4

Step 5: Your DB created, enjoy...

Step 5

Google Forms file upload complete example

Update: Google Forms can now upload files. This answer was posted before Google Forms had the capability to upload files.

This solution does not use Google Forms. This is an example of using an Apps Script Web App, which is very different than a Google Form. A Web App is basically a website, but you can't get a domain name for it. This is not a modification of a Google Form, which can't be done to upload a file.

NOTE: I did have an example of both the UI Service and HTML Service, but have removed the UI Service example, because the UI Service is deprecated.

NOTE: The only sandbox setting available is now IFRAME. I you want to use an onsubmit attribute in the beginning form tag: <form onsubmit="myFunctionName()">, it may cause the form to disappear from the screen after the form submission.

If you were using NATIVE mode, your file upload Web App may no longer be working. With NATIVE mode, a form submission would not invoke the default behavior of the page disappearing from the screen. If you were using NATIVE mode, and your file upload form is no longer working, then you may be using a "submit" type button. I'm guessing that you may also be using the "google.script.run" client side API to send data to the server. If you want the page to disappear from the screen after a form submission, you could do that another way. But you may not care, or even prefer to have the page stay on the screen. Depending upon what you want, you'll need to configure the settings and code a certain way.

If you are using a "submit" type button, and want to continue to use it, you can try adding event.preventDefault(); to your code in the submit event handler function. Or you'll need to use the google.script.run client side API.


A custom form for uploading files from a users computer drive, to your Google Drive can be created with the Apps Script HTML Service. This example requires writing a program, but I've provide all the basic code here.

This example shows an upload form with Google Apps Script HTML Service.

What You Need

  • Google Account
  • Google Drive
  • Google Apps Script - also called Google Script

Google Apps Script

There are various ways to end up at the Google Apps Script code editor.

I mention this because if you are not aware of all the possibilities, it could be a little confusing. Google Apps Script can be embedded in a Google Site, Sheets, Docs or Forms, or used as a stand alone app.

Apps Script Overview

This example is a "Stand Alone" app with HTML Service.

HTML Service - Create a web app using HTML, CSS and Javascript

Google Apps Script only has two types of files inside of a Project:

  • Script
  • HTML

Script files have a .gs extension. The .gs code is a server side code written in JavaScript, and a combination of Google's own API.

  • Copy and Paste the following code

  • Save It

  • Create the first Named Version

  • Publish it

  • Set the Permissions

    and you can start using it.

Start by:

  • Create a new Blank Project in Apps Script
  • Copy and Paste in this code:

Upload a file with HTML Service:

Code.gs file (Created by Default)

//For this to work, you need a folder in your Google drive named:
// 'For Web Hosting'
// or change the hard coded folder name to the name of the folder
// you want the file written to

function doGet(e) {
  return HtmlService.createTemplateFromFile('Form')
    .evaluate() // evaluate MUST come before setting the Sandbox mode
    .setTitle('Name To Appear in Browser Tab')
    .setSandboxMode();//Defaults to IFRAME which is now the only mode available
}

function processForm(theForm) {
  var fileBlob = theForm.picToLoad;
  
  Logger.log("fileBlob Name: " + fileBlob.getName())
  Logger.log("fileBlob type: " + fileBlob.getContentType())
  Logger.log('fileBlob: ' + fileBlob);

  var fldrSssn = DriveApp.getFolderById(Your Folder ID);
    fldrSssn.createFile(fileBlob);
    
  return true;
}

Create an html file:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <h1 id="main-heading">Main Heading</h1>
    <br/>
    <div id="formDiv">

      <form id="myForm">
    
        <input name="picToLoad" type="file" /><br/>
        <input type="button" value="Submit" onclick="picUploadJs(this.parentNode)" />
          
      </form>
    </div>


  <div id="status" style="display: none">
  <!-- div will be filled with innerHTML after form submission. -->
  Uploading. Please wait...
</div>

</body>
<script>

function picUploadJs(frmData) {

  document.getElementById('status').style.display = 'inline';

  google.script.run
    .withSuccessHandler(updateOutput)
    .processForm(frmData)
};
  // Javascript function called by "submit" button handler,
  // to show results.
  
  function updateOutput() {
  
    var outputDiv = document.getElementById('status');
    outputDiv.innerHTML = "The File was UPLOADED!";
  }

</script>
</html>

This is a full working example. It only has two buttons and one <div> element, so you won't see much on the screen. If the .gs script is successful, true is returned, and an onSuccess function runs. The onSuccess function (updateOutput) injects inner HTML into the div element with the message, "The File was UPLOADED!"

  • Save the file, give the project a name
  • Using the menu: File, Manage Version then Save the first Version
  • Publish, Deploy As Web App then Update

When you run the Script the first time, it will ask for permissions because it's saving files to your drive. After you grant permissions that first time, the Apps Script stops, and won't complete running. So, you need to run it again. The script won't ask for permissions again after the first time.

The Apps Script file will show up in your Google Drive. In Google Drive you can set permissions for who can access and use the script. The script is run by simply providing the link to the user. Use the link just as you would load a web page.

Another example of using the HTML Service can be seen at this link here on StackOverflow:

File Upload with HTML Service

NOTES about deprecated UI Service:

There is a difference between the UI Service, and the Ui getUi() method of the Spreadsheet Class (Or other class) The Apps Script UI Service was deprecated on Dec. 11, 2014. It will continue to work for some period of time, but you are encouraged to use the HTML Service.

Google Documentation - UI Service

Even though the UI Service is deprecated, there is a getUi() method of the spreadsheet class to add custom menus, which is NOT deprecated:

Spreadsheet Class - Get UI method

I mention this because it could be confusing because they both use the terminology UI.

The UI method returns a Ui return type.

You can add HTML to a UI Service, but you can't use a <button>, <input> or <script> tag in the HTML with the UI Service.

Here is a link to a shared Apps Script Web App file with an input form:

Shared File - Contact Form

PDO with INSERT INTO through prepared statements

Please add try catch also in your code so that you can be sure that there in no exception.

try {
    $hostname = "servername";
    $dbname = "dbname";
    $username = "username";
    $pw = "password";
    $pdo = new PDO ("mssql:host=$hostname;dbname=$dbname","$username","$pw");
  } catch (PDOException $e) {
    echo "Failed to get DB handle: " . $e->getMessage() . "\n";
    exit;
  }

Really killing a process in Windows

"End Process" on the Processes-Tab calls TerminateProcess which is the most ultimate way Windows knows to kill a process.

If it doesn't go away, it's currently locked waiting on some kernel resource (probably a buggy driver) and there is nothing (short of a reboot) you could do to make the process go away.

Have a look at this blog-entry from wayback when: http://blogs.technet.com/markrussinovich/archive/2005/08/17/unkillable-processes.aspx

Unix based systems like Linux also have that problem where processes could survive a kill -9 if they are in what's known as "Uninterruptible sleep" (shown by top and ps as state D) at which point the processes sleep so well that they can't process incoming signals (which is what kill does - sending signals).

Normally, Uninterruptible sleep should not last long, but as under Windows, broken drivers or broken userpace programs (vfork without exec) can end up sleeping in D forever.

Convert xlsx to csv in Linux with command line

In bash, I used this libreoffice command to convert all my xlsx files in the current directory:

for i   in *.xlsx; do  libreoffice --headless --convert-to csv "$i" ; done

It takes care of spaces in the filename.

Tried again some years later, and it didn't work. This thread gives some tips, but the quickiest solution was to run as root (or running a sudo libreoffice). Not elegant, but quick.

Use the command scalc.exe in Windows

Wait for a process to finish

All these solutions are tested in Ubuntu 14.04:

Solution 1 (by using ps command): Just to add up to Pierz answer, I would suggest:

while ps axg | grep -vw grep | grep -w process_name > /dev/null; do sleep 1; done

In this case, grep -vw grep ensures that grep matches only process_name and not grep itself. It has the advantage of supporting the cases where the process_name is not at the end of a line at ps axg.

Solution 2 (by using top command and process name):

while [[ $(awk '$12=="process_name" {print $0}' <(top -n 1 -b)) ]]; do sleep 1; done

Replace process_name with the process name that appears in top -n 1 -b. Please keep the quotation marks.

To see the list of processes that you wait for them to be finished, you can run:

while : ; do p=$(awk '$12=="process_name" {print $0}' <(top -n 1 -b)); [[ $b ]] || break; echo $p; sleep 1; done

Solution 3 (by using top command and process ID):

while [[ $(awk '$1=="process_id" {print $0}' <(top -n 1 -b)) ]]; do sleep 1; done

Replace process_id with the process ID of your program.

Android RecyclerView addition & removal of items

if still item not removed use this magic method :)

private void deleteItem(int position) {
        mDataSet.remove(position);
        notifyItemRemoved(position);
        notifyItemRangeChanged(position, mDataSet.size());
        holder.itemView.setVisibility(View.GONE);
}

Kotlin version

private fun deleteItem(position: Int) {
    mDataSet.removeAt(position)
    notifyItemRemoved(position)
    notifyItemRangeChanged(position, mDataSet.size)
    holder.itemView.visibility = View.GONE
}

How to update a value in a json file and save it through node.js

//change the value in the in-memory object
content.val1 = 42;
//Serialize as JSON and Write it to a file
fs.writeFileSync(filename, JSON.stringify(content));

How can I set focus on an element in an HTML form using JavaScript?

For what it's worth, you can use the autofocus attribute on HTML5 compatible browsers. Works even on IE as of version 10.

<input name="myinput" value="whatever" autofocus />

How do I remove version tracking from a project cloned from git?

In a Windows environment you can remove Git tracking from a project's directory by simply typing the below.

rd .git /S/Q

QComboBox - set selected item based on the item's data

You lookup the value of the data with findData() and then use setCurrentIndex()

QComboBox* combo = new QComboBox;
combo->addItem("100",100.0);    // 2nd parameter can be any Qt type
combo->addItem .....

float value=100.0;
int index = combo->findData(value);
if ( index != -1 ) { // -1 for not found
   combo->setCurrentIndex(index);
}

How to delete/unset the properties of a javascript object?

simply use delete, but be aware that you should read fully what the effects are of using this:

 delete object.index; //true
 object.index; //undefined

but if I was to use like so:

var x = 1; //1
delete x; //false
x; //1

but if you do wish to delete variables in the global namespace, you can use it's global object such as window, or using this in the outermost scope i.e

var a = 'b';
delete a; //false
delete window.a; //true
delete this.a; //true

http://perfectionkills.com/understanding-delete/

another fact is that using delete on an array will not remove the index but only set the value to undefined, meaning in certain control structures such as for loops, you will still iterate over that entity, when it comes to array's you should use splice which is a prototype of the array object.

Example Array:

var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

if I was to do:

delete myCars[1];

the resulting array would be:

["Saab", undefined, "BMW"]

but using splice like so:

myCars.splice(1,1);

would result in:

["Saab", "BMW"]

Error inflating class android.support.v7.widget.Toolbar?

This happened to me when I tried to use my older code in new android with androidx implementations. change your XML definition to;

<androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/colorPrimary"
            android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
            app:titleTextColor="@android:color/white" />

then in your java code;

import androidx.appcompat.widget.Toolbar;

Put spacing between divs in a horizontal row?

You can set left margins for li tags in percents and set the same negative left margin on parent:

_x000D_
_x000D_
ul {margin-left:-5%;}_x000D_
li {width:20%;margin-left:5%;float:left;}
_x000D_
<ul>_x000D_
  <li>A_x000D_
  <li>B_x000D_
  <li>C_x000D_
  <li>D_x000D_
</ul>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/UZHbS/

jQuery date/time picker

@David, thanks for the recommendation! @fluid_chelsea, I've just released Any+Time(TM) version 3.x which uses jQuery instead of Prototype and has a much-improved interface, so I hope it now meets your needs:

http://www.ama3.com/anytime/

Any problems, please let me know via the comment link on my website!

awk - concatenate two string variable and assign to a third

Just use var = var1 var2 and it will automatically concatenate the vars var1 and var2:

awk '{new_var=$1$2; print new_var}' file

You can put an space in between with:

awk '{new_var=$1" "$2; print new_var}' file

Which in fact is the same as using FS, because it defaults to the space:

awk '{new_var=$1 FS $2; print new_var}' file

Test

$ cat file
hello how are you
i am fine
$ awk '{new_var=$1$2; print new_var}' file
hellohow
iam
$ awk '{new_var=$1 FS $2; print new_var}' file
hello how
i am

You can play around with it in ideone: http://ideone.com/4u2Aip

Get Substring between two characters using javascript

To get all substring.

var out = []; 'MyLongString:StringIWant;'
.replace(/(:)\w+(;)+/g, (e) => {
    out.push(e.replace(':', '').replace(';', ''))
    return e;
});
console.log(out[0])

Clear form after submission with jQuery

Propably this would do it for you.

 $('input').val('').removeAttr('checked').removeAttr('selected');

C - error: storage size of ‘a’ isn’t known

To anyone with who is having this problem, its a typo error. Check your spelling of your struct delcerations and your struct

Implementing a HashMap in C

There are other mechanisms to handle overflow than the simple minded linked list of overflow entries which e.g. wastes a lot of memory.

Which mechanism to use depends among other things on if you can choose the hash function and possible pick more than one (to implement e.g. double hashing to handle collisions); if you expect to often add items or if the map is static once filled; if you intend to remove items or not; ...

The best way to implement this is to first think about all these parameters and then not code it yourself but to pick a mature existing implementation. Google has a few good implementations -- e.g. http://code.google.com/p/google-sparsehash/

Keras, how do I predict after I trained a model?

You must use the same Tokenizer you used to build your model!

Else this will give different vector to each word.

Then, I am using:

phrase = "not good"
tokens = myTokenizer.texts_to_matrix([phrase])

model.predict(np.array(tokens))

How to compile multiple java source files in command line

Here is another example, for compiling a java file in a nested directory.

I was trying to build this from the command line. This is an example from 'gradle', which has dependency 'commons-collection.jar'. For more info, please see 'gradle: java quickstart' example. -- of course, you would use the 'gradle' tools to build it. But i thought to extend this example, for a nested java project, with a dependent jar.

Note: You need the 'gradle binary or source' distribution for this, example code is in: 'samples/java/quickstart'

% mkdir -p temp/classes
% curl --get \
    http://central.maven.org/maven2/commons-collections/commons-collections/3.2.2/commons-collections-3.2.2.jar \
        --output commons-collections-3.2.2.jar

% javac -g -classpath commons-collections-3.2.2.jar \
     -sourcepath src/main/java -d temp/classes \
      src/main/java/org/gradle/Person.java 

% jar cf my_example.jar -C temp/classes org/gradle/Person.class
% jar tvf my_example.jar
   0 Wed Jun 07 14:11:56 CEST 2017 META-INF/
  69 Wed Jun 07 14:11:56 CEST 2017 META-INF/MANIFEST.MF
 519 Wed Jun 07 13:58:06 CEST 2017 org/gradle/Person.class

ASP.NET custom error page - Server.GetLastError() is null

Here is my solution..

In Global.aspx:

void Application_Error(object sender, EventArgs e)
    {
        // Code that runs when an unhandled error occurs

        //direct user to error page 
        Server.Transfer("~/ErrorPages/Oops.aspx"); 
    }

In Oops.aspx:

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            LoadError(Server.GetLastError()); 
    }

    protected void LoadError(Exception objError)
    {
        if (objError != null)
        {
            StringBuilder lasterror = new StringBuilder();

            if (objError.Message != null)
            {
                lasterror.AppendLine("Message:");
                lasterror.AppendLine(objError.Message);
                lasterror.AppendLine();
            }

            if (objError.InnerException != null)
            {
                lasterror.AppendLine("InnerException:");
                lasterror.AppendLine(objError.InnerException.ToString());
                lasterror.AppendLine();
            }

            if (objError.Source != null)
            {
                lasterror.AppendLine("Source:");
                lasterror.AppendLine(objError.Source);
                lasterror.AppendLine();
            }

            if (objError.StackTrace != null)
            {
                lasterror.AppendLine("StackTrace:");
                lasterror.AppendLine(objError.StackTrace);
                lasterror.AppendLine();
            }

            ViewState.Add("LastError", lasterror.ToString());
        }
    }

   protected void btnReportError_Click(object sender, EventArgs e)
    {
        SendEmail();
    }

    public void SendEmail()
    {
        try
        {
            MailMessage msg = new MailMessage("webteam", "webteam");
            StringBuilder body = new StringBuilder();

            body.AppendLine("An unexcepted error has occurred.");
            body.AppendLine();

            body.AppendLine(ViewState["LastError"].ToString());

            msg.Subject = "Error";
            msg.Body = body.ToString();
            msg.IsBodyHtml = false;

            SmtpClient smtp = new SmtpClient("exchangeserver");
            smtp.Send(msg);
        }

        catch (Exception ex)
        {
            lblException.Text = ex.Message;
        }
    }

The name 'InitializeComponent' does not exist in the current context

Another common cause of this error is if you did something in this:

  1. Right click on folder in project to create new UserControl. This creates a class and xaml file that derives from user control in the namespace of the folder.

  2. Then you decide to change the namespace of the class because you're really just using folders for organization of code. The x:Class attribute will not get automatically updated so it will be searching for a class that doesn't exist. Could probably use a better error message like "x:Class type could not be found in namesace bla.blaa.blaaa."

Where are shared preferences stored?

I just tried to get path of shared preferences below like this.This is work for me.

File f = getDatabasePath("MyPrefsFile.xml");

if (f != null)
    Log.i("TAG", f.getAbsolutePath());

PHP mPDF save file as PDF

Try this:

$mpdf->Output('my_filename.pdf','D'); 

because:

D - means Download
F - means File-save only

add maven repository to build.gradle

You will need to define the repository outside of buildscript. The buildscript configuration block only sets up the repositories and dependencies for the classpath of your build script but not your application.

Changing the row height of a datagridview

you can do that on RowAdded Event :

_data_grid_view.RowsAdded += new System.Windows.Forms.DataGridViewRowsAddedEventHandler(this._data_grid_view_RowsAdded);

private void _data_grid_view_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            _data_grid_view.Rows[e.RowIndex].Height = 42;
        }

when a row add to the dataGridView it just change it height to 42.

How to generate a Makefile with source in sub-directories using just one makefile

This is another trick.

In main 'Makefile' define SRCDIR for each source dir and include 'makef.mk' for each value of SRCDIR. In each source dir put file 'files.mk' with list of source files and compile options for some of them. In main 'Makefile' one can define compile options and exclude files for each value of SRCDIR.

Makefile:

PRG             := prog-name

OPTIMIZE        := -O2 -fomit-frame-pointer

CFLAGS += -finline-functions-called-once
LDFLAGS += -Wl,--gc-section,--reduce-memory-overheads,--relax


.DEFAULT_GOAL   := hex

OBJDIR          := obj

MK_DIRS         := $(OBJDIR)


SRCDIR          := .
include         makef.mk

SRCDIR := crc
CFLAGS_crc := -DCRC8_BY_TABLE -DMODBUS_CRC_BY_TABLE
ASFLAGS_crc := -DCRC8_BY_TABLE -DMODBUS_CRC_BY_TABLE
include makef.mk

################################################################

CC              := avr-gcc -mmcu=$(MCU_TARGET) -I.
OBJCOPY         := avr-objcopy
OBJDUMP         := avr-objdump

C_FLAGS         := $(CFLAGS) $(REGS) $(OPTIMIZE)
CPP_FLAGS       := $(CPPFLAGS) $(REGS) $(OPTIMIZE)
AS_FLAGS        := $(ASFLAGS)
LD_FLAGS        := $(LDFLAGS) -Wl,-Map,$(OBJDIR)/$(PRG).map


C_OBJS          := $(C_SRC:%.c=$(OBJDIR)/%.o)
CPP_OBJS        := $(CPP_SRC:%.cpp=$(OBJDIR)/%.o)
AS_OBJS         := $(AS_SRC:%.S=$(OBJDIR)/%.o)

C_DEPS          := $(C_OBJS:%=%.d)
CPP_DEPS        := $(CPP_OBJS:%=%.d)
AS_DEPS         := $(AS_OBJS:%=%.d)

OBJS            := $(C_OBJS) $(CPP_OBJS) $(AS_OBJS)
DEPS            := $(C_DEPS) $(CPP_DEPS) $(AS_DEPS)


hex:  $(PRG).hex
lst:  $(PRG).lst


$(OBJDIR)/$(PRG).elf : $(OBJS)
    $(CC) $(C_FLAGS) $(LD_FLAGS) $^ -o $@

%.lst: $(OBJDIR)/%.elf
    -@rm $@ 2> /dev/nul
    $(OBJDUMP) -h -s -S $< > $@

%.hex: $(OBJDIR)/%.elf
    -@rm $@ 2> /dev/nul
    $(OBJCOPY) -j .text -j .data -O ihex $< $@


$(C_OBJS) : $(OBJDIR)/%.o : %.c Makefile
    $(CC) -MMD -MF [email protected] -c $(C_FLAGS) $(C_FLAGS_$(call clear_name,$<)) $< -o $@
    @sed -e 's,.*:,SRC_FILES += ,g' < [email protected] > [email protected]
    @sed -e "\$$s/$$/ $(subst /,\/,$(dir $<))files.mk\n/" < [email protected] >> [email protected]
    @sed -e 's,^[^:]*: *,,' -e 's,^[ \t]*,,' -e 's, \\$$,,' -e 's,$$, :,' < [email protected] >> [email protected]
    -@rm -f [email protected]

$(CPP_OBJS) : $(OBJDIR)/%.o : %.cpp Makefile
    $(CC) -MMD -MF [email protected] -c $(CPP_FLAGS) $(CPP_FLAGS_$(call clear_name,$<)) $< -o $@
    @sed -e 's,.*:,SRC_FILES += ,g' < [email protected] > [email protected]
    @sed -e "\$$s/$$/ $(subst /,\/,$(dir $<))files.mk\n/" < [email protected] >> [email protected]
    @sed -e 's,^[^:]*: *,,' -e 's,^[ \t]*,,' -e 's, \\$$,,' -e 's,$$, :,' < [email protected] >> [email protected]
    -@rm -f [email protected]

$(AS_OBJS) : $(OBJDIR)/%.o : %.S Makefile
    $(CC) -MMD -MF [email protected] -c $(AS_FLAGS) $(AS_FLAGS_$(call clear_name,$<)) $< -o $@
    @sed -e 's,.*:,SRC_FILES += ,g' < [email protected] > [email protected]
    @sed -e "\$$s/$$/ $(subst /,\/,$(dir $<))files.mk\n/" < [email protected] >> [email protected]
    @sed -e 's,^[^:]*: *,,' -e 's,^[ \t]*,,' -e 's, \\$$,,' -e 's,$$, :,' < [email protected] >> [email protected]
    -@rm -f [email protected]


clean:
    -@rm -rf $(OBJDIR)/$(PRG).elf
    -@rm -rf $(PRG).lst $(OBJDIR)/$(PRG).map
    -@rm -rf $(PRG).hex $(PRG).bin $(PRG).srec
    -@rm -rf $(PRG)_eeprom.hex $(PRG)_eeprom.bin $(PRG)_eeprom.srec
    -@rm -rf $(MK_DIRS:%=%/*.o) $(MK_DIRS:%=%/*.o.d)
    -@rm -f tags cscope.out

#   -rm -rf $(OBJDIR)/*
#   -rm -rf $(OBJDIR)
#   -rm $(PRG)


tag: tags
tags: $(SRC_FILES)
    if [ -e tags ] ; then ctags -u $? ; else ctags $^ ; fi
    cscope -U -b $^


# include dep. files
ifneq "$(MAKECMDGOALS)" "clean"
-include $(DEPS)
endif


# Create directory
$(shell mkdir $(MK_DIRS) 2>/dev/null)

makef.mk

SAVE_C_SRC := $(C_SRC)
SAVE_CPP_SRC := $(CPP_SRC)
SAVE_AS_SRC := $(AS_SRC)

C_SRC :=
CPP_SRC :=
AS_SRC :=


include $(SRCDIR)/files.mk
MK_DIRS += $(OBJDIR)/$(SRCDIR)


clear_name = $(subst /,_,$(1))


define rename_var
$(2)_$(call clear_name,$(SRCDIR))_$(call clear_name,$(1)) := \
    $($(subst _,,$(2))_$(call clear_name,$(SRCDIR))) $($(call clear_name,$(1)))
$(call clear_name,$(1)) :=
endef


define proc_lang

ORIGIN_SRC_FILES := $($(1)_SRC)

ifneq ($(strip $($(1)_ONLY_FILES)),)
$(1)_SRC := $(filter $($(1)_ONLY_FILES),$($(1)_SRC))
else

ifneq ($(strip $(ONLY_FILES)),)
$(1)_SRC := $(filter $(ONLY_FILES),$($(1)_SRC))
else
$(1)_SRC := $(filter-out $(EXCLUDE_FILES),$($(1)_SRC))
endif

endif

$(1)_ONLY_FILES :=
$(foreach name,$($(1)_SRC),$(eval $(call rename_var,$(name),$(1)_FLAGS)))
$(foreach name,$(ORIGIN_SRC_FILES),$(eval $(call clear_name,$(name)) :=))

endef


$(foreach lang,C CPP AS, $(eval $(call proc_lang,$(lang))))


EXCLUDE_FILES :=
ONLY_FILES :=


SAVE_C_SRC += $(C_SRC:%=$(SRCDIR)/%)
SAVE_CPP_SRC += $(CPP_SRC:%=$(SRCDIR)/%)
SAVE_AS_SRC += $(AS_SRC:%=$(SRCDIR)/%)

C_SRC := $(SAVE_C_SRC)
CPP_SRC := $(SAVE_CPP_SRC)
AS_SRC := $(SAVE_AS_SRC)

./files.mk

C_SRC   := main.c
CPP_SRC :=
AS_SRC  := timer.S

main.c += -DDEBUG

./crc/files.mk

C_SRC    := byte-modbus-crc.c byte-crc8.c
AS_SRC   := modbus-crc.S crc8.S modbus-crc-table.S crc8-table.S

byte-modbus-crc.c += --std=gnu99
byte-crc8.c       += --std=gnu99

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

To add new ViewController once you have have an existing ViewController, follow below step:

  1. Click on background of Main.storyboard.

  2. Search and select ViewController from object library at the utility window.

  3. Drag and drop it in background to create a new ViewController.

Can't create project on Netbeans 8.2

If you run in linux, open file netbeans.conf using nano or anything else.

nano netbeans-8.2/etc/netbeans.conf

and edit jdkhome or directory for jdk

netbeans_jdkhome="/usr/lib/jvm/java-1.8.0-openjdk-amd64"

you can check your jdk version with

java -version

or

ls /usr/lib/jvm

What is the best way to merge mp3 files?

Personally I would use something like mplayer with the audio pass though option eg -oac copy

WCF Service Client: The content type text/html; charset=utf-8 of the response message does not match the content type of the binding

NOTE: If your target server endpoint is using secure socket layer (SSL) certificate

Change your .config setting from basicHttpBinding to basicHttpsBinding

I am sure, It will resolve your problem.

'workbooks.worksheets.activate' works, but '.select' does not

You can't select a sheet in a non-active workbook.

You must first activate the workbook, then you can select the sheet.

workbooks("A").activate
workbooks("A").worksheets("B").select 

When you use Activate it automatically activates the workbook.

Note you can select >1 sheet in a workbook:

activeworkbook.sheets(array("sheet1","sheet3")).select

but only one sheet can be Active, and if you activate a sheet which is not part of a multi-sheet selection then those other sheets will become un-selected.

How can I create a marquee effect?

Based on the previous reply, mainly @fcalderan, this marquee scrolls when hovered, with the advantage that the animation scrolls completely even if the text is shorter than the space within it scrolls, also any text length takes the same amount of time (this may be a pros or a cons) when not hovered the text return in the initial position.

No hardcoded value other than the scroll time, best suited for small scroll spaces

_x000D_
_x000D_
.marquee {_x000D_
    width: 100%;_x000D_
    margin: 0 auto;_x000D_
    white-space: nowrap;_x000D_
    overflow: hidden;_x000D_
    box-sizing: border-box;_x000D_
    display: inline-flex;    _x000D_
}_x000D_
_x000D_
.marquee span {_x000D_
    display: flex;        _x000D_
    flex-basis: 100%;_x000D_
    animation: marquee-reset;_x000D_
    animation-play-state: paused;                _x000D_
}_x000D_
_x000D_
.marquee:hover> span {_x000D_
    animation: marquee 2s linear infinite;_x000D_
    animation-play-state: running;_x000D_
}_x000D_
_x000D_
@keyframes marquee {_x000D_
    0% {_x000D_
        transform: translate(0%, 0);_x000D_
    }    _x000D_
    50% {_x000D_
        transform: translate(-100%, 0);_x000D_
    }_x000D_
    50.001% {_x000D_
        transform: translate(100%, 0);_x000D_
    }_x000D_
    100% {_x000D_
        transform: translate(0%, 0);_x000D_
    }_x000D_
}_x000D_
@keyframes marquee-reset {_x000D_
    0% {_x000D_
        transform: translate(0%, 0);_x000D_
    }  _x000D_
}
_x000D_
<span class="marquee">_x000D_
    <span>This is the marquee text</span>_x000D_
</span>
_x000D_
_x000D_
_x000D_

CSS @font-face not working with Firefox, but working with Chrome and IE

I had exactly the same problem. I had to create a new folder called "fonts" and put it in wp_content. I can access it from my browser like this http://www.example.com/wp-content/fonts/CANDY.otf

Previously, the fonts folder was in the same directory as my CSS file, and the @font-face looked like this:

@font-face { 
    font-family: CANDY;
    src: url("fonts/CANDY.otf");
}

As i mentioned above, this was not working in Firefox but only with Chrome. Now it is working because I used an absolute path:

@font-face { 
    font-family: CANDY;
    src: url("http://www.example.com/wp-content/fonts/CANDY.otf");
}

How to center the content inside a linear layout?

android:gravity handles the alignment of its children,

android:layout_gravity handles the alignment of itself.

So use one of these.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000"
    android:baselineAligned="false"
    android:gravity="center"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".Main" >

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center" >

        <ImageView
            android:id="@+id/imageButton_speak"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/image_bg"
            android:src="@drawable/ic_speak" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center" >

        <ImageView
            android:id="@+id/imageButton_readtext"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/image_bg"
            android:src="@drawable/ic_readtext" />
    </LinearLayout>

    ...
</LinearLayout>

or

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000"
    android:baselineAligned="false"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".Main" >

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1" >

        <ImageView
            android:id="@+id/imageButton_speak"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:background="@drawable/image_bg"
            android:src="@drawable/ic_speak" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1" >

        <ImageView
            android:id="@+id/imageButton_readtext"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:background="@drawable/image_bg"
            android:src="@drawable/ic_readtext" />
    </LinearLayout>

    ...
</LinearLayout>

Convert an integer to a byte array

Check out the "encoding/binary" package. Particularly the Read and Write functions:

binary.Write(a, binary.LittleEndian, myInt)

Refreshing data in RecyclerView and keeping its scroll position

I was making a mistake like this, maybe it will help someone :)

If you use recyclerView.setAdapter every time new data come, it calls the adapter clear() method every time you use it, which causes the recyclerview to refresh and start over. To get rid of this, you need to use adapter.notiftyDatasetChanced().

XAMPP: Couldn't start Apache (Windows 10)

It's simply a matter of making port 80 available for your Apache service. The way I solved the problem was:

  1. On Windows 10, right click the start button and select Run
  2. Type services.msc and click OK
  3. Find and right click World wide web publishing service
  4. Select Properties
  5. Change the Startup type value to Automatic (Delayed Start)
  6. Restart your computer.

There you have it. All is back to normal.

How to convert a UTF-8 string into Unicode?

I have string that displays UTF-8 encoded characters

There is no such thing in .NET. The string class can only store strings in UTF-16 encoding. A UTF-8 encoded string can only exist as a byte[]. Trying to store bytes into a string will not come to a good end; UTF-8 uses byte values that don't have a valid Unicode codepoint. The content will be destroyed when the string is normalized. So it is already too late to recover the string by the time your DecodeFromUtf8() starts running.

Only handle UTF-8 encoded text with byte[]. And use UTF8Encoding.GetString() to convert it.