Programs & Examples On #Particles

Can't resolve module (not found) in React.js

I faced the same issue when I created a new react app, I tried all options in https://github.com/facebook/create-react-app/issues/2534 but it didn't help. I had to change the port for the new app and then it worked. By default, apps use the port 3000.I changed the port to 8001 in package.json as follows:

  "scripts": {
    "start": "PORT=8001 react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

Recursion in Python? RuntimeError: maximum recursion depth exceeded while calling a Python object

I've changed the recursion to iteration.

def MovingTheBall(listOfBalls,position,numCell):
while 1:
    stop=1
    positionTmp = (position[0]+choice([-1,0,1]),position[1]+choice([-1,0,1]),0)
    for i in range(0,len(listOfBalls)):
        if positionTmp==listOfBalls[i].pos:
            stop=0
    if stop==1:
        if (positionTmp[0]==0 or positionTmp[0]>=numCell or positionTmp[0]<=-numCell or positionTmp[1]>=numCell or positionTmp[1]<=-numCell):
            stop=0
        else:
            return positionTmp

Works good :D

Reading a binary file with python

import pickle
f=open("filename.dat","rb")
try:
    while True:
        x=pickle.load(f)
        print x
except EOFError:
    pass
f.close()

Fastest way to check if a value exists in a list

Code to check whether two elements exist in array whose product equals k:

n = len(arr1)
for i in arr1:
    if k%i==0:
        print(i)

Python interpreter error, x takes no arguments (1 given)

Python implicitly passes the object to method calls, but you need to explicitly declare the parameter for it. This is customarily named self:

def updateVelocity(self):

HTML Canvas Full Screen

You can just insert the following in to your main html page, or a function:

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

Then to remove the margins on the page

html, body {
    margin: 0 !important;
    padding: 0 !important;
}

That should do the job

Set selected radio from radio group with a value

$('input[name="mygroup"]').val([5])

Create space at the beginning of a UITextField

Such margin can be achieved by setting leftView / rightView to UITextField.

Updated For Swift 4

// Create a padding view for padding on left
textField.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 15, height: textField.frame.height))
textField.leftViewMode = .always

// Create a padding view for padding on right
textField.rightView = UIView(frame: CGRect(x: 0, y: 0, width: 15, height: textField.frame.height))
textField.rightViewMode = .always

I just added/placed an UIView to left and right side of the textfield. So now the typing will start after the view.

Thanks

Hope this helped...

How to find the cumulative sum of numbers in a list?

A pure python oneliner for cumulative sum:

cumsum = lambda X: X[:1] + cumsum([X[0]+X[1]] + X[2:]) if X[1:] else X

This is a recursive version inspired by recursive cumulative sums. Some explanations:

  1. The first term X[:1] is a list containing the previous element and is almost the same as [X[0]] (which would complain for empty lists).
  2. The recursive cumsum call in the second term processes the current element [1] and remaining list whose length will be reduced by one.
  3. if X[1:] is shorter for if len(X)>1.

Test:

cumsum([4,6,12])
#[4, 10, 22]

cumsum([])
#[]

And simular for cumulative product:

cumprod = lambda X: X[:1] + cumprod([X[0]*X[1]] + X[2:]) if X[1:] else X

Test:

cumprod([4,6,12])
#[4, 24, 288]

Getting the closest string match

To query a large set of text in efficient manner you can use the concept of Edit Distance/ Prefix Edit Distance.

Edit Distance ED(x,y): minimal number of transfroms to get from term x to term y

But computing ED between each term and query text is resource and time intensive. Therefore instead of calculating ED for each term first we can extract possible matching terms using a technique called Qgram Index. and then apply ED calculation on those selected terms.

An advantage of Qgram index technique is it supports for Fuzzy Search.

One possible approach to adapt QGram index is build an Inverted Index using Qgrams. In there we store all the words which consists with particular Qgram, under that Qgram.(Instead of storing full string you can use unique ID for each string). You can use Tree Map data structure in Java for this. Following is a small example on storing of terms

col : colmbia, colombo, gancola, tacolama

Then when querying, we calculate the number of common Qgrams between query text and available terms.

Example: x = HILLARY, y = HILARI(query term)
Qgrams
$$HILLARY$$ -> $$H, $HI, HIL, ILL, LLA, LAR, ARY, RY$, Y$$
$$HILARI$$ -> $$H, $HI, HIL, ILA, LAR, ARI, RI$, I$$
number of q-grams in common = 4

number of q-grams in common = 4.

For the terms with high number of common Qgrams, we calculate the ED/PED against the query term and then suggest the term to the end user.

you can find an implementation of this theory in following project(See "QGramIndex.java"). Feel free to ask any questions. https://github.com/Bhashitha-Gamage/City_Search

To study more about Edit Distance, Prefix Edit Distance Qgram index please watch the following video of Prof. Dr Hannah Bast https://www.youtube.com/embed/6pUg2wmGJRo (Lesson starts from 20:06)

jQuery if Element has an ID?

Simple way:

Fox example this is your html,

<div class='classname' id='your_id_name'>
</div>

Jquery code:

if($('.classname').prop('id')=='your_id_name')
{
    //works your_id_name exist (true part)
}
else
{ 
    //works your_id_name not exist (false part)
}

How to set up gradle and android studio to do release build?

No need to update gradle for making release application in Android studio.If you were eclipse user then it will be so easy for you. If you are new then follow the steps

1: Go to the "Build" at the toolbar section. 2: Choose "Generate Signed APK..." option. enter image description here

3:fill opened form and go next 4 :if you already have .keystore or .jks then choose that file enter your password and alias name and respective password. 5: Or don't have .keystore or .jks file then click on Create new... button as shown on pic 1 then fill the form.enter image description here

Above process was to make build manually. If You want android studio to automatically Signing Your App

In Android Studio, you can configure your project to sign your release APK automatically during the build process:

On the project browser, right click on your app and select Open Module Settings. On the Project Structure window, select your app's module under Modules. Click on the Signing tab. Select your keystore file, enter a name for this signing configuration (as you may create more than one), and enter the required information. enter image description here Figure 4. Create a signing configuration in Android Studio.

Click on the Build Types tab. Select the release build. Under Signing Config, select the signing configuration you just created. enter image description here Figure 5. Select a signing configuration in Android Studio.

4:Most Important thing that make debuggable=false at gradle.

    buildTypes {
        release {
           minifyEnabled false
          proguardFiles getDefaultProguardFile('proguard-  android.txt'), 'proguard-rules.txt'
        debuggable false
        jniDebuggable false
        renderscriptDebuggable false
        zipAlignEnabled true
       }
     }

visit for more in info developer.android.com

How to move certain commits to be based on another branch in git?

// on your branch that holds the commit you want to pass
$ git log
// copy the commit hash found
$ git checkout [branch that will copy the commit]
$ git reset --hard [hash of the commit you want to copy from the other branch]
// remove the [brackets]

Other more useful commands here with explanation: Git Guide

how to create Socket connection in Android?

Socket connections in Android are the same as in Java: http://www.oracle.com/technetwork/java/socket-140484.html

Things you need to be aware of:

  1. If phone goes to sleep your app will no longer execute, so socket will eventually timeout. You can prevent this with wake lock. This will eat devices battery tremendously - I know I wouldn't use that app.
  2. If you do this constantly, even when your app is not active, then you need to use Service.
  3. Activities and Services can be killed off by OS at any time, especially if they are part of an inactive app.

Take a look at AlarmManager, if you need scheduled execution of your code.

Do you need to run your code and receive data even if user does not use the app any more (i.e. app is inactive)?

How can I get a side-by-side diff when I do "git diff"?

ydiff

Formerly called cdiff, this tool can display side by side, incremental, and colorful diff.

Instead of doing git diff, do:

ydiff -s -w0

This will launch ydiff in side-by-side display mode for each of the files with differences.

Install with:

python3 -m pip install --user ydiff

-or-

brew install ydiff

For git log, you can use:

ydiff -ls -w0

-w0 auto-detects your terminal width. See the ydiff GitHub repository page for detail and demo.

Tested in Git 2.18.0, ydiff 1.1.

how to download image from any web page in java

The following code downloads an image from a direct link to the disk into the project directory. Also note that it uses try-with-resources.

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.io.FilenameUtils;

public class ImageDownloader
{
    public static void main(String[] arguments) throws IOException
    {
        downloadImage("https://upload.wikimedia.org/wikipedia/commons/7/73/Lion_waiting_in_Namibia.jpg",
                new File("").getAbsolutePath());
    }

    public static void downloadImage(String sourceUrl, String targetDirectory)
            throws MalformedURLException, IOException, FileNotFoundException
    {
        URL imageUrl = new URL(sourceUrl);
        try (InputStream imageReader = new BufferedInputStream(
                imageUrl.openStream());
                OutputStream imageWriter = new BufferedOutputStream(
                        new FileOutputStream(targetDirectory + File.separator
                                + FilenameUtils.getName(sourceUrl)));)
        {
            int readByte;

            while ((readByte = imageReader.read()) != -1)
            {
                imageWriter.write(readByte);
            }
        }
    }
}

Add onClick event to document.createElement("th")

var newTH = document.createElement('th');
newTH.onclick = function() {
      //Your code here
}

Concatenate multiple node values in xpath

Here comes a solution with XSLT:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="//element3">
    <xsl:value-of select="element4/text()" />.<xsl:value-of select="element5/text()" />
</xsl:template>
</xsl:stylesheet>

Check If array is null or not in php

you can use

empty($result) 

to check if the main array is empty or not.

But since you have a SimpleXMLElement object, you need to query the object if it is empty or not. See http://www.php.net/manual/en/simplexmlelement.count.php

ex:

if (empty($result) || !isset($result['Tags'])) {
    return false;
}
if ( !($result['Tags'] instanceof SimpleXMLElement)) {
    return false;
}
return ($result['Tags']->count());

How to insert new cell into UITableView in Swift

Swift 5.0, 4.0, 3.0 Updated Solution

Insert at Bottom

self.yourArray.append(msg)

self.tblView.beginUpdates()
self.tblView.insertRows(at: [IndexPath.init(row: self.yourArray.count-1, section: 0)], with: .automatic)
self.tblView.endUpdates()

Insert at Top of TableView

self.yourArray.insert(msg, at: 0)
self.tblView.beginUpdates()
self.tblView.insertRows(at: [IndexPath.init(row: 0, section: 0)], with: .automatic)
self.tblView.endUpdates()

How to force DNS refresh for a website?

you can't force refresh but you can forward all old ip requests to new one. for a website:

replace [OLD_IP] with old server's ip

replace [NEW_IP] with new server's ip

run & win.

echo "1" > /proc/sys/net/ipv4/ip_forward

iptables -t nat -A PREROUTING -d [OLD_IP] -p tcp --dport 80 -j DNAT --to-destination [NEW_IP]:80

iptables -t nat -A PREROUTING -d [OLD_IP] -p tcp --dport 443 -j DNAT --to-destination [NEW_IP]:443

iptables -t nat -A POSTROUTING -j MASQUERADE

SQL: Alias Column Name for Use in CASE Statement

This:

SELECT col1 as a,
       CASE WHEN a = 'test' THEN 'yes' END as value 
  FROM table;

...will not work. This will:

SELECT CASE WHEN a = 'test' THEN 'yes' END as value
  FROM (SELECT col1 AS a
          FROM TABLE)

Why you wouldn't use:

SELECT t.col1 as a,
       CASE WHEN t.col1 = 'test' THEN 'yes' END as value 
  FROM TABLE t;

...I don't know.

`col-xs-*` not working in Bootstrap 4

you could do this, if you want to use the old syntax (or don't want to rewrite every template)

@for $i from 1 through $grid-columns {
  @include media-breakpoint-up(xs) {
    .col-xs-#{$i} {
      @include make-col-ready();
      @include make-col($i);
    }
  }
}

Can you center a Button in RelativeLayout?

Its easy, dont Align it to anything

_x000D_
_x000D_
<Button_x000D_
        android:id="@+id/the_button"_x000D_
        android:layout_width="wrap_content"_x000D_
        android:layout_height="wrap_content" _x000D_
        android:layout_centerInParent="true"_x000D_
        android:text="Centered Button"/>
_x000D_
_x000D_
_x000D_

(413) Request Entity Too Large | uploadReadAheadSize

I had the same problem and setting the uploadReadAheadSize solved it:

http://www.iis.net/configreference/system.webserver/serverruntime

"The value must be between 0 and 2147483647."

It is easily set it in the applicationHost.config-fle if you don't want to do a cmd-thing.

Its located in WindowsFOLDER\System32\inetsrv\config (2008 server).

You must open it with notepad. Do a Backup of the file first.

According to the comments in config the recommended way to unlock sections is by using a location tag:

<location path="Default Web Site" overrideMode="Allow">
    <system.webServer>
        <asp />
    </system.webServer>
</location>"

So you can write in the bottom (since it doesn't exist before). I write maxvalue here - write your own value if you want.

<location path="THENAMEOFTHESITEYOUHAVE" overrideMode="Allow">
    <system.webServer>
        <asp />
        <serverRuntime uploadReadAheadSize="2147483647" />
    </system.webServer>
</location>

If you put it last before </configuration> for example, you know where you have it.

Hope that solves your problems. It was an SSL overhead issue for me, where too much post freezed the application, raising a (413) Request Entity Too Large error.

How to auto generate migrations with Sequelize CLI from Sequelize models?

You cannot create migration scripts for existing models.

Resources:

If going the classic way, you'll have to recreate the models via the CLI:

sequelize model:create --name MyUser --attributes first_name:string,last_name:string,bio:text

It will generate these files:

models/myuser.js:

_x000D_
_x000D_
"use strict";_x000D_
module.exports = function(sequelize, DataTypes) {_x000D_
  var MyUser = sequelize.define("MyUser", {_x000D_
    first_name: DataTypes.STRING,_x000D_
    last_name: DataTypes.STRING,_x000D_
    bio: DataTypes.TEXT_x000D_
  }, {_x000D_
    classMethods: {_x000D_
      associate: function(models) {_x000D_
        // associations can be defined here_x000D_
      }_x000D_
    }_x000D_
  });_x000D_
  return MyUser;_x000D_
};
_x000D_
_x000D_
_x000D_

migrations/20150210104840-create-my-user.js:

_x000D_
_x000D_
"use strict";_x000D_
module.exports = {_x000D_
  up: function(migration, DataTypes, done) {_x000D_
    migration.createTable("MyUsers", {_x000D_
      id: {_x000D_
        allowNull: false,_x000D_
        autoIncrement: true,_x000D_
        primaryKey: true,_x000D_
        type: DataTypes.INTEGER_x000D_
      },_x000D_
      first_name: {_x000D_
        type: DataTypes.STRING_x000D_
      },_x000D_
      last_name: {_x000D_
        type: DataTypes.STRING_x000D_
      },_x000D_
      bio: {_x000D_
        type: DataTypes.TEXT_x000D_
      },_x000D_
      createdAt: {_x000D_
        allowNull: false,_x000D_
        type: DataTypes.DATE_x000D_
      },_x000D_
      updatedAt: {_x000D_
        allowNull: false,_x000D_
        type: DataTypes.DATE_x000D_
      }_x000D_
    }).done(done);_x000D_
  },_x000D_
  down: function(migration, DataTypes, done) {_x000D_
    migration.dropTable("MyUsers").done(done);_x000D_
  }_x000D_
};
_x000D_
_x000D_
_x000D_

Why would a JavaScript variable start with a dollar sign?

As others have mentioned the dollar sign is intended to be used by mechanically generated code. However, that convention has been broken by some wildly popular JavaScript libraries. JQuery, Prototype and MS AJAX (AKA Atlas) all use this character in their identifiers (or as an entire identifier).

In short you can use the $ whenever you want. (The interpreter won't complain.) The question is when do you want to use it?

I personally do not use it, but I think its use is valid. I think MS AJAX uses it to signify that a function is an alias for some more verbose call.

For example:

var $get = function(id) { return document.getElementById(id); }

That seems like a reasonable convention.

How can I get a List from some class properties with Java 8 Stream?

You can use map :

List<String> names = 
    personList.stream()
              .map(Person::getName)
              .collect(Collectors.toList());

EDIT :

In order to combine the Lists of friend names, you need to use flatMap :

List<String> friendNames = 
    personList.stream()
              .flatMap(e->e.getFriends().stream())
              .collect(Collectors.toList());

What is JAVA_HOME? How does the JVM find the javac path stored in JAVA_HOME?

The command prompt wouldn't use JAVA_HOME to find javac.exe, it would use PATH.

jquery to loop through table rows and cells, where checkob is checked, concatenate

Try this:

function createcodes() {

    $('.authors-list tr').each(function () {
        //processing this row
        //how to process each cell(table td) where there is checkbox
        $(this).find('td input:checked').each(function () {

             // it is checked, your code here...
        });
    });
}

Laravel - Model Class not found

Make sure to be careful when editing your model file. For example, in your post model:

<?php 
namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model {
    protected $table = 'posts';    
}

You need to pay close attention to the class Post extend Model line. The class Post defined here will be your namespace for your controller.

String replace a Backslash

you have to do

sSource.replaceAll("\\\\/", "/");

because the backshlash should be escaped twice one for string in source one in regular expression

Mockito How to mock only the call of a method of the superclass

create a package protected (assumes test class in same package) method in the sub class that calls the super class method and then call that method in your overridden sub class method. you can then set expectations on this method in your test through the use of the spy pattern. not pretty but certainly better than having to deal with all the expectation setting for the super method in your test

Why are hexadecimal numbers prefixed with 0x?

The preceding 0 is used to indicate a number in base 2, 8, or 16.

In my opinion, 0x was chosen to indicate hex because 'x' sounds like hex.

Just my opinion, but I think it makes sense.

Good Day!

Check if array is empty or null

I think it is dangerous to use $.isEmptyObject from jquery to check whether the array is empty, as @jesenko mentioned. I just met that problem.

In the isEmptyObject doc, it mentions:

The argument should always be a plain JavaScript Object

which you can determine by $.isPlainObject. The return of $.isPlainObject([]) is false.

jquery - How to determine if a div changes its height or any css attribute?

Please don't use techniques described in other answers here. They are either not working with css3 animations size changes, floating layout changes or changes that don't come from jQuery land. You can use a resize-detector, a event-based approach, that doesn't waste your CPU time.

https://github.com/marcj/css-element-queries

It contains a ResizeSensor class you can use for that purpose.

new ResizeSensor(jQuery('#mainContent'), function(){ 
    console.log('main content dimension changed');
});

Disclaimer: I wrote this library

postgresql - add boolean column to table set default

In psql alter column query syntax like this

Alter table users add column priv_user boolean default false ;

boolean value (true-false) save in DB like (t-f) value .

If a folder does not exist, create it

Just write this line:

System.IO.Directory.CreateDirectory("my folder");
  • If the folder does not exist yet, it will be created.
  • If the folder exists already, the line will be ignored.

Reference: Article about Directory.CreateDirectory at MSDN

Of course, you can also write using System.IO; at the top of the source file and then just write Directory.CreateDirectory("my folder"); every time you want to create a folder.

java.lang.OutOfMemoryError: Java heap space

If you want to increase your heap space, you can use java -Xms<initial heap size> -Xmx<maximum heap size> on the command line. By default, the values are based on the JRE version and system configuration. You can find out more about the VM options on the Java website.

However, I would recommend profiling your application to find out why your heap size is being eaten. NetBeans has a very good profiler included with it. I believe it uses the jvisualvm under the hood. With a profiler, you can try to find where many objects are being created, when objects get garbage collected, and more.

Session timeout in ASP.NET

https://usefulaspandcsharp.wordpress.com/tag/session-timeout/

<authentication mode="Forms">
  <forms loginUrl="Login.aspx" name=".ASPXFORMSAUTH" timeout="60" slidingExpiration="true" />
</authentication>

<sessionState mode="InProc" timeout="60" />

How do you calculate the variance, median, and standard deviation in C++ or Java?

public class Statistics {
    double[] data;
    int size;   

    public Statistics(double[] data) {
        this.data = data;
        size = data.length;
    }   

    double getMean() {
        double sum = 0.0;
        for(double a : data)
            sum += a;
        return sum/size;
    }

    double getVariance() {
        double mean = getMean();
        double temp = 0;
        for(double a :data)
            temp += (a-mean)*(a-mean);
        return temp/(size-1);
    }

    double getStdDev() {
        return Math.sqrt(getVariance());
    }

    public double median() {
       Arrays.sort(data);
       if (data.length % 2 == 0)
          return (data[(data.length / 2) - 1] + data[data.length / 2]) / 2.0;
       return data[data.length / 2];
    }
}

How to compare two object variables in EL expression language?

Not sure if I get you right, but the simplest way would be something like:

<c:if test="${languageBean.locale == 'en'">
  <f:selectItems value="#{customerBean.selectableCommands_limited_en}" />
</c:if>

Just a quick copy and paste from an app of mine...

HTH

Failed to serialize the response in Web API with Json

This also happens when the Response-Type is not public! I returned an internal class as I used Visual Studio to generate me the type.

internal class --> public class

How do I use JDK 7 on Mac OSX?

I know that some may want to smack me for re-opening old post, but if you feel so do it I just hope this may help someone else trying to set JDK 7 on Mac OS (using IntelliJ).

What I did to get this working on my machine is to:

  • followed instructions on Oracle JDK7 Mac OS X Port for general installation
  • in IntelliJ open/create new project so you can add new SDK (File > Project Structure)
  • select Platform Settings > SDKs, press "+" (plus) sign to add new SDK
  • select JSDK and navigate to /Library/Java/JavaVirtualMachines/JDK 1.7.0 Developer Preview.jdk/Contents/Home. Do not get it mistaken with /Users/YOUR_USERNAME/Library/Java/. This will link 4 JARs from "lib" directory (dt.jar, jconsole.jar, sa-jdi.jar and tools.jar)
  • you will need also add JARs from /Library/Java/JavaVirtualMachines/JDK 1.7.0 Developer Preview.jdk/Contents/Home/jre/lib (charsets.jar, jce.jar, JObjC.jar, jsse.jar, management-agent.jar, resources.jar and rt.jar)

Split array into chunks

If you are using Underscore JS, just use :

var result = _.chunk(arr,elements_per_chunk)

Most projects already use underscore as a dependency, anyways.

How to call a Parent Class's method from Child Class in Python?

This is a more abstract method:

super(self.__class__,self).baz(arg)

Selenium WebDriver.get(url) does not open the URL

It is a defect of Selenium.
I have the same problem in Ubuntu 12.04 behind the proxy.

Problem is in incorrect processing proxy exclusions. Default Ubuntu exclusions are located in no_proxy environment variable:

no_proxy=localhost,127.0.0.0/8

But it seems that /8 mask doesn't work for selenium. To workaround the problem it is enough to change no_proxy to the following:

no_proxy=localhost,127.0.0.1

Removing proxy settings before running python script also helps:

http_proxy= python script.py

In AVD emulator how to see sdcard folder? and Install apk to AVD?

DDMS is deprecated in android 3.0. "Device file explorer"can be used to browse files.

PHP code to convert a MySQL query to CSV

Look at the documentation regarding the SELECT ... INTO OUTFILE syntax.

SELECT a,b,a+b INTO OUTFILE '/tmp/result.txt'
  FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
  LINES TERMINATED BY '\n'
  FROM test_table;

Correct Way to Load Assembly, Find Class and Call Run() Method

You will need to use reflection to get the type "TestRunner". Use the Assembly.GetType method.

class Program
{
    static void Main(string[] args)
    {
        Assembly assembly = Assembly.LoadFile(@"C:\dyn.dll");
        Type type = assembly.GetType("TestRunner");
        var obj = (TestRunner)Activator.CreateInstance(type);
        obj.Run();
    }
}

Why use pointers?

  • Why use pointers over normal variables?

Short answer is: Don't. ;-) Pointers are to be used where you can't use anything else. It is either because the lack of appropriate functionality, missing data types or for pure perfomance. More below...

  • When and where should I use pointers?

Short answer here is: Where you cannot use anything else. In C you don't have any support for complex datatypes such as a string. There are also no way of passing a variable "by reference" to a function. That's where you have to use pointers. Also you can have them to point at virtually anything, linked lists, members of structs and so on. But let's not go into that here.

  • How do you use pointers with arrays?

With little effort and much confusion. ;-) If we talk about simple data types such as int and char there is little difference between an array and a pointer. These declarations are very similar (but not the same - e.g., sizeof will return different values):

char* a = "Hello";
char a[] = "Hello";

You can reach any element in the array like this

printf("Second char is: %c", a[1]);

Index 1 since the array starts with element 0. :-)

Or you could equally do this

printf("Second char is: %c", *(a+1));

The pointer operator (the *) is needed since we are telling printf that we want to print a character. Without the *, the character representation of the memory address itself would be printed. Now we are using the character itself instead. If we had used %s instead of %c, we would have asked printf to print the content of the memory address pointed to by 'a' plus one (in this example above), and we wouldn't have had to put the * in front:

printf("Second char is: %s", (a+1)); /* WRONG */

But this would not have just printed the second character, but instead all characters in the next memory addresses, until a null character (\0) were found. And this is where things start to get dangerous. What if you accidentally try and print a variable of the type integer instead of a char pointer with the %s formatter?

char* a = "Hello";
int b = 120;
printf("Second char is: %s", b);

This would print whatever is found on memory address 120 and go on printing until a null character was found. It is wrong and illegal to perform this printf statement, but it would probably work anyway, since a pointer actually is of the type int in many environments. Imagine the problems you might cause if you were to use sprintf() instead and assign this way too long "char array" to another variable, that only got a certain limited space allocated. You would most likely end up writing over something else in the memory and cause your program to crash (if you are lucky).

Oh, and if you don't assign a string value to the char array / pointer when you declare it, you MUST allocate sufficient amount of memory to it before giving it a value. Using malloc, calloc or similar. This since you only declared one element in your array / one single memory address to point at. So here's a few examples:

char* x;
/* Allocate 6 bytes of memory for me and point x to the first of them. */
x = (char*) malloc(6);
x[0] = 'H';
x[1] = 'e';
x[2] = 'l';
x[3] = 'l';
x[4] = 'o';
x[5] = '\0';
printf("String \"%s\" at address: %d\n", x, x);
/* Delete the allocation (reservation) of the memory. */
/* The char pointer x is still pointing to this address in memory though! */
free(x);
/* Same as malloc but here the allocated space is filled with null characters!*/
x = (char *) calloc(6, sizeof(x));
x[0] = 'H';
x[1] = 'e';
x[2] = 'l';
x[3] = 'l';
x[4] = 'o';
x[5] = '\0';
printf("String \"%s\" at address: %d\n", x, x);
/* And delete the allocation again... */
free(x);
/* We can set the size at declaration time as well */
char xx[6];
xx[0] = 'H';
xx[1] = 'e';
xx[2] = 'l';
xx[3] = 'l';
xx[4] = 'o';
xx[5] = '\0';
printf("String \"%s\" at address: %d\n", xx, xx);

Do note that you can still use the variable x after you have performed a free() of the allocated memory, but you do not know what is in there. Also do notice that the two printf() might give you different addresses, since there is no guarantee that the second allocation of memory is performed in the same space as the first one.

LINQ Using Max() to select a single row

Addressing the first question, if you need to take several rows grouped by certain criteria with the other column with max value you can do something like this:

var query =
    from u1 in table
    join u2 in (
        from u in table
        group u by u.GroupId into g
        select new { GroupId = g.Key, MaxStatus = g.Max(x => x.Status) }
    ) on new { u1.GroupId, u1.Status } equals new { u2.GroupId, Status = u2.MaxStatus}
    select u1;

SQL Server : GROUP BY clause to get comma-separated values

SELECT  [ReportId], 
        SUBSTRING(d.EmailList,1, LEN(d.EmailList) - 1) EmailList
FROM
        (
            SELECT DISTINCT [ReportId]
            FROM Table1
        ) a
        CROSS APPLY
        (
            SELECT [Email] + ', ' 
            FROM Table1 AS B 
            WHERE A.[ReportId] = B.[ReportId]
            FOR XML PATH('')
        ) D (EmailList) 

SQLFiddle Demo

Pytorch reshape tensor dimension

torch.reshape() is made to dupe the numpy reshape method.

It came after the view() and torch.resize_() and it is inside the dir(torch) package.

import torch
x=torch.arange(24)
print(x, x.shape)
x_view = x.view(1,2,3,4) # works on is_contiguous() tensor
print(x_view.shape)
x_reshaped = x.reshape(1,2,3,4) # works on any tensor
print(x_reshaped.shape)
x_reshaped2 = torch.reshape(x_reshaped, (-1,)) # part of torch package, while view() and resize_() are not
print(x_reshaped2.shape)

Out:

tensor([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
        18, 19, 20, 21, 22, 23]) torch.Size([24])
torch.Size([1, 2, 3, 4])
torch.Size([1, 2, 3, 4])
torch.Size([24])

But did you know it can also work as a replacement for squeeze() and unsqueeze()

x = torch.tensor([1, 2, 3, 4])
print(x.shape)
x1 = torch.unsqueeze(x, 0)
print(x1.shape)
x2 = torch.unsqueeze(x1, 1)
print(x2.shape)
x3=x.reshape(1,1,4)
print(x3.shape)
x4=x.reshape(4)
print(x4.shape)
x5=x3.squeeze()
print(x5.shape)

Out:

torch.Size([4])
torch.Size([1, 4])
torch.Size([1, 1, 4])
torch.Size([1, 1, 4])
torch.Size([4])
torch.Size([4])

how to set imageview src?

To set image cource in imageview you can use any of the following ways. First confirm your image is present in which format.

If you have image in the form of bitmap then use

imageview.setImageBitmap(bm);

If you have image in the form of drawable then use

imageview.setImageDrawable(drawable);

If you have image in your resource example if image is present in drawable folder then use

imageview.setImageResource(R.drawable.image);

If you have path of image then use

imageview.setImageURI(Uri.parse("pathofimage"));

Strict Standards: Only variables should be assigned by reference PHP 5.4

It's because you're trying to assign an object by reference. Remove the ampersand and your script should work as intended.

What is the difference between min SDK version/target SDK version vs. compile SDK version?

The formula is

minSdkVersion <= targetSdkVersion <= compileSdkVersion

minSdkVersion - is a marker that defines a minimum Android version on which application will be able to install. Also it is used by Lint to prevent calling API that doesn’t exist. Also it has impact on Build Time. So you can use build flavors to override minSdkVersion to maximum during the development. It will help to make build faster using all improvements that the Android team provides for us. For example some features Java 8 are available only from specific version of minSdkVersion.

targetSdkVersion - If AndroidOS version is >= targetSdkVersion it says Android system to turn on specific(new) behavior changes. *Please note that some of new behaviors will be turned on by default even if thought targetSdkVersion is <, you should read official doc.

For example:

  • Starting in Android 6.0 (API level 23) Runtime Permissions were introduced. If you set targetSdkVersion to 22 or lower your application does not ask a user for some permission in run time.

  • Starting in Android 8.0 (API level 26), all notifications must be assigned to a channel or it will not appear. On devices running Android 7.1 (API level 25) and lower, users can manage notifications on a per-app basis only (effectively each app only has one channel on Android 7.1 and lower).

  • Starting in Android 9 (API level 28), Web-based data directories separated by process. If targetSdkVersion is 28+ and you create several WebView in different processes you will get java.lang.RuntimeException

compileSdkVersion - actually it is SDK Platform version and tells Gradle which Android SDK use to compile. When you want to use new features or debug .java files from Android SDK you should take care of compileSdkVersion. One more example is using AndroidX that forces to use compileSdkVersion - level 28. compileSdkVersion is not included in your APK: it is purely used at compile time. Changing your compileSdkVersion does not change runtime behavior. It can generate for example new compiler warnings/errors. Therefore it is strongly recommended that you always compile with the latest SDK. You’ll get all the benefits of new compilation checks on existing code, avoid newly deprecated APIs, and be ready to use new APIs. One more fact is compileSdkVersion >= Support Library version

You can read more about it here. Also I would recommend you to take a look at the example of migration to Android 8.0.

[buildToolsVersion]

How do I get the browser scroll position in jQuery?

Since it appears you are using jQuery, here is a jQuery solution.

$(function() {
    $('#Eframe').on("mousewheel", function() {
        alert($(document).scrollTop());
    });
});

Not much to explain here. If you want, here is the jQuery documentation.

How to convert String to DOM Document object in java?

DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = db.parse(new ByteArrayInputStream(xmlString.getBytes("UTF-8"))); //remove the parameter UTF-8 if you don't want to specify the Encoding type.

this works well for me even though the XML structure is complex.

And please make sure your xmlString is valid for XML, notice the escape character should be added "\" at the front.

The main problem might not come from the attributes.

How do I enable/disable log levels in Android?

Log4j or slf4j can also be used as logging frameworks in Android together with logcat. See the project android-logging-log4j or log4j support in android

How to display image with JavaScript?

You could make use of the Javascript DOM API. In particular, look at the createElement() method.

You could create a re-usable function that will create an image like so...

function show_image(src, width, height, alt) {
    var img = document.createElement("img");
    img.src = src;
    img.width = width;
    img.height = height;
    img.alt = alt;

    // This next line will just add it to the <body> tag
    document.body.appendChild(img);
}

Then you could use it like this...

<button onclick=
    "show_image('http://google.com/images/logo.gif', 
                 276, 
                 110, 
                 'Google Logo');">Add Google Logo</button> 

See a working example on jsFiddle: http://jsfiddle.net/Bc6Et/

Is there a sleep function in JavaScript?

You can use the setTimeout or setInterval functions.

Closing pyplot windows

Please use

plt.show(block=False)
plt.close('all')

extract column value based on another column pandas dataframe

df[df['B']==3]['A'], assuming df is your pandas.DataFrame.

How to check a string for specific characters?

s=input("Enter any character:")   
if s.isalnum():   
   print("Alpha Numeric Character")   
   if s.isalpha():   
       print("Alphabet character")   
       if s.islower():   
         print("Lower case alphabet character")   
       else:   
         print("Upper case alphabet character")   
   else:   
     print("it is a digit")   
elif s.isspace():   
    print("It is space character")   

else:
print("Non Space Special Character")

How to test if a DataSet is empty?

Don't forget to set table name da.Fill(ds,"tablename");

So you return data using table name instead of 0

if (ds.Tables["tablename"].Rows.Count == 0)
 {
  MessageBox.Show("No result found");
 }

showDialog deprecated. What's the alternative?

package com.keshav.datePicker_With_Hide_Future_Past_Date;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

    EditText ed_date;
    int year;
    int month;
    int day;

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

        ed_date=(EditText) findViewById(R.id.et_date);

        ed_date.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Calendar mcurrentDate=Calendar.getInstance();
                year=mcurrentDate.get(Calendar.YEAR);
                month=mcurrentDate.get(Calendar.MONTH);
                day=mcurrentDate.get(Calendar.DAY_OF_MONTH);

                final DatePickerDialog   mDatePicker =new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener()
                {
                    @Override
                    public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday)
                    {
                              ed_date.setText(new StringBuilder().append(year).append("-").append(month+1).append("-").append(day));
                            int month_k=selectedmonth+1;

                    }
                },year, month, day);
                mDatePicker.setTitle("Please select date");
                // TODO Hide Future Date Here
                mDatePicker.getDatePicker().setMaxDate(System.currentTimeMillis());

                // TODO Hide Past Date Here
                //  mDatePicker.getDatePicker().setMinDate(System.currentTimeMillis());
                mDatePicker.show();
            }
        });
    }
}


// Its Working 

Display loading image while post with ajax

Let's say you have a tag someplace on the page which contains your loading message:

<div id='loadingmessage' style='display:none'>
  <img src='loadinggraphic.gif'/>
</div>

You can add two lines to your ajax call:

function getData(p){
    var page=p;
    $('#loadingmessage').show();  // show the loading message.
    $.ajax({
        url: "loadData.php?id=<? echo $id; ?>",
        type: "POST",
        cache: false,
        data: "&page="+ page,
        success : function(html){
            $(".content").html(html);
            $('#loadingmessage').hide(); // hide the loading message
        }
    });

Using Selenium Web Driver to retrieve value of a HTML input

This is kind of hacky, but it works.

I used JavascriptExecutor and added a div to the HTML, and changed the text in the div to $('#prettyTime').val() I then used Selenium to retrieve the div and grab its value. After testing the correctness of the value, I removed the div that was just created.

Compile to stand alone exe for C# app in Visual Studio 2010

You can use the files from debug folder,however if you look at app debug informations with some inspection software,you can clearly see "Symbols File Name" which can reveals not wanted informations in path to the original exe file.

How to hide image broken Icon using only CSS/HTML?

The trick with img::after is a good stuff, but has at least 2 downsides:

  1. not supported by all browsers (e.g. doesn't work on Edge https://codepen.io/dsheiko/pen/VgYErm)
  2. you cannot simply hide the image, you cover it - so not that helpful when you what to show a default image in the case

I do not know an universal solution without JavaScript, but for Firefox only there is a nice one:

img:-moz-broken{
  opacity: 0;
}

Could not open a connection to your authentication agent

I had the same problem on Ubuntu and the other solutions didn't help me. I finally realized what my problem was. I had created my ssh keys in /root/.ssh folder, So even when I ran ssh-add as root, it couldn't do its work and keep saying

Could not open a connection to your authentication agent.

I created my ssh public and private keys in /home/myUsername/ folder and I used

ssh-agent /bin/sh

then I ran

ssh-add /home/myUsername/.ssh/id_rsa

and problem was solved this way.

Note: For accessing your repository on git add your git password when you are creating ssh keys with ssh-keygen -t rsa -C "your git email here".

How to convert numbers between hexadecimal and decimal

If you want maximum performance when doing conversion from hex to decimal number, you can use the approach with pre-populated table of hex-to-decimal values.

Here is the code that illustrates that idea. My performance tests showed that it can be 20%-40% faster than Convert.ToInt32(...):

class TableConvert
  {
      static sbyte[] unhex_table =
      { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
       ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
       ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
       , 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1
       ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
       ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
       ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
       ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
      };

      public static int Convert(string hexNumber)
      {
          int decValue = unhex_table[(byte)hexNumber[0]];
          for (int i = 1; i < hexNumber.Length; i++)
          {
              decValue *= 16;
              decValue += unhex_table[(byte)hexNumber[i]];
          }
          return decValue;
      }
  }

Get key by value in dictionary

This is how you access the dictionary to do what you want:

list = {'george': 16, 'amber': 19}
search_age = raw_input("Provide age")
for age in list:
    if list[age] == search_age:
        print age

of course, your names are so off it looks like it would be printing an age, but it DOES print the name. Since you are accessing by name, it becomes more understandable if you write:

list = {'george': 16, 'amber': 19}
search_age = raw_input("Provide age")
for name in list:
    if list[name] == search_age:
        print name

Better yet:

people = {'george': {'age': 16}, 'amber': {'age': 19}}
search_age = raw_input("Provide age")
for name in people:
    if people[name]['age'] == search_age:
        print name

Flask ImportError: No Module Named Flask

The simplest answer to this problem is specifying the correct path to flask in your environment. Make sure the script you are running knows how to get to the flask installation. Using print(sys.path) as mentioned above certainly helped to figure out the path(s) the script was using.

What is the best way to modify a list in a 'foreach' loop?

The best approach from a performance perspective is probably to use a one or two arrays. Copy the list to an array, do operations on the array, and then build a new list from the array. Accessing an array element is faster than accessing a list item, and conversions between a List<T> and a T[] can use a fast "bulk copy" operation which avoids the overhead associated accessing individual items.

For example, suppose you have a List<string> and wish to have every string in the list which starts with T be followed by an item "Boo", while every string that starts with "U" is dropped entirely. An optimal approach would probably be something like:

int srcPtr,destPtr;
string[] arr;

srcPtr = theList.Count;
arr = new string[srcPtr*2];
theList.CopyTo(arr, theList.Count); // Copy into second half of the array
destPtr = 0;
for (; srcPtr < arr.Length; srcPtr++)
{
  string st = arr[srcPtr];
  char ch = (st ?? "!")[0]; // Get first character of string, or "!" if empty
  if (ch != 'U')
    arr[destPtr++] = st;
  if (ch == 'T')
    arr[destPtr++] = "Boo";
}
if (destPtr > arr.Length/2) // More than half of dest. array is used
{
  theList = new List<String>(arr); // Adds extra elements
  if (destPtr != arr.Length)
    theList.RemoveRange(destPtr, arr.Length-destPtr); // Chop to proper length
}
else
{
  Array.Resize(ref arr, destPtr);
  theList = new List<String>(arr); // Adds extra elements
}

It would have been helpful if List<T> provided a method to construct a list from a portion of an array, but I'm unaware of any efficient method for doing so. Still, operations on arrays are pretty fast. Of note is the fact that adding and removing items from the list does not require "pushing" around other items; each item gets written directly to its appropriate spot in the array.

Linux: where are environment variables stored?

The environment variables of a process exist at runtime, and are not stored in some file or so. They are stored in the process's own memory (that's where they are found to pass on to children). But there is a virtual file in

/proc/pid/environ

This file shows all the environment variables that were passed when calling the process (unless the process overwrote that part of its memory — most programs don't). The kernel makes them visible through that virtual file. One can list them. For example to view the variables of process 3940, one can do

cat /proc/3940/environ | tr '\0' '\n'

Each variable is delimited by a binary zero from the next one. tr replaces the zero into a newline.

How to use EditText onTextChanged event when I press the number?

To change the text;

multipleLine.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            MainActivity.myArray.set(pickId,String.valueOf(s));
            MainActivity.myAdapt.notifyDataSetChanged();
        }

        @Override
        public void afterTextChanged(Editable s) {

        }

Windows Batch Files: if else

you have to do like this...

if not "A%1" == "A"

if the input argument %1 is null, your code will have problem.

What does OpenCV's cvWaitKey( ) function do?

cvWaitKey(x) / cv::waitKey(x) does two things:

  1. It waits for x milliseconds for a key press on a OpenCV window (i.e. created from cv::imshow()). Note that it does not listen on stdin for console input. If a key was pressed during that time, it returns the key's ASCII code. Otherwise, it returns -1. (If x is zero, it waits indefinitely for the key press.)
  2. It handles any windowing events, such as creating windows with cv::namedWindow(), or showing images with cv::imshow().

A common mistake for opencv newcomers is to call cv::imshow() in a loop through video frames, without following up each draw with cv::waitKey(30). In this case, nothing appears on screen, because highgui is never given time to process the draw requests from cv::imshow().

jQuery $("#radioButton").change(...) not firing during de-selection

Same problem here, this worked just fine:

$('input[name="someRadioGroup"]').change(function() {
    $('#r1edit:input').prop('disabled', !$("#r1").is(':checked'));
});

How to get last inserted row ID from WordPress database?

Putting the call to mysql_insert_id() inside a transaction, should do it:

mysql_query('BEGIN');
// Whatever code that does the insert here.
$id = mysql_insert_id();
mysql_query('COMMIT');
// Stuff with $id.

Delete certain lines in a txt file via a batch file

If you have sed:

sed -e '/REFERENCE/d' -e '/ERROR/d' [FILENAME]

Where FILENAME is the name of the text file with the good & bad lines

Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries

Since Django 2.x, on_delete is required.

Django Documentation

Deprecated since version 1.9: on_delete will become a required argument in Django 2.0. In older versions it defaults to CASCADE.

What is the correct value for the disabled attribute?

From MDN by setAttribute():

To set the value of a Boolean attribute, such as disabled, you can specify any value. An empty string or the name of the attribute are recommended values. All that matters is that if the attribute is present at all, regardless of its actual value, its value is considered to be true. The absence of the attribute means its value is false. By setting the value of the disabled attribute to the empty string (""), we are setting disabled to true, which results in the button being disabled.

Link to MDN

Solution

  • I mean that in XHTML Strict is right disabled="disabled",
  • and in HTML5 is only disabled, like <input name="myinput" disabled>
  • In javascript, I set the value to true via e.disabled = true;
    or to "" via setAttribute( "disabled", "" );

Test in Chrome

var f = document.querySelectorAll( "label.disabled input" );
for( var i = 0; i < f.length; i++ )
{
    // Reference
    var e = f[ i ];

    // Actions
    e.setAttribute( "disabled", false|null|undefined|""|0|"disabled" );
    /*
        <input disabled="false"|"null"|"undefined"|empty|"0"|"disabled">
        e.getAttribute( "disabled" ) === "false"|"null"|"undefined"|""|"0"|"disabled"
        e.disabled === true
    */
    
    e.removeAttribute( "disabled" );
    /*
        <input>
        e.getAttribute( "disabled" ) === null
        e.disabled === false
    */

    e.disabled = false|null|undefined|""|0;
    /*
        <input>
        e.getAttribute( "disabled" ) === null|null|null|null|null
        e.disabled === false
    */

    e.disabled = true|" "|"disabled"|1;
    /*
        <input disabled>
        e.getAttribute( "disabled" ) === ""|""|""|""
        e.disabled === true
    */
}

Checking to see if one array's elements are in another array in PHP

You can use array_intersect().

$result = !empty(array_intersect($people, $criminals));

Reading numbers from a text file into an array in C

There are two problems in your code:

  • the return value of scanf must be checked
  • the %d conversion does not take overflows into account (blindly applying *10 + newdigit for each consecutive numeric character)

The first value you got (-104204697) is equals to 5623125698541159 modulo 2^32; it is thus the result of an overflow (if int where 64 bits wide, no overflow would happen). The next values are uninitialized (garbage from the stack) and thus unpredictable.

The code you need could be (similar to the answer of BLUEPIXY above, with the illustration how to check the return value of scanf, the number of items successfully matched):

#include <stdio.h>

int main(int argc, char *argv[]) {
    int i, j;
    short unsigned digitArray[16];
    i = 0;
    while (
        i != sizeof(digitArray) / sizeof(digitArray[0])
     && 1 == scanf("%1hu", digitArray + i)
    ) {
        i++;
    }
    for (j = 0; j != i; j++) {
        printf("%hu\n", digitArray[j]);
    }
    return 0;
}

Find a value anywhere in a database

Thanks for the really useful script.

You may need to add the following modification to the code if your tables have non-convertable fields:

SET @ColumnName =
    (
        SELECT MIN(QUOTENAME(COLUMN_NAME))
        FROM    INFORMATION_SCHEMA.COLUMNS
        WHERE       TABLE_SCHEMA    = PARSENAME(@TableName, 2)
            AND TABLE_NAME  = PARSENAME(@TableName, 1)
            AND DATA_TYPE NOT IN ('text', 'image', 'ntext')                 
            AND QUOTENAME(COLUMN_NAME) > @ColumnName
    )

Chris

how to bind img src in angular 2 in ngFor?

Angular 2 and Angular 4 

In a ngFor loop it must be look like this:

<div class="column" *ngFor="let u of events ">
                <div class="thumb">
                    <img src="assets/uploads/{{u.image}}">
                    <h4>{{u.name}}</h4>
                </div>
                <div class="info">
                    <img src="assets/uploads/{{u.image}}">
                    <h4>{{u.name}}</h4>
                    <p>{{u.text}}</p>
                </div>
            </div>

Address already in use: JVM_Bind java

The quick answer on how to prevent it is that you most likely need to stop JBoss before starting it again.

You should be able to call the "Terminate" button in the Console view to shutdown the server.

How can I set response header on express.js assets

Short Answer:

  • res.setHeaders - calls the native Node.js method

  • res.set - sets headers

  • res.headers - an alias to res.set

bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js

Use

/js/bootstrap.bundle.min.js

instead of

/js/bootstrap.min.js

Typescript: TS7006: Parameter 'xxx' implicitly has an 'any' type

I encounted this error and found that it was because the "strict" parameter was set to true in the tsconfig.json file. Just set it "false" (obviously). In my case I had generated the tsconfig file from the cmd prompt and simply missed the "strict" parameter, which was located further down in the file.

Html Agility Pack get all elements by class

I used this extension method a lot in my project. Hope it will help one of you guys.

public static bool HasClass(this HtmlNode node, params string[] classValueArray)
    {
        var classValue = node.GetAttributeValue("class", "");
        var classValues = classValue.Split(' ');
        return classValueArray.All(c => classValues.Contains(c));
    }

Showing ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)

numpy.dot(a, b, out=None)

Dot product of two arrays.

For N dimensions it is a sum product over the last axis of a and the second-to-last of b.

Documentation: numpy.dot.

How can I limit ngFor repeat to some number of items in Angular?

This seems simpler to me

<li *ngFor="let item of list | slice:0:10; let i=index" class="dropdown-item" (click)="onClick(item)">{{item.text}}</li>

Closer to your approach

<ng-container *ngFor="let item of list" let-i="index">
  <li class="dropdown-item" (click)="onClick(item)" *ngIf="i<11">{{item.text}}</li>
</ng-container>

How do I empty an array in JavaScript?

If you use constants then you have no choice:

const numbers = [1, 2, 3]

You can not reasign:

numbers = []

You can only truncate:

numbers.length = 0

How to format a JavaScript date

This Module can easily handle mostly every case there is. It is part of a bigger npm package, by Locutus, which includes a variety of functions, but can be used totally independent of the package it self, just copy paste/ adapt a little if not working with npm (change from module to just a function)

As a second parameter it accepts a timestamp, which can come from anywhere, such as Date.getTime()

Also, Locutus maintains a bigger datetime module, also inside the locutus package which will give a more object oriented way to use it

Here you can see other datetime functions, as modules, that proved to be very usefull too.

You can find documentation on parameters and format strings here (note that the doc site is a php site, but the locutus implementation follows exactly the same specs)

Examples of date Module

date('H:m:s \\m \\i\\s \\m\\o\\n\\t\\h', 1062402400)//'07:09:40 m is month'

date('F j, Y, g:i a', 1062462400)//'September 2, 2003, 12:26 am'

date('Y W o', 1062462400)//'2003 36 2003'

var $x = date('Y m d', (new Date()).getTime() / 1000) $x = $x + '' var $result = $x.length // 2009 01 09    10

date('W', 1104534000)   //'52'

date('B t', 1104534000) //'999 31'

date('W U', 1293750000.82); // 2010-12-31   '52 1293750000'

date('W', 1293836400); // 2011-01-01    '52'

date('W Y-m-d', 1293974054); // 2011-01-02  '52 2011-01-02'

Collapse all methods in Visual Studio Code

  • Ctrl + K + 0: fold all levels (namespace, class, method, and block)
  • Ctrl + K + 1: namspace
  • Ctrl + K + 2: class
  • Ctrl + K + 3: methods
  • Ctrl + K + 4: blocks
  • Ctrl + K + [ or Ctrl + k + ]: current cursor block
  • Ctrl + K + j: UnFold

Is there a foreach in MATLAB? If so, how does it behave if the underlying data changes?

Let's say you have an array of data:

n = [1    2   3   4   6   12  18  51  69  81  ]

then you can 'foreach' it like this:

for i = n, i, end

This will echo every element in n (but replacing the i with more interesting stuff is also possible of course!)

Could not open input file: artisan

This error happens because you didn't install composer on your project.

run composer install command in your project path.

unary operator expected in shell script when comparing null value with string

Since the value of $var is the empty string, this:

if [ $var == $var1 ]; then

expands to this:

if [ == abcd ]; then

which is a syntax error.

You need to quote the arguments:

if [ "$var" == "$var1" ]; then

You can also use = rather than ==; that's the original syntax, and it's a bit more portable.

If you're using bash, you can use the [[ syntax, which doesn't require the quotes:

if [[ $var = $var1 ]]; then

Even then, it doesn't hurt to quote the variable reference, and adding quotes:

if [[ "$var" = "$var1" ]]; then

might save a future reader a moment trying to remember whether [[ ... ]] requires them.

This view is not constrained

Solution

Just click this and it will be solved

jQuery UI Sortable, then write order into a database

This is my example.

https://github.com/luisnicg/jQuery-Sortable-and-PHP

You need to catch the order in the update event

    $( "#sortable" ).sortable({
    placeholder: "ui-state-highlight",
    update: function( event, ui ) {
        var sorted = $( "#sortable" ).sortable( "serialize", { key: "sort" } );
        $.post( "form/order.php",{ 'choices[]': sorted});
    }
});

No ConcurrentList<T> in .Net 4.0?

In cases where reads greatly outnumber writes, or (however frequent) writes are non-concurrent, a copy-on-write approach may be appropriate.

The implementation shown below is

  • lockless
  • blazingly fast for concurrent reads, even while concurrent modifications are ongoing - no matter how long they take
  • because "snapshots" are immutable, lockless atomicity is possible, i.e. var snap = _list; snap[snap.Count - 1]; will never (well, except for an empty list of course) throw, and you also get thread-safe enumeration with snapshot semantics for free.. how I LOVE immutability!
  • implemented generically, applicable to any data structure and any type of modification
  • dead simple, i.e. easy to test, debug, verify by reading the code
  • usable in .Net 3.5

For copy-on-write to work, you have to keep your data structures effectively immutable, i.e. no one is allowed to change them after you made them available to other threads. When you want to modify, you

  1. clone the structure
  2. make modifications on the clone
  3. atomically swap in the reference to the modified clone

Code

static class CopyOnWriteSwapper
{
    public static void Swap<T>(ref T obj, Func<T, T> cloner, Action<T> op)
        where T : class
    {
        while (true)
        {
            var objBefore = Volatile.Read(ref obj);
            var newObj = cloner(objBefore);
            op(newObj);
            if (Interlocked.CompareExchange(ref obj, newObj, objBefore) == objBefore)
                return;
        }
    }
}

Usage

CopyOnWriteSwapper.Swap(ref _myList,
    orig => new List<string>(orig),
    clone => clone.Add("asdf"));

If you need more performance, it will help to ungenerify the method, e.g. create one method for every type of modification (Add, Remove, ...) you want, and hard code the function pointers cloner and op.

N.B. #1 It is your responsibility to make sure the no one modifies the (supposedly) immutable data structure. There's nothing we can do in a generic implementation to prevent that, but when specializing to List<T>, you could guard against modification using List.AsReadOnly()

N.B. #2 Be careful about the values in the list. The copy on write approach above guards their list membership only, but if you'd put not strings, but some other mutable objects in there, you have to take care of thread safety (e.g. locking). But that is orthogonal to this solution and e.g. locking of the mutable values can be easily used without issues. You just need to be aware of it.

N.B. #3 If your data structure is huge and you modify it frequently, the copy-all-on-write approach might be prohibitive both in terms of memory consumption and the CPU cost of copying involved. In that case, you might want to use MS's Immutable Collections instead.

show/hide a div on hover and hover out

May be there no need for JS. You can achieve this with css also. Write like this:

.flyout {
    position: absolute;
    width: 1000px;
    height: 450px;
    background: red;
    overflow: hidden;
    z-index: 10000;
    display: none;
}
#menu:hover + .flyout {
    display: block;
}

How to make clang compile to llvm IR

If you have multiple files and you don't want to have to type each file, I would recommend that you follow these simple steps (I am using clang-3.8 but you can use any other version):

  1. generate all .ll files

    clang-3.8 -S -emit-llvm *.c
    
  2. link them into a single one

    llvm-link-3.8 -S -v -o single.ll *.ll
    
  3. (Optional) Optimise your code (maybe some alias analysis)

    opt-3.8 -S -O3 -aa -basicaaa -tbaa -licm single.ll -o optimised.ll
    
  4. Generate assembly (generates a optimised.s file)

    llc-3.8 optimised.ll
    
  5. Create executable (named a.out)

    clang-3.8 optimised.s
    

curl POST format for CURLOPT_POSTFIELDS

For CURLOPT_POSTFIELDS, the parameters can either be passed as a urlencoded string like para1=val1&para2=val2&.. or as an array with the field name as key and field data as value

Try the following format :

$data = json_encode(array(
"first"  => "John",
"last" => "Smith"
));

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
curl_close($ch);

Running Composer returns: "Could not open input file: composer.phar"

I got this error "Could not open input file: composer.phar" while installing Yii2 using below mentioned command.

php composer.phar create-project yiisoft/yii2-app-basic basic

Solutions which worked for me was, I changed the command to

composer create-project yiisoft/yii2-app-basic basic

I hope it help!

Add params to given URL in Python

You can also use the furl module https://github.com/gruns/furl

>>> from furl import furl
>>> print furl('http://example.com/search?q=question').add({'lang':'en','tag':'python'}).url
http://example.com/search?q=question&lang=en&tag=python

Center the nav in Twitter Bootstrap

For Bootstrap v4 check this:

https://v4-alpha.getbootstrap.com/components/pagination/#alignment

only add class to ul.pagination:

<nav">
  <ul class="pagination justify-content-center">
    <li class="page-item disabled">
      <a class="page-link" href="#" tabindex="-1">Previous</a>
    </li>
    <li class="page-item"><a class="page-link" href="#">1</a></li>
    <li class="page-item"><a class="page-link" href="#">2</a></li>
    <li class="page-item"><a class="page-link" href="#">3</a></li>
    <li class="page-item">
      <a class="page-link" href="#">Next</a>
    </li>
  </ul>
</nav>

Finding last index of a string in Oracle

Use -1 as the start position:

INSTR('JD-EQ-0001', '-', -1)

Creating a range of dates in Python

Matplotlib related

from matplotlib.dates import drange
import datetime

base = datetime.date.today()
end  = base + datetime.timedelta(days=100)
delta = datetime.timedelta(days=1)
l = drange(base, end, delta)

How to pass password automatically for rsync SSH command?

The official solution (and others) were incomplete when I first visited, so I came back, years later, to post this alternate approach in case any others wound up here intending to use a public/private key-pair:

Execute this from the target backup machine, which pulls from source to target backup

rsync -av --delete -e 'ssh -p 59333 -i /home/user/.ssh/id_rsa' [email protected]:/home/user/Server/ /home/keith/Server/

Execute this from the source machine, which sends from source to target backup

rsync -av --delete -e 'ssh -p 59333 -i /home/user/.ssh/id_rsa' /home/user/Server/ [email protected]:/home/user/Server/

And, if you are not using an alternate port for ssh, then consider the more elegant examples below:

Execute this from the target backup machine, which pulls from source to target backup:

sudo rsync -avi --delete [email protected]:/var/www/ /media/sdb1/backups/www/

Execute this from the source machine, which sends from source to target backup:

sudo rsync -avi --delete /media/sdb1/backups/www/ [email protected]:/var/www/

If you are still getting prompted for a password, then you need to check your ssh configuration in /etc/ssh/sshd_config and verify that the users in source and target each have the others' respective public ssh key by sending each over with ssh-copy-id [email protected].

(Again, this is for using ssh key-pairs without a password, as an alternate approach, and not for passing the password over via a file.)

submitting a form when a checkbox is checked

You can submit form by just clicking on checkbox by simple method in JavaScript. Inside form tag or Input attribute add following attribute:

    onchange="this.form.submit()"

Example:

<form>
      <div>
           <input type="checkbox">
      </div>
</form>

How to use default Android drawables

If you read through any of the discussions on the android development group you will see that they discourage the use of anything that isn't in the public SDK because the rest is subject to extensive change.

Operation must use an updatable query. (Error 3073) Microsoft Access

There is another scenario here that would apply. A file that was checked out of Visual Source Safe, for anyone still using it, that was not given "Writeablity", either in the View option or Check Out, will also recieve this error message.

Solution is to re-acquire the file from Source Safe and apply the Writeability setting.

Android: how to create Switch case from this?

switch(position) {
  case 0:
    ...
    break;
  case 1:
    ...
    break;
  default:
    ...

}

Did you mean that?

How to pass in password to pg_dump?

You can pass a password into pg_dump directly by using the following:

pg_dump "host=localhost port=5432 dbname=mydb user=myuser password=mypass" > mydb_export.sql

WAMP 403 Forbidden message on Windows 7

Thanks for your question. I'am using wamp 3 now. And I find an simple answer to do this under your question. But that answer should change a little on wamp 3. The steps are as following:

  1. Right click wamp icon
  2. Choose Wamp Setting
  3. Click the Menu item:online/offline
  4. Left click wamp icon
  5. You will find there is a new item called "Put online"

Excel - Sum column if condition is met by checking other column in same table

Actually a more refined solution is use the build-in function sumif, this function does exactly what you need, will only sum those expenses of a specified month.

example

=SUMIF(A2:A100,"=January",B2:B100)

Copying text to the clipboard using Java

For JavaFx based applications.

        //returns System Clipboard
        final Clipboard clipboard = Clipboard.getSystemClipboard();
        // ClipboardContent provides flexibility to store data in different formats
        final ClipboardContent content = new ClipboardContent();
        content.putString("Some text");
        content.putHtml("<b>Some</b> text");
        //this will be replaced by previous putString
        content.putString("Some different text");
        //set the content to clipboard
        clipboard.setContent(content);
       // validate before retrieving it
        if(clipboard.hasContent(DataFormat.HTML)){
            System.out.println(clipboard.getHtml());
        }
        if(clipboard.hasString()){
            System.out.println(clipboard.getString());
        }

ClipboardContent can save multiple data in several data formats like(html,url,plain text,image).

For more information see official documentation

Choosing bootstrap vs material design

As far as I know you can use all mentioned technologies separately or together. It's up to you. I think you look at the problem from the wrong angle. Material Design is just the way particular elements of the page are designed, behave and put together. Material Design provides great UI/UX, but it relies on the graphic layout (HTML/CSS) rather than JS (events, interactions).

On the other hand, AngularJS and Bootstrap are front-end frameworks that can speed up your development by saving you from writing tons of code. For example, you can build web app utilizing AngularJS, but without Material Design. Or You can build simple HTML5 web page with Material Design without AngularJS or Bootstrap. Finally you can build web app that uses AngularJS with Bootstrap and with Material Design. This is the best scenario. All technologies support each other.

  1. Bootstrap = responsive page
  2. AngularJS = MVC
  3. Material Design = great UI/UX

You can check awesome material design components for AngularJS:

https://material.angularjs.org


enter image description here

Demo: https://material.angularjs.org/latest/demo/ enter image description here

SQL Server format decimal places with commas

If you are using SQL Azure Reporting Services, the "format" function is unsupported. This is really the only way to format a tooltip in a chart in SSRS. So the workaround is to return a column that has a string representation of the formatted number to use for the tooltip. So, I do agree that SQL is not the place for formatting. Except in cases like this where the tool does not have proper functions to handle display formatting.

In my case I needed to show a number formatted with commas and no decimals (type decimal 2) and ended up with this gem of a calculated column in my dataset query:

,Fmt_DDS=reverse(stuff(reverse(CONVERT(varchar(25),cast(SUM(kv.DeepDiveSavingsEst) as money),1)), 1, 3, ''))

It works, but is very ugly and non-obvious to whoever maintains the report down the road. Yay Cloud!

dynamically set iframe src

You should also consider that in some Opera versions onload is fired several times and add some hooks:

// fixing Opera 9.26, 10.00
if (doc.readyState && doc.readyState != 'complete') {
    // Opera fires load event multiple times
    // Even when the DOM is not ready yet
    // this fix should not affect other browsers
    return;
}

// fixing Opera 9.64
if (doc.body && doc.body.innerHTML == "false") {
    // In Opera 9.64 event was fired second time
    // when body.innerHTML changed from false
    // to server response approx. after 1 sec
    return;
}

Code borrowed from Ajax Upload

How to test Spring Data repositories?

I solved this by using this way -

    @RunWith(SpringRunner.class)
    @EnableJpaRepositories(basePackages={"com.path.repositories"})
    @EntityScan(basePackages={"com.model"})
    @TestPropertySource("classpath:application.properties")
    @ContextConfiguration(classes = {ApiTestConfig.class,SaveActionsServiceImpl.class})
    public class SaveCriticalProcedureTest {

        @Autowired
        private SaveActionsService saveActionsService;
        .......
        .......
}

Java "lambda expressions not supported at this language level"

Possible Cause #1 (same as the first 3 answers for this question): Project Structure Settings

  1. File > Project Structure > Under Project Settings, go to Project > set Project SDK to 1.8 (with version 65 or above, latest is 112) and set Project Language Level to 8.

  2. File > Project Structure > Under Platform Settings, go to Project > ensure that your JDK home path is set to 1.8 (with version 65 or above, latest is 112).

If the above does not work, check the target bytecode version of your compiler and move on to Possible Cause #2.

Possible Cause #2: Compiler

  1. File > Settings > Build, Execution, Deployment > Under Compiler, go to Java Compiler > set your Project Bytecode Version to 1.8, as well as all the Target Bytecode Version for your modules. Click Apply and hit OK. Restart your IntelliJ IDE. Lambda expression was accepted in my IDE at this point.

Best wishes :)

How to install xgboost in Anaconda Python (Windows platform)?

Anaconda's website addresses this problem here: https://anaconda.org/anaconda/py-xgboost.

conda install -c anaconda py-xgboost

This fixed the problem for me with no problems.

Using the Web.Config to set up my SQL database connection string?

http://www.connectionstrings.com is a site where you can find a lot of connection strings. All that you need to do is copy-paste and modify it to suit your needs. It is sure to have all the connection strings for all of your needs.

JavaScript - cannot set property of undefined

i'd just do a simple check to see if d[a] exists and if not initialize it...

var a = "1",
    b = "hello",
    c = { "100" : "some important data" },
    d = {};

    if (d[a] === undefined) {
        d[a] = {}
    };
    d[a]["greeting"] = b;
    d[a]["data"] = c;

    console.debug (d);

How do you create vectors with specific intervals in R?

Use the code

x = seq(0,100,5) #this means (starting number, ending number, interval)

the output will be

[1]   0   5  10  15  20  25  30  35  40  45  50  55  60  65  70  75
[17]  80  85  90  95 100

urllib and "SSL: CERTIFICATE_VERIFY_FAILED" Error

To expand on Craig Glennie's answer:

in Python 3.6.1 on MacOs Sierra

Entering this in the bash terminal solved the problem:

pip install certifi
/Applications/Python\ 3.6/Install\ Certificates.command

How do you run a single query through mysql from the command line?

here's how you can do it with a cool shell trick:

mysql -uroot -p -hslavedb.mydomain.com mydb_production <<< 'select * from users'

'<<<' instructs the shell to take whatever follows it as stdin, similar to piping from echo.

use the -t flag to enable table-format output

Get Public URL for File - Google Cloud Storage - App Engine (Python)

You need to use get_serving_url from the Images API. As that page explains, you need to call create_gs_key() first to get the key to pass to the Images API.

Regex date validation for yyyy-mm-dd

A simple one would be

\d{4}-\d{2}-\d{2}

Regular expression visualization

Debuggex Demo

but this does not restrict month to 1-12 and days from 1 to 31.

There are more complex checks like in the other answers, by the way pretty clever ones. Nevertheless you have to check for a valid date, because there are no checks for if a month has 28, 30, or 31 days.

How to write :hover condition for a:before and a:after?

or you can set pointer-events:none to your a element and pointer-event:all to your a:before element, and then add hover CSS to a element

a{
    pointer-events:none;
}
a:before{
    pointer-events:all
}
a:hover:before{
    background:blue;
}

How do I pass parameters into a PHP script through a webpage?

Presumably you're passing the arguments in on the command line as follows:

php /path/to/wwwpublic/path/to/script.php arg1 arg2

... and then accessing them in the script thusly:

<?php
// $argv[0] is '/path/to/wwwpublic/path/to/script.php'
$argument1 = $argv[1];
$argument2 = $argv[2];
?>

What you need to be doing when passing arguments through HTTP (accessing the script over the web) is using the query string and access them through the $_GET superglobal:

Go to http://yourdomain.com/path/to/script.php?argument1=arg1&argument2=arg2

... and access:

<?php
$argument1 = $_GET['argument1'];
$argument2 = $_GET['argument2'];
?>

If you want the script to run regardless of where you call it from (command line or from the browser) you'll want something like the following:

EDIT: as pointed out by Cthulhu in the comments, the most direct way to test which environment you're executing in is to use the PHP_SAPI constant. I've updated the code accordingly:

<?php
if (PHP_SAPI === 'cli') {
    $argument1 = $argv[1];
    $argument2 = $argv[2];
}
else {
    $argument1 = $_GET['argument1'];
    $argument2 = $_GET['argument2'];
}
?>

Using grep to search for hex strings in a file

This seems to work for me:

LANG=C grep --only-matching --byte-offset --binary --text --perl-regexp "<\x-hex pattern>" <file>

short form:

LANG=C grep -obUaP "<\x-hex pattern>" <file>

Example:

LANG=C grep -obUaP "\x01\x02" /bin/grep

Output (cygwin binary):

153: <\x01\x02>
33210: <\x01\x02>
53453: <\x01\x02>

So you can grep this again to extract offsets. But don't forget to use binary mode again.

Note: LANG=C is needed to avoid utf8 encoding issues.

JQuery ajax call default timeout value

As an aside, when trying to diagnose a similar bug I realised that jquery's ajax error callback returns a status of "timeout" if it failed due to a timeout.

Here's an example:

$.ajax({
    url: "/ajax_json_echo/",
    timeout: 500,
    error: function(jqXHR, textStatus, errorThrown) {
        alert(textStatus); // this will be "timeout"
    }
});

Here it is on jsfiddle.

How to use SharedPreferences in Android to store, fetch and edit values

Simple and hassle-free :: "Android-SharedPreferences-Helper" library

Better late than never: I created the "Android-SharedPreferences-Helper" library to help reduce the complexity and effort of using SharedPreferences. It also provides some extended functionality. Few things that it offers are as follows:

  • One line initialization and setup
  • Easily selecting whether to use default preferences or a custom preference file
  • Predefined (data type defaults) and customizable (what you may choose) default values for each datatype
  • Ability to set different default value for single use with just an additional param
  • You can register and unregister OnSharedPreferenceChangeListener as you do for default class
dependencies {
    ...
    ...
    compile(group: 'com.viralypatel.sharedpreferenceshelper', name: 'library', version: '1.1.0', ext: 'aar')
}

Declaration of SharedPreferencesHelper object: (recommended at class level)

SharedPreferencesHelper sph; 

Instantiation of the SharedPreferencesHelper object: (recommended in onCreate() method)

// use one of the following ways to instantiate
sph = new SharedPreferencesHelper(this); //this will use default shared preferences
sph = new SharedPreferencesHelper(this, "myappprefs"); // this will create a named shared preference file
sph = new SharedPreferencesHelper(this, "myappprefs", 0); // this will allow you to specify a mode

Putting values into shared preferences

Fairly simple! Unlike the default way (when using the SharedPreferences class) you'll NOT need to call .edit() and .commit() ever time.

sph.putBoolean("boolKey", true);
sph.putInt("intKey", 123);
sph.putString("stringKey", "string value");
sph.putLong("longKey", 456876451);
sph.putFloat("floatKey", 1.51f);

// putStringSet is supported only for android versions above HONEYCOMB
Set name = new HashSet();
name.add("Viral");
name.add("Patel");
sph.putStringSet("name", name);

That's it! Your values are stored in the shared preferences.

Getting values from shared preferences

Again, just one simple method call with the key name.

sph.getBoolean("boolKey");
sph.getInt("intKey");
sph.getString("stringKey");
sph.getLong("longKey");
sph.getFloat("floatKey");

// getStringSet is supported only for android versions above HONEYCOMB
sph.getStringSet("name");

It has a lot of other extended functionality

Check the details of extended functionality, usage and installation instructions etc on the GitHub Repository Page.

Python error: "IndexError: string index out of range"

It looks like you indented so_far = new too much. Try this:

if guess in word:
    print("\nYes!", guess, "is in the word!")

    # Create a new variable (so_far) to contain the guess
    new = ""
    i = 0
    for i in range(len(word)):
        if guess == word[i]:
            new += guess
        else:
            new += so_far[i]
    so_far = new # unindented this

How to increase the timeout period of web service in asp.net?

you can do this in different ways:

  1. Setting a timeout in the web service caller from code (not 100% sure but I think I have seen this done);
  2. Setting a timeout in the constructor of the web service proxy in the web references;
  3. Setting a timeout in the server side, web.config of the web service application.

see here for more details on the second case:

http://msdn.microsoft.com/en-us/library/ff647786.aspx#scalenetchapt10_topic14

and here for details on the last case:

How to increase the timeout to a web service request?

Remove characters from a String in Java

Kotlin Solution

Kotlin has a built-in function for this, removeSuffix (Documentation)

var text = "filename.xml"
text = text.removeSuffix(".xml") // "filename"

If the suffix does not exist in the string, it just returns the original

var text = "not_a_filename"
text = text.removeSuffix(".xml") // "not_a_filename"

You can also check out removePrefix and removeSurrounding which are similar

How to properly use jsPDF library

first, you have to create a handler.

var specialElementHandlers = {
    '#editor': function(element, renderer){
        return true;
    }
};

then write this code in click event:

doc.fromHTML($('body').get(0), 15, 15, {
    'width': 170, 
    'elementHandlers': specialElementHandlers
        });

var pdfOutput = doc.output();
            console.log(">>>"+pdfOutput );

assuming you've already declared doc variable. And Then you have save this pdf file using File-Plugin.

How do I concatenate const/literal strings in C?

Also malloc and realloc are useful if you don't know ahead of time how many strings are being concatenated.

#include <stdio.h>
#include <string.h>

void example(const char *header, const char **words, size_t num_words)
{
    size_t message_len = strlen(header) + 1; /* + 1 for terminating NULL */
    char *message = (char*) malloc(message_len);
    strncat(message, header, message_len);

    for(int i = 0; i < num_words; ++i)
    {
       message_len += 1 + strlen(words[i]); /* 1 + for separator ';' */
       message = (char*) realloc(message, message_len);
       strncat(strncat(message, ";", message_len), words[i], message_len);
    }

    puts(message);

    free(message);
}

Python + Regex: AttributeError: 'NoneType' object has no attribute 'groups'

import re

htmlString = '</dd><dt> Fine, thank you.&#160;</dt><dd> Molt bé, gràcies. (<i>mohl behh, GRAH-syuhs</i>)'

SearchStr = '(\<\/dd\>\<dt\>)+ ([\w+\,\.\s]+)([\&\#\d\;]+)(\<\/dt\>\<dd\>)+ ([\w\,\s\w\s\w\?\!\.]+) (\(\<i\>)([\w\s\,\-]+)(\<\/i\>\))'

Result = re.search(SearchStr.decode('utf-8'), htmlString.decode('utf-8'), re.I | re.U)

print Result.groups()

Works that way. The expression contains non-latin characters, so it usually fails. You've got to decode into Unicode and use re.U (Unicode) flag.

I'm a beginner too and I faced that issue a couple of times myself.

How to include an HTML page into another HTML page without frame/iframe?

Also make sure to check out how to use Angular includes (using AngularJS). It's pretty straight forward…

<body ng-app="">
  <div ng-include="'myFile.htm'"></div>
</body> 

Increment value in mysql update query

You could also just do this:

mysql_query("
    UPDATE member_profile 
    SET points = points + 1
    WHERE user_id = '".$userid."'
");

Java array reflection: isArray vs. instanceof

There is no difference in behavior that I can find between the two (other than the obvious null-case). As for which version to prefer, I would go with the second. It is the standard way of doing this in Java.

If it confuses readers of your code (because String[] instanceof Object[] is true), you may want to use the first to be more explicit if code reviewers keep asking about it.

JavaScript require() on client side

You can create elements to the DOM, which loads items.

Like such:

var myScript = document.createElement('script'); // Create new script element
myScript.type = 'text/javascript'; // Set appropriate type
myScript.src = './js/myclass.js'; // Load javascript file

How to get the cookie value in asp.net website

You may use Request.Cookies collection to read the cookies.

if(Request.Cookies["key"]!=null)
{
   var value=Request.Cookies["key"].Value;
}

How to initialize an array's length in JavaScript?

As explained above, using new Array(size) is somewhat dangerous. Instead of using it directly, place it inside an "array creator function". You can easily make sure that this function is bug-free and you avoid the danger of calling new Array(size) directly. Also, you can give it an optional default initial value. This createArray function does exactly that:

function createArray(size, defaultVal) {
    const arr = new Array(size);
    if (defaultVal !== undefined) {
        // optional default value
        for (let i = 0; i < size; ++i) {
            arr[i] = defaultVal;
        }
    }
    return arr;
}

Finding row index containing maximum value using R

See ?order. You just need the last index (or first, in decreasing order), so this should do the trick:

order(matrix[,2],decreasing=T)[1]

Jenkins - How to access BUILD_NUMBER environment variable

To Answer your first question, Jenkins variables are case sensitive. However, if you are writing a windows batch script, they are case insensitive, because Windows doesn't care about the case.

Since you are not very clear about your setup, let's make the assumption that you are using an ant build step to fire up your ant task. Have a look at the Jenkins documentation (same page that Adarsh gave you, but different chapter) for an example on how to make Jenkins variables available to your ant task.

EDIT:

Hence, I will need to access the environmental variable ${BUILD_NUMBER} to construct the URL.

Why don't you use $BUILD_URL then? Isn't it available in the extended email plugin?

What is the ideal data type to use when storing latitude / longitude in a MySQL database?

MySQL uses double for all floats ... So use type double. Using float will lead to unpredictable rounded values in most situations

how can I copy a conditional formatting in Excel 2010 to other cells, which is based on a other cells content?

I had this problem too and couldn't solve it without using VBA.

In my case I had a table with numbers that I wanted to be formatted and a corresponding table next to it with the desired formatting values.

i.e. While column F contains the values I want to format, the desired formatting for each cell is captured in column Z, expressed as "RED", "AMBER" or "GREEN."

Quick solution below. Manually select the range to which to apply the conditional formatting and then run the macro.

   Sub ConditionalFormatting()
For Each Cell In Selection.Cells
With Cell
    'clean
    .FormatConditions.Delete

    'green rule
    .FormatConditions.Add Type:=xlExpression, Formula1:= _
        "=$Z" & Cell.Row & "=""GREEN"""
    .FormatConditions(.FormatConditions.Count).SetFirstPriority
    With .FormatConditions(1).Font
        .Color = -11489280
        .TintAndShade = 0
    End With
    .FormatConditions(1).StopIfTrue = False

    'amber rule
    .FormatConditions.Add Type:=xlExpression, Formula1:= _
        "=$Z" & Cell.Row & "=""AMBER"""
    .FormatConditions(.FormatConditions.Count).SetFirstPriority
    With .FormatConditions(1).Font
        .ThemeColor = xlThemeColorAccent6
        .TintAndShade = -0.249946592608417
    End With
    .FormatConditions(1).StopIfTrue = False

    'red rule
    .FormatConditions.Add Type:=xlExpression, Formula1:= _
        "=$Z" & Cell.Row & "=""RED"""
    .FormatConditions(.FormatConditions.Count).SetFirstPriority
    With .FormatConditions(1).Font
        .Color = -16776961
        .TintAndShade = 0
    End With
    .FormatConditions(1).StopIfTrue = False
End With

Next Cell

End Sub

How do I print my Java object without getting "SomeType@2f92e0f4"?

I prefer to use a utility function which uses GSON to de-serialize the Java object into JSON string.

/**
 * This class provides basic/common functionalities to be applied on Java Objects.
 */
public final class ObjectUtils {

    private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();

    private ObjectUtils() {
         throw new UnsupportedOperationException("Instantiation of this class is not permitted in case you are using reflection.");
    }

    /**
     * This method is responsible for de-serializing the Java Object into Json String.
     *
     * @param object Object to be de-serialized.
     * @return String
     */
    public static String deserializeObjectToString(final Object object) {
        return GSON.toJson(object);
    }
}

Converting a string to an integer on Android

Kotlin

There are available Extension methods to parse them into other primitive types.

Java

String num = "10";
Integer.parseInt(num );

How to edit a text file in my terminal

You can open the file again using vi helloworld.txt and then use cat /path/your_file to view it.

Angular2 QuickStart npm start is not working correctly

Change the start field in package.json from:

"start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" "

To:

"start": "concurrently \"npm run tsc:w\" \"npm run lite\" "

It really helped.

Python timedelta in years

Yet another 3rd party lib not mentioned here is mxDateTime (predecessor of both python datetime and 3rd party timeutil) could be used for this task.

The aforementioned yearsago would be:

from mx.DateTime import now, RelativeDateTime

def years_ago(years, from_date=None):
    if from_date == None:
        from_date = now()
    return from_date-RelativeDateTime(years=years)

First parameter is expected to be a DateTime instance.

To convert ordinary datetime to DateTime you could use this for 1 second precision):

def DT_from_dt_s(t):
    return DT.DateTimeFromTicks(time.mktime(t.timetuple()))

or this for 1 microsecond precision:

def DT_from_dt_u(t):
    return DT.DateTime(t.year, t.month, t.day, t.hour,
  t.minute, t.second + t.microsecond * 1e-6)

And yes, adding the dependency for this single task in question would definitely be an overkill compared even with using timeutil (suggested by Rick Copeland).

__init__() missing 1 required positional argument

If error is like Author=models.ForeignKey(User, related_names='blog_posts') TypeError:init() missing 1 required positional argument:'on_delete'

Then the solution will be like, you have to add one argument Author=models.ForeignKey(User, related_names='blog_posts', on_delete=models.DO_NOTHING)

Dump Mongo Collection into JSON format

Use mongoexport/mongoimport to dump/restore a collection:

Export JSON File:

mongoexport --db <database-name> --collection <collection-name> --out output.json

Import JSON File:

mongoimport --db <database-name> --collection <collection-name> --file input.json

WARNING mongoimport and mongoexport do not reliably preserve all rich BSON data types because JSON can only represent a subset of the types supported by BSON. As a result, data exported or imported with these tools may lose some measure of fidelity.

Also, http://bsonspec.org/

BSON is designed to be fast to encode and decode. For example, integers are stored as 32 (or 64) bit integers, so they don't need to be parsed to and from text. This uses more space than JSON for small integers, but is much faster to parse.

In addition to compactness, BSON adds additional data types unavailable in JSON, notably the BinData and Date data types.

JavaScript global event mechanism

Does this help you:

<script type="text/javascript">
window.onerror = function() {
    alert("Error caught");
};

xxx();
</script>

I'm not sure how it handles Flash errors though...

Update: it doesn't work in Opera, but I'm hacking Dragonfly right now to see what it gets. Suggestion about hacking Dragonfly came from this question:

Mimic Window. onerror in Opera using javascript

How to decrease prod bundle size?

I have a angular 5 + spring boot app(application.properties 1.3+) with help of compression(link attached below) was able to reduce the size of main.bundle.ts size from 2.7 MB to 530 KB.

Also by default --aot and --build-optimizer are enabled with --prod mode you need not specify those separately.

https://stackoverflow.com/a/28216983/9491345

How do I remove an item from a stl vector with a certain value?

If you have an unsorted vector, then you can simply swap with the last vector element then resize().

With an ordered container, you'll be best off with ?std::vector::erase(). Note that there is a std::remove() defined in <algorithm>, but that doesn't actually do the erasing. (Read the documentation carefully).

Easiest way to rotate by 90 degrees an image using OpenCV?

Update for transposition:

You should use cvTranspose() or cv::transpose() because (as you rightly pointed out) it's more efficient. Again, I recommend upgrading to OpenCV2.0 since most of the cvXXX functions just convert IplImage* structures to Mat objects (no deep copies). If you stored the image in a Mat object, Mat.t() would return the transpose.

Any rotation:

You should use cvWarpAffine by defining the rotation matrix in the general framework of the transformation matrix. I would highly recommend upgrading to OpenCV2.0 which has several features as well as a Mat class which encapsulates matrices and images. With 2.0 you can use warpAffine to the above.

What's the proper way to "go get" a private repository?

I came across .netrc and found it relevant to this.

Create a file ~/.netrc with the following content:

machine github.com
    login <github username>
    password <github password or Personal access tokens >

Done!

Additionally, for latest GO versions, you might need to add this to the environment variables GOPRIVATE=github.com (I've added it to my .zshrc)

netrc also makes my development environment setup better as my personal github access for HTTPS is been configured now to be used across the machine (just like my SSH configuration).

Generate GitHub personal access tokens: https://github.com/settings/tokens

See this answer for its use with Git on Windows specifically

Ref: netrc man page


If you want to stick with the SSH authentication, then mask the request to use ssh forcefully

git config --global url."[email protected]:".insteadOf "https://github.com/"


More methods for setting up git access: https://gist.github.com/technoweenie/1072829#gistcomment-2979908

How can I use an array of function pointers?

This question has been already answered with very good examples. The only example that might be missing is one where the functions return pointers. I wrote another example with this, and added lots of comments, in case someone finds it helpful:

#include <stdio.h>

char * func1(char *a) {
    *a = 'b';
    return a;
}

char * func2(char *a) {
    *a = 'c';
    return a;
}

int main() {
    char a = 'a';
    /* declare array of function pointers
     * the function pointer types are char * name(char *)
     * A pointer to this type of function would be just
     * put * before name, and parenthesis around *name:
     *   char * (*name)(char *)
     * An array of these pointers is the same with [x]
     */
    char * (*functions[2])(char *) = {func1, func2};
    printf("%c, ", a);
    /* the functions return a pointer, so I need to deference pointer
     * Thats why the * in front of the parenthesis (in case it confused you)
     */
    printf("%c, ", *(*functions[0])(&a)); 
    printf("%c\n", *(*functions[1])(&a));

    a = 'a';
    /* creating 'name' for a function pointer type
     * funcp is equivalent to type char *(*funcname)(char *)
     */
    typedef char *(*funcp)(char *);
    /* Now the declaration of the array of function pointers
     * becomes easier
     */
    funcp functions2[2] = {func1, func2};

    printf("%c, ", a);
    printf("%c, ", *(*functions2[0])(&a));
    printf("%c\n", *(*functions2[1])(&a));

    return 0;
}

android download pdf from url then open it with a pdf reader

This is the best method to download and view PDF file.You can just call it from anywhere as like

PDFTools.showPDFUrl(context, url);

here below put the code. It will works fine

public class PDFTools {
private static final String TAG = "PDFTools";
private static final String GOOGLE_DRIVE_PDF_READER_PREFIX = "http://drive.google.com/viewer?url=";
private static final String PDF_MIME_TYPE = "application/pdf";
private static final String HTML_MIME_TYPE = "text/html";


public static void showPDFUrl(final Context context, final String pdfUrl ) {
    if ( isPDFSupported( context ) ) {
        downloadAndOpenPDF(context, pdfUrl);
    } else {
        askToOpenPDFThroughGoogleDrive( context, pdfUrl );
    }
}


@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public static void downloadAndOpenPDF(final Context context, final String pdfUrl) {
    // Get filename
    //final String filename = pdfUrl.substring( pdfUrl.lastIndexOf( "/" ) + 1 );
    String filename = "";
    try {
        filename = new GetFileInfo().execute(pdfUrl).get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    // The place where the downloaded PDF file will be put
    final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), filename );
    Log.e(TAG,"File Path:"+tempFile);
    if ( tempFile.exists() ) {
        // If we have downloaded the file before, just go ahead and show it.
        openPDF( context, Uri.fromFile( tempFile ) );
        return;
    }

    // Show progress dialog while downloading
    final ProgressDialog progress = ProgressDialog.show( context, context.getString( R.string.pdf_show_local_progress_title ), context.getString( R.string.pdf_show_local_progress_content ), true );

    // Create the download request
    DownloadManager.Request r = new DownloadManager.Request( Uri.parse( pdfUrl ) );
    r.setDestinationInExternalFilesDir( context, Environment.DIRECTORY_DOWNLOADS, filename );
    final DownloadManager dm = (DownloadManager) context.getSystemService( Context.DOWNLOAD_SERVICE );
    BroadcastReceiver onComplete = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ( !progress.isShowing() ) {
                return;
            }
            context.unregisterReceiver( this );

            progress.dismiss();
            long downloadId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, -1 );
            Cursor c = dm.query( new DownloadManager.Query().setFilterById( downloadId ) );

            if ( c.moveToFirst() ) {
                int status = c.getInt( c.getColumnIndex( DownloadManager.COLUMN_STATUS ) );
                if ( status == DownloadManager.STATUS_SUCCESSFUL ) {
                    openPDF( context, Uri.fromFile( tempFile ) );
                }
            }
            c.close();
        }
    };
    context.registerReceiver( onComplete, new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE ) );

    // Enqueue the request
    dm.enqueue( r );
}


public static void askToOpenPDFThroughGoogleDrive( final Context context, final String pdfUrl ) {
    new AlertDialog.Builder( context )
            .setTitle( R.string.pdf_show_online_dialog_title )
            .setMessage( R.string.pdf_show_online_dialog_question )
            .setNegativeButton( R.string.pdf_show_online_dialog_button_no, null )
            .setPositiveButton( R.string.pdf_show_online_dialog_button_yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    openPDFThroughGoogleDrive(context, pdfUrl);
                }
            })
            .show();
}

public static void openPDFThroughGoogleDrive(final Context context, final String pdfUrl) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    i.setDataAndType(Uri.parse(GOOGLE_DRIVE_PDF_READER_PREFIX + pdfUrl ), HTML_MIME_TYPE );
    context.startActivity( i );
}

public static final void openPDF(Context context, Uri localUri ) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    i.setDataAndType( localUri, PDF_MIME_TYPE );
    context.startActivity( i );
}

public static boolean isPDFSupported( Context context ) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), "test.pdf" );
    i.setDataAndType( Uri.fromFile( tempFile ), PDF_MIME_TYPE );
    return context.getPackageManager().queryIntentActivities( i, PackageManager.MATCH_DEFAULT_ONLY ).size() > 0;
}

// get File name from url
static class GetFileInfo extends AsyncTask<String, Integer, String>
{
    protected String doInBackground(String... urls)
    {
        URL url;
        String filename = null;
        try {
            url = new URL(urls[0]);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            conn.setInstanceFollowRedirects(false);
            if(conn.getHeaderField("Content-Disposition")!=null){
                String depo = conn.getHeaderField("Content-Disposition");

                String depoSplit[] = depo.split("filename=");
                filename = depoSplit[1].replace("filename=", "").replace("\"", "").trim();
            }else{
                filename = "download.pdf";
            }
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
        }
        return filename;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        // use result as file name
    }
}

}

try it. it will works, enjoy

How to go back to previous page if back button is pressed in WebView?

In kotlin:

override fun onBackPressed() {
    when {
        webView.canGoBack() -> webView.goBack()
        else -> super.onBackPressed()
    }
}

webView - id of the webview component in xml, if using synthetic reference.

How to use bootstrap datepicker

You should include bootstrap-datepicker.js after bootstrap.js and you should bind the datepicker to your control.

$(function(){
   $('.datepicker').datepicker({
      format: 'mm-dd-yyyy'
    });
});

SASS :not selector

I tried re-creating this, and .someclass.notip was being generated for me but .someclass:not(.notip) was not, for as long as I did not have the @mixin tip() defined. Once I had that, it all worked.

http://sassmeister.com/gist/9775949

$dropdown-width: 100px;
$comp-tip: true;

@mixin tip($pos:right) {

}

@mixin dropdown-pos($pos:right) {
  &:not(.notip) {
    @if $comp-tip == true{
      @if $pos == right {
        top:$dropdown-width * -0.6;
        background-color: #f00;
        @include tip($pos:$pos);
      }
    }
  }
  &.notip {
    @if $pos == right {
      top: 0;
      left:$dropdown-width * 0.8;
      background-color: #00f;
    }
  }
}

.someclass { @include dropdown-pos(); }

EDIT: http://sassmeister.com/ is a good place to debug your SASS because it gives you error messages. Undefined mixin 'tip'. it what I get when I remove @mixin tip($pos:right) { }

How to adjust gutter in Bootstrap 3 grid system?

(Posted on behalf of the OP).

I believe I figured it out.

In my case, I added [class*="col-"] {padding: 0 7.5px;};.

Then added .row {margin: 0 -7.5px;}.

This works pretty well, except there is 1px margin on both sides. So I just make .row {margin: 0 -7.5px;} to .row {margin: 0 -8.5px;}, then it works perfectly.

I have no idea why there is a 1px margin. Maybe someone can explain it?

See the sample I created:

Demo
Code

Passing data to a jQuery UI Dialog

jQuery provides a method which store data for you, no need to use a dummy attribute or to find workaround to your problem.

Bind the click event:

$('a[href*=/Booking.aspx/Change]').bind('click', function(e) {
    e.preventDefault();
    $("#dialog-confirm")
        .data('link', this)  // The important part .data() method
        .dialog('open');
});

And your dialog:

$("#dialog-confirm").dialog({
    autoOpen: false,
    resizable: false,
    height:200,
    modal: true,
    buttons: {
        Cancel: function() {
            $(this).dialog('close');
        },
        'Delete': function() {
            $(this).dialog('close');
            var path = $(this).data('link').href; // Get the stored result
            $(location).attr('href', path);
        }
    }
});

Using Mockito, how do I verify a method was a called with a certain argument?

Building off of Mamboking's answer:

ContractsDao mock_contractsDao = mock(ContractsDao.class);
when(mock_contractsDao.save(anyString())).thenReturn("Some result");

m_orderSvc.m_contractsDao = mock_contractsDao;
m_prog = new ProcessOrdersWorker(m_orderSvc, m_opportunitySvc, m_myprojectOrgSvc);
m_prog.work(); 

Addressing your request to verify whether the argument contains a certain value, I could assume you mean that the argument is a String and you want to test whether the String argument contains a substring. For this you could do:

ArgumentCaptor<String> savedCaptor = ArgumentCaptor.forClass(String.class);
verify(mock_contractsDao).save(savedCaptor.capture());
assertTrue(savedCaptor.getValue().contains("substring I want to find");

If that assumption was wrong, and the argument to save() is a collection of some kind, it would be only slightly different:

ArgumentCaptor<Collection<MyType>> savedCaptor = ArgumentCaptor.forClass(Collection.class);
verify(mock_contractsDao).save(savedCaptor.capture());
assertTrue(savedCaptor.getValue().contains(someMyTypeElementToFindInCollection);

You might also check into ArgumentMatchers, if you know how to use Hamcrest matchers.

Constructing pandas DataFrame from values in variables gives "ValueError: If using all scalar values, you must pass an index"

Maybe Series would provide all the functions you need:

pd.Series({'A':a,'B':b})

DataFrame can be thought of as a collection of Series hence you can :

  • Concatenate multiple Series into one data frame (as described here )

  • Add a Series variable into existing data frame ( example here )

PLS-00103: Encountered the symbol "CREATE"

For me / had to be in a new line.

For example

create type emp_t;/

didn't work

but

create type emp_t;

/

worked.

How to call a method in another class in Java?

You should capitalize names of your classes. After doing that do this in your school class,

Classroom cls = new Classroom();
cls.setTeacherName(newTeacherName);

Also I'd recommend you use some kind of IDE such as eclipse, which can help you with your code for instance generate getters and setters for you. Ex: right click Source -> Generate getters and setters

How do you stop MySQL on a Mac OS install?

Apparently you want:

sudo /Library/StartupItems/MySQLCOM/MySQLCOM stop

Have a further read in Jeez People, Stop Fretting Over Installing RMagic.

Generating Unique Random Numbers in Java

I have made this like that.

    Random random = new Random();
    ArrayList<Integer> arrayList = new ArrayList<Integer>();

    while (arrayList.size() < 6) { // how many numbers u need - it will 6
        int a = random.nextInt(49)+1; // this will give numbers between 1 and 50.

        if (!arrayList.contains(a)) {
            arrayList.add(a);
        }
    }

How to parse unix timestamp to time.Time

The time.Parse function does not do Unix timestamps. Instead you can use strconv.ParseInt to parse the string to int64 and create the timestamp with time.Unix:

package main

import (
    "fmt"
    "time"
    "strconv"
)

func main() {
    i, err := strconv.ParseInt("1405544146", 10, 64)
    if err != nil {
        panic(err)
    }
    tm := time.Unix(i, 0)
    fmt.Println(tm)
}

Output:

2014-07-16 20:55:46 +0000 UTC

Playground: http://play.golang.org/p/v_j6UIro7a

Edit:

Changed from strconv.Atoi to strconv.ParseInt to avoid int overflows on 32 bit systems.

How do I get a value of datetime.today() in Python that is "timezone aware"?

Use dateutil as described in Python datetime.datetime.now() that is timezone aware:

from dateutil.tz import tzlocal
# Get the current date/time with the timezone.
now = datetime.datetime.now(tzlocal())

Check if string has space in between (or anywhere)

Trim() will only remove leading or trailing spaces.

Try .Contains() to check if a string contains white space

"sossjjs sskkk".Contains(" ") // returns true

Pseudo-terminal will not be allocated because stdin is not a terminal

After reading a lot of these answers I thought I would share my resulting solution. All I added is /bin/bash before the heredoc and it doesn't give the error anymore.

Use this:

ssh user@machine /bin/bash <<'ENDSSH'
   hostname
ENDSSH

Instead of this (gives error):

ssh user@machine <<'ENDSSH'
   hostname
ENDSSH

Or use this:

ssh user@machine /bin/bash < run-command.sh

Instead of this (gives error):

ssh user@machine < run-command.sh

EXTRA:

If you still want a remote interactive prompt e.g. if the script you're running remotely prompts you for a password or other information, because the previous solutions won't allow you to type into the prompts.

ssh -t user@machine "$(<run-command.sh)"

And if you also want to log the entire session in a file logfile.log:

ssh -t user@machine "$(<run-command.sh)" | tee -a logfile.log

Gradle task - pass arguments to Java application

If you want to use the same set of arguments all the time, the following is all you need.

run {
    args = ["--myarg1", "--myarg2"]
}

how to properly display an iFrame in mobile safari

This only works if you control both the outside page and the iframe page.

On the outside page, make the iframe unscrollable.

<iframe src="" height=200 scrolling=no></iframe>

On the iframe page, add this.

<!doctype html>
...
<style>
html, body {height:100%; overflow:hidden}
body {overflow:auto; -webkit-overflow-scrolling:touch}
</style>

This works because modern browsers uses html to determine the height, so we just give that a fixed height and turn the body into a scrollable node.

Drawing a simple line graph in Java

There exist many open source projects that handle all the drawing of line charts for you with a couple of lines of code. Here's how you can draw a line chart from data in a couple text (CSV) file with the XChart library. Disclaimer: I'm the lead developer of the project.

In this example, two text files exist in ./CSV/CSVChartRows/. Notice that each row in the files represents a data point to be plotted and that each file represents a different series. series1 contains x, y, and error bar data, whereas series2 contains just x and y, data.

series1.csv

1,12,1.4
2,34,1.12
3,56,1.21
4,47,1.5

series2.csv

1,56
2,34
3,12
4,26

Source Code

public class CSVChartRows {

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

    // import chart from a folder containing CSV files
    XYChart chart = CSVImporter.getChartFromCSVDir("./CSV/CSVChartRows/", DataOrientation.Rows, 600, 400);

    // Show it
    new SwingWrapper(chart).displayChart();
  }
}

Resulting Plot

enter image description here

What is WEB-INF used for in a Java EE web application?

You should put in WEB-INF any pages, or pieces of pages, that you do not want to be public. Usually, JSP or facelets are found outside WEB-INF, but in this case they are easily accesssible for any user. In case you have some authorization restrictions, WEB-INF can be used for that.

WEB-INF/lib can contain 3rd party libraries which you do not want to pack at system level (JARs can be available for all the applications running on your server), but only for this particular applciation.

Generally speaking, many configurations files also go into WEB-INF.

As for WEB-INF/classes - it exists in any web-app, because that is the folder where all the compiled sources are placed (not JARS, but compiled .java files that you wrote yourself).

How to get label text value form a html page?

The best way to get the text value from a <label> element is as follows.

if you will be getting element ids frequently it's best to have a function to return the ids:

function id(e){return document.getElementById(e)}

Assume the following structure: <label for='phone'>Phone number</label> <input type='text' id='phone' placeholder='Mobile or landline numbers...'>

This code will extract the text value 'Phone number' from the<label>: var text = id('phone').previousElementSibling.innerHTML;

This code works on all browsers, and you don't have to give each<label>element a unique id.

How to change symbol for decimal point in double.ToString()?

You can change the decimal separator by changing the culture used to display the number. Beware however that this will change everything else about the number (eg. grouping separator, grouping sizes, number of decimal places). From your question, it looks like you are defaulting to a culture that uses a comma as a decimal separator.

To change just the decimal separator without changing the culture, you can modify the NumberDecimalSeparator property of the current culture's NumberFormatInfo.

Thread.CurrentCulture.NumberFormat.NumberDecimalSeparator = ".";

This will modify the current culture of the thread. All output will now be altered, meaning that you can just use value.ToString() to output the format you want, without worrying about changing the culture each time you output a number.

(Note that a neutral culture cannot have its decimal separator changed.)

How do I count a JavaScript object's attributes?

You can do that by using this simple code:

Object.keys(myObject).length

How do you split a list into evenly sized chunks?

python pydash package could be a good choice.

from pydash.arrays import chunk
ids = ['22', '89', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '1']
chunk_ids = chunk(ids,5)
print(chunk_ids)
# output: [['22', '89', '2', '3', '4'], ['5', '6', '7', '8', '9'], ['10', '11', '1']]

for more checkout pydash chunk list

MySQL error code: 1175 during UPDATE in MySQL Workbench

If you're having this problem in a stored procedure and you aren't able to use the key in the WHERE clause, you can solve this by declaring a variable that will hold the limit of the rows that should be updated and then use it in the update/delete query.

DELIMITER $
CREATE PROCEDURE myProcedure()
BEGIN
    DECLARE the_limit INT;

    SELECT COUNT(*) INTO the_limit
    FROM my_table
    WHERE my_column IS NULL;
        
    UPDATE my_table
    SET my_column = true
    WHERE my_column IS NULL
    LIMIT the_limit;
END$

Create an empty object in JavaScript with {} or new Object()?

Var Obj = {};

This is the most used and simplest method.

Using

var Obj = new Obj() 

is not preferred.

There is no need to use new Object().

For simplicity, readability and execution speed, use the first one (the object literal method).

How to get a value of an element by name instead of ID

To get the value, we can use multiple attributes, one of them being the name attribute. E.g

$("input[name='nameOfElement']").val();

We can also use other attributes to get values

HTML

<input type="text" id="demoText" demo="textValue" />

JS

$("[demo='textValue']").val();

How to select the last record from MySQL table using SQL syntax

SELECT   *
FROM     table
ORDER BY id DESC
LIMIT    0, 1

Recursion in Python? RuntimeError: maximum recursion depth exceeded while calling a Python object

Python lacks the tail recursion optimizations common in functional languages like lisp. In Python, recursion is limited to 999 calls (see sys.getrecursionlimit).

If 999 depth is more than you are expecting, check if the implementation lacks a condition that stops recursion, or if this test may be wrong for some cases.

I dare to say that in Python, pure recursive algorithm implementations are not correct/safe. A fib() implementation limited to 999 is not really correct. It is always possible to convert recursive into iterative, and doing so is trivial.

It is not reached often because in many recursive algorithms the depth tend to be logarithmic. If it is not the case with your algorithm and you expect recursion deeper than 999 calls you have two options:

1) You can change the recursion limit with sys.setrecursionlimit(n) until the maximum allowed for your platform:

sys.setrecursionlimit(limit):

Set the maximum depth of the Python interpreter stack to limit. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python.

The highest possible limit is platform-dependent. A user may need to set the limit higher when she has a program that requires deep recursion and a platform that supports a higher limit. This should be done with care, because a too-high limit can lead to a crash.

2) You can try to convert the algorithm from recursive to iterative. If recursion depth is bigger than allowed by your platform, it is the only way to fix the problem. There are step by step instructions on the Internet and it should be a straightforward operation for someone with some CS education. If you are having trouble with that, post a new question so we can help.

How to modify a text file?

Rewriting a file in place is often done by saving the old copy with a modified name. Unix folks add a ~ to mark the old one. Windows folks do all kinds of things -- add .bak or .old -- or rename the file entirely or put the ~ on the front of the name.

import shutil
shutil.move( afile, afile+"~" )

destination= open( aFile, "w" )
source= open( aFile+"~", "r" )
for line in source:
    destination.write( line )
    if <some condition>:
        destination.write( >some additional line> + "\n" )
source.close()
destination.close()

Instead of shutil, you can use the following.

import os
os.rename( aFile, aFile+"~" )

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

Check whether title has any value or not. If not, then retrive the value using Id.

<form>
Title : <input type="text" id="title" size="40" name="title" value = ''/>
<input type="button" onclick="headingSearch(this.form)" value="Submit"/><br /><br />
</form>
<script type="text/javascript">
function headingSearch(f)
{
    var title=jQuery('#title').val();
    $.ajax({
      type: "POST",
      url: "edit.php",
      data: {title:title} ,
      success: function(data) {
    $('.center').html(data); 
}
});
}
</script>

Try this code.

In php code, use echo instead of return. Only then, javascript data will have its value.

Storing image in database directly or as base64 data?

I recommend looking at modern databases like NoSQL and also I agree with user1252434's post. For instance I am storing a few < 500kb PNGs as base64 on my Mongo db with binary set to true with no performance hit at all. Mongo can be used to store large files like 10MB videos and that can offer huge time saving advantages in metadata searches for those videos, see storing large objects and files in mongodb.

SyntaxError: Unexpected token function - Async Await Nodejs

Node.JS does not fully support ES6 currently, so you can either use asyncawait module or transpile it using Bable.

install

npm install --save asyncawait

helloz.js

var async = require('asyncawait/async');
var await = require('asyncawait/await');

(async (function testingAsyncAwait() {
    await (console.log("Print me!"));
}))();

RegEx to make sure that the string contains at least one lower case char, upper case char, digit and symbol

Bart Kiers, your regex has a couple issues. The best way to do that is this:

(.*[a-z].*)       // For lower cases
(.*[A-Z].*)       // For upper cases
(.*\d.*)          // For digits

In this way you are searching no matter if at the beginning, at the end or at the middle. In your have I have a lot of troubles with complex passwords.

How to display an unordered list in two columns?

The legacy solution in the top answer didn't work for me because I wanted to affect multiple lists on the page and the answer assumes a single list plus it uses a fair bit of global state. In this case I wanted to alter every list inside a <section class="list-content">:

const columns = 2;
$("section.list-content").each(function (index, element) {
    let section = $(element);
    let items = section.find("ul li").detach();
    section.find("ul").detach();
    for (let i = 0; i < columns; i++) {
        section.append("<ul></ul>");
    }
    let lists = section.find("ul");
    for (let i = 0; i < items.length; i++) {
        lists.get(i % columns).append(items[i]);
    }
});

UnsupportedClassVersionError unsupported major.minor version 51.0 unable to load class

Well presumably it's not using the same version of Java when running it externally. Look through the startup scripts carefully to find where it picks up the version of Java to run. You should also check the startup logs to see whether they indicate which version is running.

Alternatively, unless you need the Java 7 features, you could always change your compiler preferences in Eclipse to target 1.6 instead.