Programs & Examples On #Live update

How do I find where JDK is installed on my windows machine?

In Windows at the command prompt

where javac

How to get values and keys from HashMap?

Map is internally made up of Map.Entry objects. Each Entry contains key and value. To get key and value from the entry you use accessor and modifier methods.

If you want to get values with given key, use get() method and to insert value, use put() method.

#Define and initialize map;
Map map = new HashMap();
map.put("USA",1)
map.put("Japan",3)
map.put("China",2)
map.put("India",5)
map.put("Germany",4)

map.get("Germany") // returns 4

If you want to get the set of keys from map, you can use keySet() method

Set keys = map.keySet();
System.out.println("All keys are: " + keys);
// To get all key: value
for(String key: keys){
    System.out.println(key + ": " + map.get(key));
}

Generally, To get all keys and values from the map, you have to follow the sequence in the following order:

  • Convert Hashmap to MapSet to get set of entries in Map with entryset() method.:
    Set st = map.entrySet();
  • Get the iterator of this set:
    Iterator it = st.iterator();
  • Get Map.Entry from the iterator:
    Map.Entry entry = it.next();
  • use getKey() and getValue() methods of the Map.Entry to get keys and values.
// Now access it
Set st = (Set) map.entrySet();
Iterator it = st.iterator();
while(it.hasNext()){
    Map.Entry entry = mapIterator.next();
    System.out.print(entry.getKey() + " : " + entry.getValue());
}

In short, use iterator directly in for

for(Map.Entry entry:map.entrySet()){
    System.out.print(entry.getKey() + " : " + entry.getValue());
}

Div with horizontal scrolling only

I couldn't get the selected answer to work but after a bit of research, I found that the horizontal scrolling div must have white-space: nowrap in the css.

Here's complete working code:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Something</title>
    <style type="text/css">
        #scrolly{
            width: 1000px;
            height: 190px;
            overflow: auto;
            overflow-y: hidden;
            margin: 0 auto;
            white-space: nowrap
        }

        img{
            width: 300px;
            height: 150px;
            margin: 20px 10px;
            display: inline;
        }
    </style>
</head>
<body>
    <div id='scrolly'>
        <img src='img/car.jpg'></img>
        <img src='img/car.jpg'></img>
        <img src='img/car.jpg'></img>
        <img src='img/car.jpg'></img>
        <img src='img/car.jpg'></img>
        <img src='img/car.jpg'></img>
    </div>
</body>
</html>

What's the simplest way to list conflicted files in Git?

Utility git wizard https://github.com/makelinux/git-wizard counts separately unresolved conflicted changes (collisions) and unmerged files. Conflicts must be resolved manually or with mergetool. Resolved unmerged changes can me added and committed usually with git rebase --continue.

Remove Fragment Page from ViewPager in Android

i solved this problem by these steps

1- use FragmentPagerAdapter

2- in each fragment create a random id

fragment.id = new Random().nextInt();

3- override getItemPosition in adapter

@Override
public int getItemPosition(@NonNull Object object) {
    return PagerAdapter.POSITION_NONE;
}

4-override getItemId in adapter

 @Override
public long getItemId(int position) {
    return mDatasetFragments.get(position).id;
}

5- now delete code is

 adapter.mDatasetFragments.remove(< item to delete position >);
 adapter.notifyDataSetChanged();

this worked for me i hope help

R plot: size and resolution

If you'd like to use base graphics, you may have a look at this. An extract:

You can correct this with the res= argument to png, which specifies the number of pixels per inch. The smaller this number, the larger the plot area in inches, and the smaller the text relative to the graph itself.

How to use PHP OPCache?

OPcache replaces APC

Because OPcache is designed to replace the APC module, it is not possible to run them in parallel in PHP. This is fine for caching PHP opcode as neither affects how you write code.

However it means that if you are currently using APC to store other data (through the apc_store() function) you will not be able to do that if you decide to use OPCache.

You will need to use another library such as either APCu or Yac which both store data in shared PHP memory, or switch to use something like memcached, which stores data in memory in a separate process to PHP.

Also, OPcache has no equivalent of the upload progress meter present in APC. Instead you should use the Session Upload Progress.

Settings for OPcache

The documentation for OPcache can be found here with all of the configuration options listed here. The recommended settings are:

; Sets how much memory to use
opcache.memory_consumption=128

;Sets how much memory should be used by OPcache for storing internal strings 
;(e.g. classnames and the files they are contained in)
opcache.interned_strings_buffer=8

; The maximum number of files OPcache will cache
opcache.max_accelerated_files=4000

;How often (in seconds) to check file timestamps for changes to the shared
;memory storage allocation.
opcache.revalidate_freq=60

;If enabled, a fast shutdown sequence is used for the accelerated code
;The fast shutdown sequence doesn't free each allocated block, but lets
;the Zend Engine Memory Manager do the work.
opcache.fast_shutdown=1

;Enables the OPcache for the CLI version of PHP.
opcache.enable_cli=1

If you use any library or code that uses code annotations you must enable save comments:

opcache.save_comments=1

If disabled, all PHPDoc comments are dropped from the code to reduce the size of the optimized code. Disabling "Doc Comments" may break some existing applications and frameworks (e.g. Doctrine, ZF2, PHPUnit)

Add JVM options in Tomcat

As Bhavik Shah says, you can do it in JAVA_OPTS, but the recommended way (as per catalina.sh) is to use CATALINA_OPTS:

#   CATALINA_OPTS   (Optional) Java runtime options used when the "start",
#                   "run" or "debug" command is executed.
#                   Include here and not in JAVA_OPTS all options, that should
#                   only be used by Tomcat itself, not by the stop process,
#                   the version command etc.
#                   Examples are heap size, GC logging, JMX ports etc.

#   JAVA_OPTS       (Optional) Java runtime options used when any command
#                   is executed.
#                   Include here and not in CATALINA_OPTS all options, that
#                   should be used by Tomcat and also by the stop process,
#                   the version command etc.
#                   Most options should go into CATALINA_OPTS.

Best lightweight web server (only static content) for Windows

Have a look at mongoose:

  • single executable
  • very small memory footprint
  • allows multiple worker threads
  • easy to install as service
  • configurable with a configuration file if required

What is the coolest thing you can do in <10 lines of simple code? Help me inspire beginners!

Private Declare Function Beep Lib "kernel32" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Public Sub JohnDenverAnniesSong(): Const E4# = 329.6276: Dim Note&, Frequencies$, Durations$: Frequencies = "iiihfihfffhidadddfhihfffhihiiihfihffihfdadddfhihffhiki": Durations = "aabbbfjaabbbbnaabbbfjaabcapaabbbfjaabbbbnaabbbfjaabcap": For Note = 1 To Len(Frequencies): Beep CLng(E4 * 2 ^ ((AscW(Mid$(Frequencies, Note, 1)) - 96) / 12)), CLng((Asc(Mid$(Durations, Note, 1)) - 96) * 200 - 10): Sleep 10: DoEvents: Next: End Sub

Dump in Excel to run:D

Chrome says my extension's manifest file is missing or unreadable

Mine also was funny. While copypasting " manifest.json" from the tutorial, i also managed to copy a leading space. Couldn't get why it's not finding it.

How to make a rest post call from ReactJS code?

As of 2018 and beyond, you have a more modern option which is to incorporate async/await in your ReactJS application. A promise-based HTTP client library such as axios can be used. The sample code is given below:

import axios from 'axios';
...
class Login extends Component {
    constructor(props, context) {
        super(props, context);
        this.onLogin = this.onLogin.bind(this);
        ...
    }
    async onLogin() {
        const { email, password } = this.state;
        try {
           const response = await axios.post('/login', { email, password });
           console.log(response);
        } catch (err) {
           ...
        }
    }
    ...
}

How to replace all dots in a string using JavaScript

you can replace all occurrence of any string/character using RegExp javasscript object.

Here is the code,

var mystring = 'okay.this.is.a.string';

var patt = new RegExp("\\.");

while(patt.test(mystring)){

  mystring  = mystring .replace(".","");

}

Show a child form in the centre of Parent form in C#

On the SubLogin Form I would expose a SetLocation method so that you can set it from your parent form:

public class SubLogin : Form
{
   public void SetLocation(Point p)
   {
      this.Location = p;
   }
} 

Then, from your main form:

loginForm = new SubLogin();   
Point p = //do math to get point
loginForm.SetLocation(p);
loginForm.Show();

How can I split a delimited string into an array in PHP?

explode has some very big problems in real life usage:

count(explode(',', null)); // 1 !! 
explode(',', null); // [""] not an empty array, but an array with one empty string!
explode(',', ""); // [""]
explode(',', "1,"); // ["1",""] ending commas are also unsupported, kinda like IE8

this is why i prefer preg_split

preg_split('@,@', $string, NULL, PREG_SPLIT_NO_EMPTY)

the entire boilerplate:

/** @brief wrapper for explode
 * @param string|int|array $val string will explode. '' return []. int return string in array (1 returns ['1']). array return itself. for other types - see $as_is
 * @param bool $as_is false (default): bool/null return []. true: bool/null return itself.
 * @param string $delimiter default ','
 * @return array|mixed
 */
public static function explode($val, $as_is = false, $delimiter = ',')
{
    // using preg_split (instead of explode) because it is the best way to handle ending comma and avoid empty string converted to ['']
    return (is_string($val) || is_int($val)) ?
        preg_split('@' . preg_quote($delimiter, '@') . '@', $val, NULL, PREG_SPLIT_NO_EMPTY)
        :
        ($as_is ? $val : (is_array($val) ? $val : []));
}

How can I join elements of an array in Bash?

liststr=""
for item in list
do
    liststr=$item,$liststr
done
LEN=`expr length $liststr`
LEN=`expr $LEN - 1`
liststr=${liststr:0:$LEN}

This takes care of the extra comma at the end also. I am no bash expert. Just my 2c, since this is more elementary and understandable

How to add number of days to today's date?

[UPDATE] Consider reading this before you proceed...

Moment.js

Install moment.js from here.

npm : $ npm i --save moment

Bower : $ bower install --save moment

Next,

var date = moment()
            .add(2,'d') //replace 2 with number of days you want to add
            .toDate(); //convert it to a Javascript Date Object if you like

Link Ref : http://momentjs.com/docs/#/manipulating/add/

Moment.js is an amazing Javascript library to manage Date objects and extremely light weight at 40kb.

Good Luck.

How to work with complex numbers in C?

Complex types are in the C language since C99 standard (-std=c99 option of GCC). Some compilers may implement complex types even in more earlier modes, but this is non-standard and non-portable extension (e.g. IBM XL, GCC, may be intel,... ).

You can start from http://en.wikipedia.org/wiki/Complex.h - it gives a description of functions from complex.h

This manual http://pubs.opengroup.org/onlinepubs/009604499/basedefs/complex.h.html also gives some info about macros.

To declare a complex variable, use

  double _Complex  a;        // use c* functions without suffix

or

  float _Complex   b;        // use c*f functions - with f suffix
  long double _Complex c;    // use c*l functions - with l suffix

To give a value into complex, use _Complex_I macro from complex.h:

  float _Complex d = 2.0f + 2.0f*_Complex_I;

(actually there can be some problems here with (0,-0i) numbers and NaNs in single half of complex)

Module is cabs(a)/cabsl(c)/cabsf(b); Real part is creal(a), Imaginary is cimag(a). carg(a) is for complex argument.

To directly access (read/write) real an imag part you may use this unportable GCC-extension:

 __real__ a = 1.4;
 __imag__ a = 2.0;
 float b = __real__ a;

Align Bootstrap Navigation to Center

Try this css

.clearfix:before, .clearfix:after, .container:before, .container:after, .container-fluid:before, .container-fluid:after, .row:before, .row:after, .form-horizontal .form-group:before, .form-horizontal .form-group:after, .btn-toolbar:before, .btn-toolbar:after, .btn-group-vertical > .btn-group:before, .btn-group-vertical > .btn-group:after, .nav:before, .nav:after, .navbar:before, .navbar:after, .navbar-header:before, .navbar-header:after, .navbar-collapse:before, .navbar-collapse:after, .pager:before, .pager:after, .panel-body:before, .panel-body:after, .modal-footer:before, .modal-footer:after {
    content: " ";
    display: table-cell;
}

ul.nav {
    float: none;
    margin-bottom: 0;
    margin-left: auto;
    margin-right: auto;
    margin-top: 0;
    width: 240px;
}

adding css file with jquery

Your issue is that your selector is for an anchor element <a>. You are treating the <a> tag as if it represents the page which is not the case.

$('head') will work as long as this selector is being executed by the page that needs the css.

Why not simply add the css file to the page in question. Any particular reason to attempt this dynamically from another page? I am not even familiar with a way to inject css to remote pages like this ... seems like it would be a major security hole.

ADDENDUM to your reasoning:

Then you should simply pass a parameter to the page, read it using javascript, and then do whatever is needed based on the parameter.

Java/ JUnit - AssertTrue vs AssertFalse

Your understanding is incorrect, in cases like these always consult the JavaDoc.

assertFalse

public static void assertFalse(java.lang.String message,
                               boolean condition)

Asserts that a condition is false. If it isn't it throws an AssertionError with the given message.

Parameters:

  • message - the identifying message for the AssertionError (null okay)
  • condition - condition to be checked

Make footer stick to bottom of page correctly

This should help you.

* {
    margin: 0;
}
html, body {
    height: 100%;
}
.wrapper {
    min-height: 100%;
    height: auto !important;
    height: 100%;
    margin: 0 auto -155px; /* the bottom margin is the negative value of the footer's height */
}
.footer {
    height: 155px;
}

How to make scipy.interpolate give an extrapolated result beyond the input range?

You can take a look at InterpolatedUnivariateSpline

Here an example using it:

import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import InterpolatedUnivariateSpline

# given values
xi = np.array([0.2, 0.5, 0.7, 0.9])
yi = np.array([0.3, -0.1, 0.2, 0.1])
# positions to inter/extrapolate
x = np.linspace(0, 1, 50)
# spline order: 1 linear, 2 quadratic, 3 cubic ... 
order = 1
# do inter/extrapolation
s = InterpolatedUnivariateSpline(xi, yi, k=order)
y = s(x)

# example showing the interpolation for linear, quadratic and cubic interpolation
plt.figure()
plt.plot(xi, yi)
for order in range(1, 4):
    s = InterpolatedUnivariateSpline(xi, yi, k=order)
    y = s(x)
    plt.plot(x, y)
plt.show()

What is the native keyword in Java for?

Java native method provides a mechanism for Java code to call OS native code, either due to functional or performance reasons.

Example:

606  public native int availableProcessors();
617  public native long freeMemory();
630  public native long totalMemory();
641  public native long maxMemory();
664  public native void gc();

In the corresponding Runtime.class file in OpenJDK, located in JAVA_HOME/jmods/java.base.jmod/classes/java/lang/Runtime.class, contains these methods and tagged them with ACC_NATIVE (0x0100), and these methods do not contain the Code attribute, which means these method do not have any actual coding logic in the Runtime.class file:

  • Method 13 availableProcessors: tagged as native and no Code attribute
  • Method 14 freeMemory: tagged as native and no Code attribute
  • Method 15 totalMemory: tagged as native and no Code attribute
  • Method 16 maxMemory: tagged as native and no Code attribute
  • Method 17 gc: tagged as native and no Code attribute

enter image description here

The in fact coding logic is in the corresponding Runtime.c file:

42  #include "java_lang_Runtime.h"
43
44  JNIEXPORT jlong JNICALL
45  Java_java_lang_Runtime_freeMemory(JNIEnv *env, jobject this)
46  {
47      return JVM_FreeMemory();
48  }
49
50  JNIEXPORT jlong JNICALL
51  Java_java_lang_Runtime_totalMemory(JNIEnv *env, jobject this)
52  {
53      return JVM_TotalMemory();
54  }
55
56  JNIEXPORT jlong JNICALL
57  Java_java_lang_Runtime_maxMemory(JNIEnv *env, jobject this)
58  {
59      return JVM_MaxMemory();
60  }
61
62  JNIEXPORT void JNICALL
63  Java_java_lang_Runtime_gc(JNIEnv *env, jobject this)
64  {
65      JVM_GC();
66  }
67  
68  JNIEXPORT jint JNICALL
69  Java_java_lang_Runtime_availableProcessors(JNIEnv *env, jobject this)
70  {
71      return JVM_ActiveProcessorCount();
72  }

And these C coding is compiled into the libjava.so (Linux) or libjava.dll (Windows) file, located at JAVA_HOME/jmods/java.base.jmod/lib/libjava.so:

enter image description here

enter image description here

Reference

javascript unexpected identifier

It looks like there is an extra curly bracket in the code.

function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        document.getElementById("content").innerHTML = xmlhttp.responseText;
    }
// extra bracket }
xmlhttp.open("GET", "data/" + id + ".html", true);
xmlhttp.send();
}

How to make an Android Spinner with initial text "Select One"?

Refer to one of the above answers: https://stackoverflow.com/a/23005376/1312796

I added my code to fix a little bug. That where no data retrieved..How to show the prompt text..!

Here is my Trick...It works fine with me. !

Try to put your spinner in a Relative_layoutand align a Textview with your spinner and play with the visibility of the Textview (SHOW/HIDE) whenever the adapter of the spinner loaded or empty..Like this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="20dp"
android:background="#ededed"
android:orientation="vertical">



    <TextView
        android:id="@+id/txt_prompt_from"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:textColor="@color/gray"
        android:textSize="16sp"
        android:layout_alignStart="@+id/sp_from"
        android:text="From"
        android:visibility="gone"/>

    <Spinner
        android:id="@+id/sp_from"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        />

Here is the code:

  txt__from = (TextView) rootView.findViewById(R.id.txt_prompt_from);

call this method after and before spinner adapter loaded and empty.

setPromptTextViewVisibility (); //True or fales 

public void setPromptTextViewVisibility (boolean visible )
{
    if (visible)
    {
        txt_from.setVisibility(View.VISIBLE);
    }
    else
    {
        txt_from.setVisibility(View.INVISIBLE);
    }

}

Entity Framework code-first: migration fails with update-database, forces unneccessary(?) add-migration

I understand this is a very old thread. However, wanted to share how I encountered the message in my scenario and in case it might help others

  1. I created an Add-Migration <Migration_name> on my local machine. Didn't run the update-database yet.
  2. Meanwhile, there were series of commits in parent branch that I must down merge. The merge also had a migration to it and when I fixed conflicts, I ended up having 2 migrations that are added to my project but are not executed via update-database.
  3. Now I don't use enable-migrations -force in my application. Rather my preferred way is execute the update-database -script command to control the target migrations I need.
  4. So, when I attempted the above command, I get the error in question.

My solution was to run update-database -Script -TargetMigration <migration_name_from_merge> and then my update-database -Script -TargetMigration <migration_name> which generated 2 scripts that I was able to run manually on my local db.

Needless to say above experience is on my local machine.

Oracle SQL Developer: Unable to find a JVM

There is another route of failure, besides the version of Java you are running: You could be running out of Heap/RAM

If you had a once working version of SQLDeveloper, and you are starting to see the screenshot referenced in the original post, then you can try to adjust the amount of space SQLDeveloper requests when starting up.

Edit the file:

/ide/bin/ide.conf

Edit the line that specifies the max ram to use: AddVMOption -Xmx, reducing the size. For example I changed my file to have the following lines, which solved the issue.

#AddVMOption  -Xmx640M   # Original Value
AddVMOption  -Xmx256M    # New Value

Refused to display 'url' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

This happens because of your application does not allow to append iframe from origin other than your application domain.

If your application have web.config then add the following tag in web.config

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="X-Frame-Options" value="ALLOW" />
        </customHeaders>
    </httpProtocol>
</system.webServer>

This will allow application to append iframe from other origin also. You can also use the following value for X-Frame-Option

X-FRAME-OPTIONS: ALLOW-FROM https://example.com/ 

printing a value of a variable in postgresql

You can raise a notice in Postgres as follows:

raise notice 'Value: %', deletedContactId;

Read here

Find the paths between two given nodes?

Breadth-first search traverses a graph and in fact finds all paths from a starting node. Usually, BFS doesn't keep all paths, however. Instead, it updates a prededecessor function p to save the shortest path. You can easily modify the algorithm so that p(n) doesn't only store one predecessor but a list of possible predecessors.

Then all possible paths are encoded in this function, and by traversing p recursively you get all possible path combinations.

One good pseudocode which uses this notation can be found in Introduction to Algorithms by Cormen et al. and has subsequently been used in many University scripts on the subject. A Google search for “BFS pseudocode predecessor p” uproots this hit on Stack Exchange.

Is it wrong to place the <script> tag after the </body> tag?

Google actually recommends this in regards to 'CSS Optimization'. They recommend in-lining critical above-fold styles and deferring the rest(css file).

Example:

<html>
  <head>
    <style>
      .blue{color:blue;}
    </style>
    </head>
  <body>
    <div class="blue">
      Hello, world!
    </div>
  </body>
</html>
<noscript><link rel="stylesheet" href="small.css"></noscript>

See: https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery

How to grep for contents after pattern?

grep -Po 'potato:\s\K.*' file

-P to use Perl regular expression

-o to output only the match

\s to match the space after potato:

\K to omit the match

.* to match rest of the string(s)

Vertically align text within input field of fixed-height without display: table or padding?

After much searching and frustration a combo of setting height, line height and no padding worked for me when using a fixed height (24px) background image for a text input field.

.form-text {
    color: white;
    outline: none;
    background-image: url(input_text.png);
    border-width: 0px;
    padding: 0px 10px 0px 10px;
    margin: 0px;
    width: 274px;
    height: 24px;
    line-height: 24px;
    vertical-align: middle;
}

How to install Visual Studio 2015 on a different drive

I use Xamarin with Visual Studio, and I prefer to move only some large android to another directory with(copy these folders to destination before create hardlinks):

mklink \J "C:\Users\yourUser\.android" "E:\yourFolder\.android"

mklink \J "C:\Program Files (x86)\Android" "E:\yourFolder\Android"

How to get and set the current web page scroll position?

There are some inconsistencies in how browsers expose the current window scrolling coordinates. Google Chrome on Mac and iOS seems to always return 0 when using document.documentElement.scrollTop or jQuery's $(window).scrollTop().

However, it works consistently with:

// horizontal scrolling amount
window.pageXOffset

// vertical scrolling amount
window.pageYOffset

In Flask, What is request.args and how is it used?

According to the flask.Request.args documents.

flask.Request.args
A MultiDict with the parsed contents of the query string. (The part in the URL after the question mark).

So the args.get() is method get() for MultiDict, whose prototype is as follows:

get(key, default=None, type=None)

Update:
In newer version of flask (v1.0.x and v1.1.x), flask.Request.args is an ImmutableMultiDict(an immutable MultiDict), so the prototype and specific method above is still valid.

How to store directory files listing into an array?

Here's a variant that lets you use a regex pattern for initial filtering, change the regex to be get the filtering you desire.

files=($(find -E . -type f -regex "^.*$"))
for item in ${files[*]}
do
  printf "   %s\n" $item
done

Disable Logback in SpringBoot

Using Gradle & Lombok, here is the simplest configuration for Log4j2 that worked for me using the latest Spring Boot (2.4.1 at this time) :

build.gradle (partial)

configurations {
    compileOnly { extendsFrom annotationProcessor }
    compile.exclude module: 'spring-boot-starter-logging'
}


dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-security' 
    implementation 'org.springframework.boot:spring-boot-starter-web-services'
    implementation 'org.springframework.boot:spring-boot-starter-log4j2'

    compileOnly 'org.projectlombok:lombok'

    // (*** other dependencies ***)

    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'org.springframework.security:spring-security-test'
}

I noticed you will get errors if you include spring-bbot-starter-log4j2 as a compileOnly dependency instead of as an implementation.

Just annotate your classes with @Log4j2 (or @Slf4j) and lombok will make available a log variable you can use for logging.

As usual, provide a log4j2.xml configuration file in your /src/main/resources folder.

Install pdo for postgres Ubuntu

Try the packaged pecl version instead (the advantage of the packaged installs is that they're easier to upgrade):

apt-get install php5-dev
pecl install pdo
pecl install pdo_pgsql

or, if you just need a driver for PHP, but that it doesn't have to be the PDO one:

apt-get install php5-pgsql

Otherwise, that message most likely means you need to install a more recent libpq package. You can check which version you have by running:

dpkg -s libpq-dev

How to check if a service is running on Android?

For kotlin, you can use the below code.

fun isMyServiceRunning(calssObj: Class<SERVICE_CALL_NAME>): Boolean {
    val manager = requireActivity().getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
    for (service in manager.getRunningServices(Integer.MAX_VALUE)) {
        if (calssObj.getName().equals(service.service.getClassName())) {
            return true
        }
    }
    return false
}

In Perl, how to remove ^M from a file?

^M is carriage return. You can do this:

$str =~ s/\r//g

Multiple models in a view

Use a view model that contains multiple view models:

   namespace MyProject.Web.ViewModels
   {
      public class UserViewModel
      {
          public UserDto User { get; set; }
          public ProductDto Product { get; set; }
          public AddressDto Address { get; set; }
      }
   }

In your view:

  @model MyProject.Web.ViewModels.UserViewModel

  @Html.LabelFor(model => model.User.UserName)
  @Html.LabelFor(model => model.Product.ProductName)
  @Html.LabelFor(model => model.Address.StreetName)

Connection failed: SQLState: '01000' SQL Server Error: 10061

  1. Windows firewall blocks the sql server. Even if you open the 1433 port from exceptions, in the client machine it sets the connection point to dynamic port. Add also the sql server to the exceptions.

"C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Binn\Sqlservr.exe"

More info

  1. This page helped me to solve the problem. Especially

or if you feel brave, locate the alias in the registry and delete it there.

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer\Client\ConnectTo\

How can I use a DLL file from Python?

If the DLL is of type COM library, then you can use pythonnet.

pip install pythonnet

Then in your python code, try the following

import clr
clr.AddReference('path_to_your_dll')

then instantiate an object as per the class in the DLL, and access the methods within it.

How to connect access database in c#

You are building a DataGridView on the fly and set the DataSource for it. That's good, but then do you add the DataGridView to the Controls collection of the hosting form?

this.Controls.Add(dataGridView1);

By the way the code is a bit confused

String connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Tables.accdb;Persist Security Info=True";
string sql  = "SELECT Clients  FROM Tables";
using(OleDbConnection conn = new OleDbConnection(connection))
{
     conn.Open();
     DataSet ds = new DataSet();
     DataGridView dataGridView1 = new DataGridView();
     using(OleDbDataAdapter adapter = new OleDbDataAdapter(sql,conn))
     {
         adapter.Fill(ds);
         dataGridView1.DataSource = ds;
         // Of course, before addint the datagrid to the hosting form you need to 
         // set position, location and other useful properties. 
         // Why don't you create the DataGrid with the designer and use that instance instead?
         this.Controls.Add(dataGridView1);
     }
}

EDIT After the comments below it is clear that there is a bit of confusion between the file name (TABLES.ACCDB) and the name of the table CLIENTS.
The SELECT statement is defined (in its basic form) as

 SELECT field_names_list FROM _tablename_

so the correct syntax to use for retrieving all the clients data is

 string sql  = "SELECT * FROM Clients";

where the * means -> all the fields present in the table

Can I safely delete contents of Xcode Derived data folder?

XCODE 10 UPDATE

Click to Xcode at the Status Bar Then Select Preferences

In the PopUp Window Choose Locations before the last Segment

You can reach Derived Data folder with small right icon

enter image description here

Passing parameter to controller from route in laravel

You don't need anything special for adding paramaters. Just like you had it.

Route::get('groups/(:any)', array('as' => 'group', 'uses' => 'groups@show'));


class Groups_Controller extends Base_Controller {

    public $restful = true;    

    public function get_show($groupID) {
        return 'I am group id ' . $groupID;
    }  


}

How to animate button in android?


Class.Java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_with_the_button);

    final Animation myAnim = AnimationUtils.loadAnimation(this, R.anim.milkshake);
    Button myButton = (Button) findViewById(R.id.new_game_btn);
    myButton.setAnimation(myAnim);
}

For onClick of the Button

myButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        v.startAnimation(myAnim);
    }
});

Create the anim folder in res directory

Right click on, res -> New -> Directory

Name the new Directory anim

create a new xml file name it milkshake


milkshake.xml

<?xml version="1.0" encoding="utf-8"?>
    <rotate xmlns:android="http://schemas.android.com/apk/res/android"
        android:duration="100"
        android:fromDegrees="-5"
        android:pivotX="50%"
        android:pivotY="50%"
        android:repeatCount="10"
        android:repeatMode="reverse"
        android:toDegrees="5" />

How do I multiply each element in a list by a number?

You can just use a list comprehension:

my_list = [1, 2, 3, 4, 5]
my_new_list = [i * 5 for i in my_list]

>>> print(my_new_list)
[5, 10, 15, 20, 25]

Note that a list comprehension is generally a more efficient way to do a for loop:

my_new_list = []
for i in my_list:
    my_new_list.append(i * 5)

>>> print(my_new_list)
[5, 10, 15, 20, 25]

As an alternative, here is a solution using the popular Pandas package:

import pandas as pd

s = pd.Series(my_list)

>>> s * 5
0     5
1    10
2    15
3    20
4    25
dtype: int64

Or, if you just want the list:

>>> (s * 5).tolist()
[5, 10, 15, 20, 25]

ImportError: No module named 'selenium'

Even though the egg file may be present, that does not necessarily mean that it is installed. Check out this previous answer for some hint:

How to install Selenium WebDriver on Mac OS

How can I display just a portion of an image in HTML/CSS?

As mentioned in the question, there is the clip css property, although it does require that the element being clipped is position: absolute; (which is a shame):

_x000D_
_x000D_
.container {_x000D_
  position: relative;_x000D_
}_x000D_
#clip {_x000D_
  position: absolute;_x000D_
  clip: rect(0, 100px, 200px, 0);_x000D_
  /* clip: shape(top, right, bottom, left); NB 'rect' is the only available option */_x000D_
}
_x000D_
<div class="container">_x000D_
  <img src="http://lorempixel.com/200/200/nightlife/3" />_x000D_
</div>_x000D_
<div class="container">_x000D_
  <img id="clip" src="http://lorempixel.com/200/200/nightlife/3" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

JS Fiddle demo, for experimentation.

To supplement the original answer – somewhat belatedly – I'm editing to show the use of clip-path, which has replaced the now-deprecated clip property.

The clip-path property allows a range of options (more-so than the original clip), of:

  • inset — rectangular/cuboid shapes, defined with four values as 'distance-from' (top right bottom left).
  • circlecircle(diameter at x-coordinate y-coordinate).
  • ellipseellipse(x-axis-length y-axis-length at x-coordinate y-coordinate).
  • polygon — defined by a series of x/y coordinates in relation to the element's origin of the top-left corner. As the path is closed automatically the realistic minimum number of points for a polygon should be three, any fewer (two) is a line or (one) is a point: polygon(x-coordinate1 y-coordinate1, x-coordinate2 y-coordinate2, x-coordinate3 y-coordinate3, [etc...]).
  • url — this can be either a local URL (using a CSS id-selector) or the URL of an external file (using a file-path) to identify an SVG, though I've not experimented with either (as yet), so I can offer no insight as to their benefit or caveat.

_x000D_
_x000D_
div.container {_x000D_
  display: inline-block;_x000D_
}_x000D_
#rectangular {_x000D_
  -webkit-clip-path: inset(30px 10px 30px 10px);_x000D_
  clip-path: inset(30px 10px 30px 10px);_x000D_
}_x000D_
#circle {_x000D_
  -webkit-clip-path: circle(75px at 50% 50%);_x000D_
  clip-path: circle(75px at 50% 50%)_x000D_
}_x000D_
#ellipse {_x000D_
  -webkit-clip-path: ellipse(75px 50px at 50% 50%);_x000D_
  clip-path: ellipse(75px 50px at 50% 50%);_x000D_
}_x000D_
#polygon {_x000D_
  -webkit-clip-path: polygon(50% 0, 100% 38%, 81% 100%, 19% 100%, 0 38%);_x000D_
  clip-path: polygon(50% 0, 100% 38%, 81% 100%, 19% 100%, 0 38%);_x000D_
}
_x000D_
<div class="container">_x000D_
  <img id="control" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>_x000D_
<div class="container">_x000D_
  <img id="rectangular" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>_x000D_
<div class="container">_x000D_
  <img id="circle" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>_x000D_
<div class="container">_x000D_
  <img id="ellipse" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>_x000D_
<div class="container">_x000D_
  <img id="polygon" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

JS Fiddle demo, for experimentation.

References:

How to improve a case statement that uses two columns

You could do it this way:

-- Notice how STATE got moved inside the condition:
CASE WHEN STATE = 2 AND RetailerProcessType IN (1, 2) THEN '"AUTHORISED"'
     WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'
     ELSE '"DECLINED"'
END

The reason you can do an AND here is that you are not checking the CASE of STATE, but instead you are CASING Conditions.

The key part here is that the STATE condition is a part of the WHEN.

How to convert String into Hashmap in java

Should Use this way to convert into map :

    String student[] = students.split("\\{|}");
    String id_name[] = student[1].split(",");

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

    for (String std: id_name) {
        String str[] = std.split("=");
        studentIdName.put(str[0],str[1]);
  }

Maven dependencies are failing with a 501 error

Add the following repository in pom.xml.

<project>
...
    <repositories>
        <repository>
            <id>central</id>
            <name>Maven Plugin Repository</name>
            <url>https://repo1.maven.org/maven2</url>
            <layout>default</layout>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
...
</project>

How to change the icon of an Android app in Eclipse?

Look for this on your Manifest.xml android:icon="@drawable/ic_launcher" then change the ic_launcher to the name of your icon which is on your @drawable folder.

Protecting cells in Excel but allow these to be modified by VBA script

You can modify a sheet via code by taking these actions

  • Unprotect
  • Modify
  • Protect

In code this would be:

Sub UnProtect_Modify_Protect()

  ThisWorkbook.Worksheets("Sheet1").Unprotect Password:="Password"
'Unprotect

  ThisWorkbook.ActiveSheet.Range("A1").FormulaR1C1 = "Changed"
'Modify

  ThisWorkbook.Worksheets("Sheet1").Protect Password:="Password"
'Protect

End Sub

The weakness of this method is that if the code is interrupted and error handling does not capture it, the worksheet could be left in an unprotected state.

The code could be improved by taking these actions

  • Re-protect
  • Modify

The code to do this would be:

Sub Re-Protect_Modify()

ThisWorkbook.Worksheets("Sheet1").Protect Password:="Password", _
 UserInterfaceOnly:=True
'Protect, even if already protected

  ThisWorkbook.ActiveSheet.Range("A1").FormulaR1C1 = "Changed"
'Modify

End Sub

This code renews the protection on the worksheet, but with the ‘UserInterfaceOnly’ set to true. This allows VBA code to modify the worksheet, while keeping the worksheet protected from user input via the UI, even if execution is interrupted.

This setting is lost when the workbook is closed and re-opened. The worksheet protection is still maintained.

So the 'Re-protection' code needs to be included at the start of any procedure that attempts to modify the worksheet or can just be run once when the workbook is opened.

Getting the base url of the website and globally passing it to twig in Symfony 2

This is now available for free in twig templates (tested on sf2 version 2.0.14)

{{ app.request.getBaseURL() }}

In later Symfony versions (tested on 2.5), try :

{{ app.request.getSchemeAndHttpHost() }}

Jquery asp.net Button Click Event via ajax

I found myself wanting to do this and I reviewed the above answers and did a hybrid approach of them. It got a little tricky, but here is what I did:

My button already worked with a server side post. I wanted to let that to continue to work so I left the "OnClick" the same, but added a OnClientClick:

OnClientClick="if (!OnClick_Submit()) return false;"

Here is my full button element in case it matters:

<asp:Button UseSubmitBehavior="false" runat="server" Class="ms-ButtonHeightWidth jiveSiteSettingsSubmit" OnClientClick="if (!OnClick_Submit()) return false;" OnClick="BtnSave_Click" Text="<%$Resources:wss,multipages_okbutton_text%>" id="BtnOK" accesskey="<%$Resources:wss,okbutton_accesskey%>" Enabled="true"/>

If I inspect the onclick attribute of the HTML button at runtime it actually looks like this:

if (!OnClick_Submit()) return false;WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$PlaceHolderMain$ctl03$RptControls$BtnOK", "", true, "", "", false, true))

Then in my Javascript I added the OnClick_Submit method. In my case I needed to do a check to see if I needed to show a dialog to the user. If I show the dialog I return false causing the event to stop processing. If I don't show the dialog I return true causing the event to continue processing and my postback logic to run as it used to.

function OnClick_Submit() {
    var initiallyActive = initialState.socialized && initialState.activityEnabled;
    var socialized = IsSocialized();
    var enabled = ActivityStreamsEnabled();

    var displayDialog;

    // Omitted the setting of displayDialog for clarity

    if (displayDialog) {
        $("#myDialog").dialog('open');
        return false;
    }
    else {
        return true;
    }
}

Then in my Javascript code that runs when the dialog is accepted, I do the following depending on how the user interacted with the dialog:

$("#myDialog").dialog('close');
__doPostBack('message', '');

The "message" above is actually different based on what message I want to send.

But wait, there's more!

Back in my server-side code, I changed OnLoad from:

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e)
    if (IsPostBack)
    {
        return;
    }

    // OnLoad logic removed for clarity
}

To:

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e)
    if (IsPostBack)
    {
        switch (Request.Form["__EVENTTARGET"])
        {
            case "message1":
                // We did a __doPostBack with the "message1" command provided
                Page.Validate();
                BtnSave_Click(this, new CommandEventArgs("message1", null));
                break;

            case "message2":
                // We did a __doPostBack with the "message2" command provided
                Page.Validate();
                BtnSave_Click(this, new CommandEventArgs("message2", null));
                break;
            }
            return;
    }

    // OnLoad logic removed for clarity
}

Then in BtnSave_Click method I do the following:

CommandEventArgs commandEventArgs = e as CommandEventArgs;
string message = (commandEventArgs == null) ? null : commandEventArgs.CommandName;

And finally I can provide logic based on whether or not I have a message and based on the value of that message.

Free c# QR-Code generator

Take a look QRCoder - pure C# open source QR code generator. Can be used in three lines of code

QRCodeGenerator qrGenerator = new QRCodeGenerator();
QRCodeGenerator.QRCode qrCode = qrGenerator.CreateQrCode(textBoxQRCode.Text, QRCodeGenerator.ECCLevel.Q);
pictureBoxQRCode.BackgroundImage = qrCode.GetGraphic(20);

How to do URL decoding in Java?

This does not have anything to do with character encodings such as UTF-8 or ASCII. The string you have there is URL encoded. This kind of encoding is something entirely different than character encoding.

Try something like this:

try {
    String result = java.net.URLDecoder.decode(url, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
    // not going to happen - value came from JDK's own StandardCharsets
}

Java 10 added direct support for Charset to the API, meaning there's no need to catch UnsupportedEncodingException:

String result = java.net.URLDecoder.decode(url, StandardCharsets.UTF_8);

Note that a character encoding (such as UTF-8 or ASCII) is what determines the mapping of characters to raw bytes. For a good intro to character encodings, see this article.

Detecting the onload event of a window opened with window.open

This did the trick for me; full example:

HTML:

<a href="/my-popup.php" class="import">Click for my popup on same domain</a>

Javascript:

(function(){
    var doc = document;

    jQuery('.import').click(function(e){
        e.preventDefault();
        window.popup = window.open(jQuery(this).attr('href'), 'importwindow', 'width=500, height=200, top=100, left=200, toolbar=1');

        window.popup.onload = function() {
            window.popup.onbeforeunload = function(){
                doc.location.reload(true); //will refresh page after popup close
            }
        }
    });
})();

Redirect with CodeIgniter

first, you need to load URL helper like this type or you can upload within autoload.php file:

$this->load->helper('url');

if (!$user_logged_in)
{
  redirect('/account/login', 'refresh');
}

android pinch zoom

I have created a project for basic pinch-zoom that supports Android 2.1+

Available here

How can I open a .tex file?

I don't know what the .tex extension on your file means. If we are saying that it is any file with any extension you have several methods of reading it.

I have to assume you are using windows because you have mentioned notepad++.

  1. Use notepad++. Right click on the file and choose "edit with notepad++"

  2. Use notepad Change the filename extension to .txt and double click the file.

  3. Use command prompt. Open the folder that your file is in. Hold down shift and right click. (not on the file, but in the folder that the file is in.) Choose "open command window here" from the command prompt type: "type filename.tex"

If these don't work, I would need more detail as to how they are not working. Errors that you may be getting or what you may expect to be in the file might help.

A failure occurred while executing com.android.build.gradle.internal.tasks

If you getting this error saying signing-config.json (Access denied) means just exit the android studio and just go to the desktop home and click on the android studio icon and give Run as Administrator, this will sort out the problem (or) you can delete the signing-config.json and re-run the program :)

npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\Nuwanst\package.json'

the file path you ran is wrong. So if you are working on windows, go to the correct file location with cd and rerun from there.

What are the differences and similarities between ffmpeg, libav, and avconv?

Confusing messages

These messages are rather misleading and understandably a source of confusion. Older Ubuntu versions used Libav which is a fork of the FFmpeg project. FFmpeg returned in Ubuntu 15.04 "Vivid Vervet".

The fork was basically a non-amicable result of conflicting personalities and development styles within the FFmpeg community. It is worth noting that the maintainer for Debian/Ubuntu switched from FFmpeg to Libav on his own accord due to being involved with the Libav fork.

The real ffmpeg vs the fake one

For a while both Libav and FFmpeg separately developed their own version of ffmpeg.

Libav then renamed their bizarro ffmpeg to avconv to distance themselves from the FFmpeg project. During the transition period the "not developed anymore" message was displayed to tell users to start using avconv instead of their counterfeit version of ffmpeg. This confused users into thinking that FFmpeg (the project) is dead, which is not true. A bad choice of words, but I can't imagine Libav not expecting such a response by general users.

This message was removed upstream when the fake "ffmpeg" was finally removed from the Libav source, but, depending on your version, it can still show up in Ubuntu because the Libav source Ubuntu uses is from the ffmpeg-to-avconv transition period.

In June 2012, the message was re-worded for the package libav - 4:0.8.3-0ubuntu0.12.04.1. Unfortunately the new "deprecated" message has caused additional user confusion.

Starting with Ubuntu 15.04 "Vivid Vervet", FFmpeg's ffmpeg is back in the repositories again.

libav vs Libav

To further complicate matters, Libav chose a name that was historically used by FFmpeg to refer to its libraries (libavcodec, libavformat, etc). For example the libav-user mailing list, for questions and discussions about using the FFmpeg libraries, is unrelated to the Libav project.

How to tell the difference

If you are using avconv then you are using Libav. If you are using ffmpeg you could be using FFmpeg or Libav. Refer to the first line in the console output to tell the difference: the copyright notice will either mention FFmpeg or Libav.

Secondly, the version numbering schemes differ. Each of the FFmpeg or Libav libraries contains a version.h header which shows a version number. FFmpeg will end in three digits, such as 57.67.100, and Libav will end in one digit such as 57.67.0. You can also view the library version numbers by running ffmpeg or avconv and viewing the console output.

If you want to use the real ffmpeg

Ubuntu 15.04 "Vivid Vervet" or newer

The real ffmpeg is in the repository, so you can install it with:

apt-get install ffmpeg

For older Ubuntu versions

Your options are:

These methods are non-intrusive, reversible, and will not interfere with the system or any repository packages.

Another possible option is to upgrade to Ubuntu 15.04 "Vivid Vervet" or newer and just use ffmpeg from the repository.

Also see

For an interesting blog article on the situation, as well as a discussion about the main technical differences between the projects, see The FFmpeg/Libav situation.

Moment.js - tomorrow, today and yesterday

You can use this:


const today     = moment();

const tomorrow  = moment().add(1, 'days');

const yesterday = moment().subtract(1, 'days');

@synthesize vs @dynamic, what are the differences?

One thing want to add is that if a property is declared as @dynamic it will not occupy memory (I confirmed with allocation instrument). A consequence is that you can declare property in class category.

App store link for "rate/review this app"

Starting in iOS 10.3:

import StoreKit

func someFunction() {
 SKStoreReviewController.requestReview()
}

but its has been just released with 10.3, so you will still need some fallback method for older versions as described above

About the Full Screen And No Titlebar from manifest

To set your App or any individual activity display in Full Screen mode, insert the code

<application 
    android:icon="@drawable/icon" 
    android:label="@string/app_name" 
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen">

in AndroidManifest.xml, under application or activity tab.

How to install 2 Anacondas (Python 2 and 3) on Mac OS

Edit!: Please be sure that you should have both Python installed on your computer.

Maybe my answer is late for you but I can help someone who has the same problem!

You don't have to download both Anaconda.

If you are using Spyder and Jupyter in Anaconda environmen and,

If you have already Anaconda 2 type in Terminal:

    python3 -m pip install ipykernel

    python3 -m ipykernel install --user

If you have already Anaconda 3 then type in terminal:

    python2 -m pip install ipykernel

    python2 -m ipykernel install --user

Then before use Spyder you can choose Python environment like below! Sometimes only you can see root and your new Python environment, so root is your first anaconda environment!

Anaconda spyder Python 2.7 or 3.5

Also this is Jupyter. You can choose python version like this!

Jupyter Notebook

I hope it will help.

How to update a single pod without touching other dependencies

I'm using cocoapods version 1.0.1 and using pod update name-of-pod works perfectly. No other pods are updated, just the specific one you enter.

How to validate an Email in PHP?

You can use the filter_var() function, which gives you a lot of handy validation and sanitization options.

filter_var($email, FILTER_VALIDATE_EMAIL)

If you don't want to change your code that relied on your function, just do:

function isValidEmail($email){ 
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

Note: For other uses (where you need Regex), the deprecated ereg function family (POSIX Regex Functions) should be replaced by the preg family (PCRE Regex Functions). There are a small amount of differences, reading the Manual should suffice.

Update 1: As pointed out by @binaryLV:

PHP 5.3.3 and 5.2.14 had a bug related to FILTER_VALIDATE_EMAIL, which resulted in segfault when validating large values. Simple and safe workaround for this is using strlen() before filter_var(). I'm not sure about 5.3.4 final, but it is written that some 5.3.4-snapshot versions also were affected.

This bug has already been fixed.

Update 2: This method will of course validate bazmega@kapa as a valid email address, because in fact it is a valid email address. But most of the time on the Internet, you also want the email address to have a TLD: [email protected]. As suggested in this blog post (link posted by @Istiaque Ahmed), you can augment filter_var() with a regex that will check for the existence of a dot in the domain part (will not check for a valid TLD though):

function isValidEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL) 
        && preg_match('/@.+\./', $email);
}

As @Eliseo Ocampos pointed out, this problem only exists before PHP 5.3, in that version they changed the regex and now it does this check, so you do not have to.

Deleting rows with Python in a CSV file

You are very close; currently you compare the row[2] with integer 0, make the comparison with the string "0". When you read the data from a file, it is a string and not an integer, so that is why your integer check fails currently:

row[2]!="0":

Also, you can use the with keyword to make the current code slightly more pythonic so that the lines in your code are reduced and you can omit the .close statements:

import csv
with open('first.csv', 'rb') as inp, open('first_edit.csv', 'wb') as out:
    writer = csv.writer(out)
    for row in csv.reader(inp):
        if row[2] != "0":
            writer.writerow(row)

Note that input is a Python builtin, so I've used another variable name instead.


Edit: The values in your csv file's rows are comma and space separated; In a normal csv, they would be simply comma separated and a check against "0" would work, so you can either use strip(row[2]) != 0, or check against " 0".

The better solution would be to correct the csv format, but in case you want to persist with the current one, the following will work with your given csv file format:

$ cat test.py 
import csv
with open('first.csv', 'rb') as inp, open('first_edit.csv', 'wb') as out:
    writer = csv.writer(out)
    for row in csv.reader(inp):
        if row[2] != " 0":
            writer.writerow(row)
$ cat first.csv 
6.5, 5.4, 0, 320
6.5, 5.4, 1, 320
$ python test.py 
$ cat first_edit.csv 
6.5, 5.4, 1, 320

javascript create array from for loop

var yearStart = 2000;
var yearEnd = 2040;

var arr = [];

for (var i = yearStart; i <= yearEnd; i++) {

     arr.push(i);
}

How to give a Blob uploaded as FormData a file name?

Since you're getting the data pasted to clipboard, there is no reliable way of knowing the origin of the file and its properties (including name).

Your best bet is to come up with a file naming scheme of your own and send along with the blob.

form.append("filename",getFileName());
form.append("blob",blob);

function getFileName() {
 // logic to generate file names
}

Push commits to another branch

I got a bad result with git push origin branch1:branch2 command:

In my case, branch2 is deleted and branch1 has been updated with some new changes.

Hence, if you want only the changes push on the branch2 from the branch1, try procedures below:

  • On branch1: git add .
  • On branch1: git commit -m 'comments'
  • On branch1: git push origin branch1

  • On branch2: git pull origin branch1

  • On branch1: revert to the previous commit.

VBA for clear value in specific range of cell and protected cell from being wash away formula

Try this

Sheets("your sheetname").range("A5:X50").Value = ""

You can also use

ActiveSheet.range

What equivalents are there to TortoiseSVN, on Mac OSX?

My previous version of this answer had links, that kept becoming dead.
So, I've pointed it to the internet archive to preserve the original answer.

Subversion client releases for Windows and Macintosh

Wiki - Subversion clients comparison table

Excel - programm cells to change colour based on another cell

  1. Select cell B3 and click the Conditional Formatting button in the ribbon and choose "New Rule".
  2. Select "Use a formula to determine which cells to format"
  3. Enter the formula: =IF(B2="X",IF(B3="Y", TRUE, FALSE),FALSE), and choose to fill green when this is true
  4. Create another rule and enter the formula =IF(B2="X",IF(B3="W", TRUE, FALSE),FALSE) and choose to fill red when this is true.

More details - conditional formatting with a formula applies the format when the formula evaluates to TRUE. You can use a compound IF formula to return true or false based on the values of any cells.

S3 - Access-Control-Allow-Origin Header

First, activate CORS in your S3 bucket. Use this code as a guidance:

<CORSConfiguration>
 <CORSRule>
   <AllowedOrigin>http://www.example1.com</AllowedOrigin>

   <AllowedMethod>PUT</AllowedMethod>
   <AllowedMethod>POST</AllowedMethod>
   <AllowedMethod>DELETE</AllowedMethod>

   <AllowedHeader>*</AllowedHeader>
 </CORSRule>
 <CORSRule>
   <AllowedOrigin>http://www.example2.com</AllowedOrigin>

   <AllowedMethod>PUT</AllowedMethod>
   <AllowedMethod>POST</AllowedMethod>
   <AllowedMethod>DELETE</AllowedMethod>

   <AllowedHeader>*</AllowedHeader>
 </CORSRule>
 <CORSRule>
   <AllowedOrigin>*</AllowedOrigin>
   <AllowedMethod>GET</AllowedMethod>
 </CORSRule>
</CORSConfiguration>

2) If it still not working, make sure to also add a "crossorigin" with a "*" value to your img tags. Put this in your html file:

  let imagenes = document.getElementsByTagName("img");
    for (let i = 0; i < imagenes.length; i++) {
      imagenes[i].setAttribute("crossorigin", "*");

Transposing a 1D NumPy array

numpy 1D array --> column/row matrix:

>>> a=np.array([1,2,4])
>>> a[:, None]    # col
array([[1],
       [2],
       [4]])
>>> a[None, :]    # row, or faster `a[None]`
array([[1, 2, 4]])

And as @joe-kington said, you can replace None with np.newaxis for readability.

How do you cache an image in Javascript

I have a similar answer for asynchronous preloading images via JS. Loading them dynamically is the same as loading them normally. they will cache.

as for caching, you can't control the browser but you can set it via server. if you need to load a really fresh resource on demand, you can use the cache buster technique to force load a fresh resource.

How to solve Object reference not set to an instance of an object.?

I think you just need;

List<string> list = new List<string>();
list.Add("hai");

There is a difference between

List<string> list; 

and

List<string> list = new List<string>();

When you didn't use new keyword in this case, your list didn't initialized. And when you try to add it hai, obviously you get an error.

How to change an image on click using CSS alone?

This introduces a new paradigm to HTML/CSS, but using an <input readonly="true"> would allow you to append an input:focus selector to then alter the background-image

This of course would require applying specific CSS to the input itself to override browser defaults but it does go to show that click actions can indeed be triggered without the use of Javascript.

Remove non-ascii character in string

ASCII is in range of 0 to 127, so:

str.replace(/[^\x00-\x7F]/g, "");

ImportError: No Module named simplejson

Sometimes there is permission errors. Try:

sudo pip install simplejson

Hope it helps.

Best Regular Expression for Email Validation in C#

Email address: RFC 2822 Format
Matches a normal email address. Does not check the top-level domain.
Requires the "case insensitive" option to be ON.

[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?

Usage :

bool isEmail = Regex.IsMatch(emailString, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase);

Base64 Java encode and decode a string

The following is a good solution -

import android.util.Base64;

String converted = Base64.encodeToString(toConvert.toString().getBytes(), Base64.DEFAULT);

String stringFromBase = new String(Base64.decode(converted, Base64.DEFAULT));

That's it. A single line encoding and decoding.

Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource

Be aware to use constant HTTPS or HTTP for all requests. I had the same error msg: "No 'Access-Control-Allow-Origin' header is present on the requested resource."

No matching client found for package name (Google Analytics) - multiple productFlavors & buildTypes

This error occurs when you have a Google Services Json file downloaded in your project whose Package name doesn't match with your Project's package name.

Recently renamed the project's package name?

It does update all the classes but not the Gradle File. So check if your package name is correct in your Gradle, and also maybe Manifest too.

Remove CSS class from element with JavaScript (no jQuery)

Here's a way to bake this functionality right into all DOM elements:

HTMLElement.prototype.removeClass = function(remove) {
    var newClassName = "";
    var i;
    var classes = this.className.split(" ");
    for(i = 0; i < classes.length; i++) {
        if(classes[i] !== remove) {
            newClassName += classes[i] + " ";
        }
    }
    this.className = newClassName;
}

Turn off enclosing <p> tags in CKEditor 3.0

I'm doing something I'm not proud of as workaround. In my Python servlet that actually saves to the database, I do:

if description.startswith('<p>') and description.endswith('</p>'):
    description = description[3:-4]

.NET Console Application Exit Event

If you are using a console application and you are pumping messages, can't you use the WM_QUIT message?

Draw text in OpenGL ES

The Android SDK doesn't come with any easy way to draw text on OpenGL views. Leaving you with the following options.

  1. Place a TextView over your SurfaceView. This is slow and bad, but the most direct approach.
  2. Render common strings to textures, and simply draw those textures. This is by far the simplest and fastest, but the least flexible.
  3. Roll-your-own text rendering code based on a sprite. Probably second best choice if 2 isn't an option. A good way to get your feet wet but note that while it seems simple (and basic features are), it get's harder and more challenging as you add more features (texture-alignment, dealing with line-breaks, variable-width fonts etc.) - if you take this route, make it as simple as you can get away with!
  4. Use an off-the-shelf/open-source library. There are a few around if you hunt on Google, the tricky bit is getting them integrated and running. But at least, once you do that, you'll have all the flexibility and maturity they provide.

How do I find the date a video (.AVI .MP4) was actually recorded?

The best way I found of getting the "dateTaken" date for either video or pictures is to use:

 Imports Microsoft.WindowsAPICodePack.Shell
 Imports Microsoft.WindowsAPICodePack.Shell.PropertySystem
 Imports System.IO
 Dim picture As ShellObject = ShellObject.FromParsingName(path)
 Dim picture As ShellObject = ShellObject.FromParsingName(path)
 Dim ItemDate=picture.Properties.System.ItemDate

The above code requires the shell api, which is internal to Microsoft, and does not depend on any other external dll.

Using an if statement to check if a div is empty

if (typeof($('#container .prateleira')[0]) === 'undefined') {
    $('#ctl00_Conteudo_ctrPaginaSistemaAreaWrapper').css('display','none');
}

What is the easiest way to push an element to the beginning of the array?

Since Ruby 2.5.0, Array ships with the prepend method (which is just an alias for the unshift method).

SystemError: Parent module '' not loaded, cannot perform relative import

I usually use this workaround:

try:
    from .mymodule import myclass
except Exception: #ImportError
    from mymodule import myclass

Which means your IDE should pick up the right code location and the python interpreter will manage to run your code.

How to compare two lists in python?

for i in arr1:
    if i in arr2:
        return 1
    return  0
arr1=[1,2,5]
arr2=[2,4,15]
q=checkarrayequalornot(arr1,arr2)
print(q)
>>0

Callback function for JSONP with jQuery AJAX

$.ajax({
        url: 'http://url.of.my.server/submit',
        dataType: "jsonp",
        jsonp: 'callback',
        jsonpCallback: 'jsonp_callback'
    });

jsonp is the querystring parameter name that is defined to be acceptable by the server while the jsonpCallback is the javascript function name to be executed at the client.
When you use such url:

url: 'http://url.of.my.server/submit?callback=?'

the question mark ? at the end instructs jQuery to generate a random function while the predfined behavior of the autogenerated function will just invoke the callback -the sucess function in this case- passing the json data as a parameter.

$.ajax({
        url: 'http://url.of.my.server/submit?callback=?',
        success: function (data, status) {
            mySurvey.closePopup();
        },
        error: function (xOptions, textStatus) {
            mySurvey.closePopup();
        }
    });


The same goes here if you are using $.getJSON with ? placeholder it will generate a random function while the predfined behavior of the autogenerated function will just invoke the callback:

$.getJSON('http://url.of.my.server/submit?callback=?',function(data){
//process data here
});

Convert an image (selected by path) to base64 string

Try this

using (Image image = Image.FromFile(Path))
{
    using (MemoryStream m = new MemoryStream())
    {
        image.Save(m, image.RawFormat);
        byte[] imageBytes = m.ToArray();

        // Convert byte[] to Base64 String
        string base64String = Convert.ToBase64String(imageBytes);
        return base64String;
    }
}

Ruby value of a hash key?

Hashes are indexed using the square brackets ([]). Just as arrays. But instead of indexing with the numerical index, hashes are indexed using either the string literal you used for the key, or the symbol. So if your hash is similar to

hash = { "key1" => "value1", "key2" => "value2" }

you can access the value with

hash["key1"]

or for

hash = { :key1 => "value1", :key2 => "value2"}

or the new format supported in Ruby 1.9

hash = { key1: "value1", key2: "value2" }

you can access the value with

hash[:key1]

Convert a number range to another range, maintaining ratio

I wrote a function to do this in R. The method is the same as above, but I needed to do this a bunch of times in R, so I thought I'd share in case it helps anybody.

convertRange <- function(
  oldValue,
  oldRange = c(-16000.00, 16000.00), 
  newRange = c(0, 100),
  returnInt = TRUE # the poster asked for an integer, so this is an option
){
  oldMin <- oldRange[1]
  oldMax <- oldRange[2]
  newMin <- newRange[1]
  newMax <- newRange[2]
  newValue = (((oldValue - oldMin)* (newMax - newMin)) / (oldMax - oldMin)) + newMin
  
  if(returnInt){
   return(round(newValue))
  } else {
   return(newValue)
  }
}

jQuery UI Dialog OnBeforeUnload

For ASP.NET MVC if you want to make an exception for leaving the page via submitting a particular form:

Set a form id:

@using (Html.BeginForm("Create", "MgtJob", FormMethod.Post, new { id = "createjob" }))
{
  // Your code
}



<script type="text/javascript">

  // Without submit form
   $(window).bind('beforeunload', function () {
        if ($('input').val() !== '') {
            return "It looks like you have input you haven't submitted."
        }
    });

    // this will call before submit; and it will unbind beforeunload
    $(function () {
        $("#createjob").submit(function (event) {
            $(window).unbind("beforeunload");
        });
    });

</script>

LINQ extension methods - Any() vs. Where() vs. Exists()

Where returns a new sequence of items matching the predicate.

Any returns a Boolean value; there's a version with a predicate (in which case it returns whether or not any items match) and a version without (in which case it returns whether the query-so-far contains any items).

I'm not sure about Exists - it's not a LINQ standard query operator. If there's a version for the Entity Framework, perhaps it checks for existence based on a key - a sort of specialized form of Any? (There's an Exists method in List<T> which is similar to Any(predicate) but that predates LINQ.)

How to create a secure random AES key in Java?

Lots of good advince in the other posts. This is what I use:

Key key;
SecureRandom rand = new SecureRandom();
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(256, rand);
key = generator.generateKey();

If you need another randomness provider, which I sometime do for testing purposes, just replace rand with

MySecureRandom rand = new MySecureRandom();

How to add two edit text fields in an alert dialog

Check the following code. It shows 2 edit text fields programmatically without any layout xml. Change 'this' to 'getActivity()' if you use it in a fragment.

The tricky thing is we have to set the second text field's input type after creating alert dialog, otherwise, the second text field shows texts instead of dots.

    public void showInput() {
        OnFocusChangeListener onFocusChangeListener = new OnFocusChangeListener() {
            @Override
            public void onFocusChange(final View v, boolean hasFocus) {
                if (hasFocus) {
                    // Must use message queue to show keyboard
                    v.post(new Runnable() {
                        @Override
                        public void run() {
                            InputMethodManager inputMethodManager= (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                            inputMethodManager.showSoftInput(v, 0);
                        }
                    });
                }
            }
        };

        final EditText editTextName = new EditText(this);
        editTextName.setHint("Name");
        editTextName.setFocusable(true);
        editTextName.setClickable(true);
        editTextName.setFocusableInTouchMode(true);
        editTextName.setSelectAllOnFocus(true);
        editTextName.setSingleLine(true);
        editTextName.setImeOptions(EditorInfo.IME_ACTION_NEXT);
        editTextName.setOnFocusChangeListener(onFocusChangeListener);

        final EditText editTextPassword = new EditText(this);
        editTextPassword.setHint("Password");
        editTextPassword.setFocusable(true);
        editTextPassword.setClickable(true);
        editTextPassword.setFocusableInTouchMode(true);
        editTextPassword.setSelectAllOnFocus(true);
        editTextPassword.setSingleLine(true);
        editTextPassword.setImeOptions(EditorInfo.IME_ACTION_DONE);
        editTextPassword.setOnFocusChangeListener(onFocusChangeListener);

        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout.addView(editTextName);
        linearLayout.addView(editTextPassword);

        DialogInterface.OnClickListener alertDialogClickListener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which){
                case DialogInterface.BUTTON_POSITIVE:
                    // Done button clicked
                    break;
                case DialogInterface.BUTTON_NEGATIVE:
                    // Cancel button clicked
                    break;
                }
            }
        };
        final AlertDialog alertDialog = (new AlertDialog.Builder(this)).setMessage("Please enter name and password")
                .setView(linearLayout)
                .setPositiveButton("Done", alertDialogClickListener)
                .setNegativeButton("Cancel", alertDialogClickListener)
                .create();

        editTextName.setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                editTextPassword.requestFocus(); // Press Return to focus next one
                return false;
            }
        });
        editTextPassword.setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                // Press Return to invoke positive button on alertDialog.
                alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).performClick();
                return false;
            }
        });

        // Must set password mode after creating alert dialog.
        editTextPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
        editTextPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
        alertDialog.show();
    }

jQuery bind to Paste Event, how to get the content of the paste

This work on all browser to get pasted value. And also to creating common method for all text box.

$("#textareaid").bind("paste", function(e){       
    var pastedData = e.target.value;
    alert(pastedData);
} )

Converting Pandas dataframe into Spark dataframe error

I have tried this with your data and it is working :

%pyspark
import pandas as pd
from pyspark.sql import SQLContext
print sc
df = pd.read_csv("test.csv")
print type(df)
print df
sqlCtx = SQLContext(sc)
sqlCtx.createDataFrame(df).show()

Using scanner.nextLine()

It's because when you enter a number then press Enter, input.nextInt() consumes only the number, not the "end of line". Primitive data types like int, double etc do not consume "end of line", therefore the "end of line" remains in buffer and When input.next() executes, it consumes the "end of line" from buffer from the first input. That's why, your String sentence = scanner.next() only consumes the "end of line" and does not wait to read from keyboard.

Tip: use scanner.nextLine() instead of scanner.next() because scanner.next() does not read white spaces from the keyboard. (Truncate the string after giving some space from keyboard, only show string before space.)

Cassandra "no viable alternative at input"

Wrong syntax. Here you are:

insert into user_by_category (game_category,customer_id) VALUES ('Goku','12');

or:

insert into user_by_category ("game_category","customer_id") VALUES ('Kakarot','12');

The second one is normally used for case-sensitive column names.

Finishing current activity from a fragment

When working with fragments, instead of using this or refering to the context, always use getActivity(). You should call

getActivity().finish();

to finish your activity from fragment.

Import module from subfolder

Just to notify here. (from a newbee, keviv22)

Never and ever for the sake of your own good, name the folders or files with symbols like "-" or "_". If you did so, you may face few issues. like mine, say, though your command for importing is correct, you wont be able to successfully import the desired files which are available inside such named folders.

Invalid Folder namings as follows:

  • Generic-Classes-Folder
  • Generic_Classes_Folder

valid Folder namings for above:

  • GenericClassesFolder or Genericclassesfolder or genericClassesFolder (or like this without any spaces or special symbols among the words)

What mistake I did:

consider the file structure.

Parent
   . __init__.py
   . Setup
     .. __init__.py
     .. Generic-Class-Folder
        ... __init__.py
        ... targetClass.py
   . Check
     .. __init__.py
     .. testFile.py

What I wanted to do?

  • from testFile.py, I wanted to import the 'targetClass.py' file inside the Generic-Class-Folder file to use the function named "functionExecute" in 'targetClass.py' file

What command I did?

  • from 'testFile.py', wrote command, from Core.Generic-Class-Folder.targetClass import functionExecute
  • Got errors like SyntaxError: invalid syntax

Tried many searches and viewed many stackoverflow questions and unable to decide what went wrong. I cross checked my files multiple times, i used __init__.py file, inserted environment path and hugely worried what went wrong......

And after a long long long time, i figured this out while talking with a friend of mine. I am little stupid to use such naming conventions. I should never use space or special symbols to define a name for any folder or file. So, this is what I wanted to convey. Have a good day!

(sorry for the huge post over this... just letting my frustrations go.... :) Thanks!)

Create pandas Dataframe by appending one row at a time

pandas.DataFrame.append

DataFrame.append(self, other, ignore_index=False, verify_integrity=False, sort=False) ? 'DataFrame'

df = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))
df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB'))
df.append(df2)

With ignore_index set to True:

df.append(df2, ignore_index=True)

Find p-value (significance) in scikit-learn LinearRegression

An easy way to pull of the p-values is to use statsmodels regression:

import statsmodels.api as sm
mod = sm.OLS(Y,X)
fii = mod.fit()
p_values = fii.summary2().tables[1]['P>|t|']

You get a series of p-values that you can manipulate (for example choose the order you want to keep by evaluating each p-value):

enter image description here

How can I mix LaTeX in with Markdown?

I'll answer your question with a counter-question...

What do you think of Org-mode? It's not as pure as Markdown, but it is Markdown-like, and I find it as easy to work with, and it allows embedding of Latex. Cf. http://www.gnu.org/software/emacs/manual/html_node/org/Embedded-LaTeX.html

Postscript

In case you haven't looked at org-mode, it has one great strength as a general purpose "natural markup language" over Markdown, namely its treatment of tables. The source:

| 1 | 0 | 0 |
| -1 | 1 | 0 |
| -1 | -1 | 1 |

represents just what you think it will...

And the Latex is rendered in pieces using tex-mode's preview-latex.

python: how to identify if a variable is an array or a scalar

I am surprised that such a basic question doesn't seem to have an immediate answer in python. It seems to me that nearly all proposed answers use some kind of type checking, that is usually not advised in python and they seem restricted to a specific case (they fail with different numerical types or generic iteratable objects that are not tuples or lists).

For me, what works better is importing numpy and using array.size, for example:

>>> a=1
>>> np.array(a)
Out[1]: array(1)

>>> np.array(a).size
Out[2]: 1

>>> np.array([1,2]).size
Out[3]: 2

>>> np.array('125')
Out[4]: 1

Note also:

>>> len(np.array([1,2]))

Out[5]: 2

but:

>>> len(np.array(a))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-40-f5055b93f729> in <module>()
----> 1 len(np.array(a))

TypeError: len() of unsized object

How to comment in Vim's config files: ".vimrc"?

You can add comments in Vim's configuration file by either:

" brief descriptiion of command

or:

"" commended command

Taken from here

How can I render inline JavaScript with Jade / Pug?

script(nonce="some-nonce").
  console.log("test");

//- Workaround
<script nonce="some-nonce">console.log("test");</script>

MySQL Daemon Failed to Start - centos 6

  1. /etc/init.d/mysql stop
  2. chown -R mysql:mysql /var/lib/mysql
  3. mysql_install_db
  4. /etc/init.d/mysql start

All this rescued my MySQL server!

HTML: how to make 2 tables with different CSS

You need to assign different classes to each table.

Create a class in CSS with the dot '.' operator and write your properties inside each class. For example,

.table1 {
//some properties
}

.table2 {
//Some other properties
}

and use them in your html code.

JPG vs. JPEG image formats

The term "JPEG" is an acronym for the Joint Photographic Experts Group, which created the standard. .jpeg and .jpg files are identical. JPEG images are identified with 6 different standard file name extensions:

  • .jpg
  • .jpeg
  • .jpe
  • .jif
  • .jfif
  • .jfi

The jpg was used in Microsoft Operating Systems when they only supported 3 chars-extensions.

The JPEG File Interchange Format (JFIF - last three extensions in my list) is an image file format standard for exchanging JPEG encoded files compliant with the JPEG Interchange Format (JIF) standard, solving some of JIF's limitations in regard. Image data in JFIF files is compressed using the techniques in the JPEG standard, hence JFIF is sometimes referred to as "JPEG/JFIF".

Format XML string to print friendly XML string

if you load up the XMLDoc I'm pretty sure the .ToString() function posses an overload for this.

But is this for debugging? The reason that it is sent like that is to take up less space (i.e stripping unneccessary whitespace from the XML).

How to correctly implement custom iterators and const_iterators?

  • Choose type of iterator which fits your container: input, output, forward etc.
  • Use base iterator classes from standard library. For example, std::iterator with random_access_iterator_tag.These base classes define all type definitions required by STL and do other work.
  • To avoid code duplication iterator class should be a template class and be parametrized by "value type", "pointer type", "reference type" or all of them (depends on implementation). For example:

    // iterator class is parametrized by pointer type
    template <typename PointerType> class MyIterator {
        // iterator class definition goes here
    };
    
    typedef MyIterator<int*> iterator_type;
    typedef MyIterator<const int*> const_iterator_type;
    

    Notice iterator_type and const_iterator_type type definitions: they are types for your non-const and const iterators.

See Also: standard library reference

EDIT: std::iterator is deprecated since C++17. See a relating discussion here.

Export P7b file with all the certificate chain into CER file

The selected answer didn't work for me, but it's close. I found a tutorial that worked for me and the certificate I obtained from StartCom.

  1. Open the .p7b in a text editor.
  2. Change the leader and trailer so the file looks similar to this:

    -----BEGIN PKCS7-----
    [... certificate content here ...]
    -----END PKCS7-----
    

For example, my StartCom certificate began with:

    -----BEGIN CERTIFICATE----- 

and ended with:

    -----END CERTIFICATE----- 
  1. Save and close the .p7b.
  2. Run the following OpenSSL command (works on Ubuntu 14.04.4, as of this writing):

    openssl pkcs7 -print_certs –in pkcs7.p7b -out pem.cer
    

The output is a .cer with the certificate chain.

Reference: http://www.freetutorialssubmit.com/extract-certificates-from-P7B/2206

Remove all git files from a directory?

cd to the repository then

find . -name ".git*" -exec rm -R {} \;

Make sure not to accidentally pipe a single dot, slash, asterisk, or other regex wildcard into find, or else rm will happily delete it.

Is Java's assertEquals method reliable?

assertEquals uses the equals method for comparison. There is a different assert, assertSame, which uses the == operator.

To understand why == shouldn't be used with strings you need to understand what == does: it does an identity check. That is, a == b checks to see if a and b refer to the same object. It is built into the language, and its behavior cannot be changed by different classes. The equals method, on the other hand, can be overridden by classes. While its default behavior (in the Object class) is to do an identity check using the == operator, many classes, including String, override it to instead do an "equivalence" check. In the case of String, instead of checking if a and b refer to the same object, a.equals(b) checks to see if the objects they refer to are both strings that contain exactly the same characters.

Analogy time: imagine that each String object is a piece of paper with something written on it. Let's say I have two pieces of paper with "Foo" written on them, and another with "Bar" written on it. If I take the first two pieces of paper and use == to compare them it will return false because it's essentially asking "are these the same piece of paper?". It doesn't need to even look at what's written on the paper. The fact that I'm giving it two pieces of paper (rather than the same one twice) means it will return false. If I use equals, however, the equals method will read the two pieces of paper and see that they say the same thing ("Foo"), and so it'll return true.

The bit that gets confusing with Strings is that the Java has a concept of "interning" Strings, and this is (effectively) automatically performed on any string literals in your code. This means that if you have two equivalent string literals in your code (even if they're in different classes) they'll actually both refer to the same String object. This makes the == operator return true more often than one might expect.

How do you set the Content-Type header for an HttpClient request?

try to use TryAddWithoutValidation

  var client = new HttpClient();
  client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");

Change URL and redirect using jQuery

you can do it simpler without jquery

location = "https://example.com/" + txt.value

_x000D_
_x000D_
function send() {_x000D_
  location = "https://example.com/" + txt.value;_x000D_
}
_x000D_
<form id="abc">_x000D_
  <input type="text" id="txt" />_x000D_
</form>_x000D_
_x000D_
<button onclick="send()">Send</button>
_x000D_
_x000D_
_x000D_

NodeJS / Express: what is "app.use"?

app.use
is created by express(nodejs middleware framework )
app.use is use to execute any specific query at intilization process
server.js(node)
var app = require('express');
app.use(bodyparser.json())
so the basically app.use function called every time when server up

In MySQL, how to copy the content of one table to another table within the same database?

CREATE TABLE target_table SELECT * FROM source_table;

It just create a new table with same structure as of source table and also copy all rows from source_table into target_table.

CREATE TABLE target_table SELECT * FROM source_table WHERE condition;

If you need some rows to be copied into target_table, then apply a condition inside where clause

jsonify a SQLAlchemy result set in Flask

It seems that you actually haven't executed your query. Try following:

return jsonify(json_list = qryresult.all())

[Edit]: Problem with jsonify is, that usually the objects cannot be jsonified automatically. Even Python's datetime fails ;)

What I have done in the past, is adding an extra property (like serialize) to classes that need to be serialized.

def dump_datetime(value):
    """Deserialize datetime object into string form for JSON processing."""
    if value is None:
        return None
    return [value.strftime("%Y-%m-%d"), value.strftime("%H:%M:%S")]

class Foo(db.Model):
    # ... SQLAlchemy defs here..
    def __init__(self, ...):
       # self.foo = ...
       pass

    @property
    def serialize(self):
       """Return object data in easily serializable format"""
       return {
           'id'         : self.id,
           'modified_at': dump_datetime(self.modified_at),
           # This is an example how to deal with Many2Many relations
           'many2many'  : self.serialize_many2many
       }
    @property
    def serialize_many2many(self):
       """
       Return object's relations in easily serializable format.
       NB! Calls many2many's serialize property.
       """
       return [ item.serialize for item in self.many2many]

And now for views I can just do:

return jsonify(json_list=[i.serialize for i in qryresult.all()])

Hope this helps ;)

[Edit 2019]: In case you have more complex objects or circular references, use a library like marshmallow).

Javascript - How to show escape characters in a string?

JavaScript uses the \ (backslash) as an escape characters for:

  • \' single quote
  • \" double quote
  • \ backslash
  • \n new line
  • \r carriage return
  • \t tab
  • \b backspace
  • \f form feed
  • \v vertical tab (IE < 9 treats '\v' as 'v' instead of a vertical tab ('\x0B'). If cross-browser compatibility is a concern, use \x0B instead of \v.)
  • \0 null character (U+0000 NULL) (only if the next character is not a decimal digit; else it’s an octal escape sequence)

Note that the \v and \0 escapes are not allowed in JSON strings.

Difference between JSONObject and JSONArray

I always use object, it is more easily extendable, JSON array is not. For example you originally had some data as a json array, then you needed to add a status header on it you'd be a bit stuck, unless you'd nested the data in an object. The only disadvantage is a slight increase in complexity of creation / parsing.

So instead of

[datum0, datum1, datumN]

You'd have

{data: [datum0, datum1, datumN]}

then later you can add more...

{status: "foo", data: [datum0, datum1, datumN]}

How to get cookie expiration date / creation date from javascript?

It's now possible with new chrome update for version 47 for 2016 , you can see it through developer tools on the resources tabenter image description here, select cookies and look for your cookie expiration date under "Expires/Max-age"

How to convert milliseconds into a readable date?

No, you'll need to do it manually.

_x000D_
_x000D_
function prettyDate(date) {_x000D_
  var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',_x000D_
                'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];_x000D_
_x000D_
  return months[date.getUTCMonth()] + ' ' + date.getUTCDate() + ', ' + date.getUTCFullYear();_x000D_
}_x000D_
_x000D_
console.log(prettyDate(new Date(1324339200000)));
_x000D_
_x000D_
_x000D_

Javascript onload not working

There's nothing wrong with include file in head. It seems you forgot to add;. Please try this one:

<body onload="imageRefreshBig();">

But as per my knowledge semicolons are optional. You can try with ; but better debug code and see if chrome console gives any error.

I hope this helps.

Creating an empty list in Python

list() is inherently slower than [], because

  1. there is symbol lookup (no way for python to know in advance if you did not just redefine list to be something else!),

  2. there is function invocation,

  3. then it has to check if there was iterable argument passed (so it can create list with elements from it) ps. none in our case but there is "if" check

In most cases the speed difference won't make any practical difference though.

How to use LocalBroadcastManager?

When you'll play enough with LocalBroadcastReceiver I'll suggest you to give Green Robot's EventBus a try - you will definitely realize the difference and usefulness of it compared to LBR. Less code, customizable about receiver's thread (UI/Bg), checking receivers availability, sticky events, events could be used as data delivery etc.

How do I get a list of all the duplicate items using pandas in python?

df[df.duplicated(['ID'], keep=False)]

it'll return all duplicated rows back to you.

According to documentation:

keep : {‘first’, ‘last’, False}, default ‘first’

  • first : Mark duplicates as True except for the first occurrence.
  • last : Mark duplicates as True except for the last occurrence.
  • False : Mark all duplicates as True.

How to check if a div is visible state or not?

if element is hide by jquery then use

if($("#elmentid").is(':hidden'))

Difference between npx and npm?

Simple Definition:

npm - Javascript package manager

npx - Execute npm package binaries

How to store JSON object in SQLite database

https://github.com/app-z/Json-to-SQLite

At first generate Plain Old Java Objects from JSON http://www.jsonschema2pojo.org/

Main method

void createDb(String dbName, String tableName, List dataList, Field[] fields){ ...

Fields name will create dynamically

HashMap allows duplicates?

m.put(null,null); // here key=null, value=null
m.put(null,a);    // here also key=null, and value=a

Duplicate keys are not allowed in hashmap.
However,value can be duplicated.

Alter a MySQL column to be AUTO_INCREMENT

Roman is right, but note that the auto_increment column must be part of the PRIMARY KEY or a UNIQUE KEY (and in almost 100% of the cases, it should be the only column that makes up the PRIMARY KEY):

ALTER TABLE document MODIFY document_id INT AUTO_INCREMENT PRIMARY KEY

How to iterate over a TreeMap?

Using Google Collections, assuming K is your key type:

Maps.filterKeys(treeMap, new Predicate<K>() {
  @Override
  public boolean apply(K key) {
    return false; //return true here if you need the entry to be in your new map
  }});

You can use filterEntries instead if you need the value as well.

how to set imageview src?

What you are looking for is probably this:

ImageView myImageView;
myImageView = mDialog.findViewById(R.id.image_id);
String src = "imageFileName"

int drawableId = this.getResources().getIdentifier(src, "drawable", context.getPackageName())
popupImageView.setImageResource(drawableId);

Let me know if this was helpful :)

Session 'app' error while installing APK

your device can be the problem too

'cmd package install-create -r -t --full  -S 85640035' returns error 'Unknown failure: Exception occurred while executing:
        android.os.ParcelableException: java.io.IOException: Requested internal only, but not enough space
        at android.util.ExceptionUtils.wrap(ExceptionUtils.java:34)

when there is not enough storage

Array to Collection: Optimized code

Arrays.asList(array)

Arrays uses new ArrayList(array). But this is not the java.util.ArrayList. It's very similar though. Note that this constructor takes the array and places it as the backing array of the list. So it is O(1).

In case you already have the list created, Collections.addAll(list, array), but that's less efficient.

Update: Thus your Collections.addAll(list, array) becomes a good option. A wrapper of it is guava's Lists.newArrayList(array).

Use JavaScript to place cursor at end of text in text input element

Set the cursor when click on text area to the end of text... Variation of this code is...ALSO works! for Firefox, IE, Safari, Chrome..

In server-side code:

txtAddNoteMessage.Attributes.Add("onClick", "sendCursorToEnd('" & txtAddNoteMessage.ClientID & "');")

In Javascript:

function sendCursorToEnd(obj) {
    var value =  $(obj).val(); //store the value of the element
    var message = "";
    if (value != "") {
        message = value + "\n";
     };
    $(obj).focus().val(message);
    $(obj).unbind();
 }

Updating and committing only a file's permissions using git version control

By default, git will update execute file permissions if you change them. It will not change or track any other permissions.

If you don't see any changes when modifying execute permission, you probably have a configuration in git which ignore file mode.

Look into your project, in the .git folder for the config file and you should see something like this:

[core]
    filemode = false

You can either change it to true in your favorite text editor, or run:

git config core.filemode true

Then, you should be able to commit normally your files. It will only commit the permission changes.

Strip last two characters of a column in MySQL

To select all characters except the last n from a string (or put another way, remove last n characters from a string); use the SUBSTRING and CHAR_LENGTH functions together:

SELECT col
     , /* ANSI Syntax  */ SUBSTRING(col FROM 1 FOR CHAR_LENGTH(col) - 2) AS col_trimmed
     , /* MySQL Syntax */ SUBSTRING(col,     1,    CHAR_LENGTH(col) - 2) AS col_trimmed
FROM tbl

To remove a specific substring from the end of string, use the TRIM function:

SELECT col
     , TRIM(TRAILING '.php' FROM col)
-- index.php becomes index
-- index.txt remains index.txt

Using awk to print all columns from the nth to the last

Would this work?

awk '{print substr($0,length($1)+1);}' < file

It leaves some whitespace in front though.

How to convert a string to integer in C?

You can always roll your own!

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

int my_atoi(const char* snum)
{
    int idx, strIdx = 0, accum = 0, numIsNeg = 0;
    const unsigned int NUMLEN = (int)strlen(snum);

    /* Check if negative number and flag it. */
    if(snum[0] == 0x2d)
        numIsNeg = 1;

    for(idx = NUMLEN - 1; idx >= 0; idx--)
    {
        /* Only process numbers from 0 through 9. */
        if(snum[strIdx] >= 0x30 && snum[strIdx] <= 0x39)
            accum += (snum[strIdx] - 0x30) * pow(10, idx);

        strIdx++;
    }

    /* Check flag to see if originally passed -ve number and convert result if so. */
    if(!numIsNeg)
        return accum;
    else
        return accum * -1;
}

int main()
{
    /* Tests... */
    printf("Returned number is: %d\n", my_atoi("34574"));
    printf("Returned number is: %d\n", my_atoi("-23"));

    return 0;
}

This will do what you want without clutter.

Reinitialize Slick js after successful ajax call

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

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

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

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

How do I grep for all non-ASCII characters?

Searching for non-printable chars. TLDR; Executive Summary

  1. search for control chars AND extended unicode
  2. locale setting e.g. LC_ALL=C needed to make grep do what you might expect with extended unicode

SO the preferred non-ascii char finders:

$ perl -ne 'print "$. $_" if m/[\x00-\x08\x0E-\x1F\x80-\xFF]/' notes_unicode_emoji_test

as in top answer, the inverse grep:

$ grep --color='auto' -P -n "[^\x00-\x7F]" notes_unicode_emoji_test

as in top answer but WITH LC_ALL=C:

$ LC_ALL=C grep --color='auto' -P -n "[\x80-\xFF]" notes_unicode_emoji_test

. . more . . excruciating detail on this: . . .

I agree with Harvey above buried in the comments, it is often more useful to search for non-printable characters OR it is easy to think non-ASCII when you really should be thinking non-printable. Harvey suggests "use this: "[^\n -~]". Add \r for DOS text files. That translates to "[^\x0A\x020-\x07E]" and add \x0D for CR"

Also, adding -c (show count of patterns matched) to grep is useful when searching for non-printable chars as the strings matched can mess up terminal.

I found adding range 0-8 and 0x0e-0x1f (to the 0x80-0xff range) is a useful pattern. This excludes the TAB, CR and LF and one or two more uncommon printable chars. So IMHO a quite a useful (albeit crude) grep pattern is THIS one:

grep -c -P -n "[\x00-\x08\x0E-\x1F\x80-\xFF]" *

ACTUALLY, generally you will need to do this:

LC_ALL=C grep -c -P -n "[\x00-\x08\x0E-\x1F\x80-\xFF]" *

breakdown:

LC_ALL=C - set locale to C, otherwise many extended chars will not match (even though they look like they are encoded > 0x80)
\x00-\x08 - non-printable control chars 0 - 7 decimal
\x0E-\x1F - more non-printable control chars 14 - 31 decimal
\x80-1xFF - non-printable chars > 128 decimal
-c - print count of matching lines instead of lines
-P - perl style regexps

Instead of -c you may prefer to use -n (and optionally -b) or -l
-n, --line-number
-b, --byte-offset
-l, --files-with-matches

E.g. practical example of use find to grep all files under current directory:

LC_ALL=C find . -type f -exec grep -c -P -n "[\x00-\x08\x0E-\x1F\x80-\xFF]" {} + 

You may wish to adjust the grep at times. e.g. BS(0x08 - backspace) char used in some printable files or to exclude VT(0x0B - vertical tab). The BEL(0x07) and ESC(0x1B) chars can also be deemed printable in some cases.

Non-Printable ASCII Chars
** marks PRINTABLE but CONTROL chars that is useful to exclude sometimes
Dec   Hex Ctrl Char description           Dec Hex Ctrl Char description
0     00  ^@  NULL                        16  10  ^P  DATA LINK ESCAPE (DLE)
1     01  ^A  START OF HEADING (SOH)      17  11  ^Q  DEVICE CONTROL 1 (DC1)
2     02  ^B  START OF TEXT (STX)         18  12  ^R  DEVICE CONTROL 2 (DC2)
3     03  ^C  END OF TEXT (ETX)           19  13  ^S  DEVICE CONTROL 3 (DC3)
4     04  ^D  END OF TRANSMISSION (EOT)   20  14  ^T  DEVICE CONTROL 4 (DC4)
5     05  ^E  END OF QUERY (ENQ)          21  15  ^U  NEGATIVE ACKNOWLEDGEMENT (NAK)
6     06  ^F  ACKNOWLEDGE (ACK)           22  16  ^V  SYNCHRONIZE (SYN)
7     07  ^G  BEEP (BEL)                  23  17  ^W  END OF TRANSMISSION BLOCK (ETB)
8     08  ^H  BACKSPACE (BS)**            24  18  ^X  CANCEL (CAN)
9     09  ^I  HORIZONTAL TAB (HT)**       25  19  ^Y  END OF MEDIUM (EM)
10    0A  ^J  LINE FEED (LF)**            26  1A  ^Z  SUBSTITUTE (SUB)
11    0B  ^K  VERTICAL TAB (VT)**         27  1B  ^[  ESCAPE (ESC)
12    0C  ^L  FF (FORM FEED)**            28  1C  ^\  FILE SEPARATOR (FS) RIGHT ARROW
13    0D  ^M  CR (CARRIAGE RETURN)**      29  1D  ^]  GROUP SEPARATOR (GS) LEFT ARROW
14    0E  ^N  SO (SHIFT OUT)              30  1E  ^^  RECORD SEPARATOR (RS) UP ARROW
15    0F  ^O  SI (SHIFT IN)               31  1F  ^_  UNIT SEPARATOR (US) DOWN ARROW

UPDATE: I had to revisit this recently. And, YYMV depending on terminal settings/solar weather forecast BUT . . I noticed that grep was not finding many unicode or extended characters. Even though intuitively they should match the range 0x80 to 0xff, 3 and 4 byte unicode characters were not matched. ??? Can anyone explain this? YES. @frabjous asked and @calandoa explained that LC_ALL=C should be used to set locale for the command to make grep match.

e.g. my locale LC_ALL= empty

$ locale
LANG=en_IE.UTF-8
LC_CTYPE="en_IE.UTF-8"
.
.
LC_ALL=

grep with LC_ALL= empty matches 2 byte encoded chars but not 3 and 4 byte encoded:

$ grep -P -n "[\x00-\x08\x0E-\x1F\x80-\xFF]" notes_unicode_emoji_test
5:© copyright c2a9
7:call  underscore c2a0
9:CTRL
31:5 © copyright
32:7 call  underscore

grep with LC_ALL=C does seem to match all extended characters that you would want:

$ LC_ALL=C grep --color='auto' -P -n "[\x80-\xFF]" notes_unicode_emoji_test  
1:???? unicode dashes e28090
3:??? Heart With Arrow Emoji - Emojipedia == UTF8? f09f9298
5:? copyright c2a9
7:call? underscore c2a0
11:LIVE??E! ?????????? ???? ?????????? ???? ?? ?? ???? ????  YEOW, mix of japanese and chars from other e38182 e38184 . . e0a487
29:1 ???? unicode dashes
30:3 ??? Heart With Arrow Emoji - Emojipedia == UTF8 e28090
31:5 ? copyright
32:7 call? underscore
33:11 LIVE??E! ?????????? ???? ?????????? ???? ?? ?? ???? ????  YEOW, mix of japanese and chars from other
34:52 LIVE??E! ?????????? ???? ?????????? ???? ?? ?? ???? ????  YEOW, mix of japanese and chars from other
81:LIVE??E! ?????????? ???? ?????????? ???? ?? ?? ???? ????  YEOW, mix of japanese and chars from other

THIS perl match (partially found elsewhere on stackoverflow) OR the inverse grep on the top answer DO seem to find ALL the ~weird~ and ~wonderful~ "non-ascii" characters without setting locale:

$ grep --color='auto' -P -n "[^\x00-\x7F]" notes_unicode_emoji_test

$ perl -ne 'print "$. $_" if m/[\x00-\x08\x0E-\x1F\x80-\xFF]/' notes_unicode_emoji_test  

1 -- unicode dashes e28090
3  Heart With Arrow Emoji - Emojipedia == UTF8? f09f9298
5 © copyright c2a9
7 call  underscore c2a0
9 CTRL-H CHARS URK URK URK 
11 LIVE-E! ????? ?? ????? ?? ? ? ?? ??  YEOW, mix of japanese and chars from other e38182 e38184 . . e0a487
29 1 -- unicode dashes
30 3  Heart With Arrow Emoji - Emojipedia == UTF8 e28090
31 5 © copyright
32 7 call  underscore
33 11 LIVE-E! ????? ?? ????? ?? ? ? ?? ??  YEOW, mix of japanese and chars from other
34 52 LIVE-E! ????? ?? ????? ?? ? ? ?? ??  YEOW, mix of japanese and chars from other
73 LIVE-E! ????? ?? ????? ?? ? ? ?? ??  YEOW, mix of japanese and chars from other

SO the preferred non-ascii char finders:

$ perl -ne 'print "$. $_" if m/[\x00-\x08\x0E-\x1F\x80-\xFF]/' notes_unicode_emoji_test

as in top answer, the inverse grep:

$ grep --color='auto' -P -n "[^\x00-\x7F]" notes_unicode_emoji_test

as in top answer but WITH LC_ALL=C:

$ LC_ALL=C grep --color='auto' -P -n "[\x80-\xFF]" notes_unicode_emoji_test

How to install a Notepad++ plugin offline?

It's worth noting that the exact steps to follow can differ depending on the plugin. (E.g. I've just manually installed XML Tools and this involved copying some files from a subfolder into the root Notepad++ installation directory.) So would recommend the following:-

  1. Download the plugin you wish to install. A comprehensive list is provided at Notepad++ Plugin Central.
  2. Extract to a local folder (e.g. using 7-zip or similar).
  3. Look in the extracted files and folders for any readme files or specific instructions to be followed - and then follow them. In case there aren't any instructions, the one thing that must be done for all plugins is to copy the .DLL file into the plugins folder within your Notepad++ installation folder (e.g. C:\Program Files (x86)\Notepad++\plugins\).

JS - window.history - Delete a state

You may have moved on by now, but... as far as I know there's no way to delete a history entry (or state).

One option I've been looking into is to handle the history yourself in JavaScript and use the window.history object as a carrier of sorts.

Basically, when the page first loads you create your custom history object (we'll go with an array here, but use whatever makes sense for your situation), then do your initial pushState. I would pass your custom history object as the state object, as it may come in handy if you also need to handle users navigating away from your app and coming back later.

var myHistory = [];

function pageLoad() {
    window.history.pushState(myHistory, "<name>", "<url>");

    //Load page data.
}

Now when you navigate, you add to your own history object (or don't - the history is now in your hands!) and use replaceState to keep the browser out of the loop.

function nav_to_details() {
    myHistory.push("page_im_on_now");
    window.history.replaceState(myHistory, "<name>", "<url>");

    //Load page data.
}

When the user navigates backwards, they'll be hitting your "base" state (your state object will be null) and you can handle the navigation according to your custom history object. Afterward, you do another pushState.

function on_popState() {
    // Note that some browsers fire popState on initial load,
    // so you should check your state object and handle things accordingly.
    // (I did not do that in these examples!)

    if (myHistory.length > 0) {
        var pg = myHistory.pop();
        window.history.pushState(myHistory, "<name>", "<url>");

        //Load page data for "pg".
    } else {
        //No "history" - let them exit or keep them in the app.
    }
}

The user will never be able to navigate forward using their browser buttons because they are always on the newest page.

From the browser's perspective, every time they go "back", they've immediately pushed forward again.

From the user's perspective, they're able to navigate backwards through the pages but not forward (basically simulating the smartphone "page stack" model).

From the developer's perspective, you now have a high level of control over how the user navigates through your application, while still allowing them to use the familiar navigation buttons on their browser. You can add/remove items from anywhere in the history chain as you please. If you use objects in your history array, you can track extra information about the pages as well (like field contents and whatnot).

If you need to handle user-initiated navigation (like the user changing the URL in a hash-based navigation scheme), then you might use a slightly different approach like...

var myHistory = [];

function pageLoad() {
    // When the user first hits your page...
    // Check the state to see what's going on.

    if (window.history.state === null) {
        // If the state is null, this is a NEW navigation,
        //    the user has navigated to your page directly (not using back/forward).

        // First we establish a "back" page to catch backward navigation.
        window.history.replaceState(
            { isBackPage: true },
            "<back>",
            "<back>"
        );

        // Then push an "app" page on top of that - this is where the user will sit.
        // (As browsers vary, it might be safer to put this in a short setTimeout).
        window.history.pushState(
            { isBackPage: false },
            "<name>",
            "<url>"
        );

        // We also need to start our history tracking.
        myHistory.push("<whatever>");

        return;
    }

    // If the state is NOT null, then the user is returning to our app via history navigation.

    // (Load up the page based on the last entry of myHistory here)

    if (window.history.state.isBackPage) {
        // If the user came into our app via the back page,
        //     you can either push them forward one more step or just use pushState as above.

        window.history.go(1);
        // or window.history.pushState({ isBackPage: false }, "<name>", "<url>");
    }

    setTimeout(function() {
        // Add our popstate event listener - doing it here should remove
        //     the issue of dealing with the browser firing it on initial page load.
        window.addEventListener("popstate", on_popstate);
    }, 100);
}

function on_popstate(e) {
    if (e.state === null) {
        // If there's no state at all, then the user must have navigated to a new hash.

        // <Look at what they've done, maybe by reading the hash from the URL>
        // <Change/load the new page and push it onto the myHistory stack>
        // <Alternatively, ignore their navigation attempt by NOT loading anything new or adding to myHistory>

        // Undo what they've done (as far as navigation) by kicking them backwards to the "app" page
        window.history.go(-1);

        // Optionally, you can throw another replaceState in here, e.g. if you want to change the visible URL.
        // This would also prevent them from using the "forward" button to return to the new hash.
        window.history.replaceState(
            { isBackPage: false },
            "<new name>",
            "<new url>"
        );
    } else {
        if (e.state.isBackPage) {
            // If there is state and it's the 'back' page...

            if (myHistory.length > 0) {
                // Pull/load the page from our custom history...
                var pg = myHistory.pop();
                // <load/render/whatever>

                // And push them to our "app" page again
                window.history.pushState(
                    { isBackPage: false },
                    "<name>",
                    "<url>"
                );
            } else {
                // No more history - let them exit or keep them in the app.
            }
        }

        // Implied 'else' here - if there is state and it's NOT the 'back' page
        //     then we can ignore it since we're already on the page we want.
        //     (This is the case when we push the user back with window.history.go(-1) above)
    }
}

Getting the number of filled cells in a column (VBA)

One way is to: (Assumes index column begins at A1)

MsgBox Range("A1").End(xlDown).Row

Which is looking for the 1st unoccupied cell downwards from A1 and showing you its ordinal row number.

You can select the next empty cell with:

Range("A1").End(xlDown).Offset(1, 0).Select

If you need the end of a dataset (including blanks), try: Range("A:A").SpecialCells(xlLastCell).Row

Why does the preflight OPTIONS request of an authenticated CORS request work in Chrome but not Firefox?

Why does it work in Chrome and not Firefox?

The W3 spec for CORS preflight requests clearly states that user credentials should be excluded. There is a bug in Chrome and WebKit where OPTIONS requests returning a status of 401 still send the subsequent request.

Firefox has a related bug filed that ends with a link to the W3 public webapps mailing list asking for the CORS spec to be changed to allow authentication headers to be sent on the OPTIONS request at the benefit of IIS users. Basically, they are waiting for those servers to be obsoleted.

How can I get the OPTIONS request to send and respond consistently?

Simply have the server (API in this example) respond to OPTIONS requests without requiring authentication.

Kinvey did a good job expanding on this while also linking to an issue of the Twitter API outlining the catch-22 problem of this exact scenario interestingly a couple weeks before any of the browser issues were filed.

How do I add a library (android-support-v7-appcompat) in IntelliJ IDEA

Another yet simple solution is to paste these line into the build.gradle file

dependencies {

    //import of gridlayout
    compile 'com.android.support:gridlayout-v7:19.0.0'
    compile 'com.android.support:appcompat-v7:+'
}

Get number of digits with JavaScript

A solution that also works with both negative numbers and floats, and doesn't call any expensive String manipulation functions:

function getDigits(n) {
   var a = Math.abs(n);            // take care of the sign
   var b = a << 0;                 // truncate the number
   if(b - a !== 0) {               // if the number is a float
       return ("" + a).length - 1; // return the amount of digits & account for the dot
   } else {
       return ("" + a).length;     // return the amount of digits
   }
}

In JPA 2, using a CriteriaQuery, how to count results

You can also use Projections:

ProjectionList projection = Projections.projectionList();
projection.add(Projections.rowCount());
criteria.setProjection(projection);

Long totalRows = (Long) criteria.list().get(0);

Using numpy to build an array of all combinations of two arrays

It looks like you want a grid to evaluate your function, in which case you can use numpy.ogrid (open) or numpy.mgrid (fleshed out):

import numpy
my_grid = numpy.mgrid[[slice(0,1,0.1)]*6]

SQL Server : Transpose rows to columns

SQL Server has a PIVOT command that might be what you are looking for.

select * from Tag
pivot (MAX(Value) for TagID in ([A1],[A2],[A3],[A4])) as TagTime;

If the columns are not constant, you'll have to combine this with some dynamic SQL.

DECLARE @columns AS VARCHAR(MAX);
DECLARE @sql AS VARCHAR(MAX);

select @columns = substring((Select DISTINCT ',' + QUOTENAME(TagID) FROM Tag FOR XML PATH ('')),2, 1000);

SELECT @sql =

'SELECT *
FROM TAG
PIVOT 
(
  MAX(Value) 
  FOR TagID IN( ' + @columns + ' )) as TagTime;';

 execute(@sql);

Set environment variables from file of key/value pairs

My requirements were:

  • simple .env file without export prefixes (for compatibility with dotenv)
  • supporting values in quotes: TEXT="alpha bravo charlie"
  • supporting comments prefixed with # and empty lines
  • universal for both mac/BSD and linux/GNU

Full working version compiled from the answers above:

  set -o allexport
  eval $(grep -v '^#' .env | sed 's/^/export /')
  set +o allexport

Merge two rows in SQL

There are a few ways depending on some data rules that you have not included, but here is one way using what you gave.

SELECT
    t1.Field1,
    t2.Field2
FROM Table1 t1
    LEFT JOIN Table1 t2 ON t1.FK = t2.FK AND t2.Field1 IS NULL

Another way:

SELECT
    t1.Field1,
    (SELECT Field2 FROM Table2 t2 WHERE t2.FK = t1.FK AND Field1 IS NULL) AS Field2
FROM Table1 t1

bash "if [ false ];" returns true instead of false -- why?

You are running the [ (aka test) command with the argument "false", not running the command false. Since "false" is a non-empty string, the test command always succeeds. To actually run the command, drop the [ command.

if false; then
   echo "True"
else
   echo "False"
fi

How to increase scrollback buffer size in tmux?

Open tmux configuration file with the following command:

vim ~/.tmux.conf

In the configuration file add the following line:

set -g history-limit 5000

Log out and log in again, start a new tmux windows and your limit is 5000 now.

Error :- java runtime environment JRE or java development kit must be available in order to run eclipse

This doesn't seem to be relevant in this case, but in case others face this problem --- make sure that if you installed 32 bit version of Eclipse, you also installed 32 bit version of JRE. Similarly, if you installed 64 bit version of Eclipse, you need 64 bit version of JRE in your Windows. Otherwise you will see the above error message as well.

How do I create an empty array/matrix in NumPy?

Here is some workaround to make numpys look more like Lists

np_arr = np.array([])
np_arr = np.append(np_arr , 2)
np_arr = np.append(np_arr , 24)
print(np_arr)

OUTPUT: array([ 2., 24.])

How to copy a java.util.List into another java.util.List

You should use the addAll method. It appends all of the elements in the specified collection to the end of the copy list. It will be a copy of your list.

List<String> myList = new ArrayList<>();
myList.add("a");
myList.add("b");
List<String> copyList = new ArrayList<>();
copyList.addAll(myList);

Convert a binary NodeJS Buffer to JavaScript ArrayBuffer

A quicker way to write it

var arrayBuffer = new Uint8Array(nodeBuffer).buffer;

However, this appears to run roughly 4 times slower than the suggested toArrayBuffer function on a buffer with 1024 elements.

How to add custom html attributes in JSX

You can add an attribute using ES6 spread operator, e.g.

let myAttr = {'data-attr': 'value'}

and in render method:

<MyComponent {...myAttr} />

Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST

'T' and 'Z' are considered here as constants. You need to pass Z without the quotes. Moreover you need to specify the timezone in the input string.

Example : 2013-09-29T18:46:19-0700 And the format as "yyyy-MM-dd'T'HH:mm:ssZ"

Convert integer to string Jinja

I found the answer.

Cast integer to string:

myOldIntValue|string

Cast string to integer:

myOldStrValue|int

When does a process get SIGABRT (signal 6)?

SIGABRT is commonly used by libc and other libraries to abort the program in case of critical errors. For example, glibc sends an SIGABRT in case of a detected double-free or other heap corruptions.

Also, most assert implementations make use of SIGABRT in case of a failed assert.

Furthermore, SIGABRT can be sent from any other process like any other signal. Of course, the sending process needs to run as same user or root.

What is a race condition?

A "race condition" exists when multithreaded (or otherwise parallel) code that would access a shared resource could do so in such a way as to cause unexpected results.

Take this example:

for ( int i = 0; i < 10000000; i++ )
{
   x = x + 1; 
}

If you had 5 threads executing this code at once, the value of x WOULD NOT end up being 50,000,000. It would in fact vary with each run.

This is because, in order for each thread to increment the value of x, they have to do the following: (simplified, obviously)

Retrieve the value of x
Add 1 to this value
Store this value to x

Any thread can be at any step in this process at any time, and they can step on each other when a shared resource is involved. The state of x can be changed by another thread during the time between x is being read and when it is written back.

Let's say a thread retrieves the value of x, but hasn't stored it yet. Another thread can also retrieve the same value of x (because no thread has changed it yet) and then they would both be storing the same value (x+1) back in x!

Example:

Thread 1: reads x, value is 7
Thread 1: add 1 to x, value is now 8
Thread 2: reads x, value is 7
Thread 1: stores 8 in x
Thread 2: adds 1 to x, value is now 8
Thread 2: stores 8 in x

Race conditions can be avoided by employing some sort of locking mechanism before the code that accesses the shared resource:

for ( int i = 0; i < 10000000; i++ )
{
   //lock x
   x = x + 1; 
   //unlock x
}

Here, the answer comes out as 50,000,000 every time.

For more on locking, search for: mutex, semaphore, critical section, shared resource.

Set the text in a span

You need to fix your selector. Although CSS syntax requires multiple classes to be space separated, selector syntax would require them to be directly concatenated, and dot prefixed:

$(".ui-icon.ui-icon-circle-triangle-w").text(...);

or better:

$(".ui-datepicker-prev > span").text(...);

Upgrading React version and it's dependencies by reading package.json

Use this command to update react npm install --save [email protected] Don't forget to change 16.12.0 to the latest version or the version you need to setup.

CSS animation delay in repeating

I made a poster on the wall which moves left and right with intervals. For me it works:

.div-animation {
   -webkit-animation: bounce 2000ms ease-out;
    -moz-animation: bounce 2000ms ease-out;
    -o-animation: bounce 2000ms ease-out;
    animation: bounce 2000ms ease-out infinite;
    -webkit-animation-delay: 2s; /* Chrome, Safari, Opera */
    animation-delay: 2s;
    transform-origin: 55% 10%;    
}

@-webkit-keyframes bounce {
    0% {
        transform: rotate(0deg);
    }
    3% {
        transform: rotate(1deg);
    }
    6% {
        transform: rotate(2deg);
    }
    9% {
        transform: rotate(3deg);
    }
    12% {
        transform: rotate(2deg);
    }
    15% {
        transform: rotate(1deg);
    }
    18% {
        transform: rotate(0deg);
    }
    21% {
        transform: rotate(-1deg);
    }
    24% {
        transform: rotate(-2deg);
    }
    27% {
        transform: rotate(-3deg);
    }
    30% {
        transform: rotate(-2deg);
    }
    33% {
        transform: rotate(-1deg);
    }
    36% {
        transform: rotate(0deg);
    }
    100% {
        transform: rotate(0deg);
    }
}

How to truncate a foreign key constrained table?

Just use CASCADE

TRUNCATE "products" RESTART IDENTITY CASCADE;

But be ready for cascade deletes )

Make an existing Git branch track a remote branch?

To avoid remembering what you need to do each time you get the message:

Please specify which branch you want to merge with. See git-pull(1)
for details.
.....

You can use the following script which sets origin as upstream for the current branch you are in.

In my case I almost never set something else than origin as the default upstream. Also I almost always keep the same branch name for local and remote branch. So the following fits me:

#!/bin/bash
# scriptname: git-branch-set-originupstream
current_branch="$(git branch | grep -oP '(?<=^\* )(.*)$')"
upstream="origin/$current_branch"
git branch -u "$upstream"

Using AES encryption in C#

For a more complete example that performs key derivation in addition to the AES encryption, see the answer and links posted in Getting AES encryption to work across Javascript and C#.

EDIT
a side note: Javascript Cryptography considered harmful. Worth the read.

Getting key with maximum value in dictionary?

Example:

stats = {'a':1000, 'b':3000, 'c': 100}

if you wanna find the max value with its key, maybe follwing could be simple, without any relevant functions.

max(stats, key=stats.get)

the output is the key which has the max value.

How do I find the caller of a method using stacktrace or reflection?

I've done this before. You can just create a new exception and grab the stack trace on it without throwing it, then examine the stack trace. As the other answer says though, it's extremely costly--don't do it in a tight loop.

I've done it before for a logging utility on an app where performance didn't matter much (Performance rarely matters much at all, actually--as long as you display the result to an action such as a button click quickly).

It was before you could get the stack trace, exceptions just had .printStackTrace() so I had to redirect System.out to a stream of my own creation, then (new Exception()).printStackTrace(); Redirect System.out back and parse the stream. Fun stuff.

Embedding SVG into ReactJS

There is a package that converts it for you and returns the svg as a string to implement into your reactJS file.

https://www.npmjs.com/package/convert-svg-react

Overriding a JavaScript function while referencing the original

The Proxy pattern might help you:

(function() {
    // log all calls to setArray
    var proxied = jQuery.fn.setArray;
    jQuery.fn.setArray = function() {
        console.log( this, arguments );
        return proxied.apply( this, arguments );
    };
})();

The above wraps its code in a function to hide the "proxied"-variable. It saves jQuery's setArray-method in a closure and overwrites it. The proxy then logs all calls to the method and delegates the call to the original. Using apply(this, arguments) guarantees that the caller won't be able to notice the difference between the original and the proxied method.