Programs & Examples On #Jplayer

jPlayer is the completely free and open source (GPL/MIT) media library written in JavaScript.

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

How to diff a commit with its parent?

If you know how far back, you can try something like:

# Current branch vs. parent
git diff HEAD^ HEAD

# Current branch, diff between commits 2 and 3 times back
git diff HEAD~3 HEAD~2

Prior commits work something like this:

# Parent of HEAD
git show HEAD^1

# Grandparent
git show HEAD^2

There are a lot of ways you can specify commits:

# Great grandparent
git show HEAD~3

See this page for details.

ETag vs Header Expires

In my view, With Expire Header, server can tell the client when my data would be stale, while with Etag, server would check the etag value for client' each request.

Can I set max_retries for requests.request?

After struggling a bit with some of the answers here, I found a library called backoff that worked better for my situation. A basic example:

import backoff

@backoff.on_exception(
    backoff.expo,
    requests.exceptions.RequestException,
    max_tries=5,
    giveup=lambda e: e.response is not None and e.response.status_code < 500
)
def publish(self, data):
    r = requests.post(url, timeout=10, json=data)
    r.raise_for_status()

I'd still recommend giving the library's native functionality a shot, but if you run into any problems or need broader control, backoff is an option.

jQuery: print_r() display equivalent?

Look at this: http://phpjs.org/functions/index and find for print_r or use console.log() with firebug.

LIKE vs CONTAINS on SQL Server

Having run both queries on a SQL Server 2012 instance, I can confirm the first query was fastest in my case.

The query with the LIKE keyword showed a clustered index scan.

The CONTAINS also had a clustered index scan with additional operators for the full text match and a merge join.

Plan

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly

I got a solution after a long time in tutorials.

I followed the github tutorial on this link -> https://help.github.com/articles/error-permission-denied-publickey and I was able to connect in every step. But when I was trying to git push -u origin master I got this error:

Permission denied (publickey). fatal: Could not read from remote repository.

Please make sure you have the correct access rights

Thats how I`ve fixed it!! Go to the project directory using the Terminal and check it out

$git remote -v

You will get something like this:

origin  ssh://[email protected]/yourGithubUserName/yourRepo.git (fetch)
origin  ssh://[email protected]/yourGithubUserName/yourRepo.git (push)

If you are using anything different then [email protected], open the config file on git directory by typing the command:

vi .git/config

And configure the line

[remote "origin"]

url = ssh://[email protected]/yourGithubUserName/yourRepo.git

fetch = +refs/heads/*:refs/remotes/origin/

Java Compare Two List's object values?

First, implement the MyData.equals(Object o) and MyData.hashCode() methods. Once you implemented the equals method, you can iterate over the lists as follows:

if(ListA == null && ListB == null)
    return false;
if(ListA == null && ListB != null)
    return true;
if(ListA != null && ListB == null)
    return true;
int max = ListA.size() > ListB.size() ? ListA.size() : ListB.size();
for(int i = 0; i < max; i++) {
    myData1 = ListA.get(i);
    myData2 = ListB.get(i);
    if(!myData1.equals(myData2)) {
        return true;
    }
}
return false;

How to consume a SOAP web service in Java

I will use CXF also you can think of AXIS 2 .

The best way to do it may be using JAX RS Refer this example

Example:

wsimport -p stockquote http://stockquote.xyz/quote?wsdl

This will generate the Java artifacts and compile them by importing the http://stockquote.xyz/quote?wsdl.

I

What is the inclusive range of float and double in Java?

Java's Double class has members containing the Min and Max value for the type.

2^-1074 <= x <= (2-2^-52)·2^1023 // where x is the double.

Check out the Min_VALUE and MAX_VALUE static final members of Double.

(some)People will suggest against using floating point types for things where accuracy and precision are critical because rounding errors can throw off calculations by measurable (small) amounts.

What's the difference between TRUNCATE and DELETE in SQL

TRUNCATE can be rolled back if wrapped in a transaction.

Please see the two references below and test yourself:-

http://blog.sqlauthority.com/2007/12/26/sql-server-truncate-cant-be-rolled-back-using-log-files-after-transaction-session-is-closed/

http://sqlblog.com/blogs/kalen_delaney/archive/2010/10/12/tsql-tuesday-11-rolling-back-truncate-table.aspx

The TRUNCATE vs. DELETE is one of the infamous questions during SQL interviews. Just make sure you explain it properly to the Interviewer or it might cost you the job. The problem is that not many are aware so most likely they will consider the answer as wrong if you tell them that YES Truncate can be rolled back.

Convert String[] to comma separated string in java

Extention for prior Java 8 solution

String result = String.join(",", name);

If you need prefix or/ and suffix for array values

 StringJoiner joiner = new StringJoiner(",");
 for (CharSequence cs: name) {
     joiner.add("'" + cs + "'");
 }
 return joiner.toString();

Or simple method concept

  public static String genInValues(String delimiter, String prefix, String suffix, String[] name) {
    StringJoiner joiner = new StringJoiner(delimiter);
    for (CharSequence cs: name) {
      joiner.add(prefix + cs + suffix);
    }
    return joiner.toString();
  }

For example

For Oracle i need "id in (1,2,3,4,5)" 
then use genInValues(",", "", "", name);
But for Postgres i need "id in (values (1),(2),(3),(4),(5))"
then use genInValues(",", "(", ")", name);

Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK - Android

  1. If you have android studio installed within your system, then copy the templates folder from C:\Program Files\Android\Android Studio\plugins\android\lib\templates
  2. Paste it in the folder C:\Users\<user-name>\AppData\Local\Android\sdk\tools
  3. Run the command: ionic build android

All necessary jar files will be downloaded and apk file for the application will be generated.

Note: Set environment variables to C:\Users\<user-name>\AppData\Local\Android\sdk\tools. Also set user-name to your current username.

Maven2: Best practice for Enterprise Project (EAR file)

I've been searching high and low for an end-to-end example of a complete maven-based ear-packaged application and finally stumbled upon this. The instructions say to select option 2 when running through the CLI but for your purposes, use option 1.

Simple pagination in javascript

Following is the Logic which accepts count from user and performs pagination in Javascript. It prints alphabets. Hope it helps!!. Thankyou.

_x000D_
_x000D_
/*_x000D_
*****_x000D_
USER INPUT : NUMBER OF SUGGESTIONS._x000D_
*****_x000D_
*/_x000D_
_x000D_
var recordSize = prompt('please, enter the Record Size');_x000D_
console.log(recordSize);_x000D_
_x000D_
_x000D_
/*_x000D_
*****_x000D_
POPULATE SUGGESTIONS IN THE suggestion_set LIST._x000D_
*****_x000D_
*/_x000D_
var suggestion_set = [];_x000D_
counter = 0;_x000D_
_x000D_
asscicount = 65;_x000D_
do{_x000D_
if(asscicount <= 90){_x000D_
 var temp = String.fromCharCode(asscicount);_x000D_
 suggestion_set.push(temp);_x000D_
 asscicount += 1;     _x000D_
}else{_x000D_
 asscicount = 65;_x000D_
 var temp = String.fromCharCode(asscicount);_x000D_
 suggestion_set.push(temp); _x000D_
 asscicount += 1;     _x000D_
}_x000D_
counter += 1;_x000D_
}while(counter < recordSize);_x000D_
_x000D_
console.log(suggestion_set); _x000D_
_x000D_
_x000D_
_x000D_
/*_x000D_
*****_x000D_
LOGIC FOR PAGINATION_x000D_
*****_x000D_
*/_x000D_
_x000D_
var totalRecords = recordSize, pageSize = 6;_x000D_
var q = Math.floor(totalRecords/pageSize);_x000D_
var r = totalRecords%pageSize;_x000D_
var itr = 1;_x000D_
_x000D_
if(r==0 ||r==1 ||r==2) {_x000D_
itr=q;_x000D_
}_x000D_
else {_x000D_
itr=q+1;_x000D_
}_x000D_
console.log(itr);_x000D_
_x000D_
var output = "", pageCnt=1, newPage=false;_x000D_
_x000D_
if(totalRecords <= pageSize+2) {_x000D_
output += "\n";_x000D_
_x000D_
 for(var i=0; i < totalRecords; i++){_x000D_
  output += suggestion_set[i] + "\t";_x000D_
 }_x000D_
}_x000D_
_x000D_
else {_x000D_
 output += "\n";_x000D_
 for(var i=0; i<totalRecords; i++) {_x000D_
  //output += (i+1) + "\t";_x000D_
  if(pageCnt==1){_x000D_
  output += suggestion_set[i] + "\t";_x000D_
  if((i+1)==(pageSize+1)) {_x000D_
  output += "Next" + "\t";_x000D_
  pageCnt++;_x000D_
  newPage=true;_x000D_
 }_x000D_
}_x000D_
else {_x000D_
if(newPage) {_x000D_
output += "\n" + "Previous" + "\t";_x000D_
newPage = false;_x000D_
}_x000D_
output += suggestion_set[i] + "\t";_x000D_
if((i+1)==(pageSize*pageCnt+1) && (pageSize*pageCnt+1)<totalRecords) {_x000D_
if((i+2) == (pageSize*pageCnt+2) && pageCnt==itr) {_x000D_
output += (suggestion_set[i] + 1) + "\t";_x000D_
break;_x000D_
}_x000D_
else {_x000D_
output += "Next" + "\t";_x000D_
pageCnt++;_x000D_
newPage=true;_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
console.log(output);
_x000D_
_x000D_
_x000D_

Is there a <meta> tag to turn off caching in all browsers?

I noticed some caching issues with service calls when repeating the same service call (long polling). Adding metadata didn't help. One solution is to pass a timestamp to ensure ie thinks it's a different http service request. That worked for me, so adding a server side scripting code snippet to automatically update this tag wouldn't hurt:

<meta http-equiv="expires" content="timestamp">

git - remote add origin vs remote set-url origin

1. git remote add origin [email protected]:User/UserRepo.git

  • This command is the second step in the command series after you initialize git into your current working repository using git init.
  • This command simply means "you are adding the location of your remote repository where you wish to push/pull your files to/from !!.."
  • Your remote repository could be anywhere on github, gitlab, bitbucket, etc.
  • Here origin is an alias/alternate name for your remote repository so that you don't have to type the entire path for remote every time and henceforth you are declaring that you will use this name(origin) to refer to your remote. This name could be anything.
  • To verify that the remote is set properly type : git remote -v

OR git remote get-url origin

2. git remote set-url origin [email protected]:User/UserRepo.git

This command means that if at any stage you wish to change the location of your repository(i.e if you made a mistake while adding the remote path using the git add command) the first time, you can easily go back & "reset(update) your current remote repository path" by using the above command.

3. git push -u remote master

This command simply pushes your files to the remote repository.Git has a concept of something known as a "branch", so by default everything is pushed to the master branch unless explicitly specified an alternate branch.

To know about the list of all branches you have in your repository type :git branch

Initializing a list to a known number of elements in Python

Without knowing more about the problem domain, it's hard to answer your question. Unless you are certain that you need to do something more, the pythonic way to initialize a list is:

verts = []

Are you actually seeing a performance problem? If so, what is the performance bottleneck? Don't try to solve a problem that you don't have. It's likely that performance cost to dynamically fill an array to 1000 elements is completely irrelevant to the program that you're really trying to write.

The array class is useful if the things in your list are always going to be a specific primitive fixed-length type (e.g. char, int, float). But, it doesn't require pre-initialization either.

How to run a task when variable is undefined in ansible?

As per latest Ansible Version 2.5, to check if a variable is defined and depending upon this if you want to run any task, use undefined keyword.

tasks:
    - shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
      when: foo is defined

    - fail: msg="Bailing out. this play requires 'bar'"
      when: bar is undefined

Ansible Documentation

Multiple "style" attributes in a "span" tag: what's supposed to happen?

In HTML, SGML and XML, (1) attributes cannot be repeated, and should only be defined in an element once.

So your example:

<span style="color:blue" style="font-style:italic">Test</span>

is non-conformant to the HTML standard, and will result in undefined behaviour, which explains why different browsers are rendering it differently.


Since there is no defined way to interpret this, browsers can interpret it however they want and merge them, or ignore them as they wish.

(1): Every article I can find states that attributes are "key/value" pairs or "attribute-value" pairs, heavily implying the keys must be unique. The best source I can find states:

Attribute names (id and status in this example) are subject to the same restrictions as other names in XML; they need not be unique across the whole DTD, however, but only within the list of attributes for a given element. (Emphasis mine.)

TypeError: argument of type 'NoneType' is not iterable

The python error says that wordInput is not an iterable -> it is of NoneType.

If you print wordInput before the offending line, you will see that wordInput is None.

Since wordInput is None, that means that the argument passed to the function is also None. In this case word. You assign the result of pickEasy to word.

The problem is that your pickEasy function does not return anything. In Python, a method that didn't return anything returns a NoneType.

I think you wanted to return a word, so this will suffice:

def pickEasy():
    word = random.choice(easyWords)
    word = str(word)
    for i in range(1, len(word) + 1):
        wordCount.append("_")
    return word

Opencv - Grayscale mode Vs gray color conversion

Note: This is not a duplicate, because the OP is aware that the image from cv2.imread is in BGR format (unlike the suggested duplicate question that assumed it was RGB hence the provided answers only address that issue)

To illustrate, I've opened up this same color JPEG image:

enter image description here

once using the conversion

img = cv2.imread(path)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

and another by loading it in gray scale mode

img_gray_mode = cv2.imread(path, cv2.IMREAD_GRAYSCALE)

Like you've documented, the diff between the two images is not perfectly 0, I can see diff pixels in towards the left and the bottom

enter image description here

I've summed up the diff too to see

import numpy as np
np.sum(diff)
# I got 6143, on a 494 x 750 image

I tried all cv2.imread() modes

Among all the IMREAD_ modes for cv2.imread(), only IMREAD_COLOR and IMREAD_ANYCOLOR can be converted using COLOR_BGR2GRAY, and both of them gave me the same diff against the image opened in IMREAD_GRAYSCALE

The difference doesn't seem that big. My guess is comes from the differences in the numeric calculations in the two methods (loading grayscale vs conversion to grayscale)

Naturally what you want to avoid is fine tuning your code on a particular version of the image just to find out it was suboptimal for images coming from a different source.

In brief, let's not mix the versions and types in the processing pipeline.

So I'd keep the image sources homogenous, e.g. if you have capturing the image from a video camera in BGR, then I'd use BGR as the source, and do the BGR to grayscale conversion cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

Vice versa if my ultimate source is grayscale then I'd open the files and the video capture in gray scale cv2.imread(path, cv2.IMREAD_GRAYSCALE)

IIS7 Permissions Overview - ApplicationPoolIdentity

Top Answer from Jon Adams

Here is how to implement this for the PowerShell folks

$IncommingPath = "F:\WebContent"
$Acl = Get-Acl $IncommingPath
$Ar = New-Object  system.security.accesscontrol.filesystemaccessrule("IIS AppPool\DefaultAppPool","FullControl","ContainerInherit, ObjectInherit", "None", "Allow")
$Acl.SetAccessRule($Ar)
Set-Acl $IncommingPath $Acl

How to Run a jQuery or JavaScript Before Page Start to Load

If you don't want anything to display before the redirect, then you will need to use some server side scripting to accomplish the task before the page is served. The page has already begun loading by the time your Javascript is executed on the client side.

If Javascript is your only option, your best best is to make your script the first .js file included in the <head> of your document.

Instead of Javascript, I recommend setting up your redirect logic in your Apache or nginx server configuration.

Currency format for display

You can use string.Format("{0:c}", value).

See also here:

Center a button in a Linear layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <ImageButton android:id="@+id/btnFindMe" 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content"
        android:layout_gravity = "center"
        android:background="@drawable/findme">
    </ImageButton>

</LinearLayout>

The above code will work.

Angular + Material - How to refresh a data source (mat-table)

In Angular 10, this is what works for me: In the HTML:

<mat-table [dataSource]="myArray">

In the component TS:

    myArray: MyObject[] = [];

 addObjectToTable(object:MyObject): void {
      //TO PREVENT DUPLICATED OBJECTS
    if (object&& !this.myArray.includes(object)) {
      this.myArray.push(object);
      // TO FORCE DATA-TABLE's DATASOURCE TO REFRESH
      this.myArray= [...this.myArray];
    }
  }

JavaScript string newline character?

A note - when using ExtendScript JavaScript (the Adobe Scripting language used in applications like Photoshop CS3+), the character to use is "\r". "\n" will be interpreted as a font character, and many fonts will thus have a block character instead.

For example (to select a layer named 'Note' and add line feeds after all periods):

var layerText = app.activeDocument.artLayers.getByName('Note').textItem.contents;
layerText = layerText.replace(/\. /g,".\r");

JPA: how do I persist a String into a database field, type MYSQL Text

Since you're using JPA, use the Lob annotation (and optionally the Column annotation). Here is what the JPA specification says about it:

9.1.19 Lob Annotation

A Lob annotation specifies that a persistent property or field should be persisted as a large object to a database-supported large object type. Portable applications should use the Lob annotation when mapping to a database Lob type. The Lob annotation may be used in conjunction with the Basic annotation. A Lob may be either a binary or character type. The Lob type is inferred from the type of the persistent field or property, and except for string and character-based types defaults to Blob.

So declare something like this:

@Lob 
@Column(name="CONTENT", length=512)
private String content;

References

  • JPA 1.0 specification:
    • Section 9.1.19 "Lob Annotation"

Vertical divider doesn't work in Bootstrap 3

Here is some LESS for you, in case you customize the navbar:

.navbar .divider-vertical {
    height: floor(@navbar-height - @navbar-margin-bottom);
    margin: floor(@navbar-margin-bottom / 2) 9px;
    border-left: 1px solid #f2f2f2;
    border-right: 1px solid #ffffff;
}

How do I put variable values into a text string in MATLAB?

Here's how you convert numbers to strings, and join strings to other things (it's weird):

>> ['the number is ' num2str(15) '.']
ans =
the number is 15.

Oracle SQL Developer - tables cannot be seen

Select 'Other Users' from the and select your user(schema), under which you will be able to see your tables and views.

Screenshot

MySQL foreach alternative for procedure

Here's the mysql reference for cursors. So I'm guessing it's something like this:

  DECLARE done INT DEFAULT 0;
  DECLARE products_id INT;
  DECLARE result varchar(4000);
  DECLARE cur1 CURSOR FOR SELECT products_id FROM sets_products WHERE set_id = 1;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

  OPEN cur1;

  REPEAT
    FETCH cur1 INTO products_id;
    IF NOT done THEN
      CALL generate_parameter_list(@product_id, @result);
      SET param = param + "," + result; -- not sure on this syntax
    END IF;
  UNTIL done END REPEAT;

  CLOSE cur1;

  -- now trim off the trailing , if desired

destination path already exists and is not an empty directory

This just means that the git clone copied the files down from github and placed them into a folder. If you try to do it again it will not let you because it can't clone into a folder that has files into it. So if you think the git clone did not complete properly, just delete the folder and do the git clone again. The clone creates a folder the same name as the git repo.

How to Get the Query Executed in Laravel 5? DB::getQueryLog() Returning Empty Array

For laravel 5 and onwards using only DB::getQueryLog() , will not do. BY default in this the value of

 protected $loggingQueries = false;

change it to

protected $loggingQueries = true; 

in the below file for logging query.

/vendor/laravel/framework/src/illuminate/Database/Connection.php 

And then we can use the DB::getQueryLog() where you want to print the query.

How do I import a pre-existing Java project into Eclipse and get up and running?

  1. Create a new Java project in Eclipse. This will create a src folder (to contain your source files).

  2. Also create a lib folder (the name isn't that important, but it follows standard conventions).

  3. Copy the ./com/* folders into the /src folder (you can just do this using the OS, no need to do any fancy importing or anything from the Eclipse GUI).

  4. Copy any dependencies (jar files that your project itself depends on) into /lib (note that this should NOT include the TGGL jar - thanks to commenter Mike Deck for pointing out my misinterpretation of the OPs post!)

  5. Copy the other TGGL stuff into the root project folder (or some other folder dedicated to licenses that you need to distribute in your final app)

  6. Back in Eclipse, select the project you created in step 1, then hit the F5 key (this refreshes Eclipse's view of the folder tree with the actual contents.

  7. The content of the /src folder will get compiled automatically (with class files placed in the /bin file that Eclipse generated for you when you created the project). If you have dependencies (which you don't in your current project, but I'll include this here for completeness), the compile will fail initially because you are missing the dependency jar files from the project classpath.

  8. Finally, open the /lib folder in Eclipse, right click on each required jar file and choose Build Path->Add to build path.

That will add that particular jar to the classpath for the project. Eclipse will detect the change and automatically compile the classes that failed earlier, and you should now have an Eclipse project with your app in it.

Java 8 Streams: multiple filters vs. complex condition

This test shows that your second option can perform significantly better. Findings first, then the code:

one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=4142, min=29, average=41.420000, max=82}
two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=13315, min=117, average=133.150000, max=153}
one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=10320, min=82, average=103.200000, max=127}

now the code:

enum Gender {
    FEMALE,
    MALE
}

static class User {
    Gender gender;
    int age;

    public User(Gender gender, int age){
        this.gender = gender;
        this.age = age;
    }

    public Gender getGender() {
        return gender;
    }

    public void setGender(Gender gender) {
        this.gender = gender;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

static long test1(List<User> users){
    long time1 = System.currentTimeMillis();
    users.stream()
            .filter((u) -> u.getGender() == Gender.FEMALE && u.getAge() % 2 == 0)
            .allMatch(u -> true);                   // least overhead terminal function I can think of
    long time2 = System.currentTimeMillis();
    return time2 - time1;
}

static long test2(List<User> users){
    long time1 = System.currentTimeMillis();
    users.stream()
            .filter(u -> u.getGender() == Gender.FEMALE)
            .filter(u -> u.getAge() % 2 == 0)
            .allMatch(u -> true);                   // least overhead terminal function I can think of
    long time2 = System.currentTimeMillis();
    return time2 - time1;
}

static long test3(List<User> users){
    long time1 = System.currentTimeMillis();
    users.stream()
            .filter(((Predicate<User>) u -> u.getGender() == Gender.FEMALE).and(u -> u.getAge() % 2 == 0))
            .allMatch(u -> true);                   // least overhead terminal function I can think of
    long time2 = System.currentTimeMillis();
    return time2 - time1;
}

public static void main(String... args) {
    int size = 10000000;
    List<User> users =
    IntStream.range(0,size)
            .mapToObj(i -> i % 2 == 0 ? new User(Gender.MALE, i % 100) : new User(Gender.FEMALE, i % 100))
            .collect(Collectors.toCollection(()->new ArrayList<>(size)));
    repeat("one filter with predicate of form u -> exp1 && exp2", users, Temp::test1, 100);
    repeat("two filters with predicates of form u -> exp1", users, Temp::test2, 100);
    repeat("one filter with predicate of form predOne.and(pred2)", users, Temp::test3, 100);
}

private static void repeat(String name, List<User> users, ToLongFunction<List<User>> test, int iterations) {
    System.out.println(name + ", list size " + users.size() + ", averaged over " + iterations + " runs: " + IntStream.range(0, iterations)
            .mapToLong(i -> test.applyAsLong(users))
            .summaryStatistics());
}

HTTP Error 500.30 - ANCM In-Process Start Failure

Just in case this helps anyone that may have made the same mistake I did.

My website has a SSL certificate by Certify the Web.

When I published, I deleted the _Well-Known folder and this error came up.

enter image description here

Had I not emptied my recycle bin 30 seconds before I figured this out on my virtual machine, I could have just restored the folder.

Instead, I re-requested my certificate, restarted that site and the issue was resolved.

CKEditor automatically strips classes from div

Since CKEditor v4.1, you can do this in config.js of CKEditor:

CKEDITOR.editorConfig = function( config ) {
  config.extraAllowedContent = '*[id](*)';  // remove '[id]', if you don't want IDs for HTML tags
}

You can refer to the official documentation for the detailed syntax of Allowed Content Rules

Set cookie and get cookie with JavaScript

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

Examples derived from these references:

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

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

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

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

Should I declare Jackson's ObjectMapper as a static field?

com.fasterxml.jackson.databind.type.TypeFactory._hashMapSuperInterfaceChain(HierarchicType)

com.fasterxml.jackson.databind.type.TypeFactory._findSuperInterfaceChain(Type, Class)
  com.fasterxml.jackson.databind.type.TypeFactory._findSuperTypeChain(Class, Class)
     com.fasterxml.jackson.databind.type.TypeFactory.findTypeParameters(Class, Class, TypeBindings)
        com.fasterxml.jackson.databind.type.TypeFactory.findTypeParameters(JavaType, Class)
           com.fasterxml.jackson.databind.type.TypeFactory._fromParamType(ParameterizedType, TypeBindings)
              com.fasterxml.jackson.databind.type.TypeFactory._constructType(Type, TypeBindings)
                 com.fasterxml.jackson.databind.type.TypeFactory.constructType(TypeReference)
                    com.fasterxml.jackson.databind.ObjectMapper.convertValue(Object, TypeReference)

The method _hashMapSuperInterfaceChain in class com.fasterxml.jackson.databind.type.TypeFactory is synchronized. Am seeing contention on the same at high loads.

May be another reason to avoid a static ObjectMapper

(413) Request Entity Too Large | uploadReadAheadSize

In my case I had to increase the "Maximum received message size" of the Receive Location in BizTalk. That also has a default value of 64K and so every message was bounced by BizTAlk regardless of what I configured in my web.config

'Framework not found' in Xcode

I got the error 'AdBrixRM framework not found'. I checked the AdBrixRM.framework. I noticed that 'AdBrixRM' excution file is missed. I copied this file into the framework folder and the issue was gone.

How to execute a Windows command on a remote PC?

You can use native win command:

WMIC /node:ComputerName process call create “cmd.exe /c start.exe”

The WMIC is part of wbem win folder: C:\Windows\System32\wbem

Add new field to every document in a MongoDB collection

if you are using mongoose try this,after mongoose connection

async ()=> await Mongoose.model("collectionName").updateMany({}, {$set: {newField: value}})

Read file data without saving it in Flask

I was trying to do the exact same thing, open a text file (a CSV for Pandas actually). Don't want to make a copy of it, just want to open it. The form-WTF has a nice file browser, but then it opens the file and makes a temporary file, which it presents as a memory stream. With a little work under the hood,

form = UploadForm() 
 if form.validate_on_submit(): 
      filename = secure_filename(form.fileContents.data.filename)  
      filestream =  form.fileContents.data 
      filestream.seek(0)
      ef = pd.read_csv( filestream  )
      sr = pd.DataFrame(ef)  
      return render_template('dataframe.html',tables=[sr.to_html(justify='center, classes='table table-bordered table-hover')],titles = [filename], form=form) 

How do I use IValidatableObject?

Just to add a couple of points:

Because the Validate() method signature returns IEnumerable<>, that yield return can be used to lazily generate the results - this is beneficial if some of the validation checks are IO or CPU intensive.

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
    if (this.Enable)
    {
        // ...
        if (this.Prop1 > this.Prop2)
        {
            yield return new ValidationResult("Prop1 must be larger than Prop2");
        }

Also, if you are using MVC ModelState, you can convert the validation result failures to ModelState entries as follows (this might be useful if you are doing the validation in a custom model binder):

var resultsGroupedByMembers = validationResults
    .SelectMany(vr => vr.MemberNames
                        .Select(mn => new { MemberName = mn ?? "", 
                                            Error = vr.ErrorMessage }))
    .GroupBy(x => x.MemberName);

foreach (var member in resultsGroupedByMembers)
{
    ModelState.AddModelError(
        member.Key,
        string.Join(". ", member.Select(m => m.Error)));
}

MySQL Stored procedure variables from SELECT statements

Corrected a few things and added an alternative select - delete as appropriate.

DELIMITER |

CREATE PROCEDURE getNearestCities
(
IN p_cityID INT -- should this be int unsigned ?
)
BEGIN

DECLARE cityLat FLOAT; -- should these be decimals ?
DECLARE cityLng FLOAT;

    -- method 1
    SELECT lat,lng into cityLat, cityLng FROM cities WHERE cities.cityID = p_cityID;

    SELECT 
     b.*, 
     HAVERSINE(cityLat,cityLng, b.lat, b.lng) AS dist 
    FROM 
     cities b 
    ORDER BY 
     dist 
    LIMIT 10;

    -- method 2
    SELECT   
      b.*, 
      HAVERSINE(a.lat, a.lng, b.lat, b.lng) AS dist
    FROM     
      cities AS a
    JOIN cities AS b on a.cityID = p_cityID
    ORDER BY 
      dist
    LIMIT 10;

END |

delimiter ;

How do I resolve git saying "Commit your changes or stash them before you can merge"?

I tried the first answer: git stash with the highest score but the error message still popped up, and then I found this article to commit the changes instead of stash 'Reluctant Commit'

and the error message disappeared finally:

1: git add .

2: git commit -m "this is an additional commit"

3: git checkout the-other-file-name

then it worked. hope this answer helps.:)

Unclosed Character Literal error

'' encloses single char, while "" encloses a String.

Change

y = 'hello';

-->

y = "hello";

Error parsing yaml file: mapping values are not allowed here

Another cause is wrong indentation which means trying to create the wrong objects. I've just fixed one in a Kubernetes Ingress definition:

Wrong

- path: / 
    backend: 
      serviceName: <service_name> 
      servicePort: <port> 

Correct

- path: /
  backend:
    serviceName: <service_name>
    servicePort: <port>

python date of the previous month

from datetime import date, timedelta

first_day_of_current_month = date.today().replace(day=1)
last_day_of_previous_month = first_day_of_current_month - timedelta(days=1)

print "Previous month:", last_day_of_previous_month.month

Or:

from datetime import date, timedelta

prev = date.today().replace(day=1) - timedelta(days=1)
print prev.month

Adding a column to a data.frame

Approach based on identifying number of groups (x in mapply) and its length (y in mapply)

mytb<-read.table(text="h_no  h_freq  h_freqsq group
1     0.09091 0.008264628 1
2     0.00000 0.000000000 1
3     0.04545 0.002065702 1
4     0.00000 0.000000000 1  
1     0.13636 0.018594050 2
2     0.00000 0.000000000 2
3     0.00000 0.000000000 2
4     0.04545 0.002065702 2
5     0.31818 0.101238512 2
6     0.00000 0.000000000 2
7     0.50000 0.250000000 2 
1     0.13636 0.018594050 3 
2     0.09091 0.008264628 3
3     0.40909 0.167354628 3
4     0.04545 0.002065702 3", header=T, stringsAsFactors=F)
mytb$group<-NULL

positionsof1s<-grep(1,mytb$h_no)

mytb$newgroup<-unlist(mapply(function(x,y) 
  rep(x,y),                      # repeat x number y times
  x= 1:length(positionsof1s),    # x is 1 to number of nth group = g1:g3
  y= c( diff(positionsof1s),     # y is number of repeats of groups g1 to penultimate (g2) = 4, 7
        nrow(mytb)-              # this line and the following gives number of repeat for last group (g3)
          (positionsof1s[length(positionsof1s )]-1 )  # number of rows - position of penultimate group (g2) 
      ) ) )
mytb

Laravel view not found exception

Create the index.blade.php file in the views folder, that should be all

Finding an item in a List<> using C#

You have a few options:

  1. Using Enumerable.Where:

    list.Where(i => i.Property == value).FirstOrDefault();       // C# 3.0+
    
  2. Using List.Find:

    list.Find(i => i.Property == value);                         // C# 3.0+
    list.Find(delegate(Item i) { return i.Property == value; }); // C# 2.0+
    

Both of these options return default(T) (null for reference types) if no match is found.

As mentioned in the comments below, you should use the appropriate form of comparison for your scenario:

  • == for simple value types or where use of operator overloads are desired
  • object.Equals(a,b) for most scenarios where the type is unknown or comparison has potentially been overridden
  • string.Equals(a,b,StringComparison) for comparing strings
  • object.ReferenceEquals(a,b) for identity comparisons, which are usually the fastest

How to store an output of shell script to a variable in Unix?

Two simple examples to capture output the pwd command:

$ b=$(pwd)
$ echo $b
/home/user1

or

$ a=`pwd`
$ echo $a
/home/user1

The first way is preferred. Note that there can't be any spaces after the = for this to work.

Example using a short script:

#!/bin/bash

echo "hi there"

then:

$ ./so.sh
hi there
$ a=$(so.sh)
$ echo $a
hi there

In general a more flexible approach would be to return an exit value from the command and use it for further processing, though sometimes we just may want to capture the simple output from a command.

How do you add a scroll bar to a div?

If you want to add a scroll bar using jquery the following will work. If your div had a id of 'mydiv' you could us the following jquery id selector with css property:

jQuery('#mydiv').css("overflow-y", "scroll");

How to specify function types for void (not Void) methods in Java8?

Set return type to Void instead of void and return null

// Modify existing method
public static Void displayInt(Integer i) {
    System.out.println(i);
    return null;
}

OR

// Or use Lambda
myForEach(theList, i -> {System.out.println(i);return null;});

How to get device make and model on iOS?

Swift 3 compatible

// MARK: - UIDevice Extension -

private let DeviceList = [
/* iPod 5 */          "iPod5,1": "iPod Touch 5",
/* iPhone 4 */        "iPhone3,1":  "iPhone 4", "iPhone3,2": "iPhone 4", "iPhone3,3": "iPhone 4",
/* iPhone 4S */       "iPhone4,1": "iPhone 4S",
/* iPhone 5 */        "iPhone5,1": "iPhone 5", "iPhone5,2": "iPhone 5",
/* iPhone 5C */       "iPhone5,3": "iPhone 5C", "iPhone5,4": "iPhone 5C",
/* iPhone 5S */       "iPhone6,1": "iPhone 5S", "iPhone6,2": "iPhone 5S",
/* iPhone 6 */        "iPhone7,2": "iPhone 6",
/* iPhone 6 Plus */   "iPhone7,1": "iPhone 6 Plus",
/* iPhone 6S */       "iPhone8,1": "iPhone 6S",
/* iPhone 6S Plus */  "iPhone8,2": "iPhone 6S Plus",
/* iPhone SE */       "iPhone8,4": "iPhone SE",
/* iPhone 7 */        "iPhone9,1": "iPhone 7",
/* iPhone 7 */        "iPhone9,3": "iPhone 7",
/* iPhone 7 Plus */   "iPhone9,2": "iPhone 7 Plus",
/* iPhone 7 Plus */   "iPhone9,4": "iPhone 7 Plus",
/* iPad 2 */          "iPad2,1": "iPad 2", "iPad2,2": "iPad 2", "iPad2,3": "iPad 2", "iPad2,4": "iPad 2",
/* iPad 3 */          "iPad3,1": "iPad 3", "iPad3,2": "iPad 3", "iPad3,3":     "iPad 3",
/* iPad 4 */          "iPad3,4": "iPad 4", "iPad3,5": "iPad 4", "iPad3,6": "iPad 4",
/* iPad Air */        "iPad4,1": "iPad Air", "iPad4,2": "iPad Air", "iPad4,3": "iPad Air",
/* iPad Air 2 */      "iPad5,1": "iPad Air 2", "iPad5,3": "iPad Air 2", "iPad5,4": "iPad Air 2",
/* iPad Mini */       "iPad2,5": "iPad Mini 1", "iPad2,6": "iPad Mini 1", "iPad2,7": "iPad Mini 1",
/* iPad Mini 2 */     "iPad4,4": "iPad Mini 2", "iPad4,5": "iPad Mini 2", "iPad4,6": "iPad Mini 2",
/* iPad Mini 3 */     "iPad4,7": "iPad Mini 3", "iPad4,8": "iPad Mini 3", "iPad4,9": "iPad Mini 3",
/* iPad Pro 12.9 */   "iPad6,7": "iPad Pro 12.9", "iPad6,8": "iPad Pro 12.9",
/* iPad Pro  9.7 */   "iPad6,3": "iPad Pro 9.7", "iPad6,4": "iPad Pro 9.7",
/* Simulator */       "x86_64": "Simulator", "i386": "Simulator"
]

extension UIDevice {

    static var modelName: String {
        var systemInfo = utsname()
        uname(&systemInfo)

        let machine = systemInfo.machine
        let mirror = Mirror(reflecting: machine)

        var identifier = ""

        for child in mirror.children {
            if let value = child.value as? Int8, value != 0 {
                identifier += String(UnicodeScalar(UInt8(value)))
            }
        }
        return DeviceList[identifier] ?? identifier
    }

    static var isIphone4: Bool {
        return modelName == "iPhone 5" || modelName == "iPhone 5C" || modelName == "iPhone 5S" || UIDevice.isSimulatorIPhone4
    }

    static var isIphone5: Bool {
        return modelName == "iPhone 4S" || modelName == "iPhone 4" || UIDevice.isSimulatorIPhone5
    }

    static var isIphone6: Bool {
        return modelName == "iPhone 6" || UIDevice.isSimulatorIPhone6
    }
    static var isIphone6Plus: Bool {
        return modelName == "iPhone 6 Plus" || UIDevice.isSimulatorIPhone6Plus
    }

    static var isIpad: Bool {
        if UIDevice.current.model.contains("iPad") {
            return true
        }
        return false
    }

    static var isIphone: Bool {
        return !self.isIpad
    }

    /// Check if current device is iPhone4S (and earlier) relying on screen heigth
    static var isSimulatorIPhone4: Bool {
        return UIDevice.isSimulatorWithScreenHeigth(480)
    }

    /// Check if current device is iPhone5 relying on screen heigth
    static var isSimulatorIPhone5: Bool {
        return UIDevice.isSimulatorWithScreenHeigth(568)
    }

    /// Check if current device is iPhone6 relying on screen heigth
    static var isSimulatorIPhone6: Bool {
        return UIDevice.isSimulatorWithScreenHeigth(667)
    }

    /// Check if current device is iPhone6 Plus relying on screen heigth
    static var isSimulatorIPhone6Plus: Bool {
        return UIDevice.isSimulatorWithScreenHeigth(736)
    }

    private static func isSimulatorWithScreenHeigth(_ heigth: CGFloat) -> Bool {
        let screenSize: CGRect = UIScreen.main.bounds
        return modelName == "Simulator" && screenSize.height == heigth
    }

}

C++ equivalent of java's instanceof

dynamic_cast is known to be inefficient. It traverses up the inheritance hierarchy, and it is the only solution if you have multiple levels of inheritance, and need to check if an object is an instance of any one of the types in its type hierarchy.

But if a more limited form of instanceof that only checks if an object is exactly the type you specify, suffices for your needs, the function below would be a lot more efficient:

template<typename T, typename K>
inline bool isType(const K &k) {
    return typeid(T).hash_code() == typeid(k).hash_code();
}

Here's an example of how you'd invoke the function above:

DerivedA k;
Base *p = &k;

cout << boolalpha << isType<DerivedA>(*p) << endl;  // true
cout << boolalpha << isType<DerivedB>(*p) << endl;  // false

You'd specify template type A (as the type you're checking for), and pass in the object you want to test as the argument (from which template type K would be inferred).

Allowed memory size of 262144 bytes exhausted (tried to allocate 24576 bytes)

In my case neither M or G helped, so I have converted allocated memory to bytes using: https://www.gbmb.org/mb-to-bytes

4096M = 4294967296

php.ini:

memory_limit = 4294967296

Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe

Since you're dealing with values that are just supposed to be boolean anyway, just use == and convert the logical response to as.integer:

df <- data.frame(col = c("true", "true", "false"))
df
#     col
# 1  true
# 2  true
# 3 false
df$col <- as.integer(df$col == "true")
df
#   col
# 1   1
# 2   1
# 3   0

How to include clean target in Makefile?

The best thing is probably to create a variable that holds your binaries:

binaries=code1 code2

Then use that in the all-target, to avoid repeating:

all: clean $(binaries)

Now, you can use this with the clean-target, too, and just add some globs to catch object files and stuff:

.PHONY: clean

clean:
    rm -f $(binaries) *.o

Note use of the .PHONY to make clean a pseudo-target. This is a GNU make feature, so if you need to be portable to other make implementations, don't use it.

Using Java to pull data from a webpage?

The simplest solution (without depending on any third-party library or platform) is to create a URL instance pointing to the web page / link you want to download, and read the content using streams.

For example:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;


public class DownloadPage {

    public static void main(String[] args) throws IOException {

        // Make a URL to the web page
        URL url = new URL("http://stackoverflow.com/questions/6159118/using-java-to-pull-data-from-a-webpage");

        // Get the input stream through URL Connection
        URLConnection con = url.openConnection();
        InputStream is =con.getInputStream();

        // Once you have the Input Stream, it's just plain old Java IO stuff.

        // For this case, since you are interested in getting plain-text web page
        // I'll use a reader and output the text content to System.out.

        // For binary content, it's better to directly read the bytes from stream and write
        // to the target file.


        BufferedReader br = new BufferedReader(new InputStreamReader(is));

        String line = null;

        // read each line and write to System.out
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    }
}

Hope this helps.

iOS 8 removed "minimal-ui" viewport property, are there other "soft fullscreen" solutions?

It IS possible, using something like the below example that I put together with the help of work from (https://gist.github.com/bitinn/1700068a276fb29740a7) that didn't quite work on iOS 11:

Here's the modified code that works on iOS 11.03, please comment if it worked for you.

The key is adding some size to BODY so the browser can scroll, ex: height: calc(100% + 40px);

Full sample below & link to view in your browser (please test!)

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CodeHots iOS WebApp Minimal UI via Scroll Test</title>

    <style>
        html, body {
            height: 100%;
        }
        html {
            background-color: red;
        }
        body {
            background-color: blue;
            /* important to allow page to scroll */
            height: calc(100% + 40px);
            margin: 0;
        }
        div.header {
            width: 100%;
            height: 40px;
            background-color: green;
            overflow: hidden;
        }
        div.content {
            height: 100%;
            height: calc(100% - 40px);
            width: 100%;
            background-color: purple;
            overflow: hidden;
        }
        div.cover {
            position: absolute;
            top: 0;
            left: 0;
            z-index: 100;
            width: 100%;
            height: 100%;
            overflow: hidden;
            background-color: rgba(0, 0, 0, 0.5);
            color: #fff;
            display: none;
        }
        @media screen and (width: 320px) {
            html {
                height: calc(100% + 72px);
            }
            div.cover {
                display: block;
            }
        }
    </style>
    <script>
        var timeout;

        function interceptTouchMove(){
            // and disable the touchmove features 
            window.addEventListener("touchmove", (event)=>{
                if (!event.target.classList.contains('scrollable')) {
                    // no more scrolling
                    event.preventDefault();
                }
            }, false); 
        }

        function scrollDetect(event){
            // wait for the result to settle
            if( timeout ) clearTimeout(timeout);

            timeout = setTimeout(function() {
                console.log( 'scrolled up detected..' );
                if (window.scrollY > 35) {
                    console.log( ' .. moved up enough to go into minimal UI mode. cover off and locking touchmove!');
                    // hide the fixed scroll-cover
                    var cover = document.querySelector('div.cover');
                    cover.style.display = 'none';

                    // push back down to designated start-point. (as it sometimes overscrolls (this is jQuery implementation I used))
                    window.scrollY = 40;

                    // and disable the touchmove features 
                    interceptTouchMove();

                    // turn off scroll checker
                    window.removeEventListener('scroll', scrollDetect );                
                }
            }, 200);            
        }

        // listen to scroll to know when in minimal-ui mode.
        window.addEventListener('scroll', scrollDetect, false );
    </script>
</head>
<body>

    <div class="header">
        <p>header zone</p>
    </div>
    <div class="content">
        <p>content</p>
    </div>
    <div class="cover">
        <p>scroll to soft fullscreen</p>
    </div>

</body>

Full example link here: https://repos.codehot.tech/misc/ios-webapp-example2.html

Android studio - Failed to find target android-18

STEP 1) Start Android SDK Manager

With android command something as below,

$ /usr/local/android-studio/sdk/tools/android

STEP 2) Find API 18

enter image description here

STEP 3) Select Android 4.3 (API 18 ) and install packages.

java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication Maven

If you would like to stay in spring boot space just set the pom packaging to jar

<packaging>jar</packaging>

and add the spring-boot-maven-plugin to you build properties in the pom.xml file:

<build>
  <plugins>
    <plugin>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-maven-plugin</artifactId>
    </plugin>
  </plugins>
</build>

then a simple mvn package command will create a complete executable jar file.

See the very good spring reference doc for more details (doing it gradle style also) spring reference doc

Fitting empirical distribution to theoretical ones with Scipy (Python)?

fit() method mentioned by @Saullo Castro provides maximum likelihood estimates (MLE). The best distribution for your data is the one give you the highest can be determined by several different ways: such as

1, the one that gives you the highest log likelihood.

2, the one that gives you the smallest AIC, BIC or BICc values (see wiki: http://en.wikipedia.org/wiki/Akaike_information_criterion, basically can be viewed as log likelihood adjusted for number of parameters, as distribution with more parameters are expected to fit better)

3, the one that maximize the Bayesian posterior probability. (see wiki: http://en.wikipedia.org/wiki/Posterior_probability)

Of course, if you already have a distribution that should describe you data (based on the theories in your particular field) and want to stick to that, you will skip the step of identifying the best fit distribution.

scipy does not come with a function to calculate log likelihood (although MLE method is provided), but hard code one is easy: see Is the build-in probability density functions of `scipy.stat.distributions` slower than a user provided one?

Linux bash script to extract IP address

ip -4 addr show eth0 | grep -oP "(?<=inet ).*(?=/)"

Change DIV content using ajax, php and jQuery

<script>

function getSummary(id)
{
   $.ajax({

     type: "GET",
     url: 'Your URL',
     data: "id=" + id, // appears as $_GET['id'] @ your backend side
     success: function(data) {
           // data is ur summary
          $('#summary').html(data);
     }

   });

}
</script>

And add onclick event in your lists

<a onclick="getSummary('1')">View Text</a>
<div id="#summary">This text will be replaced when the onclick event (link is clicked) is triggered.</div>

top align in html table?

Some CSS :

table td, table td * {
    vertical-align: top;
}

How can I specify a local gem in my Gemfile?

I believe you can do this:

gem "foo", path: "/path/to/foo"

How to style readonly attribute with CSS?

If you select the input by the id and then add the input[readonly="readonly"] tag in the css, something like:

 #inputID input[readonly="readonly"] {
     background-color: #000000;
 }

That will not work. You have to select a parent class or id an then the input. Something like:

 .parentClass, #parentID input[readonly="readonly"] {
     background-color: #000000;
 }

My 2 cents while waiting for new tickets at work :D

symfony2 twig path with parameter url creation

/**
 * @Route("/category/{id}", name="_category")
 * @Route("/category/{id}/{active}", name="_be_activatecategory")
 * @Template()
 */
public function categoryAction($id, $active = null)
{ .. }

May works.

Remove menubar from Electron app

Use this:

mainWindow = new BrowserWindow({width: 640, height: 360})
mainWindow.setMenuBarVisibility(false)

Reference: https://github.com/electron/electron/issues/1415

I tried mainWindow.setMenu(null), but it didn't work.

The first day of the current month in php using date_modify as DateTime object

Requires PHP 5.3 to work ("first day of" is introduced in PHP 5.3). Otherwise the example above is the only way to do it:

<?php
    // First day of this month
    $d = new DateTime('first day of this month');
    echo $d->format('jS, F Y');

    // First day of a specific month
    $d = new DateTime('2010-01-19');
    $d->modify('first day of this month');
    echo $d->format('jS, F Y');

    // alternatively...
    echo date_create('2010-01-19')
      ->modify('first day of this month')
      ->format('jS, F Y');

In PHP 5.4+ you can do this:

<?php
    // First day of this month
    echo (new DateTime('first day of this month'))->format('jS, F Y');

    echo (new DateTime('2010-01-19'))
      ->modify('first day of this month')
      ->format('jS, F Y');

If you prefer a concise way to do this, and already have the year and month in numerical values, you can use date():

<?php
    echo date('Y-m-01'); // first day of this month
    echo date("$year-$month-01"); // first day of a month chosen by you

Deleting rows from parent and child tables

Two possible approaches.

  1. If you have a foreign key, declare it as on-delete-cascade and delete the parent rows older than 30 days. All the child rows will be deleted automatically.

  2. Based on your description, it looks like you know the parent rows that you want to delete and need to delete the corresponding child rows. Have you tried SQL like this?

      delete from child_table
          where parent_id in (
               select parent_id from parent_table
                    where updd_tms != (sysdate-30)
    

    -- now delete the parent table records

    delete from parent_table
    where updd_tms != (sysdate-30);
    

---- Based on your requirement, it looks like you might have to use PL/SQL. I'll see if someone can post a pure SQL solution to this (in which case that would definitely be the way to go).

declare
    v_sqlcode number;
    PRAGMA EXCEPTION_INIT(foreign_key_violated, -02291);
begin
    for v_rec in (select parent_id, child id from child_table
                         where updd_tms != (sysdate-30) ) loop

    -- delete the children
    delete from child_table where child_id = v_rec.child_id;

    -- delete the parent. If we get foreign key violation, 
    -- stop this step and continue the loop
    begin
       delete from parent_table
          where parent_id = v_rec.parent_id;
    exception
       when foreign_key_violated
         then null;
    end;
 end loop;
end;
/

Share link on Google+

Yep! Use the link:

https://m.google.com/app/plus/x/?v=compose&content=YOUR_TEXT

It's SHARE url (not used for plus one) button.

If this will not work (not for me) try this url:

https://plusone.google.com/_/+1/confirm?hl=ru&url=_URL_&title=_TITLE_

Or see this solution:

Adding a Google Plus (one or share) link to an email newsletter

What does the explicit keyword mean?

The explicit keyword makes a conversion constructor to non-conversion constructor. As a result, the code is less error prone.

jQuery: Count number of list elements?

_x000D_
_x000D_
$("button").click(function(){_x000D_
    alert($("li").length);_x000D_
 });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>_x000D_
  <meta charset="utf-8">_x000D_
  <title>Count the number of specific elements</title>_x000D_
</head>_x000D_
<body>_x000D_
<ul>_x000D_
  <li>List - 1</li>_x000D_
  <li>List - 2</li>_x000D_
  <li>List - 3</li>_x000D_
</ul>_x000D_
  <button>Display the number of li elements</button>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

What are the differences between if, else, and else if?

you can think of the if and else as a pair, that satisfies two actions for one given condition.
ex: if it rains, take an umbrella else go without an umbrella.
there are two actions

  • go with an umbrella
  • go without an umbrella

and both the two actions are bound to one condition, i.e is it raining?

now, consider a scenario where there are multiple conditions and actions, bound together.
ex: if you are hungry and you are not broke, enjoy your meal at kfc, else if you are hungry but you are broke, try to compromise, else if you are not hungry, but you just want to hangout in a cafe, try startbucks, else do anything, just don't ask me about hunger or food. i have got bigger things to worry.
the else if statement to to string together all the actions that falls in between the if and the else conditions.

What Regex would capture everything from ' mark to the end of a line?

The appropriate regex would be the ' char followed by any number of any chars [including zero chars] ending with an end of string/line token:

'.*$

And if you wanted to capture everything after the ' char but not include it in the output, you would use:

(?<=').*$

This basically says give me all characters that follow the ' char until the end of the line.

Edit: It has been noted that $ is implicit when using .* and therefore not strictly required, therefore the pattern:

'.* 

is technically correct, however it is clearer to be specific and avoid confusion for later code maintenance, hence my use of the $. It is my belief that it is always better to declare explicit behaviour than rely on implicit behaviour in situations where clarity could be questioned.

HTML - How to do a Confirmation popup to a Submit button and then send the request?

I believe you want to use confirm()

<script type="text/javascript">
    function clicked() {
       if (confirm('Do you want to submit?')) {
           yourformelement.submit();
       } else {
           return false;
       }
    }

</script>

Java: get all variable names in a class

As mentioned by few users, below code can help find all the fields in a given class.

TestClass testObject= new TestClass().getClass();
Method[] methods = testObject.getMethods();
for (Method method:methods)
{
    String name=method.getName();
    if(name.startsWith("get"))
    {
        System.out.println(name.substring(3));
    }else if(name.startsWith("is"))
    {
        System.out.println(name.substring(2));
    }
}

However a more interesting approach is below:

With the help of Jackson library, I was able to find all class properties of type String/integer/double, and respective values in a Map class. (without using reflections api!)

TestClass testObject = new TestClass();
com.fasterxml.jackson.databind.ObjectMapper m = new com.fasterxml.jackson.databind.ObjectMapper();

Map<String,Object> props = m.convertValue(testObject, Map.class);

for(Map.Entry<String, Object> entry : props.entrySet()){
    if(entry.getValue() instanceof String || entry.getValue() instanceof Integer || entry.getValue() instanceof Double){
        System.out.println(entry.getKey() + "-->" + entry.getValue());
    }
}

How to set a variable to be "Today's" date in Python/Pandas

i got the same problem so tried so many things but finally this is the solution.

import time 

print (time.strftime("%d/%m/%Y"))

How long will my session last?

If session.cookie_lifetime is 0, the session cookie lives until the browser is quit.

EDIT: Others have mentioned the session.gc_maxlifetime setting. When session garbage collection occurs, the garbage collector will delete any session data that has not been accessed in longer than session.gc_maxlifetime seconds. To set the time-to-live for the session cookie, call session_set_cookie_params() or define the session.cookie_lifetime PHP setting. If this setting is greater than session.gc_maxlifetime, you should increase session.gc_maxlifetime to a value greater than or equal to the cookie lifetime to ensure that your sessions won't expire.

How to sort a list of objects based on an attribute of the objects?

It looks much like a list of Django ORM model instances.

Why not sort them on query like this:

ut = Tag.objects.order_by('-count')

Adding content to a linear layout dynamically?

In your onCreate(), write the following

LinearLayout myRoot = (LinearLayout) findViewById(R.id.my_root);
LinearLayout a = new LinearLayout(this);
a.setOrientation(LinearLayout.HORIZONTAL);
a.addView(view1);
a.addView(view2);
a.addView(view3);
myRoot.addView(a);

view1, view2 and view3 are your TextViews. They're easily created programmatically.

How do I draw a shadow under a UIView?

I use this as part of my utils. With this we can not only set shadow but also can get a rounded corner for any UIView. Also you could set what color shadow you prefer. Normally black is preferred but sometimes, when the background is non-white you might want something else. Here's what I use -

in utils.m
+ (void)roundedLayer:(CALayer *)viewLayer 
              radius:(float)r 
              shadow:(BOOL)s
{
    [viewLayer setMasksToBounds:YES];
    [viewLayer setCornerRadius:r];        
    [viewLayer setBorderColor:[RGB(180, 180, 180) CGColor]];
    [viewLayer setBorderWidth:1.0f];
    if(s)
    {
        [viewLayer setShadowColor:[RGB(0, 0, 0) CGColor]];
        [viewLayer setShadowOffset:CGSizeMake(0, 0)];
        [viewLayer setShadowOpacity:1];
        [viewLayer setShadowRadius:2.0];
    }
    return;
}

To use this we need to call this - [utils roundedLayer:yourview.layer radius:5.0f shadow:YES];

Laravel 5.4 redirection to custom url after login

you can add method in LoginController add line use App\User; on Top, after this add method, it is work for me wkwkwkwkw , but you must add {{ csrf_field() }} on view admin and user

protected function authenticated(Request $request, $user){

$user=User::where('email',$request->input('email'))->pluck('jabatan');
$c=" ".$user." ";
$a=strcmp($c,' ["admin"] ');

if ($a==0) {
    return redirect('admin');

}else{
    return redirect('user');

}}

EXCEL VBA Check if entry is empty or not 'space'

A common trick is to check like this:

trim(TextBox1.Value & vbnullstring) = vbnullstring

this will work for spaces, empty strings, and genuine null values

Ant is using wrong java version

In Eclipse:

  • Right click on your build.xml

  • click "Run As", click on "External Tool Configurations..."

  • Select tab JRE. Select the JRE you are using.

Re-run the task, it should be fine now.

Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<>

I had a column that did not allow nulls and I was inserting a null value.

How to solve Notice: Undefined index: id in C:\xampp\htdocs\invmgt\manufactured_goods\change.php on line 21

if you are getting id from url try

$id = (isset($_GET['id']) ? $_GET['id'] : '');

if getting from form you need to use POST method cause your form has method="post"

 $id = (isset($_POST['id']) ? $_POST['id'] : '');

For php notices use isset() or empty() to check values exist or not or initialize variable first with blank or a value

$id= '';

how to call a method in another Activity from Activity

public class ActivityB extends AppCompatActivity {

static Context mContext;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_b);

    try {

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String texto = bundle.getString("message");
            if (texto != null) {
              //code....
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void launch(String message) {
        Intent intent = new Intent(mContext, ActivityB.class);
        intent.putExtra("message", message);
        mContext.startActivity(intent);
    }
}

In ActivityA or Service.

public class Service extends Service{

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {    

        String text = "Value to send";
        ActivityB.launch(text);
        Log.d(TAG, text);
    }
}

Setting Inheritance and Propagation flags with set-acl and powershell

Here's a table to help find the required flags for different permission combinations.

    +-----------------------------------------------------------------------------------------------------------------------------------------------------------+
    ¦             ¦ folder only ¦ folder, sub-folders and files ¦ folder and sub-folders ¦ folder and files ¦ sub-folders and files ¦ sub-folders ¦    files    ¦
    ¦-------------+-------------+-------------------------------+------------------------+------------------+-----------------------+-------------+-------------¦
    ¦ Propagation ¦ none        ¦ none                          ¦ none                   ¦ none             ¦ InheritOnly           ¦ InheritOnly ¦ InheritOnly ¦
    ¦ Inheritance ¦ none        ¦ Container|Object              ¦ Container              ¦ Object           ¦ Container|Object      ¦ Container   ¦ Object      ¦
    +-----------------------------------------------------------------------------------------------------------------------------------------------------------+

So, as David said, you'll want

InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit
PropagationFlags.None

SQL Server 2005 Using CHARINDEX() To split a string

Try the following query:

DECLARE @item VARCHAR(MAX) = 'LD-23DSP-1430'

SELECT
SUBSTRING( @item, 0, CHARINDEX('-', @item)) ,
SUBSTRING(
               SUBSTRING( @item, CHARINDEX('-', @item)+1,LEN(@ITEM)) ,
               0 ,
               CHARINDEX('-', SUBSTRING( @item, CHARINDEX('-', @item)+1,LEN(@ITEM)))
              ),
REVERSE(SUBSTRING( REVERSE(@ITEM), 0, CHARINDEX('-', REVERSE(@ITEM))))

CREATE DATABASE permission denied in database 'master' (EF code-first)

Check that the connection string is in your Web.Config. I removed that node and put it in my Web.Debug.config and this is the error I received. Moved it back to the Web.config and worked great.

Google Maps v3 - limit viewable area and zoom level

For some reason

if (strictBounds.contains(map.getCenter())) return;

didnt work for me (maybe a southern hemisphere issue). I had to change it to:

    function checkBounds() {
        var c = map.getCenter(),
            x = c.lng(),
            y = c.lat(),
            maxX = strictBounds.getNorthEast().lng(),
            maxY = strictBounds.getNorthEast().lat(),
            minX = strictBounds.getSouthWest().lng(),
            minY = strictBounds.getSouthWest().lat();

        if(x < minX || x > maxX || y < minY || y > maxY) {
            if (x < minX) x = minX;
            if (x > maxX) x = maxX;
            if (y < minY) y = minY;
            if (y > maxY) y = maxY;
            map.setCenter(new google.maps.LatLng(y, x));
        }
    }

Hope it will help someone.

Renew Provisioning Profile

for Team Profile, simple in Prereference --> Account--->select the corret account-->detail-->click the left bottom 'refresh' button. the profile will be renewed.

How is Java platform-independent when it needs a JVM to run?

The JVM abstracts from the concrete platform. Your program relies only upon the JVM and since the JVM is available for different platforms like Windows and Linux, your program is platform independent (but jvm depended).

How many characters in varchar(max)

See the MSDN reference table for maximum numbers/sizes.

Bytes per varchar(max), varbinary(max), xml, text, or image column: 2^31-1

There's a two-byte overhead for the column, so the actual data is 2^31-3 max bytes in length. Assuming you're using a single-byte character encoding, that's 2^31-3 characters total. (If you're using a character encoding that uses more than one byte per character, divide by the total number of bytes per character. If you're using a variable-length character encoding, all bets are off.)

Using malloc for allocation of multi-dimensional arrays with different row lengths

If every element in b has different lengths, then you need to do something like:

int totalLength = 0;
for_every_element_in_b {
    totalLength += length_of_this_b_in_bytes;
}
return (char **)malloc(totalLength);

Count number of files within a directory in Linux?

this is one:

ls -l . | egrep -c '^-'

Note:

ls -1 | wc -l

Which means: ls: list files in dir

-1: (that's a ONE) only one entry per line. Change it to -1a if you want hidden files too

|: pipe output onto...

wc: "wordcount"

-l: count lines.

SHOW PROCESSLIST in MySQL command: sleep

"Sleep" state connections are most often created by code that maintains persistent connections to the database.

This could include either connection pools created by application frameworks, or client-side database administration tools.

As mentioned above in the comments, there is really no reason to worry about these connections... unless of course you have no idea where the connection is coming from.

(CAVEAT: If you had a long list of these kinds of connections, there might be a danger of running out of simultaneous connections.)

Count number of occurrences for each unique value

You should change the query to:

SELECT time_col, COUNT(time_col) As Count
FROM time_table
WHERE activity_col = 3
GROUP BY time_col

This vl works correctly.

How do I create sql query for searching partial matches?

First of all, this approach won't scale in the large, you'll need a separate index from words to item (like an inverted index).

If your data is not large, you can do

SELECT DISTINCT(name) FROM mytable WHERE name LIKE '%mall%' OR description LIKE '%mall%'

using OR if you have multiple keywords.

Failed to resolve: com.android.support:appcompat-v7:28.0

implementation 'com.android.support:appcompat-v7:28.0' implementation 'com.android.support:support-media-compat:28.0.0' implementation 'com.android.support:support-v4:28.0.0' All to add

Using ORDER BY and GROUP BY together

Here is the simplest solution

select m_id,v_id,max(timestamp) from table group by m_id;

Group by m_id but get max of timestamp for each m_id.

How do I rename a file using VBScript?

You can rename the file using FSO by moving it: MoveFile Method.

Dim Fso
Set Fso = WScript.CreateObject("Scripting.FileSystemObject")
Fso.MoveFile "A.txt", "B.txt"

How to get access token from FB.login method in javascript SDK

If you are already connected, simply type this in the javascript console:

FB.getAuthResponse()['accessToken']

How to pretty print XML from the command line?

You can also use tidy, which may need to be installed first (e.g. on Ubuntu: sudo apt-get install tidy).

For this, you would issue something like following:

tidy -xml -i your-file.xml > output.xml

Note: has many additional readability flags, but word-wrap behavior is a bit annoying to untangle (http://tidy.sourceforge.net/docs/quickref.html).

Solve Cross Origin Resource Sharing with Flask

You can get the results with a simple:

@app.route('your route', methods=['GET'])
def yourMethod(params):
    response = flask.jsonify({'some': 'data'})
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response

How to Import .bson file format on mongodb

I have used this:

mongorestore -d databasename -c file.bson fullpath/file.bson

1.copy the file path and file name from properties (try to put all bson files in different folder), 2.use this again and again with changing file name only.

Sorting int array in descending order

If it's not a big/long array just mirror it:

for( int i = 0; i < arr.length/2; ++i ) 
{ 
  temp = arr[i]; 
  arr[i] = arr[arr.length - i - 1]; 
  arr[arr.length - i - 1] = temp; 
}

MySQL - SELECT * INTO OUTFILE LOCAL ?

Since I find myself rather regularly looking for this exact problem (in the hopes I missed something before...), I finally decided to take the time and write up a small gist to export MySQL queries as CSV files, kinda like https://stackoverflow.com/a/28168869 but based on PHP and with a couple of more options. This was important for my use case, because I need to be able to fine-tune the CSV parameters (delimiter, NULL value handling) AND the files need to be actually valid CSV, so that a simple CONCAT is not sufficient since it doesn't generate valid CSV files if the values contain line breaks or the CSV delimiter.

Caution: Requires PHP to be installed on the server! (Can be checked via php -v)

"Install" mysql2csv via

wget https://gist.githubusercontent.com/paslandau/37bf787eab1b84fc7ae679d1823cf401/raw/29a48bb0a43f6750858e1ddec054d3552f3cbc45/mysql2csv -O mysql2csv -q && (sha256sum mysql2csv | cmp <(echo "b109535b29733bd596ecc8608e008732e617e97906f119c66dd7cf6ab2865a65  mysql2csv") || (echo "ERROR comparing hash, Found:" ;sha256sum mysql2csv) ) && chmod +x mysql2csv

(download content of the gist, check checksum and make it executable)

Usage example

./mysql2csv --file="/tmp/result.csv" --query='SELECT 1 as foo, 2 as bar;' --user="username" --password="password"

generates file /tmp/result.csv with content

foo,bar
1,2

help for reference

./mysql2csv --help
Helper command to export data for an arbitrary mysql query into a CSV file.
Especially helpful if the use of "SELECT ... INTO OUTFILE" is not an option, e.g.
because the mysql server is running on a remote host.

Usage example:
./mysql2csv --file="/tmp/result.csv" --query='SELECT 1 as foo, 2 as bar;' --user="username" --password="password"

cat /tmp/result.csv

Options:
        -q,--query=name [required]
                The query string to extract data from mysql.
        -h,--host=name
                (Default: 127.0.0.1) The hostname of the mysql server.
        -D,--database=name
                The default database.
        -P,--port=name
                (Default: 3306) The port of the mysql server.
        -u,--user=name
                The username to connect to the mysql server.
        -p,--password=name
                The password to connect to the mysql server.
        -F,--file=name
                (Default: php://stdout) The filename to export the query result to ('php://stdout' prints to console).
        -L,--delimiter=name
                (Default: ,) The CSV delimiter.
        -C,--enclosure=name
                (Default: ") The CSV enclosure (that is used to enclose values that contain special characters).
        -E,--escape=name
                (Default: \) The CSV escape character.
        -N,--null=name
                (Default: \N) The value that is used to replace NULL values in the CSV file.
        -H,--header=name
                (Default: 1) If '0', the resulting CSV file does not contain headers.
        --help
                Prints the help for this command.

How to put/get multiple JSONObjects to JSONArray?

From android API Level 19, when I want to instance JSONArray object I put JSONObject directly as parameter like below:

JSONArray jsonArray=new JSONArray(jsonObject);

JSONArray has constructor to accept object.

Java Compare Two Lists

public static boolean compareList(List ls1, List ls2){
    return ls1.containsAll(ls2) && ls1.size() == ls2.size() ? true :false;
     }

public static void main(String[] args) {

    ArrayList<String> one = new ArrayList<String>();
    one.add("one");
    one.add("two");
    one.add("six");

    ArrayList<String> two = new ArrayList<String>();
    two.add("one");
    two.add("six");
    two.add("two");

    System.out.println("Output1 :: " + compareList(one, two));

    two.add("ten");

    System.out.println("Output2 :: " + compareList(one, two));
  }

Get decimal portion of a number with JavaScript

How is 0.2999999999999998 an acceptable answer? If I were the asker I would want an answer of .3. What we have here is false precision, and my experiments with floor, %, etc indicate that Javascript is fond of false precision for these operations. So I think the answers that are using conversion to string are on the right track.

I would do this:

var decPart = (n+"").split(".")[1];

Specifically, I was using 100233.1 and I wanted the answer ".1".

Where can I view Tomcat log files in Eclipse?

Go to the "Server" view, then double-click the Tomcat server you're running. The access log files are stored relative to the path in the "Server path" field, which itself is relative to the workspace path.

How do I modify a MySQL column to allow NULL?

Your syntax error is caused by a missing "table" in the query

ALTER TABLE mytable MODIFY mycolumn varchar(255) null;

How to use Monitor (DDMS) tool to debug application

I think that I got a solution for this. You don't have to start monitor but you can use DDMS instead almost like in Eclipse.

Start Android Studio-> pick breakpoint-> Run-> Debug-> Go to %sdk\tools in Terminal window and run ddms.bat to run DDMS without Monitor running (since it won't let you run ADB). You can now start profiling or debug step-by-step.

Hope this helps you.

See image here

Mocha / Chai expect.to.throw not catching thrown errors

This question has many, many duplicates, including questions not mentioning the Chai assertion library. Here are the basics collected together:

The assertion must call the function, instead of it evaluating immediately.

assert.throws(x.y.z);      
   // FAIL.  x.y.z throws an exception, which immediately exits the
   // enclosing block, so assert.throw() not called.
assert.throws(()=>x.y.z);  
   // assert.throw() is called with a function, which only throws
   // when assert.throw executes the function.
assert.throws(function () { x.y.z });   
   // if you cannot use ES6 at work
function badReference() { x.y.z }; assert.throws(badReference);  
   // for the verbose
assert.throws(()=>model.get(z));  
   // the specific example given.
homegrownAssertThrows(model.get, z);
   //  a style common in Python, but not in JavaScript

You can check for specific errors using any assertion library:

Node

  assert.throws(() => x.y.z);
  assert.throws(() => x.y.z, ReferenceError);
  assert.throws(() => x.y.z, ReferenceError, /is not defined/);
  assert.throws(() => x.y.z, /is not defined/);
  assert.doesNotThrow(() => 42);
  assert.throws(() => x.y.z, Error);
  assert.throws(() => model.get.z, /Property does not exist in model schema./)

Should

  should.throws(() => x.y.z);
  should.throws(() => x.y.z, ReferenceError);
  should.throws(() => x.y.z, ReferenceError, /is not defined/);
  should.throws(() => x.y.z, /is not defined/);
  should.doesNotThrow(() => 42);
  should.throws(() => x.y.z, Error);
  should.throws(() => model.get.z, /Property does not exist in model schema./)

Chai Expect

  expect(() => x.y.z).to.throw();
  expect(() => x.y.z).to.throw(ReferenceError);
  expect(() => x.y.z).to.throw(ReferenceError, /is not defined/);
  expect(() => x.y.z).to.throw(/is not defined/);
  expect(() => 42).not.to.throw();
  expect(() => x.y.z).to.throw(Error);
  expect(() => model.get.z).to.throw(/Property does not exist in model schema./);

You must handle exceptions that 'escape' the test

it('should handle escaped errors', function () {
  try {
    expect(() => x.y.z).not.to.throw(RangeError);
  } catch (err) {
    expect(err).to.be.a(ReferenceError);
  }
});

This can look confusing at first. Like riding a bike, it just 'clicks' forever once it clicks.

Best way to test exceptions with Assert to ensure they will be thrown

With most .net unit testing frameworks you can put an [ExpectedException] attribute on the test method. However this can't tell you that the exception happened at the point you expected it to. That's where xunit.net can help.

With xunit you have Assert.Throws, so you can do things like this:

    [Fact]
    public void CantDecrementBasketLineQuantityBelowZero()
    {
        var o = new Basket();
        var p = new Product {Id = 1, NetPrice = 23.45m};
        o.AddProduct(p, 1);
        Assert.Throws<BusinessException>(() => o.SetProductQuantity(p, -3));
    }

[Fact] is the xunit equivalent of [TestMethod]

Cannot overwrite model once compiled Mongoose

Here is one more reason why this can happen. Perhaps this can help someone else. Notice the difference, Members vs Member. They must be the same...

export default mongoose.models.Members || mongoose.model('Member', FamilySchema)

Change to:

export default mongoose.models.Member || mongoose.model('Member', FamilySchema)

Understanding dispatch_async

The main reason you use the default queue over the main queue is to run tasks in the background.

For instance, if I am downloading a file from the internet and I want to update the user on the progress of the download, I will run the download in the priority default queue and update the UI in the main queue asynchronously.

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
    //Background Thread
    dispatch_async(dispatch_get_main_queue(), ^(void){
        //Run UI Updates
    });
});

Child element click event trigger the parent click event

The stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event.

You can use the method event.isPropagationStopped() to know whether this method was ever called (on that event object).

Syntax:

Here is the simple syntax to use this method:

event.stopPropagation() 

Example:

$("div").click(function(event) {
    alert("This is : " + $(this).prop('id'));

    // Comment the following to see the difference
    event.stopPropagation();
});?

Check if a number is a perfect square

I just posted a slight variation on some of the examples above on another thread (Finding perfect squares) and thought I'd include a slight variation of what I posted there here (using nsqrt as a temporary variable), in case it's of interest / use:

import math

def is_square(n):
  if not (isinstance(n, int) and (n >= 0)):
    return False 
  else:
    nsqrt = math.sqrt(n)
    return nsqrt == math.trunc(nsqrt)

It is incorrect for a large non-square such as 152415789666209426002111556165263283035677490.

Scatter plot and Color mapping in Python

Here is an example

import numpy as np
import matplotlib.pyplot as plt

x = np.random.rand(100)
y = np.random.rand(100)
t = np.arange(100)

plt.scatter(x, y, c=t)
plt.show()

Here you are setting the color based on the index, t, which is just an array of [1, 2, ..., 100]. enter image description here

Perhaps an easier-to-understand example is the slightly simpler

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(100)
y = x
t = x
plt.scatter(x, y, c=t)
plt.show()

enter image description here

Note that the array you pass as c doesn't need to have any particular order or type, i.e. it doesn't need to be sorted or integers as in these examples. The plotting routine will scale the colormap such that the minimum/maximum values in c correspond to the bottom/top of the colormap.

Colormaps

You can change the colormap by adding

import matplotlib.cm as cm
plt.scatter(x, y, c=t, cmap=cm.cmap_name)

Importing matplotlib.cm is optional as you can call colormaps as cmap="cmap_name" just as well. There is a reference page of colormaps showing what each looks like. Also know that you can reverse a colormap by simply calling it as cmap_name_r. So either

plt.scatter(x, y, c=t, cmap=cm.cmap_name_r)
# or
plt.scatter(x, y, c=t, cmap="cmap_name_r")

will work. Examples are "jet_r" or cm.plasma_r. Here's an example with the new 1.5 colormap viridis:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(100)
y = x
t = x
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.scatter(x, y, c=t, cmap='viridis')
ax2.scatter(x, y, c=t, cmap='viridis_r')
plt.show()

enter image description here

Colorbars

You can add a colorbar by using

plt.scatter(x, y, c=t, cmap='viridis')
plt.colorbar()
plt.show()

enter image description here

Note that if you are using figures and subplots explicitly (e.g. fig, ax = plt.subplots() or ax = fig.add_subplot(111)), adding a colorbar can be a bit more involved. Good examples can be found here for a single subplot colorbar and here for 2 subplots 1 colorbar.

How to test if a list contains another list?

The problem of most of the answers, that they are good for unique items in list. If items are not unique and you still want to know whether there is an intersection, you should count items:

from collections import Counter as count

def listContains(l1, l2):
  list1 = count(l1)
  list2 = count(l2)

  return list1&list2 == list1

print( listContains([1,1,2,5], [1,2,3,5,1,2,1]) ) # Returns True
print( listContains([1,1,2,8], [1,2,3,5,1,2,1]) ) # Returns False

You can also return the intersection by using ''.join(list1&list2)

JavaScript set object key by variable

You need to make the object first, then use [] to set it.

var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);

UPDATE 2018:

If you're able to use ES6 and Babel, you can use this new feature:

{
    [yourKeyVariable]: someValueArray,
}  

cannot import name patterns

You don't need those imports. The only thing you need in your urls.py (to start) is:

from django.conf.urls.defaults import *

# This two if you want to enable the Django Admin: (recommended)
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    # ... your url patterns
)

NOTE: This solution was intended for Django <1.6. This was actually the code generated by Django itself. For newer version, see Jacob Hume's answer.

How to read a single char from the console in Java (as the user types it)?

Use jline3:

Example:

Terminal terminal = TerminalBuilder.builder()
    .jna(true)
    .system(true)
    .build();

// raw mode means we get keypresses rather than line buffered input
terminal.enterRawMode();
reader = terminal .reader();
...
int read = reader.read();
....
reader.close();
terminal.close();

How to add icon inside EditText view in Android ?

Use :

<EditText
    ..     
    android:drawableStart="@drawable/icon" />

Python lookup hostname from IP with 1 second timeout

>>> import socket
>>> socket.gethostbyaddr("69.59.196.211")
('stackoverflow.com', ['211.196.59.69.in-addr.arpa'], ['69.59.196.211'])

For implementing the timeout on the function, this stackoverflow thread has answers on that.

Is it possible to add an HTML link in the body of a MAILTO link

It isn't possible as far as I can tell, since a link needs HTML, and mailto links don't create an HTML email.

This is probably for security as you could add javascript or iframes to this link and the email client might open up the end user for vulnerabilities.

Read a file line by line with VB.NET

Replaced the reader declaration with this one and now it works!

Dim reader As New StreamReader(filetoimport.Text, Encoding.Default)

Encoding.Default represents the ANSI code page that is set under Windows Control Panel.

How do I create a basic UIButton programmatically?

To add a button programatically to your controller's view, use the following:

-(void)viewDidLoad
{
   UIButton * btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
   btn.frame = CGRectMake(0, 0, 100, 50);
   [btn setTitle:@"Hello, world!" forState:UIControlStateNormal];
   [self.view addSubview:btn];
}

To add three of these, rinse and repeat.

How can I take a screenshot with Selenium WebDriver?

Python

Each WebDriver has a .save_screenshot(filename) method. So for Firefox, it can be used like this:

from selenium import webdriver

browser = webdriver.Firefox()
browser.get('http://www.google.com/')
browser.save_screenshot('screenie.png')

Confusingly, a .get_screenshot_as_file(filename) method also exists that does the same thing.

There are also methods for: .get_screenshot_as_base64() (for embedding in HTML) and .get_screenshot_as_png()(for retrieving binary data).

And note that WebElements have a .screenshot() method that works similarly, but only captures the selected element.

How to Empty Caches and Clean All Targets Xcode 4 and later

I tried almost everything but could not help,what helped me was disabling SIP(System Integration Protection) n it works,I do not know what happens when and how but system file get confused somewhere and causes this...though there might be risks to disabling this obviously

here is how

1.Power on your Mac and hold down the [command]+[R] keys to access the Recovery Partition.

2.From the Recovery Partition, click Utilities from the menu bar, and then select Terminal.

3.Enter the following command into Terminal and press Enter to execute it: csrutil disable

4.Once the command has executed, exit the Terminal and reboot the Mac. When you log back into OS X, SIP will be disabled.

Postgresql: password authentication failed for user "postgres"

Answer given is almost correct just missing some pointers which i'll be taking care of in my solution

First make sure your user have a sudo access if not you can use the below command to add your user as sudo user :-

sudo adduser <username> sudo

The change will take effect the next time the user logs in.

i) Now go to sudo vim /etc/postgresql/<your_postgres_version>/main/pg_hba.conf file and look for line that says :

local   all             postgres                                md5 #peer

and comment that. Just below that line there must be a commented line that says:

local   all             postgres                                peer

or for older versions it'll be :-

local   all         postgres                          ident

Uncomment that line.

ii) Now restart the postgres by using any of these commands :-

sudo /etc/init.d/postgresql restart

OR

sudo service postgresql restart

iii) Now you can simply log into postgres using the following command :

sudo -u postgres psql

iv) once you're in you can create any operation you want to in my case i wanted to create a new database you can do the same using below command :

CREATE DATABASE airflow_replica;

How to find the serial port number on Mac OS X?

Found the port esp32 was connected to by -

ls /dev/*

You would get a long list and you can find the port you need

Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on

I know its too late now. However even today if you are having trouble accessing cross thread controls? This is the shortest answer till date :P

Invoke(new Action(() =>
                {
                    label1.Text = "WooHoo!!!";
                }));

This is how i access any form control from a thread.

What could cause java.lang.reflect.InvocationTargetException?

The exception is thrown if

InvocationTargetException - if the underlying method throws an exception.

So if the method, that has been invoked with reflection API, throws an exception (runtime exception for example), the reflection API will wrap the exception into an InvocationTargetException.

explode string in jquery

The split method will create an array. So you need to access the third element in your case..

(arrays are 0-indexed) You need to access result[2] to get the url

var result = $(row).text().split('|');
alert( result[2] );

You do not give us enough information to know what row is, exactly.. So depending on how you acquire the variable row you might need to do one of the following.

  • if row is a string then row.split('|');
  • if it is a DOM element then $(row).text().split('|');
  • if it is an input element then $(row).val().split('|');

Escaping ampersand character in SQL string

You can use

set define off

Using this it won't prompt for the input

Speed tradeoff of Java's -Xms and -Xmx options

The -Xmx argument defines the max memory size that the heap can reach for the JVM. You must know your program well and see how it performs under load and set this parameter accordingly. A low value can cause OutOfMemoryExceptions or a very poor performance if your program's heap memory is reaching the maximum heap size. If your program is running in dedicated server you can set this parameter higher because it wont affect other programs.

The -Xms argument sets the initial heap memory size for the JVM. This means that when you start your program the JVM will allocate this amount of memory instantly. This is useful if your program will consume a large amount of heap memory right from the start. This avoids the JVM to be constantly increasing the heap and can gain some performance there. If you don't know if this parameter is going to help you, don't use it.

In summary, this is a compromise that you have to decide based only in the memory behavior of your program.

Delete all records in a table of MYSQL in phpMyAdmin

You have 2 options delete and truncate :

  1. delete from mytable

    This will delete all the content of the table, not reseting the autoincremental id, this process is very slow. If you want to delete specific records append a where clause at the end.

  2. truncate myTable

    This will reset the table i.e. all the auto incremental fields will be reset. Its a DDL and its very fast. You cannot delete any specific record through truncate.

Video 100% width and height

By checking other answers, I used object-fit in CSS:

video {
    object-fit: fill;
}

From MDN (https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit):

The object-fit CSS property specifies how the contents of a replaced element should be fitted to the box established by its used height and width.

Value: fill

The replaced content is sized to fill the element’s content box: the object’s concrete object size is the element’s used width and height.

How to get client IP address using jQuery

jQuery can handle JSONP, just pass an url formatted with the callback=? parameter to the $.getJSON method, for example:

_x000D_
_x000D_
$.getJSON("https://api.ipify.org/?format=json", function(e) {_x000D_
    console.log(e.ip);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

This example is of a really simple JSONP service implemented on with api.ipify.org.

If you aren't looking for a cross-domain solution the script can be simplified even more, since you don't need the callback parameter, and you return pure JSON.

Java Enum return Int

Simply call the ordinal() method on an enum value, to retrieve its corresponding number. There's no need to declare an addition attribute with its value, each enumerated value gets its own number by default, assigned starting from zero, incrementing by one for each value in the same order they were declared.

You shouldn't depend on the int value of an enum, only on its actual value. Enums in Java are a different kind of monster and are not like enums in C, where you depend on their integer code.

Regarding the example you provided in the question, Font.PLAIN works because that's just an integer constant of the Font class. If you absolutely need a (possibly changing) numeric code, then an enum is not the right tool for the job, better stick to numeric constants.

Please explain about insertable=false and updatable=false in reference to the JPA @Column annotation

You would do that when the responsibility of creating/updating the referenced column isn't in the current entity, but in another entity.

How to test abstract class in Java with JUnit?

Create a concrete class that inherits the abstract class and then test the functions the concrete class inherits from the abstract class.

Test if a variable is a list or tuple

How about: hasattr(a, "__iter__") ?

It tells if the object returned can be iterated over as a generator. By default, tuples and lists can, but not the string types.

How do I convert a Python program to a runnable .exe Windows program?

I use cx_Freeze. Works with Python 2 and 3, and I have tested it to work on Windows, Mac, and Linux.

cx_Freeze: http://cx-freeze.sourceforge.net/

Get yesterday's date using Date

Try this one:

private String toDate() {
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

    // Create a calendar object with today date. Calendar is in java.util pakage.
    Calendar calendar = Calendar.getInstance();

    // Move calendar to yesterday
    calendar.add(Calendar.DATE, -1);

    // Get current date of calendar which point to the yesterday now
    Date yesterday = calendar.getTime();

    return dateFormat.format(yesterday).toString();
}

Getting Error "Form submission canceled because the form is not connected"

I see you are using jQuery for the form initialization.

When I try @KyungHun Jeon's answer, it doesn't work for me that use jQuery too.

So, I tried appending the form to the body by using the jQuery way:

$(document.body).append(form);

And it worked!

Why doesn't document.addEventListener('load', function) work in a greasemonkey script?

Apparently, document.addEventListener() is unreliable, and hence, my error. Use window.addEventListener() with the same parameters, instead.

Save image from url with curl PHP

Option #1

Instead of picking the binary/raw data into a variable and then writing, you can use CURLOPT_FILE option to directly show a file to the curl for the downloading.

Here is the function:

// takes URL of image and Path for the image as parameter
function download_image1($image_url, $image_file){
    $fp = fopen ($image_file, 'w+');              // open file handle

    $ch = curl_init($image_url);
    // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // enable if you want
    curl_setopt($ch, CURLOPT_FILE, $fp);          // output to file
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 1000);      // some large value to allow curl to run for a long time
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
    // curl_setopt($ch, CURLOPT_VERBOSE, true);   // Enable this line to see debug prints
    curl_exec($ch);

    curl_close($ch);                              // closing curl handle
    fclose($fp);                                  // closing file handle
}

And here is how you should call it:

// test the download function
download_image1("http://www.gravatar.com/avatar/10773ae6687b55736e171c038b4228d2", "local_image1.jpg");

Option #2

Now, If you want to download a very large file, that case above function may not become handy. You can use the below function this time for handling a big file. Also, you can print progress(in % or in any other format) if you want. Below function is implemented using a callback function that writes a chunk of data in to the file in to the progress of downloading.

// takes URL of image and Path for the image as parameter
function download_image2($image_url){
    $ch = curl_init($image_url);
    // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // enable if you want
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 1000);      // some large value to allow curl to run for a long time
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
    curl_setopt($ch, CURLOPT_WRITEFUNCTION, "curl_callback");
    // curl_setopt($ch, CURLOPT_VERBOSE, true);   // Enable this line to see debug prints
    curl_exec($ch);

    curl_close($ch);                              // closing curl handle
}

/** callback function for curl */
function curl_callback($ch, $bytes){
    global $fp;
    $len = fwrite($fp, $bytes);
    // if you want, you can use any progress printing here
    return $len;
}

And here is how to call this function:

// test the download function
$image_file = "local_image2.jpg";
$fp = fopen ($image_file, 'w+');              // open file handle
download_image2("http://www.gravatar.com/avatar/10773ae6687b55736e171c038b4228d2");
fclose($fp);                                  // closing file handle

Round a floating-point number down to the nearest integer?

x//1

The // operator returns the floor of the division. Since dividing by 1 doesn't change your number, this is equivalent to floor but no import is needed. Notes:

  1. This returns a float
  2. This rounds towards -8

Python group by

result = []
# Make a set of your "types":
input_set = set([tpl[1] for tpl in input])
>>> set(['ETH', 'KAT', 'NOT'])
# Iterate over the input_set
for type_ in input_set:
    # a dict to gather things:
    D = {}
    # filter all tuples from your input with the same type as type_
    tuples = filter(lambda tpl: tpl[1] == type_, input)
    # write them in the D:
    D["type"] = type_
    D["itmes"] = [tpl[0] for tpl in tuples]
    # append D to results:
    result.append(D)

result
>>> [{'itmes': ['9085267', '11788544'], 'type': 'NOT'}, {'itmes': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}, {'itmes': ['11013331', '9843236'], 'type': 'KAT'}]

git reset --hard HEAD leaves untracked files behind

You can use git stash. You have to specify --include-untracked, otherwise you'll end up with the original problem.

git stash --include-untracked

Then just drop the last entry in the stash

git stash drop

You can make a handy-dandy alias for that, and call it git discard for example:

git config --global alias.discard "! git stash -q --include-untracked && git stash drop -q"

Vertical Align text in a Label

Vertical alignment only works with inline or inline-block elements, and it's only relative to other inline[-block] elements. Because you float the label, it becomes a block element.

The simplest solution in your case is to set the label to display: inline-block and add vertical-align: middle to the labels and the inputs. (You might find that the height of the text is such that vertical align won't make any difference anyway.)

How to set the text color of TextView in code?

getColor() is depreceted

So try this way:

 tv_title.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.sf_white));

Reload the page after ajax success

BrixenDK is right.

.ajaxStop() callback executed when all ajax call completed. This is a best place to put your handler.

$(document).ajaxStop(function(){
    window.location.reload();
});

How do I directly modify a Google Chrome Extension File? (.CRX)

If you have installed the Portable version of Chrome, or have it installed in a custom directory - the extensions won't be available in directory referenced in above answers.

Try right-clicking on Chrome's shortcut & Check the "Target" directory. From there, navigate to one directory above and you should be able to see the User Data folder and then can use the answers mentioned above

How to echo with different colors in the Windows command line

We used to do this with ANSI terminal codes. Not sure if they still work, but you could try them.

How to zip a whole folder using PHP

I assume this is running on a server where the zip application is in the search path. Should be true for all unix-based and I guess most windows-based servers.

exec('zip -r archive.zip "My folder"');
unlink('My\ folder/index.html');
unlink('My\ folder/picture.jpg');

The archive will reside in archive.zip afterwards. Keep in mind that blanks in file or folder names are a common cause of errors and should be avoided where possible.

Git commit -a "untracked files"?

For others having the same problem, try running

git add . which will add all files of the current directory to track (including untracked) and then use

git commit -a to commit all tracked files.

As suggested by @Pacerier, one liner that does the same thing is

git add -A

Storing sex (gender) in database

I use char 'f', 'm' and 'u' because I surmise the gender from name, voice and conversation, and sometimes don't know the gender. The final determination is their opinion.

It really depends how well you know the person and whether your criteria is physical form or personal identity. A psychologist might need additional options - cross to female, cross to male, trans to female, trans to male, hermaphrodite and undecided. With 9 options, not clearly defined by a single character, I might go with Hugo's advice of tiny integer.

Flask-SQLAlchemy how to delete all rows in a single table

Try delete:

models.User.query.delete()

From the docs: Returns the number of rows deleted, excluding any cascades.

Command to change the default home directory of a user

Ibrahim's comment on the other answer is the correct way to alter an existing user's home directory.

Change the user's home directory:

usermod -d /newhome/username username

usermod is the command to edit an existing user.
-d (abbreviation for --home) will change the user's home directory.

Change the user's home directory + Move the contents of the user's current directory:

usermod -m -d /newhome/username username

-m (abbreviation for --move-home) will move the content from the user's current directory to the new directory.

ValueError: Length of values does not match length of index | Pandas DataFrame.unique()

The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:

A data frame of four rows:

df = pd.DataFrame({'A': [1,2,3,4]})

Now trying to assign a list/array of two elements to it:

df['B'] = [3,4]   # or df['B'] = np.array([3,4])

Both errors out:

ValueError: Length of values does not match length of index

Because the data frame has four rows but the list and array has only two elements.

Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:

df['B'] = pd.Series([3,4])

df
#   A     B
#0  1   3.0
#1  2   4.0
#2  3   NaN          # NaN because the value at index 2 and 3 doesn't exist in the Series
#3  4   NaN

For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:

df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))

#   A     B
#0  1   1.0
#1  2   5.0
#2  7   9.0
#3  8   NaN

How to check if a line has one of the strings in a list?

One approach is to combine the search strings into a regex pattern as in this answer.

How to insert new row to database with AUTO_INCREMENT column without specifying column names?

For some databases, you can just explicitly insert a NULL into the auto_increment column:

INSERT INTO table_name VALUES (NULL, 'my name', 'my group')

What is exactly the base pointer and stack pointer? To what do they point?

esp stands for "Extended Stack Pointer".....ebp for "Something Base Pointer"....and eip for "Something Instruction Pointer"...... The stack Pointer points to the offset address of the stack segment. The Base Pointer points to the offset address of the extra segment. The Instruction Pointer points to the offset address of the code segment. Now, about the segments...they are small 64KB divisions of the processors memory area.....This process is known as Memory Segmentation. I hope this post was helpful.

How stable is the git plugin for eclipse?

There is also gitclipse(based on JavaGit), but seems dead.

In C++, what is a virtual base class?

Virtual classes are not the same as virtual inheritance. Virtual classes you cannot instantiate, virtual inheritance is something else entirely.

Wikipedia describes it better than I can. http://en.wikipedia.org/wiki/Virtual_inheritance

Draw path between two points using Google Maps Android API v2

in below code midpointsList is an ArrayList of waypoints

private String getMapsApiDirectionsUrl(GoogleMap googleMap, LatLng startLatLng, LatLng endLatLng, ArrayList<LatLng> midpointsList) {
    String origin = "origin=" + startLatLng.latitude + "," + startLatLng.longitude;

    String midpoints = "";
    for (int mid = 0; mid < midpointsList.size(); mid++) {
        midpoints += "|" + midpointsList.get(mid).latitude + "," + midpointsList.get(mid).longitude;
    }

    String waypoints = "waypoints=optimize:true" + midpoints + "|";

    String destination = "destination=" + endLatLng.latitude + "," + endLatLng.longitude;
    String key = "key=AIzaSyCV1sOa_7vASRBs6S3S6t1KofFvDhjohvI";

    String sensor = "sensor=false";
    String params = origin + "&" + waypoints + "&" + destination + "&" + sensor + "&" + key;
    String output = "json";
    String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + params;


    Log.e("url", url);
    parseDirectionApidata(url, googleMap);
    return url;
}

Then copy and paste this url in your browser to check And the below code is to parse the url

    private void parseDirectionApidata(String url, final GoogleMap googleMap) {

    final JSONObject jsonObject = new JSONObject();

    try {

        AppUtill.getJsonWithHTTPPost(ViewMapActivity.this, 1, new ServiceCallBack() {
            @Override
            public void serviceCallBack(int id, JSONObject jsonResult) throws JSONException {

                if (jsonResult != null) {

                    Log.e("jsonRes", jsonResult.toString());

                    String status = jsonResult.optString("status");

                    if (status.equalsIgnoreCase("ok")) {
                        drawPath(jsonResult, googleMap);
                    }

                } else {

                    Toast.makeText(ViewMapActivity.this, "Unable to parse Directions Data", Toast.LENGTH_LONG).show();
                }

            }
        }, url, jsonObject);

    } catch (Exception e) {
        e.printStackTrace();

    }
}

And then pass the result to the drawPath method

    public void drawPath(JSONObject jObject, GoogleMap googleMap) {

    List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String, String>>>();
    JSONArray jRoutes = null;
    JSONArray jLegs = null;
    JSONArray jSteps = null;
    List<LatLng> list = null;
    try {

        Toast.makeText(ViewMapActivity.this, "Drawing Path...", Toast.LENGTH_SHORT).show();
        jRoutes = jObject.getJSONArray("routes");

        /** Traversing all routes */
        for (int i = 0; i < jRoutes.length(); i++) {
            jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
            List path = new ArrayList<HashMap<String, String>>();

            /** Traversing all legs */
            for (int j = 0; j < jLegs.length(); j++) {
                jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");

                /** Traversing all steps */
                for (int k = 0; k < jSteps.length(); k++) {
                    String polyline = "";
                    polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
                    list = decodePoly(polyline);
                }
                Log.e("list", list.toString());
                routes.add(path);
                Log.e("routes", routes.toString());
                if (list != null) {
                    Polyline line = googleMap.addPolyline(new PolylineOptions()
                            .addAll(list)
                            .width(12)
                            .color(Color.parseColor("#FF0000"))//Google maps blue color #05b1fb
                            .geodesic(true)
                    );
                }
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

}

  private List<LatLng> decodePoly(String encoded) {

    List<LatLng> poly = new ArrayList<LatLng>();
    int index = 0, len = encoded.length();
    int lat = 0, lng = 0;

    while (index < len) {
        int b, shift = 0, result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lat += dlat;

        shift = 0;
        result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lng += dlng;

        LatLng p = new LatLng((((double) lat / 1E5)),
                (((double) lng / 1E5)));
        poly.add(p);
    }

    return poly;
}

decode poly function is to decode the points(lat and long) provided by Directions API in encoded form

Image vs zImage vs uImage

What is the difference between them?

Image: the generic Linux kernel binary image file.

zImage: a compressed version of the Linux kernel image that is self-extracting.

uImage: an image file that has a U-Boot wrapper (installed by the mkimage utility) that includes the OS type and loader information.
A very common practice (e.g. the typical Linux kernel Makefile) is to use a zImage file. Since a zImage file is self-extracting (i.e. needs no external decompressors), the wrapper would indicate that this kernel is "not compressed" even though it actually is.


Note that the author/maintainer of U-Boot considers the (widespread) use of using a zImage inside a uImage questionable:

Actually it's pretty stupid to use a zImage inside an uImage. It is much better to use normal (uncompressed) kernel image, compress it using just gzip, and use this as poayload for mkimage. This way U-Boot does the uncompresiong instead of including yet another uncompressor with each kernel image.

(quoted from https://lists.yoctoproject.org/pipermail/yocto/2013-October/016778.html)


Which type of kernel image do I have to use?

You could choose whatever you want to program for.
For economy of storage, you should probably chose a compressed image over the uncompressed one.
Beware that executing the kernel (presumably the Linux kernel) involves more than just loading the kernel image into memory. Depending on the architecture (e.g. ARM) and the Linux kernel version (e.g. with or without DTB), there are registers and memory buffers that may have to be prepared for the kernel. In one instance there was also hardware initialization that U-Boot performed that had to be replicated.

ADDENDUM

I know that u-boot needs a kernel in uImage format.

That is accurate for all versions of U-Boot which only have the bootm command.
But more recent versions of U-Boot could also have the bootz command that can boot a zImage.

setting request headers in selenium

If you use the HtmlUnitDriver, you can set request headers by modifying the WebClient, like so:

final case class Header(name: String, value: String)

final class HtmlUnitDriverWithHeaders(headers: Seq[Header]) extends HtmlUnitDriver {
  super.modifyWebClient {
    val client = super.getWebClient
    headers.foreach(h => client.addRequestHeader(h.name, h.value))
    client
  }
}

The headers will then be on all requests made by the web browser.

Runtime error: Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

Is there a System.Web.WebPages.Razor.dll in the bin folder of your web app? What is its version? (Explorer right click, properties) I'm guessing it's not 3.0.0.0. Just get the nuget packages for v3.0.0.0, perhaps by copying the packages folder from your colleague. Or install it manually: http://www.nuget.org/packages/Microsoft.AspNet.Mvc/3.0.20105.1

EDIT: if you copy stuff from your colleague, also copy the relevant version numbers into packages.config. This is what tells nuget which versions to put into the packages folder.

React.js inline style best practices

The style attribute in React expect the value to be an object, ie Key value pair.

style = {} will have another object inside it like {float:'right'} to make it work.

<span style={{float:'right'}}>{'Download Audit'}</span>

Hope this solves the problem

How to define Typescript Map of key value pair. where key is a number and value is an array of objects

you can also skip creating dictionary altogether. i used below approach to same problem .

 mappedItems: {};
 items.forEach(item => {     
        if (mappedItems[item.key]) {
           mappedItems[item.key].push({productId : item.productId , price : item.price , discount : item.discount});
        } else {
          mappedItems[item.key] = [];
          mappedItems[item.key].push({productId : item.productId , price : item.price , discount : item.discount}));
        }
    });

How can I control Chromedriver open window size?

Try with driver.manage.window.maximize(); to maximize window.

How to set Default Controller in asp.net MVC 4 & MVC 5

Set below code in RouteConfig.cs in App_Start folder

public static void RegisterRoutes(RouteCollection routes)
{
 routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 routes.MapRoute(
 name: "Default",
 url: "{controller}/{action}/{id}",
 defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional });
}

IF still not working then do below steps

Second Way : You simple follow below steps,

1) Right click on your Project

2) Select Properties

3) Select Web option and then Select Specific Page (Controller/View) and then set your login page

Here, Account is my controller and Login is my action method (saved in Account Controller)

Please take a look attachedenter image description here screenshot.

Where is Python language used?

Python is used for developing sites. It's more highlevel than php. Python is used for linux dekstop applications. For example, the most of Ubuntu configurations utilites are pythonic.

Limit to 2 decimal places with a simple pipe

It's Works

.ts -> pi = 3.1415

.html -> {{ pi | number : '1.0-2' }}

Ouput -> 3.14
  1. if it has a decimal it only shows one
  2. if it has two decimals it shows both

https://stackblitz.com/edit/angular-e8g2pt?file=src/app/app.component.html

this works for me!!! thanks!!

How to read if a checkbox is checked in PHP?

$check_value = isset($_POST['my_checkbox_name']) ? 1 : 0;

Detect WebBrowser complete page loading

I think the DocumentCompleted event will get fired for all child documents that are loaded as well (like JS and CSS, for example). You could look at the WebBrowserDocumentCompletedEventArgs in DocumentCompleted and check the Url property and compare that to the Url of the main page.

How to create a file in Android?

Write to a file test.txt:

String filepath ="/mnt/sdcard/test.txt";
FileOutputStream fos = null;
try {
        fos = new FileOutputStream(filepath);
        byte[] buffer = "This will be writtent in test.txt".getBytes();
        fos.write(buffer, 0, buffer.length);
        fos.close();
    } catch (FileNotFoundException e) {
         e.printStackTrace();
    } catch (IOException e) {
         e.printStackTrace();
    }finally{
        if(fos != null)
            fos.close();
    }

Read from file test.txt:

String filepath ="/mnt/sdcard/test.txt";        
FileInputStream fis = null;
try {
       fis = new FileInputStream(filepath);
       int length = (int) new File(filepath).length();
       byte[] buffer = new byte[length];
       fis.read(buffer, 0, length);
       fis.close();
    } catch (FileNotFoundException e) {
         e.printStackTrace();
    } catch (IOException e) {
         e.printStackTrace();
    }finally{
        if(fis != null)
            fis.close();
   }

Note: don't forget to add these two permission in AndroidManifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

How to find count of Null and Nan values for each column in a PySpark dataframe efficiently?

To make sure it does not fail for string, date and timestamp columns:

import pyspark.sql.functions as F
def count_missings(spark_df,sort=True):
    """
    Counts number of nulls and nans in each column
    """
    df = spark_df.select([F.count(F.when(F.isnan(c) | F.isnull(c), c)).alias(c) for (c,c_type) in spark_df.dtypes if c_type not in ('timestamp', 'string', 'date')]).toPandas()

    if len(df) == 0:
        print("There are no any missing values!")
        return None

    if sort:
        return df.rename(index={0: 'count'}).T.sort_values("count",ascending=False)

    return df

If you want to see the columns sorted based on the number of nans and nulls in descending:

count_missings(spark_df)

# | Col_A | 10 |
# | Col_C | 2  |
# | Col_B | 1  | 

If you don't want ordering and see them as a single row:

count_missings(spark_df, False)
# | Col_A | Col_B | Col_C |
# |  10   |   1   |   2   |

How to insert an item into a key/value pair object?

Do you need to look up objects by the key? If not, consider using List<Tuple<string, string>> or List<KeyValuePair<string, string>> if you're not using .NET 4.

What is The difference between ListBox and ListView

A ListView is basically like a ListBox (and inherits from it), but it also has a View property. This property allows you to specify a predefined way of displaying the items. The only predefined view in the BCL (Base Class Library) is GridView, but you can easily create your own.

Another difference is the default selection mode: it's Single for a ListBox, but Extended for a ListView

Semi-transparent color layer over background-image?

From CSS-Tricks... there is a one step way to do this without z-indexing and adding pseudo elements-- requires linear gradient which I think means you need CSS3 support

.tinted-image {
  background-image: 
    /* top, transparent red */
    linear-gradient(
      rgba(255, 0, 0, 0.45), 
      rgba(255, 0, 0, 0.45)
    ),
    /* your image */
    url(image.jpg);
}

Create Map in Java

Map <Integer, Point2D.Double> hm = new HashMap<Integer, Point2D>();
hm.put(1, new Point2D.Double(50, 50));

How to save a pandas DataFrame table as a png

The easiest and fastest way to convert a Pandas dataframe into a png image using Anaconda Spyder IDE- just double-click on the dataframe in variable explorer, and the IDE table will appear, nicely packaged with automatic formatting and color scheme. Just use a snipping tool to capture the table for use in your reports, saved as a png:

2020 Blue Chip Ratio

This saves me lots of time, and is still elegant and professional.