Programs & Examples On #Grinder

The Grinder is a Java load-testing framework that makes it easy to run a distributed test using many load injector machines.

ESLint Parsing error: Unexpected token

In my case (im using Firebase Cloud Functions) i opened .eslintrc.json and changed:

"parserOptions": {
  // Required for certain syntax usages
  "ecmaVersion": 2017
},

to:

"parserOptions": {
  // Required for certain syntax usages
  "ecmaVersion": 2020
},

Reducing video size with same format and reducing frame size

ffmpeg -i <input.mp4> -b:v 2048k -s 1000x600 -fs 2048k -vcodec mpeg4 -acodec copy <output.mp4>
  • -i input file

  • -b:v videobitrate of output video in kilobytes (you have to try)

  • -s dimensions of output video

  • -fs FILESIZE of output video in kilobytes

  • -vcodec videocodec (use ffmpeg -codecs to list all available codecs)

  • -acodec audio codec for output video (only copy the audiostream, don't temper)

explode string in jquery

if your input's id is following

<input type='text'  id='kg_row1' >

then you can get explode/split the above with the following function of split in jquery

  var kg_id = $(this).attr("id");
  var getvalues =kg_id.split("_");
  var id = getvalues[1];

How can I find the number of years between two dates?

Here's what I think is a better method:

public int getYearsBetweenDates(Date first, Date second) {
    Calendar firstCal = GregorianCalendar.getInstance();
    Calendar secondCal = GregorianCalendar.getInstance();

    firstCal.setTime(first);
    secondCal.setTime(second);

    secondCal.add(Calendar.DAY_OF_YEAR, 1 - firstCal.get(Calendar.DAY_OF_YEAR));

    return secondCal.get(Calendar.YEAR) - firstCal.get(Calendar.YEAR);
}

EDIT

Apart from a bug which I fixed, this method does not work well with leap years. Here's a complete test suite. I guess you're better off using the accepted answer.

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

class YearsBetweenDates {
    public static int getYearsBetweenDates(Date first, Date second) {
        Calendar firstCal = GregorianCalendar.getInstance();
        Calendar secondCal = GregorianCalendar.getInstance();

        firstCal.setTime(first);
        secondCal.setTime(second);

        secondCal.add(Calendar.DAY_OF_YEAR, 1 - firstCal.get(Calendar.DAY_OF_YEAR));

        return secondCal.get(Calendar.YEAR) - firstCal.get(Calendar.YEAR);
    }

    private static class TestCase {
        public Calendar date1;
        public Calendar date2;
        public int expectedYearDiff;
        public String comment;

        public TestCase(Calendar date1, Calendar date2, int expectedYearDiff, String comment) {
            this.date1 = date1;
            this.date2 = date2;
            this.expectedYearDiff = expectedYearDiff;
            this.comment = comment;
        }
    }

    private static TestCase[] tests = {
        new TestCase(
                new GregorianCalendar(2014, Calendar.JULY, 15),
                new GregorianCalendar(2015, Calendar.JULY, 15),
                1,
                "exactly one year"),
        new TestCase(
                new GregorianCalendar(2014, Calendar.JULY, 15),
                new GregorianCalendar(2017, Calendar.JULY, 14),
                2,
                "one day less than 3 years"),
        new TestCase(
                new GregorianCalendar(2015, Calendar.NOVEMBER, 3),
                new GregorianCalendar(2017, Calendar.MAY, 3),
                1,
                "a year and a half"),
        new TestCase(
                new GregorianCalendar(2016, Calendar.JULY, 15),
                new GregorianCalendar(2017, Calendar.JULY, 15),
                1,
                "leap years do not compare correctly"),
    };

    public static void main(String[] args) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        for (TestCase t : tests) {
            int diff = getYearsBetweenDates(t.date1.getTime(), t.date2.getTime());
            String result = diff == t.expectedYearDiff ? "PASS" : "FAIL";
            System.out.println(t.comment + ": " +
                    df.format(t.date1.getTime()) + " -> " +
                    df.format(t.date2.getTime()) + " = " +
                    diff + ": " + result);
        }
    }
}

Query for documents where array size is greater than 1

I believe this is the fastest query that answers your question, because it doesn't use an interpreted $where clause:

{$nor: [
    {name: {$exists: false}},
    {name: {$size: 0}},
    {name: {$size: 1}}
]}

It means "all documents except those without a name (either non existant or empty array) or with just one name."

Test:

> db.test.save({})
> db.test.save({name: []})
> db.test.save({name: ['George']})
> db.test.save({name: ['George', 'Raymond']})
> db.test.save({name: ['George', 'Raymond', 'Richard']})
> db.test.save({name: ['George', 'Raymond', 'Richard', 'Martin']})
> db.test.find({$nor: [{name: {$exists: false}}, {name: {$size: 0}}, {name: {$size: 1}}]})
{ "_id" : ObjectId("511907e3fb13145a3d2e225b"), "name" : [ "George", "Raymond" ] }
{ "_id" : ObjectId("511907e3fb13145a3d2e225c"), "name" : [ "George", "Raymond", "Richard" ] }
{ "_id" : ObjectId("511907e3fb13145a3d2e225d"), "name" : [ "George", "Raymond", "Richard", "Martin" ] }
>

Returning a pointer to a vector element in c++

I'm not sure if returning the address of the thing pointed by the iterator is needed. All you need is the pointer itself. You will see STL's iterator class itself implementing the use of _Ptr for this purpose. So, just do:

return iterator._Ptr;

OpenSSL Verify return code: 20 (unable to get local issuer certificate)

This error also happens if you're using a self-signed certificate with a keyUsage missing the value keyCertSign.

JQuery get data from JSON array

You're not looping over the items. Try this instead:

$.getJSON(url, function(data){
    $.each(data.response.venue.tips.groups.items, function (index, value) {
        console.log(this.text);
    });
});

Bootstrap Element 100% Width

If you can't change the HTML layout:

.full-width {
    width: 100vw;
    margin-left: -50vw;
    left: 50%;
}
<div class="container">
  <div class="row">
    <div class="col-xs-12">a</div>
    <div class="col-xs-12">b</div>
    <div class="col-xs-12 full-width">c</div>
    <div class="col-xs-12">d</div>
  </div>
</div>

Demo: http://www.bootply.com/tVkNyWJxA6

CSS Change List Item Background Color with Class

The ul.nav li is more restrictive and so takes precedence, try this:

ul.nav li.selected {  
  background-color:red; 
}

Why am I suddenly getting a "Blocked loading mixed active content" issue in Firefox?

If you are consuming an internal service via AJAX, make sure the url points to https, this cleared up the error for me.

Initial AJAX URL: "http://XXXXXX.com/Core.svc/" + ApiName
Corrected AJAX URL: "https://XXXXXX.com/Core.svc/" + ApiName,

How can I overwrite file contents with new content in PHP?

MY PREFERRED METHOD is using fopen,fwrite and fclose [it will cost less CPU]

$f=fopen('myfile.txt','w');
fwrite($f,'new content');
fclose($f);

Warning for those using file_put_contents

It'll affect a lot in performance, for example [on the same class/situation] file_get_contents too: if you have a BIG FILE, it'll read the whole content in one shot and that operation could take a long waiting time

Clear the form field after successful submission of php form

I was just trying to fix same error, I finally fixed it, so I will copy to you part of the code, maybe it helps you.

<input type="text" name="usu" id="usu" value="<?php echo $usu;?>" ></input>
<input type="text" name="pass" id="pass" value="<?php echo $varpass;?>"></input>  

those are the inputs I wanted to clean after pressing my button.

And here php code:

$query= "INSERT INTO usuarios (tipo, usuario, password) VALUES ('".$vartipo."', '".$usu."', '".$varpass."')";


        if (!mysqli_query($conexion,$query)){

            die('Error: ' . mysqli_error($conexion));
        }

        else{


            $usu = '';  
            $varpass= '';   

            $result = '<div class="result_ok">El usuario se ha registrado con éxito! <div>';        


        }

$usu = '';
$varpass= '';

those are the lines that cleans the inputs :D

Android LinearLayout : Add border with shadow around a LinearLayout

okay, i know this is way too late. but i had the same requirement. i solved like this

1.First create a xml file (example: border_shadow.xml) in "drawable" folder and copy the below code into it.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >

<item>
    <shape>
        <!-- set the shadow color here -->
        <stroke
            android:width="2dp"
            android:color="#7000" />

        <!-- setting the thickness of shadow (positive value will give shadow on that side) -->

        <padding
            android:bottom="2dp"
            android:left="2dp"
            android:right="-1dp"
            android:top="-1dp" />

        <corners android:radius="3dp" />
    </shape>
</item>

<!-- Background -->

<item>
    <shape>
        <solid android:color="#fff" />
        <corners android:radius="3dp" />
    </shape>
</item>

2.now on the layout where you want the shadow(example: LinearLayout) add this in android:background

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="8dip"
    android:background="@drawable/border_shadow"
    android:orientation="vertical">

and that worked for me.

UICollectionView cell selection and cell reuse

you can just set the selectedBackgroundView of the cell to be backgroundColor=x.

Now any time you tap on cell his selected mode will change automatically and will couse to the background color to change to x.

Multi-line string with extra space (preserved indentation)

it will work if you put it as below:

AA='first line
\nsecond line 
\nthird line'
echo $AA
output:
first line
second line
third line

How can I trigger the click event of another element in ng-click using angularjs?

I think you are over complicated things a bit. Do you really need to trigger a click on the input from your button ?

I suggest you just apply a proper style to your input and the ngFileSelect directive will do the rest and call your onFileSelect function whenever a file is submitted :

input.file {
    cursor: pointer;
    direction: ltr;
    font-size: 23px;
    margin: 0;
    opacity: 0;
    position: absolute;
    right: 0;
    top: 0;
    transform: translate(-300px, 0px) scale(4);
}

How do I test a single file using Jest?

You have two options:

  • Option 1: Command line. You can run the following command

    node '/Users/complete-path-to-you-project/your-project/node_modules/.bin/jest' '/Users/complete-path-to-you-project/your-project/path-to-your-file-within-the-project/your-file.spec.ts'
    

    This avoids you to install Jest globally. You use the jest used by your project.

  • Option 2: If you are using Visual Studio Code you have a great plugin to do this: Jest Runner. It allows you not only to run tests file by file, but even specific suites and specs just by a right click on the tests you want to run.

What is the best way to implement constants in Java?

The number one mistake you can make is creating a globally accessible class called with a generic name, like Constants. This simply gets littered with garbage and you lose all ability to figure out what portion of your system uses these constants.

Instead, constants should go into the class which "owns" them. Do you have a constant called TIMEOUT? It should probably go into your Communications() or Connection() class. MAX_BAD_LOGINS_PER_HOUR? Goes into User(). And so on and so forth.

The other possible use is Java .properties files when "constants" can be defined at run-time, but not easily user changeable. You can package these up in your .jars and reference them with the Class resourceLoader.

Why did I get the compile error "Use of unassigned local variable"?

While value types have default values and can not be null, they also need to be explicitly initialized in order to be used. You can think of these two rules as side by side rules.

Value types can not be null ? the compiler guarantees that. If you ask how, the error message you got is the answer. Once you call their constructors, they got initialized with their default values.

int tmpCnt; // Not accepted
int tmpCnt = new Int(); // Default value applied tmpCnt = 0

jump to line X in nano editor

I am using nano editor in a Raspberry Pi with Italian OS language and Italian keyboard. Don't know the exact reason, but in this environment the shortcut is:

Ctrl+-

WordPress - Check if user is logged in

Example: Display different output depending on whether the user is logged in or not.

<?php

if ( is_user_logged_in() ) {
    echo 'Welcome, registered user!';
} else {
    echo 'Welcome, visitor!';
}

?>

Responsive Images with CSS

.erb-image-wrapper img{
    max-width:100% !important;
    height:auto;
    display:block;
}

Worked for me.
Thanks for MrMisterMan for his assistance.

How to declare a global variable in JavaScript

The best way is to use closures, because the window object gets very, very cluttered with properties.

HTML

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="init.js"></script>
    <script type="text/javascript">
      MYLIBRARY.init(["firstValue", 2, "thirdValue"]);
    </script>
    <script src="script.js"></script>
  </head>

  <body>
    <h1>Hello !</h1>
  </body>
</html>

init.js (based on this answer)

var MYLIBRARY = MYLIBRARY || (function(){
    var _args = {}; // Private

    return {
        init : function(Args) {
            _args = Args;
            // Some other initialising
        },
        helloWorld : function(i) {
            return _args[i];
        }
    };
}());

script.js

// Here you can use the values defined in the HTML content as if it were a global variable
var a = "Hello World " + MYLIBRARY.helloWorld(2);

alert(a);

Here's the plnkr. Hope it help !

Validating an XML against referenced XSD in C#

personally I favor validating without a callback:

public bool ValidateSchema(string xmlPath, string xsdPath)
{
    XmlDocument xml = new XmlDocument();
    xml.Load(xmlPath);

    xml.Schemas.Add(null, xsdPath);

    try
    {
        xml.Validate(null);
    }
    catch (XmlSchemaValidationException)
    {
        return false;
    }
    return true;
}

(see Timiz0r's post in Synchronous XML Schema Validation? .NET 3.5)

PHP - find entry by object property from an array of objects

Using array_column to re-index will save time if you need to find multiple times:

$lookup = array_column($arr, NULL, 'id');   // re-index by 'id'

Then you can simply $lookup[$id] at will.

JavaScript Array to Set

If you start out with:

let array = [
    {name: "malcom", dogType: "four-legged"},
    {name: "peabody", dogType: "three-legged"},
    {name: "pablo", dogType: "two-legged"}
];

And you want a set of, say, names, you would do:

let namesSet = new Set(array.map(item => item.name));

Extract column values of Dataframe as List in Apache Spark

List<String> whatever_list = df.toJavaRDD().map(new Function<Row, String>() {
    public String call(Row row) {
        return row.getAs("column_name").toString();
    }
}).collect();

logger.info(String.format("list is %s",whatever_list)); //verification

Since no one has given any solution in java(Real Programming Language) Can thank me later

How to swap String characters in Java?

//this is a very basic way of how to order a string alpha-wise, this does not use anything fancy and is great for school use

package string_sorter;

public class String_Sorter {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        String word = "jihgfedcba";
        for (int endOfString = word.length(); endOfString > 0; endOfString--) {

            int largestWord = word.charAt(0);
            int location = 0;
            for (int index = 0; index < endOfString; index++) {

                if (word.charAt(index) > largestWord) {

                    largestWord = word.charAt(index);
                    location = index;
                }
            }

            if (location < endOfString - 1) {

                String newString = word.substring(0, location) + word.charAt(endOfString - 1) + word.substring(location + 1, endOfString - 1) + word.charAt(location);
                word = newString;
            }
            System.out.println(word);
        }

        System.out.println(word);
    }

}

Best timestamp format for CSV/Excel?

For second accuracy, yyyy-MM-dd HH:mm:ss should do the trick.

I believe Excel is not very good with fractions of a second (loses them when interacting with COM object IIRC).

UnicodeEncodeError: 'ascii' codec can't encode character at special name

Try setting the system default encoding as utf-8 at the start of the script, so that all strings are encoded using that.

Example -

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

The above should set the default encoding as utf-8 .

Python : List of dict, if exists increment a dict value, if not append a new dict

Except for the first time, each time a word is seen the if statement's test fails. If you are counting a large number of words, many will probably occur multiple times. In a situation where the initialization of a value is only going to occur once and the augmentation of that value will occur many times it is cheaper to use a try statement:

urls_d = {}
for url in list_of_urls:
    try:
        urls_d[url] += 1
    except KeyError:
        urls_d[url] = 1

you can read more about this: https://wiki.python.org/moin/PythonSpeed/PerformanceTips

Detecting a redirect in ajax request?

You can now use fetch API/ It returns redirected: *boolean*

How to get an Array with jQuery, multiple <input> with the same name

You can't use same id for multiple elements in a document. Keep the ids different and name same for the elements.

<input type="text" id="task1" name="task" />
<input type="text" id="task2" name="task" />
<input type="text" id="task3" name="task" />
<input type="text" id="task4" name="task" />
<input type="text" id="task5" name="task" />

var newArray = new Array();

$("input:text[name=task]").each(function(){
    newArray.push($(this));
});

An array of List in c#

simple approach:

        List<int>[] a = new List<int>[100];
        for (int i = 0; i < a.Length; i++)
        {
            a[i] = new List<int>();
        }

or LINQ approach

        var b = Enumerable.Range(0,100).Select((i)=>new List<int>()).ToArray();

How to check cordova android version of a cordova/phonegap project?

For getting all the info about the cordova package use this command:

npm info cordova

Moment.js - two dates difference in number of days

_x000D_
_x000D_
$('#test').click(function() {_x000D_
  var startDate = moment("01.01.2019", "DD.MM.YYYY");_x000D_
  var endDate = moment("01.02.2019", "DD.MM.YYYY");_x000D_
_x000D_
  var result = 'Diff: ' + endDate.diff(startDate, 'days');_x000D_
_x000D_
  $('#result').html(result);_x000D_
});
_x000D_
#test {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background: #ffb;_x000D_
  padding: 10px;_x000D_
  border: 2px solid #999;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.js"></script>_x000D_
_x000D_
<div id='test'>Click Me!!!</div>_x000D_
<div id='result'></div>
_x000D_
_x000D_
_x000D_

Chrome Extension - Get DOM content

For those who tried gkalpak answer and it did not work,

be aware that chrome will add the content script to a needed page only when your extension enabled during chrome launch and also a good idea restart browser after making these changes

How to validate white spaces/empty spaces? [Angular 2]

What I did was created a validator that did the samething as angular for minLength except I added the trim()

import { Injectable } from '@angular/core';
import { AbstractControl, ValidatorFn, Validators } from '@angular/forms';


@Injectable()
export class ValidatorHelper {
    ///This is the guts of Angulars minLength, added a trim for the validation
    static minLength(minLength: number): ValidatorFn {
        return (control: AbstractControl): { [key: string]: any } => {
            if (ValidatorHelper.isPresent(Validators.required(control))) {
                return null;
            }
             const v: string = control.value ? control.value : '';
            return v.trim().length < minLength ?
                { 'minlength': { 'requiredLength': minLength, 'actualLength': v.trim().length } } :
                null;
        };
    }

    static isPresent(obj: any): boolean {
        return obj !== undefined && obj !== null;
    }
}

I then in my app.component.ts overrode the minLength function provided by angular.

import { Component, OnInit } from '@angular/core';    
import { ValidatorHelper } from 'app/common/components/validators/validator-helper';
import { Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {  
  constructor() { }

  ngOnInit(): void {       
    Validators.minLength = ValidatorHelper.minLength;
  }
}

Now everywhere angular's minLength built in validator is used, it will use the minLength that you have created in the helper.

Validators.compose([
      Validators.minLength(2)         
    ]);

How to use ES6 Fat Arrow to .filter() an array of objects

As simple as you can use const adults = family.filter(({ age }) => age > 18 );

_x000D_
_x000D_
const family =[{"name":"Jack",  "age": 26},_x000D_
              {"name":"Jill",  "age": 22},_x000D_
              {"name":"James", "age": 5 },_x000D_
              {"name":"Jenny", "age": 2 }];_x000D_
_x000D_
const adults = family.filter(({ age }) => age > 18 );_x000D_
_x000D_
console.log(adults)
_x000D_
_x000D_
_x000D_

Accessing an SQLite Database in Swift

This is by far the best SQLite library that I've used in Swift: https://github.com/stephencelis/SQLite.swift

Look at the code examples. So much cleaner than the C API:

import SQLite

let db = try Connection("path/to/db.sqlite3")

let users = Table("users")
let id = Expression<Int64>("id")
let name = Expression<String?>("name")
let email = Expression<String>("email")

try db.run(users.create { t in
    t.column(id, primaryKey: true)
    t.column(name)
    t.column(email, unique: true)
})
// CREATE TABLE "users" (
//     "id" INTEGER PRIMARY KEY NOT NULL,
//     "name" TEXT,
//     "email" TEXT NOT NULL UNIQUE
// )

let insert = users.insert(name <- "Alice", email <- "[email protected]")
let rowid = try db.run(insert)
// INSERT INTO "users" ("name", "email") VALUES ('Alice', '[email protected]')

for user in try db.prepare(users) {
    print("id: \(user[id]), name: \(user[name]), email: \(user[email])")
    // id: 1, name: Optional("Alice"), email: [email protected]
}
// SELECT * FROM "users"

let alice = users.filter(id == rowid)

try db.run(alice.update(email <- email.replace("mac.com", with: "me.com")))
// UPDATE "users" SET "email" = replace("email", 'mac.com', 'me.com')
// WHERE ("id" = 1)

try db.run(alice.delete())
// DELETE FROM "users" WHERE ("id" = 1)

try db.scalar(users.count) // 0
// SELECT count(*) FROM "users"

The documentation also says that "SQLite.swift also works as a lightweight, Swift-friendly wrapper over the C API," and follows with some examples of that.

Eclipse error: 'Failed to create the Java Virtual Machine'

  1. Open the eclipse.ini file from your eclipse folder.

  2. It has some of add on configuration . Find the line –launcher.XXMaxPermSize. Now remove the the default value 256m and save it.

How to connect to a secure website using SSL in Java with a pkcs12 file?

For anyone encountering a similar situation I was able to solve the issue above as follows:

  1. Regenerate your pkcs12 file as follows:

    openssl pkcs12 -in oldpkcs.p12 -out keys -passout pass:tmp
    openssl pkcs12 -in keys -export -out new.p12 -passin pass:tmp -passout pass:newpasswd
    
  2. Import the CA certificate from server into a TrustStore ( either your own, or the java keystore in $JAVA_HOME/jre/lib/security/cacerts, password: changeit).

  3. Set the following system properties:

    System.setProperty("javax.net.ssl.trustStore", "myTrustStore");
    System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
    System.setProperty("javax.net.ssl.keyStoreType", "pkcs12");
    System.setProperty("javax.net.ssl.keyStore", "new.p12");
    System.setProperty("javax.net.ssl.keyStorePassword", "newpasswd");
    
  4. Test ur url.

Courtesy@ http://forums.sun.com/thread.jspa?threadID=5296333

Abstraction vs Encapsulation in Java

In simple words: You do abstraction when deciding what to implement. You do encapsulation when hiding something that you have implemented.

TypeScript - Append HTML to container element in Angular 2

You could do something like this:

htmlComponent.ts

htmlVariable: string = "<b>Some html.</b>"; //this is html in TypeScript code that you need to display

htmlComponent.html

<div [innerHtml]="htmlVariable"></div> //this is how you display html code from TypeScript in your html

How to enable TLS 1.2 in Java 7

There are many suggestions but I found two of them most common.

Re. JAVA_OPTS

I first tried export JAVA_OPTS="-Dhttps.protocols=SSLv3,TLSv1,TLSv1.1,TLSv1.2" on command line before startup of program but it didn't work for me.

Re. constructor

Then I added the following code in the startup class constructor and it worked for me.

try {
        SSLContext ctx = SSLContext.getInstance("TLSv1.2");
        ctx.init(null, null, null);
        SSLContext.setDefault(ctx);
} catch (Exception e) {
        System.out.println(e.getMessage());
}

Frankly, I don't know in detail why ctx.init(null, null, null); but all (SSL/TLS) is working fine for me.

Re. System.setProperty

There is one more option: System.setProperty("https.protocols", "SSLv3,TLSv1,TLSv1.1,TLSv1.2");. It will also go in code but I've not tried it.

What are intent-filters in Android?

If possible try this one instant solution:

Intent intent =new Intent(getApplicationBaseContext,second_Act.class);
StartActivity(intent);

JPA mapping: "QuerySyntaxException: foobar is not mapped..."

JPQL mostly is case-insensitive. One of the things that is case-sensitive is Java entity names. Change your query to:

"SELECT r FROM FooBar r"

How to get the current plugin directory in WordPress?

Try this:

function PluginUrl() {

        //Try to use WP API if possible, introduced in WP 2.6
        if (function_exists('plugins_url')) return trailingslashit(plugins_url(basename(dirname(__FILE__))));

        //Try to find manually... can't work if wp-content was renamed or is redirected
        $path = dirname(__FILE__);
        $path = str_replace("\\","/",$path);
        $path = trailingslashit(get_bloginfo('wpurl')) . trailingslashit(substr($path,strpos($path,"wp-content/")));
        return $path;
    }

echo PluginUrl(); will return the current plugin url.

Display PNG image as response to jQuery AJAX request

This allows you to just get the image data and set to the img src, which is cool.

var oReq = new XMLHttpRequest();
oReq.open("post", '/somelocation/getmypic', true );        
oReq.responseType = "blob";
oReq.onload = function ( oEvent )
{
    var blob = oReq.response;
    var imgSrc = URL.createObjectURL( blob );                        
    var $img = $( '<img/>', {                
        "alt": "test image",
        "src": imgSrc
    } ).appendTo( $( '#bb_theImageContainer' ) );
    window.URL.revokeObjectURL( imgSrc );
};
oReq.send( null );

The basic idea is that the data is returned untampered with, it is placed in a blob and then a url is created to that object in memory. See here and here. Note supported browsers.

Format date in a specific timezone

You can Try this ,

Here you can get the date based on the Client Timezone (Browser).

moment(new Date().getTime()).zone(new Date().toString().match(/([-\+][0-9]+)\s/)[1]).format('YYYY-MM-DD HH:mm:ss')

The regex basically gets you the offset value.

Cheers!!

Spring 3 RequestMapping: Get path value

Non-matched part of the URL is exposed as a request attribute named HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE:

@RequestMapping("/{id}/**")
public void foo(@PathVariable("id") int id, HttpServletRequest request) {
    String restOfTheUrl = (String) request.getAttribute(
        HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
    ...
}

How to change the color of the axis, ticks and labels for a plot in matplotlib

If you have several figures or subplots that you want to modify, it can be helpful to use the matplotlib context manager to change the color, instead of changing each one individually. The context manager allows you to temporarily change the rc parameters only for the immediately following indented code, but does not affect the global rc parameters.

This snippet yields two figures, the first one with modified colors for the axis, ticks and ticklabels, and the second one with the default rc parameters.

import matplotlib.pyplot as plt
with plt.rc_context({'axes.edgecolor':'orange', 'xtick.color':'red', 'ytick.color':'green', 'figure.facecolor':'white'}):
    # Temporary rc parameters in effect
    fig, (ax1, ax2) = plt.subplots(1,2)
    ax1.plot(range(10))
    ax2.plot(range(10))
# Back to default rc parameters
fig, ax = plt.subplots()
ax.plot(range(10))

enter image description here

enter image description here

You can type plt.rcParams to view all available rc parameters, and use list comprehension to search for keywords:

# Search for all parameters containing the word 'color'
[(param, value) for param, value in plt.rcParams.items() if 'color' in param]

How can I generate UUID in C#

Be careful: while the string representations for .NET Guid and (RFC4122) UUID are identical, the storage format is not. .NET trades in little-endian bytes for the first three Guid parts.

If you are transmitting the bytes (for example, as base64), you can't just use Guid.ToByteArray() and encode it. You'll need to Array.Reverse the first three parts (Data1-3).

I do it this way:

var rfc4122bytes = Convert.FromBase64String("aguidthatIgotonthewire==");
Array.Reverse(rfc4122bytes,0,4);
Array.Reverse(rfc4122bytes,4,2);
Array.Reverse(rfc4122bytes,6,2);
var guid = new Guid(rfc4122bytes);

See this answer for the specific .NET implementation details.

Edit: Thanks to Jeff Walker, Code Ranger, for pointing out that the internals are not relevant to the format of the byte array that goes in and out of the byte-array constructor and ToByteArray().

How do I check if a list is empty?

Simple way is checking the length is equal zero.

if len(a) == 0:
    print("a is empty")

How can I create an utility class?

Making a class abstract sends a message to the readers of your code that you want users of your abstract class to subclass it. However, this is not what you want then to do: a utility class should not be subclassed.

Therefore, adding a private constructor is a better choice here. You should also make the class final to disallow subclassing of your utility class.

Javascript querySelector vs. getElementById

The functions getElementById and getElementsByClassName are very specific, while querySelector and querySelectorAll are more elaborate. My guess is that they will actually have a worse performance.

Also, you need to check for the support of each function in the browsers you are targetting. The newer it is, the higher probability of lack of support or the function being "buggy".

List vs tuple, when to use each?

A minor but notable advantage of a list over a tuple is that lists tend to be slightly more portable. Standard tools are less likely to support tuples. JSON, for example, does not have a tuple type. YAML does, but its syntax is ugly compared to its list syntax, which is quite nice.

In those cases, you may wish to use a tuple internally then convert to list as part of an export process. Alternately, you might want to use lists everywhere for consistency.

Clear text in EditText when entered

Very Simple to clear editText values.when u click button then only follow 1 line code.

Inside button or anywhere u want.Only use this

editText.setText("");   

What is a Question Mark "?" and Colon ":" Operator Used for?

They are called the ternary operator since they are the only one in Java.

The difference to the if...else construct is, that they return something, and this something can be anything:

  int k = a > b ? 7 : 8; 
  String s = (foobar.isEmpty ()) ? "empty" : foobar.toString (); 

Execution order of events when pressing PrimeFaces p:commandButton

It failed because you used ajax="false". This fires a full synchronous request which in turn causes a full page reload, causing the oncomplete to be never fired (note that all other ajax-related attributes like process, onstart, onsuccess, onerror and update are also never fired).

That it worked when you removed actionListener is also impossible. It should have failed the same way. Perhaps you also removed ajax="false" along it without actually understanding what you were doing. Removing ajax="false" should indeed achieve the desired requirement.


Also is it possible to execute actionlistener and oncomplete simultaneously?

No. The script can only be fired before or after the action listener. You can use onclick to fire the script at the moment of the click. You can use onstart to fire the script at the moment the ajax request is about to be sent. But they will never exactly simultaneously be fired. The sequence is as follows:

  • User clicks button in client
  • onclick JavaScript code is executed
  • JavaScript prepares ajax request based on process and current HTML DOM tree
  • onstart JavaScript code is executed
  • JavaScript sends ajax request from client to server
  • JSF retrieves ajax request
  • JSF processes the request lifecycle on JSF component tree based on process
  • actionListener JSF backing bean method is executed
  • action JSF backing bean method is executed
  • JSF prepares ajax response based on update and current JSF component tree
  • JSF sends ajax response from server to client
  • JavaScript retrieves ajax response
    • if HTTP response status is 200, onsuccess JavaScript code is executed
    • else if HTTP response status is 500, onerror JavaScript code is executed
  • JavaScript performs update based on ajax response and current HTML DOM tree
  • oncomplete JavaScript code is executed

Note that the update is performed after actionListener, so if you were using onclick or onstart to show the dialog, then it may still show old content instead of updated content, which is poor for user experience. You'd then better use oncomplete instead to show the dialog. Also note that you'd better use action instead of actionListener when you intend to execute a business action.

See also:

what does numpy ndarray shape do?

.shape() gives the actual shape of your array in terms of no of elements in it, No of rows/No of Columns. The answer you get is in the form of tuples.

For Example: 1D ARRAY:

d=np.array([1,2,3,4])
print(d)
(1,)

Output: (4,) ie the number4 denotes the no of elements in the 1D Array.

2D Array:

e=np.array([[1,2,3],[4,5,6]])   
print(e)
(2,3)

Output: (2,3) ie the number of rows and the number of columns.

The number of elements in the final output will depend on the number of rows in the Array....it goes on increasing gradually.

How to handle configuration in Go

I wrote a simple ini config library in golang.

https://github.com/c4pt0r/cfg

goroutine-safe, easy to use

package cfg
import (
    "testing"
)

func TestCfg(t *testing.T) {
    c := NewCfg("test.ini")
    if err := c.Load() ; err != nil {
        t.Error(err)
    }
    c.WriteInt("hello", 42)
    c.WriteString("hello1", "World")

    v, err := c.ReadInt("hello", 0)
    if err != nil || v != 42 {
        t.Error(err)
    }

    v1, err := c.ReadString("hello1", "")
    if err != nil || v1 != "World" {
        t.Error(err)
    }

    if err := c.Save(); err != nil {
        t.Error(err)
    }
}

===================Update=======================

Recently I need an INI parser with section support, and I write a simple package:

github.com/c4pt0r/cfg

u can parse INI like using "flag" package:

package main

import (
    "log"
    "github.com/c4pt0r/ini"
)

var conf = ini.NewConf("test.ini")

var (
    v1 = conf.String("section1", "field1", "v1")
    v2 = conf.Int("section1", "field2", 0)
)

func main() {
    conf.Parse()

    log.Println(*v1, *v2)
}

How can I print to the same line?

In Linux, there is different escape sequences for control terminal. For example, there is special escape sequence for erase whole line: \33[2K and for move cursor to previous line: \33[1A. So all you need is to print this every time you need to refresh the line. Here is the code which prints Line 1 (second variant):

System.out.println("Line 1 (first variant)");
System.out.print("\33[1A\33[2K");
System.out.println("Line 1 (second variant)");

There are codes for cursor navigation, clearing screen and so on.

I think there are some libraries which helps with it (ncurses?).

Twitter bootstrap scrollable table

I recently had a similar problem and ended up fixing it using a mixture of different solutions.

The first and most simple one was to use two tables, one for the headers and one for the body. This works but the headers and the body columns are not aligned. And, since I wanted to use the auto-size that comes with twitter bootstrap tables I ended up creating a Javascript function that changes the headers when: the body is rendered; the windows is resized; the data in the column changes, etc.

Here is some of the code I used:

        <table class="table table-striped table-hover" style="margin-bottom: 0px;">
        <thead>
            <tr>
                <th data-sort="id">Header 1</i></th>
                <th data-sort="guide">Header 2</th>
                <th data-sort="origin">Header 3</th>
                <th data-sort="supplier">Header 4</th>
            </tr>
        </thead>
    </table>
    <div class="bodycontainer scrollable">
        <table class="table table-hover table-striped table-scrollable">
            <tbody id="rows"></tbody>
        </table>
    </div>

The headers and the body are divided in two separate tables. One of them is inside a DIV with the necessary style to generate the vertical scrollbars. Here is the CSS I used:

.bodycontainer {
  //height: 200px
  width: 100%;
  margin: 0;
}

.table-scrollable {
  margin: 0px;
  padding: 0px;
}

I commented the height here because I a wanted the table to reach the bottom of the page, whatever the page height might be.

The data-sort attributes I used in the headers are also used in every td. This way I could get the width and the padding of every td and the width of the row. Using the data-sort attributes I set using CSS the padding and width of each header accordingly and of the header row which is always bigger since it doesn´t have a scrollbar. Here is the function using coffeescript:

fixHeaders: =>
  for header, i in @headers
    tdpadding = parseInt(@$("td[data-sort=#{header}]").css('padding'))
    tdwidth = parseInt(@$("td[data-sort=#{header}]").css('width'))
    @$("th[data-sort=#{header}]").css('padding', tdpadding)
    @$("th[data-sort=#{header}]").css('width', tdwidth)
    if (i+1) == @headers.length
      trwidth = @$("td[data-sort=#{header}]").parent().css('width')
      @$("th[data-sort=#{header}]").parent().parent().parent().css('width', trwidth)
      @$('.bodycontainer').css('height', window.innerHeight - ($('html').outerHeight() -@$('.bodycontainer').outerHeight() ) ) unless @collection.length == 0

Here I assume that you have an array of the headers called @headers.

It is not pretty but it works. Hope it helps someone.

T-SQL: Looping through an array of known values

You can try as below :

declare @list varchar(MAX), @i int
select @i=0, @list ='4,7,12,22,19,'

while( @i < LEN(@list))
begin
    declare @item varchar(MAX)
    SELECT  @item = SUBSTRING(@list,  @i,CHARINDEX(',',@list,@i)-@i)
    select @item

     --do your stuff here with @item 
     exec p_MyInnerProcedure @item 

    set @i = CHARINDEX(',',@list,@i)+1
    if(@i = 0) set @i = LEN(@list) 
end

How to handle the modal closing event in Twitter Bootstrap?

There are two pair of modal events, one is "show" and "shown", the other is "hide" and "hidden". As you can see from the name, hide event fires when modal is about the be close, such as clicking on the cross on the top-right corner or close button or so on. While hidden is fired after the modal is actually close. You can test these events your self. For exampel:

$( '#modal' )
   .on('hide', function() {
       console.log('hide');
   })
   .on('hidden', function(){
       console.log('hidden');
   })
   .on('show', function() {
       console.log('show');
   })
   .on('shown', function(){
      console.log('shown' )
   });

And, as for your question, I think you should listen to the 'hide' event of your modal.

How to append a newline to StringBuilder

I create original class that similar to StringBuidler and can append line by calling method appendLine(String str).

public class StringBuilderPlus {

    private StringBuilder sb;

    public StringBuilderPlus(){
         sb = new StringBuilder();
    }

    public void append(String str)
    {
        sb.append(str != null ? str : "");
    }

    public void appendLine(String str)
    {
        sb.append(str != null ? str : "").append(System.getProperty("line.separator"));
    }

    public String toString()
    {
        return sb.toString();
    }
}

Usage:

StringBuilderPlus sb = new StringBuilderPlus();
sb.appendLine("aaaaa");
sb.appendLine("bbbbb");
System.out.println(sb.toString());

Console:

aaaaa
bbbbb

java.net.URLEncoder.encode(String) is deprecated, what should I use instead?

You should use:

URLEncoder.encode("NAME", "UTF-8");

How do you get the "object reference" of an object in java when toString() and hashCode() have been overridden?

You cannot safely do what you want since the default hashCode() may not return the address, and has been mentioned, multiple objects with the same hashCode are possible. The only way to accomplish what you want, is to actually override the hashCode() method for the objects in question and guarantee that they all provide unique values. Whether this is feasible in your situation is another question.

For the record, I have experienced multiple objects with the same default hashcode in an IBM VM running in a WAS server. We had a defect where objects being put into a remote cache would get overwritten because of this. That was an eye opener for me at that point since I assumed the default hashcode was the objects memory address as well.

How to add List<> to a List<> in asp.net

Use .AddRange to append any Enumrable collection to the list.

How to vertically center a "div" element for all browsers using CSS?

This solution worked for me if you have a block element (e. g. ). I used the colors to make the solution clearer.

HTML:

<main class="skin_orange">
<p>As you can the the element/box is vertically centered</p>
<div class="bigBox skin_blue">Blue Box</div>
</main>

CSS:

main {
    position: relative;
    width: 400px;
    height: 400px;
}

.skin_orange {
    outline: thin dotted red;
    background: orange;
}

.bigBox {
    width: 150px;
    height: 150px;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
}

.skin_blue {
    background-color: blue;
}

JSFiddle Code Demo

How to check if array element is null to avoid NullPointerException in Java

String labels[] = { "MH", null, "AP", "KL", "CH", "MP", "GJ", "OR" }; 

if(Arrays.toString(labels).indexOf("null") > -1)  {
    System.out.println("Array Element Must not be null");
                     (or)
    throw new Exception("Array Element Must not be null");
}        
------------------------------------------------------------------------------------------         

For two Dimensional array

String labels2[][] = {{ "MH", null, "AP", "KL", "CH", "MP", "GJ", "OR" },{ "MH", "FG", "AP", "KL", "CH", "MP", "GJ", "OR" };    

if(Arrays.deepToString(labels2).indexOf("null") > -1)  {
    System.out.println("Array Element Must not be null");
                 (or)
    throw new Exception("Array Element Must not be null");
}    
------------------------------------------------------------------------------------------

same for Object Array    

String ObjectArray[][] = {{ "MH", null, "AP", "KL", "CH", "MP", "GJ", "OR" },{ "MH", "FG", "AP", "KL", "CH", "MP", "GJ", "OR" };    

if(Arrays.deepToString(ObjectArray).indexOf("null") > -1)  {
    System.out.println("Array Element Must not be null");
              (or)
    throw new Exception("Array Element Must not be null");
  }

If you want to find a particular null element, you should use for loop as above said .

How to make two plots side-by-side using Python?

Change your subplot settings to:

plt.subplot(1, 2, 1)

...

plt.subplot(1, 2, 2)

The parameters for subplot are: number of rows, number of columns, and which subplot you're currently on. So 1, 2, 1 means "a 1-row, 2-column figure: go to the first subplot." Then 1, 2, 2 means "a 1-row, 2-column figure: go to the second subplot."

You currently are asking for a 2-row, 1-column (that is, one atop the other) layout. You need to ask for a 1-row, 2-column layout instead. When you do, the result will be:

side by side plot

In order to minimize the overlap of subplots, you might want to kick in a:

plt.tight_layout()

before the show. Yielding:

neater side by side plot

How can I extract embedded fonts from a PDF as valid font files?

This is a followup to the font-forge section of @Kurt Pfeifle's answer, specific to Red Hat (and possibly other Linux distros).

  1. After opening the PDF and selecting the font you want, you will want to select "File -> Generate Fonts..." option.
  2. If there are errors in the file, you can choose to ignore them or save the file and edit them. Most of the errors can be fixed automatically if you click "Fix" enough times.
  3. Click "Element -> Font Info...", and "Fontname", "Family Name" and "Name for Humans" are all set to values you like. If not, modify them and save the file somewhere. These names will determine how your font appears on the system.
  4. Select your file name and click "Save..."

Once you have your TTF file, you can install it on your system by

  1. Copying it to folder /usr/share/fonts (as root)
  2. Running fc-cache -f /usr/share/fonts/ (as root)

html "data-" attribute as javascript parameter

you might use default parameters in your function and then just pass the entire dataset itself, since the dataset is already a DOMStringMap Object

<div data-uid="aaa" data-name="bbb" data-value="ccc"
onclick="fun(this.dataset)">

<script>
const fun = ({uid:'ddd', name:'eee', value:'fff', other:'default'} = {}) { 
    // 
}
</script>

that way, you can deal with any data-values that got set in the html tag, or use defaults if they weren't set - that kind of thing

maybe not in this situation, but in others, it might be advantageous to put all your preferences in a single data-attribute

<div data-all='{"uid":"aaa","name":"bbb","value":"ccc"}'
onclick="fun(JSON.parse(this.dataset.all))">

there are probably more terse ways of doing that, if you already know certain things about the order of the data

<div data-all="aaa,bbb,ccc" onclick="fun(this.dataset.all.split(','))">

Best practice for using assert?

As has been said previously, assertions should be used when your code SHOULD NOT ever reach a point, meaning there is a bug there. Probably the most useful reason I can see to use an assertion is an invariant/pre/postcondition. These are something that must be true at the start or end of each iteration of a loop or a function.

For example, a recursive function (2 seperate functions so 1 handles bad input and the other handles bad code, cause it's hard to distinguish with recursion). This would make it obvious if I forgot to write the if statement, what had gone wrong.

def SumToN(n):
    if n <= 0:
        raise ValueError, "N must be greater than or equal to 0"
    else:
        return RecursiveSum(n)

def RecursiveSum(n):
    #precondition: n >= 0
    assert(n >= 0)
    if n == 0:
        return 0
    return RecursiveSum(n - 1) + n
    #postcondition: returned sum of 1 to n

These loop invariants often can be represented with an assertion.

How to print environment variables to the console in PowerShell?

Prefix the variable name with env:

$env:path

For example, if you want to print the value of environment value "MINISHIFT_USERNAME", then command will be:

$env:MINISHIFT_USERNAME

You can also enumerate all variables via the env drive:

Get-ChildItem env:

How to compare dates in Java?

tl;dr

LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) ) ;
Boolean isBetween = 
    ( ! today.isBefore( localDate1 ) )  // “not-before” is short for “is-equal-to or later-than”.
    &&
    today.isBefore( localDate3 ) ; 

Or, better, if you add the ThreeTen-Extra library to your project.

LocalDateRange.of(
    LocalDate.of( … ) ,
    LocalDate.of( … )
).contains(
    LocalDate.now()
)

Half-open approach, where beginning is inclusive while ending is exclusive.

Bad Choice of Format

By the way, that is a bad choice of format for a text representation of a date or date-time value. Whenever possible, stick with the standard ISO 8601 formats. ISO 8601 formats are unambiguous, understandable across human cultures, and are easy to parse by machine.

For a date-only value, the standard format is YYYY-MM-DD. Note how this format has the benefit of being chronological when sorted alphabetically.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );

Table of all date-time types in Java, both modern and legacy

DateTimeFormatter

As your input strings are non-standard format, we must define a formatting pattern to match.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" );

Use that to parse the input strings.

LocalDate start = LocalDate.parse( "22-02-2010" , f );
LocalDate stop = LocalDate.parse( "25-12-2010" , f );

In date-time work, usually best to define a span of time by the Half-Open approach where the beginning is inclusive while the ending is exclusive. So we want to know if today is the same or later than the start and also before the stop. A briefer way of saying “is the same or later than the start” is “not before the start”.

Boolean intervalContainsToday = ( ! today.isBefore( start ) ) && today.isBefore( stop ) ;

See the Answer by gstackoverflow showing the list of comparison methods you can call.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


UPDATE: This “Joda-Time” section below is left intact as history. The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

Joda-Time

Other answers are correct with regard to the bundled java.util.Date and java.util.Calendar classes. But those classes are notoriously troublesome. So here's some example code using the Joda-Time 2.3 library.

If you truly want a date without any time portion and no time zone, then use the LocalDate class in Joda-Time. That class provides methods of comparison including compareTo (used with Java Comparators), isBefore, isAfter, and isEqual.

Inputs…

String string1 = "22-02-2010";
String string2 = "07-04-2010";
String string3 = "25-12-2010";

Define a formatter describing the input strings…

DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd-MM-yyyy" );

Use formatter to parse the strings into LocalDate objects…

LocalDate localDate1 = formatter.parseLocalDate( string1 );
LocalDate localDate2 = formatter.parseLocalDate( string2 );
LocalDate localDate3 = formatter.parseLocalDate( string3 );

boolean is1After2 = localDate1.isAfter( localDate2 );
boolean is2Before3 = localDate2.isBefore( localDate3 );

Dump to console…

System.out.println( "Dates: " + localDate1 + " " + localDate2 + " " + localDate3 );
System.out.println( "is1After2 " + is1After2 );
System.out.println( "is2Before3 " + is2Before3 );

When run…

Dates: 2010-02-22 2010-04-07 2010-12-25
is1After2 false
is2Before3 true

So see if the second is between the other two (exclusively, meaning not equal to either endpoint)…

boolean is2Between1And3 = ( ( localDate2.isAfter( localDate1 ) ) && ( localDate2.isBefore( localDate3 ) ) );

Working With Spans Of Time

If you are working with spans of time, I suggest exploring in Joda-Time the classes: Duration, Interval, and Period. Methods such as overlap and contains make comparisons easy.

For text representations, look at the ISO 8601 standard’s:

  • duration
    Format: PnYnMnDTnHnMnS
    Example: P3Y6M4DT12H30M5S
    (Means “three years, six months, four days, twelve hours, thirty minutes, and five seconds”)
  • interval
    Format: start/end
    Example: 2007-03-01T13:00:00Z/2008-05-11T15:30:00Z

Joda-Time classes can work with strings in both those formats, both as input (parsing) and output (generating strings).

Joda-Time performs comparisons using the Half-Open approach where the beginning of the span is inclusive while the ending is exclusive. This approach is a wise one for handling spans of time. Search StackOverflow for more info.

Passing in class names to react components

For anyone interested, I ran into this same issue when using css modules and react css modules.

Most components have an associated css module style, and in this example my Button has its own css file, as does the Promo parent component. But I want to pass some additional styles to Button from Promo

So the styleable Button looks like this:

Button.js

import React, { Component } from 'react'
import CSSModules from 'react-css-modules'
import styles from './Button.css'

class Button extends Component {

  render() {

    let button = null,
        className = ''

    if(this.props.className !== undefined){
        className = this.props.className
    }

    button = (
      <button className={className} styleName='button'>
        {this.props.children}
      </button>
    )

    return (
        button
    );
  }
};

export default CSSModules(Button, styles, {allowMultiple: true} )

In the above Button component the Button.css styles handle the common button styles. In this example just a .button class

Then in my component where I want to use the Button, and I also want to modify things like the position of the button, I can set extra styles in Promo.css and pass through as the className prop. In this example again called .button class. I could have called it anything e.g. promoButton.

Of course with css modules this class will be .Promo__button___2MVMD whereas the button one will be something like .Button__button___3972N

Promo.js

import React, { Component } from 'react';
import CSSModules from 'react-css-modules';
import styles from './Promo.css';

import Button from './Button/Button'

class Promo extends Component {

  render() {

    return (
        <div styleName='promo' >
          <h1>Testing the button</h1>
          <Button className={styles.button} >
            <span>Hello button</span>
          </Button>
        </div>
      </Block>
    );
  }
};

export default CSSModules(Promo, styles, {allowMultiple: true} );

The representation of if-elseif-else in EL using JSF

One possible solution is:

<h:panelGroup rendered="#{bean.row == 10}">
    <div class="text-success">
        <h:outputText value="#{bean.row}"/>
    </div>
</h:panelGroup>

Can an int be null in Java?

int can't be null, but Integer can. You need to be careful when unboxing null Integers since this can cause a lot of confusion and head scratching!

e.g. this:

int a = object.getA(); // getA returns a null Integer

will give you a NullPointerException, despite object not being null!

To follow up on your question, if you want to indicate the absence of a value, I would investigate java.util.Optional<Integer>

How can I add NSAppTransportSecurity to my info.plist file?

Xcode 8.2, iOS 10

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

How do I run a file on localhost?

Ok, thanks for the more specific info, ppl may remove their downvotes now...

What you are proposing is a very common thing to do! You want to run your web application locally without uploading it to your host yet. That's totally fine and that's what your Apache is there for. Your Apache is a web server meaning its main purpose is to serve HTML, PHP, ASP, etc. files. Some like PHP; it first sends to the interpreter and then sends the rendered file to the browser. All in all: it's just serving pages to your browser (the client).

Your web server has a root directory which is wwwroot (IIS) or htdocs (apache, xampp) or something else like public_html, www or html, etc. It depends on your OS and web server.

Now if you type http://localhost into your browser, your browser will be directed to this webroot and the server will serve any index.html, index.php, etc. it can find there (in a customizable order).

If you have a project called "mytutorial" you can enter http://localhost/mytutorial and the server will show you the index-file of your tutorial, etc. If you look at the absolute path of this tutorial folder then it's just a subfolder of your webroot, which is itself located somewhere on your harddrive, but that doesn't matter for your localhost.

So the relative path is

http://localhost/mytutorial

while the absolute path may be

c:/webservices/apache/www

or

c:/xampp/htdocs

If you're working with Dreamweaver you can simplify the testing process by setting up your local server as a testing server in your project settings. Try it! It's easy. Once it's done, you can just press the browser icon with any of your files and it will open on localhost.

Find if current time falls in a time range

if (new TimeSpan(11,59,0) <= currentTime.TimeOfDay && new TimeSpan(13,01,0) >=  currentTime.TimeOfDay)
{
   //match found
}

if you really want to parse a string into a TimeSpan, then you can use:

    TimeSpan start = TimeSpan.Parse("11:59");
    TimeSpan end = TimeSpan.Parse("13:01");

Inline SVG in CSS

I found one solution for SVG. But it is work only for Webkit, I just want share my workaround with you. In my example is shown how to use SVG element from DOM as background through a filter (background-image: url('#glyph') is not working).

Features needed for this SVG icon render:

  1. Applying SVG filter effects to HTML elements using CSS (IE and Edge not supports)
  2. feImage fragment load supporting (firefox not supports)

_x000D_
_x000D_
.test {_x000D_
  /*  background-image: url('#glyph');_x000D_
    background-size:100% 100%;*/_x000D_
    filter: url(#image); _x000D_
    height:100px;_x000D_
    width:100px;_x000D_
}_x000D_
.test:before {_x000D_
   display:block;_x000D_
   content:'';_x000D_
   color:transparent;_x000D_
}_x000D_
.test2{_x000D_
  width:100px;_x000D_
  height:100px;_x000D_
}_x000D_
.test2:before {_x000D_
   display:block;_x000D_
   content:'';_x000D_
   color:transparent;_x000D_
   filter: url(#image); _x000D_
   height:100px;_x000D_
   width:100px;_x000D_
}
_x000D_
<svg style="height:0;width:0;" version="1.1" viewbox="0 0 100 100"_x000D_
     xmlns="http://www.w3.org/2000/svg"_x000D_
     xmlns:xlink="http://www.w3.org/1999/xlink">_x000D_
 <defs>_x000D_
     <g id="glyph">_x000D_
          <path id="heart" d="M100 34.976c0 8.434-3.635 16.019-9.423 21.274h0.048l-31.25 31.25c-3.125 3.125-6.25 6.25-9.375 6.25s-6.25-3.125-9.375-6.25l-31.202-31.25c-5.788-5.255-9.423-12.84-9.423-21.274 0-15.865 12.861-28.726 28.726-28.726 8.434 0 16.019 3.635 21.274 9.423 5.255-5.788 12.84-9.423 21.274-9.423 15.865 0 28.726 12.861 28.726 28.726z" fill="crimson"/>_x000D_
     </g>_x000D_
    <svg id="resized-glyph"  x="0%" y="0%" width="24" height="24" viewBox="0 0 100 100" class="icon shape-codepen">_x000D_
      <use xlink:href="#glyph"></use>_x000D_
    </svg>_x000D_
     <filter id="image">_x000D_
       <feImage xlink:href="#resized-glyph" x="0%" y="0%" width="100%" height="100%" result="res"/>_x000D_
       <feComposite operator="over" in="res" in2="SourceGraphic"/>_x000D_
    </filter>_x000D_
 </defs>_x000D_
</svg>_x000D_
<div class="test">_x000D_
</div>_x000D_
<div class="test2">_x000D_
</div>
_x000D_
_x000D_
_x000D_

One more solution, is use url encode

_x000D_
_x000D_
var container = document.querySelector(".container");_x000D_
var svg = document.querySelector("svg");_x000D_
var svgText = (new XMLSerializer()).serializeToString(svg);_x000D_
container.style.backgroundImage = `url(data:image/svg+xml;utf8,${encodeURIComponent(svgText)})`;
_x000D_
.container{_x000D_
  height:50px;_x000D_
  width:250px;_x000D_
  display:block;_x000D_
  background-position: center center;_x000D_
  background-repeat: no-repeat;_x000D_
  background-size: contain;_x000D_
}
_x000D_
<svg  height="100" width="500" xmlns="http://www.w3.org/2000/svg">_x000D_
    <ellipse cx="240" cy="50" rx="220" ry="30" style="fill:yellow" />_x000D_
</svg>_x000D_
<div class="container"></div>
_x000D_
_x000D_
_x000D_

AWS ssh access 'Permission denied (publickey)' issue

If you are running AWS image from Bitnami. The username would be bitnami. Cheers!

see my debug and look at the last one:

*

ssh -v -i awsliferaysrta.pem.txt [email protected].***
OpenSSH_6.2p2, OSSLShim 0.9.8r 8 Dec 2011
debug1: Reading configuration data /etc/ssh_config
debug1: /etc/ssh_config line 20: Applying options for *
debug1: Connecting to 54.254.250.*** [54.254.250.***] port 22.
debug1: Connection established.
debug1: identity file awsliferaysrta.pem.txt type -1
debug1: identity file awsliferaysrta.pem.txt-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_6.2
debug1: Remote protocol version 2.0, remote software version OpenSSH_5.9p1 Debian-5ubuntu1.1
debug1: match: OpenSSH_5.9p1 Debian-5ubuntu1.1 pat OpenSSH_5*
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-ctr hmac-md5 none
debug1: kex: client->server aes128-ctr hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Server host key: RSA 05:5c:78:45:c9:39:3a:84:fe:f8:19:5d:31:48:aa:5f
debug1: Host '54.254.250.***' is known and matches the RSA host key.
debug1: Found key in /Users/macbookpro/.ssh/known_hosts:2
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Trying private key: awsliferaysrta.pem.txt
debug1: read PEM private key done: type RSA
debug1: Authentication succeeded (publickey).
Authenticated to 54.254.250.*** ([54.254.250.***]:22).
debug1: channel 0: new [client-session]
debug1: Requesting [email protected]
debug1: Entering interactive session.
debug1: Remote: Port forwarding disabled.
debug1: Remote: Agent forwarding disabled.
debug1: Remote: X11 forwarding disabled.
debug1: Remote: Forced command.
debug1: Sending environment.
debug1: Sending env LANG = en_US.UTF-8
Please login as the user "bitnami" rather than the user "root".

*

Media Queries: How to target desktop, tablet, and mobile?

  • Extra small devices ~ Phones (< 768px)
  • Small devices ~ Tablets (>= 768px)
  • Medium devices ~ Desktops (>= 992px)
  • Large devices ~ Desktops (>= 1200px)

Another git process seems to be running in this repository

For me for any reason :

rm .git/index.lock

Didn't work, so I just went to the .git file and deleted it manually which worked fantastically.

PHP 5.4 Call-time pass-by-reference - Easy fix available?

You should be denoting the call by reference in the function definition, not the actual call. Since PHP started showing the deprecation errors in version 5.3, I would say it would be a good idea to rewrite the code.

From the documentation:

There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);.

For example, instead of using:

// Wrong way!
myFunc(&$arg);               # Deprecated pass-by-reference argument
function myFunc($arg) { }

Use:

// Right way!
myFunc($var);                # pass-by-value argument
function myFunc(&$arg) { }

SQL Query Where Field DOES NOT Contain $x

SELECT * FROM table WHERE field1 NOT LIKE '%$x%'; (Make sure you escape $x properly beforehand to avoid SQL injection)

Edit: NOT IN does something a bit different - your question isn't totally clear so pick which one to use. LIKE 'xxx%' can use an index. LIKE '%xxx' or LIKE '%xxx%' can't.

Import cycle not allowed

You may have imported,

project/controllers/base

inside the

project/controllers/routes

You have already imported before. That's not supported.

Git: Find the most recent common ancestor of two branches

As noted in a prior answer, although git merge-base works,

$ git merge-base myfeature develop
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2

If myfeature is the current branch, as is common, you can use --fork-point:

$ git merge-base --fork-point develop
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2

This argument works only in sufficiently recent versions of git. Unfortunately it doesn't always work, however, and it is not clear why. Please refer to the limitations noted toward the end of this answer.


For full commit info, consider:

$ git log -1 $(git merge-base --fork-point develop) 

Show and hide divs at a specific time interval using jQuery

See InnerFade.

<script type="text/javascript">
    $(document).ready(

    function() {
        $('#portfolio').innerfade({
            speed: 'slow',
            timeout: 10000,
            type: 'sequence',
            containerheight: '220px'
        });
    });
</script>
<ul id="portfolio">
    <li>
        <a href="http://medienfreunde.com/deutsch/referenzen/kreation/good_guy__bad_guy.html">
        <img src="images/ggbg.gif" alt="Good Guy bad Guy" />
        </a>
    </li>
    <li>
        <a href="http://medienfreunde.com/deutsch/referenzen/kreation/whizzkids.html">
        <img src="images/whizzkids.gif" alt="Whizzkids" />
        </a>
    </li>
    <li>
        <a href="http://medienfreunde.com/deutsch/referenzen/printdesign/koenigin_mutter.html">
        <img src="images/km.jpg" alt="Königin Mutter" />
        </a>
    </li>
    <li>
        <a href="http://medienfreunde.com/deutsch/referenzen/webdesign/rt_reprotechnik_-_hybride_archivierung.html">
        <img src="images/rt_arch.jpg" alt="RT Hybride Archivierung" />
        </a>
    </li>
    <li>
        <a href="http://medienfreunde.com/deutsch/referenzen/kommunikation/tuev_sued_gruppe.html">
        <img src="images/tuev.jpg" alt="TÜV SÜD Gruppe" />
        </a>
    </li>
</ul>

Get min and max value in PHP Array

foreach ($array as $k => $v) {
  $tArray[$k] = $v['Weight'];
}
$min_value = min($tArray);
$max_value = max($tArray);

startActivityForResult() from a Fragment and finishing child Activity, doesn't call onActivityResult() in Fragment

The fragment already has startActivityForResult, which would call onActivityResult in the fragment if you use it, instead of getActivity()...

Best way to store time (hh:mm) in a database

Just store a regular datetime and ignore everything else. Why spend extra time writing code that loads an int, manipulates it, and converts it into a datetime, when you could just load a datetime?

@Nullable annotation usage

It makes it clear that the method accepts null values, and that if you override the method, you should also accept null values.

It also serves as a hint for code analyzers like FindBugs. For example, if such a method dereferences its argument without checking for null first, FindBugs will emit a warning.

Javascript - How to show escape characters in a string?

JavaScript uses the \ (backslash) as an escape characters for:

  • \' single quote
  • \" double quote
  • \ backslash
  • \n new line
  • \r carriage return
  • \t tab
  • \b backspace
  • \f form feed
  • \v vertical tab (IE < 9 treats '\v' as 'v' instead of a vertical tab ('\x0B'). If cross-browser compatibility is a concern, use \x0B instead of \v.)
  • \0 null character (U+0000 NULL) (only if the next character is not a decimal digit; else it’s an octal escape sequence)

Note that the \v and \0 escapes are not allowed in JSON strings.

Get event listeners attached to node using addEventListener

You can't.

The only way to get a list of all event listeners attached to a node is to intercept the listener attachment call.

DOM4 addEventListener

Says

Append an event listener to the associated list of event listeners with type set to type, listener set to listener, and capture set to capture, unless there already is an event listener in that list with the same type, listener, and capture.

Meaning that an event listener is added to the "list of event listeners". That's all. There is no notion of what this list should be nor how you should access it.

Markdown and including multiple files

My solution is to use m4. It's supported on most platforms and is included in the binutils package.

First include a macro changequote() in the file to change the quoting characters to what you prefer (default is `'). The macro is removed when the file is processed.

changequote(`{{', `}}')
include({{other_file}})

On the commandline:

m4 -I./dir_containing_other_file/ input.md > _tmp.md
pandoc -o output.html _tmp.md

How can I use optional parameters in a T-SQL stored procedure?

Extend your WHERE condition:

WHERE
    (FirstName = ISNULL(@FirstName, FirstName)
    OR COALESCE(@FirstName, FirstName, '') = '')
AND (LastName = ISNULL(@LastName, LastName)
    OR COALESCE(@LastName, LastName, '') = '')
AND (Title = ISNULL(@Title, Title)
    OR COALESCE(@Title, Title, '') = '')

i. e. combine different cases with boolean conditions.

Android "elevation" not showing a shadow

If it still not showing elevation try

    android:hardwareAccelerated="true" 

this will definitely help you.

AngularJs .$setPristine to reset form

There is another way to pristine form that is by sending form into the controller. For example:-

In view:-

<form name="myForm" ng-submit="addUser(myForm)" novalidate>
    <input type="text" ng-mode="user.name"/>
     <span style="color:red" ng-show="myForm.name.$dirty && myForm.name.$invalid">
      <span ng-show="myForm.name.$error.required">Name is required.</span>
    </span>

    <button ng-disabled="myForm.$invalid">Add User</button>
</form>

In Controller:-

$scope.addUser = function(myForm) {
       myForm.$setPristine();
};

psycopg2: insert multiple rows with one query

cursor.copy_from is the fastest solution I've found for bulk inserts by far. Here's a gist I made containing a class named IteratorFile which allows an iterator yielding strings to be read like a file. We can convert each input record to a string using a generator expression. So the solution would be

args = [(1,2), (3,4), (5,6)]
f = IteratorFile(("{}\t{}".format(x[0], x[1]) for x in args))
cursor.copy_from(f, 'table_name', columns=('a', 'b'))

For this trivial size of args it won't make much of a speed difference, but I see big speedups when dealing with thousands+ of rows. It will also be more memory efficient than building a giant query string. An iterator would only ever hold one input record in memory at a time, where at some point you'll run out of memory in your Python process or in Postgres by building the query string.

Touch move getting stuck Ignored attempt to cancel a touchmove

Please remove e.preventDefault(), because event.cancelable of touchmove is false. So you can't call this method.

remove duplicates from sql union

If you are using T-SQL you could use a temporary table in a stored procedure and update or insert the records of your query accordingly.

How to convert UTF8 string to byte array?

As there is no pure byte type in JavaScript we can represent a byte array as an array of numbers, where each number represents a byte and thus will have an integer value between 0 and 255 inclusive.

Here is a simple function that does convert a JavaScript string into an Array of numbers that contain the UTF-8 encoding of the string:

function toUtf8(str) {
    var value = [];
    var destIndex = 0;
    for (var index = 0; index < str.length; index++) {
        var code = str.charCodeAt(index);
        if (code <= 0x7F) {
            value[destIndex++] = code;
        } else if (code <= 0x7FF) {
            value[destIndex++] = ((code >> 6 ) & 0x1F) | 0xC0;
            value[destIndex++] = ((code >> 0 ) & 0x3F) | 0x80;
        } else if (code <= 0xFFFF) {
            value[destIndex++] = ((code >> 12) & 0x0F) | 0xE0;
            value[destIndex++] = ((code >> 6 ) & 0x3F) | 0x80;
            value[destIndex++] = ((code >> 0 ) & 0x3F) | 0x80;
        } else if (code <= 0x1FFFFF) {
            value[destIndex++] = ((code >> 18) & 0x07) | 0xF0;
            value[destIndex++] = ((code >> 12) & 0x3F) | 0x80;
            value[destIndex++] = ((code >> 6 ) & 0x3F) | 0x80;
            value[destIndex++] = ((code >> 0 ) & 0x3F) | 0x80;
        } else if (code <= 0x03FFFFFF) {
            value[destIndex++] = ((code >> 24) & 0x03) | 0xF0;
            value[destIndex++] = ((code >> 18) & 0x3F) | 0x80;
            value[destIndex++] = ((code >> 12) & 0x3F) | 0x80;
            value[destIndex++] = ((code >> 6 ) & 0x3F) | 0x80;
            value[destIndex++] = ((code >> 0 ) & 0x3F) | 0x80;
        } else if (code <= 0x7FFFFFFF) {
            value[destIndex++] = ((code >> 30) & 0x01) | 0xFC;
            value[destIndex++] = ((code >> 24) & 0x3F) | 0x80;
            value[destIndex++] = ((code >> 18) & 0x3F) | 0x80;
            value[destIndex++] = ((code >> 12) & 0x3F) | 0x80;
            value[destIndex++] = ((code >> 6 ) & 0x3F) | 0x80;
            value[destIndex++] = ((code >> 0 ) & 0x3F) | 0x80;
        } else {
            throw new Error("Unsupported Unicode character \"" 
                + str.charAt(index) + "\" with code " + code + " (binary: " 
                + toBinary(code) + ") at index " + index
                + ". Cannot represent it as UTF-8 byte sequence.");
        }
    }
    return value;
}

function toBinary(byteValue) {
    if (byteValue < 0) {
        byteValue = byteValue & 0x00FF;
    }
    var str = byteValue.toString(2);
    var len = str.length;
    var prefix = "";
    for (var i = len; i < 8; i++) {
        prefix += "0";
    }
    return prefix + str;
}

How do I compile jrxml to get jasper?

There are three ways to compile jrxml to jasper.

  1. You can do direct compile via compile button (hammer logo) on iReport designer.

  2. You can use ant to compile as shown in the Ant Compile Sample.

    <target name="compile1"> 
      <mkdir dir="./build/reports"/> 
      <jrc 
        srcdir="./reports"
        destdir="./build/reports"
        tempdir="./build/reports"
        keepjava="true"
        xmlvalidation="true">
       <classpath refid="runClasspath"/>
       <include name="**/*.jrxml"/>
      </jrc>
    </target>
    

    Below is the report compile task on my current project.

    alt text

    addition from Daniel Rikowski :

  3. You can also use the JasperCompileManager class to compile from your java code.

    JasperCompileManager.compileReportToFile(
                    "our_jasper_template.jrxml", // the path to the jrxml file to compile
                    "our_compiled_template.jasper"); // the path and name we want to save the compiled file to
    

How to SFTP with PHP?

I performed a full-on cop-out and wrote a class which creates a batch file and then calls sftp via a system call. Not the nicest (or fastest) way of doing it but it works for what I need and it didn't require any installation of extra libraries or extensions in PHP.

Could be the way to go if you don't want to use the ssh2 extensions

Common CSS Media Queries Break Points


@media only screen and (min-width : 320px) and (max-width : 480px) {/*--- Mobile portrait ---*/}
@media only screen and (min-width : 480px) and (max-width : 595px) {/*--- Mobile landscape ---*/}
@media only screen and (min-width : 595px) and (max-width : 690px) {/*--- Small tablet portrait ---*/}
@media only screen and (min-width : 690px) and (max-width : 800px) {/*--- Tablet portrait ---*/}
@media only screen and (min-width : 800px) and (max-width : 1024px) {/*--- Small tablet landscape ---*/}
@media only screen and (min-width : 1024px) and (max-width : 1224px) {/*--- Tablet landscape --- */}

JavaScript error (Uncaught SyntaxError: Unexpected end of input)

In my case, it was caused by a missing (0) in javascript:void(0) in an anchor.

How do I set the driver's python version in spark?

Ran into this today at work. An admin thought it prudent to hard code Python 2.7 as the PYSPARK_PYTHON and PYSPARK_DRIVER_PYTHON in $SPARK_HOME/conf/spark-env.sh. Needless to say this broke all of our jobs that utilize any other python versions or environments (which is > 90% of our jobs). @PhillipStich points out correctly that you may not always have write permissions for this file, as is our case. While setting the configuration in the spark-submit call is an option, another alternative (when running in yarn/cluster mode) is to set the SPARK_CONF_DIR environment variable to point to another configuration script. There you could set your PYSPARK_PYTHON and any other options you may need. A template can be found in the spark-env.sh source code on github.

Convert string into Date type on Python

from datetime import datetime

a = datetime.strptime(f, "%Y-%m-%d")

Error: expected type-specifier before 'ClassName'

For future people struggling with a similar problem, the situation is that the compiler simply cannot find the type you are using (even if your Intelisense can find it).

This can be caused in many ways:

  • You forgot to #include the header that defines it.
  • Your inclusion guards (#ifndef BLAH_H) are defective (your #ifndef BLAH_H doesn't match your #define BALH_H due to a typo or copy+paste mistake).
  • Your inclusion guards are accidentally used twice (two separate files both using #define MYHEADER_H, even if they are in separate directories)
  • You forgot that you are using a template (eg. new Vector() should be new Vector<int>())
  • The compiler is thinking you meant one scope when really you meant another (For example, if you have NamespaceA::NamespaceB, AND a <global scope>::NamespaceB, if you are already within NamespaceA, it'll look in NamespaceA::NamespaceB and not bother checking <global scope>::NamespaceB) unless you explicitly access it.
  • You have a name clash (two entities with the same name, such as a class and an enum member).

To explicitly access something in the global namespace, prefix it with ::, as if the global namespace is a namespace with no name (e.g. ::MyType or ::MyNamespace::MyType).

Remove Primary Key in MySQL

Find the table in SQL manager right click it and select design, then right click the little key icon and select remove primary key.

m2eclipse not finding maven dependencies, artifacts not found

One of the reason I found was why it doesn't find a jar from repository might be because the .pom file for that particular jar might be missing or corrupt. Just correct it and try to load from local repository.

HTTP Status 504

I have had another issue giving me a 504. It's pretty far out but I'll write it up here for googlers and posterity...

I have a client calling an IIS hosted webservice hosted in another domain (Active Directory). There is not full trust between the client domain and the domain where the web services is hosted. One of the many challenges with the selective trust between these two domains is that Kerberos does not work when calling from one to the other.

In my case I was trying to call a service in another domain where I found out that a SPN was registered. Like this : http/myurl.test.local (just an example)

This forces the call to use Kerberos instead of letting it fall back to NTLM and this gave me a 405 back from the calling server.

After removing the spn and allowing the call to fall back to NTLM, it works fine.

As I said ... this is not something you are likely to run into, as most organizations do not venture into having such a selective trusts between two domains ... But it gives a 504 and caused me a few (more) gray hairs.

How do I get the current time zone of MySQL?

To anyone come to find timezone of mysql db.

With this query you can get current timezone :

mysql> SELECT @@system_time_zone as tz;
+-------+
|  tz   |
+-------+
|  CET  |
+-------+

How to show full height background image?

You can do it with the code you have, you just need to ensure that html and body are set to 100% height.

Demo: http://jsfiddle.net/kevinPHPkevin/a7eGN/

html, body {
    height:100%;
} 

body {
    background-color: white;
    background-image: url('http://www.canvaz.com/portrait/charcoal-1.jpg');
    background-size: auto 100%;
    background-repeat: no-repeat;
    background-position: left top;
}

Conditional WHERE clause with CASE statement in Oracle

You can write the where clause as:

where (case when (:stateCode = '') then (1)
            when (:stateCode != '') and (vw.state_cd in (:stateCode)) then 1
            else 0)
       end) = 1;

Alternatively, remove the case entirely:

where (:stateCode = '') or
      ((:stateCode != '') and vw.state_cd in (:stateCode));

Or, even better:

where (:stateCode = '') or vw.state_cd in (:stateCode)

Converting array to list in Java

Even shorter:

List<Integer> list = Arrays.asList(1, 2, 3, 4);

Check file extension in upload form in PHP

i think this might work for you

//<?php
    //checks file extension for images only
    $allowed =  array('gif','png' ,'jpg');
    $file = $_FILES['file']['name'];
    $ext = pathinfo($file, PATHINFO_EXTENSION);
        if(!in_array($ext,$allowed) ) 
            { 
//?>
<script>
       alert('file extension not allowed');
       window.location.href='some_link.php?file_type_not_allowed_error';
</script>

//<?php
exit(0);
    }
//?>

Get HTML source of WebElement in Selenium WebDriver using Python

It looks outdated, but let it be here anyway. The correct way to do it in your case:

elem = wd.find_element_by_css_selector('#my-id')
html = wd.execute_script("return arguments[0].innerHTML;", elem)

or

html = elem.get_attribute('innerHTML')

Both are working for me (selenium-server-standalone-2.35.0).

overlay a smaller image on a larger image python OpenCv

Based on fireant's excellent answer above, here is the alpha blending but a bit more human legible. You may need to swap 1.0-alpha and alpha depending on which direction you're merging (mine is swapped from fireant's answer).

o* == s_img.* b* == b_img.*

for c in range(0,3):
    alpha = s_img[oy:oy+height, ox:ox+width, 3] / 255.0
    color = s_img[oy:oy+height, ox:ox+width, c] * (1.0-alpha)
    beta  = l_img[by:by+height, bx:bx+width, c] * (alpha)

    l_img[by:by+height, bx:bx+width, c] = color + beta

How can I get the current date and time in the terminal and set a custom command in the terminal for it?

The command is date

To customise the output there are a myriad of options available, see date --help for a list.

For example, date '+%A %W %Y %X' gives Tuesday 34 2013 08:04:22 which is the name of the day of the week, the week number, the year and the time.

How to name and retrieve a stash by name in git?

use git stash push -m aNameForYourStash to save it. Then use git stash list to learn the index of the stash that you want to apply. Then use git stash pop --index 0 to pop the stash and apply it.

note: I'm using git version 2.21.0.windows.1

Android - Package Name convention

Com = commercial application (just like .com, most people register their app as a com app)
First level = always the publishing entity's' name
Second level (optional) = sub-devison, group, or project name
Final level = product name

For example he android launcher (home screen) is Com.Google.android.launcher

How to escape strings in SQL Server using PHP?

After struggling with this for hours, I've come up with a solution that feels almost the best.

Chaos' answer of converting values to hexstring doesn't work with every datatype, specifically with datetime columns.

I use PHP's PDO::quote(), but as it comes with PHP, PDO::quote() is not supported for MS SQL Server and returns FALSE. The solution for it to work was to download some Microsoft bundles:

After that you can connect in PHP with PDO using a DSN like the following example:

sqlsrv:Server=192.168.0.25; Database=My_Database;

Using the UID and PWD parameters in the DSN didn't worked, so username and password are passed as the second and third parameters on the PDO constructor when creating the connection. Now you can use PHP's PDO::quote(). Enjoy.

Getting the source of a specific image element with jQuery

If you do not specifically need the alt text of an image, then you can just target the class/id of the image.

$('img.propImg').each(function(){ 
     enter code here
}

I know it’s not quite answering the question, though I’d spent ages trying to figure this out and this question gave me the solution :). In my case I needed to hide any image tags with a specific src.

$('img.propImg').each(function(){ //for each loop that gets all the images. 
        if($(this).attr('src') == "img/{{images}}") { // if the src matches this
        $(this).css("display", "none") // hide the image.
    }
});

PHP Change Array Keys

You could create a new array containing that array, so:

<?php
$array = array();
$array['name'] = $oldArray;
?>

Angular - Set headers for every request

To answer, you question you could provide a service that wraps the original Http object from Angular. Something like described below.

import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';

@Injectable()
export class HttpClient {

  constructor(private http: Http) {}

  createAuthorizationHeader(headers: Headers) {
    headers.append('Authorization', 'Basic ' +
      btoa('username:password')); 
  }

  get(url) {
    let headers = new Headers();
    this.createAuthorizationHeader(headers);
    return this.http.get(url, {
      headers: headers
    });
  }

  post(url, data) {
    let headers = new Headers();
    this.createAuthorizationHeader(headers);
    return this.http.post(url, data, {
      headers: headers
    });
  }
}

And instead of injecting the Http object you could inject this one (HttpClient).

import { HttpClient } from './http-client';

export class MyComponent {
  // Notice we inject "our" HttpClient here, naming it Http so it's easier
  constructor(http: HttpClient) {
    this.http = httpClient;
  }

  handleSomething() {
    this.http.post(url, data).subscribe(result => {
        // console.log( result );
    });
  }
}

I also think that something could be done using multi providers for the Http class by providing your own class extending the Http one... See this link: http://blog.thoughtram.io/angular2/2015/11/23/multi-providers-in-angular-2.html.

Find object by its property in array of objects with AngularJS way

you can use angular's filter https://docs.angularjs.org/api/ng/filter/filter

in your controller:

$filter('filter')(myArray, {'id':73}) 

or in your HTML

{{ myArray | filter : {'id':73} }}

Run Bash Command from PHP

You probably need to chdir to the correct directory before calling the script. This way you can ensure what directory your script is "in" before calling the shell command.

$old_path = getcwd();
chdir('/my/path/');
$output = shell_exec('./script.sh var1 var2');
chdir($old_path);

Is there a way to @Autowire a bean that requires constructor arguments?

You need the @Value annotation.

A common use case is to assign default field values using "#{systemProperties.myProp}" style expressions.

public class SimpleMovieLister {

  private MovieFinder movieFinder;
  private String defaultLocale;

  @Autowired
  public void configure(MovieFinder movieFinder, 
                        @Value("#{ systemProperties['user.region'] }") String defaultLocale) {
      this.movieFinder = movieFinder;
      this.defaultLocale = defaultLocale;
  }

  // ...
}

See: Expression Language > Annotation Configuration


To be more clear: in your scenario, you'd wire two classes, MybeanService and MyConstructorClass, something like this:

@Component
public class MyBeanService implements BeanService{
    @Autowired
    public MybeanService(MyConstructorClass foo){
        // do something with foo
    }
}

@Component
public class MyConstructorClass{
    public MyConstructorClass(@Value("#{some expression here}") String value){
         // do something with value
    }
}

Update: if you need several different instances of MyConstructorClass with different values, you should use Qualifier annotations

Best way to get all selected checkboxes VALUES in jQuery

You want the :checkbox:checked selector and map to create an array of the values:

var checkedValues = $('input:checkbox:checked').map(function() {
    return this.value;
}).get();

If your checkboxes have a shared class it would be faster to use that instead, eg. $('.mycheckboxes:checked'), or for a common name $('input[name="Foo"]:checked')

- Update -

If you don't need IE support then you can now make the map() call more succinct by using an arrow function:

var checkedValues = $('input:checkbox:checked').map((i, el) => el.value).get();

pandas DataFrame: replace nan values with average of columns

using sklearn library preprocessing class

from sklearn.impute import SimpleImputer
missingvalues = SimpleImputer(missing_values = np.nan, strategy = 'mean', axis = 0)
missingvalues = missingvalues.fit(x[:,1:3])
x[:,1:3] = missingvalues.transform(x[:,1:3])

Note: In the recent version parameter missing_values value change to np.nan from NaN

VB.NET - Remove a characters from a String

The string class's Replace method can also be used to remove multiple characters from a string:

Dim newstring As String
newstring = oldstring.Replace(",", "").Replace(";", "")

How to recursively list all the files in a directory in C#?

To avoid the UnauthorizedAccessException, I use:

var files = GetFiles(@"C:\", "*.*", SearchOption.AllDirectories);
foreach (var file in files)
{
    Console.WriteLine($"{file}");
}

public static IEnumerable<string> GetFiles(string path, string searchPattern, SearchOption searchOption)
{
    var foldersToProcess = new List<string>()
    {
        path
    };

    while (foldersToProcess.Count > 0)
    {
        string folder = foldersToProcess[0];
        foldersToProcess.RemoveAt(0);

        if (searchOption.HasFlag(SearchOption.AllDirectories))
        {
            //get subfolders
            try
            {
                var subfolders = Directory.GetDirectories(folder);
                foldersToProcess.AddRange(subfolders);
            }
            catch (Exception ex)
            {
                //log if you're interested
            }
        }

        //get files
        var files = new List<string>();
        try
        {
            files = Directory.GetFiles(folder, searchPattern, SearchOption.TopDirectoryOnly).ToList();
        }
        catch (Exception ex)
        {
            //log if you're interested
        }

        foreach (var file in files)
        {
            yield return file;
        }
    }
}

Angular 2 router no base href set

Since 2.0 beta :)

import { APP_BASE_HREF } from 'angular2/platform/common';

KeyListener, keyPressed versus keyTyped

You should use keyPressed if you want an immediate effect, and keyReleased if you want the effect after you release the key. You cannot use keyTyped because F5 is not a character. keyTyped is activated only when an character is pressed.

How to stop an app on Heroku?

1> Yes... There is pencil icon when we go to Personal==> <app name> ==>Resources then click on Pencil Icon and drag to left side and Dynos will go down.

2> You can validate using Heroku cli

heroku logs --app {your-appname}

it worked for me.

counting the number of lines in a text file

In C if you implement count line it will never fail. Yes you can get one extra line if there is stray "ENTER KEY" generally at the end of the file.

File might look some thing like this:

"hello 1
"Hello 2

"

Code below

#include <stdio.h>
#include <stdlib.h>
#define FILE_NAME "file1.txt"

int main() {

    FILE *fd = NULL;
    int cnt, ch;

    fd = fopen(FILE_NAME,"r");
    if (fd == NULL) {
            perror(FILE_NAME);
            exit(-1);
    }

    while(EOF != (ch = fgetc(fd))) {
    /*
     * int fgetc(FILE *) returns unsigned char cast to int
     * Because it has to return EOF or error also.
     */
            if (ch == '\n')
                    ++cnt;
    }

    printf("cnt line in %s is %d\n", FILE_NAME, cnt);

    fclose(fd);
    return 0;
}

Calculate the number of business days between two dates?

I believe this could be a simpler way:

    public int BusinessDaysUntil(DateTime start, DateTime end, params DateTime[] bankHolidays)
    {
        int tld = (int)((end - start).TotalDays) + 1; //including end day
        int not_buss_day = 2 * (tld / 7); //Saturday and Sunday
        int rest = tld % 7; //rest.

        if (rest > 0)
        {
            int tmp = (int)start.DayOfWeek - 1 + rest;
            if (tmp == 6 || start.DayOfWeek == DayOfWeek.Sunday) not_buss_day++; else if (tmp > 6) not_buss_day += 2;
        }

        foreach (DateTime bankHoliday in bankHolidays)
        {
            DateTime bh = bankHoliday.Date;
            if (!(bh.DayOfWeek == DayOfWeek.Saturday || bh.DayOfWeek == DayOfWeek.Sunday) && (start <= bh && bh <= end))
            {
                not_buss_day++;
            }
        }
        return tld - not_buss_day;
    }

How do I set default values for functions parameters in Matlab?

This is more or less lifted from the Matlab manual; I've only got passing experience...

function my_output = wave ( a, b, n, k, T, f, flag, varargin )
  optargin = numel(varargin);
  fTrue = inline('0');
  if optargin > 0
    fTrue = varargin{1};
  end
  % code ...
end

Qt - reading from a text file

You have to replace string line

QString line = in.readLine();

into while:

QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::ReadOnly)) {
    QMessageBox::information(0, "error", file.errorString());
}

QTextStream in(&file);

while(!in.atEnd()) {
    QString line = in.readLine();    
    QStringList fields = line.split(",");    
    model->appendRow(fields);    
}

file.close();

Java 6 Unsupported major.minor version 51.0

According to maven website, the last version to support Java 6 is 3.2.5, and 3.3 and up use Java 7. My hunch is that you're using Maven 3.3 or higher, and should either upgrade to Java 7 (and set proper source/target attributes in your pom) or downgrade maven.

How to manually trigger validation with jQuery validate?

That library seems to allow validation for single elements. Just associate a click event to your button and try the following:

$("#myform").validate().element("#i1");

Examples here:

https://jqueryvalidation.org/Validator.element

Difference between dates in JavaScript

Date.prototype.addDays = function(days) {

   var dat = new Date(this.valueOf())
   dat.setDate(dat.getDate() + days);
   return dat;
}

function getDates(startDate, stopDate) {

  var dateArray = new Array();
  var currentDate = startDate;
  while (currentDate <= stopDate) {
    dateArray.push(currentDate);
    currentDate = currentDate.addDays(1);
  }
  return dateArray;
}

var dateArray = getDates(new Date(), (new Date().addDays(7)));

for (i = 0; i < dateArray.length; i ++ ) {
  //  alert (dateArray[i]);

    date=('0'+dateArray[i].getDate()).slice(-2);
    month=('0' +(dateArray[i].getMonth()+1)).slice(-2);
    year=dateArray[i].getFullYear();
    alert(date+"-"+month+"-"+year );
}

How to use Spring Boot with MySQL database and JPA?

When moving classes into specific packages like repository, controller, domain just the generic @SpringBootApplication is not enough.

You will have to specify the base package for component scan

@ComponentScan("base_package")

For JPA

@EnableJpaRepositories(basePackages = "repository")

is also needed, so spring data will know where to look into for repository interfaces.

How to print a dictionary's key?

dict = {'name' : 'Fred', 'age' : 100, 'employed' : True }

# Choose key to print (could be a user input)
x = 'name'

if x in dict.keys():
    print(x)

How do you get the contextPath from JavaScript, the right way?

I think you can achieve what you are looking for by combining number 1 with calling a function like in number 3.

You don't want to execute scripts on page load and prefer to call a function later on? Fine, just create a function that returns the value you would have set in a variable:

function getContextPath() {
   return "<%=request.getContextPath()%>";
}

It's a function so it wont be executed until you actually call it, but it returns the value directly, without a need to do DOM traversals or tinkering with URLs.

At this point I agree with @BalusC to use EL:

function getContextPath() {
   return "${pageContext.request.contextPath}";
}

or depending on the version of JSP fallback to JSTL:

function getContextPath() {
   return "<c:out value="${pageContext.request.contextPath}" />";
}

ORA-28000: the account is locked error getting frequently

I have faced this similar issue and resolved it by using following steps :

  1. Open windows command prompt.
  2. Login using the command sqlplus "/ as sysdba"
  3. Then executed the command alter user HR identified by password account unlock

    Please note, the password is the password that I have used.

    By using above steps you can connect to Oracle Database as user HR with the password password.

Android: making a fullscreen application

In onCreate call

requestWindowFeature(Window.FEATURE_NO_TITLE); // for hiding title

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
                            WindowManager.LayoutParams.FLAG_FULLSCREEN);

How to write a cursor inside a stored procedure in SQL Server 2008

You can create a trigger which updates NoofUses column in Coupon table whenever couponid is used in CouponUse table

query :

CREATE TRIGGER [dbo].[couponcount] ON [dbo].[couponuse]
FOR INSERT
AS
if EXISTS (SELECT 1 FROM Inserted)
  BEGIN
UPDATE dbo.Coupon
SET NoofUses = (SELECT COUNT(*) FROM dbo.CouponUse WHERE Couponid = dbo.Coupon.ID)
end 

iOS 7: UITableView shows under status bar

For those like me who would rather not embed their UITableViewController in a UIViewController try this:

A custom UITableViewController subclass can append a mask view to the tableView's superview. Add the mask on viewDidAppear, and remove the mask on viewWillDisappear.

private var statusBarMaskView: UIView!

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    if let superview = self.tableView.superview {
        self.statusBarMaskView = UIView(frame: CGRect.zero)
        superview.insertSubview(self.statusBarMaskView, aboveSubview: self.tableView)
        self.statusBarMaskView.backgroundColor = self.tableView.backgroundColor

        // using a nice constraint layout library to set the frame
        self.statusBarMaskView.pinTop(to: superview)
        self.statusBarMaskView.pinLeft(to: superview)
        self.statusBarMaskView.pinRight(to: superview)
        self.statusBarMaskView.addHeightConstraint(with: 22.0)
        ////
    }
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    self.statusBarMaskView.removeFromSuperview()
    self.statusBarMaskView = nil
}

Querying data by joining two tables in two database on different servers

for this simply follow below query

select a.Id,a.type,b.Name,b.City from DatabaseName.dbo.TableName a left join DatabaseName.dbo.TableName b on a.Id=b.Id

Where I wrote databasename, you have to define the name of the database. If you are in same database so you don't need to define the database name but if you are in other database you have to mention database name as path or it will show you error. Hope I made your work easy

How can I get the size of an std::vector as an int?

In the first two cases, you simply forgot to actually call the member function (!, it's not a value) std::vector<int>::size like this:

#include <vector>

int main () {
    std::vector<int> v;
    auto size = v.size();
}

Your third call

int size = v.size();

triggers a warning, as not every return value of that function (usually a 64 bit unsigned int) can be represented as a 32 bit signed int.

int size = static_cast<int>(v.size());

would always compile cleanly and also explicitly states that your conversion from std::vector::size_type to int was intended.

Note that if the size of the vector is greater than the biggest number an int can represent, size will contain an implementation defined (de facto garbage) value.

Delete all duplicate rows Excel vba

There's a RemoveDuplicates method that you could use:

Sub DeleteRows()

    With ActiveSheet
        Set Rng = Range("A1", Range("B1").End(xlDown))
        Rng.RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
    End With

End Sub

HTTP GET with request body

IMHO you could just send the JSON encoded (ie. encodeURIComponent) in the URL, this way you do not violate the HTTP specs and get your JSON to the server.

Is calculating an MD5 hash less CPU intensive than SHA family functions?

MD5 also benefits from SSE2 usage, check out BarsWF and then tell me that it doesn't. All it takes is a little assembler knowledge and you can craft your own MD5 SSE2 routine(s). For large amounts of throughput however, there is a tradeoff of the speed during hashing as opposed to the time spent rearranging the input data to be compatible with the SIMD instructions used.

How to find good looking font color if background color is known?

Similar to @Aaron Digulla's suggestion except that I would suggest a graphics design tool, select the base color, in your case the background color, then adjust the Hue, Saturation and Value. Using this you can create color swatches very easily. Paint.Net is free and I use it all the time for this and also the pay-for-tools will also do this.

How can foreign key constraints be temporarily disabled using T-SQL?

If you want to disable all constraints in the database just run this code:

-- disable all constraints
EXEC sp_MSforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"

To switch them back on, run: (the print is optional of course and it is just listing the tables)

-- enable all constraints
exec sp_MSforeachtable @command1="print '?'", @command2="ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

I find it useful when populating data from one database to another. It is much better approach than dropping constraints. As you mentioned it comes handy when dropping all the data in the database and repopulating it (say in test environment).

If you are deleting all the data you may find this solution to be helpful.

Also sometimes it is handy to disable all triggers as well, you can see the complete solution here.

jQuery or JavaScript auto click

$(document).ready(function(){ 
  $('#some-id').trigger('click'); 
});

did the trick.

Inserting HTML into a div

As alternative you can use insertAdjacentHTML - however I dig into and make some performance tests - (2019.09.13 Friday) MacOs High Sierra 10.13.6 on Chrome 76.0.3809 (64-bit), Safari 12.1.2 (13604.5.6), Firefox 69.0.0 (64-bit) ). The test F is only for reference - it is out of the question scope because we need to insert dynamically html - but in F I do it by 'hand' (in static way) - theoretically (as far I know) this should be the fastest way to insert new html elements.

enter image description here

SUMMARY

  • The A innerHTML = (do not confuse with +=) is fastest (Safari 48k operations per second, Firefox 43k op/sec, Chrome 23k op/sec) The A is ~31% slower than ideal solution F only chrome but on safari and firefox is faster (!)
  • The B innerHTML +=... is slowest on all browsers (Chrome 95 op/sec, Firefox 88 op/sec, Sfari 84 op/sec)
  • The D jQuery is second slow on all browsers (Safari 14 op/sec, Firefox 11k op/sec, Chrome 7k op/sec)
  • The reference solution F (theoretically fastest) is not fastest on firefox and safari (!!!) - which is surprising
  • The fastest browser was Safari

More info about why innerHTML = is much faster than innerHTML += is here. You can perform test on your machine/browser HERE

_x000D_
_x000D_
let html = "<div class='box'>Hello <span class='msg'>World</span> !!!</div>"_x000D_
_x000D_
function A() {    _x000D_
  container.innerHTML = `<div id="A_oiio">A: ${html}</div>`;_x000D_
}_x000D_
_x000D_
function B() {    _x000D_
  container.innerHTML += `<div id="B_oiio">B: ${html}</div>`;_x000D_
}_x000D_
_x000D_
function C() {    _x000D_
  container.insertAdjacentHTML('beforeend', `<div id="C_oiio">C: ${html}</div>`);_x000D_
}_x000D_
_x000D_
function D() {    _x000D_
  $('#container').append(`<div id="D_oiio">D: ${html}</div>`);_x000D_
}_x000D_
_x000D_
function E() {_x000D_
  let d = document.createElement("div");_x000D_
  d.innerHTML = `E: ${html}`;_x000D_
  d.id = 'E_oiio';_x000D_
  container.appendChild(d);_x000D_
}_x000D_
_x000D_
function F() {    _x000D_
  let dm = document.createElement("div");_x000D_
  dm.id = "F_oiio";_x000D_
  dm.appendChild(document.createTextNode("F: "));_x000D_
_x000D_
  let d = document.createElement("div");_x000D_
  d.classList.add('box');_x000D_
  d.appendChild(document.createTextNode("Hello "));_x000D_
  _x000D_
  let s = document.createElement("span");_x000D_
  s.classList.add('msg');_x000D_
  s.appendChild(document.createTextNode("World"));_x000D_
_x000D_
  d.appendChild(s);_x000D_
  d.appendChild(document.createTextNode(" !!!"));_x000D_
  dm.appendChild( d );_x000D_
  _x000D_
  container.appendChild(dm);_x000D_
}_x000D_
_x000D_
_x000D_
A();_x000D_
B();_x000D_
C();_x000D_
D();_x000D_
E();_x000D_
F();
_x000D_
.warr { color: red } .msg { color: blue } .box {display: inline}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="warr">This snippet only for show code used in test (in jsperf.com) - it not perform test itself. </div>_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

Correct use for angular-translate in controllers

Recommended: don't translate in the controller, translate in your view

I'd recommend to keep your controller free from translation logic and translate your strings directly inside your view like this:

<h1>{{ 'TITLE.HELLO_WORLD' | translate }}</h1>

Using the provided service

Angular Translate provides the $translate service which you can use in your Controllers.

An example usage of the $translate service can be:

.controller('TranslateMe', ['$scope', '$translate', function ($scope, $translate) {
    $translate('PAGE.TITLE')
        .then(function (translatedValue) {
            $scope.pageTitle = translatedValue;
        });
});

The translate service also has a method for directly translating strings without the need to handle a promise, using $translate.instant():

.controller('TranslateMe', ['$scope', '$translate', function ($scope, $translate) {
    $scope.pageTitle = $translate.instant('TITLE.DASHBOARD'); // Assuming TITLE.DASHBOARD is defined
});

The downside with using $translate.instant() could be that the language file isn't loaded yet if you are loading it async.

Using the provided filter

This is my preferred way since I don't have to handle promises this way. The output of the filter can be directly set to a scope variable.

.controller('TranslateMe', ['$scope', '$filter', function ($scope, $filter) {
    var $translate = $filter('translate');

    $scope.pageTitle = $translate('TITLE.DASHBOARD'); // Assuming TITLE.DASHBOARD is defined
});

Using the provided directive

Since @PascalPrecht is the creator of this awesome library, I'd recommend going with his advise (see his answer below) and use the provided directive which seems to handle translations very intelligent.

The directive takes care of asynchronous execution and is also clever enough to unwatch translation ids on the scope if the translation has no dynamic values.

PHP MySQL Google Chart JSON - Complete Example

use this, it realy works:

data.addColumn no of your key, you can add more columns or remove

<?php
$con=mysql_connect("localhost","USername","Password") or die("Failed to connect with database!!!!");
mysql_select_db("Database Name", $con); 
// The Chart table contain two fields: Weekly_task and percentage
//this example will display a pie chart.if u need other charts such as Bar chart, u will need to change little bit to make work with bar chart and others charts
$sth = mysql_query("SELECT * FROM chart");

while($r = mysql_fetch_assoc($sth)) {
$arr2=array_keys($r);
$arr1=array_values($r);

}

for($i=0;$i<count($arr1);$i++)
{
    $chart_array[$i]=array((string)$arr2[$i],intval($arr1[$i]));
}
echo "<pre>";
$data=json_encode($chart_array);
?>

<html>
  <head>
    <!--Load the AJAX API-->
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript">

    // Load the Visualization API and the piechart package.
    google.load('visualization', '1', {'packages':['corechart']});

    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawChart);

    function drawChart() {

      // Create our data table out of JSON data loaded from server.
     var data = new google.visualization.DataTable();
        data.addColumn("string", "YEAR");
        data.addColumn("number", "NO of record");

        data.addRows(<?php $data ?>);

        ]); 
      var options = {
           title: 'My Weekly Plan',
          is3D: 'true',
          width: 800,
          height: 600
        };
      // Instantiate and draw our chart, passing in some options.
      //do not forget to check ur div ID
      var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }
    </script>
  </head>

  <body>
    <!--Div that will hold the pie chart-->
    <div id="chart_div"></div>
  </body>
</html>

create unique id with javascript

    const generateUniqueId = () => 'id_' + Date.now() + String(Math.random()).substr(2);

    // if u want to check for collision
    const arr = [];
    const checkForCollision = () => {
      for (let i = 0; i < 10000; i++) {
        const el = generateUniqueId();
        if (arr.indexOf(el) > -1) {
          alert('COLLISION FOUND');
        }
        arr.push(el);
      }
    };

How do you get total amount of RAM the computer has?

If you happen to be using Mono, then you might be interested to know that Mono 2.8 (to be released later this year) will have a performance counter which reports the physical memory size on all the platforms Mono runs on (including Windows). You would retrieve the value of the counter using this code snippet:

using System;
using System.Diagnostics;

class app
{
   static void Main ()
   {
       var pc = new PerformanceCounter ("Mono Memory", "Total Physical Memory");
       Console.WriteLine ("Physical RAM (bytes): {0}", pc.RawValue);
   }
}

If you are interested in C code which provides the performance counter, it can be found here.

What is the best Java library to use for HTTP POST, GET etc.?

imho: Apache HTTP Client

usage example:

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.*;

public class HttpClientTutorial {

  private static String url = "http://www.apache.org/";

  public static void main(String[] args) {
    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    // Create a method instance.
    GetMethod method = new GetMethod(url);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
            new DefaultHttpMethodRetryHandler(3, false));

    try {
      // Execute the method.
      int statusCode = client.executeMethod(method);

      if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + method.getStatusLine());
      }

      // Read the response body.
      byte[] responseBody = method.getResponseBody();

      // Deal with the response.
      // Use caution: ensure correct character encoding and is not binary data
      System.out.println(new String(responseBody));

    } catch (HttpException e) {
      System.err.println("Fatal protocol violation: " + e.getMessage());
      e.printStackTrace();
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    } finally {
      // Release the connection.
      method.releaseConnection();
    }  
  }
}

some highlight features:

  • Standards based, pure Java, implementation of HTTP versions 1.0 and 1.1
    • Full implementation of all HTTP methods (GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE) in an extensible OO framework.
    • Supports encryption with HTTPS (HTTP over SSL) protocol.
    • Granular non-standards configuration and tracking.
    • Transparent connections through HTTP proxies.
    • Tunneled HTTPS connections through HTTP proxies, via the CONNECT method.
    • Transparent connections through SOCKS proxies (version 4 & 5) using native Java socket support.
    • Authentication using Basic, Digest and the encrypting NTLM (NT Lan Manager) methods.
    • Plug-in mechanism for custom authentication methods.
    • Multi-Part form POST for uploading large files.
    • Pluggable secure sockets implementations, making it easier to use third party solutions
    • Connection management support for use in multi-threaded applications. Supports setting the maximum total connections as well as the maximum connections per host. Detects and closes stale connections.
    • Automatic Cookie handling for reading Set-Cookie: headers from the server and sending them back out in a Cookie: header when appropriate.
    • Plug-in mechanism for custom cookie policies.
    • Request output streams to avoid buffering any content body by streaming directly to the socket to the server.
    • Response input streams to efficiently read the response body by streaming directly from the socket to the server.
    • Persistent connections using KeepAlive in HTTP/1.0 and persistance in HTTP/1.1
    • Direct access to the response code and headers sent by the server.
    • The ability to set connection timeouts.
    • HttpMethods implement the Command Pattern to allow for parallel requests and efficient re-use of connections.
    • Source code is freely available under the Apache Software License.

Print a div content using Jquery

None of the solutions above work perfectly.They either loses CSS or have to include/edit external CSS file. I found a perfect solution that will not lose your CSS nor you have to edit/add external CSS.

HTML:

<div id='printarea'>
    <p>This is a sample text for printing purpose.</p>
    <input type='button' id='btn' value='Print' onclick='printFunc();'>
</div>
<p>Do not print.</p

JQuery:

function printFunc() {
    var divToPrint = document.getElementById('printarea');
    var htmlToPrint = '' +
        '<style type="text/css">' +
        'table th, table td {' +
        'border:1px solid #000;' +
        'padding;0.5em;' +
        '}' +
        '</style>';
    htmlToPrint += divToPrint.outerHTML;
    newWin = window.open("");
    newWin.document.write("<h3 align='center'>Print Page</h3>");
    newWin.document.write(htmlToPrint);
    newWin.print();
    newWin.close();
    }

Read all contacts' phone numbers in android

In the same way just get their other numbers using the other "People" references

People.TYPE_HOME
People.TYPE_MOBILE
People.TYPE_OTHER
People.TYPE_WORK

What is the proper way to check and uncheck a checkbox in HTML5?

<form name="myForm" method="post">
  <p>Activity</p> 
  skiing:  <input type="checkbox" name="activity" value="skiing"  checked="yes" /><br /> 
  skating: <input type="checkbox" name="activity" value="skating" /><br /> 
  running: <input type="checkbox" name="activity" value="running" /><br /> 
  hiking:  <input type="checkbox" name="activity" value="hiking"  checked="yes" />
</form>

how to check confirm password field in form without reloading page

WITHOUT clicking the button you will have to listen to the change event of the input fields

var confirmField = document.getElementById("confirm_password");
var passwordField = document.getElementById("password");

function checkPasswordMatch(){
    var status = document.getElementById("password_status");
    var submit = document.getElementById("submit");

    status.innerHTML = "";
    submit.removeAttribute("disabled");

    if(confirmField.value === "")
        return;

    if(passwordField.value === confirmField.value)
        return;

    status.innerHTML = "Passwords don't match";
    submit.setAttribute("disabled", "disabled");
}

passWordField.addEventListener("change", function(event){
    checkPasswordMatch();
});
confirmField.addEventListener("change", function(event){
    checkPasswordMatch();
});

then add the status element to your html:

<p id="password_status"></p>

and set the submit button id to submit

... id="submit" />

hope this helps you

How to get the list of all database users

I try to avoid using the "SELECT * " option and just pull what data I want or need. The code below is what I use, you may cull out or add columns and aliases per your needs.

I also us "IIF" (instant if) to replace binary 0 or 1 with a yes or no. It just makes it easier to read for the non-techie that may want this info.

Here is what I use:

SELECT 
    name AS 'User'
  , PRINCIPAL_ID
  , type AS 'User Type'
  , type_desc AS 'Login Type'
  , CAST(create_date AS DATE) AS 'Date Created' 
  , default_database_name AS 'Database Name'
  , IIF(is_fixed_role LIKE 0, 'No', 'Yes') AS 'Is Active'
FROM master.sys.server_principals
WHERE type LIKE 's' OR type LIKE 'u'
ORDER BY [User], [Database Name]; 
GO

Hope this helps.

GridLayout (not GridView) how to stretch all children evenly

Here is what I did and I'm happy to say that this worked for me. I too wanted a 2x2, 3x3 etc. grid of items to cover the entire screen. Gridlayouts do not adhere to the width of the screen. LinearLayouts kind of work but you cant use nested weights.

The best option for me was to use Fragments I used this tutorial to get started with what I wanted to do.

Here is some code:

Main Activity:

public class GridHolderActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main_6);
    }
}

activity_main_6 XML (inflates 3 fragments)

<?xml version="1.0" encoding="utf-8"?>

<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:orientation="vertical">

    <fragment
        android:id="@+id/frag1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:name=".TwoHorizontalGridFragment"
        tools:layout="@layout/two_horiz" />
    <fragment
        android:id="@+id/frag2"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:name=".TwoHorizontalGridFragment"
        tools:layout="@layout/two_horiz" />
    <fragment
        android:id="@+id/frag3"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:name=".Grid.TwoHorizontalGridFragment"
        tools:layout="@layout/two_horiz" />

Base fragment layout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:layout_gravity="center"
    android:layout_height="match_parent">

    <ImageQueue
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/img1"
        android:layout_weight="1"/>


    <ImageQueue
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/img2"
        android:layout_weight="1"/>
</LinearLayout>

Fragment Class (only handles initialization of a custom view) inflates 2 tiles per fragment

public class TwoHorizontalGridFragment extends Fragment {
private View rootView;

private ImageQueue imageQueue1;
private ImageQueue imageQueue2;

@Override
public View onCreateView(LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {
    /**
     * Inflate the layout for this fragment
     */
    rootView = inflater.inflate(
            R.layout.two_horiz, container, false);
    return rootView;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    imageQueue1 = (ImageQueue)rootView.findViewById(R.id.img1);
    imageQueue2 = (ImageQueue)rootView.findViewById(R.id.img2);
    imageQueue1.updateFiles();
    imageQueue2.updateFiles();
}

}

Thats it!

This is a weird work around to using nested weights, essentially. It gives me a perfect 2x3 grid that fills the entire screen of both my 10 inch tablet and my HTC droid DNA. Let me know how it goes for you!

Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED

Your connection to redis is failing. Try restarting your redis server, then starting up your client again by running these 3 commands:

sudo service redis-server restart
redis-server
redis-cli

private final static attribute vs private final attribute

Here is my two cents:

final           String CENT_1 = new Random().nextInt(2) == 0 ? "HEADS" : "TAILS";
final   static  String CENT_2 = new Random().nextInt(2) == 0 ? "HEADS" : "TAILS";

Example:

package test;

public class Test {

    final long OBJECT_ID = new Random().nextLong();
    final static long CLASSS_ID = new Random().nextLong();

    public static void main(String[] args) {
        Test[] test = new Test[5];
        for (int i = 0; i < test.length; i++){
            test[i] = new Test();
            System.out.println("Class id: "+test[i].CLASSS_ID);//<- Always the same value
            System.out.println("Object id: "+test[i].OBJECT_ID);//<- Always different
        }
    }
}

The key is that variables and functions can return different values.Therefore final variables can be assigned with different values.

Regex: Use start of line/end of line signs (^ or $) in different context

you just need to use word boundary (\b) instead of ^ and $:

\bgarp\b

I don't understand -Wl,-rpath -Wl,

You could also write

-Wl,-rpath=.

To get rid of that pesky space. It's arguably more readable than adding extra commas (it's exactly what gets passed to ld).

Get UTC time in seconds

You say you're using:

time.asctime(time.localtime(date_in_seconds_from_bash))

where date_in_seconds_from_bash is presumably the output of date +%s.

The time.localtime function, as the name implies, gives you local time.

If you want UTC, use time.gmtime() rather than time.localtime().

As JamesNoonan33's answer says, the output of date +%s is timezone invariant, so date +%s is exactly equivalent to date -u %s. It prints the number of seconds since the "epoch", which is 1970-01-01 00:00:00 UTC. The output you show in your question is entirely consistent with that:

date -u
Thu Jul 3 07:28:20 UTC 2014

date +%s
1404372514   # 14 seconds after "date -u" command

date -u +%s
1404372515   # 15 seconds after "date -u" command

How do I specify different layouts for portrait and landscape orientations?

The last line below is an example for applying two quantifiers: landscape and smallest width(600dp) screen. Update 600dp with the ones you need.

res/layout/main_activity.xml                # For handsets
res/layout-land/main_activity.xml           # For handsets in landscape
res/layout-sw600dp/main_activity.xml        # For 7” tablets
res/layout-sw600dp-land/main_activity.xml   # For 7” tablets in landscape

The above applies to dimens as well

res/values/dimens.xml                # For handsets
res/values-land/dimens.xml           # For handsets in landscape
res/values-sw600dp/dimens.xml        # For 7” tablets
res/values-sw600dp-land/dimens.xml   # For 7” tablets in landscape

A useful device metrics: https://material.io/tools/devices/

Removing duplicates from a String in Java

You can't. You can create a new String that has duplicates removed. Why aren't you using StringBuilder (or StringBuffer, presumably)?

You can run through the string and store the unique characters in a char[] array, keeping track of how many unique characters you've seen. Then you can create a new String using the String(char[], int, int) constructor.

Also, the problem is a little ambiguous—does “duplicates” mean adjacent repetitions? (In other words, what should happen with abcab?)

How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

PHP Double Equals == :

In most programming languages, the comparison operator (==) checks, on the one hand, the data type and on the other hand the content of the variable for equality. The standard comparison operator (==) in PHP behaves differently. This tries to convert both variables into the same data type before the comparison and only then checks whether the content of these variables is the same. The following results are obtained:

<?php
    var_dump( 1 == 1 );     // true
    var_dump( 1 == '1' );   // true
    var_dump( 1 == 2 );     // false
    var_dump( 1 == '2' );   // false
    var_dump( 1 == true );  // true
    var_dump( 1 == false ); // false
?>

PHP Triple Equals === :

This operator also checks the datatype of the variable and returns (bool)true only if both variables have the same content and the same datatype. The following would therefore be correct:

<?php
    var_dump( 1 === 1 );     // true
    var_dump( 1 === '1' );   // false
    var_dump( 1 === 2 );     // false
    var_dump( 1 === '2' );   // false
    var_dump( 1 === true );  // false
    var_dump( 1 === false ); // false
?>

Read more in What is the difference between == and === in PHP

"ImportError: No module named" when trying to run Python script

This answer applies to this question if

  1. You don't want to change your code
  2. You don't want to change PYTHONPATH permanently

Temporarily modify PYTHONPATH

path below can be relative

PYTHONPATH=/path/to/dir python script.py

unable to start mongodb local server

Sat Jun 25 09:38:51 [initandlisten] listen(): bind() failed errno:98 Address already in use for socket: 0.0.0.0:27017

is self-speaking.

Another instance of mongod is already running and allocating the MongoDB default port which is 27017.

Either kill the other process or use a different port.

INSTALL_FAILED_USER_RESTRICTED : android studio using redmi 4 device

If above answer didn't work for you as it didn't work for me on my Xiaomi Mi5.I tried to figure out the Core reason behind it and solve it. In MIUI, in order to change "Install via USB" option, you must be connected to the internet and signed in your Mi account. Due to some reason, requests from out of the China servers are getting rejected, so I connected to one open China VPN and tried again to enable 'Install via USB' and I got success. For detailed solution and VPN details, see this useful Youtube video: https://youtu.be/MeKUJlD-Ke4

Setting the Vim background colors

In a terminal emulator like konsole or gnome-terminal, you should to set a 256 color setting for vim.

:set  t_Co=256

After that you can to change your background.

How do I clone a generic List in Java?

ArrayList first = new ArrayList ();
ArrayList copy = (ArrayList) first.clone ();

How to validate array in Laravel?

You have to loop over the input array and add rules for each input as described here: Loop Over Rules

Here is a some code for ya:

$input = Request::all();
$rules = [];

foreach($input['name'] as $key => $val)
{
    $rules['name.'.$key] = 'required|distinct|min:3';
}

$rules['amount'] = 'required|integer|min:1';
$rules['description'] = 'required|string';

$validator = Validator::make($input, $rules);

//Now check validation:
if ($validator->fails()) 
{ 
  /* do something */ 
}

File path issues in R using Windows ("Hex digits in character string" error)

I know this is really old, but if you are copying and pasting anyway, you can just use:

read.csv(readClipboard())

readClipboard() escapes the back-slashes for you. Just remember to make sure the ".csv" is included in your copy, perhaps with this:

read.csv(paste0(readClipboard(),'.csv'))

And if you really want to minimize your typing you can use some functions:

setWD <- function(){
  setwd(readClipboard())
}


readCSV <- function(){
  return(readr::read_csv(paste0(readClipboard(),'.csv')))
} 

#copy directory path
setWD()

#copy file name
df <- readCSV()

How to convert datetime to integer in python

When converting datetime to integers one must keep in mind the tens, hundreds and thousands.... like "2018-11-03" must be like 20181103 in int for that you have to 2018*10000 + 100* 11 + 3

Similarly another example, "2018-11-03 10:02:05" must be like 20181103100205 in int

Explanatory Code

dt = datetime(2018,11,3,10,2,5)
print (dt)

#print (dt.timestamp()) # unix representation ... not useful when converting to int

print (dt.strftime("%Y-%m-%d"))
print (dt.year*10000 + dt.month* 100  + dt.day)
print (int(dt.strftime("%Y%m%d")))

print (dt.strftime("%Y-%m-%d %H:%M:%S"))
print (dt.year*10000000000 + dt.month* 100000000 +dt.day * 1000000 + dt.hour*10000  +  dt.minute*100 + dt.second)
print (int(dt.strftime("%Y%m%d%H%M%S")))

General Function

To avoid that doing manually use below function

def datetime_to_int(dt):
    return int(dt.strftime("%Y%m%d%H%M%S"))