Programs & Examples On #Java 5

Java SE version 5 was released in September 2004 and is no longer supported by Sun as of November 2009. Use only if your question is specifically related to features of this version.

Hibernate Error executing DDL via JDBC Statement

you have to be careful because reseved words are not only for table names, also you have to check column names, my mistake was that one of my columns was named "user". If you are using PostgreSQL the correct dialect is: org.hibernate.dialect.PostgreSQLDialect

cheers.

SEVERE: Unable to create initial connections of pool - tomcat 7 with context.xml file

I have also dealt with this exception after a fully working context.xml setup was adjusted. I didn't want environment details in the context.xml, so I took them out and saw this error. I realized I must fully create this datasource resource in code based on System Property JVM -D args.

Original error with just user/pwd/host removed: org.apache.tomcat.jdbc.pool.ConnectionPool init SEVERE: Unable to create initial connections of pool.

Removed entire contents of context.xml and try this: Initialize on startup of app server the datasource object sometime before using first connection. If using Spring this is good to do in an @Configuration bean in @Bean Datasource constructor.

package to use: org.apache.tomcat.jdbc.pool.*

PoolProperties p = new PoolProperties();
p.setUrl(jdbcUrl);
            p.setDriverClassName(driverClass);
            p.setUsername(user);
            p.setPassword(pwd);
            p.setJmxEnabled(true);
            p.setTestWhileIdle(false);
            p.setTestOnBorrow(true);
            p.setValidationQuery("SELECT 1");
            p.setTestOnReturn(false);
            p.setValidationInterval(30000);
            p.setValidationQueryTimeout(100);
            p.setTimeBetweenEvictionRunsMillis(30000);
            p.setMaxActive(100);
            p.setInitialSize(5);
            p.setMaxWait(10000);
            p.setRemoveAbandonedTimeout(60);
            p.setMinEvictableIdleTimeMillis(30000);
            p.setMinIdle(5);
            p.setLogAbandoned(true);
            p.setRemoveAbandoned(true);
            p.setJdbcInterceptors(
              "org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"+
              "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
            org.apache.tomcat.jdbc.pool.DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource();
            ds.setPoolProperties(p);
            return ds;

insert data into database using servlet and jsp in eclipse

Same problem fetch main problem in PreparedStatement use simple statement then you successfully insert record same use below.

String  st2="insert into 
user(gender,name,address,telephone,fax,email,
     destination,sdate,edate,Participant,hcategory,
     Culture,Nature,People,Cities,Beaches,Festivals,username,password) 
values('"+gender+"','"+name+"','"+address+"','"+phone+"','"+fax+"',
       '"+email+"','"+desti+"','"+sdate+"','"+edate+"','"+parti+"',
       '"+hotel+"','"+chk1+"','"+chk2+"','"+chk3+"','"+chk4+"',
       '"+chk5+"','"+chk6+"','"+user+"','"+password+"')";


int i=stm.executeUpdate(st2);

How to add the JDBC mysql driver to an Eclipse project?

You can paste the .jar file of the driver in the Java setup instead of adding it to each project that you create. Paste it in C:\Program Files\Java\jre7\lib\ext or wherever you have installed java.

After this you will find that the .jar driver is enlisted in the library folder of your created project(JRE system library) in the IDE. No need to add it repetitively.

No suitable driver found for 'jdbc:mysql://localhost:3306/mysql

In this particular case (assuming that the Class#forName() didn't throw an exception; your code is namely continuing with running instead of throwing the exception), this SQLException means that Driver#acceptsURL() has returned false for any of the loaded drivers.

And indeed, your JDBC URL is wrong:

String url = "'jdbc:mysql://localhost:3306/mysql";

Remove the singlequote:

String url = "jdbc:mysql://localhost:3306/mysql";

See also:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name

you need to add jar file in your build path..

commons-dbcp-1.1-RC2.jar

or any version of that..!!!!

ADDED : also make sure you have commons-pool-1.1.jar too in your build path.

ADDED: sorry saw complete list of jar late... may be version clashes might be there.. better check out..!!! just an assumption.

How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception

Place mysql-connector-java-5.1.6-bin.jar to the \Apache Tomcat 6.0.18\lib folder. Your problem will be solved.

ClassNotFoundException com.mysql.jdbc.Driver

just copy and paste the mysqlconnector jar to your project folder and then build path it will definitely work.

adding classpath in linux

Important difference between setting Classpath in Windows and Linux is path separator which is ";" (semi-colon) in Windows and ":" (colon) in Linux. Also %PATH% is used to represent value of existing path variable in Windows while ${PATH} is used for same purpose in Linux (in the bash shell). Here is the way to setup classpath in Linux:

export CLASSPATH=${CLASSPATH}:/new/path

but as such Classpath is very tricky and you may wonder why your program is not working even after setting correct Classpath. Things to note:

  1. -cp options overrides CLASSPATH environment variable.
  2. Classpath defined in Manifest file overrides both -cp and CLASSPATH envorinment variable.

Reference: How Classpath works in Java.

Sorting objects by property values

Let us say we have to sort a list of objects in ascending order based on a particular property, in this example lets say we have to sort based on the "name" property, then below is the required code :

var list_Objects = [{"name"="Bob"},{"name"="Jay"},{"name"="Abhi"}];
Console.log(list_Objects);   //[{"name"="Bob"},{"name"="Jay"},{"name"="Abhi"}]
    list_Objects.sort(function(a,b){
        return a["name"].localeCompare(b["name"]); 
    });
Console.log(list_Objects);  //[{"name"="Abhi"},{"name"="Bob"},{"name"="Jay"}]

Read whole ASCII file into C++ std::string

I figured out another way that works with most istreams, including std::cin!

std::string readFile()
{
    stringstream str;
    ifstream stream("Hello_World.txt");
    if(stream.is_open())
    {
        while(stream.peek() != EOF)
        {
            str << (char) stream.get();
        }
        stream.close();
        return str.str();
    }
}

Parse Error: Adjacent JSX elements must be wrapped in an enclosing tag

React 16.0.0 we can return multiple components from render as an array.

return ([
    <Comp1 />,
    <Comp2 />
]);

React 16.4.0 we can return multiple components from render in a Fragment tag. Fragment

return (
<React.Fragment>
    <Comp1 />
    <Comp2 />
</React.Fragment>);

Future React you wil be able to use this shorthand syntax. (many tools don’t support it yet so you might want to explicitly write <Fragment> until the tooling catches up.)

return (
<>
    <Comp1 />
    <Comp2 />
</>)

Notepad++: Multiple words search in a file (may be in different lines)?

If you are using Notepad++ editor (like the tag of the question suggests), you can use the great "Find in Files" functionality.

Go to SearchFind in Files (Ctrl+Shift+F for the keyboard addicted) and enter:

  • Find What = (cat|town)

  • Filters = *.txt

  • Directory = enter the path of the directory you want to search in. You can check Follow current doc. to have the path of the current file to be filled.

  • Search mode = Regular Expression

Remove specific rows from a data frame

 X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
  Variable1 Variable2
1        11         2
2        14         3
3        12         1
4        15         4
> X[X$Variable1!=11 & X$Variable1!=12, ]
  Variable1 Variable2
2        14         3
4        15         4
> X[ ! X$Variable1 %in% c(11,12), ]
  Variable1 Variable2
2        14         3
4        15         4

You can functionalize this however you like.

How to fix committing to the wrong Git branch?

If the branch you wanted to apply your changes to already exists (branch develop, for example), follow the instructions that were provided by fotanus below, then:

git checkout develop
git rebase develop my_feature # applies changes to correct branch
git checkout develop # 'cuz rebasing will leave you on my_feature
git merge develop my_feature # will be a fast-forward
git branch -d my_feature

And obviously you could use tempbranch or any other branch name instead of my_feature if you wanted.

Also, if applicable, delay the stash pop (apply) until after you've merged at your target branch.

What's the best practice using a settings file in Python?

Yaml and Json are the simplest and most commonly used file formats to store settings/config. PyYaml can be used to parse yaml. Json is already part of python from 2.5. Yaml is a superset of Json. Json will solve most uses cases except multi line strings where escaping is required. Yaml takes care of these cases too.

>>> import json
>>> config = {'handler' : 'adminhandler.py', 'timeoutsec' : 5 }
>>> json.dump(config, open('/tmp/config.json', 'w'))
>>> json.load(open('/tmp/config.json'))   
{u'handler': u'adminhandler.py', u'timeoutsec': 5}

How do I set a variable to the output of a command in Bash?

Some Bash tricks I use to set variables from commands

Sorry, there is a loong answer, but as is a , where the main goal is to run other commands and react to resut code and/or output, ( commands are often piped filter, etc... ).

Storing command output in variables is something basic and fundamental.

Therefore, depending on

  • compatibility ()
  • kind of output (filter(s))
  • number of variable to set (split or interpret)
  • execution time (monitoring)
  • error trapping
  • repeatability of request (see long running background process, further)
  • interactivity (considering user input while reading from another input file descriptor)
  • do I miss something?

First simple, old, and compatible way

myPi=`echo '4*a(1)' | bc -l`
echo $myPi 
3.14159265358979323844

Mostly compatible, second way

As nesting could become heavy, parenthesis was implemented for this

myPi=$(bc -l <<<'4*a(1)')

Nested sample:

SysStarted=$(date -d "$(ps ho lstart 1)" +%s)
echo $SysStarted 
1480656334

features

Reading more than one variable (with Bashisms)

df -k /
Filesystem     1K-blocks   Used Available Use% Mounted on
/dev/dm-0         999320 529020    401488  57% /

If I just want a used value:

array=($(df -k /))

you could see an array variable:

declare -p array
declare -a array='([0]="Filesystem" [1]="1K-blocks" [2]="Used" [3]="Available" [
4]="Use%" [5]="Mounted" [6]="on" [7]="/dev/dm-0" [8]="999320" [9]="529020" [10]=
"401488" [11]="57%" [12]="/")'

Then:

echo ${array[9]}
529020

But I often use this:

{ read foo ; read filesystem size using avail prct mountpoint ; } < <(df -k /)
echo $using
529020

The first read foo will just skip header line, but in only one command, you will populate 7 different variables:

declare -p avail filesystem foo mountpoint prct size using
declare -- avail="401488"
declare -- filesystem="/dev/dm-0"
declare -- foo="Filesystem     1K-blocks   Used Available Use% Mounted on"
declare -- mountpoint="/"
declare -- prct="57%"
declare -- size="999320"
declare -- using="529020"

Or

{ read -a head;varnames=(${head[@]//[K1% -]});varnames=(${head[@]//[K1% -]});
  read ${varnames[@],,} ; } < <(LANG=C df -k /)

Then:

declare -p varnames ${varnames[@],,} 
declare -a varnames=([0]="Filesystem" [1]="blocks" [2]="Used" [3]="Available" [4]="Use" [5]="Mounted" [6]="on")
declare -- filesystem="/dev/dm-0"
declare -- blocks="999320"
declare -- used="529020"
declare -- available="401488"
declare -- use="57%"
declare -- mounted="/"
declare -- on=""

Or even:

{ read foo ; read filesystem dsk[{6,2,9}] prct mountpoint ; } < <(df -k /)
declare -p mountpoint dsk
declare -- mountpoint="/"
declare -a dsk=([2]="529020" [6]="999320" [9]="401488")

(Note Used and Blocks is switched there: read ... dsk[6] dsk[2] dsk[9] ...)

... will work with associative arrays too: read foo disk[total] disk[used] ...

Dedicated fd using unnamed fifo:

There is an elegent way:

users=()
while IFS=: read -u $list user pass uid gid name home bin ;do
    ((uid>=500)) &&
        printf -v users[uid] "%11d %7d %-20s %s\n" $uid $gid $user $home
done {list}</etc/passwd

Using this way (... read -u $list; ... {list}<inputfile) leave STDIN free for other purposes, like user interaction.

Then

echo -n "${users[@]}"
       1000    1000 user         /home/user
...
      65534   65534 nobody       /nonexistent

and

echo ${!users[@]}
1000 ... 65534

echo -n "${users[1000]}"
      1000    1000 user       /home/user

This could be used with static files or even /dev/tcp/xx.xx.xx.xx/yyy with x for ip address or hostname and y for port number:

{
    read -u $list -a head          # read header in array `head`
    varnames=(${head[@]//[K1% -]}) # drop illegal chars for variable names
    while read -u $list ${varnames[@],,} ;do
        ((pct=available*100/(available+used),pct<10)) &&
            printf "WARN: FS: %-20s on %-14s %3d <10 (Total: %11u, Use: %7s)\n" \
                "${filesystem#*/mapper/}" "$mounted" $pct $blocks "$use"
     done
 } {list}< <(LANG=C df -k)

And of course with inline documents:

while IFS=\; read -u $list -a myvar ;do
    echo ${myvar[2]}
done {list}<<"eof"
foo;bar;baz
alice;bob;charlie
$cherry;$strawberry;$memberberries
eof

Sample function for populating some variables:

#!/bin/bash

declare free=0 total=0 used=0

getDiskStat() {
    local foo
    {
        read foo
        read foo total used free foo
    } < <(
        df -k ${1:-/}
    )
}

getDiskStat $1
echo $total $used $free

Nota: declare line is not required, just for readability.

About sudo cmd | grep ... | cut ...

shell=$(cat /etc/passwd | grep $USER | cut -d : -f 7)
echo $shell
/bin/bash

(Please avoid useless cat! So this is just one fork less:

shell=$(grep $USER </etc/passwd | cut -d : -f 7)

All pipes (|) implies forks. Where another process have to be run, accessing disk, libraries calls and so on.

So using sed for sample, will limit subprocess to only one fork:

shell=$(sed </etc/passwd "s/^$USER:.*://p;d")
echo $shell

And with Bashisms:

But for many actions, mostly on small files, Bash could do the job itself:

while IFS=: read -a line ; do
    [ "$line" = "$USER" ] && shell=${line[6]}
  done </etc/passwd
echo $shell
/bin/bash

or

while IFS=: read loginname encpass uid gid fullname home shell;do
    [ "$loginname" = "$USER" ] && break
  done </etc/passwd
echo $shell $loginname ...

Going further about variable splitting...

Have a look at my answer to How do I split a string on a delimiter in Bash?

Alternative: reducing forks by using backgrounded long-running tasks

In order to prevent multiple forks like

myPi=$(bc -l <<<'4*a(1)'
myRay=12
myCirc=$(bc -l <<<" 2 * $myPi * $myRay ")

or

myStarted=$(date -d "$(ps ho lstart 1)" +%s)
mySessStart=$(date -d "$(ps ho lstart $$)" +%s)

This work fine, but running many forks is heavy and slow.

And commands like date and bc could make many operations, line by line!!

See:

bc -l <<<$'3*4\n5*6'
12
30

date -f - +%s < <(ps ho lstart 1 $$)
1516030449
1517853288

So we could use a long running background process to make many jobs, without having to initiate a new fork for each request.

Under , there is a built-in function: coproc:

coproc bc -l
echo 4*3 >&${COPROC[1]}
read -u $COPROC answer
echo $answer
12

echo >&${COPROC[1]} 'pi=4*a(1)'
ray=42.0
printf >&${COPROC[1]} '2*pi*%s\n' $ray
read -u $COPROC answer
echo $answer
263.89378290154263202896

printf >&${COPROC[1]} 'pi*%s^2\n' $ray
read -u $COPROC answer
echo $answer
5541.76944093239527260816

As bc is ready, running in background and I/O are ready too, there is no delay, nothing to load, open, close, before or after operation. Only the operation himself! This become a lot quicker than having to fork to bc for each operation!

Border effect: While bc stay running, they will hold all registers, so some variables or functions could be defined at initialisation step, as first write to ${COPROC[1]}, just after starting the task (via coproc).

Into a function newConnector

You may found my newConnector function on GitHub.Com or on my own site (Note on GitHub: there are two files on my site. Function and demo are bundled into one uniq file which could be sourced for use or just run for demo.)

Sample:

source shell_connector.sh

tty
/dev/pts/20

ps --tty pts/20 fw
    PID TTY      STAT   TIME COMMAND
  29019 pts/20   Ss     0:00 bash
  30745 pts/20   R+     0:00  \_ ps --tty pts/20 fw

newConnector /usr/bin/bc "-l" '3*4' 12

ps --tty pts/20 fw
    PID TTY      STAT   TIME COMMAND
  29019 pts/20   Ss     0:00 bash
  30944 pts/20   S      0:00  \_ /usr/bin/bc -l
  30952 pts/20   R+     0:00  \_ ps --tty pts/20 fw

declare -p PI
bash: declare: PI: not found

myBc '4*a(1)' PI
declare -p PI
declare -- PI="3.14159265358979323844"

The function myBc lets you use the background task with simple syntax, and for date:

newConnector /bin/date '-f - +%s' @0 0
myDate '2000-01-01'
  946681200
myDate "$(ps ho lstart 1)" boottime
myDate now now ; read utm idl </proc/uptime
myBc "$now-$boottime" uptime
printf "%s\n" ${utm%%.*} $uptime
  42134906
  42134906

ps --tty pts/20 fw
    PID TTY      STAT   TIME COMMAND
  29019 pts/20   Ss     0:00 bash
  30944 pts/20   S      0:00  \_ /usr/bin/bc -l
  32615 pts/20   S      0:00  \_ /bin/date -f - +%s
   3162 pts/20   R+     0:00  \_ ps --tty pts/20 fw

From there, if you want to end one of background processes, you just have to close its fd:

eval "exec $DATEOUT>&-"
eval "exec $DATEIN>&-"
ps --tty pts/20 fw
    PID TTY      STAT   TIME COMMAND
   4936 pts/20   Ss     0:00 bash
   5256 pts/20   S      0:00  \_ /usr/bin/bc -l
   6358 pts/20   R+     0:00  \_ ps --tty pts/20 fw

which is not needed, because all fd close when the main process finishes.

Ruby class instance variable vs. class variable

For those with a C++ background, you may be interested in a comparison with the C++ equivalent:

class S
{
private: // this is not quite true, in Ruby you can still access these
  static int    k = 23;
  int           s = 15;

public:
  int get_s() { return s; }
  static int get_k() { return k; }

};

std::cerr << S::k() << "\n";

S instance;
std::cerr << instance.s() << "\n";
std::cerr << instance.k() << "\n";

As we can see, k is a static like variable. This is 100% like a global variable, except that it's owned by the class (scoped to be correct). This makes it easier to avoid clashes between similarly named variables. Like any global variable, there is just one instance of that variable and modifying it is always visible by all.

On the other hand, s is an object specific value. Each object has its own instance of the value. In C++, you must create an instance to have access to that variable. In Ruby, the class definition is itself an instance of the class (in JavaScript, this is called a prototype), therefore you can access s from the class without additional instantiation. The class instance can be modified, but modification of s is going to be specific to each instance (each object of type S). So modifying one will not change the value in another.

How to get the number of columns in a matrix?

While size(A,2) is correct, I find it's much more readable to first define

rows = @(x) size(x,1); 
cols = @(x) size(x,2);

and then use, for example, like this:

howManyColumns_in_A = cols(A)
howManyRows_in_A    = rows(A)

It might appear as a small saving, but size(.., 1) and size(.., 2) must be some of the most commonly used functions, and they are not optimally readable as-is.

Postgres error on insert - ERROR: invalid byte sequence for encoding "UTF8": 0x00

You can first insert data into blob field and then copy to text field with the folloing function

CREATE OR REPLACE FUNCTION blob2text() RETURNS void AS $$
Declare
    ref record;
    i integer;
Begin
    FOR ref IN SELECT id, blob_field FROM table LOOP

          --  find 0x00 and replace with space    
      i := position(E'\\000'::bytea in ref.blob_field);
      WHILE i > 0 LOOP
        ref.bob_field := set_byte(ref.blob_field, i-1, 20);
        i := position(E'\\000'::bytea in ref.blobl_field);
      END LOOP

    UPDATE table SET field = encode(ref.blob_field, 'escape') WHERE id = ref.id;
    END LOOP;

End; $$ LANGUAGE plpgsql; 

--

SELECT blob2text();

Getting 400 bad request error in Jquery Ajax POST

In case anyone else runs into this. I have a web site that was working fine on the desktop browser but I was getting 400 errors with Android devices.

It turned out to be the anti forgery token.

$.ajax({
        url: "/Cart/AddProduct/",
        data: {
            __RequestVerificationToken: $("[name='__RequestVerificationToken']").val(),
            productId: $(this).data("productcode")
        },

The problem was that the .Net controller wasn't set up correctly.

I needed to add the attributes to the controller:

    [AllowAnonymous]
    [IgnoreAntiforgeryToken]
    [DisableCors]
    [HttpPost]
    public async Task<JsonResult> AddProduct(int productId)
    {

The code needs review but for now at least I know what was causing it. 400 error not helpful at all.

From io.Reader to string in Go

EDIT:

Since 1.10, strings.Builder exists. Example:

buf := new(strings.Builder)
n, err := io.Copy(buf, r)
// check errors
fmt.Println(buf.String())

OUTDATED INFORMATION BELOW

The short answer is that it it will not be efficient because converting to a string requires doing a complete copy of the byte array. Here is the proper (non-efficient) way to do what you want:

buf := new(bytes.Buffer)
buf.ReadFrom(yourReader)
s := buf.String() // Does a complete copy of the bytes in the buffer.

This copy is done as a protection mechanism. Strings are immutable. If you could convert a []byte to a string, you could change the contents of the string. However, go allows you to disable the type safety mechanisms using the unsafe package. Use the unsafe package at your own risk. Hopefully the name alone is a good enough warning. Here is how I would do it using unsafe:

buf := new(bytes.Buffer)
buf.ReadFrom(yourReader)
b := buf.Bytes()
s := *(*string)(unsafe.Pointer(&b))

There we go, you have now efficiently converted your byte array to a string. Really, all this does is trick the type system into calling it a string. There are a couple caveats to this method:

  1. There are no guarantees this will work in all go compilers. While this works with the plan-9 gc compiler, it relies on "implementation details" not mentioned in the official spec. You can not even guarantee that this will work on all architectures or not be changed in gc. In other words, this is a bad idea.
  2. That string is mutable! If you make any calls on that buffer it will change the string. Be very careful.

My advice is to stick to the official method. Doing a copy is not that expensive and it is not worth the evils of unsafe. If the string is too large to do a copy, you should not be making it into a string.

Compare two dates with JavaScript

The simple way is,

var first = '2012-11-21';
var second = '2012-11-03';

if (new Date(first) > new Date(second) {
    .....
}

How do I use variables in Oracle SQL Developer?

In SQL*Plus, you can do something very similar

SQL> variable v_emp_id number;
SQL> select 1234 into :v_emp_id from dual;

      1234
----------
      1234

SQL> select *
  2    from emp
  3   where empno = :v_emp_id;

no rows selected

In SQL Developer, if you run a statement that has any number of bind variables (prefixed with a colon), you'll be prompted to enter values. As Alex points out, you can also do something similar using the "Run Script" function (F5) with the alternate EXEC syntax Alex suggests does.

variable v_count number;
variable v_emp_id number;
exec :v_emp_id := 1234;
exec select count(1) into :v_count from emp;
select *
  from emp
 where empno = :v_emp_id
exec print :v_count;

'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll

The event is probably raised before the elements are fully loaded or the references are still unset, hence the exceptions. Try only setting properties if the reference is not null and IsLoaded is true.

How to study design patterns?

I think you need to examine some of the issues you have encountered as a developer where you pulled your hair out after you had to revise your code for the 10th time because of a yet another design change. You probably have a list of projects where you felt that there was a lot of rework and pain.

From that list you can derive the scenarios that the Design Patterns intend to solve. Has there been a time where you needed to perform the same series of actions on different sets of data? Will you need to be able to future capability to an application but want to avoid reworking all your logic for existing classes? Start with those scenarios and return to the catalog of patterns and their respective problems they are supposed to solve. You are likely to see some matches between the GoF and your library of projects.

How can I determine whether a 2D Point is within a Polygon?

I did some work on this back when I was a researcher under Michael Stonebraker - you know, the professor who came up with Ingres, PostgreSQL, etc.

We realized that the fastest way was to first do a bounding box because it's SUPER fast. If it's outside the bounding box, it's outside. Otherwise, you do the harder work...

If you want a great algorithm, look to the open source project PostgreSQL source code for the geo work...

I want to point out, we never got any insight into right vs left handedness (also expressible as an "inside" vs "outside" problem...


UPDATE

BKB's link provided a good number of reasonable algorithms. I was working on Earth Science problems and therefore needed a solution that works in latitude/longitude, and it has the peculiar problem of handedness - is the area inside the smaller area or the bigger area? The answer is that the "direction" of the verticies matters - it's either left-handed or right handed and in this way you can indicate either area as "inside" any given polygon. As such, my work used solution three enumerated on that page.

In addition, my work used separate functions for "on the line" tests.

...Since someone asked: we figured out that bounding box tests were best when the number of verticies went beyond some number - do a very quick test before doing the longer test if necessary... A bounding box is created by simply taking the largest x, smallest x, largest y and smallest y and putting them together to make four points of a box...

Another tip for those that follow: we did all our more sophisticated and "light-dimming" computing in a grid space all in positive points on a plane and then re-projected back into "real" longitude/latitude, thus avoiding possible errors of wrapping around when one crossed line 180 of longitude and when handling polar regions. Worked great!

Spring data JPA query with parameter properties

if we are using JpaRepository then it will internally created the queries.

Sample

findByLastnameAndFirstname(String lastname,String firstname)

findByLastnameOrFirstname(String lastname,String firstname)

findByStartDateBetween(Date date1,Date2)

findById(int id)

Note

if suppose we need complex queries then we need to write manual queries like

@Query("SELECT salesOrder FROM SalesOrder salesOrder WHERE salesOrder.clientId=:clientId AND salesOrder.driver_username=:driver_username AND salesOrder.date>=:fdate AND salesOrder.date<=:tdate ")
 @Transactional(readOnly=true)
 List<SalesOrder> findAllSalesByDriver(@Param("clientId")Integer clientId, @Param("driver_username")String driver_username, @Param("fdate") Date fDate, @Param("tdate") Date tdate);

Adding class to element using Angular JS

AngularJS has some methods called JQlite so we can use it. see link

Select the element in DOM is

angular.element( document.querySelector( '#div1' ) );

add the class like .addClass('alpha');

So finally

var myEl = angular.element( document.querySelector( '#div1' ) );
myEl.addClass('alpha');

How to add more than one machine to the trusted hosts list using winrm

The suggested answer by Loïc MICHEL blindly writes a new value to the TrustedHosts entry.
I believe, a better way would be to first query TrustedHosts.
As Jeffery Hicks posted in 2010, first query the TrustedHosts entry:

PS C:\> $current=(get-item WSMan:\localhost\Client\TrustedHosts).value
PS C:\> $current+=",testdsk23,alpha123"
PS C:\> set-item WSMan:\localhost\Client\TrustedHosts –value $current

How to generate a random string of a fixed length in Go?

const (
    chars       = "0123456789_abcdefghijkl-mnopqrstuvwxyz" //ABCDEFGHIJKLMNOPQRSTUVWXYZ
    charsLen    = len(chars)
    mask        = 1<<6 - 1
)

var rng = rand.NewSource(time.Now().UnixNano())

// RandStr ????????????
func RandStr(ln int) string {
    /* chars 38???
     * rng.Int63() ????64bit????,??????6bit(2^6=64) ????10?
     */
    buf := make([]byte, ln)
    for idx, cache, remain := ln-1, rng.Int63(), 10; idx >= 0; {
        if remain == 0 {
            cache, remain = rng.Int63(), 10
        }
        buf[idx] = chars[int(cache&mask)%charsLen]
        cache >>= 6
        remain--
        idx--
    }
    return *(*string)(unsafe.Pointer(&buf))
}

BenchmarkRandStr16-8 20000000 68.1 ns/op 16 B/op 1 allocs/op

Why does comparing strings using either '==' or 'is' sometimes produce a different result?

The basic concept we have to be clear while approaching this question is to understand the difference between is and ==.

"is" is will compare the memory location. if id(a)==id(b), then a is b returns true else it returns false.

so, we can say that is is used for comparing memory locations. Whereas,

== is used for equality testing which means that it just compares only the resultant values. The below shown code may acts as an example to the above given theory.

code

Click here for the code

In the case of string literals(strings without getting assigned to variables), the memory address will be same as shown in the picture. so, id(a)==id(b). remaining this is self-explanatory.

How can I test that a variable is more than eight characters in PowerShell?

Use the length property of the [String] type:

if ($dbUserName.length -gt 8) {
    Write-Output "Please enter more than 8 characters."
    $dbUserName = Read-Host "Re-enter database username"
}

Please note that you have to use -gt instead of > in your if condition. PowerShell uses the following comparison operators to compare values and test conditions:

  • -eq = equals
  • -ne = not equals
  • -lt = less than
  • -gt = greater than
  • -le = less than or equals
  • -ge = greater than or equals

How to check if a string "StartsWith" another string?

The string object has methods like startsWith, endsWith and includes methods.

  • StartsWith checks whether the given string starts at the beginning or not.

  • endsWith checks whether the given string is at the end or not.

  • includes checks whether the given string is present at any part or not.

You can find the complete difference between these three in the bellow youtube video

https://www.youtube.com/watch?v=E-hyeSwg0PA

Django Model() vs Model.objects.create()

UPDATE 15.3.2017:

I have opened a Django-issue on this and it seems to be preliminary accepted here: https://code.djangoproject.com/ticket/27825

My experience is that when using the Constructor (ORM) class by references with Django 1.10.5 there might be some inconsistencies in the data (i.e. the attributes of the created object may get the type of the input data instead of the casted type of the ORM object property) example:

models

class Payment(models.Model):
     amount_cash = models.DecimalField()

some_test.py - object.create

Class SomeTestCase:
    def generate_orm_obj(self, _constructor, base_data=None, modifiers=None):
        objs = []
        if not base_data:
            base_data = {'amount_case': 123.00}
        for modifier in modifiers:
            actual_data = deepcopy(base_data)
            actual_data.update(modifier)
            # Hacky fix,
            _obj = _constructor.objects.create(**actual_data)
            print(type(_obj.amount_cash)) # Decimal
            assert created
           objs.append(_obj)
        return objs

some_test.py - Constructor()

Class SomeTestCase:
    def generate_orm_obj(self, _constructor, base_data=None, modifiers=None):
        objs = []
        if not base_data:
            base_data = {'amount_case': 123.00}
        for modifier in modifiers:
            actual_data = deepcopy(base_data)
            actual_data.update(modifier)
            # Hacky fix,
            _obj = _constructor(**actual_data)
            print(type(_obj.amount_cash)) # Float
            assert created
           objs.append(_obj)
        return objs

How to add 'ON DELETE CASCADE' in ALTER TABLE statement

Here is an handy solution! I'm using SQL Server 2008 R2.

As you want to modify the FK constraint by adding ON DELETE/UPDATE CASCADE, follow these steps:

NUMBER 1:

Right click on the constraint and click to Modify

enter image description here

NUMBER 2:

Choose your constraint on the left side (if there are more than one). Then on the right side, collapse "INSERT And UPDATE Specification" point and specify the actions on Delete Rule or Update Rule row to suit your need. After that, close the dialog box.

enter image description here

NUMBER 3:

The final step is to save theses modifications (of course!)

enter image description here

PS: It's saved me from a bunch of work as I want to modify a primary key referenced in another table.

Configuration with name 'default' not found. Android Studio

For one, it doesn't do good to have more than one settings.gradle file -- it only looks at the top-level one.

When you get this "Configuration with name 'default' not found" error, it's really confusing, but what it means is that Gradle is looking for a module (or a build.gradle) file someplace, and it's not finding it. In your case, you have this in your settings.gradle file:

include ':libraries:Android-Bootstrap',':Android-Bootstrap'

which is making Gradle look for a library at FTPBackup/libraries/Android-Bootstrap. If you're on a case-sensitive filesystem (and you haven't mistyped Libraries in your question when you meant libraries), it may not find FTPBackup/Libraries/Android-Bootstrap because of the case difference. It's also looking for another library at FTPBackup/Android-Bootstrap, and it's definitely not going to find one because that directory isn't there.

This should work:

include ':Libraries:Android-Bootstrap'

You need the same case-sensitive spec in your dependencies block:

compile project (':Libraries:Android-Bootstrap')

RestSharp simple complete example

Pawel Sawicz .NET blog has a real good explanation and example code, explaining how to call the library;

GET:

var client = new RestClient("192.168.0.1");
var request = new RestRequest("api/item/", Method.GET);
var queryResult = client.Execute<List<Items>>(request).Data;

POST:

var client = new RestClient("http://192.168.0.1");
var request = new RestRequest("api/item/", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody(new Item
{
   ItemName = someName,
   Price = 19.99
});
client.Execute(request);

DELETE:

var item = new Item(){//body};
var client = new RestClient("http://192.168.0.1");
var request = new RestRequest("api/item/{id}", Method.DELETE);
request.AddParameter("id", idItem);
 
client.Execute(request)

The RestSharp GitHub page has quite an exhaustive sample halfway down the page. To get started install the RestSharp NuGet package in your project, then include the necessary namespace references in your code, then above code should work (possibly negating your need for a full example application).

NuGet RestSharp

Bootstrap Navbar toggle button not working

Wasted several hours only to realize that viewport meta was missing from my code. Adding here just in case some one else misses it out.

As soon as I added this, the toggle started working fine.

<meta name="viewport" content="width=device-width, initial-scale=1">

compilation error: identifier expected

only variable/object declaration statement are written outside of method

public class details{
    public static void main(String arg[]){
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("What is your name?");
        String name = in.readLine(); ;
        System.out.println("Hello " + name);
    }
}

here is example try to learn java book and see the syntax then try to develop the program

count files in specific folder and display the number into 1 cel

Try below code :

Assign the path of the folder to variable FolderPath before running the below code.

Sub sample()

    Dim FolderPath As String, path As String, count As Integer
    FolderPath = "C:\Documents and Settings\Santosh\Desktop"

    path = FolderPath & "\*.xls"

    Filename = Dir(path)

    Do While Filename <> ""
       count = count + 1
        Filename = Dir()
    Loop

    Range("Q8").Value = count
    'MsgBox count & " : files found in folder"
End Sub

What is the difference between npm install and npm run build?

The main difference is ::

npm install is a npm cli-command which does the predefined thing i.e, as written by Churro, to install dependencies specified inside package.json

npm run command-name or npm run-script command-name ( ex. npm run build ) is also a cli-command predefined to run your custom scripts with the name specified in place of "command-name". So, in this case npm run build is a custom script command with the name "build" and will do anything specified inside it (for instance echo 'hello world' given in below example package.json).

Ponits to note::

  1. One more thing, npm build and npm run build are two different things, npm run build will do custom work written inside package.json and npm build is a pre-defined script (not available to use directly)

  2. You cannot specify some thing inside custom build script (npm run build) script and expect npm build to do the same. Try following thing to verify in your package.json:

    { "name": "demo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "build":"echo 'hello build'" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": {}, "dependencies": {} }

and run npm run build and npm build one by one and you will see the difference. For more about commands kindly follow npm documentation.

Cheers!!

Shortest distance between a point and a line segment

see the Matlab GEOMETRY toolbox in the following website: http://people.sc.fsu.edu/~jburkardt/m_src/geometry/geometry.html

ctrl+f and type "segment" to find line segment related functions. the functions "segment_point_dist_2d.m" and "segment_point_dist_3d.m" are what you need.

The GEOMETRY codes are available in a C version and a C++ version and a FORTRAN77 version and a FORTRAN90 version and a MATLAB version.

What is the difference between a JavaBean and a POJO?

Pojo - Plain old java object

pojo class is an ordinary class without any specialties,class totally loosely coupled from technology/framework.the class does not implements from technology/framework and does not extends from technology/framework api that class is called pojo class.

pojo class can implements interfaces and extend classes but the super class or interface should not be an technology/framework.

Examples :

1.

class ABC{
----
}

ABC class not implementing or extending from technology/framework that's why this is pojo class.

2.

class ABC extends HttpServlet{
---
}

ABC class extending from servlet technology api that's why this is not a pojo class.

3.

class ABC implements java.rmi.Remote{
----
}

ABC class implements from rmi api that's why this is not a pojo class.

4.

class ABC implements java.io.Serializable{
---
}

this interface is part of java language not a part of technology/framework.so this is pojo class.

5.

class ABC extends Thread{
--
}

here thread is also class of java language so this is also a pojo class.

6.

class ABC extends Test{
--
}

if Test class extends or implements from technologies/framework then ABC is also not a pojo class because it inherits the properties of Test class. if Test class is not a pojo class then ABC class also not a pojo class.

7.

now this point is an exceptional case

@Entity
class ABC{
--
}

@Entity is an annotation given by hibernate api or jpa api but still we can call this class as pojo class. class with annotations given from technology/framework is called pojo class by this exceptional case.

XOR operation with two strings in java

Assuming (!) the strings are of equal length, why not convert the strings to byte arrays and then XOR the bytes. The resultant byte arrays may be of different lengths too depending on your encoding (e.g. UTF8 will expand to different byte lengths for different characters).

You should be careful to specify the character encoding to ensure consistent/reliable string/byte conversion.

Is there any way to wait for AJAX response and halt execution?

Try this code. it worked for me.

 function getInvoiceID(url, invoiceId) {
    return $.ajax({
        type: 'POST',
        url: url,
        data: { invoiceId: invoiceId },
        async: false,
    });
}
function isInvoiceIdExists(url, invoiceId) {
    $.when(getInvoiceID(url, invoiceId)).done(function (data) {
        if (!data) {

        }
    });
}

How do I flush the PRINT buffer in TSQL?

Another better option is to not depend on PRINT or RAISERROR and just load your "print" statements into a ##Temp table in TempDB or a permanent table in your database which will give you visibility to the data immediately via a SELECT statement from another window. This works the best for me. Using a permanent table then also serves as a log to what happened in the past. The print statements are handy for errors, but using the log table you can also determine the exact point of failure based on the last logged value for that particular execution (assuming you track the overall execution start time in your log table.)

I want to vertical-align text in select box

I used to use height and line-height with the same values, but the proved to be inconsistent across the interwebs. My current approach is to mix that with padding like so.

select {
  font-size:14px;
  height:18px;
  line-height:18px;
  padding:5px 0;
  width:200px;
  text-align:center;
}

You could also use padding for the horizontal value instead of the width + text-align

ConnectivityManager getNetworkInfo(int) deprecated

Since answers posted only allow you to query the active network, here's how to get NetworkInfo for any network, not only the active one (for example Wifi network) (sorry, Kotlin code ahead)

(getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).run {
    allNetworks.find { getNetworkInfo(it).type == ConnectivityManager.TYPE_WIFI }?.let { network -> getNetworkInfo(network) }
//    getNetworkInfo(ConnectivityManager.TYPE_WIFI).isAvailable // This is the deprecated API pre-21
}

This requires API 21 or higher and the permission android.permission.ACCESS_NETWORK_STATE

How to position one element relative to another with jQuery?

This is what worked for me in the end.

var showMenu = function(el, menu) {
    //get the position of the placeholder element  
    var pos = $(el).offset();    
    var eWidth = $(el).outerWidth();
    var mWidth = $(menu).outerWidth();
    var left = (pos.left + eWidth - mWidth) + "px";
    var top = 3+pos.top + "px";
    //show the menu directly over the placeholder  
    $(menu).css( { 
        position: 'absolute',
        zIndex: 5000,
        left: left, 
        top: top
    } );

    $(menu).hide().fadeIn();
};

Why use HttpClient for Synchronous Connection

In my case the accepted answer did not work. I was calling the API from an MVC application which had no async actions.

This is how I managed to make it work:

private static readonly TaskFactory _myTaskFactory = new TaskFactory(CancellationToken.None, TaskCreationOptions.None, TaskContinuationOptions.None, TaskScheduler.Default);
public static T RunSync<T>(Func<Task<T>> func)
    {           
        CultureInfo cultureUi = CultureInfo.CurrentUICulture;
        CultureInfo culture = CultureInfo.CurrentCulture;
        return _myTaskFactory.StartNew<Task<T>>(delegate
        {
            Thread.CurrentThread.CurrentCulture = culture;
            Thread.CurrentThread.CurrentUICulture = cultureUi;
            return func();
        }).Unwrap<T>().GetAwaiter().GetResult();
    }

Then I called it like this:

Helper.RunSync(new Func<Task<ReturnTypeGoesHere>>(async () => await AsyncCallGoesHere(myparameter)));

Run / Open VSCode from Mac Terminal

I moved VS Code from Downloads folder to Applications, and then i was able to run code in the terminal. I guess, it might help you too.

Javascript date.getYear() returns 111 in 2011?

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getYear

getYear is no longer used and has been replaced by the getFullYear method.

The getYear method returns the year minus 1900; thus:

  • For years greater than or equal to 2000, the value returned by getYear is 100 or greater. For example, if the year is 2026, getYear returns 126.
  • For years between and including 1900 and 1999, the value returned by getYear is between 0 and 99. For example, if the year is 1976, getYear returns 76.
  • For years less than 1900, the value returned by getYear is less than 0. For example, if the year is 1800, getYear returns -100.
  • To take into account years before and after 2000, you should use getFullYear instead of getYear so that the year is specified in full.

Loading all images using imread from a given folder

If all images are of the same format:

import cv2
import glob

images = [cv2.imread(file) for file in glob.glob('path/to/files/*.jpg')]

For reading images of different formats:

import cv2
import glob

imdir = 'path/to/files/'
ext = ['png', 'jpg', 'gif']    # Add image formats here

files = []
[files.extend(glob.glob(imdir + '*.' + e)) for e in ext]

images = [cv2.imread(file) for file in files]

jQuery, checkboxes and .is(":checked")

If you anticipate this rather unwanted behaviour, then one away around it would be to pass an extra parameter from the jQuery.trigger() to the checkbox's click handler. This extra parameter is to notify the click handler that click has been triggered programmatically, rather than by the user directly clicking on the checkbox itself. The checkbox's click handler can then invert the reported check status.

So here's how I'd trigger the click event on a checkbox with the ID "myCheckBox". Note that I'm also passing an object parameter with an single member, nonUI, which is set to true:

$("#myCheckbox").trigger('click', {nonUI : true})

And here's how I handle that in the checkbox's click event handler. The handler function checks for the presence of the nonUI object as its second parameter. (The first parameter is always the event itself.) If the parameter is present and set to true then I invert the reported .checked status. If no such parameter is passed in - which there won't be if the user simply clicked on the checkbox in the UI - then I report the actual .checked status:

$("#myCheckbox").click(function(e, parameters) {
   var nonUI = false;
        try {
            nonUI = parameters.nonUI;
        } catch (e) {}
        var checked = nonUI ? !this.checked : this.checked;
        alert('Checked = ' + checked);
    });

JSFiddle version at http://jsfiddle.net/BrownieBoy/h5mDZ/

I've tested with Chrome, Firefox and IE 8.

How to do a scatter plot with empty circles in Python?

From the documentation for scatter:

Optional kwargs control the Collection properties; in particular:

    edgecolors:
        The string ‘none’ to plot faces with no outlines
    facecolors:
        The string ‘none’ to plot unfilled outlines

Try the following:

import matplotlib.pyplot as plt 
import numpy as np 

x = np.random.randn(60) 
y = np.random.randn(60)

plt.scatter(x, y, s=80, facecolors='none', edgecolors='r')
plt.show()

example image

Note: For other types of plots see this post on the use of markeredgecolor and markerfacecolor.

Using a string variable as a variable name

You can use setattr

name  = 'varname'
value = 'something'

setattr(self, name, value) #equivalent to: self.varname= 'something'

print (self.varname)
#will print 'something'

But, since you should inform an object to receive the new variable, this only works inside classes or modules.

Add space between two particular <td>s

my choice was to add a td between the two td tags and set the width to 25px. It can be more or less to your liking. This may be cheesy but it is simple and it works.

Using `window.location.hash.includes` throws “Object doesn't support property or method 'includes'” in IE11

I had a similar issue with an Angular project. In my polyfills.ts I had to add both:

    import "core-js/es7/array";
    import "core-js/es7/object";

In addition to enabling all the other IE 11 defaults. (See comments in polyfills.ts if using angular)

After adding these imports the error went away and my Object data populated as intended.

Return row number(s) for a particular value in a column in a dataframe

Use which(mydata_2$height_chad1 == 2585)

Short example

df <- data.frame(x = c(1,1,2,3,4,5,6,3),
                 y = c(5,4,6,7,8,3,2,4))
df
  x y
1 1 5
2 1 4
3 2 6
4 3 7
5 4 8
6 5 3
7 6 2
8 3 4

which(df$x == 3)
[1] 4 8

length(which(df$x == 3))
[1] 2

count(df, vars = "x")
  x freq
1 1    2
2 2    1
3 3    2
4 4    1
5 5    1
6 6    1

df[which(df$x == 3),]
  x y
4 3 7
8 3 4

As Matt Weller pointed out, you can use the length function. The count function in plyr can be used to return the count of each unique column value.

How to change the docker image installation directory?

Copy-and-paste version of the winner answer :)

Create this file with only this content:

$ sudo vi /etc/docker/daemon.json

  {
      "graph": "/my-docker-images"
  }

Tested on Ubuntu 16.04.2 LTS in docker 1.12.6

javascript - pass selected value from popup window to parent window input box

My approach: use a div instead of a pop-up window.

See it working in the jsfiddle here: http://jsfiddle.net/6RE7w/2/

Or save the code below as test.html and try it locally.

<html>

<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
    <script type="text/javascript">
        $(window).load(function(){
            $('.btnChoice').on('click', function(){
                $('#divChoices').show()
                thefield = $(this).prev()
                $('.btnselect').on('click', function(){
                    theselected = $(this).prev()
                    thefield.val( theselected.val() )
                    $('#divChoices').hide()
                })
            })

            $('#divChoices').css({
                'border':'2px solid red',
                'position':'fixed',
                'top':'100',
                'left':'200',
                'display':'none'
            })
        });
    </script>
</head>

<body>

<div class="divform">
    <input type="checkbox" name="kvi1" id="kvi1" value="1">
    <label>Field 1: </label>
    <input size="10" type="number" id="sku1" name="sku1">
    <button id="choice1" class="btnChoice">?</button>
    <br>
    <input type="checkbox" name="kvi2" id="kvi2" value="2">
    <label>Field 2: </label>
    <input size="10"  type="number" id="sku2" name="sku2">
    <button id="choice2" class="btnChoice">?</button>
</div>

<div id="divChoices">
    Select something: 
    <br>
    <input size="10" type="number" id="ch1" name="ch1" value="11">
    <button id="btnsel1" class="btnselect">Select</button>
    <label for="ch1">bla bla bla</label>
    <br>
    <input size="10" type="number" id="ch2" name="ch2" value="22">
    <button id="btnsel2" class="btnselect">Select</button>
    <label for="ch2">ble ble ble</label>
</div>

</body>

</html>

clean and simple.

C# Telnet Library

I doubt very much a telnet library will ever be part of the .Net BCL, although you do have almost full socket support so it wouldnt be too hard to emulate a telnet client, Telnet in its general implementation is a legacy and dying technology that where exists generally sits behind a nice new modern facade. In terms of Unix/Linux variants you'll find that out the box its SSH and enabling telnet is generally considered poor practice.

You could check out: http://granados.sourceforge.net/ - SSH Library for .Net http://www.tamirgal.com/home/dev.aspx?Item=SharpSsh

You'll still need to put in place your own wrapper to handle events for feeding in input in a scripted manner.

How can I undo a mysql statement that I just executed?

For some instrutions, like ALTER TABLE, this is not possible with MySQL, even with transactions (1 and 2).

How to throw a C++ exception

Wanted to ADD to the other answers described here an additional note, in the case of custom exceptions.

In the case where you create your own custom exception, that derives from std::exception, when you catch "all possible" exceptions types, you should always start the catch clauses with the "most derived" exception type that may be caught. See the example (of what NOT to do):

#include <iostream>
#include <string>

using namespace std;

class MyException : public exception
{
public:
    MyException(const string& msg) : m_msg(msg)
    {
        cout << "MyException::MyException - set m_msg to:" << m_msg << endl;
    }

   ~MyException()
   {
        cout << "MyException::~MyException" << endl;
   }

   virtual const char* what() const throw () 
   {
        cout << "MyException - what" << endl;
        return m_msg.c_str();
   }

   const string m_msg;
};

void throwDerivedException()
{
    cout << "throwDerivedException - thrown a derived exception" << endl;
    string execptionMessage("MyException thrown");
    throw (MyException(execptionMessage));
}

void illustrateDerivedExceptionCatch()
{
    cout << "illustrateDerivedExceptionsCatch - start" << endl;
    try 
    {
        throwDerivedException();
    }
    catch (const exception& e)
    {
        cout << "illustrateDerivedExceptionsCatch - caught an std::exception, e.what:" << e.what() << endl;
        // some additional code due to the fact that std::exception was thrown...
    }
    catch(const MyException& e)
    {
        cout << "illustrateDerivedExceptionsCatch - caught an MyException, e.what::" << e.what() << endl;
        // some additional code due to the fact that MyException was thrown...
    }

    cout << "illustrateDerivedExceptionsCatch - end" << endl;
}

int main(int argc, char** argv)
{
    cout << "main - start" << endl;
    illustrateDerivedExceptionCatch();
    cout << "main - end" << endl;
    return 0;
}

NOTE:

0) The proper order should be vice-versa, i.e.- first you catch (const MyException& e) which is followed by catch (const std::exception& e).

1) As you can see, when you run the program as is, the first catch clause will be executed (which is probably what you did NOT wanted in the first place).

2) Even though the type caught in the first catch clause is of type std::exception, the "proper" version of what() will be called - cause it is caught by reference (change at least the caught argument std::exception type to be by value - and you will experience the "object slicing" phenomena in action).

3) In case that the "some code due to the fact that XXX exception was thrown..." does important stuff WITH RESPECT to the exception type, there is misbehavior of your code here.

4) This is also relevant if the caught objects were "normal" object like: class Base{}; and class Derived : public Base {}...

5) g++ 7.3.0 on Ubuntu 18.04.1 produces a warning that indicates the mentioned issue:

In function ‘void illustrateDerivedExceptionCatch()’: item12Linux.cpp:48:2: warning: exception of type ‘MyException’ will be caught catch(const MyException& e) ^~~~~

item12Linux.cpp:43:2: warning: by earlier handler for ‘std::exception’ catch (const exception& e) ^~~~~

Again, I will say, that this answer is only to ADD to the other answers described here (I thought this point is worth mention, yet could not depict it within a comment).

JavaScript Adding an ID attribute to another created Element

Since id is an attribute don't create an id element, just do this:

myPara.setAttribute("id", "id_you_like");

How to force browser to download file?

Set content-type and other headers before you write the file out. For small files the content is buffered, and the browser gets the headers first. For big ones the data come first.

WCF timeout exception detailed investigation

You will also receive this error if you are passing an object back to the client that contains a property of type enum that is not set by default and that enum does not have a value that maps to 0. i.e enum MyEnum{ a=1, b=2};

You need to use a Theme.AppCompat theme (or descendant) with this activity

I had the same problem, but it solved when i put this on manifest: android:theme="@style/Theme.AppCompat.

    <application
        android:allowBackup="true"
        android:icon="@drawable/icon"
        android:label="@string/app_name_test"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat">

        ...    

    </application>

Convert Data URI to File then append to FormData

My preferred way is canvas.toBlob()

But anyhow here is yet another way to convert base64 to a blob using fetch ^^,

_x000D_
_x000D_
var url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="_x000D_
_x000D_
fetch(url)_x000D_
.then(res => res.blob())_x000D_
.then(blob => {_x000D_
  var fd = new FormData()_x000D_
  fd.append('image', blob, 'filename')_x000D_
  _x000D_
  console.log(blob)_x000D_
_x000D_
  // Upload_x000D_
  // fetch('upload', {method: 'POST', body: fd})_x000D_
})
_x000D_
_x000D_
_x000D_

'was not declared in this scope' error

Here's a simplified example based on of your problem:

if (test) 
{//begin scope 1
    int y = 1; 
}//end scope 1
else 
{//begin scope 2
    int y = 2;//error, y is not in scope
}//end scope 2
int x = y;//error, y is not in scope

In the above version you have a variable called y that is confined to scope 1, and another different variable called y that is confined to scope 2. You then try to refer to a variable named y after the end of the if, and not such variable y can be seen because no such variable exists in that scope.

You solve the problem by placing y in the outermost scope which contains all references to it:

int y;
if (test) 
{
    y = 1; 
}
else 
{
    y = 2;
}
int x = y;

I've written the example with simplified made up code to make it clearer for you to understand the issue. You should now be able to apply the principle to your code.

How to create a new object instance from a Type

I can across this question because I was looking to implement a simple CloneObject method for arbitrary class (with a default constructor)

With generic method you can require that the type implements New().

Public Function CloneObject(Of T As New)(ByVal src As T) As T
    Dim result As T = Nothing
    Dim cloneable = TryCast(src, ICloneable)
    If cloneable IsNot Nothing Then
        result = cloneable.Clone()
    Else
        result = New T
        CopySimpleProperties(src, result, Nothing, "clone")
    End If
    Return result
End Function

With non-generic assume the type has a default constructor and catch an exception if it doesn't.

Public Function CloneObject(ByVal src As Object) As Object
    Dim result As Object = Nothing
    Dim cloneable As ICloneable
    Try
        cloneable = TryCast(src, ICloneable)
        If cloneable IsNot Nothing Then
            result = cloneable.Clone()
        Else
            result = Activator.CreateInstance(src.GetType())
            CopySimpleProperties(src, result, Nothing, "clone")
        End If
    Catch ex As Exception
        Trace.WriteLine("!!! CloneObject(): " & ex.Message)
    End Try
    Return result
End Function

How to use Google Translate API in my Java application?

Generate your own API key here. Check out the documentation here.

You may need to set up a billing account when you try to enable the Google Cloud Translation API in your account.

Below is a quick start example which translates two English strings to Spanish:

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.translate.Translate;
import com.google.api.services.translate.model.TranslationsListResponse;
import com.google.api.services.translate.model.TranslationsResource;

public class QuickstartSample
{
    public static void main(String[] arguments) throws IOException, GeneralSecurityException
    {
        Translate t = new Translate.Builder(
                GoogleNetHttpTransport.newTrustedTransport()
                , GsonFactory.getDefaultInstance(), null)
                // Set your application name
                .setApplicationName("Stackoverflow-Example")
                .build();
        Translate.Translations.List list = t.new Translations().list(
                Arrays.asList(
                        // Pass in list of strings to be translated
                        "Hello World",
                        "How to use Google Translate from Java"),
                // Target language
                "ES");

        // TODO: Set your API-Key from https://console.developers.google.com/
        list.setKey("your-api-key");
        TranslationsListResponse response = list.execute();
        for (TranslationsResource translationsResource : response.getTranslations())
        {
            System.out.println(translationsResource.getTranslatedText());
        }
    }
}

Required maven dependencies for the code snippet:

<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-translate</artifactId>
    <version>LATEST</version>
</dependency>

<dependency>
    <groupId>com.google.http-client</groupId>
    <artifactId>google-http-client-gson</artifactId>
    <version>LATEST</version>
</dependency>

JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined

You did not include jquery library. In jsfiddle its already there. Just include this line in your head section.

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">

Scope 'session' is not active for the current thread; IllegalStateException: No thread-bound request found

https://stackoverflow.com/a/30640097/2569475

For This Issue check My answer at above given url

Using a request scoped bean outside of an actual web request

Saving response from Requests to file

I believe all the existing answers contain the relevant information, but I would like to summarize.

The response object that is returned by requests get and post operations contains two useful attributes:

Response attributes

  • response.text - Contains str with the response text.
  • response.content - Contains bytes with the raw response content.

You should choose one or other of these attributes depending on the type of response you expect.

  • For text-based responses (html, json, yaml, etc) you would use response.text
  • For binary-based responses (jpg, png, zip, xls, etc) you would use response.content.

Writing response to file

When writing responses to file you need to use the open function with the appropriate file write mode.

  • For text responses you need to use "w" - plain write mode.
  • For binary responses you need to use "wb" - binary write mode.

Examples

Text request and save

# Request the HTML for this web page:
response = requests.get("https://stackoverflow.com/questions/31126596/saving-response-from-requests-to-file")
with open("response.txt", "w") as f:
    f.write(response.text)

Binary request and save

# Request the profile picture of the OP:
response = requests.get("https://i.stack.imgur.com/iysmF.jpg?s=32&g=1")
with open("response.jpg", "wb") as f:
    f.write(response.content)

Answering the original question

The original code should work by using wb and response.content:

import requests

files = {'f': ('1.pdf', open('1.pdf', 'rb'))}
response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)
response.raise_for_status() # ensure we notice bad responses
file = open("out.xls", "wb")
file.write(response.content)
file.close()

But I would go further and use the with context manager for open.

import requests

with open('1.pdf', 'rb') as file:
    files = {'f': ('1.pdf', file)}
    response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)

response.raise_for_status() # ensure we notice bad responses

with open("out.xls", "wb") as file:
    file.write(response.content)

How to change background and text colors in Sublime Text 3

I had the same issue. Sublime3 no longer shows all of the installed packages when you choose Show Packages from the Preferences Menu.

To customise a colour scheme do the following (UNIX):

  • Locate your SublimeText packages directory under the directory which SublimeText is installed in (in my setup this was /opt/sublime/Packages)
  • Open "Color Scheme - Default.sublime-package"
  • Choose the colour scheme which is closest to your requirements and copy it
  • From Sublime Text choose Preferences - Browse Packages - User
  • Paste the colour scheme you copied earlier here and rename it. It should now show up on your "Preferences - Color Scheme" menu under "User"
  • Follow the instructions at the link you previously mentioned to make the changes you require (Sublime 2 -changing background color based on file type?)

--- EDIT ---

For Mac OS X the themes are stored in zipped files so although the preferences file shows them as being in Packages/Color Scheme - Default/ they don't appear in that directory unless you extract them.

  • They can be extracted using the Package Resource Viewer (See this answer for how to install and use the Package Resource Viewer).
  • Search for Color Scheme in the Package Extractor (should give options for Color Scheme Default and Color Scheme legacy)
  • Extract the one you want. It will now be available at users/UserName/Library/Application Support/Sublime Text 3/Packages/Color Scheme - Default (or Legacy)
  • Make a copy of the scheme you want to modify, edit as needed and save it
  • Add or change the line in user preferences which points to the color scheme

for example

"color_scheme": "Packages/Color Scheme - Legacy/myTheme.tmTheme"

How to sort a file in-place

Here's an approach which (ab)uses vim:

vim -c :sort -c :wq -E -s "${filename}"

The -c :sort -c :wq portion invokes commands to vim after the file opens. -E and -s are necessary so that vim executes in a "headless" mode which doesn't draw to the terminal.

This has almost no benefits over the sort -o "${filename}" "${filename}" approach except that it only takes the filename argument once.


This was useful for me to implement a formatter directive in a nanorc entry for .gitignore files. Here's what I used for that:

syntax "gitignore" "\.gitignore$"

formatter vim -c :sort -c :wq -E -s

How to delete all the rows in a table using Eloquent?

In my case laravel 4.2 delete all rows ,but not truncate table

DB::table('your_table')->delete();

Python find elements in one list that are not in the other

TL;DR:
SOLUTION (1)

import numpy as np
main_list = np.setdiff1d(list_2,list_1)
# yields the elements in `list_2` that are NOT in `list_1`

SOLUTION (2) You want a sorted list

def setdiff_sorted(array1,array2,assume_unique=False):
    ans = np.setdiff1d(array1,array2,assume_unique).tolist()
    if assume_unique:
        return sorted(ans)
    return ans
main_list = setdiff_sorted(list_2,list_1)




EXPLANATIONS:
(1) You can use NumPy's setdiff1d (array1,array2,assume_unique=False).

assume_unique asks the user IF the arrays ARE ALREADY UNIQUE.
If False, then the unique elements are determined first.
If True, the function will assume that the elements are already unique AND function will skip determining the unique elements.

This yields the unique values in array1 that are not in array2. assume_unique is False by default.

If you are concerned with the unique elements (based on the response of Chinny84), then simply use (where assume_unique=False => the default value):

import numpy as np
list_1 = ["a", "b", "c", "d", "e"]
list_2 = ["a", "f", "c", "m"] 
main_list = np.setdiff1d(list_2,list_1)
# yields the elements in `list_2` that are NOT in `list_1`


(2) For those who want answers to be sorted, I've made a custom function:

import numpy as np
def setdiff_sorted(array1,array2,assume_unique=False):
    ans = np.setdiff1d(array1,array2,assume_unique).tolist()
    if assume_unique:
        return sorted(ans)
    return ans

To get the answer, run:

main_list = setdiff_sorted(list_2,list_1)

SIDE NOTES:
(a) Solution 2 (custom function setdiff_sorted) returns a list (compared to an array in solution 1).

(b) If you aren't sure if the elements are unique, just use the default setting of NumPy's setdiff1d in both solutions A and B. What can be an example of a complication? See note (c).

(c) Things will be different if either of the two lists is not unique.
Say list_2 is not unique: list2 = ["a", "f", "c", "m", "m"]. Keep list1 as is: list_1 = ["a", "b", "c", "d", "e"]
Setting the default value of assume_unique yields ["f", "m"] (in both solutions). HOWEVER, if you set assume_unique=True, both solutions give ["f", "m", "m"]. Why? This is because the user ASSUMED that the elements are unique). Hence, IT IS BETTER TO KEEP assume_unique to its default value. Note that both answers are sorted.

how can I enable PHP Extension intl?

I have seen the screen shoot, the issue you are having is missing msvcp110.dll , this file you can download from

https://www.dll-files.com/msvcp110.dll.html

and upload to C:/Windows folder

than after edit php.ini from XAMPP

Change

;extension=php_intl.dll

to

extension=php_intl.dll

Save the file and restart Apache from XAMPP

Convert command line argument to string

I'm not sure if this is 100% portable but the way the OS SHOULD parse the args is to scan through the console command string and insert a nil-term char at the end of each token, and int main(int,char**) doesn't use const char** so we can just iterate through the args starting from the third argument (@note the first arg is the working directory) and scan backward to the nil-term char and turn it into a space rather than start from beginning of the second argument and scanning forward to the nil-term char. Here is the function with test script, and if you do need to un-nil-ify more than one nil-term char then please comment so I can fix it; thanks.

#include <cstdio>
#include <iostream>

using namespace std;

namespace _ {
/* Converts int main(int,char**) arguments back into a string.
@return false if there are no args to convert.
@param arg_count The number of arguments.
@param args      The arguments. */
bool ArgsToString(int args_count, char** args) {
  if (args_count <= 1) return false;
  if (args_count == 2) return true;
  for (int i = 2; i < args_count; ++i) {
    char* cursor = args[i];
    while (*cursor) --cursor;
    *cursor = ' ';
  }
  return true;
}
}  // namespace _

int main(int args_count, char** args) {
  cout << "\n\nTesting ArgsToString...\n";

  if (args_count <= 1) return 1;
  cout << "\nArguments:\n";
  for (int i = 0; i < args_count; ++i) {
    char* arg = args[i];
    printf("\ni:%i\"%s\" 0x%p", i, arg, arg);
  }
  cout << "\n\nContiguous Args:\n";
  char* end = args[args_count - 1];
  while (*end) ++end;
  cout << "\n\nContiguous Args:\n";
  char* cursor = args[0];
  while (cursor != end) {
    char c = *cursor++;
    if (c == 0)
      cout << '`';
    else if (c < ' ')
      cout << '~';
    else
      cout << c;
  }
  cout << "\n\nPrinting argument string...\n";
  _::ArgsToString(args_count, args);
  cout << "\n" << args[1];
  return 0;
}

Android sqlite how to check if a record exists

These are all good answers, however many forget to close the cursor and database. If you don't close the cursor or database you may run in to memory leaks.

Additionally:
You can get an error when searching by String that contains non alpha/numeric characters. For example: "1a5f9ea3-ec4b-406b-a567-e6927640db40". Those dashes (-) will cause an unrecognized token error. You can overcome this by putting the string in an array. So make it a habit to query like this:

public boolean hasObject(String id) {
    SQLiteDatabase db = getWritableDatabase();
    String selectString = "SELECT * FROM " + _TABLE + " WHERE " + _ID + " =?";

    // Add the String you are searching by here. 
    // Put it in an array to avoid an unrecognized token error 
    Cursor cursor = db.rawQuery(selectString, new String[] {id}); 

    boolean hasObject = false;
    if(cursor.moveToFirst()){
        hasObject = true;

        //region if you had multiple records to check for, use this region. 

        int count = 0;
        while(cursor.moveToNext()){
          count++;
        }
        //here, count is records found
        Log.d(TAG, String.format("%d records found", count));

        //endregion

    } 

    cursor.close();          // Dont forget to close your cursor
    db.close();              //AND your Database!
    return hasObject;
}

How to run server written in js with Node.js

If you are in a Linux container, such as on a Chromebook, you will need to manually browse to your localhost's address. I am aware the newer Chrome OS versions no longer have this problem, but on my Chromebook, I still had to manually browse to the localhost's address for your code to work.

To browse to your locahost's address, type this in command line: sudo ifconfig

and note the inet address under eth0.

Otherwise, as others have noted, simply type node.js filename and it will work as long as you point the browser to the proper address.

Hope this helps!

Keyboard shortcuts are not active in Visual Studio with Resharper installed

Updated Answer:

If the left corner shows it is a "Miscellaneous Files" on Visual Studio, you will want to make sure the current file is included in the project or not first, otherwise, ReSharper has no way to figure out the shortcut or even work. Visual Studio sometimes will not include the files in csproj

enter image description here

How to install a specific JDK on Mac OS X?

As the message says, you have to go to Apple, not Sun, for Java on the Mac. As far as I know, Apple JDK 6 is installed by default on Mac OS X 10.6 (Snow Leopard). Maybe you need to install the developer tools from your Mac OS X installation DVD (the dev tools are an optional install from the OS DVD).

See: http://developer.apple.com/java/

NOTE This answer from 16 Oct 2009 is now outdated; you can get the JDK for Mac OS X from the regular JDK download page on Oracle's website now.

Missing XML comment for publicly visible type or member

I wanted to add something to the answers listed here:

As Isak pointed out, the XML documentation is useful for Class Libraries, as it provides intellisense to any consumer within Visual Studio. Therefore, an easy and correct solution is to simply turn off documentation for any top-level project (such as UI, etc), which is not going to be implemented outside of its own project.

Additionally I wanted to point out that the warning only expresses on publicly visible members. So, if you setup your class library to only expose what it needs to, you can get by without documenting private and internal members.

Setting unique Constraint with fluent API?

@coni2k 's answer is correct however you must add [StringLength] attribute for it to work otherwise you will get an invalid key exception (Example bellow).

[StringLength(65)]
[Index("IX_FirstNameLastName", 1, IsUnique = true)]
public string FirstName { get; set; }

[StringLength(65)]
[Index("IX_FirstNameLastName", 2, IsUnique = true)]
public string LastName { get; set; }

horizontal scrollbar on top and bottom of table

To simulate a second horizontal scrollbar on top of an element, put a "dummy" div above the element that has horizontal scrolling, just high enough for a scrollbar. Then attach handlers of the "scroll" event for the dummy element and the real element, to get the other element in synch when either scrollbar is moved. The dummy element will look like a second horizontal scrollbar above the real element.

For a live example, see this fiddle

Here's the code:

HTML:

<div class="wrapper1">
  <div class="div1"></div>
</div>
<div class="wrapper2">
  <div class="div2">
    <!-- Content Here -->
  </div>
</div>

CSS:

.wrapper1, .wrapper2 {
  width: 300px;
  overflow-x: scroll;
  overflow-y:hidden;
}

.wrapper1 {height: 20px; }
.wrapper2 {height: 200px; }

.div1 {
  width:1000px;
  height: 20px;
}

.div2 {
  width:1000px;
  height: 200px;
  background-color: #88FF88;
  overflow: auto;
}

JS:

$(function(){
  $(".wrapper1").scroll(function(){
    $(".wrapper2").scrollLeft($(".wrapper1").scrollLeft());
  });
  $(".wrapper2").scroll(function(){
    $(".wrapper1").scrollLeft($(".wrapper2").scrollLeft());
  });
});

Forgot Oracle username and password, how to retrieve?

  1. Open your SQL command line and type the following:

    SQL> connect / as sysdba
    
  2. Once connected,you can enter the following query to get details of username and password:

    SQL> select username,password from dba_users;
    
  3. This will list down the usernames,but passwords would not be visible.But you can identify the particular username and then change the password for that user. For changing the password,use the below query:

    SQL> alter user username identified by password;
    
  4. Here username is the name of user whose password you want to change and password is the new password.

Simple pagination in javascript

I created a class structure for collections in general that would meet this requirement. and it looks like this:

class Collection {

    constructor() {
        this.collection = [];
        this.index = 0;
    }

    log() {
        return console.log(this.collection);
    }

    push(value) {
        return this.collection.push(value);
    }

    pushAll(...values) {
        return this.collection.push(...values);
    }

    pop() {
        return this.collection.pop();
    }

    shift() {
        return this.collection.shift();
    }

    unshift(value) {
        return this.collection.unshift(value);
    }

    unshiftAll(...values) {
        return this.collection.unshift(...values);
    }

    remove(index) {
        return this.collection.splice(index, 1);
    }

    add(index, value) {
        return this.collection.splice(index, 0, value);
    }

    replace(index, value) {
        return this.collection.splice(index, 1, value);
    }

    clear() {
        this.collection.length = 0;
    }

    isEmpty() {
        return this.collection.length === 0;
    }

    viewFirst() {
        return this.collection[0];
    }

    viewLast() {
        return this.collection[this.collection.length - 1];
    }

    current(){
        if((this.index <= this.collection.length - 1) && (this.index >= 0)){
            return this.collection[this.index];
        }
        else{
            return `Object index exceeds collection range.`;
        }
    }

    next() {
        this.index++;
        this.index > this.collection.length - 1 ? this.index = 0 : this.index;
        return this.collection[this.index];
    }

    previous(){
        this.index--;
        this.index < 0 ? (this.index = this.collection.length-1) : this.index;
        return this.collection[this.index];
    }
}

...and essentially what you would do is have a collection of arrays of whatever length for your pages pushed into the class object, and then use the next() and previous() functions to display whatever 'page' (index) you wanted to display. Would essentially look like this:

let books = new Collection();
let firstPage - [['dummyData'], ['dummyData'], ['dummyData'], ['dummyData'], ['dummyData'],];
let secondPage - [['dumberData'], ['dumberData'], ['dumberData'], ['dumberData'], ['dumberData'],];
books.pushAll(firstPage, secondPage); // loads each array individually
books.current() // display firstPage
books.next() // display secondPage

How to add Headers on RESTful call using Jersey Client API

If you want to add a header to all Jersey responses, you could also use a ContainerResponseFilter, from Jersey's filter documentation :

import java.io.IOException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.Response;

@Provider
public class PoweredByResponseFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
        throws IOException {

            responseContext.getHeaders().add("X-Powered-By", "Jersey :-)");
    }
}

Make sure that you initialize it correctly in your project using the @Provider annotation or through traditional ways with web.xml.

What's a .sh file?

open the location in terminal then type these commands 1. chmod +x filename.sh 2. ./filename.sh that's it

What is tail call optimization?

Look here:

http://tratt.net/laurie/tech_articles/articles/tail_call_optimization

As you probably know, recursive function calls can wreak havoc on a stack; it is easy to quickly run out of stack space. Tail call optimization is way by which you can create a recursive style algorithm that uses constant stack space, therefore it does not grow and grow and you get stack errors.

Convert file: Uri to File in Android

I made this like the following way:

try {
    readImageInformation(new File(contentUri.getPath()));

} catch (IOException e) {
    readImageInformation(new File(getRealPathFromURI(context,
                contentUri)));
}

public static String getRealPathFromURI(Context context, Uri contentUri) {
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = context.getContentResolver().query(contentUri, proj,
                null, null, null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
}

So basically first I try to use a file i.e. picture taken by camera and saved on SD card. This don't work for image returned by: Intent photoPickerIntent = new Intent(Intent.ACTION_PICK); That case there is a need to convert Uri to real path by getRealPathFromURI() function. So the conclusion is that it depends on what type of Uri you want to convert to File.

HTML input fields does not get focus when clicked

I had the same issue and the fix was to remove the placeholders and I changed the design of the form to use labels instead of placeholders...

Adding Google Play services version to your app's manifest?

I did following steps to recover from this:

1) Import google play services as project into your android sdk. In my system it is found at C:\adt-bundle-windows-x86_64-20140702\sdk\extras\google\google_play_services\libproject\google-play-services_lib

2) Your android application-> properties -> android

In the window

2.1) Click on Google APIs in project build target 2.2) Add google-play services in bottom frame and click on OK

Hope it gives clear instruction on what to do !!

Thanks.

How to split a comma-separated string?

In Kotlin,

val stringArray = commasString.replace(", ", ",").split(",")

where stringArray is List<String> and commasString is String with commas and spaces

Spring Boot - Error creating bean with name 'dataSource' defined in class path resource

Maybe you forgot the MySQL JDBC driver.

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.34</version>
</dependency>

Get checkbox value in jQuery

Despite the fact that this question is asking for a jQuery solution, here is a pure JavaScript answer since nobody has mentioned it.

Without jQuery:

Simply select the element and access the checked property (which returns a boolean).

_x000D_
_x000D_
var checkbox = document.querySelector('input[type="checkbox"]');_x000D_
_x000D_
alert(checkbox.checked);
_x000D_
<input type="checkbox"/>
_x000D_
_x000D_
_x000D_


Here is a quick example listening to the change event:

_x000D_
_x000D_
var checkbox = document.querySelector('input[type="checkbox"]');_x000D_
checkbox.addEventListener('change', function (e) {_x000D_
    alert(this.checked);_x000D_
});
_x000D_
<input type="checkbox"/>
_x000D_
_x000D_
_x000D_


To select checked elements, use the :checked pseudo class (input[type="checkbox"]:checked).

Here is an example that iterates over checked input elements and returns a mapped array of the checked element's names.

Example Here

var elements = document.querySelectorAll('input[type="checkbox"]:checked');
var checkedElements = Array.prototype.map.call(elements, function (el, i) {
    return el.name;
});

console.log(checkedElements);

_x000D_
_x000D_
var elements = document.querySelectorAll('input[type="checkbox"]:checked');_x000D_
var checkedElements = Array.prototype.map.call(elements, function (el, i) {_x000D_
    return el.name;_x000D_
});_x000D_
_x000D_
console.log(checkedElements);
_x000D_
<div class="parent">_x000D_
    <input type="checkbox" name="name1" />_x000D_
    <input type="checkbox" name="name2" />_x000D_
    <input type="checkbox" name="name3" checked="checked" />_x000D_
    <input type="checkbox" name="name4" checked="checked" />_x000D_
    <input type="checkbox" name="name5" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I use a third-party DLL file in Visual Studio C++?

You only need to use LoadLibrary if you want to late bind and only resolve the imported functions at runtime. The easiest way to use a third party dll is to link against a .lib.


In reply to your edit:

Yes, the third party API should consist of a dll and/or a lib that contain the implementation and header files that declares the required types. You need to know the type definitions whichever method you use - for LoadLibrary you'll need to define function pointers, so you could just as easily write your own header file instead. Basically, you only need to use LoadLibrary if you want late binding. One valid reason for this would be if you aren't sure if the dll will be available on the target PC.

How to "Open" and "Save" using java

I would suggest looking into javax.swing.JFileChooser

Here is a site with some examples in using as both 'Open' and 'Save'. http://www.java2s.com/Code/Java/Swing-JFC/DemonstrationofFiledialogboxes.htm

This will be much less work than implementing for yourself.

Git fatal: protocol 'https' is not supported

Problem is probably this.

You tried to paste it using

  • CTRL +V

before and it didn't work so you went ahead and pasted it with classic

  • Right Click - Paste**.

Sadly whenever you enter CTRL +V on terminal it adds

  • a hidden ^?

(at least on my machine it encoded like that).

the character that you only appears after you

  • backspace

(go ahead an try it on git bash).

So your link becomes ^?https://...

which is invalid.

Counting duplicates in Excel

  1. Highlight the column with the name
  2. Data > Pivot Table and Pivot Chart
  3. Next, Next layout
  4. drag the column title to the row section
  5. drag it again to the data section
  6. Ok > Finish

Replace Line Breaks in a String C#

Another option is to create a StringReader over the string in question. On the reader, do .ReadLine() in a loop. Then you have the lines separated, no matter what (consistent or inconsistent) separators they had. With that, you can proceed as you wish; one possibility is to use a StringBuilder and call .AppendLine on it.

The advantage is, you let the framework decide what constitutes a "line break".

Is it possible to assign a base class object to a derived class reference with an explicit typecast?

No, it is not possible.

Consider a scenario where an ACBus is a derived class of base class Bus. ACBus has features like TurnOnAC and TurnOffAC which operate on a field named ACState. TurnOnAC sets ACState to on and TurnOffAC sets ACState to off. If you try to use TurnOnAC and TurnOffAC features on Bus, it makes no sense.

Unit testing private methods in C#

Another option that has not been mentioned is just creating the unit test class as a child of the object that you are testing. NUnit Example:

[TestFixture]
public class UnitTests : ObjectWithPrivateMethods
{
    [Test]
    public void TestSomeProtectedMethod()
    {
        Assert.IsTrue(this.SomeProtectedMethod() == true, "Failed test, result false");
    }
}

This would allow easy testing of private and protected (but not inherited private) methods, and it would allow you to keep all your tests separate from the real code so you aren't deploying test assemblies to production. Switching your private methods to protected methods would be acceptable in a lot of inherited objects, and it is a pretty simple change to make.

HOWEVER...

While this is an interesting approach to solving the problem of how to test hidden methods, I am unsure that I would advocate that this is the correct solution to the problem in all cases. It seems a little odd to be internally testing an object, and I suspect there might be some scenarios that this approach will blow up on you. (Immutable objects for example, might make some tests really hard).

While I mention this approach, I would suggest that this is more of a brainstormed suggestion than a legitimate solution. Take it with a grain of salt.

EDIT: I find it truly hilarious that people are voting this answer down, since I explicitly describe this as a bad idea. Does that mean that people are agreeing with me? I am so confused.....

Best way to pass parameters to jQuery's .load()

In the first case, the data are passed to the script via GET, in the second via POST.

http://docs.jquery.com/Ajax/load#urldatacallback

I don't think there are limits to the data size, but the completition of the remote call will of course take longer with great amount of data.

Bash function to find newest file matching pattern

Use the find command.

Assuming you're using Bash 4.2+, use -printf '%T+ %p\n' for file timestamp value.

find $DIR -type f -printf '%T+ %p\n' | sort -r | head -n 1 | cut -d' ' -f2

Example:

find ~/Downloads -type f -printf '%T+ %p\n' | sort -r | head -n 1 | cut -d' ' -f2

For a more useful script, see the find-latest script here: https://github.com/l3x/helpers

Ruby - test for array

You probably want to use kind_of().

>> s = "something"
=> "something"
>> s.kind_of?(Array)
=> false
>> s = ["something", "else"]
=> ["something", "else"]
>> s.kind_of?(Array)
=> true

Check image width and height before upload with Javascript

function validateimg(ctrl) {

        var fileUpload = $("#txtPostImg")[0];


        var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(.jpg|.png|.gif)$");
        if (regex.test(fileUpload.value.toLowerCase())) {

            if (typeof (fileUpload.files) != "undefined") {

                var reader = new FileReader();

                reader.readAsDataURL(fileUpload.files[0]);
                reader.onload = function (e) {

                    var image = new Image();

                    image.src = e.target.result;
                    image.onload = function () {

                        var height = this.height;
                        var width = this.width;
                        console.log(this);
                        if ((height >= 1024 || height <= 1100) && (width >= 750 || width <= 800)) {
                            alert("Height and Width must not exceed 1100*800.");
                            return false;
                        }
                        alert("Uploaded image has valid Height and Width.");
                        return true;
                    };
                }
            } else {
                alert("This browser does not support HTML5.");
                return false;
            }
        } else {
            alert("Please select a valid Image file.");
            return false;
        }
    }

How I can delete in VIM all text from current line to end of file?

Go to the first line from which you would like to delete, and press the keys dG

How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?

This feature is called "strict null checks", to turn it off ensure that the --strictNullChecks compiler flag is not set.

However, the existence of null has been described as The Billion Dollar Mistake, so it is exciting to see languages such as TypeScript introducing a fix. I'd strongly recommend keeping it turned on.

One way to fix this is to ensure that the values are never null or undefined, for example by initialising them up front:

interface SelectProtected {
    readonly wrapperElement: HTMLDivElement;
    readonly inputElement: HTMLInputElement;
}

const selectProtected: SelectProtected = {
    wrapperElement: document.createElement("div"),
    inputElement: document.createElement("input")
};

See Ryan Cavanaugh's answer for an alternative option, though!

Check if decimal value is null

Assuming you are reading from a data row, what you want is:

if ( !rdrSelect.IsNull(23) ) 
{ 
   //handle parsing
}

@try - catch block in Objective-C

All work perfectly :)

 NSString *test = @"test";
 unichar a;
 int index = 5;
    
 @try {
    a = [test characterAtIndex:index];
 }
 @catch (NSException *exception) {
    NSLog(@"%@", exception.reason);
    NSLog(@"Char at index %d cannot be found", index);
    NSLog(@"Max index is: %lu", [test length] - 1);
 }
 @finally {
    NSLog(@"Finally condition");
 }

Log:

[__NSCFConstantString characterAtIndex:]: Range or index out of bounds

Char at index 5 cannot be found

Max index is: 3

Finally condition

Changing the maximum length of a varchar column?

ALTER TABLE TABLE_NAME MODIFY COLUMN_NAME VARCHAR(40);

Late to the question - but I am using Oracle SQL Developer and @anonymous's answer was the closest but kept receiving syntax errors until I edited the query to this.

Hope this helps someone

java- reset list iterator to first element of the list

Best would be not using LinkedList at all, usually it is slower in all disciplines, and less handy. (When mainly inserting/deleting to the front, especially for big arrays LinkedList is faster)

Use ArrayList, and iterate with

int len = list.size();
for (int i = 0; i < len; i++) {
  Element ele = list.get(i);
}

Reset is trivial, just loop again.
If you insist on using an iterator, then you have to use a new iterator:

iter = list.listIterator();

(I saw only once in my life an advantage of LinkedList: i could loop through whith a while loop and remove the first element)

jQuery: load txt file and insert into div

You can use jQuery load method to get the contents and insert into an element.

Try this:

$(document).ready(function() {
        $("#lesen").click(function() {
                $(".text").load("helloworld.txt");
    }); 
}); 

You, can also add a call back to execute something once the load process is complete

e.g:

$(document).ready(function() {
    $("#lesen").click(function() {
        $(".text").load("helloworld.txt", function(){
            alert("Done Loading");
        });
   }); 
}); 

add to array if it isn't there already

Try adding as key instead of value:

Adding an entry

function addEntry($entry) {
    $this->entries[$entry] = true;
}

Getting all entries

function getEntries() {
    return array_keys($this->enties);
}

git pull keeping local changes

We can also try git pull with rebase

git pull --rebase origin dev

Height equal to dynamic width (CSS fluid layout)

Expanding upon the padding top/bottom technique, it is possible to use a pseudo element to set the height of the element. Use float and negative margins to remove the pseudo element from the flow and view.

This allows you to place content inside the box without using an extra div and/or CSS positioning.

_x000D_
_x000D_
.fixed-ar::before {_x000D_
  content: "";_x000D_
  float: left;_x000D_
  width: 1px;_x000D_
  margin-left: -1px;_x000D_
}_x000D_
.fixed-ar::after {_x000D_
  content: "";_x000D_
  display: table;_x000D_
  clear: both;_x000D_
}_x000D_
_x000D_
_x000D_
/* proportions */_x000D_
_x000D_
.fixed-ar-1-1::before {_x000D_
  padding-top: 100%;_x000D_
}_x000D_
.fixed-ar-4-3::before {_x000D_
  padding-top: 75%;_x000D_
}_x000D_
.fixed-ar-16-9::before {_x000D_
  padding-top: 56.25%;_x000D_
}_x000D_
_x000D_
_x000D_
/* demo */_x000D_
_x000D_
.fixed-ar {_x000D_
  margin: 1em 0;_x000D_
  max-width: 400px;_x000D_
  background: #EEE url(https://lorempixel.com/800/450/food/5/) center no-repeat;_x000D_
  background-size: contain;_x000D_
}
_x000D_
<div class="fixed-ar fixed-ar-1-1">1:1 Aspect Ratio</div>_x000D_
<div class="fixed-ar fixed-ar-4-3">4:3 Aspect Ratio</div>_x000D_
<div class="fixed-ar fixed-ar-16-9">16:9 Aspect Ratio</div>
_x000D_
_x000D_
_x000D_

What is the `zero` value for time.Time in Go?

Invoking an empty time.Time struct literal will return Go's zero date. Thus, for the following print statement:

fmt.Println(time.Time{})

The output is:

0001-01-01 00:00:00 +0000 UTC

For the sake of completeness, the official documentation explicitly states:

The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC.

PopupWindow $BadTokenException: Unable to add window -- token null is not valid

Try to show the pop like below

findViewById(R.id.main_layout).post(new Runnable() {
        public void run() {
            mPopupWindow.showAtLocation(findViewById(R.id.main_layout), Gravity.CENTER, 0, 0);
            Button close = (Button) customView.findViewById(R.id.btn_ok);
            close.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mPopupWindow.dismiss();
                    doOtherStuff();
                }
            });
        }
    });

Should I use Python 32bit or Python 64bit

You do not need to use 64bit since windows will emulate 32bit programs using wow64. But using the native version (64bit) will give you more performance.

Batch not-equal (inequality) operator

I know this is quite out of date, but this might still be useful for those coming late to the party. (EDIT: updated since this still gets traffic and @Goozak has pointed out in the comments that my original analysis of the sample was incorrect as well.)

I pulled this from the example code in your link:

IF !%1==! GOTO VIEWDATA
REM  IF NO COMMAND-LINE ARG...
FIND "%1" C:\BOZO\BOOKLIST.TXT
GOTO EXIT0
REM  PRINT LINE WITH STRING MATCH, THEN EXIT.

:VIEWDATA
TYPE C:\BOZO\BOOKLIST.TXT | MORE
REM  SHOW ENTIRE FILE, 1 PAGE AT A TIME.

:EXIT0

!%1==! is simply an idiomatic use of == intended to verify that the thing on the left, that contains your variable, is different from the thing on the right, that does not. The ! in this case is just a character placeholder. It could be anything. If %1 has content, then the equality will be false, if it does not you'll just be comparing ! to ! and it will be true.

!==! is not an operator, so writing "asdf" !==! "fdas" is pretty nonsensical.

The suggestion to use if not "asdf" == "fdas" is definitely the way to go.

How to sort an object array by date property?

If like me you have an array with dates formatted like YYYY[-MM[-DD]] where you'd like to order more specific dates before less specific ones, I came up with this handy function:

function sortByDateSpecificity(a, b) {
  const aLength = a.date.length
  const bLength = b.date.length
  const aDate = a.date + (aLength < 10 ? '-12-31'.slice(-10 + aLength) : '')
  const bDate = b.date + (bLength < 10 ? '-12-31'.slice(-10 + bLength) : '')
  return new Date(aDate) - new Date(bDate)
}

How to change users in TortoiseSVN

Replace the line in htpasswd file:

Go to: http://www.htaccesstools.com/htpasswd-generator-windows/

(If the link is expired, search another generator from google.com.)

Enter your username and password. The site will generate an encrypted line. Copy that line and replace it with the previous line in the file "repo/htpasswd".

You might also need to Clear the 'Authentication data' from TortoiseSVN ? Settings ? Saved Data.

Only Add Unique Item To List

Just like the accepted answer says a HashSet doesn't have an order. If order is important you can continue to use a List and check if it contains the item before you add it.

if (_remoteDevices.Contains(rDevice))
    _remoteDevices.Add(rDevice);

Performing List.Contains() on a custom class/object requires implementing IEquatable<T> on the custom class or overriding the Equals. It's a good idea to also implement GetHashCode in the class as well. This is per the documentation at https://msdn.microsoft.com/en-us/library/ms224763.aspx

public class RemoteDevice: IEquatable<RemoteDevice>
{
    private readonly int id;
    public RemoteDevice(int uuid)
    {
        id = id
    }
    public int GetId
    {
        get { return id; }
    }

    // ...

    public bool Equals(RemoteDevice other)
    {
        if (this.GetId == other.GetId)
            return true;
        else
            return false;
    }
    public override int GetHashCode()
    {
        return id;
    }
}

Trying to retrieve first 5 characters from string in bash error?

Depending on your shell, you may be able to use the following syntax:

expr substr $string $position $length

So for your example:

TESTSTRINGONE="MOTEST"
echo `expr substr ${TESTSTRINGONE} 0 5`

Alternatively,

echo 'MOTEST' | cut -c1-5

or

echo 'MOTEST' | awk '{print substr($0,0,5)}'

How to format a duration in java? (e.g format H:MM:SS)

Here is one more sample how to format duration. Note that this sample shows both positive and negative duration as positive duration.

import static java.time.temporal.ChronoUnit.DAYS;
import static java.time.temporal.ChronoUnit.HOURS;
import static java.time.temporal.ChronoUnit.MINUTES;
import static java.time.temporal.ChronoUnit.SECONDS;

import java.time.Duration;

public class DurationSample {
    public static void main(String[] args) {
        //Let's say duration of 2days 3hours 12minutes and 46seconds
        Duration d = Duration.ZERO.plus(2, DAYS).plus(3, HOURS).plus(12, MINUTES).plus(46, SECONDS);

        //in case of negative duration
        if(d.isNegative()) d = d.negated();

        //format DAYS HOURS MINUTES SECONDS 
        System.out.printf("Total duration is %sdays %shrs %smin %ssec.\n", d.toDays(), d.toHours() % 24, d.toMinutes() % 60, d.getSeconds() % 60);

        //or format HOURS MINUTES SECONDS 
        System.out.printf("Or total duration is %shrs %smin %sec.\n", d.toHours(), d.toMinutes() % 60, d.getSeconds() % 60);

        //or format MINUTES SECONDS 
        System.out.printf("Or total duration is %smin %ssec.\n", d.toMinutes(), d.getSeconds() % 60);

        //or format SECONDS only 
        System.out.printf("Or total duration is %ssec.\n", d.getSeconds());
    }
}

What is the difference between res.end() and res.send()?

res.send() will send the HTTP response. Its syntax is,

res.send([body])

The body parameter can be a Buffer object, a String, an object, or an Array. For example:

res.send(new Buffer('whoop'));
res.send({ some: 'json' });
res.send('<p>some html</p>');
res.status(404).send('Sorry, we cannot find that!');
res.status(500).send({ error: 'something blew up' });

See this for more info.

res.end() will end the response process. This method actually comes from Node core, specifically the response.end() method of http.ServerResponse. It is used to quickly end the response without any data. For example:

res.end();
res.status(404).end();

Read this for more info.

How do you import classes in JSP?

In the page tag:

<%@ page import="java.util.List" %>

JPA CascadeType.ALL does not delete orphans

If you are using JPA 2.0, you can now use the orphanRemoval=true attribute of the @xxxToMany annotation to remove orphans.

Actually, CascadeType.DELETE_ORPHAN has been deprecated in 3.5.2-Final.

Should I use `import os.path` or `import os`?

Couldn't find any definitive reference, but I see that the example code for os.walk uses os.path but only imports os

Drop-down box dependent on the option selected in another drop-down box

for this, I have noticed that it far better to show and hide the tags instead of adding and removing them for the DOM. It performs better that way.

Change color of PNG image via CSS?

I required a specific colour, so filter didn't work for me.

Instead, I created a div, exploiting CSS multiple background images and the linear-gradient function (which creates an image itself). If you use the overlay blend mode, your actual image will be blended with the generated "gradient" image containing your desired colour (here, #BADA55)

_x000D_
_x000D_
.colored-image {_x000D_
        background-image: linear-gradient(to right, #BADA55, #BADA55), url("https://i.imgur.com/lYXT8R6.png");_x000D_
        background-blend-mode: overlay;_x000D_
        background-size: contain;_x000D_
        width: 200px;_x000D_
        height: 200px;        _x000D_
    }
_x000D_
<div class="colored-image"></div>
_x000D_
_x000D_
_x000D_

Can Android do peer-to-peer ad-hoc networking?

Yes, but:
1. root your device (in case you've got Nexus S like me, see this)
2. install root explorer (search in market)
3. find appropriate wpa_supplcant file and replace (and backup) original as shown in this thread

above was tested on my Nexus S I9023 android 2.3.6

C free(): invalid pointer

You're attempting to free something that isn't a pointer to a "freeable" memory address. Just because something is an address doesn't mean that you need to or should free it.

There are two main types of memory you seem to be confusing - stack memory and heap memory.

  • Stack memory lives in the live span of the function. It's temporary space for things that shouldn't grow too big. When you call the function main, it sets aside some memory for your variables you've declared (p,token, and so on).

  • Heap memory lives from when you malloc it to when you free it. You can use much more heap memory than you can stack memory. You also need to keep track of it - it's not easy like stack memory!

You have a few errors:

  • You're trying to free memory that's not heap memory. Don't do that.

  • You're trying to free the inside of a block of memory. When you have in fact allocated a block of memory, you can only free it from the pointer returned by malloc. That is to say, only from the beginning of the block. You can't free a portion of the block from the inside.

For your bit of code here, you probably want to find a way to copy relevant portion of memory to somewhere else...say another block of memory you've set aside. Or you can modify the original string if you want (hint: char value 0 is the null terminator and tells functions like printf to stop reading the string).

EDIT: The malloc function does allocate heap memory*.

"9.9.1 The malloc and free Functions

The C standard library provides an explicit allocator known as the malloc package. Programs allocate blocks from the heap by calling the malloc function."

~Computer Systems : A Programmer's Perspective, 2nd Edition, Bryant & O'Hallaron, 2011

EDIT 2: * The C standard does not, in fact, specify anything about the heap or the stack. However, for anyone learning on a relevant desktop/laptop machine, the distinction is probably unnecessary and confusing if anything, especially if you're learning about how your program is stored and executed. When you find yourself working on something like an AVR microcontroller as H2CO3 has, it is definitely worthwhile to note all the differences, which from my own experience with embedded systems, extend well past memory allocation.

Trigger to fire only if a condition is met in SQL Server

Your where clause should have worked. I am at a loss as to why it didn't. Let me show you how I would have figured out the problem with the where clause as it might help you for the future.

When I create triggers, I start at the query window by creating a temp table called #inserted (and or #deleted) with all the columns of the table. Then I popultae it with typical values (Always multiple records and I try to hit the test cases in the values)

Then I write my triggers logic and I can test without it actually being in a trigger. In a case like your where clause not doing what was expected, I could easily test by commenting out the insert to see what the select was returning. I would then probably be easily able to see what the problem was. I assure you that where clasues do work in triggers if they are written correctly.

Once I know that the code works properly for all the cases, I global replace #inserted with inserted and add the create trigger code around it and voila, a tested trigger.

AS I said in a comment, I have a concern that the solution you picked will not work properly in a multiple record insert or update. Triggers should always be written to account for that as you cannot predict if and when they will happen (and they do happen eventually to pretty much every table.)

Android Facebook style slide

In June 2012, Google has added "templates" in the Eclipse ADT plugin, and there is a template called "master/detail flow" which does exactly that (based on fragmets)

MySQL Query - Records between Today and Last 30 Days

DATE_FORMAT returns a string, so you're using two strings in your BETWEEN clause, which isn't going to work as you expect.

Instead, convert the date to your format in the SELECT and do the BETWEEN for the actual dates. For example,

SELECT DATE_FORMAT(create_date, '%m/%d/%y') as create_date_formatted
FROM table
WHERE create_date BETWEEN (CURDATE() - INTERVAL 30 DAY) AND CURDATE()

Merge trunk to branch in Subversion

It is “old-fashioned” way to specify ranges of revisions you wish to merge. With 1.5+ you can use:

svn merge HEAD url/of/trunk path/to/branch/wc

Entity Framework Core: DbContextOptionsBuilder does not contain a definition for 'usesqlserver' and no extension method 'usesqlserver'

Wow so many answers yet none mentioned this Microsoft.EntityFrameworkCore.InMemory package!

Add the reference to this package: <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="2.2.2" /> and you should be good to go.

ImportError: Cannot import name X

This is a circular dependency. It can be solved without any structural modifications to the code. The problem occurs because in vector you demand that entity be made available for use immediately, and vice versa. The reason for this problem is that you asking to access the contents of the module before it is ready -- by using from x import y. This is essentially the same as

import x
y = x.y
del x

Python is able to detect circular dependencies and prevent the infinite loop of imports. Essentially all that happens is that an empty placeholder is created for the module (ie. it has no content). Once the circularly dependent modules are compiled it updates the imported module. This is works something like this.

a = module() # import a

# rest of module

a.update_contents(real_a)

For python to be able to work with circular dependencies you must use import x style only.

import x
class cls:
    def __init__(self):
        self.y = x.y

Since you are no longer referring to the contents of the module at the top level, python can compile the module without actually having to access the contents of the circular dependency. By top level I mean lines that will be executed during compilation as opposed to the contents of functions (eg. y = x.y). Static or class variables accessing the module contents will also cause problems.

javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

I was facing the similar type of issue: Code Snippet :

<c:forEach items="${orderList}" var="xx"> ${xx.id} <br>
</c:forEach>

There was a space after orderlist like this : "${orderList} " because of which the xx variable was getting coverted into String and was not able to call xx.id.

So make sure about space. They play crucial role sometimes. :p

$(document).on("click"... not working?

You are using the correct syntax for binding to the document to listen for a click event for an element with id="test-element".

It's probably not working due to one of:

  • Not using recent version of jQuery
  • Not wrapping your code inside of DOM ready
  • or you are doing something which causes the event not to bubble up to the listener on the document.

To capture events on elements which are created AFTER declaring your event listeners - you should bind to a parent element, or element higher in the hierarchy.

For example:

$(document).ready(function() {
    // This WILL work because we are listening on the 'document', 
    // for a click on an element with an ID of #test-element
    $(document).on("click","#test-element",function() {
        alert("click bound to document listening for #test-element");
    });

    // This will NOT work because there is no '#test-element' ... yet
    $("#test-element").on("click",function() {
        alert("click bound directly to #test-element");
    });

    // Create the dynamic element '#test-element'
    $('body').append('<div id="test-element">Click mee</div>');
});

In this example, only the "bound to document" alert will fire.

JSFiddle with jQuery 1.9.1

Loop through array of values with Arrow Function

One statement can be written as such:

someValues.forEach(x => console.log(x));

or multiple statements can be enclosed in {} like this:

someValues.forEach(x => { let a = 2 + x; console.log(a); });

return in for loop or outside loop

Since there is no issue with GC. I prefer this.

for(int i=0; i<array.length; ++i){
    if(array[i] == valueToFind)
        return true;
}

Jackson overcoming underscores in favor of camel-case

If its a spring boot application, In application.properties file, just use

spring.jackson.property-naming-strategy=SNAKE_CASE

Or Annotate the model class with this annotation.

@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)

Expected response code 250 but got code "535", with message "535-5.7.8 Username and Password not accepted

Gmail tends to block usage of mailing addresses which are being used in other applications as username for security reasons. Either you should create a new email address for mail purpose or you must go to the Less Secure App Access and turn on the access for less secure apps. Gmail will send you a mail for confirmation from where you can verify that those changes were made by yourself. Only then, you can use such mailing addresses for mailing purpose through applications.

Using pip behind a proxy with CNTLM

You can continue to use pip over HTTPS by adding your corporation's root certificate to the cacert.pem file in your site-packages/pip folder. Then configure pip to use your proxy by adding the following lines to ~/pip/pip.conf (or ~\pip\pip.ini if you're on Windows):

[global]
proxy = [user:passwd@]proxy.server:port

That's it. No need to use third party packages or give up HTTPS (of course, your network admin can still see what you're doing).

How to set environment via `ng serve` in Angular 6

For Angular 2 - 5 refer the article Multiple Environment in angular

For Angular 6 use ng serve --configuration=dev

Note: Refer the same article for angular 6 as well. But wherever you find --env instead use --configuration. That's works well for angular 6.

How to enable mod_rewrite for Apache 2.2

What worked for me (in ubuntu):

sudo su
cd /etc/apache2/mods-enabled
ln ../mods-available/rewrite.load rewrite.load

Also, as already mentioned, make sure AllowOverride all is set in the relevant section of /etc/apache2/sites-available/default

Is it correct to use alt tag for an anchor link?

No, an alt attribute (it would be an attribute, not a tag) is not allowed for an a element in any HTML specification or draft. And it does not seem to be recognized by any browser either as having any significance.

It’s a bit mystery why people try to use it, then, but the probable explanation is that they are doing so in analog with alt attribute for img elements, expecting to see a “tooltip” on mouseover. There are two things wrong with this. First, each element has attributes of its own, defined in the specs for each element. Second, the “tooltip” rendering of alt attributes in some ancient browsers is/was a quirk or even a bug, rather than something to be expected; the alt attribute is supposed to be presented to the user if and only if the image itself is not presented, for whatever reason.

To create a “tooltip”, use the title attribute instead or, much better, Google for "CSS tooltips" and use CSS-based tooltips of your preference (they can be characterized as hidden “layers” that become visible on mouseover).

Remove Duplicates from range of cells in excel vba

You need to tell the Range.RemoveDuplicates method what column to use. Additionally, since you have expressed that you have a header row, you should tell the .RemoveDuplicates method that.

Sub dedupe_abcd()
    Dim icol As Long

    With Sheets("Sheet1")   '<-set this worksheet reference properly!
        icol = Application.Match("abcd", .Rows(1), 0)
        With .Cells(1, 1).CurrentRegion
            .RemoveDuplicates Columns:=icol, Header:=xlYes
        End With
    End With
End Sub

Your original code seemed to want to remove duplicates from a single column while ignoring surrounding data. That scenario is atypical and I've included the surrounding data so that the .RemoveDuplicates process does not scramble your data. Post back a comment if you truly wanted to isolate the RemoveDuplicates process to a single column.

Detect end of ScrollView

I wanted to show/hide a FAB with an offset before the very bottom of the scrollview. This is the solution I came up with (Kotlin):

scrollview.viewTreeObserver.addOnScrollChangedListener {
    if (scrollview.scrollY < scrollview.getChildAt(0).bottom - scrollview.height - offset) {
        // fab.hide()
    } else {
        // fab.show()
    }
}

Usage of \b and \r in C

As for the meaning of each character described in C Primer Plus, what you expected is an 'correct' answer. It should be true for some computer architectures and compilers, but unfortunately not yours.

I wrote a simple c program to repeat your test, and got that 'correct' answer. I was using Mac OS and gcc. enter image description here

Also, I am very curious what is the compiler that you were using. :)

Reinitialize Slick js after successful ajax call

I was facing an issue where Slick carousel wasn't refreshing on new data, it was appending new slides to previous ones, I found an answer which solved my problem, it's very simple.

try unslick, then assign your new data which is being rendered inside slick carousel, and then initialize slick again. these were the steps for me:

jQuery('.class-or-#id').slick('unslick');
myData = my-new-data;
jQuery('.class-or-#id').slick({slick options});

Note: check slick website for syntax just in case. also make sure you are not using unslick before slick is even initialized, what that means is simply initialize (like this jquery('.my-class').slick({options}); the first ajax call and once it is initialized then follow above steps, you may wanna use if else

How to find substring from string?

In C, use the strstr() standard library function:

const char *str = "/user/desktop/abc/post/";
const int exists = strstr(str, "/abc/") != NULL;

Take care to not accidentally find a too-short substring (this is what the starting and ending slashes are for).

How do I open a Visual Studio project in design view?

My problem, it showed an error called "The class Form1 can be designed, but is not the first class in the file. Visual Studio requires that designers use the first class in the file. Move the class code so that it is the first class in the file and try loading the designer again. ". So I moved the Form class to the first one and it worked. :)

ASP.Net MVC: How to display a byte array image from model

You need to have a byte[] in your DB.

My byte[] is in my Person object:

public class Person
{
    public byte[] Image { get; set; }
}


You need to convert your byte[] in a String. So, I have in my controller :

String img = Convert.ToBase64String(person.Image);


Next, in my .cshtml file, my Model is a ViewModel. This is what I have in :

 public String Image { get; set; }


I use it like this in my .cshtml file:

<img src="@String.Format("data:image/jpg;base64,{0}", Model.Image)" />

"data:image/image file extension;base64,{0}, your image String"

I wish it will help someone !

How to replace multiple patterns at once with sed?

echo "C:\Users\San.Tan\My Folder\project1" | sed -e 's/C:\\/mnt\/c\//;s/\\/\//g'

replaces

C:\Users\San.Tan\My Folder\project1

to

mnt/c/Users/San.Tan/My Folder/project1

in case someone needs to replace windows paths to Windows Subsystem for Linux(WSL) paths

How does one target IE7 and IE8 with valid CSS?

Well you don't really have to worry about IE7 code not working in IE8 because IE8 has compatibility mode (it can render pages the same as IE7). But if you still want to target different versions of IE, a way that's been done for a while now is to either use conditional comments or begin your css rule with a * to target IE7 and below. Or you could pay attention to user agent on the servers and dish up a different CSS file based on that information.

How to place the ~/.composer/vendor/bin directory in your PATH?

The Composer bin directory is set and stored in bin-dir config variable and can be different depending on your setup. Running the command composer global config bin-dir --absolute will tell you the absolute path to your global composer bin directory. Using this command you can modify your .bash_profile to add it to your PATH exactly how it is configured.

# Add Composer bin-dir to PATH if it is installed.
command -v composer >/dev/null 2>&1 && {
        COMPOSER_BIN_DIR=$(composer global config bin-dir --absolute 2> /dev/null)
        PATH="$PATH:$COMPOSER_BIN_DIR";
}
export PATH

Get current URL path in PHP

<?php
function current_url()
{
    $url      = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    $validURL = str_replace("&", "&amp", $url);
    return $validURL;
}
//echo "page URL is : ".current_url();

$offer_url = current_url();

?>



<?php

if ($offer_url == "checking url name") {
?> <p> hi this is manip5595 </p>

<?php
}
?>

Confusing "duplicate identifier" Typescript error message

Closing the solution completely and rerunning the project solved my issue.

Get all directories within directory nodejs

Alternatively, if you are able to use external libraries, you can use filehound. It supports callbacks, promises and sync calls.

Using promises:

const Filehound = require('filehound');

Filehound.create()
  .path("MyFolder")
  .directory() // only search for directories
  .find()
  .then((subdirectories) => {
    console.log(subdirectories);
  });

Using callbacks:

const Filehound = require('filehound');

Filehound.create()
  .path("MyFolder")
  .directory()
  .find((err, subdirectories) => {
    if (err) return console.error(err);

    console.log(subdirectories);
  });

Sync call:

const Filehound = require('filehound');

const subdirectories = Filehound.create()
  .path("MyFolder")
  .directory()
  .findSync();

console.log(subdirectories);

For further information (and examples), check out the docs: https://github.com/nspragg/filehound

Disclaimer: I'm the author.

Chrome doesn't delete session cookies

Go to chrome://settings/content/cookies?search=cookies

Enable Clear cookies and site data when you quit Chrome.

Worked for me

How to unlock android phone through ADB

Tested in Nexus 5:

adb shell input keyevent 26 #Pressing the lock button
adb shell input touchscreen swipe 930 880 930 380 #Swipe UP
adb shell input text XXXX #Entering your passcode
adb shell input keyevent 66 #Pressing Enter

Worked for me.

Reading all files in a directory, store them in objects, and send the object

I just wrote this and it looks more clean to me:

_x000D_
_x000D_
const fs = require('fs');
const util = require('util');

const readdir = util.promisify(fs.readdir);
const readFile = util.promisify(fs.readFile);

const readFiles = async dirname => {
    try {
        const filenames = await readdir(dirname);
        console.log({ filenames });
        const files_promise = filenames.map(filename => {
            return readFile(dirname + filename, 'utf-8');
        });
        const response = await Promise.all(files_promise);
        //console.log({ response })
        //return response
        return filenames.reduce((accumlater, filename, currentIndex) => {
            const content = response[currentIndex];
            accumlater[filename] = {
                content,
            };
            return accumlater;
        }, {});
    } catch (error) {
        console.error(error);
    }
};

const main = async () => {

    const response = await readFiles(
        './folder-name',
    );
    console.log({ response });
};
_x000D_
_x000D_
_x000D_

You can modify the response format according to your need. The response format from this code will look like:

{
   "filename-01":{
      "content":"This is the sample content of the file"
   },
   "filename-02":{
      "content":"This is the sample content of the file"
   }
}

Java equivalent of unsigned long long?

Nope, there is not. You'll have to use the primitive long data type and deal with signedness issues, or use a class such as BigInteger.

How to make ConstraintLayout work with percentage values?

You can currently do this in a couple of ways.

One is to create guidelines (right-click the design area, then click add vertical/horizontal guideline). You can then click the guideline's "header" to change the positioning to be percentage based. Finally, you can constrain views to guidelines.

Another way is to position a view using bias (percentage) and to then anchor other views to that view.

That said, we have been thinking about how to offer percentage based dimensions. I can't make any promise but it's something we would like to add.

Git - how delete file from remote repository

Use commands :

git rm /path to file name /

followed by

git commit -m "Your Comment"

git push

your files will get deleted from the repository

How to get city name from latitude and longitude coordinates in Google Maps?

 com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(data);
        if("OK".equals(jsonObject.getString("status"))){
            String formatted_address;
            JSONArray results = jsonObject.getJSONArray("results");
            if(results != null && results.size() > 0){
                com.alibaba.fastjson.JSONObject object = results.getJSONObject(0);
                String addressComponents = object.getString("address_components");
                formatted_address = object.getString("formatted_address");
                Log.e("amaya","formatted_address="+formatted_address+"--url="+url);
                if(findCity){
                    boolean finded = false;
                    JSONArray ac = JSONArray.parseArray(addressComponents);
                    if(ac != null && ac.size() > 0){
                        for(int i=0;i<ac.size();i++){
                            com.alibaba.fastjson.JSONObject jo = ac.getJSONObject(i);
                            JSONArray types = jo.getJSONArray("types");
                            if(types != null && types.size() > 0){
                                for(int j=0;j<ac.size();j++){
                                    String string = types.getString(i);
                                    if("administrative_area_level_1".equals(string)){
                                        finded = true;
                                        break;
                                    }
                                }
                            }
                            if(finded) break;
                        }
                    }
                    Log.e("amaya","city="+formatted_address);
                }else{
                    Log.e("amaya","poiName="+hotspotPoi.getPoi_name()+"--"+hotspotPoi);
                }
                if(hotspotPoi != null) hotspotPoi.setPoi_name(formatted_address);
                EventBus.getDefault().post(new AmayaEvent.GeoEvent(hotspotPoi));
            }
        }

this is a method to parse google feedback data.

regular expression for Indian mobile numbers

In Swift

 extension String {
    var isPhoneNumber: Bool {
      let PHONE_REGEX = "^[7-9][0-9]{9}$";
      let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
      let result =  phoneTest.evaluate(with: self)
      return result
   }
}

Iterating through struct fieldnames in MATLAB

Since fields or fns are cell arrays, you have to index with curly brackets {} in order to access the contents of the cell, i.e. the string.

Note that instead of looping over a number, you can also loop over fields directly, making use of a neat Matlab features that lets you loop through any array. The iteration variable takes on the value of each column of the array.

teststruct = struct('a',3,'b',5,'c',9)

fields = fieldnames(teststruct)

for fn=fields'
  fn
  %# since fn is a 1-by-1 cell array, you still need to index into it, unfortunately
  teststruct.(fn{1})
end

How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?

I had the same problem and I chosed to create my own encoder, which will cope by themself with recursion.

I created classes which implements Symfony\Component\Serializer\Normalizer\NormalizerInterface, and a service which holds every NormalizerInterface.

#This is the NormalizerService

class NormalizerService 
{

   //normalizer are stored in private properties
   private $entityOneNormalizer;
   private $entityTwoNormalizer;

   public function getEntityOneNormalizer()
   {
    //Normalizer are created only if needed
    if ($this->entityOneNormalizer == null)
        $this->entityOneNormalizer = new EntityOneNormalizer($this); //every normalizer keep a reference to this service

    return $this->entityOneNormalizer;
   }

   //create a function for each normalizer



  //the serializer service will also serialize the entities 
  //(i found it easier, but you don't really need it)
   public function serialize($objects, $format)
   {
     $serializer = new Serializer(
            array(
                $this->getEntityOneNormalizer(),
                $this->getEntityTwoNormalizer()
            ),
            array($format => $encoder) );

     return $serializer->serialize($response, $format);
}

An example of a Normalizer :

use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

class PlaceNormalizer implements NormalizerInterface {

private $normalizerService;

public function __construct($normalizerService)
{
    $this->service = normalizerService;

}

public function normalize($object, $format = null) {
    $entityTwo = $object->getEntityTwo();
    $entityTwoNormalizer = $this->service->getEntityTwoNormalizer();

    return array(
        'param' => object->getParam(),
        //repeat for every parameter
        //!!!! this is where the entityOneNormalizer dealt with recursivity
        'entityTwo' => $entityTwoNormalizer->normalize($entityTwo, $format.'_without_any_entity_one') //the 'format' parameter is adapted for ignoring entity one - this may be done with different ways (a specific method, etc.)
    );
}

}

In a controller :

$normalizerService = $this->get('normalizer.service'); //you will have to configure services.yml
$json = $normalizerService->serialize($myobject, 'json');
return new Response($json);

The complete code is here : https://github.com/progracqteur/WikiPedale/tree/master/src/Progracqteur/WikipedaleBundle/Resources/Normalizer

How to convert map to url query string?

Personally, I'd go for a solution like this, it's incredibly similar to the solution provided by @rzwitserloot, only subtle differences.

This solution is small, simple & clean, it requires very little in terms of dependencies, all of which are a part of the Java Util package.

Map<String, String> map = new HashMap<>();

map.put("param1", "12");
map.put("param2", "cat");

String output = "someUrl?";
output += map.entrySet()
    .stream()
    .map(x -> x.getKey() + "=" + x.getValue() + "&")
    .collect(Collectors.joining("&"));

System.out.println(output.substring(0, output.length() -1));

How do I undo a checkout in git?

You probably want git checkout master, or git checkout [branchname].

Set font-weight using Bootstrap classes

I found this on the Bootstrap website, but it really isn't a Bootstrap class, it's just HTML.

<strong>rendered as bold text</strong>

Why is this error, 'Sequence contains no elements', happening?

In the following line.

temp.Response = db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).First();

You are calling First but the collection returned from db.Responses.Where is empty.

How do I set 'semi-bold' font via CSS? Font-weight of 600 doesn't make it look like the semi-bold I see in my Photoshop file

In CSS, for the font-weight property, the value: normal defaults to the numeric value 400, and bold to 700.

If you want to specify other weights, you need to give the number value. That number value needs to be supported for the font family that you are using.

For example you would define semi-bold like this:

font-weight: 600;

Here an JSFiddle using 'Open Sans' font family, loaded with the above weights.

How to get id from URL in codeigniter?

I think you're using the CodeIgniter URI routing wrong: http://ellislab.com/codeigniter%20/user-guide/general/routing.html

Basically if you had a Products_controller with a method called delete($id) and the url you created was of the form http://localhost/designs2/index.php/products_controller/delete/4, the delete function would receive the $id as a parameter.

Using what you have there I think you can get the id by using $this->input->get('product_id);

How to SELECT based on value of another SELECT

SELECT x.name, x.summary, (x.summary / COUNT(*)) as percents_of_total
FROM tbl t
INNER JOIN 
(SELECT name, SUM(value) as summary
FROM tbl
WHERE year BETWEEN 2000 AND 2001
GROUP BY name) x ON x.name = t.name
GROUP BY x.name, x.summary

SQL Inner join 2 tables with multiple column conditions and update

UPDATE T1,T2 
INNER JOIN T1 ON  T1.Brands = T2.Brands
SET 
T1.Inci = T2.Inci
WHERE
    T1.Category= T2.Category
AND
    T1.Date = T2.Date

Convert JsonNode into POJO

This should do the trick:

mapper.readValue(fileReader, MyClass.class);

I say should because I'm using that with a String, not a BufferedReader but it should still work.

Here's my code:

String inputString = // I grab my string here
MySessionClass sessionObject;
try {
    ObjectMapper objectMapper = new ObjectMapper();
    sessionObject = objectMapper.readValue(inputString, MySessionClass.class);

Here's the official documentation for that call: http://jackson.codehaus.org/1.7.9/javadoc/org/codehaus/jackson/map/ObjectMapper.html#readValue(java.lang.String, java.lang.Class)

You can also define a custom deserializer when you instantiate the ObjectMapper: http://wiki.fasterxml.com/JacksonHowToCustomDeserializers

Edit: I just remembered something else. If your object coming in has more properties than the POJO has and you just want to ignore the extras you'll want to set this:

    objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

Or you'll get an error that it can't find the property to set into.

VSCode: How to Split Editor Vertically

If you're looking for a way to change this through the GUI, at least in the current version 1.10.1 if you hover over the OPEN EDITORS group in the EXPLORER pane a button appears that toggles the editor group layout between horizontal and vertical.

Visual Studio Code - toggle editor group layout button

HTML form readonly SELECT tag/input

We could also use this

Disable all except the selected option:

<select>
    <option disabled>1</option>
    <option selected>2</option>
    <option disabled>3</option>
</select>

This way the dropdown still works (and submits its value) but the user can not select another value.

Demo

JPA Query selecting only specific columns without using Criteria Query?

Yes, like in plain sql you could specify what kind of properties you want to select:

SELECT i.firstProperty, i.secondProperty FROM ObjectName i WHERE i.id=10

Executing this query will return a list of Object[], where each array contains the selected properties of one object.

Another way is to wrap the selected properties in a custom object and execute it in a TypedQuery:

String query = "SELECT NEW CustomObject(i.firstProperty, i.secondProperty) FROM ObjectName i WHERE i.id=10";
TypedQuery<CustomObject> typedQuery = em.createQuery(query , CustomObject.class);
List<CustomObject> results = typedQuery.getResultList();

Examples can be found in this article.

UPDATE 29.03.2018:

@Krish:

@PatrickLeitermann for me its giving "Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: Unable to locate class ***" exception . how to solve this ?

I guess you’re using JPA in the context of a Spring application, don't you? Some other people had exactly the same problem and their solution was adding the fully qualified name (e. g. com.example.CustomObject) after the SELECT NEW keywords.

Maybe the internal implementation of the Spring data framework only recognizes classes annotated with @Entity or registered in a specific orm file by their simple name, which causes using this workaround.

How to get the height of a body element

Simply use

$(document).height() // - $('body').offset().top

and / or

$(window).height()

instead of $('body').height();

Searching for file in directories recursively

You are creating three lists, instead of using one (you don't use the return value of DirSearch(d)). You can use a list as a parameter to save the state:

static void Main(string[] args)
{
  var list = new List<string>();
  DirSearch(list, ".");

  foreach (var file in list)
  {
    Console.WriteLine(file);
  }
}

public static void DirSearch(List<string> files, string startDirectory)
{
  try
  {
    foreach (string file in Directory.GetFiles(startDirectory, "*.*"))
    {
      string extension = Path.GetExtension(file);

      if (extension != null)
      {
        files.Add(file);
      }
    }

    foreach (string directory in Directory.GetDirectories(startDirectory))
    {
      DirSearch(files, directory);
    }
  }
  catch (System.Exception e)
  {
    Console.WriteLine(e.Message);
  }
}

Object of custom type as dictionary key

An alternative in Python 2.6 or above is to use collections.namedtuple() -- it saves you writing any special methods:

from collections import namedtuple
MyThingBase = namedtuple("MyThingBase", ["name", "location"])
class MyThing(MyThingBase):
    def __new__(cls, name, location, length):
        obj = MyThingBase.__new__(cls, name, location)
        obj.length = length
        return obj

a = MyThing("a", "here", 10)
b = MyThing("a", "here", 20)
c = MyThing("c", "there", 10)
a == b
# True
hash(a) == hash(b)
# True
a == c
# False

Visual c++ can't open include file 'iostream'

If your include directories are referenced correctly in the VC++ project property sheet -> Configuration Properties -> VC++ directories->Include directories.The path is referenced in the macro $(VC_IncludePath) In my VS 2015 this evaluates to : "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include"

using namespace std;
#include <iostream> 

That did it for me.

Android ListView selected item stay highlighted

Use the id instead:

This is the easiest method that can handle even if the list is long:

public View getView(final int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    Holder holder=new Holder();
    View rowView;
    rowView = inflater.inflate(R.layout.list_item, null);
    //Handle your items.
    //StringHolder.mSelectedItem is a public static variable.
    if(getItemId(position)==StringHolder.mSelectedItem){
        rowView.setBackgroundColor(Color.LTGRAY);

    }else{
        rowView.setBackgroundColor(Color.TRANSPARENT);
    }
    return rowView;
}

And then in your onclicklistener:

list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            StringHolder.mSelectedItem = catagoryAdapter.getItemId(i-1);
            catagoryAdapter.notifyDataSetChanged();
.....

Node.js: what is ENOSPC error and how to solve?

If you encounter this error during trying to run ember server command please rm -rf tmp directory. Then run ember s again. It helped me.

How to use JavaScript source maps (.map files)?

  • How can a developer use it?

I didn't find answer for this in the comments, here is how can be used:

  1. Don't link your js.map file in your index.html file (no need for that)
  2. Minifiacation tools (good ones) add a comment to your .min.js file:

    //# sourceMappingURL=yourFileName.min.js.map

which will connect your .map file.

When the min.js and js.map files are ready...

  1. Chrome: Open dev-tools, navigate to Sources tab, You will see sources folder, where un-minified applications files are kept.

PowerShell Remoting giving "Access is Denied" error

Had similar problems recently. Would suggest you carefully check if the user you're connecting with has proper authorizations on the remote machine.

You can review permissions using the following command.

Set-PSSessionConfiguration -ShowSecurityDescriptorUI -Name Microsoft.PowerShell

Found this tip here (updated link, thanks "unbob"):

https://devblogs.microsoft.com/scripting/configure-remote-security-settings-for-windows-powershell/

It fixed it for me.

How to get div height to auto-adjust to background size?

If you know the ratio of the image at build time, want the height based off of the window height and you're ok targeting modern browsers (IE9+), then you can use viewport units for this:

.width-ratio-of-height {
  overflow-x: scroll;
  height: 100vh;
  width: 500vh; /* width here is 5x height */
  background-image: url("http://placehold.it/5000x1000");
  background-size: cover;
}

Not quite what the OP was asking, but probably a good fit for a lot of those viewing this question, so wanted to give another option here.

Fiddle: https://jsfiddle.net/6Lkzdnge/

How to pass a list from Python, by Jinja2 to JavaScript

To pass some context data to javascript code, you have to serialize it in a way it will be "understood" by javascript (namely JSON). You also need to mark it as safe using the safe Jinja filter, to prevent your data from being htmlescaped.

You can achieve this by doing something like that:

The view

import json

@app.route('/')
def my_view():
    data = [1, 'foo']
    return render_template('index.html', data=json.dumps(data))

The template

<script type="text/javascript">
    function test_func(data) {
        console.log(data);
    }
    test_func({{ data|safe }})
</script>

Edit - exact answer

So, to achieve exactly what you want (loop over a list of items, and pass them to a javascript function), you'd need to serialize every item in your list separately. Your code would then look like this:

The view

import json

@app.route('/')
def my_view():
    data = [1, "foo"]
    return render_template('index.html', data=map(json.dumps, data))

The template

{% for item in data %}
    <span onclick=someFunction({{ item|safe }});>{{ item }}</span>
{% endfor %}

Edit 2

In my example, I use Flask, I don't know what framework you're using, but you got the idea, you just have to make it fit the framework you use.

Edit 3 (Security warning)

NEVER EVER DO THIS WITH USER-SUPPLIED DATA, ONLY DO THIS WITH TRUSTED DATA!

Otherwise, you would expose your application to XSS vulnerabilities!

The easiest way to transform collection to array?

If you use Guava in your project you can use Iterables::toArray.

Foo[] foos = Iterables.toArray(x, Foo.class);

Receiving "fatal: Not a git repository" when attempting to remote add a Git repo

Did you init a local Git repository, into which this remote is supposed to be added?

Does your local directory have a .git folder?

Try git init.

UICollectionView cell selection and cell reuse

In your custom cell create public method:

- (void)showSelection:(BOOL)selection
{
    self.contentView.backgroundColor = selection ? [UIColor blueColor] : [UIColor white];
}

Also write redefenition of -prepareForReuse cell method:

- (void)prepareForReuse
{
    [self showSelection:NO];
    [super prepareForReuse];
}

And in your ViewController you should have _selectedIndexPath variable, which defined in -didSelectItemAtIndexPath and nullified in -didDeselectItemAtIndexPath

NSIndexPath *_selectedIndexPath;

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"Cell";
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];

    if (_selectedIndexPath) {
        [cell showSelection:[indexPath isEqual:_selectedIndexPath]];
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    [cell showSelection:![indexPath isEqual:_selectedIndexPath]];// on/off selection
    _selectedIndexPath = [indexPath isEqual:_selectedIndexPath] ? nil : indexPath;
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    [cell showSelection:NO];
    _selectedIndexPath = nil;
}

Correctly ignore all files recursively under a specific folder except for a specific file type

Either I'm doing it wrongly, or the accepted answer does not work anymore with the current git.

I have actually found the proper solution and posted it under almost the same question here. For more details head there.

Solution:

# Ignore everything inside Resources/ directory
/Resources/**
# Except for subdirectories(won't be committed anyway if there is no committed file inside)
!/Resources/**/
# And except for *.foo files
!*.foo

Difference between JPanel, JFrame, JComponent, and JApplet

JFrame and JApplet are top level containers. If you wish to create a desktop application, you will use JFrame and if you plan to host your application in browser you will use JApplet.

JComponent is an abstract class for all Swing components and you can use it as the base class for your new component. JPanel is a simple usable component you can use for almost anything.

Since this is for a fun project, the simplest way for you is to work with JPanel and then host it inside JFrame or JApplet. Netbeans has a visual designer for Swing with simple examples.

How to send a model in jQuery $.ajax() post request to MVC controller method

you can create a variable and send to ajax.

var m = { "Value": @Model.Value }

$.ajax({
    url: '<%=Url.Action("ModelPage")%>',
    type: "POST",
    data:  m,
    success: function(result) {
        $("div#updatePane").html(result);
    },

    complete: function() {
    $('form').onsubmit({ preventDefault: function() { } });

    }
});

All of model's field must bo ceated in m.

How can I change all input values to uppercase using Jquery?

use css :

input.upper { text-transform: uppercase; }

probably best to use the style, and convert serverside. There's also a jQuery plugin to force uppercase: http://plugins.jquery.com/plugin-tags/uppercase

How to access Session variables and set them in javascript?

Assign value to a hidden field in the code-behind file. Access this value in your javascript like a normal HTML control.

How to do a https request with bad certificate?

If you want to use the default settings from http package, so you don't need to create a new Transport and Client object, you can change to ignore the certificate verification like this:

tr := http.DefaultTransport.(*http.Transport)
tr.TLSClientConfig.InsecureSkipVerify = true