Programs & Examples On #Parse tree

How to find the size of an int[]?

when u pass any array to some function. u are just passing it's starting address, so for it to work u have to pass it size also for it to work properly. it's the same reason why we pass argc with argv[] in command line arguement.

Neither BindingResult nor plain target object for bean name available as request attr

I worked on this same issue and I am sure I have found out the exact reason for it.

Neither BindingResult nor plain target object for bean name 'command' available as request attribute

If your successView property value (name of jsp page) is the same as your input page name, then second value of ModelAndView constructor must be match with the commandName of the input page.

E.g.

index.jsp

<html>
<body>
    <table>
        <tr><td><a href="Login.html">Login</a></td></tr>
    </table>
</body>
</html>

dispatcher-servlet.xml

<bean id="viewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">

    <property name="prefix">
        <value>/WEB-INF/jsp/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>
<bean id="urlMapping"
    class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="urlMap">
        <map>              
            <entry key="/Login.html">
                <ref bean="userController"/>
            </entry>
        </map>          
    </property>             
</bean>     
 <bean id="userController" class="controller.AddCountryFormController">     
       <property name="commandName"><value>country</value></property>
       <property name="commandClass"><value>controller.Country</value></property>        
       <property name="formView"><value>countryForm</value></property>
       <property name="successView"><value>countryForm</value></property>
   </bean>      

AddCountryFormController.java

package controller;

import javax.servlet.http.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.mvc.SimpleFormController;


public class AddCountryFormController extends SimpleFormController
{

    public AddCountryFormController(){
        setCommandName("Country.class");
    }

    protected ModelAndView onSubmit(HttpServletRequest request,HttpServletResponse response,Object command,BindException errors){

            Country country=(Country)command;

            System.out.println("calling onsubmit method !!!!!");

        return new ModelAndView(getSuccessView(),"country",country);

    }

}

Country.java

package controller;

public class Country
{
    private String countryName;

    public void setCountryName(String value){
        countryName=value;
    }

    public String getCountryName(){
        return countryName;
    }

}

countryForm.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<body>
    <form:form commandName="country" method="POST" >
            <table>
                    <tr><td><form:input path="countryName"/></td></tr>
                    <tr><td><input type="submit" value="Save"/></td></tr>
            </table>
    </form:form>
</body>
<html>

Input page commandName="country" ModelAndView Constructor as return new ModelAndView(getSuccessView(),"country",country); Means inputpage commandName==ModeAndView(,"commandName",)

GIT_DISCOVERY_ACROSS_FILESYSTEM not set

The problem is you are not in the correct directory. A simple fix in Jupyter is to do the following command:

  1. Move to the GitHub directory for your installation
  2. Run the GitHub command

Here is an example command to use in Jupyter:

%%bash
cd /home/ec2-user/ml_volume/GitHub_BMM
git show

Note you need to do the commands in the same cell.

Remove URL parameters without refreshing page

Here is an ES6 one liner which preserves the location hash and does not pollute browser history by using replaceState:

(l=>{window.history.replaceState({},'',l.pathname+l.hash)})(location)

How to downgrade from Internet Explorer 11 to Internet Explorer 10?

Go to installed updates and just uninstall Internet Explorer 11 Windows update. It works for me.

How to set full calendar to a specific start date when it's initialized for the 1st time?

This can be used in v5.3.2 to goto a date after initialization

calendar.gotoDate( '2020-09-12' );

eg on datepicker change

var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
     ...
     initialDate: '2020-09-02',
     ...
});    

$(".date-picker").change(function(){
     var date = $(this).val();
     calendar.gotoDate( date );
});

How to install the current version of Go in Ubuntu Precise

You can also use the update-golang script:

update-golang is a script to easily fetch and install new Golang releases with minimum system intrusion

git clone https://github.com/udhos/update-golang
cd update-golang
sudo ./update-golang.sh

Check list of words in another string

if any(word in 'some one long two phrase three' for word in list_):

"Are you missing an assembly reference?" compile error - Visual Studio

I bumped the answer that pointed me in the right direction, but...

For those who are using Visual C++:

If you need to turn off auto-increment of the version, you can change this value in the "AssemblyInfo.cpp" file (all CLR projects have one). Give it a real version number without the asterisk and it will work the way you want it to.

Just don't forget to implement your own version-control on your assembly!

Convert base class to derived class

No, there's no built-in way to convert a class like you say. The simplest way to do this would be to do what you suggested: create a DerivedClass(BaseClass) constructor. Other options would basically come out to automate the copying of properties from the base to the derived instance, e.g. using reflection.

The code you posted using as will compile, as I'm sure you've seen, but will throw a null reference exception when you run it, because myBaseObject as DerivedClass will evaluate to null, since it's not an instance of DerivedClass.

Select All Rows Using Entity Framework

You can use this code to select all rows :

C# :

var allStudents = [modelname].[tablename].Select(x => x).ToList();

Linux Shell Script For Each File in a Directory Grab the filename and execute a program

find . -type f -name "*.xls" -printf "xls2csv %p %p.csv\n" | bash

bash 4 (recursive)

shopt -s globstar
for xls in /path/**/*.xls
do
  xls2csv "$xls" "${xls%.xls}.csv"
done

React.js: Wrapping one component into another

In addition to Sophie's answer, I also have found a use in sending in child component types, doing something like this:

var ListView = React.createClass({
    render: function() {
        var items = this.props.data.map(function(item) {
            return this.props.delegate({data:item});
        }.bind(this));
        return <ul>{items}</ul>;
    }
});

var ItemDelegate = React.createClass({
    render: function() {
        return <li>{this.props.data}</li>
    }
});

var Wrapper = React.createClass({    
    render: function() {
        return <ListView delegate={ItemDelegate} data={someListOfData} />
    }
});

Mailto on submit button

The full list of possible fields in the html based email-creating form:

  • subject
  • cc
  • bcc
  • body
<form action="mailto:[email protected]" method="GET">
  <input name="subject" type="text" /></br>
  <input name="cc" type="email" /><br />
  <input name="bcc" type="email" /><br />
  <textarea name="body"></textarea><br />
  <input type="submit" value="Send" />
</form>

https://codepen.io/garfunkel61/pen/oYGNGp

Java math function to convert positive int to negative and negative to positive?

Just use the unary minus operator:

int x = 5;
...
x = -x; // Here's the mystery library function - the single character "-"

Java has two minus operators:

  • the familiar arithmetic version (eg 0 - x), and
  • the unary minus operation (used here), which negates the (single) operand

This compiles and works as expected.

Field 'browser' doesn't contain a valid alias configuration

In my case it was a package that was installed as a dependency in package.json with a relative path like this:

"dependencies": {
  ...
  "phoenix_html": "file:../deps/phoenix_html"
},

and imported in js/app.js with import "phoenix_html"

This had worked but after an update of node, npm, etc... it failed with the above error-message.

Changing the import line to import "../../deps/phoenix_html" fixed it.

How to set image in circle in swift

Don't know if this helps anyone but I was struggling with this problem for awhile, none of the answers online helped me. For me the problem was I had different heights and widths set on the image in storyboard. I tried every solution on stack and it turns out it was something as simple as that. Once I set them both to 200 my circle profile image was perfect. This was code then in my VC.

profileImage2.layer.cornerRadius = profileImage2.frame.size.width/2
    profileImage2.clipsToBounds = true

Need to find a max of three numbers in java

Two things: Change the variables x, y, z as int and call the method as Math.max(Math.max(x,y),z) as it accepts two parameters only.

In Summary, change below:

    String x = keyboard.nextLine();
    String y = keyboard.nextLine();
    String z = keyboard.nextLine();
    int max = Math.max(x,y,z);

to

    int x = keyboard.nextInt();
    int y = keyboard.nextInt();
    int z = keyboard.nextInt();
    int max =  Math.max(Math.max(x,y),z);

PHP - If variable is not empty, echo some html code

if($var !== '' && $var !== NULL)
{
   echo $var;
}

Render HTML to an image

You could use PhantomJS, which is a headless webkit (the rendering engine in safari and (up until recently) chrome) driver. You can learn how to do screen capture of pages here. Hope that helps!

Where can I download Spring Framework jars without using Maven?

Please edit to keep this list of mirrors current

I found this maven repo where you could download from directly a zip file containing all the jars you need.

Alternate solution: Maven

The solution I prefer is using Maven, it is easy and you don't have to download each jar alone. You can do it with the following steps:

  1. Create an empty folder anywhere with any name you prefer, for example spring-source

  2. Create a new file named pom.xml

  3. Copy the xml below into this file

  4. Open the spring-source folder in your console

  5. Run mvn install

  6. After download finished, you'll find spring jars in /spring-source/target/dependencies

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>spring-source-download</groupId>
      <artifactId>SpringDependencies</artifactId>
      <version>1.0</version>
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
      <dependencies>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>3.2.4.RELEASE</version>
        </dependency>
      </dependencies>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.8</version>
            <executions>
              <execution>
                <id>download-dependencies</id>
                <phase>generate-resources</phase>
                <goals>
                  <goal>copy-dependencies</goal>
                </goals>
                <configuration>
                  <outputDirectory>${project.build.directory}/dependencies</outputDirectory>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </project>
    

Also, if you need to download any other spring project, just copy the dependency configuration from its corresponding web page.

For example, if you want to download Spring Web Flow jars, go to its web page, and add its dependency configuration to the pom.xml dependencies, then run mvn install again.

<dependency>
  <groupId>org.springframework.webflow</groupId>
  <artifactId>spring-webflow</artifactId>
  <version>2.3.2.RELEASE</version>
</dependency>

How do I seed a random class to avoid getting duplicate random values

A good seed generation for me is:

Random rand = new Random(Guid.NewGuid().GetHashCode());

It is very random. The seed is always different because the seed is also random generated.

How do I check whether an array contains a string in TypeScript?

If your code is ES7 based (or upper versions):

channelArray.includes('three'); //will return true or false

If not, for example you are using IE with no babel transpile:

channelArray.indexOf('three') !== -1; //will return true or false

the indexOf method will return the position the element has into the array, because of that we use !== different from -1 if the needle is found at the first position.

Using JQuery hover with HTML image map

You should check out this plugin:

https://github.com/kemayo/maphilight

and the demo:

http://davidlynch.org/js/maphilight/docs/demo_usa.html

if anything, you might be able to borrow some code from it to fix yours.

Datanode process not running in Hadoop

Try this

  1. stop-all.sh
  2. vi hdfs-site.xml
  3. change the value given for property dfs.data.dir
  4. format namenode
  5. start-all.sh

With ' N ' no of nodes, how many different Binary and Binary Search Trees possible?

binary tree :

No need to consider values, we need to look at the structrue.

Given by (2 power n) - n

Eg: for three nodes it is (2 power 3) -3 = 8-3 = 5 different structrues

binary search tree:

We need to consider even the node values. We call it as Catalan Number

Given by 2n C n / n+1

Which is fastest? SELECT SQL_CALC_FOUND_ROWS FROM `table`, or SELECT COUNT(*)

According to the following article: https://www.percona.com/blog/2007/08/28/to-sql_calc_found_rows-or-not-to-sql_calc_found_rows/

If you have an INDEX on your where clause (if id is indexed in your case), then it is better not to use SQL_CALC_FOUND_ROWS and use 2 queries instead, but if you don't have an index on what you put in your where clause (id in your case) then using SQL_CALC_FOUND_ROWS is more efficient.

How to develop Desktop Apps using HTML/CSS/JavaScript?

It seems the solutions for HTML/JS/CSS desktop apps are in no short supply.

One solution I have just come across is TideSDK: http://www.tidesdk.org/, which seems very promising, looking at the documentation.

You can develop with Python, PHP or Ruby, and package it for Mac, Windows or Linux.

Tomcat - maxThreads vs maxConnections

From Tomcat documentation, For blocking I/O (BIO), the default value of maxConnections is the value of maxThreads unless Executor (thread pool) is used in which case, the value of 'maxThreads' from Executor will be used instead. For Non-blocking IO, it doesn't seem to be dependent on maxThreads.

How do you switch pages in Xamarin.Forms?

In App.Xaml.Cs:

MainPage = new NavigationPage( new YourPage());

When you wish to navigate from YourPage to the next page you do:

await Navigation.PushAsync(new YourSecondPage());

You can read more about Xamarin Forms navigation here: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/navigation/hierarchical

Microsoft has quite good docs on this.

There is also the newer concept of the Shell. It allows for a new way of structuring your application and simplifies navigation in some cases.

Intro: https://devblogs.microsoft.com/xamarin/shell-xamarin-forms-4-0-getting-started/

Video on basics of Shell: https://www.youtube.com/watch?v=0y1bUAcOjZY&t=3112s

Docs: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/shell/

Javascript one line If...else...else if statement

You can chain as much conditions as you want. If you do:

var x = (false)?("1true"):((true)?"2true":"2false");

You will get x="2true"

So it could be expressed as:

var variable = (condition) ? (true block) : ((condition)?(true block):(false block))

How do I auto size columns through the Excel interop objects?

Have a look at this article, it's not an exact match to your problem, but suits it:

jQuery, get ID of each element in a class using .each?

patrick dw's answer is right on.

For kicks and giggles I thought I would post a simple way to return an array of all the IDs.

var arrayOfIds = $.map($(".myClassName"), function(n, i){
  return n.id;
});
alert(arrayOfIds);

Does JavaScript pass by reference?

My two cents.... It's irrelevant whether JavaScript passes parameters by reference or value. What really matters is assignment vs. mutation.

I wrote a longer, more detailed explanation in this link.

When you pass anything (whether that be an object or a primitive), all JavaScript does is assign a new variable while inside the function... just like using the equal sign (=).

How that parameter behaves inside the function is exactly the same as it would behave if you just assigned a new variable using the equal sign... Take these simple examples.

_x000D_
_x000D_
var myString = 'Test string 1';

// Assignment - A link to the same place as myString
var sameString = myString;

// If I change sameString, it will not modify myString,
// it just re-assigns it to a whole new string
sameString = 'New string';

console.log(myString); // Logs 'Test string 1';
console.log(sameString); // Logs 'New string';
_x000D_
_x000D_
_x000D_

If I were to pass myString as a parameter to a function, it behaves as if I simply assigned it to a new variable. Now, let's do the same thing, but with a function instead of a simple assignment

_x000D_
_x000D_
function myFunc(sameString) {

  // Reassignment... Again, it will not modify myString
  sameString = 'New string';
}

var myString = 'Test string 1';

// This behaves the same as if we said sameString = myString
myFunc(myString);

console.log(myString); // Again, logs 'Test string 1';
_x000D_
_x000D_
_x000D_

The only reason that you can modify objects when you pass them to a function is because you are not reassigning... Instead, objects can be changed or mutated.... Again, it works the same way.

var myObject = { name: 'Joe'; }

// Assignment - We simply link to the same object
var sameObject = myObject;

// This time, we can mutate it. So a change to myObject affects sameObject and visa versa
myObject.name = 'Jack';
console.log(sameObject.name); // Logs 'Jack'

sameObject.name = 'Jill';
console.log(myObject.name); // Logs 'Jill'

// If we re-assign it, the link is lost
sameObject = { name: 'Howard' };
console.log(myObject.name); // Logs 'Jill'

If I were to pass myObject as a parameter to a function, it behaves as if I simply assigned it to a new variable. Again, the same thing with the exact same behavior but with a function.

_x000D_
_x000D_
function myFunc(sameObject) {
  // We mutate the object, so the myObject gets the change too... just like before.
  sameObject.name = 'Jill';

  // But, if we re-assign it, the link is lost
  sameObject = {
    name: 'Howard'
  };
}

var myObject = {
  name: 'Joe'
};

// This behaves the same as if we said sameObject = myObject;
myFunc(myObject);
console.log(myObject.name); // Logs 'Jill'
_x000D_
_x000D_
_x000D_

Every time you pass a variable to a function, you are "assigning" to whatever the name of the parameter is, just like if you used the equal = sign.

Always remember that the equals sign = means assignment. And passing a parameter to a function also means assignment. They are the same and the two variables are connected in exactly the same way.

The only time that modifying a variable affects a different variable is when the underlying object is mutated.

There is no point in making a distinction between objects and primitives, because it works the same exact way as if you didn't have a function and just used the equal sign to assign to a new variable.

Best way to parse command-line parameters?

I like sliding over arguments for relatively simple configurations.

var name = ""
var port = 0
var ip = ""
args.sliding(2, 2).toList.collect {
  case Array("--ip", argIP: String) => ip = argIP
  case Array("--port", argPort: String) => port = argPort.toInt
  case Array("--name", argName: String) => name = argName
}

How to disable compiler optimizations in gcc?

To test without copy elision and see you copy/move constructors/operators in action add "-fno-elide-constructors".

Even with no optimizations (-O0 ), GCC and Clang will still do copy elision, which has the effect of skipping copy/move constructors in some cases. See this question for the details about copy elision.

However, in Clang 3.4 it does trigger a bug (an invalid temporary object without calling constructor), which is fixed in 3.5.

PHP: How to handle <![CDATA[ with SimpleXMLElement?

This is working perfect for me.

$content = simplexml_load_string(
    $raw_xml
    , null
    , LIBXML_NOCDATA
);

Cross browser JavaScript (not jQuery...) scroll to top animation

There is actually a pure javascript way to accomplish this without using setTimeout or requestAnimationFrame or jQuery.

In short, find the element in the scrollView that you want to scroll to, and use scrollIntoView

el.scrollIntoView({behavior:"smooth"});

Here is a plunkr.

How to automatically update your docker containers, if base-images are updated

There are a lot of answers here, but none of them suited my needs. I wanted an actual answer to the asker's #1 question. How do I know when an image is updated on hub.docker.com?

The below script can be run daily. On first run, it gets a baseline of the tags and update dates from the HUB registry and saves them locally. From then out, every time it is run it checks the registry for new tags and update dates. Since this changes every time a new image exists, it tells us if the base image has changed. Here is the script:

#!/bin/bash

DATAPATH='/data/docker/updater/data'

if [ ! -d "${DATAPATH}" ]; then
        mkdir "${DATAPATH}";
fi
IMAGES=$(docker ps --format "{{.Image}}")
for IMAGE in $IMAGES; do
        ORIGIMAGE=${IMAGE}
        if [[ "$IMAGE" != *\/* ]]; then
                IMAGE=library/${IMAGE}
        fi
        IMAGE=${IMAGE%%:*}
        echo "Checking ${IMAGE}"
        PARSED=${IMAGE//\//.}
        if [ ! -f "${DATAPATH}/${PARSED}" ]; then
                # File doesn't exist yet, make baseline
                echo "Setting baseline for ${IMAGE}"
                curl -s "https://registry.hub.docker.com/v2/repositories/${IMAGE}/tags/" > "${DATAPATH}/${PARSED}"
        else
                # File does exist, do a compare
                NEW=$(curl -s "https://registry.hub.docker.com/v2/repositories/${IMAGE}/tags/")
                OLD=$(cat "${DATAPATH}/${PARSED}")
                if [[ "${VAR1}" == "${VAR2}" ]]; then
                        echo "Image ${IMAGE} is up to date";
                else
                        echo ${NEW} > "${DATAPATH}/${PARSED}"
                        echo "Image ${IMAGE} needs to be updated";
                        H=`hostname`
                        ssh -i /data/keys/<KEYFILE> <USER>@<REMOTEHOST>.com "{ echo \"MAIL FROM: root@${H}\"; echo \"RCPT TO: <USER>@<EMAILHOST>.com\"; echo \"DATA\"; echo \"Subject: ${H} - ${IMAGE} needs update\"; echo \"\"; echo -e \"\n${IMAGE} needs update.\n\ndocker pull ${ORIGIMAGE}\"; echo \"\"; echo \".\"; echo \"quit\"; sleep 1; } | telnet <SMTPHOST> 25"
                fi

        fi
done;

You will want to alter the DATAPATH variable at the top, and alter the email notification command at the end to suit your needs. For me, I have it SSH into a server on another network where my SMTP is located. But you could easily use the mail command, too.

Now, you also want to check for updated packages inside the containers themselves. This is actually probably more effective than doing a "pull" once your containers are working. Here's the script to pull that off:

#!/bin/bash


function needsUpdates() {
        RESULT=$(docker exec ${1} bash -c ' \
                if [[ -f /etc/apt/sources.list ]]; then \
                grep security /etc/apt/sources.list > /tmp/security.list; \
                apt-get update > /dev/null; \
                apt-get upgrade -oDir::Etc::Sourcelist=/tmp/security.list -s; \
                fi; \
                ')
        RESULT=$(echo $RESULT)
        GOODRESULT="Reading package lists... Building dependency tree... Reading state information... Calculating upgrade... 0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded."
        if [[ "${RESULT}" != "" ]] && [[ "${RESULT}" != "${GOODRESULT}" ]]; then
                return 0
        else
                return 1
        fi
}

function sendEmail() {
        echo "Container ${1} needs security updates";
        H=`hostname`
        ssh -i /data/keys/<KEYFILE> <USRER>@<REMOTEHOST>.com "{ echo \"MAIL FROM: root@${H}\"; echo \"RCPT TO: <USER>@<EMAILHOST>.com\"; echo \"DATA\"; echo \"Subject: ${H} - ${1} container needs security update\"; echo \"\"; echo -e \"\n${1} container needs update.\n\n\"; echo -e \"docker exec ${1} bash -c 'grep security /etc/apt/sources.list > /tmp/security.list; apt-get update > /dev/null; apt-get upgrade -oDir::Etc::Sourcelist=/tmp/security.list -s'\n\n\"; echo \"Remove the -s to run the update\"; echo \"\"; echo \".\"; echo \"quit\"; sleep 1; } | telnet <SMTPHOST> 25"
}

CONTAINERS=$(docker ps --format "{{.Names}}")
for CONTAINER in $CONTAINERS; do
        echo "Checking ${CONTAINER}"
        if needsUpdates $CONTAINER; then
                sendEmail $CONTAINER
        fi
done

Format number to always show 2 decimal places

var quantity = 12;

var import1 = 12.55;

var total = quantity * import1;

var answer = parseFloat(total).toFixed(2);

document.write(answer);

Remove shadow below actionbar

Use:

outLineAmbientShadowColor="@null"

Using any() and all() to check if a list contains one set of values or another

Generally speaking:

all and any are functions that take some iterable and return True, if

  • in the case of all(), no values in the iterable are falsy;
  • in the case of any(), at least one value is truthy.

A value x is falsy iff bool(x) == False. A value x is truthy iff bool(x) == True.

Any non-booleans in the iterable will be fine — bool(x) will coerce any x according to these rules: 0, 0.0, None, [], (), [], set(), and other empty collections will yield False, anything else True. The docstring for bool uses the terms 'true'/'false' for 'truthy'/'falsy', and True/False for the concrete boolean values.


In your specific code samples:

You misunderstood a little bit how these functions work. Hence, the following does something completely not what you thought:

if any(foobars) == big_foobar:

...because any(foobars) would first be evaluated to either True or False, and then that boolean value would be compared to big_foobar, which generally always gives you False (unless big_foobar coincidentally happened to be the same boolean value).

Note: the iterable can be a list, but it can also be a generator/generator expression (˜ lazily evaluated/generated list) or any other iterator.

What you want instead is:

if any(x == big_foobar for x in foobars):

which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars, it compares the item to big_foobar and emits the resulting boolean into the resulting sequence:

tmp = (x == big_foobar for x in foobars)

then any walks over all items in tmp and returns True as soon as it finds the first truthy element. It's as if you did the following:

In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']                                        

In [2]: big_foobar = 'big'                                                                          

In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])        
Out[3]: True

Note: As DSM pointed out, any(x == y for x in xs) is equivalent to y in xs but the latter is more readable, quicker to write and runs faster.

Some examples:

In [1]: any(x > 5 for x in range(4))
Out[1]: False

In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True

In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True

In [4]: all([True, True, True, False, True])
Out[4]: False

See also: http://docs.python.org/2/library/functions.html#all

Prevent text selection after double click

In plain javascript:

element.addEventListener('mousedown', function(e){ e.preventDefault(); }, false);

Or with jQuery:

jQuery(element).mousedown(function(e){ e.preventDefault(); });

Fixed point vs Floating point number

Take the number 123.456789

  • As an integer, this number would be 123
  • As a fixed point (2), this number would be 123.46 (Assuming you rounded it up)
  • As a floating point, this number would be 123.456789

Floating point lets you represent most every number with a great deal of precision. Fixed is less precise, but simpler for the computer..

How to get element value in jQuery

A li doesn't have a value. Only form-related elements such as input, textarea and select have values.

Change background of LinearLayout in Android

1- Select LinearLayout findViewById

LinearLayout llayout =(LinearLayout) findViewById(R.id.llayoutId); 

2- Set color from R.color.colorId

llayout.setBackgroundColor(getResources().getColor(R.color.colorId));

LOAD DATA INFILE Error Code : 13

I have experienced same problem and applied the solutions above.

First of all my test environment are as follows

  • Ubuntu 14.04.3 64bit
  • mysql Ver 14.14 Distrib 5.5.47, for debian-linux-gnu (x86_64) using readline 6.3 (installed by just 'sudo apt-get install ...' command)

My testing results are

i) AppArmor solution only work for /tmp cases.

ii) Following solution works without AppArmor solution. I would like to appreciate Avnish Mehta for his answer.

$ mysql -u root -p --in-file=1
...
mysql> LOAD DATA LOCAL INFILE '/home/hongsoog/study/mysql/member.dat'
    -> INTO TABLE member_table;

Important three points are

  • start mysql client with --in-file=1 option
  • use LOAD DATA LOCAL INFILE instead of LOAD DATA INFILE
  • check all path element have world read permission from the / to data file path. For example, following subpath should be world readable or mysql group readable if INFILE is targeting for '/home/hongsoog/study/mysql/memer.dat'

    • /home
    • /home/hongsoog
    • /home/hongsoog/study/mysql
    • /home/hongsoog/study/mysql/member.data

When you start mysql client WITHOUT "--in-file=1" option and use

LOAD DATA LOCAL INFILE ...
, you will get

ERROR 1148 (42000): The used command is not allowed with this MySQL version


In summary, "--in-file=1" option in mysql client command and "LOAD DATA LOCAL INFILE ..." should go hand in hand.

Hope to helpful to anyone.

How to convert integer to decimal in SQL Server query?

declare @xx int 
set     @xx = 3 
select @xx      
select @xx * 2  -- yields another integer  
select @xx/1    -- same
select @xx/1.0  --yields 6 decimal places 
select @xx/1.00 --       6 
select @xx * 1.0  --     1 decimal place - victory
select @xx * 1.00 --     2         places - hooray 

Also _ inserting an int into a temp_table with like decimal(10,3) _ works ok.

Using import fs from 'fs'

For default exports you should use:

import * as fs from 'fs';

Or in case the module has named exports:

import {fs} from 'fs';

Example:

//module1.js

export function function1() {
  console.log('f1')
}

export function function2() {
  console.log('f2')
}

export default function1;

And then:

import defaultExport, { function1, function2 } from './module1'

defaultExport();  // This calls function1
function1();
function2();

Additionally, you should use Webpack or something similar to be able to use ES6 import

MySQL - Cannot add or update a child row: a foreign key constraint fails

I had faced same issue while creating foreign constraints on table. the simple way of coming out of this issue are first take backup of your parent and child table then truncate child table and again try to make a relation. hope this will solve the problem.

hexadecimal string to byte array in python

provided I understood correctly, you should look for binascii.unhexlify

import binascii
a='45222e'
s=binascii.unhexlify(a)
b=[ord(x) for x in s]

What is the cleanest way to ssh and run multiple commands in Bash?

To match your sample code, you can wrap your commands inside single or double qoutes. For example

ssh blah_server "
  ls
  pwd
"

Apply jQuery datepicker to multiple instances

When adding datepicker at runtime generated input textboxes you have to check if it already contains datepicker then first remove class hasDatepicker then apply datePicker to it.

function convertTxtToDate() {
        $('.dateTxt').each(function () {
            if ($(this).hasClass('hasDatepicker')) {
                $(this).removeClass('hasDatepicker');
            } 
             $(this).datepicker();
        });
    } 

How to detect tableView cell touched or clicked in swift

This worked good for me:

_x000D_
_x000D_
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {_x000D_
        print("section: \(indexPath.section)")_x000D_
        print("row: \(indexPath.row)")_x000D_
    }
_x000D_
_x000D_
_x000D_

The output should be:

section: 0
row: 0

How to config routeProvider and locationProvider in angularJS?

you could try:

<a href="#/controllerone">Controller One</a>||
<a href="#/controllerTwo">Controller Two</a>||
<a href="#/controllerThree">Controller Three</a>

<div>
    <div ng-view=""></div>
</div>

SQL left join vs multiple tables on FROM line?

When you need an outer join the second syntax is not always required:

Oracle:

SELECT a.foo, b.foo
  FROM a, b
 WHERE a.x = b.x(+)

MSSQLServer (although it's been deprecated in 2000 version)/Sybase:

SELECT a.foo, b.foo
  FROM a, b
 WHERE a.x *= b.x

But returning to your question. I don't know the answer, but it is probably related to the fact that a join is more natural (syntactically, at least) than adding an expression to a where clause when you are doing exactly that: joining.

How can I open a URL in Android's web browser from my application?

Within in your try block,paste the following code,Android Intent uses directly the link within the URI(Uniform Resource Identifier) braces in order to identify the location of your link.

You can try this:

Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(myIntent);

How to easily resize/optimize an image size with iOS?

To resize an image I have better (graphical) results by using this function in stead of DrawInRect:

- (UIImage*) reduceImageSize:(UIImage*) pImage newwidth:(float) pWidth
{
    float lScale = pWidth / pImage.size.width;
    CGImageRef cgImage = pImage.CGImage;
    UIImage   *lResult = [UIImage imageWithCGImage:cgImage scale:lScale
                            orientation:UIImageOrientationRight];
    return lResult;
}

Aspect ratio is taken care for automatically

Android video streaming example

I was facing the same problem and found a solution to get the code to work.

The code given in the android-Sdk/samples/android-?/ApiDemos works fine. Copy paste each folder in the android project and then in the MediaPlayerDemo_Video.java put the path of the video you want to stream in the path variable. It is left blank in the code.

The following video stream worked for me: http://www.pocketjourney.com/downloads/pj/video/famous.3gp

I know that RTSP protocol is to be used for streaming, but mediaplayer class supports http for streaming as mentioned in the code.

I googled for the format of the video and found that the video if converted to mp4 or 3gp using Quicktime Pro works fine for streaming.

I tested the final apk on android 2.1. The application dosent work on emulators well. Try it on devices.

I hope this helps..

Download File Using jQuery

If you don't want search engines to index certain files, you can use robots.txt to tell web spiders not to access certain parts of your website.

If you rely only on javascript, then some users who browse without it won't be able to click your links.

How does a ArrayList's contains() method evaluate objects?

The ArrayList uses the equals method implemented in the class (your case Thing class) to do the equals comparison.

Illegal Character when trying to compile java code

The BOM is generated by, say, File.WriteAllText() or StreamWriter when you don't specify an Encoding. The default is to use the UTF8 encoding and generate a BOM. You can tell the java compiler about this with its -encoding command line option.

The path of least resistance is to avoid generating the BOM. Do so by specifying System.Text.Encoding.Default, that will write the file with the characters in the default code page of your operating system and doesn't write a BOM. Use the File.WriteAllText(String, String, Encoding) overload or the StreamWriter(String, Boolean, Encoding) constructor.

Just make sure that the file you create doesn't get compiled by a machine in another corner of the world. It will produce mojibake.

Error message: "'chromedriver' executable needs to be available in the path"

Some additional input/clarification for future readers of this thread, to avoid tinkering with the PATH env. variable at the Windows level and restart of the Windows system: (copy of my answer from https://stackoverflow.com/a/49851498/9083077 as applicable to Chrome):

(1) Download chromedriver (as described in this thread earlier) and place the (unzipped) chromedriver.exe at X:\Folder\of\your\choice

(2) Python code sample:

import os;
os.environ["PATH"] += os.pathsep + r'X:\Folder\of\your\choice';

from selenium import webdriver;
browser = webdriver.Chrome();
browser.get('http://localhost:8000')
assert 'Django' in browser.title

Notes: (1) It may take about 5 seconds for the sample code (in the referenced answer) to open up the Firefox browser for the specified url. (2) The python console would show the following error if there's no server already running at the specified url or serving a page with the title containing the string 'Django': assert 'Django' in browser.title AssertionError

What is a stack trace, and how can I use it to debug my application errors?

I am posting this answer so the topmost answer (when sorted by activity) is not one that is just plain wrong.

What is a Stacktrace?

A stacktrace is a very helpful debugging tool. It shows the call stack (meaning, the stack of functions that were called up to that point) at the time an uncaught exception was thrown (or the time the stacktrace was generated manually). This is very useful because it doesn't only show you where the error happened, but also how the program ended up in that place of the code. This leads over to the next question:

What is an Exception?

An Exception is what the runtime environment uses to tell you that an error occurred. Popular examples are NullPointerException, IndexOutOfBoundsException or ArithmeticException. Each of these are caused when you try to do something that is not possible. For example, a NullPointerException will be thrown when you try to dereference a Null-object:

Object a = null;
a.toString();                 //this line throws a NullPointerException

Object[] b = new Object[5];
System.out.println(b[10]);    //this line throws an IndexOutOfBoundsException,
                              //because b is only 5 elements long
int ia = 5;
int ib = 0;
ia = ia/ib;                   //this line throws an  ArithmeticException with the 
                              //message "/ by 0", because you are trying to
                              //divide by 0, which is not possible.

How should I deal with Stacktraces/Exceptions?

At first, find out what is causing the Exception. Try googleing the name of the exception to find out, what is the cause of that exception. Most of the time it will be caused by incorrect code. In the given examples above, all of the exceptions are caused by incorrect code. So for the NullPointerException example you could make sure that a is never null at that time. You could, for example, initialise a or include a check like this one:

if (a!=null) {
    a.toString();
}

This way, the offending line is not executed if a==null. Same goes for the other examples.

Sometimes you can't make sure that you don't get an exception. For example, if you are using a network connection in your program, you cannot stop the computer from loosing it's internet connection (e.g. you can't stop the user from disconnecting the computer's network connection). In this case the network library will probably throw an exception. Now you should catch the exception and handle it. This means, in the example with the network connection, you should try to reopen the connection or notify the user or something like that. Also, whenever you use catch, always catch only the exception you want to catch, do not use broad catch statements like catch (Exception e) that would catch all exceptions. This is very important, because otherwise you might accidentally catch the wrong exception and react in the wrong way.

try {
    Socket x = new Socket("1.1.1.1", 6789);
    x.getInputStream().read()
} catch (IOException e) {
    System.err.println("Connection could not be established, please try again later!")
}

Why should I not use catch (Exception e)?

Let's use a small example to show why you should not just catch all exceptions:

int mult(Integer a,Integer b) {
    try {
        int result = a/b
        return result;
    } catch (Exception e) {
        System.err.println("Error: Division by zero!");
        return 0;
    }
}

What this code is trying to do is to catch the ArithmeticException caused by a possible division by 0. But it also catches a possible NullPointerException that is thrown if a or b are null. This means, you might get a NullPointerException but you'll treat it as an ArithmeticException and probably do the wrong thing. In the best case you still miss that there was a NullPointerException. Stuff like that makes debugging much harder, so don't do that.

TLDR

  1. Figure out what is the cause of the exception and fix it, so that it doesn't throw the exception at all.
  2. If 1. is not possible, catch the specific exception and handle it.

    • Never just add a try/catch and then just ignore the exception! Don't do that!
    • Never use catch (Exception e), always catch specific Exceptions. That will save you a lot of headaches.

When do you use POST and when do you use GET?

Another difference is that POST generally requires two HTTP operations, whereas GET only requires one.

Edit: I should clarify--for common programming patterns. Generally responding to a POST with a straight up HTML web page is a questionable design for a variety of reasons, one of which is the annoying "you must resubmit this form, do you wish to do so?" on pressing the back button.

How to return a list of keys from a Hash Map?

Since Java 8:

List<String> myList = map.keySet().stream().collect(Collectors.toList());

Loading/Downloading image from URL on Swift

class func downloadImageFromUrl(with urlStr: String, andCompletionHandler:@escaping (_ result:Bool) -> Void) {
        guard let url = URL(string: urlStr) else {
            andCompletionHandler(false)
            return
        }
        DispatchQueue.global(qos: .background).async {
            URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) -> Void in
                if error == nil {
                    let httpURLResponse = response as? HTTPURLResponse
                    Utils.print( "status code ID : \(String(describing: httpURLResponse?.statusCode))")
                    if httpURLResponse?.statusCode == 200 {
                        if let data = data {
                            if let image = UIImage(data: data) {
                                ImageCaching.sharedInterface().setImage(image, withID: url.absoluteString as NSString)
                                DispatchQueue.main.async {
                                    andCompletionHandler(true)
                                }
                            }else {
                                andCompletionHandler(false)
                            }
                        }else {
                            andCompletionHandler(false)
                        }
                    }else {
                        andCompletionHandler(false)
                    }
                }else {
                    andCompletionHandler(false)
                }
            }).resume()
        }
    }

I have created a simple class function in my Utils.swift class for calling that method you can simply accesss by classname.methodname and your images are saved in NSCache using ImageCaching.swift class

Utils.downloadImageFromUrl(with: URL, andCompletionHandler: { (isDownloaded) in
                            if isDownloaded {
                                if  let image = ImageCaching.sharedInterface().getImage(URL as NSString) {
                                    self.btnTeam.setBackgroundImage(image, for: .normal)
                                }
                            }else {
                                DispatchQueue.main.async {
                                    self.btnTeam.setBackgroundImage(#imageLiteral(resourceName: "com"), for: .normal)
                                }
                            }
                        })

Happy Codding. Cheers:)

TypeScript Objects as Dictionary types as in C#

Lodash has a simple Dictionary implementation and has good TypeScript support

Install Lodash:

npm install lodash @types/lodash --save

Import and usage:

import { Dictionary } from "lodash";
let properties : Dictionary<string> = {
    "key": "value"        
}
console.log(properties["key"])

Gradle sync failed: failed to find Build Tools revision 24.0.0 rc1

Another thing is that all libraries from google (e.g. support lib, CardView and etc.) should have identical versions

Are arrays passed by value or passed by reference in Java?

Arrays are in fact objects, so a reference is passed (the reference itself is passed by value, confused yet?). Quick example:

// assuming you allocated the list
public void addItem(Integer[] list, int item) {
    list[1] = item;
}

You will see the changes to the list from the calling code. However you can't change the reference itself, since it's passed by value:

// assuming you allocated the list
public void changeArray(Integer[] list) {
    list = null;
}

If you pass a non-null list, it won't be null by the time the method returns.

Python foreach equivalent

Its also interesting to observe this

To iterate over the indices of a sequence, you can combine range() and len() as follows:

a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
  print(i, a[i])

output

0 Mary
1 had
2 a
3 little
4 lamb

Edit#1: Alternate way:

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.

for i, v in enumerate(['tic', 'tac', 'toe']):
  print(i, v)

output

0 tic
1 tac
2 toe

ggplot2, change title size

+ theme(plot.title = element_text(size=22))

Here is the full set of things you can change in element_text:

element_text(family = NULL, face = NULL, colour = NULL, size = NULL,
  hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL,
  color = NULL)

How to get the number of days of difference between two dates on mysql?

Get days between Current date to destination Date

 SELECT DATEDIFF('2019-04-12', CURDATE()) AS days;

output

days

 335

Iterating over every property of an object in javascript using Prototype?

You have to first convert your object literal to a Prototype Hash:

// Store your object literal
var obj = {foo: 1, bar: 2, barobj: {75: true, 76: false, 85: true}}

// Iterate like so.  The $H() construct creates a prototype-extended Hash.
$H(obj).each(function(pair){
  alert(pair.key);
  alert(pair.value);
});

How to send data with angularjs $http.delete() request?

$http.delete method doesn't accept request body. You can try this workaround :

$http( angular.merge({}, config || {}, {
    method  : 'delete',
    url     : _url,
    data    : _data
}));

where in config you can pass config data like headers etc.

Center text in div?

To center horizontally, use text-align:center.

To center vertically, one can only use vertical-align:middle if there is another element in the same row that it is being aligned to.
See it working here.

We use an empty span with a height of 100%, and then put the content in the next element with a vertical-align:middle.

There are other techniques such as using table-cell or putting the content in an absolutely positioned element with top, bottom, left, and right all set to zero, but they all suffer from cross browser compatibility issues.

Get Selected value of a Combobox

If you're dealing with Data Validation lists, you can use the Worksheet_Change event. Right click on the sheet with the data validation and choose View Code. Then type in this:

Private Sub Worksheet_Change(ByVal Target As Range)

    MsgBox Target.Value

End Sub

If you're dealing with ActiveX comboboxes, it's a little more complicated. You need to create a custom class module to hook up the events. First, create a class module named CComboEvent and put this code in it.

Public WithEvents Cbx As MSForms.ComboBox

Private Sub Cbx_Change()

    MsgBox Cbx.Value

End Sub

Next, create another class module named CComboEvents. This will hold all of our CComboEvent instances and keep them in scope. Put this code in CComboEvents.

Private mcolComboEvents As Collection

Private Sub Class_Initialize()
    Set mcolComboEvents = New Collection
End Sub

Private Sub Class_Terminate()
    Set mcolComboEvents = Nothing
End Sub

Public Sub Add(clsComboEvent As CComboEvent)

    mcolComboEvents.Add clsComboEvent, clsComboEvent.Cbx.Name

End Sub

Finally, create a standard module (not a class module). You'll need code to put all of your comboboxes into the class modules. You might put this in an Auto_Open procedure so it happens whenever the workbook is opened, but that's up to you.

You'll need a Public variable to hold an instance of CComboEvents. Making it Public will kepp it, and all of its children, in scope. You need them in scope so that the events are triggered. In the procedure, loop through all of the comboboxes, creating a new CComboEvent instance for each one, and adding that to CComboEvents.

Public gclsComboEvents As CComboEvents

Public Sub AddCombox()

    Dim oleo As OLEObject
    Dim clsComboEvent As CComboEvent

    Set gclsComboEvents = New CComboEvents

    For Each oleo In Sheet1.OLEObjects
        If TypeName(oleo.Object) = "ComboBox" Then
            Set clsComboEvent = New CComboEvent
            Set clsComboEvent.Cbx = oleo.Object
            gclsComboEvents.Add clsComboEvent
        End If
    Next oleo

End Sub

Now, whenever a combobox is changed, the event will fire and, in this example, a message box will show.

You can see an example at https://www.dropbox.com/s/sfj4kyzolfy03qe/ComboboxEvents.xlsm

Uncaught TypeError: Cannot set property 'onclick' of null

Try to put all your <script ...></script> tags before the </body> tag. Perhaps the js is trying to access an object of the DOM before it's built up.

Sort a list of numerical strings in ascending order

in python sorted works like you want with integers:

>>> sorted([10,3,2])
[2, 3, 10]

it looks like you have a problem because you are using strings:

>>> sorted(['10','3','2'])
['10', '2', '3']

(because string ordering starts with the first character, and "1" comes before "2", no matter what characters follow) which can be fixed with key=int

>>> sorted(['10','3','2'], key=int)
['2', '3', '10']

which converts the values to integers during the sort (it is called as a function - int('10') returns the integer 10)

and as suggested in the comments, you can also sort the list itself, rather than generating a new one:

>>> l = ['10','3','2']
>>> l.sort(key=int)
>>> l
['2', '3', '10']

but i would look into why you have strings at all. you should be able to save and retrieve integers. it looks like you are saving a string when you should be saving an int? (sqlite is unusual amongst databases, in that it kind-of stores data in the same type as it is given, even if the table column type is different).

and once you start saving integers, you can also get the list back sorted from sqlite by adding order by ... to the sql command:

select temperature from temperatures order by temperature;

How do I call a non-static method from a static method in C#?

Apologized to post answer for very old thread but i believe my answer may help other.

With the help of delegate the same thing can be achieved.

public class MyClass
{
    private static Action NonStaticDelegate;

    public void NonStaticMethod()
    {
        Console.WriteLine("Non-Static!");
    }

    public static void CaptureDelegate()
    {
        MyClass temp = new MyClass();
        MyClass.NonStaticDelegate = new Action(temp.NonStaticMethod);
    }

    public static void RunNonStaticMethod()
    {
        if (MyClass.NonStaticDelegate != null)
        {
            // This will run the non-static method.
            //  Note that you still needed to create an instance beforehand
            MyClass.NonStaticDelegate();
        }
    }
}

hasNext in Python iterators?

Try the __length_hint__() method from any iterator object:

iter(...).__length_hint__() > 0

Android layout replacing a view with another view on run time

it work in my case, oldSensor and newSnsor - oldView and newView:

private void replaceSensors(View oldSensor, View newSensor) {
            ViewGroup parent = (ViewGroup) oldSensor.getParent();

            if (parent == null) {
                return;
            }

            int indexOldSensor = parent.indexOfChild(oldSensor);
            int indexNewSensor = parent.indexOfChild(newSensor);
            parent.removeView(oldSensor);
            parent.addView(oldSensor, indexNewSensor);
            parent.removeView(newSensor);
            parent.addView(newSensor, indexOldSensor);
        }

How to set cellpadding and cellspacing in table with CSS?

Here is the solution.

The HTML:

<table cellspacing="0" cellpadding="0">
    <tr>
        <td>
            123
        </td>
    </tr>
</table>

The CSS:

table { 
      border-spacing:0; 
      border-collapse:collapse;   
    }

Hope this helps.

EDIT

td, th {padding:0}

ASP.NET Temporary files cleanup

Yes, it's safe to delete these, although it may force a dynamic recompilation of any .NET applications you run on the server.

For background, see the Understanding ASP.NET dynamic compilation article on MSDN.

How to test an SQL Update statement before running it?

Autocommit OFF ...

MySQL

set autocommit=0;

It sets the autommit off for the current session.

You execute your statement, see what it has changed, and then rollback if it's wrong or commit if it's what you expected !

EDIT: The benefit of using transactions instead of running select query is that you can check the resulting set easierly.

Parse query string into an array

For this specific question the chosen answer is correct but if there is a redundant parameter—like an extra "e"—in the URL the function will silently fail without an error or exception being thrown:

a=2&b=2&c=5&d=4&e=1&e=2&e=3 

So I prefer using my own parser like so:

//$_SERVER['QUERY_STRING'] = `a=2&b=2&c=5&d=4&e=100&e=200&e=300` 

$url_qry_str  = explode('&', $_SERVER['QUERY_STRING']);

//arrays that will hold the values from the url
$a_arr = $b_arr = $c_arr = $d_arr = $e_arr =  array();

foreach( $url_qry_str as $param )
    {
      $var =  explode('=', $param, 2);
      if($var[0]=="a")      $a_arr[]=$var[1];
      if($var[0]=="b")      $b_arr[]=$var[1];
      if($var[0]=="c")      $c_arr[]=$var[1];
      if($var[0]=="d")      $d_arr[]=$var[1];
      if($var[0]=="e")      $e_arr[]=$var[1];
    }

    var_dump($e_arr); 
    // will return :
    //array(3) { [0]=> string(1) "100" [1]=> string(1) "200" [2]=> string(1) "300" } 

Now you have all the occurrences of each parameter in its own array, you can always merge them into one array if you want to.

Hope that helps!

Android Facebook style slide

I'm going to make some bold guesses here...

I assume they have a layout that represents the menu that is not visible. When the menu button is tapped, they animate the layout/view on top to move out of the way, and simply enable the visibility of the menu layout. I have not thought about this causing any sort of z-index issues in the views, or how they control that.

Making a POST call instead of GET using urllib2

it should be sending a POST if you provide a data parameter (like you are doing):

from the docs: "the HTTP request will be a POST instead of a GET when the data parameter is provided"

so.. add some debug output to see what's up from the client side.

you can modify your code to this and try again:

import urllib
import urllib2

url = 'http://myserver/post_service'
opener = urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1))
data = urllib.urlencode({'name' : 'joe',
                         'age'  : '10'})
content = opener.open(url, data=data).read()

CSS media query to target only iOS devices

As mentioned above, the short answer is no. But I'm in need of something similar in the app I'm working on now, yet the areas where the CSS needs to be different are limited to very specific areas of a page.

If you're like me and don't need to serve up an entirely different stylesheet, another option would be to detect a device running iOS in the way described in this question's selected answer: Detect if device is iOS

Once you've detected the iOS device you could add a class to the area you're targeting using Javascript (eg. the document.getElementsByTagName("yourElementHere")[0].setAttribute("class", "iOS-device");, jQuery, PHP or whatever, and style that class accordingly using the pre-existing stylesheet.

.iOS-device {
      style-you-want-to-set: yada;
}

Find the line number where a specific word appears with "grep"

You can call tail +[line number] [file] and pipe it to grep -n which shows the line number:

tail +[line number] [file] | grep -n /regex/

The only problem with this method is the line numbers reported by grep -n will be [line number] - 1 less than the actual line number in [file].

Case insensitive comparison NSString

An alternative if you want more control than just case insensitivity is:

[someString compare:otherString options:NSCaseInsensitiveSearch];

Numeric search and diacritical insensitivity are two handy options.

C# Syntax - Split String into Array by Comma, Convert To Generic List, and Reverse Order

What your missing here is that .Reverse() is a void method. It's not possible to assign the result of .Reverse() to a variable. You can however alter the order to use Enumerable.Reverse() and get your result

var x = "Tom,Scott,Bob".Split(',').Reverse().ToList<string>()

The difference is that Enumerable.Reverse() returns an IEnumerable<T> instead of being void return

gcc makefile error: "No rule to make target ..."

In my case I had bone-headedly used commas as separators. To use your example I did this:

a.out: vertex.o, edge.o, elist.o, main.o, vlist.o, enode.o, vnode.o
    g++ vertex.o edge.o elist.o main.o vlist.o enode.o vnode.o

Changing it to the equivalent of

a.out: vertex.o edge.o elist.o main.o vlist.o enode.o vnode.o
    g++ vertex.o edge.o elist.o main.o vlist.o enode.o vnode.o

fixed it.

How can I erase all inline styles with javascript and leave only the styles specified in the css style sheet?

$('div').attr('style', '');

or

$('div').removeAttr('style'); (From Andres's Answer)

To make this a little smaller, try this:

$('div[style]').removeAttr('style');

This should speed it up a little because it checks that the divs have the style attribute.

Either way, this might take a little while to process if you have a large amount of divs, so you might want to consider other methods than javascript.

Stored Procedure parameter default value - is this a constant or a variable

It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.

Look at the definition of sys.all_parameters:

default_value sql_variant If has_default_value is 1, the value of this column is the value of the default for the parameter; otherwise, NULL.

That is, whatever the default for a parameter is, it has to fit in that column.


As Alex K pointed out in the comments, you can just do:

CREATE PROCEDURE [dbo].[problemParam] 
    @StartDate INT = NULL,
    @EndDate INT = NULL
AS  
BEGIN
   SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))

provided that NULL isn't intended to be a valid value for @StartDate.


As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE() within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.

Mapping two integers to one, in a unique and deterministic way

Given positive integers A and B, let D = number of digits A has, and E=number of digits B has The result can be a concatenation of D, 0, E, 0, A, and B.

Example: A = 300, B = 12. D = 3, E=2 result = 302030012. This takes advantage of the fact that the only number that starts with 0, is 0,

Pro: Easy to encode, easy to decode, human readable, significant digits can be compared first, potential for compare without calculation, simple error checking.

Cons: Size of results is an issue. But that's ok, why are we storing unbounded integers in a computer anyways.

How to remove multiple deleted files in Git repository

I had this issue of ghost files appearing in my repo after I deleted them and came across this neat command!

git add -A

It's essentially the same as git add -a and git add -u combined, but it's case sensitive. I got it from this awesome link (this link points to the version on archive.org now, because the original has converted to a spam/phishing page as of June 2016)

How to increase dbms_output buffer?

When buffer size gets full. There are several options you can try:

1) Increase the size of the DBMS_OUTPUT buffer to 1,000,000

2) Try filtering the data written to the buffer - possibly there is a loop that writes to DBMS_OUTPUT and you do not need this data.

3) Call ENABLE at various checkpoints within your code. Each call will clear the buffer.

DBMS_OUTPUT.ENABLE(NULL) will default to 20000 for backwards compatibility Oracle documentation on dbms_output

You can also create your custom output display.something like below snippets

create or replace procedure cust_output(input_string in varchar2 )
is 

   out_string_in long default in_string; 
   string_lenth number; 
   loop_count number default 0; 

begin 

   str_len := length(out_string_in);

   while loop_count < str_len
   loop 
      dbms_output.put_line( substr( out_string_in, loop_count +1, 255 ) ); 
      loop_count := loop_count +255; 
   end loop; 
end;

Link -Ref :Alternative to dbms_output.putline @ By: Alexander

Python: Open file in zip without temporarily extracting it

import io, pygame, zipfile
archive = zipfile.ZipFile('images.zip', 'r')

# read bytes from archive
img_data = archive.read('img_01.png')

# create a pygame-compatible file-like object from the bytes
bytes_io = io.BytesIO(img_data)

img = pygame.image.load(bytes_io)

I was trying to figure this out for myself just now and thought this might be useful for anyone who comes across this question in the future.

How to convert a string or integer to binary in Ruby?

Picking up on bta's lookup table idea, you can create the lookup table with a block. Values get generated when they are first accessed and stored for later:

>> lookup_table = Hash.new { |h, i| h[i] = i.to_s(2) }
=> {}
>> lookup_table[1]
=> "1"
>> lookup_table[2]
=> "10"
>> lookup_table[20]
=> "10100"
>> lookup_table[200]
=> "11001000"
>> lookup_table
=> {1=>"1", 200=>"11001000", 2=>"10", 20=>"10100"}

How to generate a number of most distinctive colors in R?

Here are a few options:

  1. Have a look at the palette function:

     palette(rainbow(6))     # six color rainbow
     (palette(gray(seq(0,.9,len = 25)))) #grey scale
    
  2. And the colorRampPalette function:

     ##Move from blue to red in four colours
     colorRampPalette(c("blue", "red"))( 4) 
    
  3. Look at the RColorBrewer package (and website). If you want diverging colours, then select diverging on the site. For example,

     library(RColorBrewer)
     brewer.pal(7, "BrBG")
    
  4. The I want hue web site gives lots of nice palettes. Again, just select the palette that you need. For example, you can get the rgb colours from the site and make your own palette:

     palette(c(rgb(170,93,152, maxColorValue=255),
         rgb(103,143,57, maxColorValue=255),
         rgb(196,95,46, maxColorValue=255),
         rgb(79,134,165, maxColorValue=255),
         rgb(205,71,103, maxColorValue=255),
         rgb(203,77,202, maxColorValue=255),
         rgb(115,113,206, maxColorValue=255)))
    

Convert .pfx to .cer

PFX files are PKCS#12 Personal Information Exchange Syntax Standard bundles. They can include arbitrary number of private keys with accompanying X.509 certificates and a certificate authority chain (set certificates).

If you want to extract client certificates, you can use OpenSSL's PKCS12 tool.

openssl pkcs12 -in input.pfx -out mycerts.crt -nokeys -clcerts

The command above will output certificate(s) in PEM format. The ".crt" file extension is handled by both macOS and Window.

You mention ".cer" extension in the question which is conventionally used for the DER encoded files. A binary encoding. Try the ".crt" file first and if it's not accepted, easy to convert from PEM to DER:

openssl x509 -inform pem -in mycerts.crt -outform der -out mycerts.cer

What is the best way to auto-generate INSERT statements for a SQL Server table?

You can generate INSERT or MERGE statement with this simple and free application I wrote a few years ago:
Data Script Writer (Desktop Application for Windows)

enter image description here Also, I wrote a blog post about these tools recently and approach to leveraging SSDT for a deployment database with data. Find out more:
Script and deploy the data for database from SSDT project

How to get N rows starting from row M from sorted table in T-SQL

        -- *some* implementations may support this syntax (mysql?)
SELECT Id,Value
FROM xxx
ORDER BY Id
LIMIT 2 , 0
   ;

        -- Separate LIMIT, OFFSET
SELECT Id,Value
FROM xxx
ORDER BY Id
LIMIT 2 OFFSET 2
   ;

        -- SQL-2008 syntax
SELECT Id,Value
FROM xxx
ORDER BY Id
OFFSET 4
FETCH NEXT 2 ROWS ONLY
  ;

Convert an integer to an array of digits

You can just do:

char[] digits = string.toCharArray();

And then you can evaluate the chars as integers.

For example:

char[] digits = "12345".toCharArray();
int digit = Character.getNumericValue(digits[0]);
System.out.println(digit); // Prints 1

Print Combining Strings and Numbers

Yes there is. The preferred syntax is to favor str.format over the deprecated % operator.

print "First number is {} and second number is {}".format(first, second)

ReactJS lifecycle method inside a function Component

You can make use of create-react-class module. Official documentation

Of course you must first install it

npm install create-react-class

Here is a working example

import React from "react";
import ReactDOM from "react-dom"
let createReactClass = require('create-react-class')


let Clock = createReactClass({
    getInitialState:function(){
        return {date:new Date()}
    },

    render:function(){
        return (
            <h1>{this.state.date.toLocaleTimeString()}</h1>
        )
    },

    componentDidMount:function(){
        this.timerId = setInterval(()=>this.setState({date:new Date()}),1000)
    },

    componentWillUnmount:function(){
        clearInterval(this.timerId)
    }

})

ReactDOM.render(
    <Clock/>,
    document.getElementById('root')
)

Can we have multiple <tbody> in same <table>?

EDIT: The caption tag belongs to table and thus should only exist once. Do not associate a caption with each tbody element like I did:

<table>
    <caption>First Half of Table (British Dinner)</caption>
    <tbody>
        <tr><th>1</th><td>Fish</td></tr>
        <tr><th>2</th><td>Chips</td></tr>
        <tr><th>3</th><td>Pease</td></tr>
        <tr><th>4</th><td>Gravy</td></tr>
    </tbody>
    <caption>Second Half of Table (Italian Dinner)</caption>
    <tbody>
        <tr><th>5</th><td>Pizza</td></tr>
        <tr><th>6</th><td>Salad</td></tr>
        <tr><th>7</th><td>Oil</td></tr>
        <tr><th>8</th><td>Bread</td></tr>
    </tbody>
</table>

BAD EXAMPLE ABOVE: DO NOT COPY

The above example does not render as you would expect because writing like this indicates a misunderstanding of the caption tag. You would need lots of CSS hacks to make it render correctly because you would be going against standards.

I searched for W3Cs standards on the caption tag but could not find an explicit rule that states there must be only one caption element per table but that is in fact the case.

Returning a boolean value in a JavaScript function

You could simplify this a lot:

  • Check whether one is not empty
  • Check whether they are equal

This will result in this, which will always return a boolean. Your function also should always return a boolean, but you can see it does a little better if you simplify your code:

function validatePassword()
{
   var password = document.getElementById("password");
   var confirm_password = document.getElementById("password_confirm");

   return password.value !== "" && password.value === confirm_password.value;
       //       not empty       and              equal
}

Why do I need an IoC container as opposed to straightforward DI code?

I think most of the value of an IoC is garnered by using DI. Since you are already doing that, the rest of the benefit is incremental.

The value you get will depend on the type of application you are working on:

  • For multi-tenant, the IoC container can take care of some of the infrastructure code for loading different client resources. When you need a component that is client specific, use a custom selector to do handle the logic and don't worry about it from your client code. You can certainly build this yourself but here's an example of how an IoC can help.

  • With many points of extensibility, the IoC can be used to load components from configuration. This is a common thing to build but tools are provided by the container.

  • If you want to use AOP for some cross-cutting concerns, the IoC provides hooks to intercept method invocations. This is less commonly done ad-hoc on projects but the IoC makes it easier.

I've written functionality like this before but if I need any of these features now I would rather use a pre-built and tested tool if it fits my architecture.

As mentioned by others, you can also centrally configure which classes you want to use. Although this can be a good thing, it comes at a cost of misdirection and complication. The core components for most applications aren't replaced much so the trade-off is a little harder to make.

I use an IoC container and appreciate the functionality but have to admit that I've noticed the trade-off: My code becomes more clear at the class level and less clear at the application level (i.e. visualizing control flow).

What is the role of "Flatten" in Keras?

I came across this recently, it certainly helped me understand: https://www.cs.ryerson.ca/~aharley/vis/conv/

So there's an input, a Conv2D, MaxPooling2D etc, the Flatten layers are at the end and show exactly how they are formed and how they go on to define the final classifications (0-9).

How to convert a Scikit-learn dataset to a Pandas dataset?

Manually, you can use pd.DataFrame constructor, giving a numpy array (data) and a list of the names of the columns (columns). To have everything in one DataFrame, you can concatenate the features and the target into one numpy array with np.c_[...] (note the []):

import numpy as np
import pandas as pd
from sklearn.datasets import load_iris

# save load_iris() sklearn dataset to iris
# if you'd like to check dataset type use: type(load_iris())
# if you'd like to view list of attributes use: dir(load_iris())
iris = load_iris()

# np.c_ is the numpy concatenate function
# which is used to concat iris['data'] and iris['target'] arrays 
# for pandas column argument: concat iris['feature_names'] list
# and string list (in this case one string); you can make this anything you'd like..  
# the original dataset would probably call this ['Species']
data1 = pd.DataFrame(data= np.c_[iris['data'], iris['target']],
                     columns= iris['feature_names'] + ['target'])

How to jQuery clone() and change id?

$('#cloneDiv').click(function(){


  // get the last DIV which ID starts with ^= "klon"
  var $div = $('div[id^="klon"]:last');

  // Read the Number from that DIV's ID (i.e: 3 from "klon3")
  // And increment that number by 1
  var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1;

  // Clone it and assign the new ID (i.e: from num 4 to ID "klon4")
  var $klon = $div.clone().prop('id', 'klon'+num );

  // Finally insert $klon wherever you want
  $div.after( $klon.text('klon'+num) );

});
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

How do you stretch an image to fill a <div> while keeping the image's aspect-ratio?

if you working with IMG tag, it's easy.

I made this:

<style>
        #pic{
            height: 400px;
            width: 400px;
        }
        #pic img{
            height: 225px;               
            position: relative;
            margin: 0 auto;
        }
</style>

<div id="pic"><img src="images/menu.png"></div>

$(document).ready(function(){
            $('#pic img').attr({ 'style':'height:25%; display:none; left:100px; top:100px;' })
)}

but i didn't find how to make it work with #pic { background:url(img/menu.png)} Enyone? Thanks

Mapping many-to-many association table with extra column(s)

Since the SERVICE_USER table is not a pure join table, but has additional functional fields (blocked), you must map it as an entity, and decompose the many to many association between User and Service into two OneToMany associations : One User has many UserServices, and one Service has many UserServices.

You haven't shown us the most important part : the mapping and initialization of the relationships between your entities (i.e. the part you have problems with). So I'll show you how it should look like.

If you make the relationships bidirectional, you should thus have

class User {
    @OneToMany(mappedBy = "user")
    private Set<UserService> userServices = new HashSet<UserService>();
}

class UserService {
    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

    @ManyToOne
    @JoinColumn(name = "service_code")
    private Service service;

    @Column(name = "blocked")
    private boolean blocked;
}

class Service {
    @OneToMany(mappedBy = "service")
    private Set<UserService> userServices = new HashSet<UserService>();
}

If you don't put any cascade on your relationships, then you must persist/save all the entities. Although only the owning side of the relationship (here, the UserService side) must be initialized, it's also a good practice to make sure both sides are in coherence.

User user = new User();
Service service = new Service();
UserService userService = new UserService();

user.addUserService(userService);
userService.setUser(user);

service.addUserService(userService);
userService.setService(service);

session.save(user);
session.save(service);
session.save(userService);

Pass in an enum as a method parameter

If you want to pass in the value to use, you have to use the enum type you declared and directly use the supplied value:

public string CreateFile(string id, string name, string description,
              /* --> */  SupportedPermissions supportedPermissions)
{
    file = new File
    {  
        Name = name,
        Id = id,
        Description = description,
        SupportedPermissions = supportedPermissions // <---
    };

    return file.Id;
}

If you instead want to use a fixed value, you don't need any parameter at all. Instead, directly use the enum value. The syntax is similar to a static member of a class:

public string CreateFile(string id, string name, string description) // <---
{
    file = new File
    {  
        Name = name,
        Id = id,
        Description = description,
        SupportedPermissions = SupportedPermissions.basic // <---
    };

    return file.Id;
}

Python: pandas merge multiple dataframes

Look at this pandas three-way joining multiple dataframes on columns

filenames = ['fn1', 'fn2', 'fn3', 'fn4',....]
dfs = [pd.read_csv(filename, index_col=index_col) for filename in filenames)]
dfs[0].join(dfs[1:])

How do I prevent and/or handle a StackOverflowException?

I had a stackoverflow today and i read some of your posts and decided to help out the Garbage Collecter.

I used to have a near infinite loop like this:

    class Foo
    {
        public Foo()
        {
            Go();
        }

        public void Go()
        {
            for (float i = float.MinValue; i < float.MaxValue; i+= 0.000000000000001f)
            {
                byte[] b = new byte[1]; // Causes stackoverflow
            }
        }
    }

Instead let the resource run out of scope like this:

class Foo
{
    public Foo()
    {
        GoHelper();
    }

    public void GoHelper()
    {
        for (float i = float.MinValue; i < float.MaxValue; i+= 0.000000000000001f)
        {
            Go();
        }
    }

    public void Go()
    {
        byte[] b = new byte[1]; // Will get cleaned by GC
    }   // right now
}

It worked for me, hope it helps someone.

Convert Java String to sql.Timestamp

Here's the intended way to convert a String to a Date:

String timestamp = "2011-10-02-18.48.05.123";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd-kk.mm.ss.SSS");
Date parsedDate = df.parse(timestamp);

Admittedly, it only has millisecond resolution, but in all services slower than Twitter, that's all you'll need, especially since most machines don't even track down to the actual nanoseconds.

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value

It looks like you are using entity framework. My solution was to switch all datetime columns to datetime2, and use datetime2 for any new columns, in other words make EF use datetime2 by default. Add this to the OnModelCreating method on your context:

modelBuilder.Properties<DateTime>().Configure(c => c.HasColumnType("datetime2"));

That will get all the DateTime and DateTime? properties on all the entities in your model.

Adding and using header (HTTP) in nginx

You can use upstream headers (named starting with $http_) and additional custom headers. For example:

add_header X-Upstream-01 $http_x_upstream_01;
add_header X-Hdr-01  txt01;

next, go to console and make request with user's header:

curl -H "X-Upstream-01: HEADER1" -I http://localhost:11443/

the response contains X-Hdr-01, seted by server and X-Upstream-01, seted by client:

HTTP/1.1 200 OK
Server: nginx/1.8.0
Date: Mon, 30 Nov 2015 23:54:30 GMT
Content-Type: text/html;charset=UTF-8
Connection: keep-alive
X-Hdr-01: txt01
X-Upstream-01: HEADER1

How to get visitor's location (i.e. country) using geolocation?

See ipdata.co a service I built that is fast and has reliable performance thanks to having 10 global endpoints each able to handle >10,000 requests per second!

This answer uses a 'test' API Key that is very limited and only meant for testing a few calls. Signup for your own Free API Key and get up to 1500 requests daily for development.

This snippet will return the details of your current ip. To lookup other ip addresses, simply append the ip to the https://api.ipdata.co?api-key=test url eg.

https://api.ipdata.co/1.1.1.1?api-key=test

The API also provides an is_eu field indicating whether the user is in an EU country.

_x000D_
_x000D_
$.get("https://api.ipdata.co?api-key=test", function (response) {_x000D_
    $("#response").html(JSON.stringify(response, null, 4));_x000D_
}, "jsonp");
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<pre id="response"></pre>
_x000D_
_x000D_
_x000D_

Here's the fiddle; https://jsfiddle.net/ipdata/6wtf0q4g/922/

I also wrote this detailed analysis of 8 of the best IP Geolocation APIs.

Resize image proportionally with CSS?

You can use object-fit property:

.my-image {
    width: 100px;
    height: 100px;
    object-fit: contain;
}

This will fit image, without changing the proportionally.

Repeat String - Javascript

function repeat(s, n) { var r=""; for (var a=0;a<n;a++) r+=s; return r;}

MySQL error code: 1175 during UPDATE in MySQL Workbench

just type SET SQL_SAFE_UPDATES = 0; before the delete or update and set to 1 again SET SQL_SAFE_UPDATES = 1

Static nested class in Java, why?

Static inner class is used in the builder pattern. Static inner class can instantiate it's outer class which has only private constructor. You can not do the same with the inner class as you need to have object of the outer class created prior to accessing the inner class.

class OuterClass {
    private OuterClass(int x) {
        System.out.println("x: " + x);
    }
    
    static class InnerClass {
        public static void test() {
            OuterClass outer = new OuterClass(1);
        }
    }
}

public class Test {
    public static void main(String[] args) {
        OuterClass.InnerClass.test();
        // OuterClass outer = new OuterClass(1); // It is not possible to create outer instance from outside.
    }
}

This will output x: 1

How to check if a python module exists without importing it

There is no way to reliably check if "dotted module" is importable without importing its parent package. Saying this, there are many solutions to problem "how to check if Python module exists".

Below solution address the problem that imported module can raise ImportError even it exists. We want to distinguish that situation from such in which module does not exist.

Python 2:

import importlib
import pkgutil
import sys

def find_module(full_module_name):
    """
    Returns module object if module `full_module_name` can be imported. 

    Returns None if module does not exist. 

    Exception is raised if (existing) module raises exception during its import.
    """
    module = sys.modules.get(full_module_name)
    if module is None:
        module_path_tail = full_module_name.split('.')
        module_path_head = []
        loader = True
        while module_path_tail and loader:
            module_path_head.append(module_path_tail.pop(0))
            module_name = ".".join(module_path_head)
            loader = bool(pkgutil.find_loader(module_name))
            if not loader:
                # Double check if module realy does not exist
                # (case: full_module_name == 'paste.deploy')
                try:
                    importlib.import_module(module_name)
                except ImportError:
                    pass
                else:
                    loader = True
        if loader:
            module = importlib.import_module(full_module_name)
    return module

Python 3:

import importlib

def find_module(full_module_name):
    """
    Returns module object if module `full_module_name` can be imported. 

    Returns None if module does not exist. 

    Exception is raised if (existing) module raises exception during its import.
    """
    try:
        return importlib.import_module(full_module_name)
    except ImportError as exc:
        if not (full_module_name + '.').startswith(exc.name + '.'):
            raise

Using SED with wildcard

So, the concept of a "wildcard" in Regular Expressions works a bit differently. In order to match "any character" you would use "." The "*" modifier means, match any number of times.

How to get a list of column names on Sqlite3 database?

-(NSMutableDictionary*)tableInfo:(NSString *)table
{
  sqlite3_stmt *sqlStatement;
  NSMutableDictionary *result = [[NSMutableDictionary alloc] init];
  const char *sql = [[NSString stringWithFormat:@"pragma table_info('%s')",[table UTF8String]] UTF8String];
  if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
  {
    NSLog(@"Problem with prepare statement tableInfo %@",[NSString stringWithUTF8String:(const char *)sqlite3_errmsg(db)]);

  }
  while (sqlite3_step(sqlStatement)==SQLITE_ROW)
  {
    [result setObject:@"" forKey:[NSString stringWithUTF8String:(char*)sqlite3_column_text(sqlStatement, 1)]];

  }

  return result;
  }

Is this the proper way to do boolean test in SQL?

PostgreSQL supports boolean types, so your SQL query would work perfectly in PostgreSQL.

How to plot data from multiple two column text files with legends in Matplotlib?

I feel the simplest way would be

 from matplotlib import pyplot;
 from pylab import genfromtxt;  
 mat0 = genfromtxt("data0.txt");
 mat1 = genfromtxt("data1.txt");
 pyplot.plot(mat0[:,0], mat0[:,1], label = "data0");
 pyplot.plot(mat1[:,0], mat1[:,1], label = "data1");
 pyplot.legend();
 pyplot.show();
  1. label is the string that is displayed on the legend
  2. you can plot as many series of data points as possible before show() to plot all of them on the same graph This is the simple way to plot simple graphs. For other options in genfromtxt go to this url.

How to fire an event when v-model changes?

This happens because your click handler fires before the value of the radio button changes. You need to listen to the change event instead:

<input 
  type="radio" 
  name="optionsRadios" 
  id="optionsRadios2" 
  value=""
  v-model="srStatus" 
  v-on:change="foo"> //here

Also, make sure you really want to call foo() on ready... seems like maybe you don't actually want to do that.

ready:function(){
    foo();
},

mongoError: Topology was destroyed

This error is due to mongo driver dropping the connection for any reason (server was down for example).

By default mongoose will try to reconnect for 30 seconds then stop retrying and throw errors forever until restarted.

You can change this by editing these 2 fields in the connection options

mongoose.connect(uri, 
    { server: { 
        // sets how many times to try reconnecting
        reconnectTries: Number.MAX_VALUE,
        // sets the delay between every retry (milliseconds)
        reconnectInterval: 1000 
        } 
    }
);

connection options documentation

Maven compile with multiple src directories

Used the build-helper-maven-plugin from the post - and update src/main/generated. And mvn clean compile works on my ../common/src/main/java, or on ../common, so kept the latter. Then yes, confirming that IntelliJ IDEA (ver 10.5.2) level of the compilation failed as David Phillips mentioned. The issue was that IDEA did not add another source root to the project. Adding it manually solved the issue. It's not nice as editing anything in the project should come from maven and not from direct editing of IDEA's project options. Yet I will be able to live with it until they support build-helper-maven-plugin directly such that it will auto add the sources.

Then needed another workaround to make this work though. Since each time IDEA re-imported maven settings after a pom change me newly added source was kept on module, yet it lost it's Source Folders selections and was useless. So for IDEA - need to set these once:

  • Select - Project Settings / Maven / Importing / keep source and test folders on reimport.
  • Add - Project Structure / Project Settings / Modules / {Module} / Sources / Add Content Root.

Now keeping those folders on import is not the best practice in the world either, ..., but giving it a try.

How to loop through files matching wildcard in batch file

You can use this line to print the contents of your desktop:

FOR %%I in (C:\windows\desktop\*.*) DO echo %%I 

Once you have the %%I variable it's easy to perform a command on it (just replace the word echo with your program)

In addition, substitution of FOR variable references has been enhanced You can now use the following optional syntax:

%~I         - expands %I removing any surrounding quotes (")
%~fI        - expands %I to a fully qualified path name
%~dI        - expands %I to a drive letter only
%~pI        - expands %I to a path only (directory with \)
%~nI        - expands %I to a file name only
%~xI        - expands %I to a file extension only
%~sI        - expanded path contains short names only
%~aI        - expands %I to file attributes of file
%~tI        - expands %I to date/time of file
%~zI        - expands %I to size of file
%~$PATH:I   - searches the directories listed in the PATH
               environment variable and expands %I to the
               fully qualified name of the first one found.
               If the environment variable name is not
               defined or the file is not found by the
               search, then this modifier expands to the
               empty string

https://ss64.com/nt/syntax-args.html

In the above examples %I and PATH can be replaced by other valid values. The %~ syntax is terminated by a valid FOR variable name. Picking upper case variable names like %I makes it more readable and avoids confusion with the modifiers, which are not case sensitive.

You can get the full documentation by typing FOR /?

Use PHP composer to clone git repo

I was encountering the following error: The requested package my-foo/bar could not be found in any version, there may be a typo in the package name.

If you're forking another repo to make your own changes you will end up with a new repository.

E.g:

https://github.com/foo/bar.git
=>
https://github.com/my-foo/bar.git

The new url will need to go into your repositories section of your composer.json.

Remember if you want refer to your fork as my-foo/bar in your require section, you will have to rename the package in the composer.json file inside of your new repo.

{
    "name":         "foo/bar",

=>

{
    "name":         "my-foo/bar",

If you've just forked the easiest way to do this is edit it right inside github.

How to loop over grouped Pandas dataframe?

df.groupby('l_customer_id_i').agg(lambda x: ','.join(x)) does already return a dataframe, so you cannot loop over the groups anymore.

In general:

  • df.groupby(...) returns a GroupBy object (a DataFrameGroupBy or SeriesGroupBy), and with this, you can iterate through the groups (as explained in the docs here). You can do something like:

    grouped = df.groupby('A')
    
    for name, group in grouped:
        ...
    
  • When you apply a function on the groupby, in your example df.groupby(...).agg(...) (but this can also be transform, apply, mean, ...), you combine the result of applying the function to the different groups together in one dataframe (the apply and combine step of the 'split-apply-combine' paradigm of groupby). So the result of this will always be again a DataFrame (or a Series depending on the applied function).

Detect change to ngModel on a select tag (Angular 2)

Update:

Separate the event and property bindings:

<select [ngModel]="selectedItem" (ngModelChange)="onChange($event)">
onChange(newValue) {
    console.log(newValue);
    this.selectedItem = newValue;  // don't forget to update the model here
    // ... do other stuff here ...
}

You could also use

<select [(ngModel)]="selectedItem" (ngModelChange)="onChange($event)">

and then you wouldn't have to update the model in the event handler, but I believe this causes two events to fire, so it is probably less efficient.


Old answer, before they fixed a bug in beta.1:

Create a local template variable and attach a (change) event:

<select [(ngModel)]="selectedItem" #item (change)="onChange(item.value)">

plunker

See also How can I get new selection in "select" in Angular 2?

Communicating between a fragment and an activity - best practices

There is the latest techniques to communicate fragment to activity without any interface follow the steps Step 1- Add the dependency in gradle

implementation 'androidx.fragment:fragment:1.3.0-rc01'

Make a div into a link

This is the best way to do it as used on the BBC website and the Guardian:

I found the technique here: http://codepen.io/IschaGast/pen/Qjxpxo

heres the html

<div class="highlight block-link">
      <h2>I am an example header</h2>
      <p><a href="pageone" class="block-link__overlay-link">This entire box</a> links somewhere, thanks to faux block links. I am some example text with a <a href="pagetwo">custom link</a> that sits within the block</p>

</div>

heres the CSS

/**
 * Block Link
 *
 * A Faux block-level link. Used for when you need a block-level link with
 * clickable areas within it as directly nesting a tags breaks things.
 */


.block-link {
    position: relative;
}

.block-link a {
  position: relative;
  z-index: 1;
}

.block-link .block-link__overlay-link {
    position: static;
    &:before {
      bottom: 0;
      content: "";
      left: 0;
      overflow: hidden;
      position: absolute;
      right: 0;
      top: 0;
      white-space: nowrap;
      z-index: 0;
    }
    &:hover,
    &:focus {
      &:before {
        background: rgba(255,255,0, .2);
      }
    }
}

Storyboard doesn't contain a view controller with identifier

A few of my view controllers were missing the storyboardIdentifier attribute.

Before:

<viewController
    id="pka-il-u5E"
    customClass="YourViewControllerName"
    customModule="ModuleName"
    customModuleProvider="target"
    sceneMemberID="viewController">

After:

<viewController
    storyboardIdentifier="YourViewControllerName"   <----
    id="pka-il-u5E"
    customClass="YourViewControllerName"
    customModule="ModuleName"
    customModuleProvider="target"
    sceneMemberID="viewController">

Find number of decimal places in decimal value regardless of culture

I use the following mechanism in my code

  public static int GetDecimalLength(string tempValue)
    {
        int decimalLength = 0;
        if (tempValue.Contains('.') || tempValue.Contains(','))
        {
            char[] separator = new char[] { '.', ',' };
            string[] tempstring = tempValue.Split(separator);

            decimalLength = tempstring[1].Length;
        }
        return decimalLength;
    }

decimal input=3.376; var instring=input.ToString();

call GetDecimalLength(instring)

How to fix ReferenceError: primordials is not defined in node

What worked for me was to use python2 during npm installation.

> npm install --python=~/venv/bin/python

Ternary operator ?: vs if...else

Just to be a bit left handed...

x ? y : x = value

will assign value to y if x is not 0 (false).

How to Select a substring in Oracle SQL up to a specific character?

To find any sub-string from large string:

string_value:=('This is String,Please search string 'Ple');

Then to find the string 'Ple' from String_value we can do as:

select substr(string_value,instr(string_value,'Ple'),length('Ple')) from dual;

You will find result: Ple

Mime type for WOFF fonts?

For me, the next has beeen working in an .htaccess file.

AddType font/ttf .ttf
AddType font/eot .eot
AddType font/otf .otf
AddType font/woff .woff
AddType font/woff2 .woff2   

Subtracting Number of Days from a Date in PL/SQL

Use sysdate-1 to subtract one day from system date.

select sysdate, sysdate -1 from dual;

Output:

SYSDATE  SYSDATE-1
-------- ---------
22-10-13 21-10-13 

How to catch segmentation fault in Linux?

Here's an example of how to do it in C.

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

void segfault_sigaction(int signal, siginfo_t *si, void *arg)
{
    printf("Caught segfault at address %p\n", si->si_addr);
    exit(0);
}

int main(void)
{
    int *foo = NULL;
    struct sigaction sa;

    memset(&sa, 0, sizeof(struct sigaction));
    sigemptyset(&sa.sa_mask);
    sa.sa_sigaction = segfault_sigaction;
    sa.sa_flags   = SA_SIGINFO;

    sigaction(SIGSEGV, &sa, NULL);

    /* Cause a seg fault */
    *foo = 1;

    return 0;
}

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

The root problem here seems that iOS8 safari won't hide the address bar when scrolling down if the content is equal or less than the viewport.

As you found out already, adding some padding at the bottom gets around this issue:

html {
    /* enough space to scroll up to get fullscreen on iOS8 */
    padding-bottom: 80px;
}
// sort of emulate safari's "bounce back to top" scroll
window.addEventListener('scroll', function(ev) {
    // avoids scrolling when the focused element is e.g. an input
    if (
        !document.activeElement
        || document.activeElement === document.body
    ) {
        document.body.scrollIntoViewIfNeeded(true);
    }
});

The above css should be conditionally applied, for example with UA sniffing adding a gt-ios8 class to <html>.

Is there a "previous sibling" selector?

Another flexbox solution

You can use inverse the order of elements in HTML. Then besides using order as in Michael_B's answer you can use flex-direction: row-reverse; or flex-direction: column-reverse; depending on your layout.

Working sample:

_x000D_
_x000D_
.flex {_x000D_
  display: flex;_x000D_
  flex-direction: row-reverse;_x000D_
   /* Align content at the "reversed" end i.e. beginning */_x000D_
  justify-content: flex-end;_x000D_
}_x000D_
_x000D_
/* On hover target its "previous" elements */_x000D_
.flex-item:hover ~ .flex-item {_x000D_
  background-color: lime;_x000D_
}_x000D_
_x000D_
/* styles just for demo */_x000D_
.flex-item {_x000D_
  background-color: orange;_x000D_
  color: white;_x000D_
  padding: 20px;_x000D_
  font-size: 3rem;_x000D_
  border-radius: 50%;_x000D_
}
_x000D_
<div class="flex">_x000D_
  <div class="flex-item">5</div>_x000D_
  <div class="flex-item">4</div>_x000D_
  <div class="flex-item">3</div>_x000D_
  <div class="flex-item">2</div>_x000D_
  <div class="flex-item">1</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to generate .angular-cli.json file in Angular Cli?

If you copy paste your project the .angular-cli.json you wil not find this file try to create a new file with the same name and add the code and it wil work.

How to use a App.config file in WPF applications?

I have a Class Library WPF Project, and I Use:

'Read Settings
Dim value as string = My.Settings.my_key
value = "new value"

'Write Settings
My.Settings.my_key = value
My.Settings.Save()

Why does sudo change the PATH?

comment out both "Default env_reset" and "Default secure_path ..." in /etc/sudores file works for me

Which UUID version to use?

There are two different ways of generating a UUID.

If you just need a unique ID, you want a version 1 or version 4.

  • Version 1: This generates a unique ID based on a network card MAC address and a timer. These IDs are easy to predict (given one, I might be able to guess another one) and can be traced back to your network card. It's not recommended to create these.

  • Version 4: These are generated from random (or pseudo-random) numbers. If you just need to generate a UUID, this is probably what you want.

If you need to always generate the same UUID from a given name, you want a version 3 or version 5.

  • Version 3: This generates a unique ID from an MD5 hash of a namespace and name. If you need backwards compatibility (with another system that generates UUIDs from names), use this.

  • Version 5: This generates a unique ID from an SHA-1 hash of a namespace and name. This is the preferred version.

Turn ON/OFF Camera LED/flash light in Samsung Galaxy Ace 2.2.1 & Galaxy Tab

I will soon released a new version of my app to support to galaxy ace.

You can download here: https://play.google.com/store/apps/details?id=droid.pr.coolflashlightfree

In order to solve your problem you should do this:

this._camera = Camera.open();     
this._camera.startPreview();
this._camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});

Parameters params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
this._camera.setParameters(params);

params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
this._camera.setParameters(params);

don't worry about FLASH_MODE_OFF because this will keep the light on, strange but it's true

to turn off the led just release the camera

What exactly does += do in python?

According to the documentation

x += y is equivalent to x = operator.iadd(x, y). Another way to put it is to say that z = operator.iadd(x, y) is equivalent to the compound statement z = x; z += y.

So x += 3 is the same as x = x + 3.

x = 2

x += 3

print(x)

will output 5.

Notice that there's also

LINQ query to find if items in a list are contained in another list

List<string> test1 = new List<string> { "@bob.com", "@tom.com" };
List<string> test2 = new List<string> { "[email protected]", "[email protected]", "[email protected]" };

var result = (from t2 in test2
              where test1.Any(t => t2.Contains(t)) == false
              select t2);

If query form is what you want to use, this is legible and more or less as "performant" as this could be.

What i mean is that what you are trying to do is an O(N*M) algorithm, that is, you have to traverse N items and compare them against M values. What you want is to traverse the first list only once, and compare against the other list just as many times as needed (worst case is when the email is valid since it has to compare against every black listed domain).

from t2 in test we loop the email list once.

test1.Any(t => t2.Contains(t)) == false we compare with the blacklist and when we found one match return (hence not comparing against the whole list if is not needed)

select t2 keep the ones that are clean.

So this is what I would use.

Qt Creator color scheme

QTcreator obeys your kde-wide configurations. If you choose "obsidian-coast" as the system-wide color scheme qt creator will be all dark as well. I know it is a partial solution but it works.

What does Maven do, in theory and in practice? When is it worth to use it?

What it does

Maven is a "build management tool", it is for defining how your .java files get compiled to .class, packaged into .jar (or .war or .ear) files, (pre/post)processed with tools, managing your CLASSPATH, and all others sorts of tasks that are required to build your project. It is similar to Apache Ant or Gradle or Makefiles in C/C++, but it attempts to be completely self-contained in it that you shouldn't need any additional tools or scripts by incorporating other common tasks like downloading & installing necessary libraries etc.

It is also designed around the "build portability" theme, so that you don't get issues as having the same code with the same buildscript working on one computer but not on another one (this is a known issue, we have VMs of Windows 98 machines since we couldn't get some of our Delphi applications compiling anywhere else). Because of this, it is also the best way to work on a project between people who use different IDEs since IDE-generated Ant scripts are hard to import into other IDEs, but all IDEs nowadays understand and support Maven (IntelliJ, Eclipse, and NetBeans). Even if you don't end up liking Maven, it ends up being the point of reference for all other modern builds tools.

Why you should use it

There are three things about Maven that are very nice.

  1. Maven will (after you declare which ones you are using) download all the libraries that you use and the libraries that they use for you automatically. This is very nice, and makes dealing with lots of libraries ridiculously easy. This lets you avoid "dependency hell". It is similar to Apache Ant's Ivy.

  2. It uses "Convention over Configuration" so that by default you don't need to define the tasks you want to do. You don't need to write a "compile", "test", "package", or "clean" step like you would have to do in Ant or a Makefile. Just put the files in the places in which Maven expects them and it should work off of the bat.

  3. Maven also has lots of nice plug-ins that you can install that will handle many routine tasks from generating Java classes from an XSD schema using JAXB to measuring test coverage with Cobertura. Just add them to your pom.xml and they will integrate with everything else you want to do.

The initial learning curve is steep, but (nearly) every professional Java developer uses Maven or wishes they did. You should use Maven on every project although don't be surprised if it takes you a while to get used to it and that sometimes you wish you could just do things manually, since learning something new sometimes hurts. However, once you truly get used to Maven you will find that build management takes almost no time at all.

How to Start

The best place to start is "Maven in 5 Minutes". It will get you start with a project ready for you to code in with all the necessary files and folders set-up (yes, I recommend using the quickstart archetype, at least at first).

After you get started you'll want a better understanding over how the tool is intended to be used. For that "Better Builds with Maven" is the most thorough place to understand the guts of how it works, however, "Maven: The Complete Reference" is more up-to-date. Read the first one for understanding, but then use the second one for reference.

How to remove duplicate values from an array in PHP

    if (@!in_array($classified->category,$arr)){        
                                    $arr[] = $classified->category;
                                 ?>

            <?php } endwhile; wp_reset_query(); ?>

first time check value in array and found same value ignore it

How do you remove an array element in a foreach loop?

if you have scenario in which you have to remove more then one values from the foreach array in this case you have to pass value by reference in for each: I try to explain this scenario:

foreach ($manSkuQty as $man_sku => &$man_qty) {

               foreach ($manufacturerSkus as $key1 => $val1) {

  // some processing here and unset first loops entries                     
 //  here dont include again for next iterations
                           if(some condition)
                            unset($manSkuQty[$key1]);

                        }
               }
}

in second loop you want to unset first loops entries dont come again in the iteration for performance purpose or else then unset from memory as well because in memory they present and will come in iterations.

Convert XML String to Object

You can use xsd.exe to create schema bound classes in .Net then XmlSerializer to Deserialize the string : http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.deserialize.aspx

std::thread calling method of class

Not so hard:

#include <thread>

void Test::runMultiThread()
{
    std::thread t1(&Test::calculate, this,  0, 10);
    std::thread t2(&Test::calculate, this, 11, 20);
    t1.join();
    t2.join();
}

If the result of the computation is still needed, use a future instead:

#include <future>

void Test::runMultiThread()
{
     auto f1 = std::async(&Test::calculate, this,  0, 10);
     auto f2 = std::async(&Test::calculate, this, 11, 20);

     auto res1 = f1.get();
     auto res2 = f2.get();
}

How to write text on a image in windows using python opencv2

This is indeed a bit of an annoying problem. For python 2.x.x you use:

cv2.CV_FONT_HERSHEY_SIMPLEX

and for Python 3.x.x:

cv2.FONT_HERSHEY_SIMPLEX

I recommend using a autocomplete environment(pyscripter or scipy for example). If you lookup example code, make sure they use the same version of Python(if they don't make sure you change the code).

How do you uninstall all dependencies listed in package.json (NPM)?

  1. remove unwanted dependencies from package.json
  2. npm i

"npm i" will not only install missing deps, it updates node_modules to match the package.json

I need to learn Web Services in Java. What are the different types in it?

  1. SOAP Web Services are standard-based and supported by almost every software platform: They rely heavily in XML and have support for transactions, security, asynchronous messages and many other issues. It’s a pretty big and complicated standard, but covers almost every messaging situation. On the other side, RESTful services relies of HTTP protocol and verbs (GET, POST, PUT, DELETE) to interchange messages in any format, preferable JSON and XML. It’s a pretty simple and elegant architectural approach.
  2. As in every topic in the Java World, there are several libraries to build/consume Web Services. In the SOAP Side you have the JAX-WS standard and Apache Axis, and in REST you can use Restlets or Spring REST Facilities among other libraries.

With question 3, this article states that RESTful Services are appropiate in this scenarios:

  • If you have limited bandwidth
  • If your operations are stateless: No information is preserved from one invocation to the next one, and each request is treated independently.
  • If your clients require caching.

While SOAP is the way to go when:

  • If you require asynchronous processing
  • If you need formal contract/Interfaces
  • In your service operations are stateful: For example, you store information/data on a request and use that stored data on the next one.

How to iterate using ngFor loop Map containing key as string and values as map iteration

This is because map.keys() returns an iterator. *ngFor can work with iterators, but the map.keys() will be called on every change detection cycle, thus producing a new reference to the array, resulting in the error you see. By the way, this is not always an error as you would traditionally think of it; it may even not break any of your functionality, but suggests that you have a data model which seems to behave in an insane way - changing faster than the change detector checks its value.

If you do no want to convert the map to an array in your component, you may use the pipe suggested in the comments. There is no other workaround, as it seems.

P.S. This error will not be shown in the production mode, as it is more like a very strict warning, rather than an actual error, but still, this is not a good idea to leave it be.

openCV video saving in python

Please make sure to set correct width and height. You can set it like bellow

cv2.VideoWriter('output.avi', fourcc, 20.0, (int(cap.get(3)), int(cap.get(4))))

Eclipse plugin for generating a class diagram

Assuming that you meant to state 'Class Diagram' instead of 'Project Hierarchy', I've used the following Eclipse plug-ins to generate Class Diagrams at various points in my professional career:

  • ObjectAid. My current preference.
  • EclipseUML from Omondo. Only commercial versions appear to be available right now. The class diagram in your question, is most likely generated by this plugin.

Obligatory links

The listed tools will not generate class diagrams from source code, or atleast when I used them quite a few years back. You can use them to handcraft class diagrams though.

  • UMLet. I used this several years back. Appears to be in use, going by the comments in the Eclipse marketplace.
  • Violet. This supports creation of other types of UML diagrams in addition to class diagrams.

Related questions on StackOverflow

  1. Is there a free Eclipse plugin that creates a UML diagram out of Java classes / packages?

Except for ObjectAid and a few other mentions, most of the Eclipse plug-ins mentioned in the listed questions may no longer be available, or would work only against older versions of Eclipse.

How to sort by dates excel?

The hashes are just because your column width is not enough to display the "number".

About the sorting, you should review how you system region and language is configured. For the US region, Excel date input should be "5/17/2012" not "17/05/2012" (this 17-may-12).

Regards

Sniff HTTP packets for GET and POST requests from an application

Put http.request.method == "POST" in the display filter of wireshark to only show POST requests. Click on the packet, then expand the Hypertext Transfer Protocol field. The POST data will be right there on top.

Swift performSelector:withObject:afterDelay: is unavailable

You could do this:

var timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("someSelector"), userInfo: nil, repeats: false)

func someSelector() {
    // Something after a delay
}

SWIFT 3

let timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(someSelector), userInfo: nil, repeats: false)

func someSelector() {
    // Something after a delay
}

What replaces cellpadding, cellspacing, valign, and align in HTML5 tables?

This should solve your problem:

td {
    /* <http://www.w3.org/wiki/CSS/Properties/text-align>
     * left, right, center, justify, inherit
     */
    text-align: center;
    /* <http://www.w3.org/wiki/CSS/Properties/vertical-align>
     * baseline, sub, super, top, text-top, middle,
     * bottom, text-bottom, length, or a value in percentage
     */
    vertical-align: top;
}

ASP.NET Web API - PUT & DELETE Verbs Not Allowed - IIS 8

Update your web.config

  <system.webServer>
    <modules>
      <remove name="WebDAVModule"/>
    </modules>
    <handlers>
      <remove name="WebDAV" />
      <remove name="ExtensionlessUrl-Integrated-4.0" />
      <add name="ExtensionlessUrl-Integrated-4.0"
           path="*."
           verb="GET,HEAD,POST,DEBUG,DELETE,PUT"
           type="System.Web.Handlers.TransferRequestHandler"
           preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>

http://odetocode.com/blogs/scott/archive/2012/08/07/configuration-tips-for-asp-net-mvc-4-on-a-windows.aspx

Removes the need to modify your host configs.

How to show/hide an element on checkbox checked/unchecked states using jQuery?

Try

$(document).ready(function(){
    //Register click events to all checkboxes inside question element
    $(document).on('click', '.question input:checkbox', function() {
        //Find the next answer element to the question and based on the checked status call either show or hide method
        $(this).closest('.question').next('.answer')[this.checked? 'show' : 'hide']()
    });

});

Demo: Fiddle

Or

$(document).ready(function(){
    //Register click events to all checkboxes inside question element
    $(document).on('click', '.question input:checkbox', function() {
        //Find the next answer element to the question and based on the checked status call either show or hide method
        var answer = $(this).closest('.question').next('.answer');

        if(this.checked){
            answer.show(300);
        } else {
            answer.hide(300);
        }
    });

});

QtCreator: No valid kits found

I had a similar problems after installing Qt in Windows.

This could be because only the Qt creator was installed and not any of the Qt libraries during initial installation. When installing from scratch use the online installer and select the following to install:

  1. For starting, select at least one version of Qt libs (ex Qt 5.15.1) and the c++ compiler of choice (ex MinGW 8.1.0 64-bit).

  2. Select Developer and Designer Tools. I kept the selected defaults.

Note: The choice of the Qt libs and Tools can also be changed post initial installation using MaintenanceTool.exe under Qt installation dir C:\Qt. See here.

Huge performance difference when using group by vs distinct

The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct approach is executed like:

  • Copy all business_key values to a temporary table
  • Sort the temporary table
  • Scan the temporary table, returning each item that is different from the one before it

The group by could be executed like:

  • Scan the full table, storing each value of business key in a hashtable
  • Return the keys of the hashtable

The first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.

Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.

How to remove jar file from local maven repository which was added with install:install-file?

I faced the same problem, went through all the suggestions above, but nothing worked. Finally I deleted both .m2 and .ivy folder and it worked for me.

javascript : sending custom parameters with window.open() but its not working

if you want to pass POST variables, you have to use a HTML Form:

<form action="http://localhost:8080/login" method="POST" target="_blank">
    <input type="text" name="cid" />
    <input type="password" name="pwd" />
    <input type="submit" value="open" />
</form>

or:

if you want to pass GET variables in an URL, write them without single-quotes:

http://yourdomain.com/login?cid=username&pwd=password

here's how to create the string above with javascrpt variables:

myu = document.getElementById('cid').value;
myp = document.getElementById('pwd').value;
window.open("http://localhost:8080/login?cid="+ myu +"&pwd="+ myp ,"MyTargetWindowName");

in the document with that url, you have to read the GET parameters. if it's in php, use:

$_GET['username']

be aware: to transmit passwords that way is a big security leak!

Upload DOC or PDF using PHP

For application/msword and application/vnd.ms-excel, when I deleted the size restriction:

($_FILES["file"]["size"] < 20000)

...it worked ok.

SVN Error: Commit blocked by pre-commit hook (exit code 1) with output: Error: n/a (6)

This happened to me, and it was caused the absence of a comment (should say "comment required" instead of this enigmatic error at first, right...)

How to make an authenticated web request in Powershell?

For those that need Powershell to return additional information like the Http StatusCode, here's an example. Included are the two most likely ways to pass in credentials.

Its a slightly modified version of this SO answer:
How to obtain numeric HTTP status codes in PowerShell

$req = [system.Net.WebRequest]::Create($url)
# method 1 $req.UseDefaultCredentials = $true
# method 2 $req.Credentials = New-Object System.Net.NetworkCredential($username, $pwd, $domain); 
try
{
    $res = $req.GetResponse()
}
catch [System.Net.WebException]
{
    $res = $_.Exception.Response
}

$int = [int]$res.StatusCode
$status = $res.StatusCode
return "$int $status"

How do I find all files containing specific text on Linux?

To search for the string and output just that line with the search string:

for i in $(find /path/of/target/directory -type f); do grep -i "the string to look for" "$i"; done

e.g.:

for i in $(find /usr/share/applications -type f); \
do grep -i "web browser" "$i"; done

To display filename containing the search string:

for i in $(find /path/of/target/directory -type f); do if grep -i "the string to look for" "$i" > /dev/null; then echo "$i"; fi; done;

e.g.:

for i in $(find /usr/share/applications -type f); \
do if grep -i "web browser" "$i" > /dev/null; then echo "$i"; \
fi; done;

Error: unmappable character for encoding UTF8 during maven compilation

Set incodign attribute in maven-compiler plugin work for me. The code example is the following

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.3.2</version>
    <configuration>
        <source>1.6</source>
        <target>1.6</target>
        <encoding>UTF-8</encoding>
    </configuration>
</plugin>

Do I need to close() both FileReader and BufferedReader?

I'm late, but:

BufferReader.java:

public BufferedReader(Reader in) {
  this(in, defaultCharBufferSize);
}

(...)

public void close() throws IOException {
    synchronized (lock) {
        if (in == null)
            return;
        try {
            in.close();
        } finally {
            in = null;
            cb = null;
        }
    }
}

Entity Framework : How do you refresh the model when the db changes?

You need to be careful though, You need to setup the EDMX file exactly as it was before deleting it (if you choose the delete/regenerate route), otherwise, you'll have a naming mismatch between your code and the EF generated model (especialy for pluralization and singularization)

Hope this will prevent you some headaches =)

How do I use reflection to invoke a private method?

Are you absolutely sure this can't be done through inheritance? Reflection is the very last thing you should look at when solving a problem, it makes refactoring, understanding your code, and any automated analysis more difficult.

It looks like you should just have a DrawItem1, DrawItem2, etc class that override your dynMethod.

jquery drop down menu closing by clicking outside

Another multiple dropdown example that works https://jsfiddle.net/vgjddv6u/

_x000D_
_x000D_
$('.moderate .button').on('click', (event) => {_x000D_
  $(event.target).siblings('.dropdown')_x000D_
    .toggleClass('is-open');_x000D_
});_x000D_
_x000D_
$(document).click(function(e) {_x000D_
  $('.moderate')_x000D_
    .not($('.moderate').has($(e.target)))_x000D_
    .children('.dropdown')_x000D_
    .removeClass('is-open');_x000D_
});
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.0/css/bulma.css" rel="stylesheet" />_x000D_
_x000D_
<script_x000D_
  src="https://code.jquery.com/jquery-3.2.1.min.js"_x000D_
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="_x000D_
  crossorigin="anonymous"></script>_x000D_
_x000D_
<style>_x000D_
.dropdown {_x000D_
  box-shadow: 0 0 2px #777;_x000D_
  display: none;_x000D_
  left: 0;_x000D_
  position: absolute;_x000D_
  padding: 2px;_x000D_
  z-index: 10;_x000D_
}_x000D_
_x000D_
.dropdown a {_x000D_
  font-size: 12px;_x000D_
  padding: 4px;_x000D_
}_x000D_
_x000D_
.dropdown.is-open {_x000D_
  display: block;_x000D_
}_x000D_
</style>_x000D_
_x000D_
_x000D_
<div class="control moderate">_x000D_
  <button class="button is-small" type="button">_x000D_
        moderate_x000D_
      </button>_x000D_
_x000D_
  <div class="box dropdown">_x000D_
    <ul>_x000D_
      <li><a class="nav-item">edit</a></li>_x000D_
      <li><a class="nav-item">delete</a></li>_x000D_
      <li><a class="nav-item">block user</a>   </li>_x000D_
    </ul>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
_x000D_
<div class="control moderate">_x000D_
  <button class="button is-small" type="button">_x000D_
        moderate_x000D_
      </button>_x000D_
_x000D_
  <div class="box dropdown">_x000D_
    <ul>_x000D_
      <li><a class="nav-item">edit</a></li>_x000D_
      <li><a class="nav-item">delete</a></li>_x000D_
      <li><a class="nav-item">block user</a></li>_x000D_
    </ul>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Create Django model or update if exists

It's unclear whether your question is asking for the get_or_create method (available from at least Django 1.3) or the update_or_create method (new in Django 1.7). It depends on how you want to update the user object.

Sample use is as follows:

# In both cases, the call will get a person object with matching
# identifier or create one if none exists; if a person is created,
# it will be created with name equal to the value in `name`.

# In this case, if the Person already exists, its existing name is preserved
person, created = Person.objects.get_or_create(
        identifier=identifier, defaults={"name": name}
)

# In this case, if the Person already exists, its name is updated
person, created = Person.objects.update_or_create(
        identifier=identifier, defaults={"name": name}
)

Convert InputStream to BufferedReader

BufferedReader can't wrap an InputStream directly. It wraps another Reader. In this case you'd want to do something like:

BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

How to check for DLL dependency?

On your development machine, you can execute the program and run Sysinternals Process Explorer. In the lower pane, it will show you the loaded DLLs and the current paths to them which is handy for a number of reasons. If you are executing off your deployment package, it would reveal which DLLs are referenced in the wrong path (i.e. weren't packaged correctly).

Currently, our company uses Visual Studio Installer projects to walk the dependency tree and output as loose files the program. In VS2013, this is now an extension: https://visualstudiogallery.msdn.microsoft.com/9abe329c-9bba-44a1-be59-0fbf6151054d. We then package these loose files in a more comprehensive installer but at least that setup project all the dot net dependencies and drops them into the one spot and warns you when things are missing.

Set folder browser dialog start location

Found on dotnet-snippets.de

With reflection this works and sets the real RootFolder!

using System;
using System.Reflection;
using System.Windows.Forms;

namespace YourNamespace
{
    public class RootFolderBrowserDialog
    {

        #region Public Properties

        /// <summary>
        ///   The description of the dialog.
        /// </summary>
        public string Description { get; set; } = "Chose folder...";

        /// <summary>
        ///   The ROOT path!
        /// </summary>
        public string RootPath { get; set; } = "";

        /// <summary>
        ///   The SelectedPath. Here is no initialization possible.
        /// </summary>
        public string SelectedPath { get; private set; } = "";

        #endregion Public Properties

        #region Public Methods

        /// <summary>
        ///   Shows the dialog...
        /// </summary>
        /// <returns>OK, if the user selected a folder or Cancel, if no folder is selected.</returns>
        public DialogResult ShowDialog()
        {
            var shellType = Type.GetTypeFromProgID("Shell.Application");
            var shell = Activator.CreateInstance(shellType);
            var folder = shellType.InvokeMember(
                             "BrowseForFolder", BindingFlags.InvokeMethod, null,
                             shell, new object[] { 0, Description, 0, RootPath, });
            if (folder is null)
            {
                return DialogResult.Cancel;
            }
            else
            {
                var folderSelf = folder.GetType().InvokeMember(
                                     "Self", BindingFlags.GetProperty, null,
                                     folder, null);
                SelectedPath = folderSelf.GetType().InvokeMember(
                                   "Path", BindingFlags.GetProperty, null,
                                   folderSelf, null) as string;
                // maybe ensure that SelectedPath is set
                return DialogResult.OK;
            }
        }

        #endregion Public Methods

    }
}

Converting a String to Object

A Java String is an Object. (String extends Object.)

So you can get an Object reference via assignment/initialisation:

String a = "abc";
Object b = a;

"Fatal error: Cannot redeclare <function>"

Since the code you've provided does not explicitly include anything, either it is being incldued twice, or (if the script is the entry point for the code) there must be a auto-prepend set up in the webserver config / php.ini or alternatively you've got a really obscure extension loaded which defines the function.

How can I remove an element from a list?

How about this? Again, using indices

> m <- c(1:5)
> m
[1] 1 2 3 4 5

> m[1:length(m)-1]
[1] 1 2 3 4

or

> m[-(length(m))]
[1] 1 2 3 4

PHP: How to use array_filter() to filter array keys?

With array_intersect_key and array_flip:

var_dump(array_intersect_key($my_array, array_flip($allowed)));

array(1) {
  ["foo"]=>
  int(1)
}

CSS Auto hide elements after 5 seconds

based from the answer of @SW4, you could also add a little animation at the end.

_x000D_
_x000D_
body > div{_x000D_
    border:1px solid grey;_x000D_
}_x000D_
html, body, #container {_x000D_
    height:100%;_x000D_
    width:100%;_x000D_
    margin:0;_x000D_
    padding:0;_x000D_
}_x000D_
#container {_x000D_
    overflow:hidden;_x000D_
    position:relative;_x000D_
}_x000D_
#hideMe {_x000D_
    -webkit-animation: cssAnimation 5s forwards; _x000D_
    animation: cssAnimation 5s forwards;_x000D_
}_x000D_
@keyframes cssAnimation {_x000D_
    0%   {opacity: 1;}_x000D_
    90%  {opacity: 1;}_x000D_
    100% {opacity: 0;}_x000D_
}_x000D_
@-webkit-keyframes cssAnimation {_x000D_
    0%   {opacity: 1;}_x000D_
    90%  {opacity: 1;}_x000D_
    100% {opacity: 0;}_x000D_
}
_x000D_
<div>_x000D_
<div id='container'>_x000D_
    <div id='hideMe'>Wait for it...</div>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Making the remaining 0.5 seconds to animate the opacity attribute. Just make sure to do the math if you're changing the length, in this case, 90% of 5 seconds leaves us 0.5 seconds to animate the opacity.

How do you comment out code in PowerShell?

Single line comments start with a hash symbol, everything to the right of the # will be ignored:

# Comment Here

In PowerShell 2.0 and above multi-line block comments can be used:

<# 
  Multi 
  Line 
#> 

You could use block comments to embed comment text within a command:

Get-Content -Path <# configuration file #> C:\config.ini

Note: Because PowerShell supports Tab Completion you need to be careful about copying and pasting Space + TAB before comments.