Programs & Examples On #Django users

User model is the default model in Django. It provides many APIs which are helpful for working with users. Django user model is overridable in a Project according to required field.

Extending the User model with custom fields in Django

New in Django 1.5, now you can create your own Custom User Model (which seems to be good thing to do in above case). Refer to 'Customizing authentication in Django'

Probably the coolest new feature on 1.5 release.

how to use free cloud database with android app?

As Wingman said, Google App Engine is a great solution for your scenario.

You can get some information about GAE+Android here: https://developers.google.com/eclipse/docs/appengine_connected_android

And from this Google IO 2012 session: http://www.youtube.com/watch?v=NU_wNR_UUn4

How can I lock a file using java (if possible)

FileChannel.lock is probably what you want.

try (
    FileInputStream in = new FileInputStream(file);
    java.nio.channels.FileLock lock = in.getChannel().lock();
    Reader reader = new InputStreamReader(in, charset)
) {
    ...
}

(Disclaimer: Code not compiled and certainly not tested.)

Note the section entitled "platform dependencies" in the API doc for FileLock.

Call javascript from MVC controller action

There are ways you can mimic this by having your controller return a piece of data, which your view can then translate into a JavaScript call.

We do something like this to allow people to use RESTful URLs to share their jquery-rendered workspace view.

In our case we pass a list of components which need to be rendered and use Razor to translate these back into jquery calls.

Remove "whitespace" between div element

You need this

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<-- I absolutely don't know why, but go ahead, and add this code snippet to your CSS -->

*{
    margin:0;
    padding:0;
}

That's it, have fun removing all those white-spaces problems.

JavaScript editor within Eclipse

Eclipse HTML Editor Plugin

I too have struggled with this totally obvious question. It seemed crazy that this wasn't an extremely easy-to-find feature with all the web development happening in Eclipse these days.

I was very turned off by Aptana because of how bloated it is, and the fact that it starts up a local web server (by default on port 8000) everytime you start Eclipse and you can't disable this functionality. Adobe's port of JSEclipse is now a 400Mb plugin, which is equally insane.

However, I just found a super-lightweight JavaScript editor called Eclipse HTML Editor Plugin, made by Amateras, which was exactly what I was looking for.

How do I get the time of day in javascript/Node.js?

If you only want the time string you can use this expression (with a simple RegEx):

new Date().toISOString().match(/(\d{2}:){2}\d{2}/)[0]
// "23:00:59"

PostgreSQL unnest() with element number

Postgres 9.4 or later

Use WITH ORDINALITY for set-returning functions:

When a function in the FROM clause is suffixed by WITH ORDINALITY, a bigint column is appended to the output which starts from 1 and increments by 1 for each row of the function's output. This is most useful in the case of set returning functions such as unnest().

In combination with the LATERAL feature in pg 9.3+, and according to this thread on pgsql-hackers, the above query can now be written as:

SELECT t.id, a.elem, a.nr
FROM   tbl AS t
LEFT   JOIN LATERAL unnest(string_to_array(t.elements, ','))
                    WITH ORDINALITY AS a(elem, nr) ON TRUE;

LEFT JOIN ... ON TRUE preserves all rows in the left table, even if the table expression to the right returns no rows. If that's of no concern you can use this otherwise equivalent, less verbose form with an implicit CROSS JOIN LATERAL:

SELECT t.id, a.elem, a.nr
FROM   tbl t, unnest(string_to_array(t.elements, ',')) WITH ORDINALITY a(elem, nr);

Or simpler if based off an actual array (arr being an array column):

SELECT t.id, a.elem, a.nr
FROM   tbl t, unnest(t.arr) WITH ORDINALITY a(elem, nr);

Or even, with minimal syntax:

SELECT id, a, ordinality
FROM   tbl, unnest(arr) WITH ORDINALITY a;

a is automatically table and column alias. The default name of the added ordinality column is ordinality. But it's better (safer, cleaner) to add explicit column aliases and table-qualify columns.

Postgres 8.4 - 9.3

With row_number() OVER (PARTITION BY id ORDER BY elem) you get numbers according to the sort order, not the ordinal number of the original ordinal position in the string.

You can simply omit ORDER BY:

SELECT *, row_number() OVER (PARTITION by id) AS nr
FROM  (SELECT id, regexp_split_to_table(elements, ',') AS elem FROM tbl) t;

While this normally works and I have never seen it fail in simple queries, PostgreSQL asserts nothing concerning the order of rows without ORDER BY. It happens to work due to an implementation detail.

To guarantee ordinal numbers of elements in the blank-separated string:

SELECT id, arr[nr] AS elem, nr
FROM  (
   SELECT *, generate_subscripts(arr, 1) AS nr
   FROM  (SELECT id, string_to_array(elements, ' ') AS arr FROM tbl) t
   ) sub;

Or simpler if based off an actual array:

SELECT id, arr[nr] AS elem, nr
FROM  (SELECT *, generate_subscripts(arr, 1) AS nr FROM tbl) t;

Related answer on dba.SE:

Postgres 8.1 - 8.4

None of these features are available, yet: RETURNS TABLE, generate_subscripts(), unnest(), array_length(). But this works:

CREATE FUNCTION f_unnest_ord(anyarray, OUT val anyelement, OUT ordinality integer)
  RETURNS SETOF record
  LANGUAGE sql IMMUTABLE AS
'SELECT $1[i], i - array_lower($1,1) + 1
 FROM   generate_series(array_lower($1,1), array_upper($1,1)) i';

Note in particular, that the array index can differ from ordinal positions of elements. Consider this demo with an extended function:

CREATE FUNCTION f_unnest_ord_idx(anyarray, OUT val anyelement, OUT ordinality int, OUT idx int)
  RETURNS SETOF record
  LANGUAGE sql IMMUTABLE AS
'SELECT $1[i], i - array_lower($1,1) + 1, i
 FROM   generate_series(array_lower($1,1), array_upper($1,1)) i';

SELECT id, arr, (rec).*
FROM  (
   SELECT *, f_unnest_ord_idx(arr) AS rec
   FROM  (VALUES (1, '{a,b,c}'::text[])  --  short for: '[1:3]={a,b,c}'
               , (2, '[5:7]={a,b,c}')
               , (3, '[-9:-7]={a,b,c}')
      ) t(id, arr)
   ) sub;

 id |       arr       | val | ordinality | idx
----+-----------------+-----+------------+-----
  1 | {a,b,c}         | a   |          1 |   1
  1 | {a,b,c}         | b   |          2 |   2
  1 | {a,b,c}         | c   |          3 |   3
  2 | [5:7]={a,b,c}   | a   |          1 |   5
  2 | [5:7]={a,b,c}   | b   |          2 |   6
  2 | [5:7]={a,b,c}   | c   |          3 |   7
  3 | [-9:-7]={a,b,c} | a   |          1 |  -9
  3 | [-9:-7]={a,b,c} | b   |          2 |  -8
  3 | [-9:-7]={a,b,c} | c   |          3 |  -7

Compare:

Convert a String to Modified Camel Case in Java or Title Case as is otherwise called

From commons-lang3

org.apache.commons.lang3.text.WordUtils.capitalizeFully(String str)

LINQ equivalent of foreach for IEnumerable<T>

I respectually disagree with the notion that link extension methods should be side-effect free (not only because they aren't, any delegate can perform side effects).

Consider the following:

   public class Element {}

   public Enum ProcessType
   {
      This = 0, That = 1, SomethingElse = 2
   }

   public class Class1
   {
      private Dictionary<ProcessType, Action<Element>> actions = 
         new Dictionary<ProcessType,Action<Element>>();

      public Class1()
      {
         actions.Add( ProcessType.This, DoThis );
         actions.Add( ProcessType.That, DoThat );
         actions.Add( ProcessType.SomethingElse, DoSomethingElse );
      }

      // Element actions:

      // This example defines 3 distict actions
      // that can be applied to individual elements,
      // But for the sake of the argument, make
      // no assumption about how many distict
      // actions there may, and that there could
      // possibly be many more.

      public void DoThis( Element element )
      {
         // Do something to element
      }

      public void DoThat( Element element )
      {
         // Do something to element
      }

      public void DoSomethingElse( Element element )
      {
         // Do something to element
      }

      public void Apply( ProcessType processType, IEnumerable<Element> elements )
      {
         Action<Element> action = null;
         if( ! actions.TryGetValue( processType, out action ) )
            throw new ArgumentException("processType");
         foreach( element in elements ) 
            action(element);
      }
   }

What the example shows is really just a kind of late-binding that allows one invoke one of many possible actions having side-effects on a sequence of elements, without having to write a big switch construct to decode the value that defines the action and translate it into its corresponding method.

How do I remove the non-numeric character from a string in java?

Java 8 collection streams :

StringBuilder sb = new StringBuilder();
test.chars().mapToObj(i -> (char) i).filter(Character::isDigit).forEach(sb::append);
System.out.println(sb.toString());

Fixed point vs Floating point number

The term ‘fixed point’ refers to the corresponding manner in which numbers are represented, with a fixed number of digits after, and sometimes before, the decimal point. With floating-point representation, the placement of the decimal point can ‘float’ relative to the significant digits of the number. For example, a fixed-point representation with a uniform decimal point placement convention can represent the numbers 123.45, 1234.56, 12345.67, etc, whereas a floating-point representation could in addition represent 1.234567, 123456.7, 0.00001234567, 1234567000000000, etc.

How to write a confusion matrix in Python?

Scikit-learn (which I recommend using anyways) has it included in the metrics module:

>>> from sklearn.metrics import confusion_matrix
>>> y_true = [0, 1, 2, 0, 1, 2, 0, 1, 2]
>>> y_pred = [0, 0, 0, 0, 1, 1, 0, 2, 2]
>>> confusion_matrix(y_true, y_pred)
array([[3, 0, 0],
       [1, 1, 1],
       [1, 1, 1]])

How to place two divs next to each other?

Float one or both inner divs.

Floating one div:

#wrapper {
    width: 500px;
    border: 1px solid black;
    overflow: hidden; /* will contain if #first is longer than #second */
}
#first {
    width: 300px;
    float:left; /* add this */
    border: 1px solid red;
}
#second {
    border: 1px solid green;
    overflow: hidden; /* if you don't want #second to wrap below #first */
}

or if you float both, you'll need to encourage the wrapper div to contain both the floated children, or it will think it's empty and not put the border around them

Floating both divs:

#wrapper {
    width: 500px;
    border: 1px solid black;
    overflow: hidden; /* add this to contain floated children */
}
#first {
    width: 300px;
    float:left; /* add this */
    border: 1px solid red;
}
#second {
    border: 1px solid green;
    float: left; /* add this */
}

Laravel 5 – Clear Cache in Shared Hosting Server

This package is for php ^7.0 and ^laravel5.5.

Use this package in cronjob that I have created for this purpose only. I was also facing same situation. https://packagist.org/packages/afrazahmad/clear-cached-data Install it and run:

php artisan clear:data

and it will run the following commands automcatically

php artisan cache:clear
php artisan view:clear
php artisan route:clear
php artisan clear-compiled
php artisan config:cache

Hope it helps.

If you want to run it automatically at specific time then you will have to setup crnjob first. e.g.

 in app/console/kernel.php

In schedule function:

$schedule->command('clear:data')->dailyAt('07:00');

SQL grammar for SELECT MIN(DATE)

To get the titles for dates greater than a week ago today, use this:

SELECT title, MIN(date_key_no) AS intro_date FROM table HAVING MIN(date_key_no)>= TO_NUMBER(TO_CHAR(SysDate, 'YYYYMMDD')) - 7

Default username password for Tomcat Application Manager

The admin and manager apps are two separate things. Here's a snapshot of a tomcat-users.xml file that works, try this:

<?xml version='1.0' encoding='utf-8'?>  
<tomcat-users>  
    <role rolename="tomcat"/>  
    <role rolename="role1"/>  
    <role rolename="manager"/>  
    <user username="tomcat" password="tomcat" roles="tomcat"/>  
    <user username="both" password="tomcat" roles="tomcat,role1"/>  
    <user username="role1" password="tomcat" roles="role1"/>  
    <user username="USERNAME" password="PASSWORD" roles="manager,tomcat,role1"/>  
</tomcat-users>  

It works for me very well

Use string contains function in oracle SQL query

By lines I assume you mean rows in the table person. What you're looking for is:

select p.name
from   person p
where  p.name LIKE '%A%'; --contains the character 'A'

The above is case sensitive. For a case insensitive search, you can do:

select p.name
from   person p
where  UPPER(p.name) LIKE '%A%'; --contains the character 'A' or 'a'

For the special character, you can do:

select p.name
from   person p
where  p.name LIKE '%'||chr(8211)||'%'; --contains the character chr(8211)

The LIKE operator matches a pattern. The syntax of this command is described in detail in the Oracle documentation. You will mostly use the % sign as it means match zero or more characters.

Remove plot axis values

@Richie Cotton has a pretty good answer above. I can only add that this page provides some examples. Try the following:

x <- 1:20
y <- runif(20)
plot(x,y,xaxt = "n")
axis(side = 1, at = x, labels = FALSE, tck = -0.01)

Escaping double quotes in JavaScript onClick event handler

You may also want to try two backslashes (\\") to escape the escape character.

How to run Visual Studio post-build events for debug build only

Pre- and Post-Build Events run as a batch script. You can do a conditional statement on $(ConfigurationName).

For instance

if $(ConfigurationName) == Debug xcopy something somewhere

How to install JSTL? The absolute uri: http://java.sun.com/jstl/core cannot be resolved

org.apache.jasper.JasperException: The absolute uri: http://java.sun.com/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application

That URI is for JSTL 1.0, but you're actually using JSTL 1.2 which uses URIs with an additional /jsp path (because JSTL, who invented EL expressions, was since version 1.1 integrated as part of JSP in order to share/reuse the EL logic in plain JSP too).

So, fix the taglib URI accordingly based on JSTL documentation:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

Further you need to make absolutely sure that you do not throw multiple different versioned JSTL JAR files together into the runtime classpath. This is a pretty common mistake among Tomcat users. The problem with Tomcat is that it does not offer JSTL out the box and thus you have to manually install it. This is not necessary in normal Jakarta EE servers. See also What exactly is Java EE?

In your specific case, your pom.xml basically tells you that you have jstl-1.2.jar and standard-1.1.2.jar together. This is wrong. You're basically mixing JSTL 1.2 API+impl from Oracle with JSTL 1.1 impl from Apache. You should stick to only one JSTL implementation.

Installing JSTL on Tomcat 10+

In case you're already on Tomcat 10 or newer (the first Jakartified version, with jakarta.* package instead of javax.* package), use JSTL 2.0 via this sole dependency:

<dependency>
    <groupId>org.glassfish.web</groupId>
    <artifactId>jakarta.servlet.jsp.jstl</artifactId>
    <version>2.0.0</version>
</dependency>

Non-Maven users can achieve the same by dropping the following two physical files in /WEB-INF/lib folder of the web application project (do absolutely not drop standard*.jar or any loose .tld files in there! remove them if necessary).

Installing JSTL on Tomcat 9-

In case you're not on Tomcat 10 yet, but still on Tomcat 9 or older, use JSTL 1.2 via this sole dependency:

<dependency>
    <groupId>org.glassfish.web</groupId>
    <artifactId>jakarta.servlet.jsp.jstl</artifactId>
    <version>1.2.6</version>
</dependency>

Non-Maven users can achieve the same by dropping the following two physical files in /WEB-INF/lib folder of the web application project (do absolutely not drop standard*.jar or any loose .tld files in there! remove them if necessary).

Installing JSTL on normal JEE server

In case you're actually using a normal Jakarta EE server such as WildFly, Payara, etc instead of a barebones servletcontainer such as Tomcat, Jetty, etc, then you don't need to explicitly install JSTL at all. Normal Jakarta EE servers already provide JSTL out the box. In other words, you don't need to add JSTL to pom.xml nor to drop any JAR/TLD files in webapp. Solely the provided scoped Jakarta EE coordinate is sufficient:

<dependency>
    <groupId>jakarta.platform</groupId>
    <artifactId>jakarta.jakartaee-api</artifactId>
    <version><!-- 9.0.0, 8.0.0, etc depending on your server --></version>
    <scope>provided</scope>
</dependency>

Make sure web.xml version is right

Further you should also make sure that your web.xml is declared conform at least Servlet 2.4 and thus not as Servlet 2.3 or older. Otherwise EL expressions inside JSTL tags would in turn fail to work. Pick the highest version matching your target container and make sure that you don't have a <!DOCTYPE> anywhere in your web.xml. Here's a Servlet 5.0 (Tomcat 10) compatible example:

<?xml version="1.0" encoding="UTF-8"?>
<web-app 
    xmlns="https://jakarta.ee/xml/ns/jakartaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
    version="5.0">

    <!-- Config here. -->

</web-app>

And here's a Servlet 4.0 (Tomcat 9) compatible example:

<?xml version="1.0" encoding="UTF-8"?>
<web-app
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
    version="4.0">

    <!-- Config here. -->

</web-app>

See also:

How to change href attribute using JavaScript after opening the link in a new window?

You can delay your code using setTimeout to execute after click

function changeLink(){
    setTimeout(function() {
        var link = document.getElementById("mylink");
        link.setAttribute('href', "http://facebook.com");
        document.getElementById("mylink").innerHTML = "facebook";
    }, 100);
}

Generate MD5 hash string with T-SQL

SELECT CONVERT(
      VARCHAR(32),
      HASHBYTES(
                   'MD5',
                   CAST(prescrip.IsExpressExamRX AS VARCHAR(250))
                   + CAST(prescrip.[Description] AS VARCHAR(250))
               ),
      2
  ) MD5_Value;

works for me.

How to fix a collation conflict in a SQL Server query?

I resolved a similar issue by wrapping the query in another query...

Initial query was working find giving individual columns of output, with some of the columns coming from sub queries with Max or Sum function, and other with "distinct" or case substitutions and such.

I encountered the collation error after attempting to create a single field of output with...

select
rtrim(field1)+','+rtrim(field2)+','+...

The query would execute as I wrote it, but the error would occur after saving the sql and reloading it.

Wound up fixing it with something like...

select z.field1+','+z.field2+','+... as OUTPUT_REC
from (select rtrim(field1), rtrim(field2), ... ) z

Some fields are "max" of a subquery, with a case substitution if null and others are date fields, and some are left joins (might be NULL)...in other words, mixed field types. I believe this is the cause of the issue being caused by OS collation and Database collation being slightly different, but by converting all to trimmed strings before the final select, it sorts it out, all in the SQL.

How to return values in javascript

Javascript is duck typed, so you can create a small structure.

function myFunction(value1,value2,value3)
{         
     var myObject = new Object();
     myObject.value2 = somevalue2;
     myObject.value3 = somevalue3;
     return myObject;
}


var value = myFunction("1",value2,value3);

if(value.value2  && value.value3)
{
//Do some stuff
}

How can I check if given int exists in array?

int index = std::distance(std::begin(myArray), std::find(begin(myArray), end(std::myArray), VALUE));

Returns an invalid index (length of the array) if not found.

Simple way to measure cell execution time in ipython notebook

When in trouble what means what:

?%timeit or ??timeit

To get the details:

Usage, in line mode:
  %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
or in cell mode:
  %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
  code
  code...

Time execution of a Python statement or expression using the timeit
module.  This function can be used both as a line and cell magic:

- In line mode you can time a single-line statement (though multiple
  ones can be chained with using semicolons).

- In cell mode, the statement in the first line is used as setup code
  (executed but not timed) and the body of the cell is timed.  The cell
  body has access to any variables created in the setup code.

How can I iterate over files in a given directory?

Original answer:

import os

for filename in os.listdir(directory):
    if filename.endswith(".asm") or filename.endswith(".py"): 
         # print(os.path.join(directory, filename))
        continue
    else:
        continue

Python 3.6 version of the above answer, using os - assuming that you have the directory path as a str object in a variable called directory_in_str:

import os

directory = os.fsencode(directory_in_str)
    
for file in os.listdir(directory):
     filename = os.fsdecode(file)
     if filename.endswith(".asm") or filename.endswith(".py"): 
         # print(os.path.join(directory, filename))
         continue
     else:
         continue

Or recursively, using pathlib:

from pathlib import Path

pathlist = Path(directory_in_str).glob('**/*.asm')
for path in pathlist:
     # because path is object not string
     path_in_str = str(path)
     # print(path_in_str)
  • Use rglob to replace glob('**/*.asm') with rglob('*.asm')
    • This is like calling Path.glob() with '**/' added in front of the given relative pattern:
from pathlib import Path

pathlist = Path(directory_in_str).rglob('*.asm')
for path in pathlist:
     # because path is object not string
     path_in_str = str(path)
     # print(path_in_str)

How to retrieve JSON Data Array from ExtJS Store

A better (IMO) one-line approach, works on ExtJS 4, not sure about 3:

store.proxy.reader.jsonData

How can I tell gcc not to inline a function?

GCC has a switch called

-fno-inline-small-functions

So use that when invoking gcc. But the side effect is that all other small functions are also non-inlined.

Find a pair of elements from an array whose sum equals a given number

A simple Java code snippet for printing the pairs below:

    public static void count_all_pairs_with_given_sum(int arr[], int S){
        if(arr.length < 2){
        return;
    }        
    HashSet values = new HashSet(arr.length);
    for(int value : arr)values.add(value);
    for(int value : arr){
        int difference = S - value;
    if(values.contains(difference) && value<difference){
        System.out.printf("(%d, %d) %n", value, difference);
        }
    }
    }

How can I check if an array contains a specific value in php?

You need to use a search algorithm on your array. It depends on how large is your array, you have plenty of choices on what to use. Or you can use on of the built in functions:

http://www.w3schools.com/php/php_ref_array.asp

http://php.net/manual/en/function.array-search.php

Google Play on Android 4.0 emulator


Playstore + Google Play Services In Linux(Ubuntu 14.04)


Download Google apps (GoogleLoginService.apk , GoogleServicesFramework.apk )

from here http://www.securitylearn.net/2013/08/31/google-play-store-on-android-emulator/

and Download ( Phonesky.apk) from here https://basketbuild.com/filedl/devs?dev=dankoman&dl=dankoman/Phonesky.apk

GO TO ANDROID SDK LOCATION>>

cd -Android SDK's tools Location-

TO RUN EMULATOR>>

Android/Sdk/tools$ ./emulator64-x86 -avd Kitkat -partition-size 566 -no-audio -no-boot-anim

SET PERMISSIONS>>

cd Android/Sdk/platform-tools platform-tools$ adb shell mount -o remount,rw -t yaffs2 /dev/block/mtdblock0 /system

platform-tools$ adb shell chmod 777 /system/app

platform-tools$ adb push /home/nazmul/Downloads/GoogleLoginService.apk /system/app/.

PUSH PLAY APKS >>

platform-tools$ adb push /home/nazmul/Downloads/GoogleServicesFramework.apk /system/app/. platform-tools$ adb push /home/nazmul/Downloads/Phonesky.apk /system/app/. platform-tools$ adb shell rm /system/app/SdkSetup*

how can I check if a file exists?

Start with this:

Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(path)) Then
   msg = path & " exists."
Else
   msg = path & " doesn't exist."
End If

Taken from the documentation.

iterating over and removing from a map

Here is a code sample to use the iterator in a for loop to remove the entry.

Map<String, String> map = new HashMap<String, String>() {
  {
    put("test", "test123");
    put("test2", "test456");
  }
};

for(Iterator<Map.Entry<String, String>> it = map.entrySet().iterator(); it.hasNext(); ) {
    Map.Entry<String, String> entry = it.next();
    if(entry.getKey().equals("test")) {
        it.remove();
    }
}

How to select lines between two marker patterns which may occur multiple times with awk/sed

I tried to use awk to print lines between two patterns while pattern2 also match pattern1. And the pattern1 line should also be printed.

e.g. source

package AAA
aaa
bbb
ccc
package BBB
ddd
eee
package CCC
fff
ggg
hhh
iii
package DDD
jjj

should has an ouput of

package BBB
ddd
eee

Where pattern1 is package BBB, pattern2 is package \w*. Note that CCC isn't a known value so can't be literally matched.

In this case, neither @scai 's awk '/abc/{a=1}/mno/{print;a=0}a' file nor @fedorqui 's awk '/abc/{a=1} a; /mno/{a=0}' file works for me.

Finally, I managed to solve it by awk '/package BBB/{flag=1;print;next}/package \w*/{flag=0}flag' file, haha

A little more effort result in awk '/package BBB/{flag=1;print;next}flag;/package \w*/{flag=0}' file, to print pattern2 line also, that is,

package BBB
ddd
eee
package CCC

Angular: Cannot find a differ supporting object '[object Object]'

This ridiculous error message merely means there's a binding to an array that doesn't exist.

<option
  *ngFor="let option of setting.options"
  [value]="option"
  >{{ option }}
</option>

In the example above the value of setting.options is undefined. To fix, press F12 and open developer window. When the the get request returns the data look for the values to contain data.

If data exists, then make sure the binding name is correct

//was the property name correct? 
setting.properNamedOptions

If the data exists, is it an Array?

If the data doesn't exist then fix it on the backend.

Python - round up to the nearest ten

round does take negative ndigits parameter!

>>> round(46,-1)
50

may solve your case.

How to delete the last row of data of a pandas dataframe

Surprised nobody brought this one up:

# To remove last n rows
df.head(-n)

# To remove first n rows
df.tail(-n)

Running a speed test on a DataFrame of 1000 rows shows that slicing and head/tail are ~6 times faster than using drop:

>>> %timeit df[:-1]
125 µs ± 132 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

>>> %timeit df.head(-1)
129 µs ± 1.18 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

>>> %timeit df.drop(df.tail(1).index)
751 µs ± 20.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Absolute position of an element on the screen using jQuery

BTW, if anyone want to get coordinates of element on screen without jQuery, please try this:

function getOffsetTop (el) {
    if (el.offsetParent) return el.offsetTop + getOffsetTop(el.offsetParent)
    return el.offsetTop || 0
}
function getOffsetLeft (el) {
    if (el.offsetParent) return el.offsetLeft + getOffsetLeft(el.offsetParent)
    return el.offsetleft || 0
}
function coordinates(el) {
    var y1 = getOffsetTop(el) - window.scrollY;
    var x1 = getOffsetLeft(el) - window.scrollX; 
    var y2 = y1 + el.offsetHeight;
    var x2 = x1 + el.offsetWidth;
    return {
        x1: x1, x2: x2, y1: y1, y2: y2
    }
}

DateTime.TryParse issue with dates of yyyy-dd-MM format

From DateTime on msdn:

Type: System.DateTime% When this method returns, contains the DateTime value equivalent to the date and time contained in s, if the conversion succeeded, or MinValue if the conversion failed. The conversion fails if the s parameter is null, is an empty string (""), or does not contain a valid string representation of a date and time. This parameter is passed uninitialized.

Use parseexact with the format string "yyyy-dd-MM hh:mm tt" instead.

list.clear() vs list = new ArrayList<Integer>();

list.clear() is going to keep the same ArrayList but the same memory allocation. list = new ArrayList<int>(); is going to allocate new memory for your ArrayList.

The big difference is that ArrayLists will expand dynamically as you need more space. Therefore, if you call list.clear() you will still, potentially, have a large amount of memory allocated for an ArrayList that might not be needed.

That said list.clear() will be faster but if memory maters you might want to allocate a new ArrayList.

CAST to DECIMAL in MySQL

MySQL casts to Decimal:

Cast bare integer to decimal:

select cast(9 as decimal(4,2));       //prints 9.00

Cast Integers 8/5 to decimal:

select cast(8/5 as decimal(11,4));    //prints 1.6000

Cast string to decimal:

select cast(".885" as decimal(11,3));   //prints 0.885

Cast two int variables into a decimal

mysql> select 5 into @myvar1;
Query OK, 1 row affected (0.00 sec)

mysql> select 8 into @myvar2;
Query OK, 1 row affected (0.00 sec)

mysql> select @myvar1/@myvar2;   //prints 0.6250

Cast decimal back to string:

select cast(1.552 as char(10));   //shows "1.552"

Can we overload the main method in Java?

yes we can overload main method. main method must not be static main method.

Formula to determine brightness of RGB color

This link explains everything in depth, including why those multiplier constants exist before the R, G and B values.

Edit: It has an explanation to one of the answers here too (0.299*R + 0.587*G + 0.114*B)

How to remove tab indent from several lines in IDLE?

Depends on your editor.

Have you tried Shift+Tab?

How can I color Python logging output?

Just answered the same on similar question: Python | change text color in shell

The idea is to use the clint library. Which has support for MAC, Linux and Windows shells (CLI).

Current date and time as string

#include <chrono>
#include <iostream>

int main()
{
    std::time_t ct = std::time(0);
    char* cc = ctime(&ct);

    std::cout << cc << std::endl;
    return 0;
}

Passing route control with optional parameter after root in express?

Express version:

"dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1"
  }

Optional parameter are very much handy, you can declare and use them easily using express:

app.get('/api/v1/tours/:cId/:pId/:batchNo?', (req, res)=>{
    console.log("category Id: "+req.params.cId);
    console.log("product ID: "+req.params.pId);
    if (req.params.batchNo){
        console.log("Batch No: "+req.params.batchNo);
    }
});

In the above code batchNo is optional. Express will count it optional because after in URL construction, I gave a '?' symbol after batchNo '/:batchNo?'

Now I can call with only categoryId and productId or with all three-parameter.

http://127.0.0.1:3000/api/v1/tours/5/10
//or
http://127.0.0.1:3000/api/v1/tours/5/10/8987

enter image description here enter image description here

How to get TimeZone from android mobile?

Try this code-

Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();

It will return user selected timezone.

filename and line number of Python script

Better to use sys also-

print dir(sys._getframe())
print dir(sys._getframe().f_lineno)
print sys._getframe().f_lineno

The output is:

['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'f_back', 'f_builtins', 'f_code', 'f_exc_traceback', 'f_exc_type', 'f_exc_value', 'f_globals', 'f_lasti', 'f_lineno', 'f_locals', 'f_restricted', 'f_trace']
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']
14

Write HTML to string

This is not a generic solution, however, if your pupose is to have or maintain email templates then System.Web has a built-in class called MailDefinition. This class is used by the ASP.NET membership controls to create HTML emails.

Does the same kind of 'string replace' things as mentioned above, but packs it all into a MailMessage for you.

Here is an example from MSDN:

ListDictionary replacements = new ListDictionary();
replacements.Add("<%To%>",sourceTo.Text);
replacements.Add("<%From%>", md.From);
System.Net.Mail.MailMessage fileMsg;
fileMsg = md.CreateMailMessage(toAddresses, replacements, emailTemplate, this); 
return fileMsg;

Fill background color left to right CSS

A single css code on hover can do the trick: box-shadow: inset 100px 0 0 0 #e0e0e0;

A complete demo can be found in my fiddle:

https://jsfiddle.net/shuvamallick/3o0h5oka/

How to convert an IPv4 address into a integer in C#?

Take a look at some of the crazy parsing examples in .Net's IPAddress.Parse: (MSDN)

"65536" ==> 0.0.255.255
"20.2" ==> 20.0.0.2
"20.65535" ==> 20.0.255.255
"128.1.2" ==> 128.1.0.2

Array and string offset access syntax with curly braces is deprecated

It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.

Let's say you have something like this in your code:

$str = "test";
echo($str{0});

since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:

$str = "test";
echo($str[0]);

Fixing the code in the question will look something like this:

public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
    $records = $this->listRecords($zoneID, $type, $name);
    if (isset($records->result[0]->id)) {
        return $records->result[0]->id;
    }
    return false;
}

Can multiple different HTML elements have the same ID if they're different elements?

Yes they can.

I don't know if all these anwers are outdated, but just open youtube and inspect the html. Try to inspect the suggested videos, you'll see that they all have the same Id and repeating structure as follows:

<span id="video-title" class="style-scope ytd-compact-radio-renderer" title="Mix - LARA TACTICAL">

What is the cleanest way to get the progress of JQuery ajax request?

jQuery has an AjaxSetup() function that allows you to register global ajax handlers such as beforeSend and complete for all ajax calls as well as allow you to access the xhr object to do the progress that you are looking for

Div with margin-left and width:100% overflowing on the right side

A div is a block element and by default 100% wide. You should just have to set the textarea width to 100%.

What are pipe and tap methods in Angular tutorial?

You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:

  /**
   * Used to stitch together functional operators into a chain.
   * @method pipe
   * @return {Observable} the Observable result of all of the operators having
   * been called in the order they were passed in.
   *
   * @example
   *
   * import { map, filter, scan } from 'rxjs/operators';
   *
   * Rx.Observable.interval(1000)
   *   .pipe(
   *     filter(x => x % 2 === 0),
   *     map(x => x + x),
   *     scan((acc, x) => acc + x)
   *   )
   *   .subscribe(x => console.log(x))
   */

In brief:

Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan(), but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe() to make a chain of those operators (see example above).

Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do(). You can think of it as if observable was an array over time, then tap() would be an equivalent to Array.forEach().

Changing git commit message after push (given that no one pulled from remote)

additional information for same problem if you are using bitbucket pipeline

edit your message

git commit --amend

push to the sever

git push --force <repository> <branch>

then add --force to your push command on the pipeline

git ftp push --force

This will delete your previous commit(s) and push your current one.

remove the --force after first push

i tried it on bitbucket pipeline and its working fine

Best practices for Storyboard login screen, handling clearing of data upon logout

I didn't like bhavya's answer because of using AppDelegate inside View Controllers and setting rootViewController has no animation. And Trevor's answer has issue with flashing view controller on iOS8.

UPD 07/18/2015

AppDelegate inside View Controllers:

Changing AppDelegate state (properties) inside view controller breaks encapsulation.

Very simple hierarchy of objects in every iOS project:

AppDelegate (owns window and rootViewController)

ViewController (owns view)

It's ok that objects from the top change objects at the bottom, because they are creating them. But it's not ok if objects on the bottom change objects on top of them (I described some basic programming/OOP principle : DIP (Dependency Inversion Principle : high level module must not depend on the low level module, but they should depend on abstractions)).

If any object will change any object in this hierarchy, sooner or later there will be a mess in the code. It might be ok on the small projects but it's no fun to dig through this mess on the bit projects =]

UPD 07/18/2015

I replicate modal controller animations using UINavigationController (tl;dr: check the project).

I'm using UINavigationController to present all controllers in my app. Initially I displayed login view controller in navigation stack with plain push/pop animation. Than I decided to change it to modal with minimal changes.

How it works:

  1. Initial view controller (or self.window.rootViewController) is UINavigationController with ProgressViewController as a rootViewController. I'm showing ProgressViewController because DataModel can take some time to initialize because it inits core data stack like in this article (I really like this approach).

  2. AppDelegate is responsible for getting login status updates.

  3. DataModel handles user login/logout and AppDelegate is observing it's userLoggedIn property via KVO. Arguably not the best method to do this but it works for me. (Why KVO is bad, you can check in this or this article (Why Not Use Notifications? part).

  4. ModalDismissAnimator and ModalPresentAnimator are used to customize default push animation.

How animators logic works:

  1. AppDelegate sets itself as a delegate of self.window.rootViewController (which is UINavigationController).

  2. AppDelegate returns one of animators in -[AppDelegate navigationController:animationControllerForOperation:fromViewController:toViewController:] if necessary.

  3. Animators implement -transitionDuration: and -animateTransition: methods. -[ModalPresentAnimator animateTransition:]:

    - (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
    {
        UIViewController *toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
        [[transitionContext containerView] addSubview:toViewController.view];
        CGRect frame = toViewController.view.frame;
        CGRect toFrame = frame;
        frame.origin.y = CGRectGetHeight(frame);
        toViewController.view.frame = frame;
        [UIView animateWithDuration:[self transitionDuration:transitionContext]
                         animations:^
         {
             toViewController.view.frame = toFrame;
         } completion:^(BOOL finished)
         {
             [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
         }];
    }
    

Test project is here.

How can I convert string date to NSDate?

Since Swift 3, many of the NS prefixes have been dropped.

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" 
/* date format string rules
 * http://userguide.icu-project.org/formatparse/datetime
 */

let date = dateFormatter.date(from: dateString)

SMTP connect() failed PHPmailer - PHP

This is usually a result of the server not accepting SSLv2 or SSLv3 connections which is a standard for cPanel/WHM in favor of TLS only connections. You can check this by going to WHM>>Service Configuration>>Exim Configuration Manager -> Options for OpenSSL

Pip - Fatal error in launcher: Unable to create process using '"'

I was trying to install "bottle" package in python 3.6.6 having pip version 18.0 on Windows. I faced the same error as follows:-

Fatal error in launcher: Unable to create process using '"c:\users\arnab sinha\python.exe"  "C:\Users\Arnab Sinha\Scripts\pip.exe" install bottle'

All I typed after that was

py -m pip install bottle

This solved my issue.

Pivoting rows into columns dynamically in Oracle

Oracle 11g provides a PIVOT operation that does what you want.

Oracle 11g solution

select * from
(select id, k, v from _kv) 
pivot(max(v) for k in ('name', 'age', 'gender', 'status')

(Note: I do not have a copy of 11g to test this on so I have not verified its functionality)

I obtained this solution from: http://orafaq.com/wiki/PIVOT

EDIT -- pivot xml option (also Oracle 11g)
Apparently there is also a pivot xml option for when you do not know all the possible column headings that you may need. (see the XML TYPE section near the bottom of the page located at http://www.oracle.com/technetwork/articles/sql/11g-pivot-097235.html)

select * from
(select id, k, v from _kv) 
pivot xml (max(v)
for k in (any) )

(Note: As before I do not have a copy of 11g to test this on so I have not verified its functionality)

Edit2: Changed v in the pivot and pivot xml statements to max(v) since it is supposed to be aggregated as mentioned in one of the comments. I also added the in clause which is not optional for pivot. Of course, having to specify the values in the in clause defeats the goal of having a completely dynamic pivot/crosstab query as was the desire of this question's poster.

Splitting strings in PHP and get last part

$string = 'abc-123-xyz-789';
$exploded = explode('-', $string);
echo end($exploded);

EDIT::Finally got around to removing the E_STRICT issue

How to Rotate a UIImage 90 degrees?

If you want to add a photo rotate button that'll keep rotating the photo in 90 degree increments, here you go. (finalImage is a UIImage that's already been created elsewhere.)

- (void)rotatePhoto {
    UIImage *rotatedImage;

    if (finalImage.imageOrientation == UIImageOrientationRight)
        rotatedImage = [[UIImage alloc] initWithCGImage: finalImage.CGImage
                                              scale: 1.0
                                        orientation: UIImageOrientationDown];
    else if (finalImage.imageOrientation == UIImageOrientationDown)
        rotatedImage = [[UIImage alloc] initWithCGImage: finalImage.CGImage
                                              scale: 1.0
                                        orientation: UIImageOrientationLeft];
    else if (finalImage.imageOrientation == UIImageOrientationLeft)
        rotatedImage = [[UIImage alloc] initWithCGImage: finalImage.CGImage
                                              scale: 1.0
                                        orientation: UIImageOrientationUp];
    else
        rotatedImage = [[UIImage alloc] initWithCGImage: finalImage.CGImage
                                                     scale: 1.0
                                               orientation: UIImageOrientationRight];
    finalImage = rotatedImage;
}

How can I convert this foreach code to Parallel.ForEach?

string[] lines = File.ReadAllLines(txtProxyListPath.Text);
List<string> list_lines = new List<string>(lines);
Parallel.ForEach(list_lines, line =>
{
    //Your stuff
});

How to transfer paid android apps from one google account to another google account

It's totally feasible now. Google now allow you to transfer Android apps between accounts. Please take a look at this link: https://support.google.com/googleplay/android-developer/checklist/3294213?hl=en

Block direct access to a file over http but allow php script access

Are the files on the same server as the PHP script? If so, just keep the files out of the web root and make sure your PHP script has read permissions for wherever they're stored.

JavaScript replace/regex

Your regex pattern should have the g modifier:

var pattern = /[somepattern]+/g;

notice the g at the end. it tells the replacer to do a global replace.

Also you dont need to use the RegExp object you can construct your pattern as above. Example pattern:

var pattern = /[0-9a-zA-Z]+/g;

a pattern is always surrounded by / on either side - with modifiers after the final /, the g modifier being the global.

EDIT: Why does it matter if pattern is a variable? In your case it would function like this (notice that pattern is still a variable):

var pattern = /[0-9a-zA-Z]+/g;
repeater.replace(pattern, "1234abc");

But you would need to change your replace function to this:

this.markup = this.markup.replace(pattern, value);

mysqldump exports only one table

try this. There are in general three ways to use mysqldump—

in order to dump a set of one or more tables,

shell> mysqldump [options] db_name [tbl_name ...]

a set of one or more complete databases

shell> mysqldump [options] --databases db_name ...

or an entire MySQL server—as shown here:

shell> mysqldump [options] --all-databases

Git on Windows: How do you set up a mergetool?

It seems that newer git versions support p4merge directly, so

git config --global merge.tool p4merge

should be all you need, if p4merge.exe is on your path. No need to set up cmd or path.

How do I get the calling method name and type using reflection?

public class SomeClass
{
    public void SomeMethod()
    {
        StackFrame frame = new StackFrame(1);
        var method = frame.GetMethod();
        var type = method.DeclaringType;
        var name = method.Name;
    }
}

Now let's say you have another class like this:

public class Caller
{
   public void Call()
   {
      SomeClass s = new SomeClass();
      s.SomeMethod();
   }
}

name will be "Call" and type will be "Caller"

UPDATE Two years later since I'm still getting upvotes on this

In .Net 4.5 there is now a much easier way to do this. You can take advantage of the CallerMemberNameAttribute

Going with the previous example:

public class SomeClass
{
    public void SomeMethod([CallerMemberName]string memberName = "")
    {
        Console.WriteLine(memberName); //output will be name of calling method
    }
}

Mockito - NullpointerException when stubbing Method

The default return value of methods you haven't stubbed yet is false for boolean methods, an empty collection or map for methods returning collections or maps and null otherwise.

This also applies to method calls within when(...). In you're example when(myService.getListWithData(inputData).get()) will cause a NullPointerException because myService.getListWithData(inputData) is null - it has not been stubbed before.

One option is create mocks for all intermediate return values and stub them before use. For example:

ListWithData listWithData = mock(ListWithData.class);
when(listWithData.get()).thenReturn(item1);
when(myService.getListWithData()).thenReturn(listWithData);

Or alternatively, you can specify a different default answer when creating a mock, to make methods return a new mock instead of null: RETURNS_DEEP_STUBS

SomeService myService = mock(SomeService.class, Mockito.RETURNS_DEEP_STUBS);
when(myService.getListWithData().get()).thenReturn(item1);

You should read the Javadoc of Mockito.RETURNS_DEEP_STUBS which explains this in more detail and also has some warnings about its usage.

I hope this helps. Just note that your example code seems to have more issues, such as missing assert or verify statements and calling setters on mocks (which does not have any effect).

How do I set the background color of Excel cells using VBA?

This is a perfect example of where you should use the macro recorder. Turn on the recorder and set the color of the cells through the UI. Stop the recorder and review the macro. It will generate a bunch of extraneous code, but it will also show you syntax that works for what you are trying to accomplish. Strip out what you don't need and modify (if you need to) what's left.

Insert string in beginning of another string

The first case is done using the insert() method:

_sb.insert(0, "Hello ");

The latter case can be done using the overloaded + operator on Strings. This uses a StringBuilder behind the scenes:

String s2 = "Hello " + _s;

How can I convert a string to a float in mysql?

This will convert to a numeric value without the need to cast or specify length or digits:

STRING_COL+0.0

If your column is an INT, can leave off the .0 to avoid decimals:

STRING_COL+0

header location not working in my php code

It should be Location not location:

header('Location: index.php');

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.

What is a vertical tab?

A vertical tab was the opposite of a line feed i.e. it went upwards by one line. It had nothing to do with tab positions. If you want to prove this, try it on an RS232 terminal.

How to Configure SSL for Amazon S3 bucket

I found you can do this easily via the Cloud Flare service.

Set up a bucket, enable webhosting on the bucket and point the desired CNAME to that endpoint via Cloudflare... and pay for the service of course... but $5-$20 VS $600 is much easier to stomach.

Full detail here: https://www.engaging.io/easy-way-to-configure-ssl-for-amazon-s3-bucket-via-cloudflare/

Read Numeric Data from a Text File in C++

you could read and write to a seperately like others. But if you want to write into the same one, you could try with this:

#include <iostream>
#include <fstream>

using namespace std;

int main() {

    double data[size of your data];

    std::ifstream input("file.txt");

    for (int i = 0; i < size of your data; i++) {
        input >> data[i];
        std::cout<< data[i]<<std::endl;
        }

}

How do I "select Android SDK" in Android Studio?

I just change the minSdKversion to 23 like:

andriod {
    compileSdKVersion 27
    defaultConfig {
          minSdKversion 23
    }
}

How to clone an InputStream?

You can't clone it, and how you are going to solve your problem depends on what the source of the data is.

One solution is to read all data from the InputStream into a byte array, and then create a ByteArrayInputStream around that byte array, and pass that input stream into your method.

Edit 1: That is, if the other method also needs to read the same data. I.e you want to "reset" the stream.

How to insert an element after another element in JavaScript without using a library?

The method node.after (doc) inserts a node after another node.

For two DOM nodes node1 and node2,

node1.after(node2) inserts node2 after node1.

This method is not available in older browsers, so usually a polyfill is needed.

What is the difference between rb and r+b modes in file objects

r+ is used for reading, and writing mode. b is for binary. r+b mode is open the binary file in read or write mode.
You can read more here.

Jquery asp.net Button Click Event via ajax

In the client side handle the click event of the button, use the ClientID property to get he id of the button:

$(document).ready(function() {
$("#<%=myButton.ClientID %>,#<%=muSecondButton.ClientID%>").click(

    function() {
     $.get("/myPage.aspx",{id:$(this).attr('id')},function(data) {
       // do something with the data
     return false;
     }
    });
 });

In your page on the server:

protected void Page_Load(object sender,EventArgs e) {
 // check if it is an ajax request
 if (Request.Headers["X-Requested-With"] == "XMLHttpRequest") {
  if (Request.QueryString["id"]==myButton.ClientID) {
    // call the click event handler of the myButton here
    Response.End();
  }
  if (Request.QueryString["id"]==mySecondButton.ClientID) {
    // call the click event handler of the mySecondButton here
    Response.End();
  }
 }
}

Each for object?

for(var key in object) {
   console.log(object[key]);
}

What is the difference between a schema and a table and a database?

In a nutshell, a schema is the definition for the entire database, so it includes tables, views, stored procedures, indexes, primary and foreign keys, etc.

How to normalize a vector in MATLAB efficiently? Any related built-in function?

The original code you suggest is the best way.

Matlab is extremely good at vectorized operations such as this, at least for large vectors.

The built-in norm function is very fast. Here are some timing results:

V = rand(10000000,1);
% Run once
tic; V1=V/norm(V); toc           % result:  0.228273s
tic; V2=V/sqrt(sum(V.*V)); toc   % result:  0.325161s
tic; V1=V/norm(V); toc           % result:  0.218892s

V1 is calculated a second time here just to make sure there are no important cache penalties on the first call.

Timing information here was produced with R2008a x64 on Windows.


EDIT:

Revised answer based on gnovice's suggestions (see comments). Matrix math (barely) wins:

clc; clear all;
V = rand(1024*1024*32,1);
N = 10;
tic; for i=1:N, V1 = V/norm(V);         end; toc % 6.3 s
tic; for i=1:N, V2 = V/sqrt(sum(V.*V)); end; toc % 9.3 s
tic; for i=1:N, V3 = V/sqrt(V'*V);      end; toc % 6.2 s ***
tic; for i=1:N, V4 = V/sqrt(sum(V.^2)); end; toc % 9.2 s
tic; for i=1:N, V1=V/norm(V);           end; toc % 6.4 s

IMHO, the difference between "norm(V)" and "sqrt(V'*V)" is small enough that for most programs, it's best to go with the one that's more clear. To me, "norm(V)" is clearer and easier to read, but "sqrt(V'*V)" is still idiomatic in Matlab.

Executing JavaScript without a browser?

PhantomJS allows you to do this as well

http://phantomjs.org/

How to fix 'sudo: no tty present and no askpass program specified' error?

If by any chance you came here because you can't sudo inside the Ubuntu that comes with Windows10

  1. Edit the /etc/hosts file from Windows (with Notepad), it'll be located at: %localappdata\lxss\rootfs\etc, add 127.0.0.1 WINDOWS8, this will get rid of the first error that it can't find the host.

  2. To get rid of the no tty present error, always do sudo -S <command>

Path.Combine absolute with relative path strings

For windows universal apps Path.GetFullPath() is not available, you can use the System.Uri class instead:

 Uri uri = new Uri(Path.Combine(@"C:\blah\",@"..\bling"));
 Console.WriteLine(uri.LocalPath);

How to write to file in Ruby?

For those of us that learn by example...

Write text to a file like this:

IO.write('/tmp/msg.txt', 'hi')

BONUS INFO ...

Read it back like this

IO.read('/tmp/msg.txt')

Frequently, I want to read a file into my clipboard ***

Clipboard.copy IO.read('/tmp/msg.txt')

And other times, I want to write what's in my clipboard to a file ***

IO.write('/tmp/msg.txt', Clipboard.paste)

*** Assumes you have the clipboard gem installed

See: https://rubygems.org/gems/clipboard

Jquery Ajax Call, doesn't call Success or Error

change your code to:

function ChangePurpose(Vid, PurId) {
    var Success = false;
    $.ajax({
        type: "POST",
        url: "CHService.asmx/SavePurpose",
        dataType: "text",
        async: false,
        data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            Success = true;
        },
        error: function (textStatus, errorThrown) {
            Success = false;
        }
    });
    //done after here
    return Success;
} 

You can only return the values from a synchronous function. Otherwise you will have to make a callback.

So I just added async:false, to your ajax call

Update:

jquery ajax calls are asynchronous by default. So success & error functions will be called when the ajax load is complete. But your return statement will be executed just after the ajax call is started.

A better approach will be:

     // callbackfn is the pointer to any function that needs to be called
     function ChangePurpose(Vid, PurId, callbackfn) {
        var Success = false;
        $.ajax({
            type: "POST",
            url: "CHService.asmx/SavePurpose",
            dataType: "text",
            data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                callbackfn(data)
            },
            error: function (textStatus, errorThrown) {
                callbackfn("Error getting the data")
            }
        });
     } 

     function Callback(data)
     {
        alert(data);
     }

and call the ajax as:

 // Callback is the callback-function that needs to be called when asynchronous call is complete
 ChangePurpose(Vid, PurId, Callback);

How to format a java.sql Timestamp for displaying?

Use a DateFormat. In an internationalized application, use the format provide by getInstance. If you want to explicitly control the format, create a new SimpleDateFormat yourself.

Converting bool to text in C++

Without dragging ostream into it:

constexpr char const* to_c_str(bool b) {
   return  
    std::array<char const*, 2>{"false", "true "}[b]
   ;
};

How to add items to a spinner in Android?

An easier way is to use the material spinner library: https://github.com/jaredrummler/MaterialSpinner

first add to your project:

compile 'com.jaredrummler:material-spinner:1.2.4'

and use like this:

<com.jaredrummler.materialspinner.MaterialSpinner
    android:id="@+id/spinner"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

and java code that you can add items in java so easy:

MaterialSpinner spinner = (MaterialSpinner) findViewById(R.id.spinner);
spinner.setItems("item 1", "item 2", "item 3", "item 4", "item 5");
spinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {

  @Override public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
    Snackbar.make(view, "Clicked " + item, Snackbar.LENGTH_LONG).show();
  }
});

How would I extract a single file (or changes to a file) from a git stash?

Use the following to apply the changes to a file in a stash to your working tree.

git diff stash^! -- <filename> | git apply

This is generally better than using git checkout because you won't lose any changes you made to file since you created the stash.

Adding a new SQL column with a default value

Try This :)

ALTER TABLE TABLE_NAME ADD COLUMN_NAME INT NOT NULL DEFAULT 0;

No output to console from a WPF application?

Old post, but I ran into this so if you're trying to output something to Output in a WPF project in Visual Studio, the contemporary method is:

Include this:

using System.Diagnostics;

And then:

Debug.WriteLine("something");

How to run a function in jquery

function doosomething ()
{
  //Doo something
}


$(function () {


  $("div.class").click(doosomething);

  $("div.secondclass").click(doosomething);

});

Iterator invalidation rules

C++17 (All references are from the final working draft of CPP17 - n4659)


Insertion

Sequence Containers

  • vector: The functions insert, emplace_back, emplace, push_back cause reallocation if the new size is greater than the old capacity. Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. If no reallocation happens, all the iterators and references before the insertion point remain valid. [26.3.11.5/1]
    With respect to the reserve function, reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. No reallocation shall take place during insertions that happen after a call to reserve() until the time when an insertion would make the size of the vector greater than the value of capacity(). [26.3.11.3/6]

  • deque: An insertion in the middle of the deque invalidates all the iterators and references to elements of the deque. An insertion at either end of the deque invalidates all the iterators to the deque, but has no effect on the validity of references to elements of the deque. [26.3.8.4/1]

  • list: Does not affect the validity of iterators and references. If an exception is thrown there are no effects. [26.3.10.4/1].
    The insert, emplace_front, emplace_back, emplace, push_front, push_back functions are covered under this rule.

  • forward_list: None of the overloads of insert_after shall affect the validity of iterators and references [26.3.9.5/1]

  • array: As a rule, iterators to an array are never invalidated throughout the lifetime of the array. One should take note, however, that during swap, the iterator will continue to point to the same array element, and will thus change its value.

Associative Containers

  • All Associative Containers: The insert and emplace members shall not affect the validity of iterators and references to the container [26.2.6/9]

Unordered Associative Containers

  • All Unordered Associative Containers: Rehashing invalidates iterators, changes ordering between elements, and changes which buckets elements appear in, but does not invalidate pointers or references to elements. [26.2.7/9]
    The insert and emplace members shall not affect the validity of references to container elements, but may invalidate all iterators to the container. [26.2.7/14]
    The insert and emplace members shall not affect the validity of iterators if (N+n) <= z * B, where N is the number of elements in the container prior to the insert operation, n is the number of elements inserted, B is the container’s bucket count, and z is the container’s maximum load factor. [26.2.7/15]

  • All Unordered Associative Containers: In case of a merge operation (e.g., a.merge(a2)), iterators referring to the transferred elements and all iterators referring to a will be invalidated, but iterators to elements remaining in a2 will remain valid. (Table 91 — Unordered associative container requirements)

Container Adaptors

  • stack: inherited from underlying container
  • queue: inherited from underlying container
  • priority_queue: inherited from underlying container

Erasure

Sequence Containers

  • vector: The functions erase and pop_back invalidate iterators and references at or after the point of the erase. [26.3.11.5/3]

  • deque: An erase operation that erases the last element of a deque invalidates only the past-the-end iterator and all iterators and references to the erased elements. An erase operation that erases the first element of a deque but not the last element invalidates only iterators and references to the erased elements. An erase operation that erases neither the first element nor the last element of a deque invalidates the past-the-end iterator and all iterators and references to all the elements of the deque. [ Note: pop_front and pop_back are erase operations. —end note ] [26.3.8.4/4]

  • list: Invalidates only the iterators and references to the erased elements. [26.3.10.4/3]. This applies to erase, pop_front, pop_back, clear functions.
    remove and remove_if member functions: Erases all the elements in the list referred by a list iterator i for which the following conditions hold: *i == value, pred(*i) != false. Invalidates only the iterators and references to the erased elements [26.3.10.5/15].
    unique member function - Erases all but the first element from every consecutive group of equal elements referred to by the iterator i in the range [first + 1, last) for which *i == *(i-1) (for the version of unique with no arguments) or pred(*i, *(i - 1)) (for the version of unique with a predicate argument) holds. Invalidates only the iterators and references to the erased elements. [26.3.10.5/19]

  • forward_list: erase_after shall invalidate only iterators and references to the erased elements. [26.3.9.5/1].
    remove and remove_if member functions - Erases all the elements in the list referred by a list iterator i for which the following conditions hold: *i == value (for remove()), pred(*i) is true (for remove_if()). Invalidates only the iterators and references to the erased elements. [26.3.9.6/12].
    unique member function - Erases all but the first element from every consecutive group of equal elements referred to by the iterator i in the range [first + 1, last) for which *i == *(i-1) (for the version with no arguments) or pred(*i, *(i - 1)) (for the version with a predicate argument) holds. Invalidates only the iterators and references to the erased elements. [26.3.9.6/16]

  • All Sequence Containers: clear invalidates all references, pointers, and iterators referring to the elements of a and may invalidate the past-the-end iterator (Table 87 — Sequence container requirements). But for forward_list, clear does not invalidate past-the-end iterators. [26.3.9.5/32]

  • All Sequence Containers: assign invalidates all references, pointers and iterators referring to the elements of the container. For vector and deque, also invalidates the past-the-end iterator. (Table 87 — Sequence container requirements)

Associative Containers

  • All Associative Containers: The erase members shall invalidate only iterators and references to the erased elements [26.2.6/9]

  • All Associative Containers: The extract members invalidate only iterators to the removed element; pointers and references to the removed element remain valid [26.2.6/10]

Container Adaptors

  • stack: inherited from underlying container
  • queue: inherited from underlying container
  • priority_queue: inherited from underlying container

General container requirements relating to iterator invalidation:

  • Unless otherwise specified (either explicitly or by defining a function in terms of other functions), invoking a container member function or passing a container as an argument to a library function shall not invalidate iterators to, or change the values of, objects within that container. [26.2.1/12]

  • no swap() function invalidates any references, pointers, or iterators referring to the elements of the containers being swapped. [ Note: The end() iterator does not refer to any element, so it may be invalidated. —end note ] [26.2.1/(11.6)]

As examples of the above requirements:

  • transform algorithm: The op and binary_op functions shall not invalidate iterators or subranges, or modify elements in the ranges [28.6.4/1]

  • accumulate algorithm: In the range [first, last], binary_op shall neither modify elements nor invalidate iterators or subranges [29.8.2/1]

  • reduce algorithm: binary_op shall neither invalidate iterators or subranges, nor modify elements in the range [first, last]. [29.8.3/5]

and so on...

Insert multiple values using INSERT INTO (SQL Server 2005)

In SQL Server 2008,2012,2014 you can insert multiple rows using a single SQL INSERT statement.

 INSERT INTO TableName ( Column1, Column2 ) VALUES
    ( Value1, Value2 ), ( Value1, Value2 )

Another way

INSERT INTO TableName (Column1, Column2 )
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2

How do I configure git to ignore some files locally?

Update: Consider using git update-index --skip-worktree [<file>...] instead, thanks @danShumway! See Borealid's explanation on the difference of the two options.


Old answer:

If you need to ignore local changes to tracked files (we have that with local modifications to config files), use git update-index --assume-unchanged [<file>...].

How do I get the current Date/time in DD/MM/YYYY HH:MM format?

The formatting can be done like this (I assumed you meant HH:MM instead of HH:SS, but it's easy to change):

Time.now.strftime("%d/%m/%Y %H:%M")
#=> "14/09/2011 14:09"

Updated for the shifting:

d = DateTime.now
d.strftime("%d/%m/%Y %H:%M")
#=> "11/06/2017 18:11"
d.next_month.strftime("%d/%m/%Y %H:%M")
#=> "11/07/2017 18:11"

You need to require 'date' for this btw.

Python extending with - using super() Python 3 vs Python 2

  • super() (without arguments) was introduced in Python 3 (along with __class__):

    super() -> same as super(__class__, self)
    

    so that would be the Python 2 equivalent for new-style classes:

    super(CurrentClass, self)
    
  • for old-style classes you can always use:

     class Classname(OldStyleParent):
        def __init__(self, *args, **kwargs):
            OldStyleParent.__init__(self, *args, **kwargs)
    

How to initialize a variable of date type in java?

To parse a Date from a String you can choose which format you would like it to have. For example:

public Date StringToDate(String s){

    Date result = null;
    try{
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        result  = dateFormat.parse(s);
    }

    catch(ParseException e){
        e.printStackTrace();

    }
    return result ;
}

If you would like to use this method now, you will have to use something like this

Date date = StringToDate("2015-12-06 17:03:00");

For more explanation you should check out http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Angular2 Exception: Can't bind to 'routerLink' since it isn't a known native property

In my case I have imported the RouterModule in App module but not imported in my feature module. After import the router module in my EventModule the error goes away.

    import {NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import {EventListComponent} from './EventList.Component';
    import {EventThumbnailComponent} from './EventThumbnail.Component';
    import { EventService } from './shared/Event.Service'
    import {ToastrService} from '../shared/toastr.service';
    import {EventDetailsComponent} from './event-details/event.details.component';
    import { RouterModule } from "@angular/router";
    @NgModule({
      imports:[BrowserModule,RouterModule],
      declarations:[EventThumbnailComponent,EventListComponent,EventDetailsComponent],
      exports: [EventThumbnailComponent,EventListComponent,EventDetailsComponent],
       providers: [EventService,ToastrService]
    })
    export class EventModule {
        
     }

Delete ActionLink with confirm dialog

<%= Html.ActionLink("Delete", "Delete",
    new { id = item.storyId }, 
    new { onclick = "return confirm('Are you sure you wish to delete this article?');" })     %>

The above code only works for Html.ActionLink.

For

Ajax.ActionLink

use the following code:

<%= Ajax.ActionLink(" ", "deleteMeeting", new { id = Model.eventID, subid = subItem.ID, fordate = forDate, forslot = forslot }, new AjaxOptions
                                            {
                                                Confirm = "Are you sure you wish to delete?",
                                                UpdateTargetId = "Appointments",
                                                HttpMethod = "Get",
                                                InsertionMode = InsertionMode.Replace,
                                                LoadingElementId = "div_loading"
                                            }, new { @class = "DeleteApointmentsforevent" })%>

The 'Confirm' option specifies javascript confirm box.

How to pass variable from jade template file to a script file?

Here's how I addressed this (using a MEAN derivative)

My variables:

{
  NODE_ENV : development,
  ...
  ui_varables {
     var1: one,
     var2: two
  }
}

First I had to make sure that the necessary config variables were being passed. MEAN uses the node nconf package, and by default is set up to limit which variables get passed from the environment. I had to remedy that:

config/config.js:

original:

nconf.argv()
  .env(['PORT', 'NODE_ENV', 'FORCE_DB_SYNC'] ) // Load only these environment variables
  .defaults({
  store: {
    NODE_ENV: 'development'
  }
});

after modifications:

nconf.argv()
  .env('__') // Load ALL environment variables
  // double-underscore replaces : as a way to denote hierarchy
  .defaults({
  store: {
    NODE_ENV: 'development'
  }
});

Now I can set my variables like this:

export ui_varables__var1=first-value
export ui_varables__var2=second-value

Note: I reset the "heirarchy indicator" to "__" (double underscore) because its default was ":", which makes variables more difficult to set from bash. See another post on this thread.

Now the jade part: Next the values need to be rendered, so that javascript can pick them up on the client side. A straightforward way to write these values to the index file. Because this is a one-page app (angular), this page is always loaded first. I think ideally this should be a javascript include file (just to keep things clean), but this is good for a demo.

app/controllers/index.js:

'use strict';
var config = require('../../config/config');

exports.render = function(req, res) {
  res.render('index', {
    user: req.user ? JSON.stringify(req.user) : "null",
    //new lines follow:
    config_defaults : {
       ui_defaults: JSON.stringify(config.configwriter_ui).replace(/<\//g, '<\\/')  //NOTE: the replace is xss prevention
    }
  });
};

app/views/index.jade:

extends layouts/default

block content
  section(ui-view)
    script(type="text/javascript").
    window.user = !{user};
    //new line here
    defaults = !{config_defaults.ui_defaults};

In my rendered html, this gives me a nice little script:

<script type="text/javascript">
 window.user = null;         
 defaults = {"var1":"first-value","var2:"second-value"};
</script>        

From this point it's easy for angular to utilize the code.

Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?

Firstly create app.js file in the directory you want to publish.

var http = require('http');
var fs = require('fs');
var mime = require('mime');
http.createServer(function(req,res){
    if (req.url != '/app.js') {
    var url = __dirname + req.url;
        fs.stat(url,function(err,stat){
            if (err) {
            res.writeHead(404,{'Content-Type':'text/html'});
            res.end('Your requested URI('+req.url+') wasn\'t found on our server');
            } else {
            var type = mime.getType(url);
            var fileSize = stat.size;
            var range = req.headers.range;
                if (range) {
                    var parts = range.replace(/bytes=/, "").split("-");
                var start = parseInt(parts[0], 10);
                    var end = parts[1] ? parseInt(parts[1], 10) : fileSize-1;
                    var chunksize = (end-start)+1;
                    var file = fs.createReadStream(url, {start, end});
                    var head = {
                'Content-Range': `bytes ${start}-${end}/${fileSize}`,
                'Accept-Ranges': 'bytes',
                'Content-Length': chunksize,
                'Content-Type': type
                }
                    res.writeHead(206, head);
                    file.pipe(res);
                    } else {    
                    var head = {
                'Content-Length': fileSize,
                'Content-Type': type
                    }
                res.writeHead(200, head);
                fs.createReadStream(url).pipe(res);
                    }
            }
        });
    } else {
    res.writeHead(403,{'Content-Type':'text/html'});
    res.end('Sorry, access to that file is Forbidden');
    }
}).listen(8080);

Simply run node app.js and your server shall be running on port 8080. Besides video it can stream all kinds of files.

How to use adb command to push a file on device without sd card

Sometimes you need the extension,

adb push file.zip /sdcard/file.zip

Insert a string at a specific index

Using slice

You can use slice(0,index) + str + slice(index). Or you can create a method for it.

_x000D_
_x000D_
String.prototype.insertAt = function(index,str){_x000D_
  return this.slice(0,index) + str + this.slice(index)_x000D_
}_x000D_
console.log("foo bar".insertAt(4,'baz ')) //foo baz bar
_x000D_
_x000D_
_x000D_

Splice method for Strings

You can split() the main string and add then use normal splice()

_x000D_
_x000D_
String.prototype.splice = function(index,del,...newStrs){_x000D_
  let str = this.split('');_x000D_
  str.splice(index,del,newStrs.join('') || '');_x000D_
  return str.join('');_x000D_
}_x000D_
_x000D_
_x000D_
 var txt1 = "foo baz"_x000D_
_x000D_
//inserting single string._x000D_
console.log(txt1.splice(4,0,"bar ")); //foo bar baz_x000D_
_x000D_
_x000D_
//inserting multiple strings_x000D_
console.log(txt1.splice(4,0,"bar ","bar2 ")); //foo bar bar2 baz_x000D_
_x000D_
_x000D_
//removing letters_x000D_
console.log(txt1.splice(1,2)) //f baz_x000D_
_x000D_
_x000D_
//remving and inseting atm_x000D_
console.log(txt1.splice(1,2," bar")) //f bar baz
_x000D_
_x000D_
_x000D_

Applying splice() at multiple indexes

The method takes an array of arrays each element of array representing a single splice().

_x000D_
_x000D_
String.prototype.splice = function(index,del,...newStrs){_x000D_
  let str = this.split('');_x000D_
  str.splice(index,del,newStrs.join('') || '');_x000D_
  return str.join('');_x000D_
}_x000D_
_x000D_
_x000D_
String.prototype.mulSplice = function(arr){_x000D_
  str = this_x000D_
  let dif = 0;_x000D_
  _x000D_
  arr.forEach(x => {_x000D_
    x[2] === x[2] || [];_x000D_
    x[1] === x[1] || 0;_x000D_
    str = str.splice(x[0] + dif,x[1],...x[2]);_x000D_
    dif += x[2].join('').length - x[1];_x000D_
  })_x000D_
  return str;_x000D_
}_x000D_
_x000D_
let txt = "foo bar baz"_x000D_
_x000D_
//Replacing the 'foo' and 'bar' with 'something1' ,'another'_x000D_
console.log(txt.splice(0,3,'something'))_x000D_
console.log(txt.mulSplice(_x000D_
[_x000D_
[0,3,["something1"]],_x000D_
[4,3,["another"]]_x000D_
]_x000D_
_x000D_
))
_x000D_
_x000D_
_x000D_

The type initializer for 'MyClass' threw an exception

I've had the same problem caused by having two of the same configuration properties (which matches the app.config):

[ConfigurationProperty("TransferTimeValidity")]

How to write files to assets folder or raw folder in android?

Why not update the files on the local file system instead? You can read/write files into your applications sandboxed area.

http://developer.android.com/guide/topics/data/data-storage.html#filesInternal

Other alternatives you may want to look into are Shared Perferences and using Cache Files (all described at the link above)

Copy values from one column to another in the same table

Following worked for me..

  1. Ensure you are not using Safe-mode in your query editor application. If you are, disable it!
  2. Then run following sql command

for a table say, 'test_update_cmd', source value column col2, target value column col1 and condition column col3: -

UPDATE  test_update_cmd SET col1=col2 WHERE col3='value';

Good Luck!

Angular ng-if="" with multiple arguments

Yes, it's possible. for example checkout:

<div class="singleMatch" ng-if="match.date | date:'ddMMyyyy' === main.date &&  match.team1.code === main.team1code && match.team2.code === main.team2code">
    //Do something here
    </div>

Get only records created today in laravel

$records = User::where('created_at' = CURDATE())->GET()); print($records);

Including non-Python files with setup.py

I wanted to post a comment to one of the questions but I don't enough reputation to do that >.>

Here's what worked for me (came up with it after referring the docs):

package_data={
    'mypkg': ['../*.txt']
},

include_package_data: False

The last line was, strangely enough, also crucial for me (you can also omit this keyword argument - it works the same).

What this does is it copies all text files in your top-level or root directory (one level up from the package mypkg you want to distribute).

Hope this helps!

How to pass optional arguments to a method in C++?

Typically by setting a default value for a parameter:

int func(int a, int b = -1) { 
    std::cout << "a = " << a;
    if (b != -1)        
        std::cout << ", b = " << b;
    std::cout << "\n";
}

int main() { 
    func(1, 2);  // prints "a=1, b=2\n"
    func(3);     // prints "a=3\n"
    return 0;
}

remove None value from a list without removing the 0 value

@jamylak answer is quite nice, however if you don't want to import a couple of modules just to do this simple task, write your own lambda in-place:

>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> filter(lambda v: v is not None, L)
[0, 23, 234, 89, 0, 35, 9]

How to send POST request?

If you don't want to use a module you have to install like requests, and your use case is very basic, then you can use urllib2

urllib2.urlopen(url, body)

See the documentation for urllib2 here: https://docs.python.org/2/library/urllib2.html.

How to change a TextView's style at runtime

Depending on which style you want to set, you have to use different methods. TextAppearance stuff has its own setter, TypeFace has its own setter, background has its own setter, etc.

Should a function have only one return statement?

Nobody has mentioned or quoted Code Complete so I'll do it.

17.1 return

Minimize the number of returns in each routine. It's harder to understand a routine if, reading it at the bottom, you're unaware of the possibility that it returned somewhere above.

Use a return when it enhances readability. In certain routines, once you know the answer, you want to return it to the calling routine immediately. If the routine is defined in such a way that it doesn't require any cleanup, not returning immediately means that you have to write more code.

How to get File Created Date and Modified Date

You could use below code:

DateTime creation = File.GetCreationTime(@"C:\test.txt");
DateTime modification = File.GetLastWriteTime(@"C:\test.txt");

How can I hide select options with JavaScript? (Cross browser)

On pure JS:

let select = document.getElementById("select_id")                   
let to_hide = select[select.selectedIndex];
to_hide.setAttribute('hidden', 'hidden');

to unhide just

to_hide.removeAttr('hidden');

or

to_hide.hidden = true;   // to hide
to_hide.hidden = false;  // to unhide

C++ IDE for Macs

Xcode which is part of the MacOS Developer Tools is a great IDE. There's also NetBeans and Eclipse that can be configured to build and compile C++ projects.

Clion from JetBrains, also is available now, and uses Cmake as project model.

What in layman's terms is a Recursive Function using PHP

Recursion is an alternative to loops, it's quite seldom that they bring more clearness or elegance to your code. A good example was given by Progman's answer, if he wouldn't use recursion he would be forced to keep track in which directory he is currently (this is called state) recursions allows him to do the bookkeeping using the stack (the area where variables and return adress of a method are stored)

The standard examples factorial and Fibonacci are not useful for understanding the concept because they're easy to replace by a loop.

Scatter plot and Color mapping in Python

To add to wflynny's answer above, you can find the available colormaps here

Example:

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

or alternatively,

plt.scatter(x, y, c=t, cmap='jet')

SaveFileDialog setting default path and file type?

Here's an example that actually filters for BIN files. Also Windows now want you to save files to user locations, not system locations, so here's an example (you can use intellisense to browse the other options):

            var saveFileDialog = new Microsoft.Win32.SaveFileDialog()
            {
                DefaultExt = "*.xml",
                Filter = "BIN Files (*.bin)|*.bin",
                InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
            };

            var result = saveFileDialog.ShowDialog();
            if (result != null && result == true)
            {
                // Save the file here
            }

jQuery hasClass() - check for more than one class

Works for me:

 if ( $("element").hasClass( "class1") || $("element").hasClass("class2") ) {

 //do something here

 }

Original purpose of <input type="hidden">?

The values of form elements including type='hidden' are submitted to the server when the form is posted. input type="hidden" values are not visible in the page. Maintaining User IDs in hidden fields, for example, is one of the many uses.

SO uses a hidden field for the upvote click.

<input value="16293741" name="postId" type="hidden">

Using this value, the server-side script can store the upvote.

using href links inside <option> tag

The <select> tag creates a dropdown list. You can't put html links inside a dropdown.

However, there are JavaScript libraries that provide similar functionality. Here is one example: http://www.dynamicdrive.com/dynamicindex1/dropmenuindex.htm

print highest value in dict with key

just :

 mydict = {'A':4,'B':10,'C':0,'D':87}
 max(mydict.items(), key=lambda x: x[1])

add column to mysql table if it does not exist

$smpt = $pdo->prepare("SHOW fields FROM __TABLE__NAME__");
$smpt->execute();
$res = $smpt->fetchAll(PDO::FETCH_ASSOC);
//print_r($res);

Then in $res by cycle look for key of your column Smth like this:

    if($field['Field'] == '_my_col_'){
       return true;
    }
+

**Below code is good for checking column existing in the WordPress tables:**
public static function is_table_col_exists($table, $col)
    {
        global $wpdb;
        $fields = $wpdb->get_results("SHOW fields FROM {$table}", ARRAY_A);
        foreach ($fields as $field)
        {
            if ($field['Field'] == $col)
            {
                return TRUE;
            }
        }

        return FALSE;
    }

How to loop through a dataset in powershell?

The parser is having trouble concatenating your string. Try this:

write-host 'value is : '$i' '$($ds.Tables[1].Rows[$i][0])

Edit: Using double quotes might also be clearer since you can include the expressions within the quoted string:

write-host "value is : $i $($ds.Tables[1].Rows[$i][0])"

C++ - Assigning null to a std::string

There are two methods to consider which achieve the same effect for handling null pointers to C-style strings.

The ternary operator

void setvalue(const char *value)
{
    std::string mValue = value ? value : "";

}

or the humble if statement

void setvalue(const char *value)
{
    std::string mValue;
    if(value) mValue = value;

}

In both cases, value is only assigned to mValue when value is not a null pointer. In all other cases (i.e. when value is null), mValue will contain an empty string.

The ternary operator method may be useful for providing an alternative default string literal in the absence of a value from value:

std::string mValue = value ? value : "(NULL)";

How to generate sample XML documents from their DTD or XSD?

In Visual Studio 2008 SP1 and later the XML Schema Explorer can create an XML document with some basic sample data:

  1. Open your XSD document
  2. Switch to XML Schema Explorer
  3. Right click the root node and choose "Generate Sample Xml"

Screenshot of the XML Schema Explorer

Installing Apple's Network Link Conditioner Tool

It's in an additional download. Use this menu item:

Xcode > Open Developer Tool > More Developer Tools...

and get "Hardware IO Tools for Xcode".

For Xcode 8+, get "Additional Tools for Xcode [version]".

Double-click on a .prefPane file to install. If you already have an older .prefPane installed, you'll need to remove it from /Library/PreferencePanes.

How do I disable and re-enable a button in with javascript?

you can try with

document.getElementById('btn').disabled = !this.checked"

_x000D_
_x000D_
<input type="submit" name="btn"  id="btn" value="submit" disabled/>_x000D_
_x000D_
<input type="checkbox"  onchange="document.getElementById('btn').disabled = !this.checked"/>
_x000D_
_x000D_
_x000D_

Java double.MAX_VALUE?

this states that Account.deposit(Double.MAX_VALUE); it is setting deposit value to MAX value of Double dataType.to procced for running tests.

What does the exclamation mark do before the function?

There is a good point for using ! for function invocation marked on airbnb JavaScript guide

Generally idea for using this technique on separate files (aka modules) which later get concatenated. The caveat here is that files supposed to be concatenated by tools which put the new file at the new line (which is anyway common behavior for most of concat tools). In that case, using ! will help to avoid error in if previously concatenated module missed trailing semicolon, and yet that will give the flexibility to put them in any order with no worry.

!function abc(){}();
!function bca(){}();

Will work the same as

!function abc(){}();
(function bca(){})();

but saves one character and arbitrary looks better.

And by the way any of +,-,~,void operators have the same effect, in terms of invoking the function, for sure if you have to use something to return from that function they would act differently.

abcval = !function abc(){return true;}() // abcval equals false
bcaval = +function bca(){return true;}() // bcaval equals 1
zyxval = -function zyx(){return true;}() // zyxval equals -1
xyzval = ~function xyz(){return true;}() // your guess?

but if you using IIFE patterns for one file one module code separation and using concat tool for optimization (which makes one line one file job), then construction

!function abc(/*no returns*/) {}()
+function bca() {/*no returns*/}()

Will do safe code execution, same as a very first code sample.

This one will throw error cause JavaScript ASI will not be able to do its work.

!function abc(/*no returns*/) {}()
(function bca() {/*no returns*/})()

One note regarding unary operators, they would do similar work, but only in case, they used not in the first module. So they are not so safe if you do not have total control over the concatenation order.

This works:

!function abc(/*no returns*/) {}()
^function bca() {/*no returns*/}()

This not:

^function abc(/*no returns*/) {}()
!function bca() {/*no returns*/}()

Bootstrap 3: Text overlay on image

Set the position to absolute; to move the caption area in the correct position

CSS

.post-content {
    background: none repeat scroll 0 0 #FFFFFF;
    opacity: 0.5;
    margin: -54px 20px 12px; 
    position: absolute;
}

Bootply

Count number of files within a directory in Linux?

this is one:

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

Note:

ls -1 | wc -l

Which means: ls: list files in dir

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

|: pipe output onto...

wc: "wordcount"

-l: count lines.

Strip Leading and Trailing Spaces From Java String

You can try the trim() method.

String newString = oldString.trim();

Take a look at javadocs

"pip install json" fails on Ubuntu

json is a built-in module, you don't need to install it with pip.

How to get first character of a string in SQL?

INPUT

STRMIDDLENAME
--------------
Aravind Chaterjee
Shivakumar
Robin Van Parsee

SELECT STRMIDDLENAME, 
CASE WHEN INSTR(STRMIDDLENAME,' ',1,2) != 0 THEN SUBSTR(STRMIDDLENAME,1,1) || SUBSTR(STRMIDDLENAME,INSTR(STRMIDDLENAME,' ',1,1)+1,1)||
SUBSTR(STRMIDDLENAME,INSTR(STRMIDDLENAME,' ',1,2)+1,1)
WHEN INSTR(STRMIDDLENAME,' ',1,1) != 0 THEN SUBSTR(STRMIDDLENAME,1,1) || SUBSTR(STRMIDDLENAME,INSTR(STRMIDDLENAME,' ',1,1)+1,1)
ELSE SUBSTR(STRMIDDLENAME,1,1)
END AS FIRSTLETTERS
FROM Dual;

OUTPUT
STRMIDDLENAME                    FIRSTLETTERS
---------                        -----------------
Aravind Chaterjee                AC           
Shivakumar                       S
Robin Van Parsee                 RVP

How do I join two SQLite tables in my Android application?

In addition to @pawelzieba's answer, which definitely is correct, to join two tables, while you can use an INNER JOIN like this

SELECT * FROM expense INNER JOIN refuel
ON exp_id = expense_id
WHERE refuel_id = 1

via raw query like this -

String rawQuery = "SELECT * FROM " + RefuelTable.TABLE_NAME + " INNER JOIN " + ExpenseTable.TABLE_NAME
        + " ON " + RefuelTable.EXP_ID + " = " + ExpenseTable.ID
        + " WHERE " + RefuelTable.ID + " = " +  id;
Cursor c = db.rawQuery(
        rawQuery,
        null
);

because of SQLite's backward compatible support of the primitive way of querying, we turn that command into this -

SELECT *
FROM expense, refuel
WHERE exp_id = expense_id AND refuel_id = 1

and hence be able to take advanatage of the SQLiteDatabase.query() helper method

Cursor c = db.query(
        RefuelTable.TABLE_NAME + " , " + ExpenseTable.TABLE_NAME,
        Utils.concat(RefuelTable.PROJECTION, ExpenseTable.PROJECTION),
        RefuelTable.EXP_ID + " = " + ExpenseTable.ID + " AND " + RefuelTable.ID + " = " +  id,
        null,
        null,
        null,
        null
);

For a detailed blog post check this http://blog.championswimmer.in/2015/12/doing-a-table-join-in-android-without-using-rawquery

How to add a new audio (not mixing) into a video using ffmpeg?

If you are using an old version of FFMPEG and you cant upgrade you can do the following:

ffmpeg -i PATH/VIDEO_FILE_NAME.mp4 -i PATH/AUDIO_FILE_NAME.mp3 -vcodec copy -shortest DESTINATION_PATH/NEW_VIDEO_FILE_NAME.mp4

Notice that I used -vcodec

Assembly - JG/JNLE/JL/JNGE after CMP

Addition and subtraction in two's complement is the same for signed and unsigned numbers

The key observation is that CMP is basically subtraction, and:

In two's complement (integer representation used by x86), signed and unsigned addition are exactly the same operation

This allows for example hardware developers to implement it more efficiently with just one circuit.

So when you give input bytes to the x86 ADD instruction for example, it does not care if they are signed or not.

However, ADD does set a few flags depending on what happened during the operation:

  • carry: unsigned addition or subtraction result does not fit in bit size, e.g.: 0xFF + 0x01 or 0x00 - 0x01

    For addition, we would need to carry 1 to the next level.

  • sign: result has top bit set. I.e.: is negative if interpreted as signed.

  • overflow: input top bits are both 0 and 0 or 1 and 1 and output inverted is the opposite.

    I.e. signed operation changed sigedness in an impossible way (e.g. positive + positive or negative

We can then interpret those flags in a way that makes comparison match our expectations for signed or unsigned numbers.

This interpretation is exactly what JA vs JG and JB vs JL do for us!

Code example

Here is GNU GAS a code snippet to make this more concrete:

/* 0x0 ==
 *
 * * 0 in 2's complement signed
 * * 0 in 2's complement unsigned
 */
mov $0, %al

/* 0xFF ==
 *
 * *  -1 in 2's complement signed
 * * 255 in 2's complement unsigned
 */
mov $0xFF, %bl

/* Do the operation "Is al < bl?" */
cmp %bl, %al

Note that AT&T syntax is "backwards": mov src, dst. So you have to mentally reverse the operands for the condition codes to make sense with cmp. In Intel syntax, this would be cmp al, bl

After this point, the following jumps would be taken:

  • JB, because 0 < 255
  • JNA, because !(0 > 255)
  • JNL, because !(0 < -1)
  • JG, because 0 > -1

Note how in this particular example the signedness mattered, e.g. JB is taken but not JL.

Runnable example with assertions.

Equals / Negated versions like JLE / JNG are just aliases

By looking at the Intel 64 and IA-32 Architectures Software Developer's Manuals Volume 2 section "Jcc - Jump if Condition Is Met" we see that the encodings are identical, for example:

Opcode  Instruction  Description
7E cb   JLE rel8     Jump short if less or equal (ZF=1 or SF ? OF).
7E cb   JNG rel8     Jump short if not greater (ZF=1 or SF ? OF).

What is the difference between a JavaBean and a POJO?

You've seen the formal definitions above, for all they are worth.

But don't get too hung up on definitions. Let's just look more at the sense of things here.

JavaBeans are used in Enterprise Java applications, where users frequently access data and/or application code remotely, i.e. from a server (via web or private network) via a network. The data involved must therefore be streamed in serial format into or out of the users' computers - hence the need for Java EE objects to implement the interface Serializable. This much of a JavaBean's nature is no different to Java SE application objects whose data is read in from, or written out to, a file system. Using Java classes reliably over a network from a range of user machine/OS combinations also demands the adoption of conventions for their handling. Hence the requirement for implementing these classes as public, with private attributes, a no-argument constructor and standardised getters and setters.

Java EE applications will also use classes other than those that were implemented as JavaBeans. These could be used in processing input data or organizing output data but will not be used for objects transferred over a network. Hence the above considerations need not be applied to them bar that the be valid as Java objects. These latter classes are referred to as POJOs - Plain Old Java Objects.

All in all, you could see Java Beans as just Java objects adapted for use over a network.

There's an awful lot of hype - and no small amount of humbug - in the software world since 1995.

What is python's site-packages directory?

When you use --user option with pip, the package gets installed in user's folder instead of global folder and you won't need to run pip command with admin privileges.

The location of user's packages folder can be found using:

python -m site --user-site

This will print something like:

C:\Users\%USERNAME%\AppData\Roaming\Python\Python35\site-packages

When you don't use --user option with pip, the package gets installed in global folder given by:

python -c "import site; print(site.getsitepackages())"

This will print something like:

['C:\\Program Files\\Anaconda3', 'C:\\Program Files\\Anaconda3\\lib\\site-packages'

Note: Above printed values are for On Windows 10 with Anaconda 4.x installed with defaults.

Angular 4 default radio button checked by default

getting following error

_x000D_
_x000D_
It happens:  Error: 
      ngModel cannot be used to register form controls with a parent formGroup directive.  Try using
      formGroup's partner directive "formControlName" instead.  Example:
_x000D_
_x000D_
_x000D_

How to take a first character from the string

"ABCDEFG".First returns "A"

Dim s as string

s = "Rajan"
s.First
'R

s = "Sajan"
s.First
'S

Failed to create provisioning profile

I have had this error multiple times and what solves it for me is the following:

  1. In the list with the view of all certificates, right click on each row and move each certificate to trash (go to Xcode > Preferences > Choose account > Click View Details)
  2. Go to member center download the right certificates again and click on them so
  3. Restart Xcode
  4. Go to build settings and set the right Code signing for debug/release - you should be able to see an option on the row that says "Identities from profile..."

If this doesn't work then you should consider revoking your certificate and then create a new one and the do the steps above again.

Angular 6: saving data to local storage

You should define a key name while storing data to local storage which should be a string and value should be a string

 localStorage.setItem('dataSource', this.dataSource.length);

and to print, you should use getItem

console.log(localStorage.getItem('dataSource'));

HTML 5 video or audio playlist

There's no way to define a playlist using just a <video> or <audio> tag, but there are ways of controlling them, so you can simulate a playlist using JavaScript. Check out sections 4.8.7, 4.8.9 (especially 4.8.9.12) of the HTML5 spec. Hopefully the majority of methods and events are implemented on modern browsers such as Chrome and Firefox (latest versions, of course).

How to get files in a relative path in C#

To make sure you have the application's path (and not just the current directory), use this:

http://msdn.microsoft.com/en-us/library/system.diagnostics.process.getcurrentprocess.aspx

Now you have a Process object that represents the process that is running.

Then use Process.MainModule.FileName:

http://msdn.microsoft.com/en-us/library/system.diagnostics.processmodule.filename.aspx

Finally, use Path.GetDirectoryName to get the folder containing the .exe:

http://msdn.microsoft.com/en-us/library/system.io.path.getdirectoryname.aspx

So this is what you want:

string folder = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + @"\Archive\";
string filter = "*.zip";
string[] files = Directory.GetFiles(folder, filter);

(Notice that "\Archive\" from your question is now @"\Archive\": you need the @ so that the \ backslashes aren't interpreted as the start of an escape sequence)

Hope that helps!

Dart: mapping a list (list.map)

tabs: [...data.map((title) { return Text(title);}).toList(), extra_widget],

tabs: data.map((title) { return Text(title);}).toList(),

It's working fine for me

Set transparent background using ImageMagick and commandline prompt

Using ImageMagick, this is very similar to hackerb9 code and result, but is a little simpler command line. It does assume that the top left pixel is the background color. I just flood fill the background with transparency, then select the alpha channel and blur it and remove half of the blurred area using -level 50x100%. Then turn back on all the channels and flatten it against the brown color. The -blur 0x1 -level 50x100% acts to antialias the boundaries of the alpha channel transparency. You can adjust the fuzz value, blur amount and the -level 50% value to change the degree of antialiasing.

convert logo: -fuzz 25% -fill none -draw "matte 0,0 floodfill" -channel alpha -blur 0x1 -level 50x100% +channel -background saddlebrown -flatten result.jpg

enter image description here

How can the error 'Client found response content type of 'text/html'.. be interpreted

Is your webservice configured correctly in IIS? The pool its using, the version of ASP.NET (2.0) is set? Can you browse the .asmx?

Talking about exceptions, try to put an try-catch block in the line that access your webservice. Put and catch(System.Web.Services.Protocolos.SoapException).

Also, you can set a Timeout for your webservice object.

Change the selected value of a drop-down list with jQuery

These solutions seem to assume that each item in your drop down lists has a val() value relating to their position in the drop down list.

Things are a little more complicated if this isn't the case.

To read the selected index of a drop down list, you would use this:

$("#dropDownList").prop("selectedIndex");

To set the selected index of a drop down list, you would use this:

$("#dropDownList").prop("selectedIndex", 1);

Note that the prop() feature requires JQuery v1.6 or later.

Let's see how you would use these two functions.

Supposing you had a drop down list of month names.

<select id="listOfMonths">
  <option id="JAN">January</option>
  <option id="FEB">February</option>
  <option id="MAR">March</option>
</select>

You could add a "Previous Month" and "Next Month" button, which looks at the currently selected drop down list item, and changes it to the previous/next month:

<button id="btnPrevMonth" title="Prev" onclick="btnPrevMonth_Click();return false;" />
<button id="btnNextMonth" title="Next" onclick="btnNextMonth_Click();return false;" />

And here's the JavaScript which these buttons would run:

function btnPrevMonth_Click() {
    var selectedIndex = $("#listOfMonths").prop("selectedIndex");
    if (selectedIndex > 0) {
        $("#listOfMonths").prop("selectedIndex", selectedIndex - 1);
    }
}
function btnNextMonth_Click() {
    //  Note:  the JQuery "prop" function requires JQuery v1.6 or later
    var selectedIndex = $("#listOfMonths").prop("selectedIndex");
    var itemsInDropDownList = $("#listOfMonths option").length;

    //  If we're not already selecting the last item in the drop down list, then increment the SelectedIndex
    if (selectedIndex < (itemsInDropDownList - 1)) {
        $("#listOfMonths").prop("selectedIndex", selectedIndex + 1);
    }
}

My site is also useful for showing how to populate a drop down list with JSON data:

http://mikesknowledgebase.com/pages/Services/WebServices-Page8.htm

Can I use an image from my local file system as background in HTML?

background: url(../images/backgroundImage.jpg) no-repeat center center fixed;

this should help

Detecting locked tables (locked by LOCK TABLE)

The following answer was written by Eric Leschinki in 2014/15 at https://stackoverflow.com/a/26743484/1709587 (now deleted):

Mini walkthrough on how to detect locked tables:

This may prevent the database from enforcing atomicity in the affected tables and rows. The locks were designed to make sure things stay consistent and this procedure will prevent that process from taking place as designed.

Create your table, insert some rows

create table penguins(spam int, ham int);
insert into penguins(spam, ham) values (3, 4);

show open tables:

show open tables like "penguins"

prints:

your_database penguins    0   0

Penguins isn't locked, lets lock it:

LOCK TABLES penguins READ;

Check if it's locked:

show open tables like "penguins"

Prints:

your_database, penguins 1, 0

Aha! It is locked! Lets unlock it:

unlock tables

Now it is unlocked:

show open tables like "penguins"

Prints:

your_database penguins    0   0

show all current locks

show open tables where in_use <> 0

It would be much more helpful if the MySQL developers put this information in a regular table (so I can do a select my_items from my_table where my_clauses), rather than this stripped down 'show table' syntax from system variables.

Building executable jar with maven?

Right click the project and give maven build,maven clean,maven generate resource and maven install.The jar file will automatically generate.

Extracting specific columns from a data frame

df<- dplyr::select ( df,A,B,C)

Also, you can assign a different name to the newly created data

data<- dplyr::select ( df,A,B,C)

How to check if a double is null?

I believe Double.NaN might be able to cover this. That is the only 'null' value double contains.

How to convert hashmap to JSON object in Java

this works for me :

import groovy.json.JsonBuilder
properties = new Properties()
properties.put("name", "zhangsan")

println new JsonBuilder(properties).toPrettyString()

jQuery textbox change event

You can achieve it:

 $(document).ready(function(){              
     $('#textBox').keyup(function () {alert('changed');});
 });

or with change (handle copy paste with right click):

 $(document).ready(function(){              
     $('#textBox2').change(function () {alert('changed');});
 });

Here is Demo

How to specify test directory for mocha?

Run all files in test_directory including sub directories that match test.js

find ./parent_test_directory -name '*test.js' | xargs mocha -R spec

or use the --recursive switch

mocha --recursive test_directory/

How to see JavaDoc in IntelliJ IDEA?

For me, it wasn't just getting the javadoc window to open, but also getting the complete javadoc to present. You may still get a sparse javadoc that is based solely on the method signature if you are importing libraries from a Maven repository and do not tell Idea to include the javadocs in the download. Be sure to tick the "JavaDocs" option in the "Download Library From Maven Repository" dialog, which can be found under Project Structure -> Projtect Settings -> Libraries.

What's the difference between Cache-Control: max-age=0 and no-cache?

I had this same question, and found some info in my searches (your question came up as one of the results). Here's what I determined...

There are two sides to the Cache-Control header. One side is where it can be sent by the web server (aka. "origin server"). The other side is where it can be sent by the browser (aka. "user agent").


When sent by the origin server

I believe max-age=0 simply tells caches (and user agents) the response is stale from the get-go and so they SHOULD revalidate the response (eg. with the If-Not-Modified header) before using a cached copy, whereas, no-cache tells them they MUST revalidate before using a cached copy. From 14.9.1 What is Cacheable:

no-cache

...a cache MUST NOT use the response to satisfy a subsequent request without successful revalidation with the origin server. This allows an origin server to prevent caching even by caches that have been configured to return stale responses to client requests.

In other words, caches may sometimes choose to use a stale response (although I believe they have to then add a Warning header), but no-cache says they're not allowed to use a stale response no matter what. Maybe you'd want the SHOULD-revalidate behavior when baseball stats are generated in a page, but you'd want the MUST-revalidate behavior when you've generated the response to an e-commerce purchase.

Although you're correct in your comment when you say no-cache is not supposed to prevent storage, it might actually be another difference when using no-cache. I came across a page, Cache Control Directives Demystified, that says (I can't vouch for its correctness):

In practice, IE and Firefox have started treating the no-cache directive as if it instructs the browser not to even cache the page. We started observing this behavior about a year ago. We suspect that this change was prompted by the widespread (and incorrect) use of this directive to prevent caching.

...

Notice that of late, "cache-control: no-cache" has also started behaving like the "no-store" directive.

As an aside, it appears to me that Cache-Control: max-age=0, must-revalidate should basically mean the same thing as Cache-Control: no-cache. So maybe that's a way to get the MUST-revalidate behavior of no-cache, while avoiding the apparent migration of no-cache to doing the same thing as no-store (ie. no caching whatsoever)?


When sent by the user agent

I believe shahkalpesh's answer applies to the user agent side. You can also look at 13.2.6 Disambiguating Multiple Responses.

If a user agent sends a request with Cache-Control: max-age=0 (aka. "end-to-end revalidation"), then each cache along the way will revalidate its cache entry (eg. with the If-Not-Modified header) all the way to the origin server. If the reply is then 304 (Not Modified), the cached entity can be used.

On the other hand, sending a request with Cache-Control: no-cache (aka. "end-to-end reload") doesn't revalidate and the server MUST NOT use a cached copy when responding.

T-SQL and the WHERE LIKE %Parameter% clause

It should be:

...
WHERE LastName LIKE '%' + @LastName + '%';

Instead of:

...
WHERE LastName LIKE '%@LastName%'

How to trigger a phone call when clicking a link in a web page on mobile phone

Want to add an answer here for the sake of completeness.

<a href="tel:1234567">Call 123-4567</a>

Works just fine on most devices. However, on desktops this will appear as a link which does nothing when you click on it so you should consider using CSS to make it conditionally visible only on mobile devices.

Also, you should know that Skype (which is fairly popular) uses a different syntax by default (but can be parametered to use tel:).

<a href="callto:1234567">Call 123-4567</a>

However, I think in latest mobile browsers (I know for sure on Android) now the tel syntax should offer a popup of available applications that can be used to complete the calling action.

How to use forEach in vueJs?

You can also use .map() as:

var list=[];

response.data.message.map(function(value, key) {
     list.push(value);
   });

Is there a Boolean data type in Microsoft SQL Server like there is in MySQL?

Use the Bit datatype. It has values 1 and 0 when dealing with it in native T-SQL

Laravel 5 not finding css files

This works for me

If you migrated .htaccess file from public directory to project folder and altered server.php to index.php in project folder then this should works for you.

<link rel="stylesheet" href="{{ asset('public/css/app.css') }}" type="text/css">

Thanks

HttpRequest maximum allowable size in tomcat?

The full answer

1. The default (fresh install of tomcat)

When you download tomcat from their official website (of today that's tomcat version 9.0.26), all the apps you installed to tomcat can handle HTTP requests of unlimited size, given that the apps themselves do not have any limits on request size.

However, when you try to upload an app in tomcat's manager app, that app has a default war file limit of 50MB. If you're trying to install Jenkins for example which is 77 MB as ot today, it will fail.

2. Configure tomcat's per port http request size limit

Tomcat itself has size limit for each port, and this is defined in conf\server.xml. This is controlled by maxPostSize attribute of each Connector(port). If this attribute does not exist, which it is by default, there is no limit on the request size.

To add a limit to a specific port, set a byte size for the attribute. For example, the below config for the default 8080 port limits request size to 200 MB. This means that all the apps installed under port 8080 now has the size limit of 200MB

<Connector port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           redirectPort="8443"
           maxPostSize="209715200" />

3. Configure app level size limit

After passing the port level size limit, you can still configure app level limit. This also means that app level limit should be less than port level limit. The limit can be done through annotation within each servlet, or in the web.xml file. Again, if this is not set at all, there is no limit on request size.

To set limit through java annotation

@WebServlet("/uploadFiles")
@MultipartConfig( fileSizeThreshold = 0, maxFileSize = 209715200, maxRequestSize = 209715200)
public class FileUploadServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response) {
        // ...
    }
}

To set limit through web.xml

<web-app>
  ...
  <servlet>
    ...
    <multipart-config>
      <file-size-threshold>0</file-size-threshold>
      <max-file-size>209715200</max-file-size>
      <max-request-size>209715200</max-request-size>
    </multipart-config>
    ...
  </servlet>
  ...
</web-app>

4. Appendix - If you see file upload size error when trying to install app through Tomcat's Manager app

Tomcat's Manager app (by default localhost:8080/manager) is nothing but a default web app. By default that app has a web.xml configuration of request limit of 50MB. To install (upload) app with size greater than 50MB through this manager app, you have to change the limit. Open the manager app's web.xml file from webapps\manager\WEB-INF\web.xml and follow the above guide to change the size limit and finally restart tomcat.

Check if String / Record exists in DataTable

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

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

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

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

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

DataTable workTable = new DataTable("Customers");

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

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

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

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

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

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

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

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

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

How to fix IndexError: invalid index to scalar variable

You are trying to index into a scalar (non-iterable) value:

[y[1] for y in y_test]
#  ^ this is the problem

When you call [y for y in test] you are iterating over the values already, so you get a single value in y.

Your code is the same as trying to do the following:

y_test = [1, 2, 3]
y = y_test[0] # y = 1
print(y[0]) # this line will fail

I'm not sure what you're trying to get into your results array, but you need to get rid of [y[1] for y in y_test].

If you want to append each y in y_test to results, you'll need to expand your list comprehension out further to something like this:

[results.append(..., y) for y in y_test]

Or just use a for loop:

for y in y_test:
    results.append(..., y)

Command line for looking at specific port

This command will show all the ports and their destination address:

netstat -f 

Node.js Generate html

You can use jade + express:

app.get('/', function (req, res) { res.render('index', { title : 'Home' } ) });

above you see 'index' and an object {title : 'Home'}, 'index' is your html and the object is your data that will be rendered in your html.

How can I start InternetExplorerDriver using Selenium WebDriver

It needs to set same Security level in all zones. To do that follow the steps below:

1.Open IE

2.Go to Tools -> Internet Options -> Security

3.Set all zones (Internet, Local intranet, Trusted sites, Restricted sites) to the same protected mode, enabled or disabled should not matter.

Finally, set Zoom level to 100% by right clicking on the gear located at the top right corner and enabling the status-bar. Default zoom level is now displayed at the lower right.

How do I do a not equal in Django queryset filtering?

Your query appears to have a double negative, you want to exclude all rows where x is not 5, so in other words you want to include all rows where x is 5. I believe this will do the trick:

results = Model.objects.filter(x=5).exclude(a=True)

To answer your specific question, there is no "not equal to" field lookup but that's probably because Django has both filter and exclude methods available so you can always just switch the logic around to get the desired result.

Xampp-mysql - "Table doesn't exist in engine" #1932

I had the same issue. I had a backup of my C:\xampp\mysql\data folder. But integrating it with the newly installed xampp had issues. So I located the C:\xampp\mysql\bin\my.ini file and directed innodb_data_home_dir = "C:/xampp/mysql/data" to my backed-up data folder and it worked flawlessly.

How to set date format in HTML date input tag?

short direct answer is no or not out of the box but i have come up with a method to use a text box and pure JS code to simulate the date input and do any format you want, here is the code

<html>
<body>
date : 
<span style="position: relative;display: inline-block;border: 1px solid #a9a9a9;height: 24px;width: 500px">
    <input type="date" class="xDateContainer" onchange="setCorrect(this,'xTime');" style="position: absolute; opacity: 0.0;height: 100%;width: 100%;"><input type="text" id="xTime" name="xTime" value="dd / mm / yyyy" style="border: none;height: 90%;" tabindex="-1"><span style="display: inline-block;width: 20px;z-index: 2;float: right;padding-top: 3px;" tabindex="-1">&#9660;</span>
</span>
<script language="javascript">
var matchEnterdDate=0;
//function to set back date opacity for non supported browsers
    window.onload =function(){
        var input = document.createElement('input');
        input.setAttribute('type','date');
        input.setAttribute('value', 'some text'); 
        if(input.value === "some text"){
            allDates = document.getElementsByClassName("xDateContainer");
            matchEnterdDate=1;
            for (var i = 0; i < allDates.length; i++) {
                allDates[i].style.opacity = "1";
            } 
        }
    }
//function to convert enterd date to any format
function setCorrect(xObj,xTraget){
    var date = new Date(xObj.value);
    var month = date.getMonth();
    var day = date.getDate();
    var year = date.getFullYear();
    if(month!='NaN'){
        document.getElementById(xTraget).value=day+" / "+month+" / "+year;
    }else{
        if(matchEnterdDate==1){document.getElementById(xTraget).value=xObj.value;}
    }
}
   </script>
  </body>
</html>

1- please note that this method only work for browser that support date type.

2- the first function in JS code is for browser that don't support date type and set the look to a normal text input.

3- if you will use this code for multiple date inputs in your page please change the ID "xTime" of the text input in both function call and the input itself to something else and of course use the name of the input you want for the form submit.

4-on the second function you can use any format you want instead of day+" / "+month+" / "+year for example year+" / "+month+" / "+day and in the text input use a placeholder or value as yyyy / mm / dd for the user when the page load.

Search text in fields in every table of a MySQL database

PHP function:

function searchAllDB($search){
    global $mysqli;

    $out = "";

    $sql = "show tables";
    $rs = $mysqli->query($sql);
    if($rs->num_rows > 0){
        while($r = $rs->fetch_array()){
            $table = $r[0];
            $out .= $table.";";
            $sql_search = "select * from ".$table." where ";
            $sql_search_fields = Array();
            $sql2 = "SHOW COLUMNS FROM ".$table;
            $rs2 = $mysqli->query($sql2);
            if($rs2->num_rows > 0){
                while($r2 = $rs2->fetch_array()){
                    $column = $r2[0];
                    $sql_search_fields[] = $column." like('%".$search."%')";
                }
                $rs2->close();
            }
            $sql_search .= implode(" OR ", $sql_search_fields);
            $rs3 = $mysqli->query($sql_search);
            $out .= $rs3->num_rows."\n";
            if($rs3->num_rows > 0){
                $rs3->close();
            }
        }
        $rs->close();
    }

    return $out;
}

Streaming via RTSP or RTP in HTML5

With VLC i'm able to transcode a live RTSP stream (mpeg4) to an HTTP stream in a OGG format (Vorbis/Theora). The quality is poor but the video work in Chrome 9. I have also tested with a trancoding in WEBM (VP8) but it's don't seem to work (VLC have the option but i don't know if it's really implemented for now..)

The first to have a doc on this should notify us ;)

Codeigniter - no input file specified

Godaddy hosting it seems fixed on .htaccess, myself it is working

RewriteRule ^(.*)$ index.php/$1 [L]

to

RewriteRule ^(.*)$ index.php?/$1 [QSA,L]

Pythonic way to create a long multi-line string

Are you talking about multi-line strings? Easy, use triple quotes to start and end them.

s = """ this is a very
        long string if I had the
        energy to type more and more ..."""

You can use single quotes too (3 of them of course at start and end) and treat the resulting string s just like any other string.

NOTE: Just as with any string, anything between the starting and ending quotes becomes part of the string, so this example has a leading blank (as pointed out by @root45). This string will also contain both blanks and newlines.

I.e.,:

' this is a very\n        long string if I had the\n        energy to type more and more ...'

Finally, one can also construct long lines in Python like this:

 s = ("this is a very"
      "long string too"
      "for sure ..."
     )

which will not include any extra blanks or newlines (this is a deliberate example showing what the effect of skipping blanks will result in):

'this is a verylong string toofor sure ...'

No commas required, simply place the strings to be joined together into a pair of parenthesis and be sure to account for any needed blanks and newlines.

Checking if a character is a special character in Java

What I would do:

char c;
int cint;
for(int n = 0; n < str.length(); n ++;)
{
    c = str.charAt(n);
    cint = (int)c;
    if(cint <48 || (cint > 57 && cint < 65) || (cint > 90 && cint < 97) || cint > 122)
    {
        specialCharacterCount++
    }
}

That is a simple way to do things, without having to import any special classes. Stick it in a method, or put it straight into the main code.

ASCII chart: http://www.gophoto.it/view.php?i=http://i.msdn.microsoft.com/dynimg/IC102418.gif#.UHsqxFEmG08

How do I trim leading/trailing whitespace in a standard way?

C++ STL style

std::string Trimed(const std::string& s)
{
    std::string::const_iterator begin = std::find_if(s.begin(),
                                                 s.end(),
                                                 [](char ch) { return !std::isspace(ch); });

    std::string::const_iterator   end = std::find_if(s.rbegin(),
                                                 s.rend(),
                                                 [](char ch) { return !std::isspace(ch); }).base();
    return std::string(begin, end);
}

http://ideone.com/VwJaq9

No numeric types to aggregate - change in groupby() behaviour?

I got this error generating a data frame consisting of timestamps and data:

df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp))

Adding the suggested solution works for me:

df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp), dtype=float))

Thanks Chang She!

Example:

                     data
2005-01-01 00:10:00  7.53
2005-01-01 00:20:00  7.54
2005-01-01 00:30:00  7.62
2005-01-01 00:40:00  7.68
2005-01-01 00:50:00  7.81
2005-01-01 01:00:00  7.95
2005-01-01 01:10:00  7.96
2005-01-01 01:20:00  7.95
2005-01-01 01:30:00  7.98
2005-01-01 01:40:00  8.06
2005-01-01 01:50:00  8.04
2005-01-01 02:00:00  8.06
2005-01-01 02:10:00  8.12
2005-01-01 02:20:00  8.12
2005-01-01 02:30:00  8.25
2005-01-01 02:40:00  8.27
2005-01-01 02:50:00  8.17
2005-01-01 03:00:00  8.21
2005-01-01 03:10:00  8.29
2005-01-01 03:20:00  8.31
2005-01-01 03:30:00  8.25
2005-01-01 03:40:00  8.19
2005-01-01 03:50:00  8.17
2005-01-01 04:00:00  8.18
                     data
2005-01-01 00:00:00  7.636000
2005-01-01 01:00:00  7.990000
2005-01-01 02:00:00  8.165000
2005-01-01 03:00:00  8.236667
2005-01-01 04:00:00  8.180000