Programs & Examples On #Cgi

1) The Common Gateway Interface is a standard defining how web server software can delegate web page generation to a stand-alone application or executable file. 2) Computer Generated Imagery

What is Common Gateway Interface (CGI)?

Have a look at CGI in Wikipedia. CGI is a protocol between the web server and a external program or a script that handles the input and generates output that is sent to the browser.

CGI is a simply a way for web server and a program to communicate, nothing more, nothing less. Here the server manages the network connection and HTTP protocol and the program handles input and generates output that is sent to the browser. CGI script can be basically any program that can be executed by the webserver and follows the CGI protocol. Thus a CGI program can be implemented, for example, in C. However that is extremely rare, since C is not very well suited for the task.

/cgi-bin/*.cgi is a simply a path where people commonly put their CGI script. Web server are commonly configured by default to fetch CGI scripts from that path.

a CGI script can be implemented also in PHP, but all PHP programs are not CGI scripts. If webserver has embedded PHP interpreter (e.g. mod_php in Apache), then the CGI phase is skipped by more efficient direct protocol between the web server and the interpreter.

Whether you have implemented a CGI script or not depends on how your script is being executed by the web server.

How do I configure Apache 2 to run Perl CGI scripts?

(Google search brought me to this question even though I did not ask for perl)

I had a problem with running scripts (albeit bash not perl). Apache had a config of ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ however Apache error log showed File does not exist: /var/www/cgi-bin/test.html.

Tried putting the script in both /usr/lib/cgi-bin/ and /var/www/cgi-bin/ but neither were working.

After a prolonged googling session what cracked it for me was sudo a2enmod cgi and everything fell into place using /usr/lib/cgi-bin/.

Error 500: Premature end of script headers

It was a file permission issue.

All files on my website were set to a permission level of '644.' Once I changed the permission level to 705 (chmod 705) everything worked. Note that I changed it to 705, but 755 will also work. I also changed the folder it was in to 701 (to hide it, but still be executable by the server).

Aside: I still don't understand why my .PHP file worked on the other server when it was probably set to 644?? How could Apache execute the script without world permission?? Does Apache not need world permission?? Just a few questions I still have...

Problem in running .net framework 4.0 website on iis 7.0

Go to IIS manager and click on the server name. Then click on the "ISAPI and CGI Restrictions" icon under the IIS header. Change ASP.NET 4.0 from "Not Allowed" to "Allowed".

How to use HTTP_X_FORWARDED_FOR properly?

You can also solve this problem via Apache configuration using mod_remoteip, by adding the following to a conf.d file:

RemoteIPHeader X-Forwarded-For
RemoteIPInternalProxy 172.16.0.0/12
LogFormat "%a %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined

Warning: mysql_connect(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock) in

Mac OS X EL Capitan + MAMP Pro Do this

cd /var
sudo mkdir mysql
sudo chmod 755 mysql
cd mysql
sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock mysql.sock

Then do this

cd /tmp
sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock mysql.sock

Hope this saves you some time.

How to switch a user per task or set of tasks?

In Ansible >1.4 you can actually specify a remote user at the task level which should allow you to login as that user and execute that command without resorting to sudo. If you can't login as that user then the sudo_user solution will work too.

---
- hosts: webservers
  remote_user: root
  tasks:
    - name: test connection
      ping:
      remote_user: yourname

See http://docs.ansible.com/playbooks_intro.html#hosts-and-users

How do I get a plist as a Dictionary in Swift?

Swift 4.0 iOS 11.2.6 list parsed and code to parse it, based on https://stackoverflow.com/users/3647770/ashok-r answer above.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
  <dict>
    <key>identity</key>
    <string>blah-1</string>
    <key>major</key>
    <string>1</string>
    <key>minor</key>
    <string>1</string>
    <key>uuid</key>
    <string>f45321</string>
    <key>web</key>
    <string>http://web</string>
</dict>
<dict>
    <key>identity</key>
    <string></string>
    <key>major</key>
    <string></string>
    <key>minor</key>
    <string></string>
    <key>uuid</key>
    <string></string>
    <key>web</key>
    <string></string>
  </dict>
</array>
</plist>

do {
   let plistXML = try Data(contentsOf: url)
    var plistData: [[String: AnyObject]] = [[:]]
    var propertyListFormat =  PropertyListSerialization.PropertyListFormat.xml
        do {
            plistData = try PropertyListSerialization.propertyList(from: plistXML, options: .mutableContainersAndLeaves, format: &propertyListFormat) as! [[String:AnyObject]]

        } catch {
            print("Error reading plist: \(error), format: \(propertyListFormat)")
        }
    } catch {
        print("error no upload")
    }

Matching special characters and letters in regex

let pattern = /^(?=.*[0-9])(?=.*[!@#$%^&*])(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9!@#$%^&*]{6,16}$/;

//following will give you the result as true(if the password contains Capital, small letter, number and special character) or false based on the string format

let reee =pattern .test("helLo123@");   //true as it contains all the above

Calculating the SUM of (Quantity*Price) from 2 different tables

I had the same problem as Marko and come across a solution like this:

/*Create a Table*/
CREATE TABLE tableGrandTotal
(
columnGrandtotal int
)

/*Create a Stored Procedure*/
CREATE PROCEDURE GetGrandTotal
AS

/*Delete the 'tableGrandTotal' table for another usage of the stored procedure*/
DROP TABLE tableGrandTotal

/*Create a new Table which will include just one column*/
CREATE TABLE tableGrandTotal
(
columnGrandtotal int
)

/*Insert the query which returns subtotal for each orderitem row into tableGrandTotal*/
INSERT INTO tableGrandTotal
    SELECT oi.Quantity * p.Price AS columnGrandTotal
        FROM OrderItem oi
        JOIN Product p ON oi.Id = p.Id

/*And return the sum of columnGrandTotal from the newly created table*/    
SELECT SUM(columnGrandTotal) as [Grand Total]
    FROM tableGrandTotal

And just simply use the GetGrandTotal Stored Procedure to retrieve the Grand Total :)

EXEC GetGrandTotal

What is the difference between syntax and semantics in programming languages?

Understanding how the compiler sees the code

Usually, syntax and semantics analysis of the code is done in the 'frontend' part of the compiler.

  • Syntax: Compiler generates tokens for each keyword and symbols: the token contains the information- type of keyword and its location in the code. Using these tokens, an AST(short for Abstract Syntax Tree) is created and analysed. What compiler actually checks here is whether the code is lexically meaningful i.e. does the 'sequence of keywords' comply with the language rules? As suggested in previous answers, you can see it as the grammar of the language(not the sense/meaning of the code). Side note: Syntax errors are reported in this phase.(returns tokens with the error type to the system)

  • Semantics: Now, the compiler will check whether your code operations 'makes sense'. e.g. If the language supports Type Inference, sematic error will be reported if you're trying to assign a string to a float. OR declaring the same variable twice. These are errors that are 'grammatically'/ syntaxially correct, but makes no sense during the operation. Side note: For checking whether the same variable is declared twice, compiler manages a symbol table

So, the output of these 2 frontend phases is an annotated AST(with data types) and symbol table.

Understanding it in a less technical way

Considering the normal language we use; here, English:

e.g. He go to the school. - Incorrect grammar/syntax, though he wanted to convey a correct sense/semantic.

e.g. He goes to the cold. - cold is an adjective. In English, we might say this doesn't comply with grammar, but it actually is the closest example to incorrect semantic with correct syntax I could think of.

How to quickly form groups (quartiles, deciles, etc) by ordering column(s) in a data frame

Sorry for being a bit late to the party. I wanted to add my one liner using cut2 as I didn't know max/min for my data and wanted the groups to be identically large. I read about cut2 in an issue which was marked as duplicate (link below).

library(Hmisc)   #For cut2
set.seed(123)    #To keep answers below identical to my random run

temp <- data.frame(name=letters[1:12], value=rnorm(12), quartile=rep(NA, 12))

temp$quartile <- as.numeric(cut2(temp$value, g=4))   #as.numeric to number the factors
temp$quartileBounds <- cut2(temp$value, g=4)

temp

Result:

> temp
   name       value quartile  quartileBounds
1     a -0.56047565        1 [-1.265,-0.446)
2     b -0.23017749        2 [-0.446, 0.129)
3     c  1.55870831        4 [ 1.224, 1.715]
4     d  0.07050839        2 [-0.446, 0.129)
5     e  0.12928774        3 [ 0.129, 1.224)
6     f  1.71506499        4 [ 1.224, 1.715]
7     g  0.46091621        3 [ 0.129, 1.224)
8     h -1.26506123        1 [-1.265,-0.446)
9     i -0.68685285        1 [-1.265,-0.446)
10    j -0.44566197        2 [-0.446, 0.129)
11    k  1.22408180        4 [ 1.224, 1.715]
12    l  0.35981383        3 [ 0.129, 1.224)

Similar issue where I read about cut2 in detail

How to pass a null variable to a SQL Stored Procedure from C#.net code

try this! syntax less lines and even more compact! don't forget to add the properties you want to add with this approach!

cmd.Parameters.Add(new SqlParameter{SqlValue=(object)username??DBNull.Value,ParameterName="user" }  );

How does the modulus operator work?

You can think of the modulus operator as giving you a remainder. count % 6 divides 6 out of count as many times as it can and gives you a remainder from 0 to 5 (These are all the possible remainders because you already divided out 6 as many times as you can). The elements of the array are all printed in the for loop, but every time the remainder is 5 (every 6th element), it outputs a newline character. This gives you 6 elements per line. For 5 elements per line, use

if (count % 5 == 4)

Resize an Array while keeping current elements in Java?

You can't resize an array, but you can redefine it keeping old values or use a java.util.List

Here follows two solutions but catch the performance differences running the code below

Java Lists are 450 times faster but 20 times heavier in memory!

testAddByteToArray1 nanoAvg:970355051   memAvg:100000
testAddByteToList1  nanoAvg:1923106     memAvg:2026856
testAddByteToArray1 nanoAvg:919582271   memAvg:100000
testAddByteToList1  nanoAvg:1922660     memAvg:2026856
testAddByteToArray1 nanoAvg:917727475   memAvg:100000
testAddByteToList1  nanoAvg:1904896     memAvg:2026856
testAddByteToArray1 nanoAvg:918483397   memAvg:100000
testAddByteToList1  nanoAvg:1907243     memAvg:2026856
import java.util.ArrayList;
import java.util.List;

public class Test {

    public static byte[] byteArray = new byte[0];
    public static List<Byte> byteList = new ArrayList<>();
    public static List<Double> nanoAvg = new ArrayList<>();
    public static List<Double> memAvg = new ArrayList<>();

    public static void addByteToArray1() {
        // >>> SOLUTION ONE <<<
        byte[] a = new byte[byteArray.length + 1];
        System.arraycopy(byteArray, 0, a, 0, byteArray.length);
        byteArray = a;
        //byteArray = Arrays.copyOf(byteArray, byteArray.length + 1); // the same as System.arraycopy()
    }

    public static void addByteToList1() {
        // >>> SOLUTION TWO <<<
        byteList.add(new Byte((byte) 0));
    }

    public static void testAddByteToList1() throws InterruptedException {
        System.gc();
        long m1 = getMemory();
        long n1 = System.nanoTime();
        for (int i = 0; i < 100000; i++) {
            addByteToList1();
        }
        long n2 = System.nanoTime();
        System.gc();
        long m2 = getMemory();
        byteList = new ArrayList<>();
        nanoAvg.add(new Double(n2 - n1));
        memAvg.add(new Double(m2 - m1));
    }

    public static void testAddByteToArray1() throws InterruptedException {
        System.gc();
        long m1 = getMemory();
        long n1 = System.nanoTime();
        for (int i = 0; i < 100000; i++) {
            addByteToArray1();
        }
        long n2 = System.nanoTime();
        System.gc();
        long m2 = getMemory();
        byteArray = new byte[0];
        nanoAvg.add(new Double(n2 - n1));
        memAvg.add(new Double(m2 - m1));
    }

    public static void resetMem() {
        nanoAvg = new ArrayList<>();
        memAvg = new ArrayList<>();
    }

    public static Double getAvg(List<Double> dl) {
        double max = Collections.max(dl);
        double min = Collections.min(dl);
        double avg = 0;
        boolean found = false;
        for (Double aDouble : dl) {
            if (aDouble < max && aDouble > min) {
                if (avg == 0) {
                    avg = aDouble;
                } else {
                    avg = (avg + aDouble) / 2d;
                }
                found = true;
            }
        }
        if (!found) {
            return getPopularElement(dl);
        }
        return avg;
    }

    public static double getPopularElement(List<Double> a) {
        int count = 1, tempCount;
        double popular = a.get(0);
        double temp = 0;
        for (int i = 0; i < (a.size() - 1); i++) {
            temp = a.get(i);
            tempCount = 0;
            for (int j = 1; j < a.size(); j++) {
                if (temp == a.get(j))
                    tempCount++;
            }
            if (tempCount > count) {
                popular = temp;
                count = tempCount;
            }
        }
        return popular;
    }

    public static void testCompare() throws InterruptedException {
        for (int j = 0; j < 4; j++) {
            for (int i = 0; i < 20; i++) {
                testAddByteToArray1();
            }
            System.out.println("testAddByteToArray1\tnanoAvg:" + getAvg(nanoAvg).longValue() + "\tmemAvg:" + getAvg(memAvg).longValue());
            resetMem();
            for (int i = 0; i < 20; i++) {
                testAddByteToList1();
            }
            System.out.println("testAddByteToList1\tnanoAvg:" + getAvg(nanoAvg).longValue() + "\t\tmemAvg:" + getAvg(memAvg).longValue());
            resetMem();
        }
    }

    private static long getMemory() {
        Runtime runtime = Runtime.getRuntime();
        return runtime.totalMemory() - runtime.freeMemory();
    }

    public static void main(String[] args) throws InterruptedException {
        testCompare();
    }
}

What is the difference between old style and new style classes in Python?

New style classes may use super(Foo, self) where Foo is a class and self is the instance.

super(type[, object-or-type])

Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr() except that the type itself is skipped.

And in Python 3.x you can simply use super() inside a class without any parameters.

How to open SharePoint files in Chrome/Firefox

You can use web-based protocol handlers for the links as per https://sharepoint.stackexchange.com/questions/70178/how-does-sharepoint-2013-enable-editing-of-documents-for-chrome-and-fire-fox

Basically, just prepend ms-word:ofe|u| to the links to your SharePoint hosted Word documents.

Getting date format m-d-Y H:i:s.u from milliseconds

php.net says:

Microseconds (added in PHP 5.2.2). Note that date() will always generate 000000 since it takes an integer parameter, whereas DateTime::format() does support microseconds if DateTime was created with microseconds.

So use as simple:

$micro_date = microtime();
$date_array = explode(" ",$micro_date);
$date = date("Y-m-d H:i:s",$date_array[1]);
echo "Date: $date:" . $date_array[0]."<br>";

Recommended and use dateTime() class from referenced:

$t = microtime(true);
$micro = sprintf("%06d",($t - floor($t)) * 1000000);
$d = new DateTime( date('Y-m-d H:i:s.'.$micro, $t) );

print $d->format("Y-m-d H:i:s.u"); // note at point on "u"

Note u is microseconds (1 seconds = 1000000 µs).

Another example from php.net:

$d2=new DateTime("2012-07-08 11:14:15.889342");

Reference of dateTime() on php.net

I've answered on question as short and simplify to author. Please see for more information to author: getting date format m-d-Y H:i:s.u from milliseconds

Bitbucket fails to authenticate on git pull

This answer is for SO users who browse here after searching for the error.

  • Terminal will not accept your Bitbucket or Atlassian web app password if
    your account is associated with an Atlassian (Jira) account. If this is your case, you have a giant string generated for you that you can find in your MacOSX keychain app. This is the password Terminal accepts.
  • It is not clear how to re-generate this password or re-set it to match what Bitbucket will accept.
  • Changing password in SourceTree's settings did not work for me.
  • Changing password in Atlassian account profile did not work for me.
  • Bitbucket does not have a link or interface to change password for this case in the Bitbucket account profile - user has to go to Atlassian account profile.

In my case, nothing worked because I changed my username in Bitbucket.

Atlassian and Bitbucket are not completely integrated. Bitbucket uses the Atlassian user email and web app password, but allows you to have a different username.

There seems to be a bug in this process, especially since it's not clear which application or process is generating the authentication and where it's stored or editable. Changing the username breaks authentication.

There may be a way to update the username used by the credentials and Bitbucket, but I was already several hours behind when I discovered that changing my username back to what it was before restored authentication.

PHP CURL CURLOPT_SSL_VERIFYPEER ignored

We had the same problem on a CentOS7 machine. Disabling the VERIFYHOST VERIFYPEER did not solve the problem, we did not have the cURL error anymore but the response still was invalid. Doing a wget to the same link as the cURL was doing also resulted in a certificate error.

-> Our solution also was to reboot the VPS, this solved it and we were able to complete the request again.

For us this seemed to be a memory corruption problem. Rebooting the VPS reloaded the libary in the memory again and now it works. So if the above solution from @clover does not work try to reboot your machine.

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

To simplify Kirubaharan's answer a bit:

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

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

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

What's a Good Javascript Time Picker?

You could read jQuery creator John Resig's post about it here: http://ejohn.org/blog/picking-time/.

What is the "__v" field in Mongoose

We can use versionKey: false in Schema definition

'use strict';

const mongoose = require('mongoose');

export class Account extends mongoose.Schema {

    constructor(manager) {

        var trans = {
            tran_date: Date,
            particulars: String,
            debit: Number,
            credit: Number,
            balance: Number
        }

        super({
            account_number: Number,
            account_name: String,
            ifsc_code: String,
            password: String,
            currency: String,
            balance: Number,
            beneficiaries: Array,
            transaction: [trans]
        }, {
            versionKey: false // set to false then it wont create in mongodb
        });

        this.pre('remove', function(next) {
            manager
                .getModel(BENEFICIARY_MODEL)
                .remove({
                    _id: {
                        $in: this.beneficiaries
                    }
                })
                .exec();
            next();
        });
    }

}

good postgresql client for windows?

do you mean something like pgAdmin for administration?

How to check postgres user and password?

You will not be able to find out the password he chose. However, you may create a new user or set a new password to the existing user.

Usually, you can login as the postgres user:

Open a Terminal and do sudo su postgres. Now, after entering your admin password, you are able to launch psql and do

CREATE USER yourname WITH SUPERUSER PASSWORD 'yourpassword';

This creates a new admin user. If you want to list the existing users, you could also do

\du

to list all users and then

ALTER USER yourusername WITH PASSWORD 'yournewpass';

How to convert an int to string in C?

If you want to output your structure into a file there is no need to convert any value beforehand. You can just use the printf format specification to indicate how to output your values and use any of the operators from printf family to output your data.

Getting all types that implement an interface

I appreciate this is a very old question but I thought I would add another answer for future users as all the answers to date use some form of Assembly.GetTypes.

Whilst GetTypes() will indeed return all types, it does not necessarily mean you could activate them and could thus potentially throw a ReflectionTypeLoadException.

A classic example for not being able to activate a type would be when the type returned is derived from base but base is defined in a different assembly from that of derived, an assembly that the calling assembly does not reference.

So say we have:

Class A // in AssemblyA
Class B : Class A, IMyInterface // in AssemblyB
Class C // in AssemblyC which references AssemblyB but not AssemblyA

If in ClassC which is in AssemblyC we then do something as per accepted answer:

var type = typeof(IMyInterface);
var types = AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany(s => s.GetTypes())
    .Where(p => type.IsAssignableFrom(p));

Then it will throw a ReflectionTypeLoadException.

This is because without a reference to AssemblyA in AssemblyC you would not be able to:

var bType = typeof(ClassB);
var bClass = (ClassB)Activator.CreateInstance(bType);

In other words ClassB is not loadable which is something that the call to GetTypes checks and throws on.

So to safely qualify the result set for loadable types then as per this Phil Haacked article Get All Types in an Assembly and Jon Skeet code you would instead do something like:

public static class TypeLoaderExtensions {
    public static IEnumerable<Type> GetLoadableTypes(this Assembly assembly) {
        if (assembly == null) throw new ArgumentNullException("assembly");
        try {
            return assembly.GetTypes();
        } catch (ReflectionTypeLoadException e) {
            return e.Types.Where(t => t != null);
        }
    }
}

And then:

private IEnumerable<Type> GetTypesWithInterface(Assembly asm) {
    var it = typeof (IMyInterface);
    return asm.GetLoadableTypes().Where(it.IsAssignableFrom).ToList();
}

apache ProxyPass: how to preserve original IP address

If you are using Apache reverse proxy for serving an app running on a localhost port you must add a location to your vhost.

<Location />            
   ProxyPass http://localhost:1339/ retry=0
   ProxyPassReverse http://localhost:1339/
   ProxyPreserveHost On
   ProxyErrorOverride Off
</Location>

To get the IP address have following options

console.log(">>>", req.ip);// this works fine for me returned a valid ip address 
console.log(">>>", req.headers['x-forwarded-for'] );// returned a valid IP address 
console.log(">>>", req.headers['X-Real-IP'] ); // did not work returned undefined 
console.log(">>>", req.connection.remoteAddress );// returned the loopback IP address 

So either use req.ip or req.headers['x-forwarded-for']

Set Text property of asp:label in Javascript PROPER way

The label's information is stored in the ViewState input on postback (keep in mind the server knows nothing of the page outside of the form values posted back, which includes your label's text).. you would have to somehow update that on the client side to know what changed in that label, which I'm guessing would not be worth your time.

I'm not entirely sure what problem you're trying to solve here, but this might give you a few ideas of how to go about it:

You could create a hidden field to go along with your label, and anytime you update your label, you'd update that value as well.. then in the code behind set the Text property of the label to be what was in that hidden field.

What is the difference between typeof and instanceof and when should one be used vs. the other?

Of course it matters........ !

Let's walk this through with examples.In our example we will declare function in two different ways.

We will be using both function declaration and Function Constructor. We will se how typeof and instanceof behaves in those two different scenarios.

Create function using function declaration :

function MyFunc(){  }

typeof Myfunc == 'function' // true

MyFunc instanceof Function // false

Possible explanation for such different result is, as we made a function declaration , typeof can understand that it is a function.Because typeof checks whether or not the expression on which typeof is operation on, in our case MyFunc implemented Call Method or not. If it implements Call method it is a function.Otherwise not .For clarification check ecmascript specification for typeof.

Create function using function constructor :

var MyFunc2 = new Function('a','b','return a+b') // A function constructor is used 

typeof MyFunc2 == 'function' // true

MyFunc2 instanceof Function // true

Here typeof asserts that MyFunc2 is a function as well as the instanceof operator.We already know typeof check if MyFunc2 implemented Call method or not.As MyFunc2 is a function and it implements call method,that's how typeof knows that it's a function.On the other hand, we used function constructor to create MyFunc2, it becomes an instance of Function constructor.That's why instanceof also resolves to true.

What's safer to use ?

As we can see in both cases typeof operator can successfully asserted that we are dealing with a function here,it is safer than instanceof. instanceof will fail in case of function declaration because function declarations are not an instance of Function constructor.

Best practice :

As Gary Rafferty suggested, the best way should be using both typeof and instanceof together.

  function isFunction(functionItem) {

        return typeof(functionItem) == 'function' || functionItem instanceof Function;

  }

  isFunction(MyFunc) // invoke it by passing our test function as parameter

DataGridView.Clear()

Set the datasource property to an empty string then call the Clear method.

How to display and hide a div with CSS?

You need

.abc,.ab {
    display: none;
}

#f:hover ~ .ab {
    display: block;
}

#s:hover ~ .abc {
    display: block;
}

#s:hover ~ .a,
#f:hover ~ .a{
    display: none;
}

Updated demo at http://jsfiddle.net/gaby/n5fzB/2/


The problem in your original CSS was that the , in css selectors starts a completely new selector. it is not combined.. so #f:hover ~ .abc,.a means #f:hover ~ .abc and .a. You set that to display:none so it was always set to be hidden for all .a elements.

How to resolve "could not execute statement; SQL [n/a]; constraint [numbering];"?

The solution at my end was to explicitly add a JoinColumn annotation like this:

@JoinColumn(name="mapping_type_id")

The column name is usually the table name + "_id" if there is an id field. Additionally, keep in mind which field it should be based on the relationship, OneToMany or ManyToOne.

Hope this helps.

What does "<html xmlns="http://www.w3.org/1999/xhtml">" do?

Its an XML namespace. It is required when you use XHTML 1.0 or 1.1 doctypes or application/xhtml+xml mimetypes.

You should be using HTML5 doctype, then you don't need it for text/html. Better start from template like this :

<!DOCTYPE html>
<html>
    <head>
        <meta charset=utf-8 />
        <title>domcument title</title>
        <link rel="stylesheet" href="/stylesheet.css" type="text/css" />
    </head>
    <body>
            <!-- your html content -->
            <script src="/script.js"></script>
    </body>
</html>



When you have put your Doctype straight - do and validate you html and your css .
That usually will sove you layout issues.

Can't create handler inside thread which has not called Looper.prepare()

The error is self-explanatory... doInBackground() runs on a background thread which, since it is not intended to loop, is not connected to a Looper.

You most likely don't want to directly instantiate a Handler at all... whatever data your doInBackground() implementation returns will be passed to onPostExecute() which runs on the UI thread.

   mActivity = ThisActivity.this; 

    mActivity.runOnUiThread(new Runnable() {
     public void run() {
     new asyncCreateText().execute();
     }
   });

ADDED FOLLOWING THE STACKTRACE APPEARING IN QUESTION:

Looks like you're trying to start an AsyncTask from a GL rendering thread... don't do that cos they won't ever Looper.loop() either. AsyncTasks are really designed to be run from the UI thread only.

The least disruptive fix would probably be to call Activity.runOnUiThread() with a Runnable that kicks off your AsyncTask.

How to check if a value exists in an array in Ruby

['Cat', 'Dog', 'Bird'].detect { |x| x == 'Dog'}
=> "Dog"
!['Cat', 'Dog', 'Bird'].detect { |x| x == 'Dog'}.nil?
=> true

SQL Error with Order By in Subquery

This is the error you get (emphasis mine):

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified.

So, how can you avoid the error? By specifying TOP, would be one possibility, I guess.

SELECT (
  SELECT TOP 100 PERCENT
  COUNT(1) FROM Seanslar WHERE MONTH(tarihi) = 4
  GROUP BY refKlinik_id
  ORDER BY refKlinik_id
) as dorduncuay

How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

Here is my attempt:

Function RegParse(ByVal pattern As String, ByVal html As String)
    Dim regex   As RegExp
    Set regex = New RegExp

    With regex
        .IgnoreCase = True  'ignoring cases while regex engine performs the search.
        .pattern = pattern  'declaring regex pattern.
        .Global = False     'restricting regex to find only first match.

        If .Test(html) Then         'Testing if the pattern matches or not
            mStr = .Execute(html)(0)        '.Execute(html)(0) will provide the String which matches with Regex
            RegParse = .Replace(mStr, "$1") '.Replace function will replace the String with whatever is in the first set of braces - $1.
        Else
            RegParse = "#N/A"
        End If

    End With
End Function

Password hash function for Excel VBA

Here's a module for calculating SHA1 hashes that is usable for Excel formulas eg. '=SHA1HASH("test")'. To use it, make a new module called 'module_sha1' and copy and paste it all in. This is based on some VBA code from http://vb.wikia.com/wiki/SHA-1.bas, with changes to support passing it a string, and executable from formulas in Excel cells.

' Based on: http://vb.wikia.com/wiki/SHA-1.bas
Option Explicit

Private Type FourBytes
    A As Byte
    B As Byte
    C As Byte
    D As Byte
End Type
Private Type OneLong
    L As Long
End Type

Function HexDefaultSHA1(Message() As Byte) As String
 Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long
 DefaultSHA1 Message, H1, H2, H3, H4, H5
 HexDefaultSHA1 = DecToHex5(H1, H2, H3, H4, H5)
End Function

Function HexSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long) As String
 Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long
 xSHA1 Message, Key1, Key2, Key3, Key4, H1, H2, H3, H4, H5
 HexSHA1 = DecToHex5(H1, H2, H3, H4, H5)
End Function

Sub DefaultSHA1(Message() As Byte, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)
 xSHA1 Message, &H5A827999, &H6ED9EBA1, &H8F1BBCDC, &HCA62C1D6, H1, H2, H3, H4, H5
End Sub

Sub xSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)
 'CA62C1D68F1BBCDC6ED9EBA15A827999 + "abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D"
 '"abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D"

 Dim U As Long, P As Long
 Dim FB As FourBytes, OL As OneLong
 Dim i As Integer
 Dim W(80) As Long
 Dim A As Long, B As Long, C As Long, D As Long, E As Long
 Dim T As Long

 H1 = &H67452301: H2 = &HEFCDAB89: H3 = &H98BADCFE: H4 = &H10325476: H5 = &HC3D2E1F0

 U = UBound(Message) + 1: OL.L = U32ShiftLeft3(U): A = U \ &H20000000: LSet FB = OL 'U32ShiftRight29(U)

 ReDim Preserve Message(0 To (U + 8 And -64) + 63)
 Message(U) = 128

 U = UBound(Message)
 Message(U - 4) = A
 Message(U - 3) = FB.D
 Message(U - 2) = FB.C
 Message(U - 1) = FB.B
 Message(U) = FB.A

 While P < U
     For i = 0 To 15
         FB.D = Message(P)
         FB.C = Message(P + 1)
         FB.B = Message(P + 2)
         FB.A = Message(P + 3)
         LSet OL = FB
         W(i) = OL.L
         P = P + 4
     Next i

     For i = 16 To 79
         W(i) = U32RotateLeft1(W(i - 3) Xor W(i - 8) Xor W(i - 14) Xor W(i - 16))
     Next i

     A = H1: B = H2: C = H3: D = H4: E = H5

     For i = 0 To 19
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key1), ((B And C) Or ((Not B) And D)))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 20 To 39
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key2), (B Xor C Xor D))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 40 To 59
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key3), ((B And C) Or (B And D) Or (C And D)))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 60 To 79
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key4), (B Xor C Xor D))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i

     H1 = U32Add(H1, A): H2 = U32Add(H2, B): H3 = U32Add(H3, C): H4 = U32Add(H4, D): H5 = U32Add(H5, E)
 Wend
End Sub

Function U32Add(ByVal A As Long, ByVal B As Long) As Long
 If (A Xor B) < 0 Then
     U32Add = A + B
 Else
     U32Add = (A Xor &H80000000) + B Xor &H80000000
 End If
End Function

Function U32ShiftLeft3(ByVal A As Long) As Long
 U32ShiftLeft3 = (A And &HFFFFFFF) * 8
 If A And &H10000000 Then U32ShiftLeft3 = U32ShiftLeft3 Or &H80000000
End Function

Function U32ShiftRight29(ByVal A As Long) As Long
 U32ShiftRight29 = (A And &HE0000000) \ &H20000000 And 7
End Function

Function U32RotateLeft1(ByVal A As Long) As Long
 U32RotateLeft1 = (A And &H3FFFFFFF) * 2
 If A And &H40000000 Then U32RotateLeft1 = U32RotateLeft1 Or &H80000000
 If A And &H80000000 Then U32RotateLeft1 = U32RotateLeft1 Or 1
End Function
Function U32RotateLeft5(ByVal A As Long) As Long
 U32RotateLeft5 = (A And &H3FFFFFF) * 32 Or (A And &HF8000000) \ &H8000000 And 31
 If A And &H4000000 Then U32RotateLeft5 = U32RotateLeft5 Or &H80000000
End Function
Function U32RotateLeft30(ByVal A As Long) As Long
 U32RotateLeft30 = (A And 1) * &H40000000 Or (A And &HFFFC) \ 4 And &H3FFFFFFF
 If A And 2 Then U32RotateLeft30 = U32RotateLeft30 Or &H80000000
End Function

Function DecToHex5(ByVal H1 As Long, ByVal H2 As Long, ByVal H3 As Long, ByVal H4 As Long, ByVal H5 As Long) As String
 Dim H As String, L As Long
 DecToHex5 = "00000000 00000000 00000000 00000000 00000000"
 H = Hex(H1): L = Len(H): Mid(DecToHex5, 9 - L, L) = H
 H = Hex(H2): L = Len(H): Mid(DecToHex5, 18 - L, L) = H
 H = Hex(H3): L = Len(H): Mid(DecToHex5, 27 - L, L) = H
 H = Hex(H4): L = Len(H): Mid(DecToHex5, 36 - L, L) = H
 H = Hex(H5): L = Len(H): Mid(DecToHex5, 45 - L, L) = H
End Function

' Convert the string into bytes so we can use the above functions
' From Chris Hulbert: http://splinter.com.au/blog

Public Function SHA1HASH(str)
  Dim i As Integer
  Dim arr() As Byte
  ReDim arr(0 To Len(str) - 1) As Byte
  For i = 0 To Len(str) - 1
   arr(i) = Asc(Mid(str, i + 1, 1))
  Next i
  SHA1HASH = Replace(LCase(HexDefaultSHA1(arr)), " ", "")
End Function

What size should TabBar images be?

30x30 is points, which means 30px @1x, 60px @2x, not somewhere in-between. Also, it's not a great idea to embed the title of the tab into the image—you're going to have pretty poor accessibility and localization results like that.

.crx file install in chrome

I had a similar issue where I was not able to either install a CRX file into Chrome.

It turns out that since I had my Downloads folder set to a network mapped drive, it would not allow Chrome to install any extensions and would either do nothing (drag and drop on Chrome) or ask me to download the extension (if I clicked a link from the Web Store).

Setting the Downloads folder to a local disk directory instead of a network directory allowed extensions to be installed.

Running: 20.0.1132.57 m

How can I get the request URL from a Java Filter?

Is this what you're looking for?

if (request instanceof HttpServletRequest) {
 String url = ((HttpServletRequest)request).getRequestURL().toString();
 String queryString = ((HttpServletRequest)request).getQueryString();
}

To Reconstruct:

System.out.println(url + "?" + queryString);

Info on HttpServletRequest.getRequestURL() and HttpServletRequest.getQueryString().

How do JavaScript closures work?

Here's the most Zen answer I can give:

What would you expect this code to do? Tell me in a comment before you run it. I'm curious!

function foo() {
  var i = 1;
  return function() {
    console.log(i++);
  }
}

var bar = foo();
bar();
bar();
bar();

var baz = foo();
baz();
baz();
baz();

Now open the console in your browser (Ctrl + Shift + I or F12, hopefully) and paste the code in and hit Enter.

If this code printed what you expect (JavaScript newbies - ignore the "undefined" at the end), then you already have wordless understanding. In words, the variable i is part of the inner function instance's closure.

I put it this way because, once I understood that this code is putting instances of foo()'s inner function in bar and baz and then calling them via those variables, nothing else surprised me.

But if I'm wrong and the console output surprised you, let me know!

In TensorFlow, what is the difference between Session.run() and Tensor.eval()?

eval() can not handle the list object

tf.reset_default_graph()

a = tf.Variable(0.2, name="a")
b = tf.Variable(0.3, name="b")
z = tf.constant(0.0, name="z0")
for i in range(100):
    z = a * tf.cos(z + i) + z * tf.sin(b - i)
grad = tf.gradients(z, [a, b])

init = tf.global_variables_initializer()

with tf.Session() as sess:
    init.run()
    print("z:", z.eval())
    print("grad", grad.eval())

but Session.run() can

print("grad", sess.run(grad))

correct me if I am wrong

Upgrade to python 3.8 using conda

Now that the new anaconda individual edition 2020 distribution is out, the procedure that follows is working:

Update conda in your base env:

conda update conda

Create a new environment for Python 3.8, specifying anaconda for the full distribution specification, not just the minimal environment:

conda create -n py38 python=3.8 anaconda

Activate the new environment:

conda activate py38

python --version
Python 3.8.1

Number of packages installed: 303

Or you can do:

conda create -n py38 anaconda=2020.02 python=3.8

--> UPDATE: Finally, Anaconda3-2020.07 is out with core Python 3.8.3

You can download Anaconda with Python 3.8 from https://www.anaconda.com/products/individual

Format an Integer using Java String Format

If you are using a third party library called apache commons-lang, the following solution can be useful:

Use StringUtils class of apache commons-lang :

int i = 5;
StringUtils.leftPad(String.valueOf(i), 3, "0"); // --> "005"

As StringUtils.leftPad() is faster than String.format()

jQuery-UI datepicker default date

jQuery UI Datepicker is coded to always highlight the user's local date using the class ui-state-highlight. There is no built-in option to change this.

One method, described similarly in other answers to related questions, is to override the CSS for that class to match ui-state-default of your theme, for example:

.ui-state-highlight {
    border: 1px solid #d3d3d3;
    background: #e6e6e6 url(images/ui-bg_glass_75_e6e6e6_1x400.png) 50% 50% repeat-x;
    color: #555555;
}

However this isn't very helpful if you are using dynamic themes, or if your intent is to highlight a different day (e.g., to have "today" be based on your server's clock rather than the client's).

An alternative approach is to override the datepicker prototype that is responsible for highlighting the current day.

Assuming that you are using a minimized version of the UI javascript, the following snippets can address these concerns.


If your goal is to prevent highlighting the current day altogether:

// copy existing _generateHTML method
var _generateHTML = jQuery.datepicker.constructor.prototype._generateHTML;
// remove the string "ui-state-highlight"
_generateHtml.toString().replace(' ui-state-highlight', '');
// and replace the prototype method
eval('jQuery.datepicker.constructor.prototype._generateHTML = ' + _generateHTML);

This changes the relevant code (unminimized for readability) from:

[...](printDate.getTime() == today.getTime() ? ' ui-state-highlight' : '') + [...]

to

[...](printDate.getTime() == today.getTime() ? '' : '') + [...]

If your goal is to change datepicker's definition of "today":

var useMyDateNotYours = '07/28/2014';
// copy existing _generateHTML method
var _generateHTML = jQuery.datepicker.constructor.prototype._generateHTML;
// set "today" to your own Date()-compatible date
_generateHTML.toString().replace('new Date,', 'new Date(useMyDateNotYours),');
// and replace the prototype method
eval('jQuery.datepicker.constructor.prototype._generateHTML = ' + _generateHTML);

This changes the relevant code (unminimized for readability) from:

[...]var today = new Date();[...]

to

[...]var today = new Date(useMyDateNotYours);[...]
// Note that in the minimized version, the line above take the form `L=new Date,`
// (part of a list of variable declarations, and Date is instantiated without parenthesis)

Instead of useMyDateNotYours you could of course also instead inject a string, function, or whatever suits your needs.

Suppress command line output

mysqldump doesn't work with: >nul 2>&1
Instead use: 2> nul
This suppress the stderr message: "Warning: Using a password on the command line interface can be insecure"

Pass connection string to code-first DbContext

After reading the docs, I have to pass the name of the connection string instead:

var db = new NerdDinners("NerdDinnerDb");

Regex pattern inside SQL Replace function?

Here is a function I wrote to accomplish this based off of the previous answers.

CREATE FUNCTION dbo.RepetitiveReplace
(
    @P_String VARCHAR(MAX),
    @P_Pattern VARCHAR(MAX),
    @P_ReplaceString VARCHAR(MAX),
    @P_ReplaceLength INT = 1
)
RETURNS VARCHAR(MAX)
BEGIN
    DECLARE @Index INT;

    -- Get starting point of pattern
    SET @Index = PATINDEX(@P_Pattern, @P_String);

    while @Index > 0
    begin
        --replace matching charactger at index
        SET @P_String = STUFF(@P_String, PATINDEX(@P_Pattern, @P_String), @P_ReplaceLength, @P_ReplaceString);
        SET @Index = PATINDEX(@P_Pattern, @P_String);
    end

    RETURN @P_String;
END;

Gist

Edit:

Originally I had a recursive function here which does not play well with sql server as it has a 32 nesting level limit which would result in an error like the below any time you attempt to make 32+ replacements with the function. Instead of trying to make a server level change to allow more nesting (which could be dangerous like allow never ending loops) switching to a while loop makes a lot more sense.

Maximum stored procedure, function, trigger, or view nesting level exceeded (limit 32).

How to set the action for a UIBarButtonItem in Swift

Swift 5

if you have created UIBarButtonItem in Interface Builder and you connected outlet to item and want to bind selector programmatically.

Don't forget to set target and selector.

addAppointmentButton.action = #selector(moveToAddAppointment)
addAppointmentButton.target = self

@objc private func moveToAddAppointment() {
     self.presenter.goToCreateNewAppointment()
}

How to identify platform/compiler from preprocessor macros?

If you're writing C++, I can't recommend using the Boost libraries strongly enough.

The latest version (1.55) includes a new Predef library which covers exactly what you're looking for, along with dozens of other platform and architecture recognition macros.

#include <boost/predef.h>

// ...

#if BOOST_OS_WINDOWS

#elif BOOST_OS_LINUX

#elif BOOST_OS_MACOS

#endif

Set value of hidden field in a form using jQuery's ".val()" doesn't work

Another gotcha here wasted some of my time, so I thought I would pass along the tip. I had a hidden field I gave an id that had . and [] brackets in the name (due to use with struts2) and the selector $("#model.thefield[0]") would not find my hidden field. Renaming the id to not use the periods and brackets caused the selector to begin working. So in the end I ended up with an id of model_the_field_0 instead and the selector worked fine.

How to get the position of a character in Python?

A character might appear multiple times in a string. For example in a string sentence, position of e is 1, 4, 7 (because indexing usually starts from zero). but what I find is both of the functions find() and index() returns first position of a character. So, this can be solved doing this:

def charposition(string, char):
    pos = [] #list to store positions for each 'char' in 'string'
    for n in range(len(string)):
        if string[n] == char:
            pos.append(n)
    return pos

s = "sentence"
print(charposition(s, 'e')) 

#Output: [1, 4, 7]

How to avoid java.util.ConcurrentModificationException when iterating through and removing elements from an ArrayList

If your goal is to remove all elements from the list, you can iterate over each item, and then call:

list.clear()

How to check if a string is a number?

The problem is that the result of your code "isDigit" is reflecting only the last digit test. As far as I understand your qustion, you want to return isDigit = 0 whenever you have any character that is not a number in your string. Following your logic, you should code it like this:

char tmp[16];
scanf("%s", tmp);

int isDigit = 0;
int j=0;
isDigit = 1;  /* Initialised it here */
while(j<strlen(tmp) && isDigit == 0){
  if(tmp[j] > 57 || tmp[j] < 48) /* changed it to OR || */
    isDigit = 0;
  j++;
}

To get a more understandable code, I'd also change the test:

if(tmp[j] > 57 || tmp[j] < 48) 

to the following:

if(tmp[j] > '9' || tmp[j] < '0')

Error: "The sandbox is not in sync with the Podfile.lock..." after installing RestKit with cocoapods

When you do

pod install --verbose

make sure:

1- you are in the correct directory. Most times, when a github project is downloaded, there will be a master folder. You need to be inside the actual project name folder(masterfolder/project folder) in the terminal before you invoke pod install --verbose

2- Delete the old pod lock folder then clean the project using xcode clean & do pod install.

3- Keep your rvm updated.

Filtering array of objects with lodash based on property value

With lodash:

const myArr = [ {name: "john", age: 23},
                {name: "john", age: 43},
                {name: "jim", age: 101},
                {name: "bob", age: 67} ];

const johnArr = _.filter(myArr, person => person.name === 'john');
console.log(johnArr)

enter image description here

Vanilla JavaScript:

const myArr = [ {name: "john", age: 23},
                {name: "john", age: 43},
                {name: "jim", age: 101},
                {name: "bob", age: 67} ];

const johnArr = myArr.filter(person => person.name === 'john');
console.log(johnArr);

enter image description here

How to get the real and total length of char * (char array)?

char *a = new char[10];

My question is that how can I get the length of a char *

It is very simply.:) It is enough to add only one statement

size_t N = 10;
char *a = new char[N];

Now you can get the size of the allocated array

std::cout << "The size is " << N << std::endl;

Many mentioned here C standard function std::strlen. But it does not return the actual size of a character array. It returns only the size of stored string literal.

The difference is the following. if to take your code snippet as an example

char a[] = "aaaaa";
int length = sizeof(a)/sizeof(char); // length=6

then std::strlen( a ) will return 5 instead of 6 as in your code.

So the conclusion is simple: if you need to dynamically allocate a character array consider usage of class std::string. It has methof size and its synonym length that allows to get the size of the array at any time.

For example

std::string s( "aaaaa" );

std::cout << s.length() << std::endl;

or

std::string s;
s.resize( 10 );

std::cout << s.length() << std::endl;

Redirect stderr and stdout in Bash

Curiously, this works:

yourcommand &> filename

But this gives a syntax error:

yourcommand &>> filename
syntax error near unexpected token `>'

You have to use:

yourcommand 1>> filename 2>&1

Can I make 'git diff' only the line numbers AND changed file names?

I know this is an old question but on Windows, this filters the git output to the files and changed line numbers:

(git diff -p --stat) | findstr "@@ --git"

diff --git a/dir1/dir2/file.cpp b/dir1/dir2/file.cpp
@@ -47,6 +47,7 @@ <some function name>
@@ -97,7 +98,7 @@ <another functon name>

To extract the files and the changed lines from that is a bit more work:

for /f "tokens=3,4* delims=-+ " %f in ('^(git diff -p --stat .^) ^| findstr ^"@@ --git^"') do @echo %f

a/dir1/dir2/file.cpp
47,7
98,7

Visual Studio 6 Windows Common Controls 6.0 (sp6) Windows 7, 64 bit

My solution was replacing the MSCOMCTL.OCX on windows 10 box with one from a Windows 7 box that also had MS Access installed. For some reason, there are different MSCOMCTL.OCX 2.0 controls with the same name.

I know this sounds crazy, and might not help anyone else, but we have saved this MSCOMCTL.OCX with a readme file and it has fixed our new install errors every time.

we unregister the current MSCOMCTL.OCX that came with Windows 10 box, delete it, and register the old one we have saved.

global variable for all controller and views

In Laravel 5.1 I needed a global variable populated with model data accessible in all views.

I followed a similar approach to ollieread's answer and was able to use my variable ($notifications) in any view.

My controller location: /app/Http/Controllers/Controller.php

<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

use App\Models\Main as MainModel;
use View;

abstract class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function __construct() {
        $oMainM = new MainModel;
        $notifications = $oMainM->get_notifications();
        View::share('notifications', $notifications);
    }
}

My model location: /app/Models/Main.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use DB;

class Main extends Model
{
    public function get_notifications() {...

Android error: Failed to install *.apk on device *: timeout

I get this a lot. I'm on a Galaxy S too. I unplug the cable from the phone, plug it back in and try launching the app again from Eclipse, and it usually does the trick. Eclipse seems to lose the connection to the phone occasionally but this seems to kick it back to life.

cannot be cast to java.lang.Comparable

  • the object which implements Comparable is Fegan.

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

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

How to call function on child component on parent events

A simple decoupled way to call methods on child components is by emitting a handler from the child and then invoking it from parent.

_x000D_
_x000D_
var Child = {_x000D_
  template: '<div>{{value}}</div>',_x000D_
  data: function () {_x000D_
    return {_x000D_
      value: 0_x000D_
    };_x000D_
  },_x000D_
  methods: {_x000D_
   setValue(value) {_x000D_
     this.value = value;_x000D_
    }_x000D_
  },_x000D_
  created() {_x000D_
    this.$emit('handler', this.setValue);_x000D_
  }_x000D_
}_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  components: {_x000D_
    'my-component': Child_x000D_
  },_x000D_
  methods: {_x000D_
   setValueHandler(fn) {_x000D_
     this.setter = fn_x000D_
    },_x000D_
    click() {_x000D_
     this.setter(70)_x000D_
    }_x000D_
  }_x000D_
})
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>_x000D_
_x000D_
<div id="app">_x000D_
  <my-component @handler="setValueHandler"></my-component>_x000D_
  <button @click="click">Click</button>  _x000D_
</div>
_x000D_
_x000D_
_x000D_

The parent keeps track of the child handler functions and calls whenever necessary.

Debugging iframes with Chrome developer tools

Currently evaluation in the console is performed in the context of the main frame in the page and it adheres to the same cross-origin policy as the main frame itself. This means that you cannot access elements in the iframe unless the main frame can. You can still set breakpoints in and debug your code using Scripts panel though.

Update: This is no longer true. See Metagrapher's answer.

Conda environments not showing up in Jupyter Notebook

I don't think the other answers are working any more, as conda stopped automatically setting environments up as jupyter kernels. You need to manually add kernels for each environment in the following way:

source activate myenv
python -m ipykernel install --user --name myenv --display-name "Python (myenv)"

As documented here:http://ipython.readthedocs.io/en/stable/install/kernel_install.html#kernels-for-different-environments Also see this issue.

Addendum: You should be able to install the nb_conda_kernels package with conda install nb_conda_kernels to add all environments automatically, see https://github.com/Anaconda-Platform/nb_conda_kernels

type checking in javascript

A number is an integer if its modulo %1 is 0-

function isInt(n){
    return (typeof n== 'number' && n%1== 0);
}

This is only as good as javascript gets- say +- ten to the 15th.

isInt(Math.pow(2,50)+.1) returns true, as does Math.pow(2,50)+.1 == Math.pow(2,50)

Angular 2 execute script after template render

Actually ngAfterViewInit() will initiate only once when the component initiate.

If you really want a event triggers after the HTML element renter on the screen then you can use ngAfterViewChecked()

Design DFA accepting binary strings divisible by a number 'n'

You can build DFA using simple modular arithmetics. We can interpret w which is a string of k-ary numbers using a following rule

V[0] = 0
V[i] = (S[i-1] * k) + to_number(str[i])

V[|w|] is a number that w is representing. If modify this rule to find w mod N, the rule becomes this.

V[0] = 0
V[i] = ((S[i-1] * k) + to_number(str[i])) mod N

and each V[i] is one of a number from 0 to N-1, which corresponds to each state in DFA. We can use this as the state transition.

See an example.

k = 2, N = 5

| V | (V*2 + 0) mod 5     | (V*2 + 1) mod 5     |
+---+---------------------+---------------------+
| 0 | (0*2 + 0) mod 5 = 0 | (0*2 + 1) mod 5 = 1 |
| 1 | (1*2 + 0) mod 5 = 2 | (1*2 + 1) mod 5 = 3 |
| 2 | (2*2 + 0) mod 5 = 4 | (2*2 + 1) mod 5 = 0 |
| 3 | (3*2 + 0) mod 5 = 1 | (3*2 + 1) mod 5 = 2 |
| 4 | (4*2 + 0) mod 5 = 3 | (4*2 + 1) mod 5 = 4 |

k = 3, N = 5

| V | 0 | 1 | 2 |
+---+---+---+---+
| 0 | 0 | 1 | 2 |
| 1 | 3 | 4 | 0 |
| 2 | 1 | 2 | 3 |
| 3 | 4 | 0 | 1 |
| 4 | 2 | 3 | 4 |

Now you can see a very simple pattern. You can actually build a DFA transition just write repeating numbers from left to right, from top to bottom, from 0 to N-1.

Converting bool to text in C++

With C++11 you might use a lambda to get a slightly more compact code and in place usage:

bool to_convert{true};
auto bool_to_string = [](bool b) -> std::string {
    return b ? "true" : "false";
};
std::string str{"string to print -> "};
std::cout<<str+bool_to_string(to_convert);

Prints:

string to print -> true

Find all CSV files in a directory using Python

Please use this tested working code. This function will return a list of all the CSV files with absolute CSV file paths in your specified path.

import os
from glob import glob

def get_csv_files(dir_path, ext):
    os.chdir(dir_path)
    return list(map(lambda x: os.path.join(dir_path, x), glob(f'*.{ext}')))

print(get_csv_files("E:\\input\\dir\\path", "csv"))

How to add leading zeros?

Here's a generalizable base R function:

pad_left <- function(x, len = 1 + max(nchar(x)), char = '0'){

    unlist(lapply(x, function(x) {
        paste0(
            paste(rep(char, len - nchar(x)), collapse = ''),
            x
        )
    }))
}

pad_left(1:100)

I like sprintf but it comes with caveats like:

however the actual implementation will follow the C99 standard and fine details (especially the behaviour under user error) may depend on the platform

how to check for null with a ng-if values in a view with angularjs?

You can also use ng-template, I think that would be more efficient while run time :)

<div ng-if="!test.view; else somethingElse">1</div>
<ng-template #somethingElse>
    <div>2</div>
</ng-template>

Cheers

Strange out of memory issue while loading an image to a Bitmap object

It's a known bug, it's not because of large files. Since Android Caches the Drawables, it's going out of memory after using few images. But I've found an alternate way for it, by skipping the android default cache system.

Solution: Move the images to "assets" folder and use the following function to get BitmapDrawable:

public static Drawable getAssetImage(Context context, String filename) throws IOException {
    AssetManager assets = context.getResources().getAssets();
    InputStream buffer = new BufferedInputStream((assets.open("drawable/" + filename + ".png")));
    Bitmap bitmap = BitmapFactory.decodeStream(buffer);
    return new BitmapDrawable(context.getResources(), bitmap);
}

Best method for reading newline delimited files and discarding the newlines?

What do you think about this approach?

with open(filename) as data:
    datalines = (line.rstrip('\r\n') for line in data)
    for line in datalines:
        ...do something awesome...

Generator expression avoids loading whole file into memory and with ensures closing the file

Adobe Acrobat Pro make all pages the same dimension

With Mac OS X and the more recent versions of Acrobat Pro, the PDF printer option does not work. What does work is doing basically the same thing in Preview App. Open the multi page file in Preview, select File>Print. In the Print dialog set your sheet size as if you are using a printer. You may want to select "Auto Rotate", "Scale to Fit" and "Print Entire Image". Then in the lower left corner is the drop button "PDF" and in that menu select "Save as PDF". Give it a new file name, click Save and then you can open the resulting file in whatever PDF app you want and the sheet sizes are the same.

Permutation of array

According to wiki https://en.wikipedia.org/wiki/Heap%27s_algorithm

Heap's algorithm generates all possible permutations of n objects. It was first proposed by B. R. Heap in 1963. The algorithm minimizes movement: it generates each permutation from the previous one by interchanging a single pair of elements; the other n-2 elements are not disturbed. In a 1977 review of permutation-generating algorithms, Robert Sedgewick concluded that it was at that time the most effective algorithm for generating permutations by computer.

So if we want to do it in recursive manner, Sudo code is bellow.

procedure generate(n : integer, A : array of any):
    if n = 1 then
          output(A)
    else
        for i := 0; i < n - 1; i += 1 do
            generate(n - 1, A)
            if n is even then
                swap(A[i], A[n-1])
            else
                swap(A[0], A[n-1])
            end if
        end for
        generate(n - 1, A)
    end if

java code:

public static void printAllPermutations(
        int n, int[] elements, char delimiter) {
    if (n == 1) {
        printArray(elements, delimiter);
    } else {
        for (int i = 0; i < n - 1; i++) {
            printAllPermutations(n - 1, elements, delimiter);
            if (n % 2 == 0) {
                swap(elements, i, n - 1);
            } else {
                swap(elements, 0, n - 1);
            }
        }
        printAllPermutations(n - 1, elements, delimiter);
    }
}

private static void printArray(int[] input, char delimiter) {
    int i = 0;
    for (; i < input.length; i++) {
        System.out.print(input[i]);
    }
    System.out.print(delimiter);
}

private static void swap(int[] input, int a, int b) {
    int tmp = input[a];
    input[a] = input[b];
    input[b] = tmp;
}

public static void main(String[] args) {
    int[] input = new int[]{0,1,2,3};
    printAllPermutations(input.length, input, ',');
}

Using Intent in an Android application to show another activity

The issue was the OrderScreen Activity wasn't added to the AndroidManifest.xml. Once I added that as an application node, it worked properly.

<activity android:name=".OrderScreen" />

Checking whether the pip is installed?

pip list is a shell command. You should run it in your shell (bash/cmd), rather than invoke it from python interpreter.

pip does not provide a stable API. The only supported way of calling it is via subprocess, see docs and the code at the end of this answer.

However, if you want to just check if pip exists locally, without running it, and you are running Linux, I would suggest that you use bash's which command:

which pip

It should show you whether the command can be found in bash's PATH/aliases, and if it does, what does it actually execute.

If running pip is not an issue, you could just do:

python -m pip --version

If you really need to do it from a python script, you can always put the import statement into a try...except block:

try:
    import pip
except ImportError:
    print("Pip not present.")

Or check what's the output of a pip --version using subprocess module:

subprocess.check_call([sys.executable, '-m', 'pip', '--version'])

What is the best open-source java charting library? (other than jfreechart)

There aren't a lot of them because they would be in competition with JFreeChart, and it's awesome. You can get documentation and examples by downloading the developer's guide. There are also tons of free online tutorials if you search for them.

What would be the Unicode character for big bullet in the middle of the character?

You can search for “bullet” when using e.g. BabelPad (which has a Character Map where you can search by character name), but you will hardly find anything larger than U+2022 BULLET (though the size depends on font). Searching for “circle” finds many characters, too many, as the string appears in so many names. The largest simple circle is probably U+25CF BLACK CIRCLE “?”. If it’s too large U+26AB MEDIUM BLACK CIRCLE “?” might be suitable.

Beware that few fonts contain these characters.

Remove blue border from css custom-styled button in Chrome

Don't forget the !important declaration, for a better result

button:focus {outline:0 !important;}

A rule that has the !important property will always be applied no matter where that rule appears in the CSS document.

.NET Out Of Memory Exception - Used 1.3GB but have 16GB installed

Its worth mentioning that the default for an 'Any CPU' compile now checks the 'Prefer 32bit' check box. Being set to AnyCPU, on a 64bit OS with 16gb of RAM can still hit an out of memory exception at 2gb if this is checked.

Prefer32BitCheckBox

WPF C# button style

   <Button x:Name="mybtnSave" FlowDirection="LeftToRight"  HorizontalAlignment="Left" Margin="813,614,0,0" VerticalAlignment="Top"  Width="223" Height="53" BorderBrush="#FF2B3830" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontFamily="B Titr" FontSize="15" FontWeight="Bold" BorderThickness="2" TabIndex="107" Click="mybtnSave_Click" >
        <Button.Background>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="Black" Offset="0"/>
                <GradientStop Color="#FF080505" Offset="1"/>
                <GradientStop Color="White" Offset="0.536"/>
            </LinearGradientBrush>
        </Button.Background>
        <Button.Effect>
            <DropShadowEffect/>
        </Button.Effect>
        <StackPanel HorizontalAlignment="Stretch" Cursor="Hand" >
            <StackPanel.Background>
                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="#FF3ED82E" Offset="0"/>
                    <GradientStop Color="#FF3BF728" Offset="1"/>
                    <GradientStop Color="#FF212720" Offset="0.52"/>
                </LinearGradientBrush>
            </StackPanel.Background>
            <Image HorizontalAlignment="Left"  Source="image/Append Or Save 3.png" Height="36" Width="203" />
            <TextBlock HorizontalAlignment="Center" Width="145" Height="22" VerticalAlignment="Top" Margin="0,-31,-35,0" Text="Save Com F12" FontFamily="Tahoma" FontSize="14" Padding="0,4,0,0" Foreground="White" />
        </StackPanel>
    </Button>ente[![enter image description here][1]][1]r image description here

Send request to curl with post data sourced from a file

I need to make a POST request via Curl from the command line. Data for this request is located in a file...

All you need to do is have the --data argument start with a @:

curl -H "Content-Type: text/xml" --data "@path_of_file" host:port/post-file-path

For example, if you have the data in a file called stuff.xml then you would do something like:

curl -H "Content-Type: text/xml" --data "@stuff.xml" host:port/post-file-path

The stuff.xml filename can be replaced with a relative or full path to the file: @../xml/stuff.xml, @/var/tmp/stuff.xml, ...

Read text from response

I've just tried that myself, and it gave me a 200 OK response, but no content - the content length was 0. Are you sure it's giving you content? Anyway, I'll assume that you've really got content.

Getting actual text back relies on knowing the encoding, which can be tricky. It should be in the Content-Type header, but then you've got to parse it etc.

However, if this is actually XML (e.g. from "http://google.com/xrds/xrds.xml"), it's a lot easier. Just load the XML into memory, e.g. via LINQ to XML. For example:

using System;
using System.IO;
using System.Net;
using System.Xml.Linq;
using System.Web;

class Test
{
    static void Main()
    {
        string url = "http://google.com/xrds/xrds.xml";
        HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);

        XDocument doc;
        using (WebResponse response = request.GetResponse())
        {
            using (Stream stream = response.GetResponseStream())
            {
                doc = XDocument.Load(stream);
            }
        }
        // Now do whatever you want with doc here
        Console.WriteLine(doc);
    }   
}

If the content is XML, getting the result into an XML object model (whether it's XDocument, XmlDocument or XmlReader) is likely to be more valuable than having the plain text.

Using Apache httpclient for https

I put together this test app to reproduce the issue using the HTTP testing framework from the Apache HttpClient package:

ClassLoader cl = HCTest.class.getClassLoader();
URL url = cl.getResource("test.keystore");
KeyStore keystore  = KeyStore.getInstance("jks");
char[] pwd = "nopassword".toCharArray();
keystore.load(url.openStream(), pwd);

TrustManagerFactory tmf = TrustManagerFactory.getInstance(
        TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keystore);
TrustManager[] tm = tmf.getTrustManagers();

KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
        KeyManagerFactory.getDefaultAlgorithm());
kmfactory.init(keystore, pwd);
KeyManager[] km = kmfactory.getKeyManagers();

SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(km, tm, null);

LocalTestServer localServer = new LocalTestServer(sslcontext);
localServer.registerDefaultHandlers();

localServer.start();
try {

    DefaultHttpClient httpclient = new DefaultHttpClient();
    TrustStrategy trustStrategy = new TrustStrategy() {

        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            for (X509Certificate cert: chain) {
                System.err.println(cert);
            }
            return false;
        }

    };

    SSLSocketFactory sslsf = new SSLSocketFactory("TLS", null, null, keystore, null,
            trustStrategy, new AllowAllHostnameVerifier());
    Scheme https = new Scheme("https", 443, sslsf);
    httpclient.getConnectionManager().getSchemeRegistry().register(https);

    InetSocketAddress address = localServer.getServiceAddress();
    HttpHost target1 = new HttpHost(address.getHostName(), address.getPort(), "https");
    HttpGet httpget1 = new HttpGet("/random/100");
    HttpResponse response1 = httpclient.execute(target1, httpget1);
    System.err.println(response1.getStatusLine());
    HttpEntity entity1 = response1.getEntity();
    EntityUtils.consume(entity1);
    HttpHost target2 = new HttpHost("www.verisign.com", 443, "https");
    HttpGet httpget2 = new HttpGet("/");
    HttpResponse response2 = httpclient.execute(target2, httpget2);
    System.err.println(response2.getStatusLine());
    HttpEntity entity2 = response2.getEntity();
    EntityUtils.consume(entity2);
} finally {
    localServer.stop();
}

Even though, Sun's JSSE implementation appears to always read the trust material from the default trust store for some reason, it does not seem to get added to the SSL context and to impact the process of trust verification during the SSL handshake.

Here's the output of the test app. As you can see, the first request succeeds whereas the second fails as the connection to www.verisign.com is rejected as untrusted.

[
[
  Version: V1
  Subject: CN=Simple Test Http Server, OU=Jakarta HttpClient Project, O=Apache Software Foundation, L=Unknown, ST=Unknown, C=Unknown
  Signature Algorithm: SHA1withDSA, OID = 1.2.840.10040.4.3

  Key:  Sun DSA Public Key
    Parameters:DSA
    p:     fd7f5381 1d751229 52df4a9c 2eece4e7 f611b752 3cef4400 c31e3f80 b6512669
    455d4022 51fb593d 8d58fabf c5f5ba30 f6cb9b55 6cd7813b 801d346f f26660b7
    6b9950a5 a49f9fe8 047b1022 c24fbba9 d7feb7c6 1bf83b57 e7c6a8a6 150f04fb
    83f6d3c5 1ec30235 54135a16 9132f675 f3ae2b61 d72aeff2 2203199d d14801c7
    q:     9760508f 15230bcc b292b982 a2eb840b f0581cf5
    g:     f7e1a085 d69b3dde cbbcab5c 36b857b9 7994afbb fa3aea82 f9574c0b 3d078267
    5159578e bad4594f e6710710 8180b449 167123e8 4c281613 b7cf0932 8cc8a6e1
    3c167a8b 547c8d28 e0a3ae1e 2bb3a675 916ea37f 0bfa2135 62f1fb62 7a01243b
    cca4f1be a8519089 a883dfe1 5ae59f06 928b665e 807b5525 64014c3b fecf492a

  y:
    f0cc639f 702fd3b1 03fa8fa6 676c3756 ea505448 23cd1147 fdfa2d7f 662f7c59
    a02ddc1a fd76673e 25210344 cebbc0e7 6250fff1 a814a59f 30ff5c7e c4f186d8
    f0fd346c 29ea270d b054c040 c74a9fc0 55a7020f eacf9f66 a0d86d04 4f4d23de
    7f1d681f 45c4c674 5762b71b 808ded17 05b74baf 8de3c4ab 2ef662e3 053af09e

  Validity: [From: Sat Dec 11 14:48:35 CET 2004,
               To: Tue Dec 09 14:48:35 CET 2014]
  Issuer: CN=Simple Test Http Server, OU=Jakarta HttpClient Project, O=Apache Software Foundation, L=Unknown, ST=Unknown, C=Unknown
  SerialNumber: [    41bafab3]

]
  Algorithm: [SHA1withDSA]
  Signature:
0000: 30 2D 02 15 00 85 BE 6B   D0 91 EF 34 72 05 FF 1A  0-.....k...4r...
0010: DB F6 DE BF 92 53 9B 14   27 02 14 37 8D E8 CB AC  .....S..'..7....
0020: 4E 6C 93 F2 1F 7D 20 A1   2D 6F 80 5F 58 AE 33     Nl.... .-o._X.3

]
HTTP/1.1 200 OK
[
[
  Version: V3
  Subject: CN=www.verisign.com, OU=" Production Security Services", O="VeriSign, Inc.", STREET=487 East Middlefield Road, L=Mountain View, ST=California, OID.2.5.4.17=94043, C=US, SERIALNUMBER=2497886, OID.2.5.4.15="V1.0, Clause 5.(b)", OID.1.3.6.1.4.1.311.60.2.1.2=Delaware, OID.1.3.6.1.4.1.311.60.2.1.3=US
  Signature Algorithm: SHA1withRSA, OID = 1.2.840.113549.1.1.5

  Key:  Sun RSA public key, 2048 bits
  modulus: 20699622354183393041832954221256409980425015218949582822286196083815087464214375375678538878841956356687753084333860738385445545061253653910861690581771234068858443439641948884498053425403458465980515883570440998475638309355278206558031134532548167239684215445939526428677429035048018486881592078320341210422026566944903775926801017506416629554190534665876551381066249522794321313235316733139718653035476771717662585319643139144923795822646805045585537550376512087897918635167815735560529881178122744633480557211052246428978388768010050150525266771462988042507883304193993556759733514505590387262811565107773578140271
  public exponent: 65537
  Validity: [From: Wed May 26 02:00:00 CEST 2010,
               To: Sat May 26 01:59:59 CEST 2012]
  Issuer: CN=VeriSign Class 3 Extended Validation SSL SGC CA, OU=Terms of use at https://www.verisign.com/rpa (c)06, OU=VeriSign Trust Network, O="VeriSign, Inc.", C=US
  SerialNumber: [    53d2bef9 24a7245e 83ca01e4 6caa2477]

Certificate Extensions: 10
[1]: ObjectId: 1.3.6.1.5.5.7.1.1 Criticality=false
AuthorityInfoAccess [
  [accessMethod: 1.3.6.1.5.5.7.48.1
   accessLocation: URIName: http://EVIntl-ocsp.verisign.com, accessMethod: 1.3.6.1.5.5.7.48.2
   accessLocation: URIName: http://EVIntl-aia.verisign.com/EVIntl2006.cer]
]

...

]
Exception in thread "main" javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated
    at com.sun.net.ssl.internal.ssl.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:345)
    at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:128)
    at org.apache.http.conn.ssl.SSLSocketFactory.createLayeredSocket(SSLSocketFactory.java:446)
...

Shell script to capture Process ID and kill it if exist

Came across somewhere..thought it is simple and useful

You can use the command in crontab directly ,

* * * * * ps -lf | grep "user" |  perl -ane '($h,$m,$s) = split /:/,$F
+[13]; kill 9, $F[3] if ($h > 1);'

or, we can write it as shell script ,

#!/bin/sh
# longprockill.sh
ps -lf | grep "user" |  perl -ane '($h,$m,$s) = split /:/,$F[13]; kill
+ 9, $F[3] if ($h > 1);'

And call it crontab like so,

* * * * * longprockill.sh

Center Plot title in ggplot2

From the release news of ggplot 2.2.0: "The main plot title is now left-aligned to better work better with a subtitle". See also the plot.title argument in ?theme: "left-aligned by default".

As pointed out by @J_F, you may add theme(plot.title = element_text(hjust = 0.5)) to center the title.

ggplot() +
  ggtitle("Default in 2.2.0 is left-aligned")

enter image description here

ggplot() +
  ggtitle("Use theme(plot.title = element_text(hjust = 0.5)) to center") +
  theme(plot.title = element_text(hjust = 0.5))

enter image description here

How to include JavaScript file or library in Chrome console?

Do you use some AJAX framework? Using jQuery it would be:

$.getScript('script.js');

If you're not using any framework then see the answer by Harmen.

(Maybe it is not worth to use jQuery just to do this one simple thing (or maybe it is) but if you already have it loaded then you might as well use it. I have seen websites that have jQuery loaded e.g. with Bootstrap but still use the DOM API directly in a way that is not always portable, instead of using the already loaded jQuery for that, and many people are not aware of the fact that even getElementById() doesn't work consistently on all browsers - see this answer for details.)

UPDATE:

It's been years since I wrote this answer and I think it's worth pointing out here that today you can use:

to dynamically load scripts. Those may be relevant to people reading this question.

See also: The Fluent 2014 talk by Guy Bedford: Practical Workflows for ES6 Modules.

Extract month and year from a zoo::yearmon object

You can use format:

library(zoo)
x <- as.yearmon(Sys.time())
format(x,"%b")
[1] "Mar"
format(x,"%Y")
[1] "2012"

phpmyadmin logs out after 1440 secs

You should restart apache or httpd, not mysqld

sudo service httpd restart

or

sudo /etc/init.d/apache2 restart

How do you create a toggle button?

The good semantic way would be to use a checkbox, and then style it in different ways if it is checked or not. But there are no good ways do to it. You have to add extra span, extra div, and, for a really nice look, add some javascript.

So the best solution is to use a small jQuery function and two background images for styling the two different statuses of the button. Example with an up/down effect given by borders:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('a#button').click(function() {_x000D_
    $(this).toggleClass("down");_x000D_
  });_x000D_
});
_x000D_
a {_x000D_
  background: #ccc;_x000D_
  cursor: pointer;_x000D_
  border-top: solid 2px #eaeaea;_x000D_
  border-left: solid 2px #eaeaea;_x000D_
  border-bottom: solid 2px #777;_x000D_
  border-right: solid 2px #777;_x000D_
  padding: 5px 5px;_x000D_
}_x000D_
_x000D_
a.down {_x000D_
  background: #bbb;_x000D_
  border-top: solid 2px #777;_x000D_
  border-left: solid 2px #777;_x000D_
  border-bottom: solid 2px #eaeaea;_x000D_
  border-right: solid 2px #eaeaea;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<a id="button" title="button">Press Me</a>
_x000D_
_x000D_
_x000D_

Obviously, you can add background images that represent button up and button down, and make the background color transparent.

Numpy: Get random set of rows from 2D array

This is a similar answer to the one Hezi Rasheff provided, but simplified so newer python users understand what's going on (I noticed many new datascience students fetch random samples in the weirdest ways because they don't know what they are doing in python).

You can get a number of random indices from your array by using:

indices = np.random.choice(A.shape[0], amount_of_samples, replace=False)

You can then use fancy indexing with your numpy array to get the samples at those indices:

A[indices]

This will get you the specified number of random samples from your data.

What is the difference between JavaScript and ECMAScript?

Here are my findings:

JavaScript: The Definitive Guide, written by David Flanagan provides a very concise explanation:

JavaScript was created at Netscape in the early days of the Web, and technically, "JavaScript" is a trademark licensed from Sun Microsystems (now Oracle) used to describe Netscape's (now Mozilla's) implementation of the language. Netscape submitted the language for standardization to ECMA and because of trademark issues, the standardized version of the language was stuck with the awkward name "ECMAScript". For the same trademark reasons, Microsoft's version of the language is formally known as "JScript". In practice, just about everyone calls the language JavaScript.

A blog post by Microsoft seems to agree with what Flanagan explains by saying..

ECMAScript is the official name for the JavaScript language we all know and love.

.. which makes me think all occurrences of JavaScript in this reference post (by Microsoft again) must be replaced by ECMASCript. They actually seem to be careful with using ECMAScript only in this, more recent and more technical documentation page.

w3schools.com seems to agree with the definitions above:

JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in 1997. ECMA-262 is the official name of the standard. ECMAScript is the official name of the language.

The key here is: the official name of the language.

If you check Mozilla 's JavaScript version pages, you will encounter the following statement:

Deprecated. The explicit versioning and opt-in of language features was Mozilla-specific and are in process of being removed. Firefox 4 was the last version which referred to a JavaScript version (1.8.5). With new ECMA standards, JavaScript language features are now often mentioned with their initial definition in ECMA-262 Editions such as ECMAScript 2015.

and when you see the recent release notes, you will always see reference to ECMAScript standards, such as:

  • The ES2015 Symbol.toStringTag property has been implemented (bug 1114580).

  • The ES2015 TypedArray.prototype.toString() and TypedArray.prototype.toLocaleString() methods have been implemented (bug 1121938).

Mozilla Web Docs also has a page that explains the difference between ECMAScript and JavaScript:

However, the umbrella term "JavaScript" as understood in a web browser context contains several very different elements. One of them is the core language (ECMAScript), another is the collection of the Web APIs, including the DOM (Document Object Model).

Conclusion

To my understanding, people use the word JavaScript somewhat liberally to refer to the core ECMAScript specification.

I would say, all the modern JavaScript implementations (or JavaScript Engines) are in fact ECMAScript implementations. Check the definition of the V8 Engine from Google, for example:

V8 is Google’s open source high-performance JavaScript engine, written in C++ and used in Google Chrome, the open source browser from Google, and in Node.js, among others. It implements ECMAScript as specified in ECMA-262.

They seem to use the word JavaScript and ECMAScript interchangeably, and I would say it is actually an ECMAScript engine?

So most JavaScript Engines are actually implementing the ECMAScript standard, but instead of calling them ECMAScript engines, they call themselves JavaScript Engines. This answer also supports the way I see the situation.

When must we use NVARCHAR/NCHAR instead of VARCHAR/CHAR in SQL Server?

If anyone is facing this issue in Mysql there is no need to change varchar to nvarchar you can just change the collation of the column to utf8

How to run multiple sites on one apache instance

Yes with Virtual Host you can have as many parallel programs as you want:

Open

/etc/httpd/conf/httpd.conf

Listen 81
Listen 82
Listen 83

<VirtualHost *:81>
    ServerAdmin [email protected]
    DocumentRoot /var/www/site1/html
    ServerName site1.com
    ErrorLog logs/site1-error_log
    CustomLog logs/site1-access_log common
    ScriptAlias /cgi-bin/ "/var/www/site1/cgi-bin/"
</VirtualHost>

<VirtualHost *:82>
    ServerAdmin [email protected]
    DocumentRoot /var/www/site2/html
    ServerName site2.com
    ErrorLog logs/site2-error_log
    CustomLog logs/site2-access_log common
    ScriptAlias /cgi-bin/ "/var/www/site2/cgi-bin/"
</VirtualHost>

<VirtualHost *:83>
    ServerAdmin [email protected]
    DocumentRoot /var/www/site3/html
    ServerName site3.com
    ErrorLog logs/site3-error_log
    CustomLog logs/site3-access_log common
    ScriptAlias /cgi-bin/ "/var/www/site3/cgi-bin/"
</VirtualHost>

Restart apache

service httpd restart

You can now refer Site1 :

http://<ip-address>:81/ 
http://<ip-address>:81/cgi-bin/

Site2 :

http://<ip-address>:82/
http://<ip-address>:82/cgi-bin/

Site3 :

http://<ip-address>:83/ 
http://<ip-address>:83/cgi-bin/

If path is not hardcoded in any script then your websites should work seamlessly.

Map.Entry: How to use it?

Map.Entry is a key and its value combined into one class. This allows you to iterate over Map.entrySet() instead of having to iterate over Map.keySet(), then getting the value for each key. A better way to write what you have is:

for (Map.Entry<String, JButton> entry : listbouton.entrySet())
{
  String key = entry.getKey();
  JButton value = entry.getValue();

  this.add(value);
}

If this wasn't clear let me know and I'll amend my answer.

How can I replace newlines using PowerShell?

In my understanding, Get-Content eliminates ALL newlines/carriage returns when it rolls your text file through the pipeline. To do multiline regexes, you have to re-combine your string array into one giant string. I do something like:

$text = [string]::Join("`n", (Get-Content test.txt))
[regex]::Replace($text, "t`n", "ting`na ", "Singleline")

Clarification: small files only folks! Please don't try this on your 40 GB log file :)

Connection refused on docker container

You need to publish the exposed ports by using the following options:

-P (upper case) or --publish-all that will tell Docker to use random ports from your host and map them to the exposed container's ports.

-p (lower case) or --publish=[] that will tell Docker to use ports you manually set and map them to the exposed container's ports.

The second option is preferred because you already know which ports are mapped. If you use the first option then you will need to call docker inspect demo and check which random ports are being used from your host at the Ports section.

Just run the following command:

docker run -it -p 8080:8080 demo

After that your url will work.

Set Value of Input Using Javascript Function

The following works in MVC5:

document.getElementById('theID').value = 'new value';

File to import not found or unreadable: compass

Compass adjusts the way partials are imported. It allows importing components based solely on their name, without specifying the path.

Before you can do @import 'compass';, you should:

Install Compass as a Ruby gem:

gem install compass

After that, you should use Compass's own command line tool to compile your SASS code:

cd path/to/your/project/
compass compile

Note that Compass reqiures a configuration file called config.rb. You should create it for Compass to work.

The minimal config.rb can be as simple as this:

css_dir =   "css"
sass_dir =  "sass"

And your SASS code should reside in sass/.

Instead of creating a configuration file manually, you can create an empty Compass project with compass create <project-name> and then copy your SASS code inside it.

Note that if you want to use Compass extensions, you will have to:

  1. require them from the config.rb;
  2. import them from your SASS file.

More info here: http://compass-style.org/help/

What is the best way to generate a unique and short file name in Java

This also works

String logFileName = new SimpleDateFormat("yyyyMMddHHmm'.txt'").format(new Date());

logFileName = "loggerFile_" + logFileName;

MySQL INNER JOIN Alias

You'll need to join twice:

SELECT home.*, away.*, g.network, g.date_start 
FROM game AS g
INNER JOIN team AS home
  ON home.importid = g.home
INNER JOIN team AS away
  ON away.importid = g.away
ORDER BY g.date_start DESC 
LIMIT 7

How to change environment's font size?

(VS Code 1.33.1 on Windows 7)

Zoom all (UI and editor): CTRL + +, CTRL + -.

Zoom editor: CTRL + Mouse Wheel.

See below how i fixed it.

As suggested by @Edwin: Pressing Control+Shift+P and then typing "settings" will allow you to easily find the user or workspace settings file.

My settings file is found here: "C:\Users\You_user\AppData\Roaming\Code\User\settings.json"

My file looks like this:

{
    "editor.fontSize": 12,
    "editor.suggestFontSize": 6,
    "markdown.preview.fontSize": 0,
    "terminal.integrated.fontSize": 10,
    "window.zoomLevel": 0,
    "workbench.sideBar.location": "left",
    "editor.mouseWheelZoom": true
}

In which conda environment is Jupyter executing?

Question 1: Find the current notebook's conda environment

Open the notebook in Jupyter Notebooks and look in the upper right corner of the screen.

It should say, for example, "Python [env_name]" if the language is Python and it's using an environment called env_name.

jupyter notebook with name of environment


Question 2: Start Jupyter Notebook from within a different conda environment

Activate a conda environment in your terminal using source activate <environment name> before you run jupyter notebook. This sets the default environment for Jupyter Notebooks. Otherwise, the [Root] environment is the default.

jupyter notebooks home screen, conda tab, create new environment

You can also create new environments from within Jupyter Notebook (home screen, Conda tab, and then click the plus sign).

And you can create a notebook in any environment you want. Select the "Files" tab on the home screen and click the "New" dropdown menu, and in that menu select a Python environment from the list.

jupyter notebooks home screen, files tab, create new notebook

Best way to check for IE less than 9 in JavaScript without library

Javascript

var ie = (function(){

    var undef,
        v = 3,
        div = document.createElement('div'),
        all = div.getElementsByTagName('i');

    while (
        div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
        all[0]
    );

    return v > 4 ? v : undef;

}());

You can then do:

ie < 9

By James Panolsey from here: http://james.padolsey.com/javascript/detect-ie-in-js-using-conditional-comments

Convert String into a Class Object

You can use the statement :-

Class c = s.getClass();

To get the class instance.

Char Comparison in C

A char variable is actually an 8-bit integral value. It will have values from 0 to 255. These are ASCII codes. 0 stands for the C-null character, and 255 stands for an empty symbol.

So, when you write the following assignment:

char a = 'a'; 

It is the same thing as:

char a = 97;

So, you can compare two char variables using the >, <, ==, <=, >= operators:

char a = 'a';
char b = 'b';

if( a < b ) printf("%c is smaller than %c", a, b);
if( a > b ) printf("%c is smaller than %c", a, b);
if( a == b ) printf("%c is equal to %c", a, b);

What's the difference between RANK() and DENSE_RANK() functions in oracle?

This article here nicely explains it. Essentially, you can look at it as such:

CREATE TABLE t AS
SELECT 'a' v FROM dual UNION ALL
SELECT 'a'   FROM dual UNION ALL
SELECT 'a'   FROM dual UNION ALL
SELECT 'b'   FROM dual UNION ALL
SELECT 'c'   FROM dual UNION ALL
SELECT 'c'   FROM dual UNION ALL
SELECT 'd'   FROM dual UNION ALL
SELECT 'e'   FROM dual;

SELECT
  v,
  ROW_NUMBER() OVER (ORDER BY v) row_number,
  RANK()       OVER (ORDER BY v) rank,
  DENSE_RANK() OVER (ORDER BY v) dense_rank
FROM t
ORDER BY v;

The above will yield:

+---+------------+------+------------+
| V | ROW_NUMBER | RANK | DENSE_RANK |
+---+------------+------+------------+
| a |          1 |    1 |          1 |
| a |          2 |    1 |          1 |
| a |          3 |    1 |          1 |
| b |          4 |    4 |          2 |
| c |          5 |    5 |          3 |
| c |          6 |    5 |          3 |
| d |          7 |    7 |          4 |
| e |          8 |    8 |          5 |
+---+------------+------+------------+

In words

  • ROW_NUMBER() attributes a unique value to each row
  • RANK() attributes the same row number to the same value, leaving "holes"
  • DENSE_RANK() attributes the same row number to the same value, leaving no "holes"

event.preventDefault() function not working in IE

preventDefault is a widespread standard; using an adhoc every time you want to be compliant with old IE versions is cumbersome, better to use a polyfill:

if (typeof Event.prototype.preventDefault === 'undefined') {
    Event.prototype.preventDefault = function (e, callback) {
        this.returnValue = false;
    };
}

This will modify the prototype of the Event and add this function, a great feature of javascript/DOM in general. Now you can use e.preventDefault with no problem.

POST Content-Length exceeds the limit

I suggest that you should change to post_max_size from 8M to 32M in the php.ini file.

How can I represent a range in Java?

import java.util.Arrays;

class Soft{
    public static void main(String[] args){
        int[] nums=range(9, 12);
        System.out.println(Arrays.toString(nums));
    }
    static int[] range(int low, int high){
        int[] a=new int[high-low];
        for(int i=0,j=low;i<high-low;i++,j++){
            a[i]=j;
        }
        return a;

    }
}

My code is similar to Python`s range :)

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;
}

Export DataBase with MySQL Workbench with INSERT statements

If you want to export just single table, or subset of data from some table, you can do it directly from result window:

  1. Click export button: enter image description here

  2. Change Save as type to "SQL Insert statements" enter image description here

Java array assignment (multiple values)

    public class arrayFloats {
      public static void main (String [] args){
        float [] Values = new float[3];
        float Incre = 0.1f;
        int Count = 0;

        for (Count = 0;Count<3 ;Count++ ) {
          Values [Count] = Incre + 0.0f;
          Incre += 0.1f;
          System.out.println("Values [" + Count + "] : " + Values [Count]);
        }


      }
    }

//OUTPUT:
//Values [0] : 0.1
//Values [1] : 0.2
//Values [2] : 0.3

This isn't the all and be all of assigning values to a specific array. Since I've seen the sample was 0.1 - 0.3 you could do it this way. This method is very useful if you're designing charts and graphs. You can have the x-value incremented by 0.1 until nth time.

Or you want to design some grid of some sort.

Check if String / Record exists in DataTable

You can loop over each row of the DataTable and check the value.

I'm a big fan of using a foreach loop when using IEnumerables. Makes it very simple and clean to look at or process each row

DataTable dtPs = // ... initialize your DataTable
foreach (DataRow dr in dtPs.Rows)
{
    if (dr["item_manuf_id"].ToString() == "some value")
    {
        // do your deed
    }
}

Alternatively you can use a PrimaryKey for your DataTable. This helps in various ways, but you often need to define one before you can use it.

An example of using one if at http://msdn.microsoft.com/en-us/library/z24kefs8(v=vs.80).aspx

DataTable workTable = new DataTable("Customers");

// set constraints on the primary key
DataColumn workCol = workTable.Columns.Add("CustID", typeof(Int32));
workCol.AllowDBNull = false;
workCol.Unique = true;

workTable.Columns.Add("CustLName", typeof(String));
workTable.Columns.Add("CustFName", typeof(String));
workTable.Columns.Add("Purchases", typeof(Double));

// set primary key
workTable.PrimaryKey = new DataColumn[] { workTable.Columns["CustID"] };

Once you have a primary key defined and data populated, you can use the Find(...) method to get the rows that match your primary key.

Take a look at http://msdn.microsoft.com/en-us/library/y06xa2h1(v=vs.80).aspx

DataRow drFound = dtPs.Rows.Find("some value");
if (drFound["item_manuf_id"].ToString() == "some value")
{
    // do your deed
}

Finally, you can use the Select() method to find data within a DataTable also found at at http://msdn.microsoft.com/en-us/library/y06xa2h1(v=vs.80).aspx.

String sExpression = "item_manuf_id == 'some value'";
DataRow[] drFound;
drFound = dtPs.Select(sExpression);

foreach (DataRow dr in drFound)
{
    // do you deed. Each record here was already found to match your criteria
}

How to correctly use the ASP.NET FileUpload control

Adding a FileUpload control from the code behind should work just fine, where the HasFile property should be available (for instance in your Click event).

If the properties don't appear to be available (either as a compiler error or via intellisense), you probably are referencing a different variable than you think you are.

Web-scraping JavaScript page with Python

It sounds like the data you're really looking for can be accessed via secondary URL called by some javascript on the primary page.

While you could try running javascript on the server to handle this, a simpler approach to might be to load up the page using Firefox and use a tool like Charles or Firebug to identify exactly what that secondary URL is. Then you can just query that URL directly for the data you are interested in.

MySQL combine two columns and add into a new column

Create the column:

ALTER TABLE yourtable ADD COLUMN combined VARCHAR(50);

Update the current values:

UPDATE yourtable SET combined = CONCAT(zipcode, ' - ', city, ', ', state);

Update all future values automatically:

CREATE TRIGGER insert_trigger
BEFORE INSERT ON yourtable
FOR EACH ROW
SET new.combined = CONCAT(new.zipcode, ' - ', new.city, ', ', new.state);

CREATE TRIGGER update_trigger
BEFORE UPDATE ON yourtable
FOR EACH ROW
SET new.combined = CONCAT(new.zipcode, ' - ', new.city, ', ', new.state);

Undefined index error PHP

This is happening because your PHP code is getting executed before the form gets posted.

To avoid this wrap your PHP code in following if statement and it will handle the rest no need to set if statements for each variables

       if(isset($_POST) && array_key_exists('name_of_your_submit_input',$_POST))
        {
             //process PHP Code
        }
        else
        {
             //do nothing
         }

Using generic std::function objects with member functions in one class

Unfortunately, C++ does not allow you to directly get a callable object referring to an object and one of its member functions. &Foo::doSomething gives you a "pointer to member function" which refers to the member function but not the associated object.

There are two ways around this, one is to use std::bind to bind the "pointer to member function" to the this pointer. The other is to use a lambda that captures the this pointer and calls the member function.

std::function<void(void)> f = std::bind(&Foo::doSomething, this);
std::function<void(void)> g = [this](){doSomething();};

I would prefer the latter.

With g++ at least binding a member function to this will result in an object three-pointers in size, assigning this to an std::function will result in dynamic memory allocation.

On the other hand, a lambda that captures this is only one pointer in size, assigning it to an std::function will not result in dynamic memory allocation with g++.

While I have not verified this with other compilers, I suspect similar results will be found there.

Difference between single and double quotes in Bash

If you're referring to what happens when you echo something, the single quotes will literally echo what you have between them, while the double quotes will evaluate variables between them and output the value of the variable.

For example, this

#!/bin/sh
MYVAR=sometext
echo "double quotes gives you $MYVAR"
echo 'single quotes gives you $MYVAR'

will give this:

double quotes gives you sometext
single quotes gives you $MYVAR

How to get Linux console window width in Python

It looks like there are some problems with that code, Johannes:

  • getTerminalSize needs to import os
  • what is env? looks like os.environ.

Also, why switch lines and cols before returning? If TIOCGWINSZ and stty both say lines then cols, I say leave it that way. This confused me for a good 10 minutes before I noticed the inconsistency.

Sridhar, I didn't get that error when I piped output. I'm pretty sure it's being caught properly in the try-except.

pascal, "HHHH" doesn't work on my machine, but "hh" does. I had trouble finding documentation for that function. It looks like it's platform dependent.

chochem, incorporated.

Here's my version:

def getTerminalSize():
    """
    returns (lines:int, cols:int)
    """
    import os, struct
    def ioctl_GWINSZ(fd):
        import fcntl, termios
        return struct.unpack("hh", fcntl.ioctl(fd, termios.TIOCGWINSZ, "1234"))
    # try stdin, stdout, stderr
    for fd in (0, 1, 2):
        try:
            return ioctl_GWINSZ(fd)
        except:
            pass
    # try os.ctermid()
    try:
        fd = os.open(os.ctermid(), os.O_RDONLY)
        try:
            return ioctl_GWINSZ(fd)
        finally:
            os.close(fd)
    except:
        pass
    # try `stty size`
    try:
        return tuple(int(x) for x in os.popen("stty size", "r").read().split())
    except:
        pass
    # try environment variables
    try:
        return tuple(int(os.getenv(var)) for var in ("LINES", "COLUMNS"))
    except:
        pass
    # i give up. return default.
    return (25, 80)

Process with an ID #### is not running in visual studio professional 2013 update 3

I recently had the same issue with VS 2013 and IIS Express:

"Process with an ID #### is not running ." // every time there is different ID number showing.

Here was the solution I found that worked for me:

1) Go into the Documents -> IIS Express -> config -> applicationhost.config

2) I opened applicationhost.config in Notepad++

3) Under the tag , there are lines of code that looks like this:

    <add name="Clr4IntegratedAppPool" managedRuntimeVersion="v4.0" managedPipelineMode="Integrated" CLRConfigFile="%IIS_USER_HOME%\config\aspnet.config" autoStart="true">
                 <processModel loadUserProfile="true" />
        </add>

4) Remove these two lines

                <processModel loadUserProfile="true" /> 
        </add>

5) Change the END of the first line to

            <add name="Clr4IntegratedAppPool" managedRuntimeVersion="v4.0" managedPipelineMode="Integrated" CLRConfigFile="%IIS_USER_HOME%\config\aspnet.config" autoStart="true" />

Notice that all I did was close the tag by adding ' /' after "true".

I am now able to run my projects in a web browser AND debug my code.

Also, I had updated to Update 4, but was having the same issue. I believe appending the applicationhost.config file was what fixed the problem.

I hope this helps!

Python Key Error=0 - Can't find Dict error in code

The defaultdict solution is better. But for completeness you could also check and create empty list before the append. Add the + lines:

+ if not u in self.adj.keys():
+     self.adj[u] = []
  self.adj[u].append(edge)
.
.

Bash function to find newest file matching pattern

There is a much more efficient way of achieving this. Consider the following command:

find . -cmin 1 -name "b2*"

This command finds the latest file produced exactly one minute ago with the wildcard search on "b2*". If you want files from the last two days then you'll be better off using the command below:

find . -mtime 2 -name "b2*"

The "." represents the current directory. Hope this helps.

How much overhead does SSL impose?

I second @erickson: The pure data-transfer speed penalty is negligible. Modern CPUs reach a crypto/AES throughput of several hundred MBit/s. So unless you are on resource constrained system (mobile phone) TLS/SSL is fast enough for slinging data around.

But keep in mind that encryption makes caching and load balancing much harder. This might result in a huge performance penalty.

But connection setup is really a show stopper for many application. On low bandwidth, high packet loss, high latency connections (mobile device in the countryside) the additional roundtrips required by TLS might render something slow into something unusable.

For example we had to drop the encryption requirement for access to some of our internal web apps - they where next to unusable if used from china.

Oracle Partition - Error ORA14400 - inserted partition key does not map to any partition

select partition_name,column_name,high_value,partition_position
from ALL_TAB_PARTITIONS a , ALL_PART_KEY_COLUMNS b 
where table_name='YOUR_TABLE' and a.table_name = b.name;

This query lists the column name used as key and the allowed values. make sure, you insert the allowed values(high_value). Else, if default partition is defined, it would go there.


EDIT:

I presume, your TABLE DDL would be like this.

CREATE TABLE HE0_DT_INF_INTERFAZ_MES
  (
    COD_PAIS NUMBER,
    FEC_DATA NUMBER,
    INTERFAZ VARCHAR2(100)
  )
  partition BY RANGE(COD_PAIS, FEC_DATA)
  (
    PARTITION PDIA_98_20091023 VALUES LESS THAN (98,20091024)
  );

Which means I had created a partition with multiple columns which holds value less than the composite range (98,20091024);

That is first COD_PAIS <= 98 and Also FEC_DATA < 20091024

Combinations And Result:

98, 20091024     FAIL
98, 20091023     PASS
99, ********     FAIL
97, ********     PASS
 < 98, ********     PASS

So the below INSERT fails with ORA-14400; because (98,20091024) in INSERT is EQUAL to the one in DDL but NOT less than it.

SQL> INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
                                  VALUES(98, 20091024, 'CTA');  2
INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
            *
ERROR at line 1:
ORA-14400: inserted partition key does not map to any partition

But, we I attempt (97,20091024), it goes through

SQL> INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
  2                                    VALUES(97, 20091024, 'CTA');

1 row created.

Using Node.js require vs. ES6 import/export

I personally use import because, we can import the required methods, members by using import.

import {foo, bar} from "dep";

FileName: dep.js

export foo function(){};
export const bar = 22

Credit goes to Paul Shan. More info.

What is the difference between exit and return?

  • return returns from the current function; it's a language keyword like for or break.
  • exit() terminates the whole program, wherever you call it from. (After flushing stdio buffers and so on).

The only case when both do (nearly) the same thing is in the main() function, as a return from main performs an exit().

In most C implementations, main is a real function called by some startup code that does something like int ret = main(argc, argv); exit(ret);. The C standard guarantees that something equivalent to this happens if main returns, however the implementation handles it.

Example with return:

#include <stdio.h>

void f(){
    printf("Executing f\n");
    return;
}

int main(){
    f();
    printf("Back from f\n");
}

If you execute this program it prints:

Executing f
Back from f

Another example for exit():

#include <stdio.h>
#include <stdlib.h>

void f(){
    printf("Executing f\n");
    exit(0);
}

int main(){
    f();
    printf("Back from f\n");
}

If you execute this program it prints:

Executing f

You never get "Back from f". Also notice the #include <stdlib.h> necessary to call the library function exit().

Also notice that the parameter of exit() is an integer (it's the return status of the process that the launcher process can get; the conventional usage is 0 for success or any other value for an error).

The parameter of the return statement is whatever the return type of the function is. If the function returns void, you can omit the return at the end of the function.

Last point, exit() come in two flavors _exit() and exit(). The difference between the forms is that exit() (and return from main) calls functions registered using atexit() or on_exit() before really terminating the process while _exit() (from #include <unistd.h>, or its synonymous _Exit from #include <stdlib.h>) terminates the process immediately.

Now there are also issues that are specific to C++.

C++ performs much more work than C when it is exiting from functions (return-ing). Specifically it calls destructors of local objects going out of scope. In most cases programmers won't care much of the state of a program after the processus stopped, hence it wouldn't make much difference: allocated memory will be freed, file ressource closed and so on. But it may matter if your destructor performs IOs. For instance automatic C++ OStream locally created won't be flushed on a call to exit and you may lose some unflushed data (on the other hand static OStream will be flushed).

This won't happen if you are using the good old C FILE* streams. These will be flushed on exit(). Actually, the rule is the same that for registered exit functions, FILE* will be flushed on all normal terminations, which includes exit(), but not calls to _exit() or abort().

You should also keep in mind that C++ provide a third way to get out of a function: throwing an exception. This way of going out of a function will call destructor. If it is not catched anywhere in the chain of callers, the exception can go up to the main() function and terminate the process.

Destructors of static C++ objects (globals) will be called if you call either return from main() or exit() anywhere in your program. They wont be called if the program is terminated using _exit() or abort(). abort() is mostly useful in debug mode with the purpose to immediately stop the program and get a stack trace (for post mortem analysis). It is usually hidden behind the assert() macro only active in debug mode.

When is exit() useful ?

exit() means you want to immediately stops the current process. It can be of some use for error management when we encounter some kind of irrecoverable issue that won't allow for your code to do anything useful anymore. It is often handy when the control flow is complicated and error codes has to be propagated all way up. But be aware that this is bad coding practice. Silently ending the process is in most case the worse behavior and actual error management should be preferred (or in C++ using exceptions).

Direct calls to exit() are especially bad if done in libraries as it will doom the library user and it should be a library user's choice to implement some kind of error recovery or not. If you want an example of why calling exit() from a library is bad, it leads for instance people to ask this question.

There is an undisputed legitimate use of exit() as the way to end a child process started by fork() on Operating Systems supporting it. Going back to the code before fork() is usually a bad idea. This is the rationale explaining why functions of the exec() family will never return to the caller.

django admin - add custom form fields that are not part of the model

Either in your admin.py or in a separate forms.py you can add a ModelForm class and then declare your extra fields inside that as you normally would. I've also given an example of how you might use these values in form.save():

from django import forms
from yourapp.models import YourModel


class YourModelForm(forms.ModelForm):

    extra_field = forms.CharField()

    def save(self, commit=True):
        extra_field = self.cleaned_data.get('extra_field', None)
        # ...do something with extra_field here...
        return super(YourModelForm, self).save(commit=commit)

    class Meta:
        model = YourModel

To have the extra fields appearing in the admin just:

  1. edit your admin.py and set the form property to refer to the form you created above
  2. include your new fields in your fields or fieldsets declaration

Like this:

class YourModelAdmin(admin.ModelAdmin):

    form = YourModelForm

    fieldsets = (
        (None, {
            'fields': ('name', 'description', 'extra_field',),
        }),
    )

UPDATE: In django 1.8 you need to add fields = '__all__' to the metaclass of YourModelForm.

How to change working directory in Jupyter Notebook?

You may use jupyter magic command as below

%cd "C:\abc\xyz\"

Convert MySql DateTime stamp into JavaScript's Date format

I think I may have found a simpler way, that nobody mentioned.

A MySQL DATETIME column can be converted to a unix timestamp through:

SELECT unix_timestamp(my_datetime_column) as stamp ...

We can make a new JavaScript Date object by using the constructor that requires milliseconds since the epoch. The unix_timestamp function returns seconds since the epoch, so we need to multiply by 1000:

SELECT unix_timestamp(my_datetime_column) * 1000 as stamp ...

The resulting value can be used directly to instantiate a correct Javascript Date object:

var myDate = new Date(<?=$row['stamp']?>);

Hope this helps.

What is the list of supported languages/locales on Android?

http://developer.android.com/reference/java/util/Locale.html

See CLDR for specific language support.

Ex : CLDR 1.8 for 2.3

http://cldr.unicode.org/index/downloads/cldr-1-8

Languages:

Afar [Qafar];
Afrikaans;
Akan;
Albanian [shqipe];
Amharic [????];
Arabic [?????????];
Armenian [???????];
Assamese [??????];
Asu [Kipare];
Atsam [cch];
Azerbaijani (Arabic) [az?rbaycanca (?r?b)];
Azerbaijani (Cyrillic) [?????????? (kiril)];
Azerbaijani (Latin) [az?rbaycanca (latin)];
Bambara [bamanakan];
Basque [euskara];
Belarusian [??????????];
Bemba [Ichibemba];
Bena [Hibena];
Bengali [?????];
Blin [???];
Bosnian [Bosanski];
Breton [br];
Bulgarian [?????????];
Burmese [???];
Catalan [català];
Central Morocco Tamazight (Latin) [Tamazi?t (Latn)];
Cherokee [???];
Chiga [Rukiga];
Colognian [ksh];
Cornish [kernewek];
Croatian [hrvatski];
Czech [ceština];
Danish [dansk];
Divehi [????????????];
Dutch [Nederlands];
Dzongkha [??????];
Embu [Kiembu];
English (Deseret) [ ()];
English (Shavian);
Esperanto;
Estonian [eesti];
Ewe [E?egbe];
Faroese [føroyskt];
Filipino;
Finnish [suomi];
French [français];
Friulian [furlan];
Fulah [Pulaar];
Ga [gaa];
Galician [galego];
Ganda [Luganda];
Geez [????];
Georgian [???????];
German [Deutsch];
Greek [????????];
Gujarati [???????];
Gusii [Ekegusii];
Hausa (Arabic) [Hausa (Arab)];
Hausa (Latin) [Hausa (Latn)];
Hawaiian [?olelo Hawai?i];
Hebrew [???????];
Hindi [??????];
Hungarian [magyar];
Icelandic [íslenska];
Igbo;
Indonesian [Bahasa Indonesia];
Interlingua;
Inuktitut [?????? ??????];
Irish [Gaeilge];
Italian [italiano];
Japanese [???];
Jju [kaj];
Kabuverdianu;
Kabyle [Taqbaylit];
Kalaallisut;
Kalenjin;
Kamba [Kikamba];
Kannada [?????];
Kazakh (Cyrillic) [????? (Cyrl)];
Khmer [?????????];
Kikuyu [Gikuyu];
Kinyarwanda;
Kirghiz [??????];
Konkani [??????];
Korean [???];
Koro [kfo];
Koyra Chiini [Koyra ciini];
Koyraboro Senni;
Kpelle [kpe];
Kurdish (Arabic) [?????? (??????)?];
Kurdish (Latin) [?kurdî (?????)?];
Langi [K?laangi];
Lao [???];
Latvian [latviešu];
Lingala [lingála];
Lithuanian [lietuviu];
Low German [Plattdüütsch];
Luo [Dholuo];
Luyia [Luluhia];
Macedonian [??????????];
Machame [Kimachame];
Makonde [Chimakonde];
Malagasy;
Malay [Bahasa Melayu];
Malayalam [??????];
Maltese [Malti];
Manx [Gaelg];
Maori [mi];
Marathi [?????];
Masai [Maa];
Meru [Kimiru];
Mongolian (Cyrillic) [?????? (Cyrl)];
Mongolian (Mongolian) [?????? (Mong)];
Morisyen [kreol morisien];
Nama [Khoekhoegowab];
Nepali [??????];
North Ndebele [isiNdebele];
Northern Sami [davvisámegiella];
Northern Sotho [Sesotho sa Leboa];
Norwegian [norsk];
Norwegian Bokmål [norsk bokmål];
Norwegian Nynorsk [nynorsk];
Nyanja [ny];
Nyankole [Runyankore];
Occitan;
Oriya [?????];
Oromo [Oromoo];
Pashto [??????];
Persian [???????];
Polish [polski];
Portuguese [português];
Punjabi (Arabic) [?????? (???????)?];
Punjabi (Gurmukhi) [?????? (???????)];
Romanian [româna];
Romansh [rumantsch];
Rombo [Kihorombo];
Russian [???????];
Rwa [Kiruwa];
Saho [ssy];
Samburu [Kisampur];
Sango [Sängö];
Sanskrit [??????? ????];
Sena;
Serbian (Cyrillic) [?????? (????????)];
Serbian (Latin) [Srpski (Latinica)];
Shambala [Kishambaa];
Shona [chiShona];
Sichuan Yi [???];
Sidamo [Sidaamu Afo];
Simplified Chinese [??(??)];
Sinhala [?????];
Slovak [slovencina];
Slovenian [slovenšcina];
Soga [Olusoga];
Somali [Soomaali];
South Ndebele [isiNdebele];
Southern Sotho [Sesotho];
Spanish [español];
Swahili [Kenya];
Swati [Siswati];
Swedish [svenska];
Swiss German [Schwiizertüütsch];
Syriac [????????];
Tachelhit (Latin) [tamazight (Latn)];
Tachelhit (Tifinagh) [???????? (Tfng)];
Tagalog;
Taita [Kitaita];
Tajik (Cyrillic) [tg (Cyrl)];
Tamil [?????];
Taroko [trv];
Tatar [?????];
Telugu [??????];
Teso [Kiteso];
Thai [???];
Tibetan [????????];
Tigre [???];
Tigrinya [????];
Tonga [lea fakatonga];
Traditional Chinese [????];
Tsonga [Xitsonga];
Tswana [Setswana];
Turkish [Türkçe];
Tyap [kcg];
Uighur (Arabic) [ug (Arab)];
Ukrainian [??????????];
Urdu [??????];
Uzbek (Arabic) [??????? (????)?];
Uzbek (Cyrillic) [????? (?????)];
Uzbek (Latin) [o'zbekcha (Lotin)];
Venda [Tshiven?a];
Vietnamese [Ti?ng Vi?t];
Vunjo [Kyivunjo];
Walamo [?????];
Welsh [Cymraeg];
Wolof (Latin) [wo (Latn)];
Xhosa [isiXhosa];
Yoruba [Èdè Yorùbá];
Zulu [isiZulu]

Locale IDs can be found in:

http://www.localeplanet.com/icu/

Steps to follow

Step 1 : Need to find which all Languages supported on Android

Sol - follow my above answer ie in cldr-1-8 Languages.

Step 2 : Since cldr-1-8 Languages does not give u Locale short form which is need to be found for desire language Sol - Once language is available in cldr-1-8 Languages list then check for the shortform in http://www.localeplanet.com/icu/ link

Example :For language Hindi [??????] (1)we need to search its present in cldr-1-8 language then (2)search for Hindi in http://www.localeplanet.com/icu/ for Locale id its comes out to be http://www.localeplanet.com/icu/hi/index.html this link and see Locale id from it .

Programmatically set TextBlock Foreground Color

Foreground needs a Brush, so you can use

textBlock.Foreground = Brushes.Navy;

If you want to use the color from RGB or ARGB then

textBlock.Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(100, 255, 125, 35)); 

or

textBlock.Foreground = new System.Windows.Media.SolidColorBrush(Colors.Navy); 

To get the Color from Hex

textBlock.Foreground = new System.Windows.Media.SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFDFD991")); 

How to convert object array to string array in Java

Another alternative to System.arraycopy:

String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);

Max size of URL parameters in _GET

See What is the maximum length of a URL in different browsers?

The length of the url can't be changed in PHP. The linked question is about the URL size limit, you will find what you want.

Can .NET load and parse a properties file equivalent to Java Properties class?

I realize that this isn't exactly what you're asking, but just in case:

When you want to load an actual Java properties file, you'll need to accomodate its encoding. The Java docs indicate that the encoding is ISO 8859-1, which contains some escape sequences that you might not correctly interpret. For instance look at this SO answer to see what's necessary to turn UTF-8 into ISO 8859-1 (and vice versa)

When we needed to do this, we found an open-source PropertyFile.cs and made a few changes to support the escape sequences. This class is a good one for read/write scenarios. You'll need the supporting PropertyFileIterator.cs class as well.

Even if you're not loading true Java properties, make sure that your prop file can express all the characters you need to save (UTF-8 at least)

Declare a constant array

From Effective Go:

Constants in Go are just that—constant. They are created at compile time, even when defined as locals in functions, and can only be numbers, characters (runes), strings or booleans. Because of the compile-time restriction, the expressions that define them must be constant expressions, evaluatable by the compiler. For instance, 1<<3 is a constant expression, while math.Sin(math.Pi/4) is not because the function call to math.Sin needs to happen at run time.

Slices and arrays are always evaluated during runtime:

var TestSlice = []float32 {.03, .02}
var TestArray = [2]float32 {.03, .02}
var TestArray2 = [...]float32 {.03, .02}

[...] tells the compiler to figure out the length of the array itself. Slices wrap arrays and are easier to work with in most cases. Instead of using constants, just make the variables unaccessible to other packages by using a lower case first letter:

var ThisIsPublic = [2]float32 {.03, .02}
var thisIsPrivate = [2]float32 {.03, .02}

thisIsPrivate is available only in the package it is defined. If you need read access from outside, you can write a simple getter function (see Getters in golang).

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

You are getting AttributeError because you're calling groups on None, which hasn't any methods.

regex.search returning None means the regex couldn't find anything matching the pattern from supplied string.

when using regex, it is nice to check whether a match has been made:

Result = re.search(SearchStr, htmlString)

if Result:
    print Result.groups()

pass parameter by link_to ruby on rails

The above did not work for me but this did

<%= link_to "text_to_show_in_url", action_controller_path(:gender => "male", :param2=> "something_else") %>

How to get the current plugin directory in WordPress?

This will actually get the result you want:

<?php plugin_dir_url(__FILE__); ?>

http://codex.wordpress.org/Function_Reference/plugin_dir_url

How do I find the length/number of items present for an array?

Do you mean how long is the array itself, or how many customerids are in it?

Because the answer to the first question is easy: 5 (or if you don't want to hard-code it, Ben Stott's answer).

But the answer to the other question cannot be automatically determined. Presumably you have allocated an array of length 5, but will initially have 0 customer IDs in there, and will put them in one at a time, and your question is, "how many customer IDs have I put into the array?"

C can't tell you this. You will need to keep a separate variable, int numCustIds (for example). Every time you put a customer ID into the array, increment that variable. Then you can tell how many you have put in.

How to write multiple conditions of if-statement in Robot Framework

You should use small caps "or" and "and" instead of OR and AND.

And beware also the spaces/tabs between keywords and arguments (you need at least two spaces).

Here is a code sample with your three keywords working fine:

Here is the file ts.txt:

  *** test cases ***
  mytest
    ${color} =  set variable  Red
    Run Keyword If  '${color}' == 'Red'  log to console  \nexecuted with single condition
    Run Keyword If  '${color}' == 'Red' or '${color}' == 'Blue' or '${color}' == 'Pink'  log to console  \nexecuted with multiple or

    ${color} =  set variable  Blue
    ${Size} =  set variable  Small
    ${Simple} =  set variable  Simple
    ${Design} =  set variable  Simple
    Run Keyword If  '${color}' == 'Blue' and '${Size}' == 'Small' and '${Design}' != '${Simple}'  log to console  \nexecuted with multiple and

    ${Size} =  set variable  XL
    ${Design} =  set variable  Complicated
    Run Keyword Unless  '${color}' == 'Black' or '${Size}' == 'Small' or '${Design}' == 'Simple'  log to console  \nexecuted with unless and multiple or

and here is what I get when I execute it:

$ pybot ts.txt
==============================================================================
Ts
==============================================================================
mytest                                                                .
executed with single condition
executed with multiple or
executed with unless and multiple or
mytest                                                                | PASS |
------------------------------------------------------------------------------

How to convert minutes to hours/minutes and add various time values together using jQuery?

function parseMinutes(x) {
  hours = Math.floor(x / 60);
  minutes = x % 60;
}

function parseHours(H, M) {
  x = M + H * 60;
}

RecyclerView expand/collapse items

Not saying this is the best approach, but it seems to work for me.

The full code may be found at: Example code at: https://github.com/dbleicher/recyclerview-grid-quickreturn

First off, add the expanded area to your cell/item layout, and make the enclosing cell layout animateLayoutChanges="true". This will ensure that the expand/collapse is animated:

<LinearLayout
    android:id="@+id/llCardBack"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/white"
    android:animateLayoutChanges="true"
    android:padding="4dp"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tvTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center|fill_horizontal"
        android:padding="10dp"
        android:gravity="center"
        android:background="@android:color/holo_green_dark"
        android:text="This is a long title to show wrapping of text in the view."
        android:textColor="@android:color/white"
        android:textSize="16sp" />

    <TextView
        android:id="@+id/tvSubTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center|fill_horizontal"
        android:background="@android:color/holo_purple"
        android:padding="6dp"
        android:text="My subtitle..."
        android:textColor="@android:color/white"
        android:textSize="12sp" />

    <LinearLayout
        android:id="@+id/llExpandArea"
        android:visibility="gone"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="6dp"
            android:text="Item One" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="6dp"
            android:text="Item Two" />

    </LinearLayout>
</LinearLayout>

Then, make your RV Adapter class implement View.OnClickListener so that you can act on the item being clicked. Add an int field to hold the position of the one expanded view, and initialize it to a negative value:

private int expandedPosition = -1;

Finally, implement your ViewHolder, onBindViewHolder() methods and override the onClick() method. You will expand the view in onBindViewHolder if it's position is equal to "expandedPosition", and hide it if not. You set the value of expandedPosition in the onClick listener:

@Override
public void onBindViewHolder(RVAdapter.ViewHolder holder, int position) {

    int colorIndex = randy.nextInt(bgColors.length);
    holder.tvTitle.setText(mDataset.get(position));
    holder.tvTitle.setBackgroundColor(bgColors[colorIndex]);
    holder.tvSubTitle.setBackgroundColor(sbgColors[colorIndex]);

    if (position == expandedPosition) {
        holder.llExpandArea.setVisibility(View.VISIBLE);
    } else {
        holder.llExpandArea.setVisibility(View.GONE);
    }
}

@Override
public void onClick(View view) {
    ViewHolder holder = (ViewHolder) view.getTag();
    String theString = mDataset.get(holder.getPosition());

    // Check for an expanded view, collapse if you find one
    if (expandedPosition >= 0) {
        int prev = expandedPosition;
        notifyItemChanged(prev);
    }
    // Set the current position to "expanded"
    expandedPosition = holder.getPosition();
    notifyItemChanged(expandedPosition);

    Toast.makeText(mContext, "Clicked: "+theString, Toast.LENGTH_SHORT).show();
}

/**
 * Create a ViewHolder to represent your cell layout
 * and data element structure
 */
public static class ViewHolder extends RecyclerView.ViewHolder {
    TextView tvTitle;
    TextView tvSubTitle;
    LinearLayout llExpandArea;

    public ViewHolder(View itemView) {
        super(itemView);

        tvTitle = (TextView) itemView.findViewById(R.id.tvTitle);
        tvSubTitle = (TextView) itemView.findViewById(R.id.tvSubTitle);
        llExpandArea = (LinearLayout) itemView.findViewById(R.id.llExpandArea);
    }
}

This should expand only one item at a time, using the system-default animation for the layout change. At least it works for me. Hope it helps.

Excel Formula to SUMIF date falls in particular month

Try this instead:

  =SUM(IF(MONTH($A$2:$A$6)=1,$B$2:$B$6,0))

It's an array formula, so you will need to enter it with the Control-Shift-Enter key combination.

Here's how the formula works.

  1. MONTH($A$2:$A$6) creates an array of numeric values of the month for the dates in A2:A6, that is,
    {1, 1, 1, 2, 2}.
  2. Then the comparison {1, 1, 1, 2, 2}= 1 produces the array {TRUE, TRUE, TRUE, FALSE, FALSE}, which comprises the condition for the IF statement.
  3. The IF statement then returns an array of values, with {430, 96, 400.. for the values of the sum ranges where the month value equals 1 and ..0,0} where the month value does not equal 1.
  4. That array {430, 96, 400, 0, 0} is then summed to get the answer you are looking for.

This is essentially equivalent to what the SUMIF and SUMIFs functions do. However, neither of those functions support the kind of calculation you tried to include in the conditional.

It's also possible to drop the IF completely. Since TRUE and FALSE can also be treated as 1 and 0, this formula--=SUM((MONTH($A$2:$A$6)=1)*$B$2:$B$6)--also works.

Heads up: This does not work in Google Spreadsheets

How to display a list inline using Twitter's Bootstrap

This solution works using Bootstrap v2, however in TBS3 the class INLINE. I haven't figured out what is the equivalent class (if there is one) in TBS3.

This gentleman had a pretty good article of the differences between v2 and v3.

http://mattduchek.com/differences-between-bootstrap-v2-3-and-v3-0/

EDIT - use CSS to target the li elements to solve your problem as below

    { display: inline-block; }

In my situation I was targeting the UL, instead of the LI

    nav ul li { display: inline-block; }

How do I terminate a thread in C++11?

I guess the thread that needs to be killed is either in any kind of waiting mode, or doing some heavy job. I would suggest using a "naive" way.

Define some global boolean:

std::atomic_bool stop_thread_1 = false;

Put the following code (or similar) in several key points, in a way that it will cause all functions in the call stack to return until the thread naturally ends:

if (stop_thread_1)
    return;

Then to stop the thread from another (main) thread:

stop_thread_1 = true;
thread1.join ();
stop_thread_1 = false; //(for next time. this can be when starting the thread instead)

vertical-align: middle with Bootstrap 2

Try this:

.row > .span3 {
    display: inline-block !important;
    vertical-align: middle !important;
}

Edit:

Fiddle: http://jsfiddle.net/EexYE/

You may need to add Diego's float: none !important; also if span3 is floating and it interferes.

Edit:

Fiddle: http://jsfiddle.net/D8McR/

In response to Alberto: if you fix the height of the row div, then to continue the vertical center alignment you'll need to set the line-height of the row to be the same as the pixel height of the row (ie. both to 300px in your case). If you'll do that you will notice that the child elements inherit the line-height, which is a problem in this case, so you will then need to set your line height for the span3s to whatever it should actually be (1.5 is the example value in the fiddle, or 1.5 x the font-size, which we did not change when we changed the line-height).

Passing an array of data as an input parameter to an Oracle procedure

If the types of the parameters are all the same (varchar2 for example), you can have a package like this which will do the following:

CREATE OR REPLACE PACKAGE testuser.test_pkg IS

   TYPE assoc_array_varchar2_t IS TABLE OF VARCHAR2(4000) INDEX BY BINARY_INTEGER;

   PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t);

END test_pkg;

CREATE OR REPLACE PACKAGE BODY testuser.test_pkg IS

   PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t) AS
   BEGIN
      FOR i IN p_parm.first .. p_parm.last
      LOOP
         dbms_output.put_line(p_parm(i));
      END LOOP;

   END;

END test_pkg;

Then, to call it you'd need to set up the array and pass it:

DECLARE
  l_array testuser.test_pkg.assoc_array_varchar2_t;
BEGIN
  l_array(0) := 'hello';
  l_array(1) := 'there';  

  testuser.test_pkg.your_proc(l_array);
END;
/

php multidimensional array get values

For people who searched for php multidimensional array get values and actually want to solve problem comes from getting one column value from a 2 dimensinal array (like me!), here's a much elegant way than using foreach, which is array_column

For example, if I only want to get hotel_name from the below array, and form to another array:

$hotels = [
    [
        'hotel_name' => 'Hotel A',
        'info' => 'Hotel A Info',
    ],
    [
        'hotel_name' => 'Hotel B',
        'info' => 'Hotel B Info',
    ]
];

I can do this using array_column:

$hotel_name = array_column($hotels, 'hotel_name');

print_r($hotel_name); // Which will give me ['Hotel A', 'Hotel B']

For the actual answer for this question, it can also be beautified by array_column and call_user_func_array('array_merge', $twoDimensionalArray);

Let's make the data in PHP:

$hotels = [
    [
        'hotel_name' => 'Hotel A',
        'info' => 'Hotel A Info',
        'rooms' => [
            [
                'room_name' => 'Luxury Room',
                'bed' => 2,
                'boards' => [
                    'board_id' => 1,
                    'price' => 200
                ]
            ],
            [
                'room_name' => 'Non Luxy Room',
                'bed' => 4,
                'boards' => [
                    'board_id' => 2,
                    'price' => 150
                ]
            ],
        ]
    ],
    [
        'hotel_name' => 'Hotel B',
        'info' => 'Hotel B Info',
        'rooms' => [
            [
                'room_name' => 'Luxury Room',
                'bed' => 2,
                'boards' => [
                    'board_id' => 3,
                    'price' => 900
                ]
            ],
            [
                'room_name' => 'Non Luxy Room',
                'bed' => 4,
                'boards' => [
                    'board_id' => 4,
                    'price' => 300
                ]
            ],
        ]
    ]
];

And here's the calculation:

$rooms = array_column($hotels, 'rooms');
$rooms = call_user_func_array('array_merge', $rooms);
$boards = array_column($rooms, 'boards');

foreach($boards as $board){
    $board_id = $board['board_id'];
    $price = $board['price'];
    echo "Board ID is: ".$board_id." and price is: ".$price . "<br/>";
}

Which will give you the following result:

Board ID is: 1 and price is: 200
Board ID is: 2 and price is: 150
Board ID is: 3 and price is: 900
Board ID is: 4 and price is: 300

Javascript array value is undefined ... how do I test for that

This code works very well

function isUndefined(array, index) {
    return ((String(array[index]) == "undefined") ? "Yes" : "No");
}

How to extract the decision rules from scikit-learn decision-tree?

Thank for the wonderful solution of @paulkerfeld. On top of his solution, for all those who want to have a serialized version of trees, just use tree.threshold, tree.children_left, tree.children_right, tree.feature and tree.value. Since the leaves don't have splits and hence no feature names and children, their placeholder in tree.feature and tree.children_*** are _tree.TREE_UNDEFINED and _tree.TREE_LEAF. Every split is assigned a unique index by depth first search.
Notice that the tree.value is of shape [n, 1, 1]

What is the proper REST response code for a valid request but an empty data?

If it's expected that the resource exists, but it might be empty, I would argue that it might be easier to just get a 200 OK with a representation that indicates that the thing is empty.

So I'd rather have /things return a 200 OK with {"Items": []} than a 204 with nothing at all, because in this way a collection with 0 items can be treated just the same as a collection with one or more item in it.

I'd just leave the 204 No Content for PUTs and DELETEs, where it might be the case that there really is no useful representation.

In the case that /thing/9 really doesn't exist, a 404 is appropriate.

Insert current date into a date column using T-SQL?

UPDATE Table
SET DateColumn=GETDATE()
WHERE UserID=@UserID

If you're inserting into a table, and will always need to put the current date, I would recommend setting GETDATE() as the default value for that column, and don't allow NULLs

Add custom buttons on Slick Carousel

I know this is an old question, but maybe I can be of help to someone, bc this also stumped me until I read the documentation a bit more:

prevArrow string (html|jQuery selector) | object (DOM node|jQuery object) Previous Allows you to select a node or customize the HTML for the "Previous" arrow.

nextArrow string (html|jQuery selector) | object (DOM node|jQuery object) Next Allows you to select a node or customize the HTML for the "Next" arrow.

this is how i changed my buttons.. worked perfectly.

  $('.carousel-content').slick({
      prevArrow:"<img class='a-left control-c prev slick-prev' src='../images/shoe_story/arrow-left.png'>",
      nextArrow:"<img class='a-right control-c next slick-next' src='../images/shoe_story/arrow-right.png'>"
  });

How do I call a dynamically-named method in Javascript?

A simple function to call a function dynamically with parameters:

this.callFunction = this.call_function = function(name) {
    var args = Array.prototype.slice.call(arguments, 1);
    return window[name].call(this, ...args);
};

function sayHello(name, age) {
    console.log('hello ' + name + ', your\'e age is ' + age);
    return some;
}

console.log(call_function('sayHello', 'john', 30)); // hello john, your'e age is 30

How to create a new object instance from a Type

If this is for something that will be called a lot in an application instance, it's a lot faster to compile and cache dynamic code instead of using the activator or ConstructorInfo.Invoke(). Two easy options for dynamic compilation are compiled Linq Expressions or some simple IL opcodes and DynamicMethod. Either way, the difference is huge when you start getting into tight loops or multiple calls.

In what situations would AJAX long/short polling be preferred over HTML5 WebSockets?

One contending technology you've omitted is Server-Sent Events / Event Source. What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet? has a good discussion of all of these. Keep in mind that some of these are easier than others to integrate with on the server side.

running multiple bash commands with subprocess

>>> command = "echo a; echo b"
>>> shlex.split(command);
    ['echo', 'a; echo', 'b']

so, the problem is shlex module do not handle ";"

Can I start the iPhone simulator without "Build and Run"?

For Xcode 7.2

open /Applications/Xcode.app/Contents/Developer/Applications/Simulator.app/Contents/MacOS/Simulator.app

sudo ./Simulator

And adding this path in your profile is the best way.

How can I add a new column and data to a datatable that already contains data?

Try this

> dt.columns.Add("ColumnName", typeof(Give the type you want));
> dt.Rows[give the row no like  or  or any no]["Column name in which you want to add data"] = Value;

one line if statement in php

Use ternary operator:

echo (($test == '') ? $redText : '');
echo $test == '' ? $redText : ''; //removed parenthesis

But in this case you can't use shorter reversed version because it will return bool(true) in first condition.

echo (($test != '') ?: $redText); //this will not work properly for this case

Multiple WHERE clause in Linq

@Theo

The LINQ translator is smart enough to execute:

.Where(r => r.UserName !="XXXX" && r.UsernName !="YYYY")

I've test this in LinqPad ==> YES, Linq translator is smart enough :))

How to check if a service is running on Android?

You can use this (I didn't try this yet, but I hope this works):

if(startService(someIntent) != null) {
    Toast.makeText(getBaseContext(), "Service is already running", Toast.LENGTH_SHORT).show();
}
else {
    Toast.makeText(getBaseContext(), "There is no service running, starting service..", Toast.LENGTH_SHORT).show();
}

The startService method returns a ComponentName object if there is an already running service. If not, null will be returned.

See public abstract ComponentName startService (Intent service).

This is not like checking I think, because it's starting the service, so you can add stopService(someIntent); under the code.

Is there an easy way to add a border to the top and bottom of an Android View?

<shape xmlns:android="http://schemas.android.com/apk/res/android">

<solid android:color="@color/light_grey1" />
<stroke
    android:width="1dip"
    android:color="@color/light_grey1" />

<corners
    android:bottomLeftRadius="0dp"
    android:bottomRightRadius="0dp"
    android:topLeftRadius="5dp"
    android:topRightRadius="5dp" />

    </shape>

How do I detect IE 8 with jQuery?

You can use $.browser to detect the browser name. possible values are :

  • webkit (as of jQuery 1.4)
  • safari (deprecated)
  • opera
  • msie
  • mozilla

or get a boolean flag: $.browser.msie will be true if the browser is MSIE.

as for the version number, if you are only interested in the major release number - you can use parseInt($.browser.version, 10). no need to parse the $.browser.version string yourself.

Anyway, The $.support property is available for detection of support for particular features rather than relying on $.browser.

Javascript can't find element by id?

How will the browser know when to run the code inside script tag? So, to make the code run after the window is loaded completely,

window.onload = doStuff;

function doStuff() {
    var e = document.getElementById("db_info");
    e.innerHTML='Found you';
}

The other alternative is to keep your <script...</script> just before the closing </body> tag.

Tomcat: How to find out running tomcat version

run the following

/usr/local/tomcat/bin/catalina.sh version

its response will be something like:

Using CATALINA_BASE:   /usr/local/tomcat
Using CATALINA_HOME:   /usr/local/tomcat
Using CATALINA_TMPDIR: /var/tmp/
Using JRE_HOME:        /usr
Using CLASSPATH:       /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
Using CATALINA_PID:    /var/catalina.pid
Server version: Apache Tomcat/7.0.30
Server built:   Sep 27 2012 05:13:37
Server number:  7.0.30.0
OS Name:        Linux
OS Version:     2.6.32-504.3.3.el6.x86_64
Architecture:   amd64
JVM Version:    1.7.0_60-b19
JVM Vendor:     Oracle Corporation

Storing Images in DB - Yea or Nay?

If you're not on SQL Server 2008 and you have some solid reasons for putting specific image files in the database, then you could take the "both" approach and use the file system as a temporary cache and use the database as the master repository.

For example, your business logic can check if an image file exists on disc before serving it up, retrieving from the database when necessary. This buys you the capability of multiple web servers and fewer sync issues.

Eclipse interface icons very small on high resolution screen in Windows 8.1

Had same problem, to resolve it, create a shortcut of the launcher, right click > properties > compatibility > tick on 'Override high DPI scaling behaviour' and select System Enhanced from the dropdown as shown on pic below. Relaunch eclipse after changes.

enter image description here

Is there a way to use use text as the background with CSS?

Using pure CSS:

(But use this in rare occasions, because HTML method is PREFERRED WAY).

_x000D_
_x000D_
.container{_x000D_
 position:relative;_x000D_
}_x000D_
.container::before{ _x000D_
 content:"";_x000D_
 width: 100%; height: 100%; position: absolute; background: black; opacity: 0.3; z-index: 1;  top: 0;   left: 0;_x000D_
 background: black;_x000D_
}_x000D_
.container::after{ _x000D_
 content: "Your Text"; position: absolute; top: 0; left: 0; bottom: 0; right: 0; z-index: 3; overflow: hidden; font-size: 2em; color: red;    text-align: center; text-shadow: 0px 0px 5px black; background: #0a0a0a8c; padding: 5px;_x000D_
 animation-name: blinking;_x000D_
 animation-duration: 1s;_x000D_
 animation-iteration-count: infinite;_x000D_
 animation-direction: alternate;_x000D_
}_x000D_
@keyframes blinking {_x000D_
 0% {opacity: 0;}_x000D_
 100% {opacity: 1;}_x000D_
}
_x000D_
<div class="container">here is main content, text , <br/> images and other page details</div>
_x000D_
_x000D_
_x000D_

Redraw datatables after using ajax to refresh the table content?

Use this:

var table = $(selector).dataTables();
table.api().draw(false);

or

var table = $(selector).DataTables();
table.draw(false);

SQL select * from column where year = 2010

T-SQL and others;

select * from t where year(Columnx) = 2010

how to view the contents of a .pem certificate

Use the -printcert command like this:

keytool -printcert -file certificate.pem

How to download file from database/folder using php

You can use html5 tag to download the image directly

<?php
$file = "Bang.png"; //Let say If I put the file name Bang.png
echo "<a href='download.php?nama=".$file."' download>donload</a> ";
?>

For more information, check this link http://www.w3schools.com/tags/att_a_download.asp

in linux terminal, how do I show the folder's last modification date, taking its content into consideration?

If I could, I would vote for the answer by Paulo. I tested it and understood the concept. I can confirm it works. The find command can output many parameters. For example, add the following to the --printf clause:

%a for attributes in the octal format
%n for the file name including a complete path

Example:

find Desktop/ -exec stat \{} --printf="%y %n\n" \; | sort -n -r | head -1
2011-02-14 22:57:39.000000000 +0100 Desktop/new file

Let me raise this question as well: Does the author of this question want to solve his problem using Bash or PHP? That should be specified.

Accessing certain pixel RGB value in openCV

The low-level way would be to access the matrix data directly. In an RGB image (which I believe OpenCV typically stores as BGR), and assuming your cv::Mat variable is called frame, you could get the blue value at location (x, y) (from the top left) this way:

frame.data[frame.channels()*(frame.cols*y + x)];

Likewise, to get B, G, and R:

uchar b = frame.data[frame.channels()*(frame.cols*y + x) + 0];    
uchar g = frame.data[frame.channels()*(frame.cols*y + x) + 1];
uchar r = frame.data[frame.channels()*(frame.cols*y + x) + 2];

Note that this code assumes the stride is equal to the width of the image.

Memory address of an object in C#

There's a better solution if you don't really need the memory address but rather some means of uniquely identifying a managed object:

using System.Runtime.CompilerServices;

public static class Extensions
{
    private static readonly ConditionalWeakTable<object, RefId> _ids = new ConditionalWeakTable<object, RefId>();

    public static Guid GetRefId<T>(this T obj) where T: class
    {
        if (obj == null)
            return default(Guid);

        return _ids.GetOrCreateValue(obj).Id;
    }

    private class RefId
    {
        public Guid Id { get; } = Guid.NewGuid();
    }
}

This is thread safe and uses weak references internally, so you won't have memory leaks.

You can use any key generation means that you like. I'm using Guid.NewGuid() here because it's simple and thread safe.

Update

I went ahead and created a Nuget package Overby.Extensions.Attachments that contains some extension methods for attaching objects to other objects. There's an extension called GetReferenceId() that effectively does what the code in this answer shows.

SQL providerName in web.config

System.Data.SqlClient is the .NET Framework Data Provider for SQL Server. ie .NET library for SQL Server.

I don't know where providerName=SqlServer comes from. Could you be getting this confused with the provider keyword in your connection string? (I know I was :) )

In the web.config you should have the System.Data.SqlClient as the value of the providerName attribute. It is the .NET Framework Data Provider you are using.

<connectionStrings>
   <add 
      name="LocalSqlServer" 
      connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" 
      providerName="System.Data.SqlClient"
   />
</connectionStrings>

See http://msdn.microsoft.com/en-US/library/htw9h4z3(v=VS.80).aspx

how to start the tomcat server in linux?

The command you have typed is /startup.sh, if you have to start a shell script you have to fire the command as shown below:

$ cd /home/mpatil/softwares/apache-tomcat-7.0.47/bin
$ sh startup.sh 
or 
$ ./startup.sh 

Please try that, you also have to go to your tomcat's bin-folder (by using the cd-command) to execute this shell script. In your case this is /home/mpatil/softwares/apache-tomcat-7.0.47/bin.

jQuery.inArray(), how to use it right?

The answer comes from the first paragraph of the documentation check if the results is greater than -1, not if it's true or false.

The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.

Because JavaScript treats 0 as loosely equal to false (i.e. 0 == false, but 0 !== false), if we're checking for the presence of value within array, we need to check if it's not equal to (or greater than) -1.

How to open a new HTML page using jQuery?

If you want to use jQuery, the .load() function is the correct function you are after;

But you are missing the # from the div1 id selector in the example 2)

This should work:

$("#div1").load("file2.html");

Remove android default action bar

You can set it as a no title bar theme in the activity's xml in the AndroidManifest

    <activity 
        android:name=".AnActivity"
        android:label="@string/a_string"
        android:theme="@android:style/Theme.NoTitleBar">
    </activity>

How to access model hasMany Relation with where condition?

//lower for v4 some version

public function videos() {
    $instance =$this->hasMany('Video');
    $instance->getQuery()->where('available','=', 1);
    return $instance
}

//v5

public function videos() {
    return $this->hasMany('Video')->where('available','=', 1);
}

"Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))"

After a sequence of attempts I came into a facile solution. You can try Reinstalling ActiveX plugin for Adobe flashplayer.

How to install pip3 on Windows?

For python3.5.3, pip3 is also installed when you install python. When you install it you may not select the add to path. Then you can find where the pip3 located and add it to path manually.

Github: Can I see the number of downloads for a repo?

11 years later...
Here's a small python3 snippet to retrieve the download count of the last 100 release assets:

import requests

owner = "twbs"
repo = "bootstrap"
h = {"Accept": "application/vnd.github.v3+json"}
u = f"https://api.github.com/repos/{owner}/{repo}/releases?per_page=100"
r = requests.get(u, headers=h).json()
r.reverse() # older tags first
for rel in r:
  if rel['assets']:
    tag = rel['tag_name']
    dls = rel['assets'][0]['download_count']
    pub = rel['published_at']
    print(f"Pub: {pub} | Tag: {tag} | Dls: {dls} ")

Pub: 2013-07-18T00:03:17Z | Tag: v1.2.0 | Dls: 1193 
Pub: 2013-08-19T21:20:59Z | Tag: v3.0.0 | Dls: 387786 
Pub: 2013-10-30T17:07:16Z | Tag: v3.0.1 | Dls: 102278 
Pub: 2013-11-06T21:58:55Z | Tag: v3.0.2 | Dls: 381136 
...
Pub: 2020-12-07T16:24:37Z | Tag: v5.0.0-beta1 | Dls: 93943 

Demo

Value does not fall within the expected range

This might be due to the fact that you are trying to add a ListBoxItem with a same name to the page.

If you want to refresh the content of the listbox with the newly retrieved values you will have to first manually remove the content of the listbox other wise your loop will try to create lb_1 again and add it to the same list.

Look at here for a similar problem that occured Silverlight: Value does not fall within the expected range exception

Cheers,

PHP Fatal Error Failed opening required File

Run php -f /common/configs/config_templates.inc.php to verify the validity of the PHP syntax in the file.

is there a css hack for safari only NOT chrome?

This works:

@media not all and (min-resolution:.001dpcm) { 
  @media {
    /* your code for Safari Desktop & Mobile */
    body {
      background-color: red;
      color: blue;
    }
    /* end */
  }
}

Populating a dictionary using for loops (python)

dicts = {}
keys = range(4)
values = ["Hi", "I", "am", "John"]
for i in keys:
        dicts[i] = values[i]
print(dicts)

alternatively

In [7]: dict(list(enumerate(values)))
Out[7]: {0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}

How can I pass an Integer class correctly by reference?

What you are seeing here is not an overloaded + oparator, but autoboxing behaviour. The Integer class is immutable and your code:

Integer i = 0;
i = i + 1;  

is seen by the compiler (after the autoboxing) as:

Integer i = Integer.valueOf(0);
i = Integer.valueOf(i.intValue() + 1);  

so you are correct in your conclusion that the Integer instance is changed, but not sneakily - it is consistent with the Java language definition :-)

"Active Directory Users and Computers" MMC snap-in for Windows 7?

The commands from WEFX worked for me after I enabled the parent features RemoteServerAdministrationTools, RemoteServerAdministrationTools-Roles, and RemoteServerAdministrationTools-Roles-AD