Programs & Examples On #Document based

return in for loop or outside loop

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

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

HttpServletRequest to complete URL

Somewhat late to the party, but I included this in my MarkUtils-Web library in WebUtils - Checkstyle-approved and JUnit-tested:

import javax.servlet.http.HttpServletRequest;

public class GetRequestUrl{
    /**
     * <p>A faster replacement for {@link HttpServletRequest#getRequestURL()}
     *  (returns a {@link String} instead of a {@link StringBuffer} - and internally uses a {@link StringBuilder})
     *  that also includes the {@linkplain HttpServletRequest#getQueryString() query string}.</p>
     * <p><a href="https://gist.github.com/ziesemer/700376d8da8c60585438"
     *  >https://gist.github.com/ziesemer/700376d8da8c60585438</a></p>
     * @author Mark A. Ziesemer
     *  <a href="http://www.ziesemer.com.">&lt;www.ziesemer.com&gt;</a>
     */
    public String getRequestUrl(final HttpServletRequest req){
        final String scheme = req.getScheme();
        final int port = req.getServerPort();
        final StringBuilder url = new StringBuilder(256);
        url.append(scheme);
        url.append("://");
        url.append(req.getServerName());
        if(!(("http".equals(scheme) && (port == 0 || port == 80))
                || ("https".equals(scheme) && port == 443))){
            url.append(':');
            url.append(port);
        }
        url.append(req.getRequestURI());
        final String qs = req.getQueryString();
        if(qs != null){
            url.append('?');
            url.append(qs);
        }
        final String result = url.toString();
        return result;
    }
}

Probably the fastest and most robust answer here so far behind Mat Banik's - but even his doesn't account for potential non-standard port configurations with HTTP/HTTPS.

See also:

Numpy - add row to array

import numpy as np
array_ = np.array([[1,2,3]])
add_row = np.array([[4,5,6]])

array_ = np.concatenate((array_, add_row), axis=0)

how to create a window with two buttons that will open a new window

You add your ActionListener twice to button. So correct your code for button2 to

  JButton button2 = new JButton("hello agin2");
  panel.add(button2);
  button2.addActionListener (new Action2());//note the button2 here instead of button

Furthermore, perform your Swing operations on the correct thread by using EventQueue.invokeLater

Why declare unicode by string in python?

That doesn't set the format of the string; it sets the format of the file. Even with that header, "hello" is a byte string, not a Unicode string. To make it Unicode, you're going to have to use u"hello" everywhere. The header is just a hint of what format to use when reading the .py file.

scp files from local to remote machine error: no such file or directory

i had a kind of similar problem. i tried to copy from a server to my desktop and always got the same message for the local path. the problem was, i already was logged in to my server per ssh, so it was searching for the local path in the server path.

solution: i had to log out and run the command again and it worked

Why use Select Top 100 Percent?

The error says it all...

Msg 1033, Level 15, State 1, Procedure TestView, Line 5 The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.

Don't use TOP 100 PERCENT, use TOP n, where N is a number

The TOP 100 PERCENT (for reasons I don't know) is ignored by SQL Server VIEW (post 2012 versions), but I think MS kept it for syntax reasons. TOP n is better and will work inside a view and sort it the way you want when a view is used initially, but be careful.

Generate pdf from HTML in div using Javascript

  • No depenencies, pure JS
  • To add CSS or images - do not use relative URLs, use full URLs http://...domain.../path.css or so. It creates separate HTML document and it has no context of main thing.
  • you can also embed images as base64

This served me for years now:

export default function printDiv({divId, title}) {
  let mywindow = window.open('', 'PRINT', 'height=650,width=900,top=100,left=150');

  mywindow.document.write(`<html><head><title>${title}</title>`);
  mywindow.document.write('</head><body >');
  mywindow.document.write(document.getElementById(divId).innerHTML);
  mywindow.document.write('</body></html>');

  mywindow.document.close(); // necessary for IE >= 10
  mywindow.focus(); // necessary for IE >= 10*/

  mywindow.print();
  mywindow.close();

  return true;
}

"unadd" a file to svn before commit

For Files - svn revert filename

For Folders - svn revert -R folder

No shadow by default on Toolbar?

In my situation elevation doesn't work well because I haven't given any background to the toolbar. Try giving background color to the toolbar then set elevation and it will work well.

How to discover number of *logical* cores on Mac OS X?

$ system_profiler | grep 'Total Number Of Cores'

vertical & horizontal lines in matplotlib

The pyplot functions you are calling, axhline() and axvline() draw lines that span a portion of the axis range, regardless of coordinates. The parameters xmin or ymin use value 0.0 as the minimum of the axis and 1.0 as the maximum of the axis.

Instead, use plt.plot((x1, x2), (y1, y2), 'k-') to draw a line from the point (x1, y1) to the point (x2, y2) in color k. See pyplot.plot.

json parsing error syntax error unexpected end of input

I did this in Node JS and it solved this problem:

var data = JSON.parse(Buffer.concat(arr).toString());

What is Bootstrap?

Bootstrap is the world’s most popular and widely used open-source framework for developing with HTML, CSS, and JS. It is a front end framework of HTML. Bootstrap helps in building responsive websites or web applications and a 12-column grid system that helps dynamically adjust the website to a suitable screen resolution. The current version of bootstrap is 4.3.1 and the bootstrap team has also officially announced Bootstrap 5 version and changes like removing jquery from bootstrap. Some of the crucial reasons why bootstrap framework is most preferable are

  • It is easy to use

  • Bootstrap has a big community support

  • Customizations can be done easily

  • It increases development speed

  • Responsiveness

    For more details, you can check the official website: https://getbootstrap.com/

Source: https://vmokshagroup.com/blog/bootstrap-advantages/

How do you write to a folder on an SD card in Android?

Add Permission to Android Manifest

Add this WRITE_EXTERNAL_STORAGE permission to your applications manifest.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="your.company.package"
    android:versionCode="1"
    android:versionName="0.1">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <!-- ... -->
    </application>
    <uses-sdk android:minSdkVersion="7" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest> 

Check availability of external storage

You should always check for availability first. A snippet from the official android documentation on external storage.

boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state)) {
    // We can read and write the media
    mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
    // We can only read the media
    mExternalStorageAvailable = true;
    mExternalStorageWriteable = false;
} else {
    // Something else is wrong. It may be one of many other states, but all we need
    //  to know is we can neither read nor write
    mExternalStorageAvailable = mExternalStorageWriteable = false;
}

Use a Filewriter

At last but not least forget about the FileOutputStream and use a FileWriter instead. More information on that class form the FileWriter javadoc. You'll might want to add some more error handling here to inform the user.

// get external storage file reference
FileWriter writer = new FileWriter(getExternalStorageDirectory()); 
// Writes the content to the file
writer.write("This\n is\n an\n example\n"); 
writer.flush();
writer.close();

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays

You should use async pipe. Doc: https://angular.io/api/common/AsyncPipe

For example:

<li *ngFor="let a of authorizationTypes | async"[value]="a.id">
     {{ a.name }}
</li>

Force IE9 to emulate IE8. Possible?

The 1st element as in no hard returns. A hard return I guess = an empty node/element in the DOM which becomes the 1st element disabling the doc compatability meta tag.

Can I add jars to maven 2 build classpath without installing them?

You really ought to get a framework in place via a repository and identifying your dependencies up front. Using the system scope is a common mistake people use, because they "don't care about the dependency management." The trouble is that doing this you end up with a perverted maven build that will not show maven in a normal condition. You would be better off following an approach like this.

Percentage width in a RelativeLayout

You cannot use percentages to define the dimensions of a View inside a RelativeLayout. The best ways to do it is to use LinearLayout and weights, or a custom Layout.

javax.faces.application.ViewExpiredException: View could not be restored

Avoid multipart forms in Richfaces:

<h:form enctype="multipart/form-data">
    <a4j:poll id="poll" interval="10000"/>
</h:form>

If you are using Richfaces, i have found that ajax requests inside of multipart forms return a new View ID on each request.

How to debug:

On each ajax request a View ID is returned, that is fine as long as the View ID is always the same. If you get a new View ID on each request, then there is a problem and must be fixed.

How do I get extra data from intent on Android?

First, get the intent which has started your activity using the getIntent() method:

Intent intent = getIntent();

If your extra data is represented as strings, then you can use intent.getStringExtra(String name) method. In your case:

String id = intent.getStringExtra("id");
String name = intent.getStringExtra("name");

Count number of columns in a table row

document.getElementById('table1').rows[0].cells.length

cells is not a property of a table, rows are. Cells is a property of a row though

Django ChoiceField

Better Way to Provide Choice inside a django Model :

from django.db import models

class Student(models.Model):
    FRESHMAN = 'FR'
    SOPHOMORE = 'SO'
    JUNIOR = 'JR'
    SENIOR = 'SR'
    GRADUATE = 'GR'
    YEAR_IN_SCHOOL_CHOICES = [
        (FRESHMAN, 'Freshman'),
        (SOPHOMORE, 'Sophomore'),
        (JUNIOR, 'Junior'),
        (SENIOR, 'Senior'),
        (GRADUATE, 'Graduate'),
    ]
    year_in_school = models.CharField(
        max_length=2,
        choices=YEAR_IN_SCHOOL_CHOICES,
        default=FRESHMAN,
    )

CXF: No message body writer found for class - automatically mapping non-simple resources

If you are using "cxf-rt-rs-client" version 3.03. or above make sure the xml name space and schemaLocation are declared as below

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:jaxrs="http://cxf.apache.org/jaxrs" 
    xmlns:jaxrs-client="http://cxf.apache.org/jaxrs-client"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd http://cxf.apache.org/jaxrs-client http://cxf.apache.org/schemas/jaxrs-client.xsd">

And make sure the client have JacksonJsonProvider or your custom JsonProvider

<jaxrs-client:client id="serviceClient" address="${cxf.endpoint.service.address}" serviceClass="serviceClass">
        <jaxrs-client:headers>
            <entry key="Accept" value="application/json"></entry>
        </jaxrs-client:headers>
        <jaxrs-client:providers>
            <bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider">
            <property name="mapper" ref="jacksonMapper" />
        </bean>
        </jaxrs-client:providers>
</jaxrs-client:client>

How to copy selected files from Android with adb pull

As to the short script, the following runs on my Linux host

#!/bin/bash
HOST_DIR=<pull-to>
DEVICE_DIR=/sdcard/<pull-from>
EXTENSION="\.jpg"

while read MYFILE ; do
    adb pull "$DEVICE_DIR/$MYFILE" "$HOST_DIR/$MYFILE"
done < $(adb shell ls -1 "$DEVICE_DIR" | grep "$EXTENSION")

"ls minus one" lets "ls" show one file per line, and the quotation marks allow spaces in the filename.

Get line number while using grep

grep -n SEARCHTERM file1 file2 ...

How to diff one file to an arbitrary version in Git?

git diff master~20 -- pom.xml

Works if you are not in master branch too.

Python Traceback (most recent call last)

You are using Python 2 for which the input() function tries to evaluate the expression entered. Because you enter a string, Python treats it as a name and tries to evaluate it. If there is no variable defined with that name you will get a NameError exception.

To fix the problem, in Python 2, you can use raw_input(). This returns the string entered by the user and does not attempt to evaluate it.

Note that if you were using Python 3, input() behaves the same as raw_input() does in Python 2.

ng: command not found while creating new project using angular-cli

This works to update your angular/cli //*Global package (cmd as administrator)

npm uninstall -g @angular/cli
npm cache verify
npm install -g @angular/cli@latest

JAX-WS - Adding SOAP Headers

you can add the username and password to the SOAP Header

BindingProvider prov = (BindingProvider)port;
prov.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
                "your end point"));
Map<String, List<String>> headers = new HashMap<String, List<String>>();
prov.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "myusername");
prov.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "mypassword");
prov.getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, headers);

"Insert if not exists" statement in SQLite

If you have a table called memos that has two columns id and text you should be able to do like this:

INSERT INTO memos(id,text) 
SELECT 5, 'text to insert' 
WHERE NOT EXISTS(SELECT 1 FROM memos WHERE id = 5 AND text = 'text to insert');

If a record already contains a row where text is equal to 'text to insert' and id is equal to 5, then the insert operation will be ignored.

I don't know if this will work for your particular query, but perhaps it give you a hint on how to proceed.

I would advice that you instead design your table so that no duplicates are allowed as explained in @CLs answer below.

Truncate Two decimal places without rounding

If you don't worry too much about performance and your end result can be a string, the following approach will be resilient to floating precision issues:

string Truncate(double value, int precision)
{
    if (precision < 0)
    {
        throw new ArgumentOutOfRangeException("Precision cannot be less than zero");
    }

    string result = value.ToString();

    int dot = result.IndexOf('.');
    if (dot < 0)
    {
        return result;
    }

    int newLength = dot + precision + 1;

    if (newLength == dot + 1)
    {
        newLength--;
    }

    if (newLength > result.Length)
    {
        newLength = result.Length;
    }

    return result.Substring(0, newLength);
}

Function for Factorial in Python

def factorial(n):
    if n < 2:
        return 1
    return n * factorial(n - 1)

How to create a file in Android?

I decided to write a class from this thread that may be helpful to others. Note that this is currently intended to write in the "files" directory only (e.g. does not write to "sdcard" paths).

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import android.content.Context;

public class AndroidFileFunctions {

    public static String getFileValue(String fileName, Context context) {
        try {
            StringBuffer outStringBuf = new StringBuffer();
            String inputLine = "";
            /*
             * We have to use the openFileInput()-method the ActivityContext
             * provides. Again for security reasons with openFileInput(...)
             */
            FileInputStream fIn = context.openFileInput(fileName);
            InputStreamReader isr = new InputStreamReader(fIn);
            BufferedReader inBuff = new BufferedReader(isr);
            while ((inputLine = inBuff.readLine()) != null) {
                outStringBuf.append(inputLine);
                outStringBuf.append("\n");
            }
            inBuff.close();
            return outStringBuf.toString();
        } catch (IOException e) {
            return null;
        }
    }

    public static boolean appendFileValue(String fileName, String value,
            Context context) {
        return writeToFile(fileName, value, context, Context.MODE_APPEND);
    }

    public static boolean setFileValue(String fileName, String value,
            Context context) {
        return writeToFile(fileName, value, context,
                Context.MODE_WORLD_READABLE);
    }

    public static boolean writeToFile(String fileName, String value,
            Context context, int writeOrAppendMode) {
        // just make sure it's one of the modes we support
        if (writeOrAppendMode != Context.MODE_WORLD_READABLE
                && writeOrAppendMode != Context.MODE_WORLD_WRITEABLE
                && writeOrAppendMode != Context.MODE_APPEND) {
            return false;
        }
        try {
            /*
             * We have to use the openFileOutput()-method the ActivityContext
             * provides, to protect your file from others and This is done for
             * security-reasons. We chose MODE_WORLD_READABLE, because we have
             * nothing to hide in our file
             */
            FileOutputStream fOut = context.openFileOutput(fileName,
                    writeOrAppendMode);
            OutputStreamWriter osw = new OutputStreamWriter(fOut);
            // Write the string to the file
            osw.write(value);
            // save and close
            osw.flush();
            osw.close();
        } catch (IOException e) {
            return false;
        }
        return true;
    }

    public static void deleteFile(String fileName, Context context) {
        context.deleteFile(fileName);
    }
}

Spring transaction REQUIRED vs REQUIRES_NEW : Rollback Transaction

If you really need to do it in separate transaction you need to use REQUIRES_NEW and live with the performance overhead. Watch out for dead locks.

I'd rather do it the other way:

  • Validate data on Java side.
  • Run everyting in one transaction.
  • If anything goes wrong on DB side -> it's a major error of DB or validation design. Rollback everything and throw critical top level error.
  • Write good unit tests.

How to read GET data from a URL using JavaScript?

Please see this, more current solution before using a custom parsing function like below, or a 3rd party library.

The a code below works and is still useful in situations where URLSearchParams is not available, but it was written in a time when there was no native solution available in JavaScript. In modern browsers or Node.js, prefer to use the built-in functionality.


function parseURLParams(url) {
    var queryStart = url.indexOf("?") + 1,
        queryEnd   = url.indexOf("#") + 1 || url.length + 1,
        query = url.slice(queryStart, queryEnd - 1),
        pairs = query.replace(/\+/g, " ").split("&"),
        parms = {}, i, n, v, nv;

    if (query === url || query === "") return;

    for (i = 0; i < pairs.length; i++) {
        nv = pairs[i].split("=", 2);
        n = decodeURIComponent(nv[0]);
        v = decodeURIComponent(nv[1]);

        if (!parms.hasOwnProperty(n)) parms[n] = [];
        parms[n].push(nv.length === 2 ? v : null);
    }
    return parms;
}

Use as follows:

var urlString = "http://www.example.com/bar?a=a+a&b%20b=b&c=1&c=2&d#hash";
    urlParams = parseURLParams(urlString);

which returns a an object like this:

{
  "a"  : ["a a"],     /* param values are always returned as arrays */
  "b b": ["b"],       /* param names can have special chars as well */
  "c"  : ["1", "2"]   /* an URL param can occur multiple times!     */
  "d"  : [null]       /* parameters without values are set to null  */ 
} 

So

parseURLParams("www.mints.com?name=something")

gives

{name: ["something"]}

EDIT: The original version of this answer used a regex-based approach to URL-parsing. It used a shorter function, but the approach was flawed and I replaced it with a proper parser.

AngularJS : Initialize service with asynchronous data

Also, you can use the following techniques to provision your service globally, before actual controllers are executed: https://stackoverflow.com/a/27050497/1056679. Just resolve your data globally and then pass it to your service in run block for example.

Free Online Team Foundation Server

VSO is now Azure DevOps https://visualstudio.microsoft.com/vso

Recently Microsoft Visual Studio Online (VSO) is now Azure DevOps

Text file with 0D 0D 0A line breaks

Netscape ANSI encoded files use 0D 0D 0A for their line breaks.

'Must Override a Superclass Method' Errors after importing a project into Eclipse

Fixing must override a super class method error is not difficult, You just need to change Java source version to 1.6 because from Java 1.6 @Override annotation can be used along with interface method. In order to change source version to 1.6 follow below steps :

  1. Select Project , Right click , Properties
  2. Select Java Compiler and check the check box "Enable project specific settings"
  3. Now make Compiler compliance level to 1.6
  4. Apply changes

Can dplyr package be used for conditional mutating?

Use ifelse

df %>%
  mutate(g = ifelse(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4), 2,
               ifelse(a == 0 | a == 1 | a == 4 | a == 3 |  c == 4, 3, NA)))

Added - if_else: Note that in dplyr 0.5 there is an if_else function defined so an alternative would be to replace ifelse with if_else; however, note that since if_else is stricter than ifelse (both legs of the condition must have the same type) so the NA in that case would have to be replaced with NA_real_ .

df %>%
  mutate(g = if_else(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4), 2,
               if_else(a == 0 | a == 1 | a == 4 | a == 3 |  c == 4, 3, NA_real_)))

Added - case_when Since this question was posted dplyr has added case_when so another alternative would be:

df %>% mutate(g = case_when(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4) ~ 2,
                            a == 0 | a == 1 | a == 4 | a == 3 |  c == 4 ~ 3,
                            TRUE ~ NA_real_))

Added - arithmetic/na_if If the values are numeric and the conditions (except for the default value of NA at the end) are mutually exclusive, as is the case in the question, then we can use an arithmetic expression such that each term is multiplied by the desired result using na_if at the end to replace 0 with NA.

df %>%
  mutate(g = 2 * (a == 2 | a == 5 | a == 7 | (a == 1 & b == 4)) +
             3 * (a == 0 | a == 1 | a == 4 | a == 3 |  c == 4),
         g = na_if(g, 0))

Is there a GUI design app for the Tkinter / grid geometry?

You have VisualTkinter also known as Visual Python. Development seems not active. You have sourceforge and googlecode sites. Web site is here.

On the other hand, you have PAGE that seems active and works in python 2.7 and py3k

As you indicate on your comment, none of these use the grid geometry. As far as I can say the only GUI builder doing that could probably be Komodo Pro GUI Builder which was discontinued and made open source in ca. 2007. The code was located in the SpecTcl repository.

It seems to install fine on win7 although has not used it yet. This is an screenshot from my PC:

enter image description here

By the way, Rapyd Tk also had plans to implement grid geometry as in its documentation says it is not ready 'yet'. Unfortunately it seems 'nearly' abandoned.

How to auto import the necessary classes in Android Studio with shortcut?

Go to File -> Settings -> Editor -> Auto Import -> Java and make the below things:

Select Insert imports on paste value to All

Do tick mark on Add unambigious imports on the fly option and "Optimize imports on the fly*

Screenshot

Format a datetime into a string with milliseconds

In python 3.6 and above using python f-strings:

from datetime import datetime 

i = datetime.utcnow()

print(f"""{i:%Y-%m-%d %H:%M:%S}.{"{:03d}".format(i.microsecond // 1000)}""")

The code specific to format milliseconds is:

{"{:03d}".format(i.microsecond // 1000)}

The format string {:03d} and microsecond to millisecond conversion // 1000 is from def _format_time in https://github.com/python/cpython/blob/master/Lib/datetime.py that is used for datetime.datetime.isoformat().

Moving from JDK 1.7 to JDK 1.8 on Ubuntu

Just use these command lines:

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer

If needed, you can also follow this Ubuntu tutorial.

Changing directory in Google colab (breaking out of the python interpreter)

use

%cd SwitchFrequencyAnalysis

to change the current working directory for the notebook environment (and not just the subshell that runs your ! command).

you can confirm it worked with the pwd command like this:

!pwd

further information about jupyter / ipython magics: http://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-cd

What is "pass-through authentication" in IIS 7?

Normally, IIS would use the process identity (the user account it is running the worker process as) to access protected resources like file system or network.

With passthrough authentication, IIS will attempt to use the actual identity of the user when accessing protected resources.

If the user is not authenticated, IIS will use the application pool identity instead. If pool identity is set to NetworkService or LocalSystem, the actual Windows account used is the computer account.

The IIS warning you see is not an error, it's just a warning. The actual check will be performed at execution time, and if it fails, it'll show up in the log.

How to disable logging on the standard error stream in Python?

Using Context manager - [ most simple ]

import logging 

class DisableLogger():
    def __enter__(self):
       logging.disable(logging.CRITICAL)
    def __exit__(self, exit_type, exit_value, exit_traceback):
       logging.disable(logging.NOTSET)

Example of use:

with DisableLogger():
    do_something()

If you need a [more COMPLEX] fine-grained solution you can look at AdvancedLogger

AdvancedLogger can be used for fine grained logging temporary modifications

How it works:
Modifications will be enabled when context_manager/decorator starts working and be reverted after

Usage:
AdvancedLogger can be used
- as decorator `@AdvancedLogger()`
- as context manager `with  AdvancedLogger():`

It has three main functions/features:
- disable loggers and it's handlers by using disable_logger= argument
- enable/change loggers and it's handlers by using enable_logger= argument
- disable specific handlers for all loggers, by using  disable_handler= argument

All features they can be used together

Use cases for AdvancedLogger

# Disable specific logger handler, for example for stripe logger disable console
AdvancedLogger(disable_logger={"stripe": "console"})
AdvancedLogger(disable_logger={"stripe": ["console", "console2"]})

# Enable/Set loggers
# Set level for "stripe" logger to 50
AdvancedLogger(enable_logger={"stripe": 50})
AdvancedLogger(enable_logger={"stripe": {"level": 50, "propagate": True}})

# Adjust already registered handlers
AdvancedLogger(enable_logger={"stripe": {"handlers": "console"}

is it possible to add colors to python output?

If your console (like your standard ubuntu console) understands ANSI color codes, you can use those.

Here an example:

print ('This is \x1b[31mred\x1b[0m.') 

How to build and fill pandas dataframe from for loop?

Try this using list comprehension:

import pandas as pd

df = pd.DataFrame(
    [p, p.team, p.passing_att, p.passer_rating()] for p in game.players.passing()
)

How to find the logs on android studio?

On toolbar -> Help Menu -> Show log in explorer.

It opens log folder, where you can find all logs

PHP - Check if two arrays are equal

Short solution that works even with arrays which keys are given in different order:

public static function arrays_are_equal($array1, $array2)
{
    array_multisort($array1);
    array_multisort($array2);
    return ( serialize($array1) === serialize($array2) );
}

How to limit depth for recursive file list?

Make use of find's options

There is actually no exec of /bin/ls needed;

Find has an option that does just that:

find . -maxdepth 2 -type d -ls

To see only the one level of subdirectories you are interested in, add -mindepth to the same level as -maxdepth:

find . -mindepth 2 -maxdepth 2 -type d -ls

Use output formatting

When the details that get shown should be different, -printf can show any detail about a file in custom format; To show the symbolic permissions and the owner name of the file, use -printf with %M and %u in the format.

I noticed later you want the full ownership information, which includes the group. Use %g in the format for the symbolic name, or %G for the group id (like also %U for numeric user id)

find . -mindepth 2 -maxdepth 2 -type d -printf '%M %u %g %p\n'

This should give you just the details you need, for just the right files.

I will give an example that shows actually different values for user and group:

$ sudo find /tmp -mindepth 2 -maxdepth 2 -type d -printf '%M %u %g %p\n'
drwx------ www-data  www-data /tmp/user/33
drwx------ octopussy root     /tmp/user/126
drwx------ root      root     /tmp/user/0
drwx------ siegel    root     /tmp/user/1000
drwxrwxrwt root      root     /tmp/systemd-[...].service-HRUQmm/tmp

(Edited for readability: indented, shortened last line)


Notes on performance

Although the execution time is mostly irrelevant for this kind of command, increase in performance is large enough here to make it worth pointing it out:

Not only do we save creating a new process for each name - a huge task - the information does not even need to be read, as find already knows it.

Div width 100% minus fixed amount of pixels

The usual way to do it is as outlined by Guffa, nested elements. It's a bit sad having to add extra markup to get the hooks you need for this, but in practice a wrapper div here or there isn't going to hurt anyone.

If you must do it without extra elements (eg. when you don't have control of the page markup), you can use box-sizing, which has pretty decent but not complete or simple browser support. Likely more fun than having to rely on scripting though.

A cron job for rails: best practices?

Assuming your tasks don't take too long to complete, just create a new controller with an action for each task. Implement the logic of the task as controller code, Then set up a cronjob at the OS level that uses wget to invoke the URL of this controller and action at the appropriate time intervals. The advantages of this method are you:

  1. Have full access to all your Rails objects just as in a normal controller.
  2. Can develop and test just as you do normal actions.
  3. Can also invoke your tasks adhoc from a simple web page.
  4. Don't consume any more memory by firing up additional ruby/rails processes.

How to use IntelliJ IDEA to find all unused code?

In latest IntelliJ versions, you should run it from Analyze->Run Inspection By Name:

enter image description here

Than, pick Unused declaration:

enter image description here

And finally, uncheck the Include test sources:

enter image description here

How often does python flush to a file?

Here is another approach, up to the OP to choose which one he prefers.

When including the code below in the __init__.py file before any other code, messages printed with print and any errors will no longer be logged to Ableton's Log.txt but to separate files on your disk:

import sys

path = "/Users/#username#"

errorLog = open(path + "/stderr.txt", "w", 1)
errorLog.write("---Starting Error Log---\n")
sys.stderr = errorLog
stdoutLog = open(path + "/stdout.txt", "w", 1)
stdoutLog.write("---Starting Standard Out Log---\n")
sys.stdout = stdoutLog

(for Mac, change #username# to the name of your user folder. On Windows the path to your user folder will have a different format)

When you open the files in a text editor that refreshes its content when the file on disk is changed (example for Mac: TextEdit does not but TextWrangler does), you will see the logs being updated in real-time.

Credits: this code was copied mostly from the liveAPI control surface scripts by Nathan Ramella

Django model "doesn't declare an explicit app_label"

TL;DR: Adding a blank __init__.py fixed the issue for me.

I got this error in PyCharm and realised that my settings file was not being imported at all. There was no obvious error telling me this, but when I put some nonsense code into the settings.py, it didn't cause an error.

I had settings.py inside a local_settings folder. However, I'd fogotten to include a __init__.py in the same folder to allow it to be imported. Once I'd added this, the error went away.

What is the difference between an int and an Integer in Java and C#?

In java as per my knowledge if you learner then, when you write int a; then in java generic it will compile code like Integer a = new Integer(). So,as per generics Integer is not used but int is used. so there is so such difference there.

Allow only numeric value in textbox using Javascript

or

function isNumber(n){
  return (parseFloat(n) == n);
}

http://jsfiddle.net/Vj2Kk/2/

Execute a SQL Stored Procedure and process the results

My Stored Procedure Requires 2 Parameters and I needed my function to return a datatable here is 100% working code

Please make sure that your procedure return some rows

Public Shared Function Get_BillDetails(AccountNumber As String) As DataTable
    Try
        Connection.Connect()
        debug.print("Look up account number " & AccountNumber)
        Dim DP As New SqlDataAdapter("EXEC SP_GET_ACCOUNT_PAYABLES_GROUP  '" & AccountNumber & "' , '" & 08/28/2013 &"'", connection.Con)
        Dim DST As New DataSet
        DP.Fill(DST)
        Return DST.Tables(0)      
    Catch ex As Exception
        Return Nothing
    End Try
End Function

A more useful statusline in vim?

Some times less is more, do you really need to know the percentage through the file you are when coding? What about the type of file?

set statusline=%F%m%r%h%w\ 
set statusline+=%{fugitive#statusline()}\    
set statusline+=[%{strlen(&fenc)?&fenc:&enc}]
set statusline+=\ [line\ %l\/%L]          
set statusline+=%{rvm#statusline()}       

statusline

statusline

I also prefer minimal color as not to distract from the code.

Taken from: https://github.com/krisleech/vimfiles

Note: rvm#statusline is Ruby specific and fugitive#statusline is git specific.

How can I compile my Perl script so it can be executed on systems without perl installed?

Look at PAR (Perl Archiving Toolkit).

PAR is a Cross-Platform Packaging and Deployment tool, dubbed as a cross between Java's JAR and Perl2EXE/PerlApp.

jQuery UI DatePicker - Change Date Format

Try to use the

$( ".selector" ).datepicker({ dateFormat: 'dd/mm/yy' });  

and there is lots of option available For the datepicker you can find it Here

http://api.jqueryui.com/datepicker/

This is the way we call the datepicker with the parameter

$(function() {
      $('.selector').datepicker({
            dateFormat: 'dd/mm/yy',
            changeMonth: true,
            numberOfMonths: 1,
            buttonImage: 'contact/calendar/calendar.gif',
            buttonImageOnly: true,
            onSelect: function(selectedDate) {
                 // we can write code here 
             }
      });
});

Dockerfile copy keep subdirectory structure

Alternatively you can use a "." instead of *, as this will take all the files in the working directory, include the folders and subfolders:

FROM ubuntu
COPY . /
RUN ls -la /

How do you find all subclasses of a given class in Java?

You can use org.reflections library and then, create an object of Reflections class. Using this object, you can get list of all subclasses of given class. https://www.javadoc.io/doc/org.reflections/reflections/0.9.10/org/reflections/Reflections.html

    Reflections reflections = new Reflections("my.project.prefix");
    System.out.println(reflections.getSubTypesOf(A.class)));

Why does JPA have a @Transient annotation?

I will try to answer the question of "why". Imagine a situation where you have a huge database with a lot of columns in a table, and your project/system uses tools to generate entities from database. (Hibernate has those, etc...) Now, suppose that by your business logic you need a particular field NOT to be persisted. You have to "configure" your entity in a particular way. While Transient keyword works on an object - as it behaves within a java language, the @Transient only designed to answer the tasks that pertains only to persistence tasks.

Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function?

Use "mutable" when for things that are LOGICALLY stateless to the user (and thus should have "const" getters in the public class' APIs) but are NOT stateless in the underlying IMPLEMENTATION (the code in your .cpp).

The cases I use it most frequently are lazy initialization of state-less "plain old data" members. Namely, it is ideal in the narrow cases when such members are expensive to either build (processor) or carry around (memory) and many users of the object will never ask for them. In that situation you want lazy construction on the back end for performance, since 90% of the objects built will never need to build them at all, yet you still need to present the correct stateless API for public consumption.

How to detect READ_COMMITTED_SNAPSHOT is enabled?

SELECT is_read_committed_snapshot_on FROM sys.databases 
WHERE name= 'YourDatabase'

Return value:

  • 1: READ_COMMITTED_SNAPSHOT option is ON. Read operations under the READ COMMITTED isolation level are based on snapshot scans and do not acquire locks.
  • 0 (default): READ_COMMITTED_SNAPSHOT option is OFF. Read operations under the READ COMMITTED isolation level use Shared (S) locks.

docker cannot start on windows

1st start Powershell "as Administrator" that will also prevent the error you got from docker version.

The try to start the docker service: start-service docker If that fails delete the docker.pid file you will find with cd $env:programfiles\docker; rm docker.pid
Finally you should change HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualization\Containers\VSmbDisableOplocks to 0 or delete the value.

FAIL - Application at context path /Hello could not be started

I've had the same problem, was missing a slash in servlet url in web.xml

replace

<servlet-mapping>
    <servlet-name>jsonservice</servlet-name>
    <url-pattern>jsonservice</url-pattern>
</servlet-mapping>

with

<servlet-mapping>
    <servlet-name>jsonservice</servlet-name>
    <url-pattern>/jsonservice</url-pattern>
</servlet-mapping>

Animate element transform rotate

I stumbled upon this post, looking to use CSS transform in jQuery for an infinite loop animation. This one worked fine for me. I don't know how professional it is though.

function progressAnim(e) {
    var ang = 0;

    setInterval(function () {
        ang += 3;
        e.css({'transition': 'all 0.01s linear',
        'transform': 'rotate(' + ang + 'deg)'});
    }, 10);
}

Example of using:

var animated = $('#elem');
progressAnim(animated)

Best way to verify string is empty or null

With the openJDK 11 you can use the internal validation to check if the String is null or just white spaces

import jdk.internal.joptsimple.internal.Strings;
...

String targetString;
if (Strings.isNullOrEmpty(tragetString)) {}

"&" meaning after variable type

It means you're passing the variable by reference.

In fact, in a declaration of a type, it means reference, just like:

int x = 42;
int& y = x;

declares a reference to x, called y.

How to return a custom object from a Spring Data JPA GROUP BY query

I know this is an old question and it has already been answered, but here's another approach:

@Query("select new map(count(v) as cnt, v.answer) from Survey v group by v.answer")
public List<?> findSurveyCount();

Creating a config file in PHP

You can create a config class witch static properties

class Config 
{
    static $dbHost = 'localhost';
    static $dbUsername = 'user';
    static $dbPassword  = 'pass';
}

then you can simple use it:

Config::$dbHost  

Sometimes in my projects I use a design pattern SINGLETON to access configuration data. It's very comfortable in use.

Why?

For example you have 2 data source in your project. And you can choose witch of them is enabled.

  • mysql
  • json

Somewhere in config file you choose:

$dataSource = 'mysql' // or 'json'

When you change source whole app shoud switch to new data source, work fine and dont need change in code.

Example:

Config:

class Config 
{
  // ....
  static $dataSource = 'mysql';
  / .....
}

Singleton class:

class AppConfig
{
    private static $instance;
    private $dataSource;

    private function __construct()
    {
        $this->init();
    }

    private function init()
    {
        switch (Config::$dataSource)
        {
            case 'mysql':
                $this->dataSource = new StorageMysql();
                break;
            case 'json':
                $this->dataSource = new StorageJson();
                break;
            default:
                $this->dataSource = new StorageMysql();
        }
    }

    public static function getInstance()
    {
        if (empty(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function getDataSource()
    {
        return $this->dataSource;
    }
}

... and somewhere in your code (eg. in some service class):

$container->getItemsLoader(AppConfig::getInstance()->getDataSource()) // getItemsLoader need Object of specific data source class by dependency injection

We can obtain an AppConfig object from any place in the system and always get the same copy (thanks to static). The init () method of the class is called In the constructor, which guarantees only one execution. Init() body checks The value of the config $dataSource, and create new object of specific data source class. Now our script can get object and operate on it, not knowing even which specific implementation actually exists.

How to Avoid Response.End() "Thread was being aborted" Exception during the Excel file download

Looks to be the same question as:

When an ASP.NET System.Web.HttpResponse.End() is called, the current thread is aborted?

So it's by design. You need to add a catch for that exception and gracefully "ignore" it.

How to maximize the browser window in Selenium WebDriver (Selenium 2) using C#?

This is working fine for me.

Capybara.current_session.driver.browser.manage.window.resize_to(1800, 1000)

Find substring in the string in TWIG

Just searched for the docs, and found this:

Containment Operator: The in operator performs containment test. It returns true if the left operand is contained in the right:

{# returns true #}

{{ 1 in [1, 2, 3] }}

{{ 'cd' in 'abcde' }}

Parsing query strings on Android

For a servlet or a JSP page you can get querystring key/value pairs by using request.getParameter("paramname")

String name = request.getParameter("name");

There are other ways of doing it but that's the way I do it in all the servlets and jsp pages that I create.

Event for Handling the Focus of the EditText

  1. Declare object of EditText on top of class:

     EditText myEditText;
    
  2. Find EditText in onCreate Function and setOnFocusChangeListener of EditText:

    myEditText = findViewById(R.id.yourEditTextNameInxml); 
    
    myEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View view, boolean hasFocus) {
                    if (!hasFocus) {
                         Toast.makeText(this, "Focus Lose", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(this, "Get Focus", Toast.LENGTH_SHORT).show();
                    }
    
                }
            });
    

It works fine.

ERROR Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies

Might sound obvious but do you definitely have AjaxControlToolkit.dll in your bin?

How To Set A JS object property name from a variable

This is the way to dynamically set the value

var jsonVariable = {};
for (var i = 1; i < 3; i++) {
    var jsonKey = i + 'name';
    jsonVariable[jsonKey] = 'name' + i;
}

Twitter bootstrap scrollable modal

In case of using .modal {overflow-y: auto;}, would create additional scroll bar on the right of the page, when body is already overflowed.

The work around for this is to remove overflow from the body tag temporarily and set modal overflow-y to auto.

Example:

$('.myModalSelector').on('show.bs.modal', function () {

        // Store initial body overflow value
        _initial_body_overflow = $('body').css('overflow');

        // Let modal be scrollable
        $(this).css('overflow-y', 'auto');
        $('body').css('overflow', 'hidden');


    }).on('hide.bs.modal', function () {

        // Reverse previous initialization
        $(this).css('overflow-y', 'hidden');
        $('body').css('overflow', _initial_body_overflow);
});

Foreach in a Foreach in MVC View

You have:

foreach (var category in Model.Categories)

and then

@foreach (var product in Model)

Based on that view and model it seems that Model is of type Product if yes then the second foreach is not valid. Actually the first one could be the one that is invalid if you return a collection of Product.

UPDATE:

You are right, I am returning the model of type Product. Also, I do understand what is wrong now that you've pointed it out. How am I supposed to do what I'm trying to do then if I can't do it this way?

I'm surprised your code compiles when you said you are returning a model of Product type. Here's how you can do it:

@foreach (var category in Model)
{
    <h3><u>@category.Name</u></h3>

    <div>
        <ul>    
            @foreach (var product in category.Products)
            {
                <li>
                    put the rest of your code
                </li>
            }
        </ul>
    </div>
}

That suggest that instead of returning a Product, you return a collection of Category with Products. Something like this in EF:

// I am typing it here directly 
// so I'm not sure if this is the correct syntax.
// I assume you know how to do this,
// anyway this should give you an idea.
context.Categories.Include(o=>o.Product)

Simulate a specific CURL in PostMan

In addition to the answer
1. Open POSTMAN
2. Click on "import" tab on the upper left side.
3. Select the Raw Text option and paste your cURL command.
4. Hit import and you will have the command in your Postman builder!
5. If -u admin:admin are not imported, just go to the Authorization 
   tab, select Basic Auth -> enter the user name eg admin and password eg admin.
This will automatically generate Authorization header based on Base64 encoder

Spring 3 MVC resources and tag <mvc:resources />

Different order make it works :)

<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:annotation-driven />

.attr("disabled", "disabled") issue

$("#vp_code").textinput("enable");
$("#vp_code").textinput("disable");

you can try it

How to save CSS changes of Styles panel of Chrome Developer Tools?

FYI, If you're using inline styles or modifying the DOM directly (for instance adding an element), workspaces don't solve this problem. That's because the DOM is living in memory and there's not an actual file associated with the active state of the DOM.

For that, I like to take a "before" and "after" snapshot of the dom from the console: copy(document.getElementsByTagName('html')[0].outerHTML)

Then I place it in a diff tool to see my changes.

Diff tool image

Full article: https://medium.com/@theroccob/get-code-out-of-chrome-devtools-and-into-your-editor-defaf5651b4a

Why are only a few video games written in Java?

A large reason is that video games require direct knowledge of the hardware underneath, often times, and there really is no great implementation for many architectures. It's the knowledge of the underlying hardware architecture that allows developers to squeeze every ounce of performance out of a gaming system. Why would you take the time to port Java to a gaming platform, and then write a game on top of that port when you could just write the game?

edit: this is to say that it's more than a "speed" or "don't have the right libraries" issue. Those two things go hand-in-hand with this, but it's more a matter of "how do I make a system like the cell b.e. run my java code? there aren't really any good java compilers that can manage the pipelines and vectors like i need.."

How to disable a ts rule for a specific line?

@ts-expect-error

TS 3.9 introduces a new magic comment. @ts-expect-error will:

  • have same functionality as @ts-ignore
  • trigger an error, if actually no compiler error has been suppressed (= indicates useless flag)
if (false) {
  // @ts-expect-error: Let's ignore a single compiler error like this unreachable code 
  console.log("hello"); // compiles
}

// If @ts-expect-error didn't suppress anything at all, we now get a nice warning 
let flag = true;
// ...
if (flag) {
  // @ts-expect-error
  // ^~~~~~~~~~~~~~~^ error: "Unused '@ts-expect-error' directive.(2578)"
  console.log("hello"); 
}

Alternatives

@ts-ignore and @ts-expect-error can be used for all sorts of compiler errors. For type issues (like in OP), I recommend one of the following alternatives due to narrower error suppression scope:

? Use any type

// type assertion for single expression
delete ($ as any).summernote.options.keyMap.pc.TAB;

// new variable assignment for multiple usages
const $$: any = $
delete $$.summernote.options.keyMap.pc.TAB;
delete $$.summernote.options.keyMap.mac.TAB;

? Augment JQueryStatic interface

// ./global.d.ts
interface JQueryStatic {
  summernote: any;
}

// ./main.ts
delete $.summernote.options.keyMap.pc.TAB; // works

In other cases, shorthand module declarations or module augmentations for modules with no/extendable types are handy utilities. A viable strategy is also to keep not migrated code in .js and use --allowJs with checkJs: false.

SQL: parse the first, middle and last name from a fullname field

The biggest problem I ran into doing this was cases like "Bob R. Smith, Jr.". The algorithm I used is posted at http://www.blackbeltcoder.com/Articles/strings/splitting-a-name-into-first-and-last-names. My code is in C# but you could port it if you must have in SQL.

Convert SVG to image (JPEG, PNG, etc.) in the browser

I recently discovered a couple of image tracing libraries for JavaScript that indeed are able to build an acceptable approximation to the bitmap, both size and quality. I'm developing this JavaScript library and CLI :

https://www.npmjs.com/package/svg-png-converter

Which provides unified API for all of them, supporting browser and node, non depending on DOM, and a Command line tool.

For converting logos/cartoon/like images it does excellent job. For photos / realism some tweaking is needed since the output size can grow a lot.

It has a playground although right now I'm working on a better one, easier to use, since more features has been added:

https://cancerberosgx.github.io/demos/svg-png-converter/playground/#

Attribute 'nowrap' is considered outdated. A newer construct is recommended. What is it?

If HTML and use bootstrap they have a helper class.

<span class="text-nowrap">1-866-566-7233</span>

how to get the cookies from a php curl into a variable

If you use CURLOPT_COOKIE_FILE and CURLOPT_COOKIE_JAR curl will read/write the cookies from/to a file. You can, after curl is done with it, read and/or modify it however you want.

Convert datetime object to a String of date only in Python

It is possible to convert a datetime object into a string by working directly with the components of the datetime object.

from datetime import date  

myDate = date.today()    
#print(myDate) would output 2017-05-23 because that is today
#reassign the myDate variable to myDate = myDate.month 
#then you could print(myDate.month) and you would get 5 as an integer
dateStr = str(myDate.month)+ "/" + str(myDate.day) + "/" + str(myDate.year)    
# myDate.month is equal to 5 as an integer, i use str() to change it to a 
# string I add(+)the "/" so now I have "5/" then myDate.day is 23 as
# an integer i change it to a string with str() and it is added to the "5/"   
# to get "5/23" and then I add another "/" now we have "5/23/" next is the 
# year which is 2017 as an integer, I use the function str() to change it to 
# a string and add it to the rest of the string.  Now we have "5/23/2017" as 
# a string. The final line prints the string.

print(dateStr)  

Output --> 5/23/2017

Powershell Get-ChildItem most recent file in directory

Yes I think this would be quicker.

Get-ChildItem $folder | Sort-Object -Descending -Property LastWriteTime -Top 1 

Adding a line break in MySQL INSERT INTO text

INSERT INTO myTable VALUES("First line\r\nSecond line\r\nThird line");

When to use std::size_t?

Soon most computers will be 64-bit architectures with 64-bit OS:es running programs operating on containers of billions of elements. Then you must use size_t instead of int as loop index, otherwise your index will wrap around at the 2^32:th element, on both 32- and 64-bit systems.

Prepare for the future!

How to use java.net.URLConnection to fire and handle HTTP requests?

When working with HTTP it's almost always more useful to refer to HttpURLConnection rather than the base class URLConnection (since URLConnection is an abstract class when you ask for URLConnection.openConnection() on a HTTP URL that's what you'll get back anyway).

Then you can instead of relying on URLConnection#setDoOutput(true) to implicitly set the request method to POST instead do httpURLConnection.setRequestMethod("POST") which some might find more natural (and which also allows you to specify other request methods such as PUT, DELETE, ...).

It also provides useful HTTP constants so you can do:

int responseCode = httpURLConnection.getResponseCode();

if (responseCode == HttpURLConnection.HTTP_OK) {

How to do a JUnit assert on a message in a logger

What I have done if all I want to do is see that some string was logged (as opposed to verifying exact log statements which is just too brittle) is to redirect StdOut to a buffer, do a contains, then reset StdOut:

PrintStream original = System.out;
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
System.setOut(new PrintStream(buffer));

// Do something that logs

assertTrue(buffer.toString().contains(myMessage));
System.setOut(original);

UTC Date/Time String to Timezone

General purpose normalisation function to format any timestamp from any timezone to other. Very useful for storing datetimestamps of users from different timezones in a relational database. For database comparisons store timestamp as UTC and use with gmdate('Y-m-d H:i:s')

/**
 * Convert Datetime from any given olsonzone to other.
 * @return datetime in user specified format
 */

function datetimeconv($datetime, $from, $to)
{
    try {
        if ($from['localeFormat'] != 'Y-m-d H:i:s') {
            $datetime = DateTime::createFromFormat($from['localeFormat'], $datetime)->format('Y-m-d H:i:s');
        }
        $datetime = new DateTime($datetime, new DateTimeZone($from['olsonZone']));
        $datetime->setTimeZone(new DateTimeZone($to['olsonZone']));
        return $datetime->format($to['localeFormat']);
    } catch (\Exception $e) {
        return null;
    }
}

Usage:

$from = ['localeFormat' => "d/m/Y H:i A", 'olsonZone' => 'Asia/Calcutta'];

$to = ['localeFormat' => "Y-m-d H:i:s", 'olsonZone' => 'UTC'];

datetimeconv("14/05/1986 10:45 PM", $from, $to); // returns "1986-05-14 17:15:00"

Recording video feed from an IP camera over a network

Motion is an alternative to Zoneminder. It has a steeper setup curve as everything is configured via config files.However, the config files are nicely commented and it's easier than it sounds. It's very reliable once running as well.

To add a Foscam camera (mentioned above) use the following syntax to stream the video from the camera.

netcam_url http://<IPADDRESS>/videostream.cgi?user=admin?pwd=

Where the user is admin with a blank password (the default for Foscam cameras).

For really high uptime/reliablity consider using a monitoring tool such as Monit. This works well with Motion.

PostgreSQL CASE ... END with multiple conditions

This kind of code perhaps should work for You

SELECT
 *,
 CASE
  WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
  ELSE '00'
 END AS modifiedpvc
FROM my_table;


 gid | datepose | pvc | modifiedpvc 
-----+----------+-----+-------------
   1 |     1961 | 01  | 00
   2 |     1949 |     | 01
   3 |     1990 | 02  | 00
   1 |     1981 |     | 02
   1 |          | 03  | 00
   1 |          |     | 03
(6 rows)

C++ - How to append a char to char*?

char ch = 't';
char chArray[2];
sprintf(chArray, "%c", ch);
char chOutput[10]="tes";
strcat(chOutput, chArray);
cout<<chOutput;

OUTPUT:

test

How to set default value for form field in Symfony2?

A general solution for any case/approach, mainly by using a form without a class or when we need access to any services to set the default value:

// src/Form/Extension/DefaultFormTypeExtension.php

class DefaultFormTypeExtension extends AbstractTypeExtension
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        if (null !== $options['default']) {
            $builder->addEventListener(
                FormEvents::PRE_SET_DATA,
                function (FormEvent $event) use ($options) {
                    if (null === $event->getData()) {
                        $event->setData($options['default']);
                    }
                }
            );
        }
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefault('default', null);
    }

    public function getExtendedType()
    {
        return FormType::class;
    }
}

and register the form extension:

app.form_type_extension:
    class: App\Form\Extension\DefaultFormTypeExtension
    tags:
        - { name: form.type_extension, extended_type: Symfony\Component\Form\Extension\Core\Type\FormType }

After that, we can use default option in any form field:

$formBuilder->add('user', null, array('default' => $this->getUser()));
$formBuilder->add('foo', null, array('default' => 'bar'));

Create an empty object in JavaScript with {} or new Object()?

The object and array literal syntax {}/[] was introduced in JavaScript 1.2, so is not available (and will produce a syntax error) in versions of Netscape Navigator prior to 4.0.

My fingers still default to saying new Array(), but I am a very old man. Thankfully Netscape 3 is not a browser many people ever have to consider today...

Postgres and Indexes on Foreign Keys and Primary Keys

Yes - for primary keys, no - for foreign keys (more in the docs).

\d <table_name>

in "psql" shows a description of a table including all its indexes.

How to handle change text of span

Span does not have 'change' event by default. But you can add this event manually.

Listen to the change event of span.

$("#span1").on('change',function(){
     //Do calculation and change value of other span2,span3 here
     $("#span2").text('calculated value');
});

And wherever you change the text in span1. Trigger the change event manually.

$("#span1").text('test').trigger('change'); 

SQL Server, How to set auto increment after creating a table without data loss?

Below script can be a good solution.Worked in large data as well.

ALTER DATABASE WMlive SET RECOVERY SIMPLE WITH NO_WAIT

ALTER TABLE WMBOMTABLE DROP CONSTRAINT PK_WMBomTable

ALTER TABLE WMBOMTABLE drop column BOMID

ALTER TABLE WMBOMTABLE ADD BomID int IDENTITY(1, 1) NOT NULL;

ALTER TABLE WMBOMTABLE ADD CONSTRAINT PK_WMBomTable PRIMARY KEY CLUSTERED (BomID);

ALTER DATABASE WMlive SET RECOVERY FULL WITH NO_WAIT

Postgres FOR LOOP

Below is example you can use:

create temp table test2 (
  id1  numeric,
  id2  numeric,
  id3  numeric,
  id4  numeric,
  id5  numeric,
  id6  numeric,
  id7  numeric,
  id8  numeric,
  id9  numeric,
  id10 numeric) 
with (oids = false);

do
$do$
declare
     i int;
begin
for  i in 1..100000
loop
    insert into test2  values (random(), i * random(), i / random(), i + random(), i * random(), i / random(), i + random(), i * random(), i / random(), i + random());
end loop;
end;
$do$;

Convert datetime value into string

Use DATE_FORMAT()

SELECT
  DATE_FORMAT(NOW(), '%d %m %Y') AS your_date;

Remove all items from a FormArray in Angular

You can easily define a getter for your array and clear it as follows:

  formGroup: FormGroup    
  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.formGroup = this.fb.group({
      sliders: this.fb.array([])
    })
  }
  get sliderForms() {
    return this.formGroup.get('sliders') as FormArray
  }

  clearAll() {
    this.formGroup.reset()
    this.sliderForms.clear()
  }

Update React component every second

The following code is a modified example from React.js website.

Original code is available here: https://reactjs.org/#a-simple-component

class Timer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      seconds: parseInt(props.startTimeInSeconds, 10) || 0
    };
  }

  tick() {
    this.setState(state => ({
      seconds: state.seconds + 1
    }));
  }

  componentDidMount() {
    this.interval = setInterval(() => this.tick(), 1000);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  formatTime(secs) {
    let hours   = Math.floor(secs / 3600);
    let minutes = Math.floor(secs / 60) % 60;
    let seconds = secs % 60;
    return [hours, minutes, seconds]
        .map(v => ('' + v).padStart(2, '0'))
        .filter((v,i) => v !== '00' || i > 0)
        .join(':');
  }

  render() {
    return (
      <div>
        Timer: {this.formatTime(this.state.seconds)}
      </div>
    );
  }
}

ReactDOM.render(
  <Timer startTimeInSeconds="300" />,
  document.getElementById('timer-example')
);

How do I conditionally add attributes to React components?

This should work, since your state will change after the Ajax call, and the parent component will re-render.

render : function () {
    var item;
    if (this.state.isRequired) {
        item = <MyOwnInput attribute={'whatever'} />
    } else {
        item = <MyOwnInput />
    }
    return (
        <div>
            {item}
        </div>
    );
}

Clearing localStorage in javascript?

localStorage.clear();

or

window.localStorage.clear();

to clear particular item

window.localStorage.removeItem("item_name");

To remove particular value by id :

var item_detail = JSON.parse(localStorage.getItem("key_name")) || [];           
            $.each(item_detail, function(index, obj){
                if (key_id == data('key')) {
                    item_detail.splice(index,1);
                    localStorage["key_name"] = JSON.stringify(item_detail);
                    return false;
                }
            });

How can I submit form on button click when using preventDefault()?

You need to use

$(this).parents('form').submit()

Returning IEnumerable<T> vs. IQueryable<T>

I recently ran into an issue with IEnumerable v. IQueryable. The algorithm being used first performed an IQueryable query to obtain a set of results. These were then passed to a foreach loop, with the items instantiated as an Entity Framework (EF) class. This EF class was then used in the from clause of a Linq to Entity query, causing the result to be IEnumerable.

I'm fairly new to EF and Linq for Entities, so it took a while to figure out what the bottleneck was. Using MiniProfiling, I found the query and then converted all of the individual operations to a single IQueryable Linq for Entities query. The IEnumerable took 15 seconds and the IQueryable took 0.5 seconds to execute. There were three tables involved and, after reading this, I believe that the IEnumerable query was actually forming a three table cross-product and filtering the results.

Try to use IQueryables as a rule-of-thumb and profile your work to make your changes measurable.

set option "selected" attribute from dynamic created option

To set the input option at run time try setting the 'checked' value. (even if it isn't a checkbox)

elem.checked=true;

Where elem is a reference to the option to be selected.

So for the above issue:

var country = document.getElementById("country");
country.options[country.options.selectedIndex].checked=true;

This works for me, even when the options are not wrapped in a .

If all of the tags share the same name, they should uncheck when the new one is checked.

Bootstrap css hides portion of container below navbar navbar-fixed-top

i solved it using jquery

_x000D_
_x000D_
<script type="text/javascript">_x000D_
$(document).ready(function(e) {_x000D_
   var h = $('nav').height() + 20;_x000D_
   $('body').animate({ paddingTop: h });_x000D_
});_x000D_
</script>
_x000D_
_x000D_
_x000D_

How to leave a message for a github.com user

Although GitHub removed the private messaging feature, there's still an alternative.

GitHub host git repositories. If the user you're willing to communicate with has ever committed some code, there are good chances you may reach your goal. Indeed, within each commit is stored some information about the author of the change or the one who accepted it.

Provided you're really dying to exchange with user user_test

  • Display the public activity page of the user: https://github.com/user_test?tab=activity
  • Search for an event stating "user_test pushed to [branch] at [repository]". There are usually good chances, they may have pushed one of his own commits. Ensure this is the case by clicking on the "View comparison..." link and make sure the user is listed as one of the committers.
  • Clone on your local machine the repository they pushed to: git clone https://github.com/..../repository.git
  • Checkout the branch they pushed to: git checkout [branch]
  • Display the latest commits: git log -50

As a committer/author, an email should be displayed along with the commit data.

Note: Every warning related to unsolicited email should apply there. Do not spam.

Removing empty lines in Notepad++

There is now a built-in way to do this as of version 6.5.2

Edit -> Line Operations -> Remove Empty Lines or Remove Empty Lines (Containing Blank characters)

Screenshot of removing empty lines

How to return a specific status code and no contents from Controller?

this.HttpContext.Response.StatusCode = 418; // I'm a teapot

How to end the request?

Try other solution, just:

return StatusCode(418);


You could use StatusCode(???) to return any HTTP status code.


Also, you can use dedicated results:

Success:

  • return Ok() ? Http status code 200
  • return Created() ? Http status code 201
  • return NoContent(); ? Http status code 204

Client Error:

  • return BadRequest(); ? Http status code 400
  • return Unauthorized(); ? Http status code 401
  • return NotFound(); ? Http status code 404


More details:

How to reset form body in bootstrap modal box?

If you using ajax to load modal's body such way and want to be able to reload it's content

<a data-toggle="modal" data-target="#myModal" href="./add">Add</a>
<a data-toggle="modal" data-target="#myModal" href="./edit/id">Modify</a>

<div id="myModal" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <!-- Content will be loaded here -->
        </div>
    </div>
</div>

use

<script>
    $(function() {
        $('.modal').on('hidden.bs.modal', function(){
            $(this).removeData('bs.modal');
        });
    });
</script>

How to pass a datetime parameter?

I feel your pain ... yet another date time format... just what you needed!

Using Web Api 2 you can use route attributes to specify parameters.

so with attributes on your class and your method you can code up a REST URL using this utc format you are having trouble with (apparently its ISO8601, presumably arrived at using startDate.toISOString())

[Route(@"daterange/{startDate:regex(^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z$)}/{endDate:regex(^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z$)}")]
    [HttpGet]
    public IEnumerable<MyRecordType> GetByDateRange(DateTime startDate, DateTime endDate)

.... BUT, although this works with one date (startDate), for some reason it doesnt work when the endDate is in this format ... debugged for hours, only clue is exception says it doesnt like colon ":" (even though web.config is set with :

<system.web>
    <compilation debug="true" targetFramework="4.5.1" />
    <httpRuntime targetFramework="4.5.1" requestPathInvalidCharacters="" />
</system.web>

So, lets make another date format (taken from the polyfill for the ISO date format) and add it to the Javascript date (for brevity, only convert up to minutes):

if (!Date.prototype.toUTCDateTimeDigits) {
    (function () {

        function pad(number) {
            if (number < 10) {
                return '0' + number;
            }
            return number;
        }

        Date.prototype.toUTCDateTimeDigits = function () {
            return this.getUTCFullYear() +
              pad(this.getUTCMonth() + 1) +
              pad(this.getUTCDate()) +
              'T' +
              pad(this.getUTCHours()) +
              pad(this.getUTCMinutes()) +
              'Z';
        };

    }());
}

Then when you send the dates to the Web API 2 method, you can convert them from string to date:

[RoutePrefix("api/myrecordtype")]
public class MyRecordTypeController : ApiController
{


    [Route(@"daterange/{startDateString}/{endDateString}")]
    [HttpGet]
    public IEnumerable<MyRecordType> GetByDateRange([FromUri]string startDateString, [FromUri]string endDateString)
    {
        var startDate = BuildDateTimeFromYAFormat(startDateString);
        var endDate = BuildDateTimeFromYAFormat(endDateString);
    ...
    }

    /// <summary>
    /// Convert a UTC Date String of format yyyyMMddThhmmZ into a Local Date
    /// </summary>
    /// <param name="dateString"></param>
    /// <returns></returns>
    private DateTime BuildDateTimeFromYAFormat(string dateString)
    {
        Regex r = new Regex(@"^\d{4}\d{2}\d{2}T\d{2}\d{2}Z$");
        if (!r.IsMatch(dateString))
        {
            throw new FormatException(
                string.Format("{0} is not the correct format. Should be yyyyMMddThhmmZ", dateString)); 
        }

        DateTime dt = DateTime.ParseExact(dateString, "yyyyMMddThhmmZ", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);

        return dt;
    }

so the url would be

http://domain/api/myrecordtype/daterange/20140302T0003Z/20140302T1603Z

Hanselman gives some related info here:

http://www.hanselman.com/blog/OnTheNightmareThatIsJSONDatesPlusJSONNETAndASPNETWebAPI.aspx

Removing viewcontrollers from navigation stack

Swift 5:

navigationController?.viewControllers.removeAll(where: { (vc) -> Bool in
    if vc.isKind(of: MyViewController.self) || vc.isKind(of: MyViewController2.self) {
        return false
    } else {
        return true
    }
})

Rails 4 Authenticity Token

These features were added for security and forgery protection purposes.
However, to answer your question, here are some inputs. You can add these lines after your the controller name.

Like so,

class NameController < ApplicationController
    skip_before_action :verify_authenticity_token

Here are some lines for different versions of rails.

Rails 3

skip_before_filter :verify_authenticity_token

Rails 4:

skip_before_action :verify_authenticity_token


Should you intend to disable this security feature for all controller routines, you can change the value of protect_from_forgery to :null_session on your application_controller.rb file.

Like so,

class ApplicationController < ActionController::Base
  protect_from_forgery with: :null_session
end

C pointers and arrays: [Warning] assignment makes pointer from integer without a cast

What are you doing: (I am using bytes instead of in for better reading)

You start with int *ap and so on, so your (your computers) memory looks like this:

-------------- memory used by some one else --------
000: ?
001: ?
...
098: ?
099: ?
-------------- your memory  --------
100: something          <- here is *ap
101: 41                 <- here starts a[] 
102: 42
103: 43
104: 44
105: 45
106: something          <- here waits x

lets take a look waht happens when (print short cut for ...print("$d", ...)

print a[0]  -> 41   //no surprise
print a     -> 101  // because a points to the start of the array
print *a    -> 41   // again the first element of array
print a+1   -> guess? 102
print *(a+1)    -> whats behind 102? 42 (we all love this number)

and so on, so a[0] is the same as *a, a[1] = *(a+1), ....

a[n] just reads easier.

now, what happens at line 9?

ap=a[4] // we know a[4]=*(a+4) somehow *105 ==>  45 
// warning! converting int to pointer!
-------------- your memory  --------
100: 45         <- here is *ap now 45

x = *ap;   // wow ap is 45 -> where is 45 pointing to?
-------------- memory used by some one else --------
bang!      // dont touch neighbours garden

So the "warning" is not just a warning it's a severe error.

Fill remaining vertical space with CSS using display:flex

The example below includes scrolling behaviour if the content of the expanded centre component extends past its bounds. Also the centre component takes 100% of remaining space in the viewport.

jsfiddle here

html, body, .r_flex_container{
    height: 100%;
    display: flex;
    flex-direction: column;
    background: red;
    margin: 0;
}
.r_flex_container {
    display:flex;
    flex-flow: column nowrap;
    background-color:blue;
}

.r_flex_fixed_child {
    flex:none;
    background-color:black;
    color:white;

}
.r_flex_expand_child {
    flex:auto;
    background-color:yellow;
    overflow-y:scroll;
}

Example of html that can be used to demonstrate this behaviour

<html>
<body>
    <div class="r_flex_container">
      <div class="r_flex_fixed_child">
        <p> This is the fixed 'header' child of the flex container </p>
      </div>
      <div class="r_flex_expand_child">
            <article>this child container expands to use all of the space given to it -  but could be shared with other expanding childs in which case they would get equal space after the fixed container space is allocated. 
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc,
            </article>
      </div>
      <div class="r_flex_fixed_child">
        this is the fixed footer child of the flex container
        asdfadsf
        <p> another line</p>
      </div>

    </div>
</body>
</html>

Applying function with multiple arguments to create a new pandas column

One more dict style clean syntax:

df["new_column"] = df.apply(lambda x: x["A"] * x["B"], axis = 1)

or,

df["new_column"] = df["A"] * df["B"]

How to use MySQL dump from a remote machine

This topic shows up on the first page of my google result, so here's a little useful tip for new comers.

You could also dump the sql and gzip it in one line:

mysqldump -u [username] -p[password] [database_name] | gzip > [filename.sql.gz]

Can a div have multiple classes (Twitter Bootstrap)

A div can can hold more than one classes either using bootstrap or not

<div class="active dropdown-toggle my-class">Multiple Classes</div>
For applying multiple classes just separate the classes by space.

Take a look at this links you will find many examples
http://getbootstrap.com/css/
http://css-tricks.com/un-bloat-css-by-using-multiple-classes/

Different CURRENT_TIMESTAMP and SYSDATE in oracle

CURRENT_DATE and CURRENT_TIMESTAMP return the current date and time in the session time zone.

SYSDATE and SYSTIMESTAMP return the system date and time - that is, of the system on which the database resides.

If your client session isn't in the same timezone as the server the database is on (or says it isn't anyway, via your NLS settings), mixing the SYS* and CURRENT_* functions will return different values. They are all correct, they just represent different things. It looks like your server is (or thinks it is) in a +4:00 timezone, while your client session is in a +4:30 timezone.

You might also see small differences in the time if the clocks aren't synchronised, which doesn't seem to be an issue here.

Cross origin requests are only supported for HTTP but it's not cross-domain

If you’re working on a little front-end project and want to test it locally, you’d typically open it by pointing your local directory in the web browser, for instance entering file:///home/erick/mysuperproject/index.html in your URL bar. However, if your site is trying to load resources, even if they’re placed in your local directory, you might see warnings like this:

XMLHttpRequest cannot load file:///home/erick/mysuperproject/mylibrary.js. Cross origin requests are only supported for HTTP.

Chrome and other modern browsers have implemented security restrictions for Cross Origin Requests, which means that you cannot load anything through file:/// , you need to use http:// protocol at all times, even locally -due Same Origin policies. Simple as that, you’d need to mount a webserver to run your project there.

This is not the end of the world and there are many solutions out there, including the good old Apache (with VirtualHosts if you’re running several other projects), node.js with express, a Ruby server, etc. or simply modifying your browser settings.

However there’s a simpler and lightweight solution for the lazy ones. You can use Python’s SimpleHTTPServer. It comes already bundled with python so you don’t need to install or configure anything at all!

So cd to your project directory, for instance

1 cd /home/erick/mysuperproject and then simply use

1 python -m SimpleHTTPServer And that’s it, you’ll see this message in your terminal

1 Serving HTTP on 0.0.0.0 port 8000 ... So now you can go back to your browser and visit http://0.0.0.0:8000 with all your directory files served there. You can configure the port and other things, just see the documentation. But this simply trick works for me when I’m in a rush to test a new library or work out a new idea.

There you go, happy coding!

EDIT: In Python 3+, SimpleHTTPServer has been replaced with http.server. So In Python 3.3, for example, the following command is equivalent:

python -m http.server 8000

Error 1046 No database Selected, how to resolve?

I faced the same error when I tried to import a database created from before. Here is what I did to fix this issue:

1- Create new database

2- Use it by use command

enter image description here

3- Try again

This works for me.

when I try to open an HTML file through `http://localhost/xampp/htdocs/index.html` it says unable to connect to localhost

You should simply create your own folder in htdocs and save your .html and .php files in it. An example is create a folder called myNewFolder directly in htdocs. Don't put it in index.html. Then save all your.html and .php files in it like this-> "localhost/myNewFolder/myFilename.html" or "localhost/myNewFolder/myFilename.php" I hope this helps.

how to resolve DTS_E_OLEDBERROR. in ssis

I had this same problem and it seemed to be related to using the same database connection for concurrent tasks. There might be some alternative solutions (maybe better), but I solved it by setting MaxConcurrentExecutables to 1.

What is event bubbling and capturing?

Event bubbling and capturing are two ways of event propagation in the HTML DOM API, when an event occurs in an element inside another element, and both elements have registered a handle for that event. The event propagation mode determines in which order the elements receive the event.

With bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements.

With capturing, the event is first captured by the outermost element and propagated to the inner elements.

Capturing is also called "trickling", which helps remember the propagation order:

trickle down, bubble up

Back in the old days, Netscape advocated event capturing, while Microsoft promoted event bubbling. Both are part of the W3C Document Object Model Events standard (2000).

IE < 9 uses only event bubbling, whereas IE9+ and all major browsers support both. On the other hand, the performance of event bubbling may be slightly lower for complex DOMs.

We can use the addEventListener(type, listener, useCapture) to register event handlers for in either bubbling (default) or capturing mode. To use the capturing model pass the third argument as true.

Example

<div>
    <ul>
        <li></li>
    </ul>
</div>

In the structure above, assume that a click event occurred in the li element.

In capturing model, the event will be handled by the div first (click event handlers in the div will fire first), then in the ul, then at the last in the target element, li.

In the bubbling model, the opposite will happen: the event will be first handled by the li, then by the ul, and at last by the div element.

For more information, see

In the example below, if you click on any of the highlighted elements, you can see that the capturing phase of the event propagation flow occurs first, followed by the bubbling phase.

_x000D_
_x000D_
var logElement = document.getElementById('log');_x000D_
_x000D_
function log(msg) {_x000D_
    logElement.innerHTML += ('<p>' + msg + '</p>');_x000D_
}_x000D_
_x000D_
function capture() {_x000D_
    log('capture: ' + this.firstChild.nodeValue.trim());_x000D_
}_x000D_
_x000D_
function bubble() {_x000D_
    log('bubble: ' + this.firstChild.nodeValue.trim());_x000D_
}_x000D_
_x000D_
function clearOutput() {_x000D_
    logElement.innerHTML = "";_x000D_
}_x000D_
_x000D_
var divs = document.getElementsByTagName('div');_x000D_
for (var i = 0; i < divs.length; i++) {_x000D_
    divs[i].addEventListener('click', capture, true);_x000D_
    divs[i].addEventListener('click', bubble, false);_x000D_
}_x000D_
var clearButton = document.getElementById('clear');_x000D_
clearButton.addEventListener('click', clearOutput);
_x000D_
p {_x000D_
    line-height: 0;_x000D_
}_x000D_
_x000D_
div {_x000D_
    display:inline-block;_x000D_
    padding: 5px;_x000D_
_x000D_
    background: #fff;_x000D_
    border: 1px solid #aaa;_x000D_
    cursor: pointer;_x000D_
}_x000D_
_x000D_
div:hover {_x000D_
    border: 1px solid #faa;_x000D_
    background: #fdd;_x000D_
}
_x000D_
<div>1_x000D_
    <div>2_x000D_
        <div>3_x000D_
            <div>4_x000D_
                <div>5</div>_x000D_
            </div>_x000D_
        </div>_x000D_
    </div>_x000D_
</div>_x000D_
<button id="clear">clear output</button>_x000D_
<section id="log"></section>
_x000D_
_x000D_
_x000D_

Another example at JSFiddle.

File Explorer in Android Studio

If anyone is looking for the Android Studio (2.3.1) on Mac OSX (10.12.1) answer then here are the steps for it.

  1. Tools Menu > Android > Android Device Monitor

  2. Choose Your Device (at Left) > Click on File Explorer Tab (at Right)

Hope this helps.

How to tell which disk Windows Used to Boot

Try HKEY_LOCAL_MACHINE\SYSTEM\Setup\SystemPartition

Angular 4: How to include Bootstrap?

Watch Video or Follow the step

Install bootstrap 4 in angular 2 / angular 4 / angular 5 / angular 6

There is three way to include bootstrap in your project
1) Add CDN Link in index.html file
2) Install bootstrap using npm and set path in angular.json Recommended
3) Install bootstrap using npm and set path in index.html file

I recommended you following 2 methods that are installed bootstrap using npm because its installed in your project directory and you can easily access it

Method 1

Add Bootstrap, Jquery and popper.js CDN path to you angular project index.html file

Bootstrap.css
https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
Bootstrap.js
https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
Jquery.js
https://code.jquery.com/jquery-3.2.1.slim.min.js
Popper.js
https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js

Method 2

1) Install bootstrap using npm

npm install bootstrap --save

after the installation of Bootstrap 4, we Need two More javascript Package that is Jquery and Popper.js without these two package bootstrap is not complete because Bootstrap 4 is using Jquery and popper.js package so we have to install as well

2) Install JQUERY

npm install jquery --save

3) Install Popper.js

npm install popper.js --save

Now Bootstrap is Install on you Project Directory inside node_modules Folder

open angular.json this file are available on you angular directory open that file and add the path of bootstrap, jquery, and popper.js files inside styles[] and scripts[] path see the below example

"styles": [   
    "node_modules/bootstrap/dist/css/bootstrap.min.css",
    "styles.css"
  ],
  "scripts": [  
    "node_modules/jquery/dist/jquery.min.js",
    "node_modules/popper.js/dist/umd/popper.min.js",
    "node_modules/bootstrap/dist/js/bootstrap.min.js"
  ],

Note: Don't change a sequence of js file it should be like this

Method 3

Install bootstrap using npm follow Method 2 in method 3 we just set path inside index.html file instead of angular.json file

bootstrap.css

    <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css",
        "styles.css">

Jquery.js

<script src="node_modules/jquery/dist/jquery.min.js"><br>

Bootstrap.js

<script src="node_modules/bootstrap/dist/js/bootstrap.min.js"><br>

Popper.js

<script src="node_modules/popper.js/dist/umd/popper.min.js"><br>

Now Bootstrap Working fine Now

How to create windows service from java jar?

Tanuki changed license of jsw some time ago, if I was to begin a project, I would use Yet Another Java Service Wrapper, http://yajsw.sourceforge.net/ that is more or less an open source implementation that mimics JWS, and then builds on it and improves it even further.

EDIT: I have been using YAJSW for several years on several platorms (Windows, several linuxes...) and it is great, development is ongoing.

Simplest SOAP example

This is the simplest JavaScript SOAP Client I can create.

<html>
<head>
    <title>SOAP JavaScript Client Test</title>
    <script type="text/javascript">
        function soap() {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.open('POST', 'https://somesoapurl.com/', true);

            // build SOAP request
            var sr =
                '<?xml version="1.0" encoding="utf-8"?>' +
                '<soapenv:Envelope ' + 
                    'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
                    'xmlns:api="http://127.0.0.1/Integrics/Enswitch/API" ' +
                    'xmlns:xsd="http://www.w3.org/2001/XMLSchema" ' +
                    'xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">' +
                    '<soapenv:Body>' +
                        '<api:some_api_call soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' +
                            '<username xsi:type="xsd:string">login_username</username>' +
                            '<password xsi:type="xsd:string">password</password>' +
                        '</api:some_api_call>' +
                    '</soapenv:Body>' +
                '</soapenv:Envelope>';

            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4) {
                    if (xmlhttp.status == 200) {
                        alert(xmlhttp.responseText);
                        // alert('done. use firebug/console to see network response');
                    }
                }
            }
            // Send the POST request
            xmlhttp.setRequestHeader('Content-Type', 'text/xml');
            xmlhttp.send(sr);
            // send request
            // ...
        }
    </script>
</head>
<body>
    <form name="Demo" action="" method="post">
        <div>
            <input type="button" value="Soap" onclick="soap();" />
        </div>
    </form>
</body>
</html> <!-- typo -->

How to update column value in laravel

You may try this:

Page::where('id', $id)->update(array('image' => 'asdasd'));

There are other ways too but no need to use Page::find($id); in this case. But if you use find() then you may try it like this:

$page = Page::find($id);

// Make sure you've got the Page model
if($page) {
    $page->image = 'imagepath';
    $page->save();
}

Also you may use:

$page = Page::findOrFail($id);

So, it'll throw an exception if the model with that id was not found.

How to get an element's top position relative to the browser's viewport?

Edit: Add some code to account for the page scrolling.

function findPos(id) {
    var node = document.getElementById(id);     
    var curtop = 0;
    var curtopscroll = 0;
    if (node.offsetParent) {
        do {
            curtop += node.offsetTop;
            curtopscroll += node.offsetParent ? node.offsetParent.scrollTop : 0;
        } while (node = node.offsetParent);

        alert(curtop - curtopscroll);
    }
}

The id argument is the id of the element whose offset you want. Adapted from a quirksmode post.

How to link external javascript file onclick of button

I have to agree with the comments above, that you can't call a file, but you could load a JS file like this, I'm unsure if it answers your question but it may help... oh and I've used a link instead of a button in my example...

<a href='linkhref.html' id='mylink'>click me</a>

<script type="text/javascript">

var myLink = document.getElementById('mylink');

myLink.onclick = function(){

    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "Public/Scripts/filename.js."; 
    document.getElementsByTagName("head")[0].appendChild(script);
    return false;

}


</script>

Firebase Storage How to store and Retrieve images

I ended up storing the images in base64 format myself. I translate them from their base64 value when called back from firebase.

Copy a file from one folder to another using vbscripting

Try this. It will check to see if the file already exists in the destination folder, and if it does will check if the file is read-only. If the file is read-only it will change it to read-write, replace the file, and make it read-only again.

Const DestinationFile = "c:\destfolder\anyfile.txt"
Const SourceFile = "c:\sourcefolder\anyfile.txt"

Set fso = CreateObject("Scripting.FileSystemObject")
    'Check to see if the file already exists in the destination folder
    If fso.FileExists(DestinationFile) Then
        'Check to see if the file is read-only
        If Not fso.GetFile(DestinationFile).Attributes And 1 Then 
            'The file exists and is not read-only.  Safe to replace the file.
            fso.CopyFile SourceFile, "C:\destfolder\", True
        Else 
            'The file exists and is read-only.
            'Remove the read-only attribute
            fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes - 1
            'Replace the file
            fso.CopyFile SourceFile, "C:\destfolder\", True
            'Reapply the read-only attribute
            fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes + 1
        End If
    Else
        'The file does not exist in the destination folder.  Safe to copy file to this folder.
        fso.CopyFile SourceFile, "C:\destfolder\", True
    End If
Set fso = Nothing

Using cURL with a username and password?

curl -X GET -u username:password  {{ http://www.example.com/filename.txt }} -O

Python: How to get stdout after running os.system?

If all you need is the stdout output, then take a look at subprocess.check_output():

import subprocess

batcmd="dir"
result = subprocess.check_output(batcmd, shell=True)

Because you were using os.system(), you'd have to set shell=True to get the same behaviour. You do want to heed the security concerns about passing untrusted arguments to your shell.

If you need to capture stderr as well, simply add stderr=subprocess.STDOUT to the call:

result = subprocess.check_output([batcmd], stderr=subprocess.STDOUT)

to redirect the error output to the default output stream.

If you know that the output is text, add text=True to decode the returned bytes value with the platform default encoding; use encoding="..." instead if that codec is not correct for the data you receive.

How could I convert data from string to long in c#

long is internally represented as System.Int64 which is a 64-bit signed integer. The value you have taken "1100.25" is actually decimal and not integer hence it can not be converted to long.

You can use:

String strValue = "1100.25";
decimal lValue = Convert.ToDecimal(strValue);

to convert it to decimal value

Cast IList to List

List<SubProduct> subProducts= (List<SubProduct>)Model.subproduct;

The implicit conversion failes because List<> implements IList, not viceversa. So you can say IList<T> foo = new List<T>(), but not List<T> foo = (some IList-returning method or property).

Self-references in object literals / initializers

Simply instantiate an anonymous function:

var foo = new function () {
    this.a = 5;
    this.b = 6;
    this.c = this.a + this.b;
};

use jQuery to get values of selected checkboxes

Jquery 3.3.1 , getting values for all checked check boxes on button click

_x000D_
_x000D_
$(document).ready(function(){_x000D_
 $(".btn-submit").click(function(){_x000D_
  $('.cbCheck:checkbox:checked').each(function(){_x000D_
 alert($(this).val())_x000D_
  });_x000D_
 });   _x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="checkbox" id="vehicle1" name="vehicle1"  class="cbCheck" value="Bike">_x000D_
  <label for="vehicle1"> I have a bike</label><br>_x000D_
  <input type="checkbox" id="vehicle2" name="vehicle2"  class="cbCheck" value="Car">_x000D_
  <label for="vehicle2"> I have a car</label><br>_x000D_
  <input type="checkbox" id="vehicle3" name="vehicle3"  class="cbCheck" value="Boat">_x000D_
  <label for="vehicle3"> I have a boat</label><br><br>_x000D_
  <input type="submit" value="Submit" class="btn-submit">
_x000D_
_x000D_
_x000D_

Installing Git on Eclipse

There are two ways of installing the Git plugin in Eclipse

  1. Installing through Help -> Install New Software..., then add the location http://download.eclipse.org/egit/updates/
  2. Installing through Help -> Eclipse Marketplace..., then type Egit and installing it.

Both methods may need you to restart Eclipse in the middle. For the step by step guide on installing and configuring Git plugin in Eclipse, you can also refer to Install and configure git plugin in Eclipse

Mysql service is missing

Go to

C:\Program Files\MySQL\MySQL Server 5.2\bin

then Open MySQLInstanceConfig file

then complete the wizard.

Click finish

Solve the problem

I think this is the best way to change the port number also.

It works for me

How to convert an enum type variable to a string?

My solution, not using boost:

#ifndef EN2STR_HXX_
#define EN2STR_HXX_

#define MAKE_STRING_1(str     ) #str
#define MAKE_STRING_2(str, ...) #str, MAKE_STRING_1(__VA_ARGS__)
#define MAKE_STRING_3(str, ...) #str, MAKE_STRING_2(__VA_ARGS__)
#define MAKE_STRING_4(str, ...) #str, MAKE_STRING_3(__VA_ARGS__)
#define MAKE_STRING_5(str, ...) #str, MAKE_STRING_4(__VA_ARGS__)
#define MAKE_STRING_6(str, ...) #str, MAKE_STRING_5(__VA_ARGS__)
#define MAKE_STRING_7(str, ...) #str, MAKE_STRING_6(__VA_ARGS__)
#define MAKE_STRING_8(str, ...) #str, MAKE_STRING_7(__VA_ARGS__)

#define PRIMITIVE_CAT(a, b) a##b
#define MAKE_STRING(N, ...) PRIMITIVE_CAT(MAKE_STRING_, N)     (__VA_ARGS__)


#define PP_RSEQ_N() 8,7,6,5,4,3,2,1,0
#define PP_ARG_N(_1,_2,_3,_4,_5,_6,_7,_8,N,...) N
#define PP_NARG_(...) PP_ARG_N(__VA_ARGS__)
#define PP_NARG( ...) PP_NARG_(__VA_ARGS__,PP_RSEQ_N())

#define MAKE_ENUM(NAME, ...) enum NAME { __VA_ARGS__ };            \
  struct NAME##_str {                                              \
    static const char * get(const NAME et) {                       \
      static const char* NAME##Str[] = {                           \
                MAKE_STRING(PP_NARG(__VA_ARGS__), __VA_ARGS__) };  \
      return NAME##Str[et];                                        \
      }                                                            \
    };

#endif /* EN2STR_HXX_ */

And here is how to use it

int main()
  {
  MAKE_ENUM(pippo, pp1, pp2, pp3,a,s,d);
  pippo c = d;
  cout << pippo_str::get(c) << "\n";
  return 0;
  }

Netbeans 8.0.2 The module has not been deployed

I've had the same issue every now and then. This is how i solve the issue, it works like a charm for me!

  1. Go to 'Task Manager'
  2. Choose 'Processes' tab
  3. Click on 'Java(TM) Platform SE Binary'
  4. Click on 'End Process' button
  5. Go to your NetBeans project
  6. Clean & Build the project

Check that a variable is a number in UNIX shell

In either ksh93 or bash with the extglob option enabled:

if [[ $var == +([0-9]) ]]; then ...

Select the values of one property on all objects of an array in PowerShell

Caution, member enumeration only works if the collection itself has no member of the same name. So if you had an array of FileInfo objects, you couldn't get an array of file lengths by using

 $files.length # evaluates to array length

And before you say "well obviously", consider this. If you had an array of objects with a capacity property then

 $objarr.capacity

would work fine UNLESS $objarr were actually not an [Array] but, for example, an [ArrayList]. So before using member enumeration you might have to look inside the black box containing your collection.

(Note to moderators: this should be a comment on rageandqq's answer but I don't yet have enough reputation.)

Splitting applicationContext to multiple files

There are two types of contexts we are dealing with:

1: root context (parent context. Typically include all jdbc(ORM, Hibernate) initialisation and other spring security related configuration)

2: individual servlet context (child context.Typically Dispatcher Servlet Context and initialise all beans related to spring-mvc (controllers , URL Mapping etc)).

Here is an example of web.xml which includes multiple application context file

_x000D_
_x000D_
<?xml version="1.0" encoding="UTF-8"?>_x000D_
<web-app xmlns="http://java.sun.com/xml/ns/javaee"_x000D_
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"_x000D_
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee_x000D_
                            http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">_x000D_
_x000D_
    <display-name>Spring Web Application example</display-name>_x000D_
_x000D_
    <!-- Configurations for the root application context (parent context) -->_x000D_
    <listener>_x000D_
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>_x000D_
    </listener>_x000D_
    <context-param>_x000D_
        <param-name>contextConfigLocation</param-name>_x000D_
        <param-value>_x000D_
            /WEB-INF/spring/jdbc/spring-jdbc.xml <!-- JDBC related context -->_x000D_
            /WEB-INF/spring/security/spring-security-context.xml <!-- Spring Security related context -->_x000D_
        </param-value>_x000D_
    </context-param>_x000D_
_x000D_
    <!-- Configurations for the DispatcherServlet application context (child context) -->_x000D_
    <servlet>_x000D_
        <servlet-name>spring-mvc</servlet-name>_x000D_
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>_x000D_
        <init-param>_x000D_
            <param-name>contextConfigLocation</param-name>_x000D_
            <param-value>_x000D_
                /WEB-INF/spring/mvc/spring-mvc-servlet.xml_x000D_
            </param-value>_x000D_
        </init-param>_x000D_
    </servlet>_x000D_
    <servlet-mapping>_x000D_
        <servlet-name>spring-mvc</servlet-name>_x000D_
        <url-pattern>/admin/*</url-pattern>_x000D_
    </servlet-mapping>_x000D_
_x000D_
</web-app>
_x000D_
_x000D_
_x000D_

javascript: optional first argument in function

Like this:

my_function (null, options) // for options only
my_function (content) // for content only
my_function (content, options) // for both

AWS Lambda import module error in python

My problem was that the .py file and dependencies were not in the zip's "root" directory. e.g the path of libraries and lambda function .py must be:

<lambda_function_name>.py
<name of library>/foo/bar/

not

/foo/bar/<name of library>/foo2/bar2

For example:

drwxr-xr-x  3.0 unx        0 bx stor 20-Apr-17 19:43 boto3/ec2/__pycache__/
-rw-r--r--  3.0 unx      192 bx defX 20-Apr-17 19:43 boto3/ec2/__pycache__/__init__.cpython-37.pyc
-rw-r--r--  3.0 unx      758 bx defX 20-Apr-17 19:43 boto3/ec2/__pycache__/deletetags.cpython-37.pyc
-rw-r--r--  3.0 unx      965 bx defX 20-Apr-17 19:43 boto3/ec2/__pycache__/createtags.cpython-37.pyc
-rw-r--r--  3.0 unx     7781 tx defN 20-Apr-17 20:33 download-cs-sensors-to-s3.py

Get difference between two dates in months using Java

You can use Joda time library for Java. It would be much easier to calculate time-diff between dates with it.

Sample snippet for time-diff:

Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();

Python Pandas : pivot table with aggfunc = count unique distinct

Since none of the answers are up to date with the last version of Pandas, I am writing another solution for this problem:

In [1]:
import pandas as pd

# Set exemple
df2 = pd.DataFrame({'X' : ['X1', 'X1', 'X1', 'X1'], 'Y' : ['Y2','Y1','Y1','Y1'], 'Z' : ['Z3','Z1','Z1','Z2']})

# Pivot
pd.crosstab(index=df2['Y'], columns=df2['Z'], values=df2['X'], aggfunc=pd.Series.nunique)

Out [1]:
Z   Z1  Z2  Z3
Y           
Y1  1.0 1.0 NaN
Y2  NaN NaN 1.0

Mapping list in Yaml to list of objects in Spring Boot

I tried 2 solutions, both work.

Solution_1

.yml

available-users-list:
  configurations:
    -
      username: eXvn817zDinHun2QLQ==
      password: IP2qP+BQfWKJMVeY7Q==
    -
      username: uwJlOl/jP6/fZLMm0w==
      password: IP2qP+BQKJLIMVeY7Q==

LoginInfos.java

@ConfigurationProperties(prefix = "available-users-list")
@Configuration
@Component
@Data
public class LoginInfos {
    private List<LoginInfo> configurations;

    @Data
    public static class LoginInfo {
        private String username;
        private String password;
    }

}
List<LoginInfos.LoginInfo> list = loginInfos.getConfigurations();

Solution_2

.yml

available-users-list: '[{"username":"eXvn817zHBVn2QLQ==","password":"IfWKJLIMVeY7Q=="}, {"username":"uwJlOl/g9jP6/0w==","password":"IP2qWKJLIMVeY7Q=="}]'

Java

@Value("${available-users-listt}")
String testList;

ObjectMapper mapper = new ObjectMapper();
LoginInfos.LoginInfo[] array = mapper.readValue(testList, LoginInfos.LoginInfo[].class);

MVC If statement in View

Every time you use html syntax you have to start the next razor statement with a @. So it should be @if ....

Creating a Custom Event

Declare the class containing the event:

class MyClass {
    public event EventHandler MyEvent;

    public void Method() {
        OnEvent();
    }

    private void OnEvent() {
        if (MyEvent != null) {
            MyEvent(this, EventArgs.Empty);
        }
    }
}

Use it like this:

MyClass myObject = new MyClass();
myObject.MyEvent += new EventHandler(myObject_MyEvent);
myObject.Method();

Setting focus to a textbox control

To set focus,

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
    TextBox1.Focus()
End Sub

Set the TabIndex by

Me.TextBox1.TabIndex = 0

Can grep show only words that match search pattern?

I was unsatisfied with awk's hard to remember syntax but I liked the idea of using one utility to do this.

It seems like ack (or ack-grep if you use Ubuntu) can do this easily:

# ack-grep -ho "\bth.*?\b" *

the
the
the
this
thoroughly

If you omit the -h flag you get:

# ack-grep -o "\bth.*?\b" *

some-other-text-file
1:the

some-text-file
1:the
the

yet-another-text-file
1:this
thoroughly

As a bonus, you can use the --output flag to do this for more complex searches with just about the easiest syntax I've found:

# echo "bug: 1, id: 5, time: 12/27/2010" > test-file
# ack-grep -ho "bug: (\d*), id: (\d*), time: (.*)" --output '$1, $2, $3' test-file

1, 5, 12/27/2010

how do you increase the height of an html textbox

I'm assuming from the way you worded the question that you want to change the size after the page has rendered?

In Javascript, you can manipulate DOM CSS properties, for example:

document.getElementById('textboxid').style.height="200px";
document.getElementById('textboxid').style.fontSize="14pt";

If you simply want to specify the height and font size, use CSS or style attributes, e.g.

//in your CSS file or <style> tag
#textboxid
{
    height:200px;
    font-size:14pt;
}

<!--in your HTML-->
<input id="textboxid" ...>

Or

<input style="height:200px;font-size:14pt;" .....>

Python: SyntaxError: keyword can't be an expression

I just got that problem when converting from % formatting to .format().

Previous code:

"SET !TIMEOUT_STEP %{USER_TIMEOUT_STEP}d" % {'USER_TIMEOUT_STEP' = 3}

Problematic syntax:

"SET !TIMEOUT_STEP {USER_TIMEOUT_STEP}".format('USER_TIMEOUT_STEP' = 3)

The problem is that format is a function that needs parameters. They cannot be strings. That is one of worst python error messages I've ever seen.

Corrected code:

"SET !TIMEOUT_STEP {USER_TIMEOUT_STEP}".format(USER_TIMEOUT_STEP = 3)

How to put a jpg or png image into a button in HTML

You can use some inline CSS like this

<input type="submit" name="submit" style="background: url(images/stack.png); width:100px; height:25px;" />

Should do the magic, also you may wanna do a border:none; to get rid of the standard borders.

How to get to Model or Viewbag Variables in a Script Tag

try this method

<script type="text/javascript">

    function set(value) {
        return value;
    }

    alert(set(@Html.Raw(Json.Encode(Model.Message)))); // Message set from controller
    alert(set(@Html.Raw(Json.Encode(ViewBag.UrMessage))));

</script>

Thanks

What is the difference between varchar and nvarchar?

nvarchar stores data as Unicode, so, if you're going to store multilingual data (more than one language) in a data column you need the N variant.

How do I use StringUtils in Java?

StringUtils is an Apache Commons project. You need to download and add the library to your classpath.

To use:

import org.apache.commons.lang3.StringUtils;

PHP Fatal error: Using $this when not in object context

$foobar = new foobar; put the class foobar in $foobar, not the object. To get the object, you need to add parenthesis: $foobar = new foobar();

Your error is simply that you call a method on a class, so there is no $this since $this only exists in objects.

How to find sitemap.xml path on websites?

According to protocol documentation there are at least three options website designers can use to inform sitemap.xml location to search engines:

  • Informing each search engine of the location through their provided interface
  • Adding url to the robots.txt file
  • Submiting url to search engines through http

So, unless they have chosen to publish the sitemap location on their robots.txt file, you cannot really know where they have put their sitemap.xml files.

How can I create a progress bar in Excel VBA?

============== This code goes in Module1 ============

Sub ShowProgress()
    UserForm1.Show
End Sub

============== Module1 Code Block End =============

Create a Button on a Worksheet; map button to "ShowProgress" macro

Create a UserForm1 with 2 buttons, progress bar, bar box, text box:

UserForm1 = canvas to hold other 5 elements
CommandButton2 = Run Progress Bar Code; Caption:Run
CommandButton1 = Close UserForm1; Caption:Close
Bar1 (label) = Progress bar graphic; BackColor:Blue
BarBox (label) = Empty box to frame Progress Bar; BackColor:White
Counter (label) = Display the integers used to drive the progress bar

======== Attach the following code to UserForm1 =========

Option Explicit

' This is used to create a delay to prevent memory overflow
' remove after software testing is complete

Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

Private Sub UserForm_Initialize()

    Bar1.Tag = Bar1.Width
    Bar1.Width = 0

End Sub
Sub ProgressBarDemo()
    Dim intIndex As Integer
    Dim sngPercent As Single
    Dim intMax As Integer
    '==============================================
    '====== Bar Length Calculation Start ==========

    '-----------------------------------------------'
    ' This section is where you can use your own    '
    ' variables to increase bar length.             '
    ' Set intMax to your total number of passes     '
    ' to match bar length to code progress.         '
    ' This sample code automatically runs 1 to 100  '
    '-----------------------------------------------'
    intMax = 100
    For intIndex = 1 To intMax
        sngPercent = intIndex / intMax
        Bar1.Width = Int(Bar1.Tag * sngPercent)
        Counter.Caption = intIndex


    '======= Bar Length Calculation End ===========
    '==============================================


DoEvents
        '------------------------
        ' Your production code would go here and cycle
        ' back to pass through the bar length calculation
        ' increasing the bar length on each pass.
        '------------------------

'this is a delay to keep the loop from overrunning memory
'remove after testing is complete
        Sleep 10

    Next

End Sub
Private Sub CommandButton1_Click() 'CLOSE button

Unload Me

End Sub
Private Sub CommandButton2_Click() 'RUN button

        ProgressBarDemo

End Sub

================= UserForm1 Code Block End =====================

============== This code goes in Module1 =============

Sub ShowProgress()
    UserForm1.Show
End Sub

============== Module1 Code Block End =============

base64 encode in MySQL

create table encrypt(username varchar(20),password varbinary(200))

insert into encrypt values('raju',aes_encrypt('kumar','key')) select *,cast(aes_decrypt(password,'key') as char(40)) from encrypt where username='raju';

Is there a Wikipedia API?

If you want to extract structured data from Wikipedia, you may consider using DbPedia http://dbpedia.org/

It provides means to query data using given criteria using SPARQL and returns data from parsed Wikipedia infobox templates

Here is a quick example how it could be done in .NET http://www.kozlenko.info/blog/2010/07/20/executing-sparql-query-on-wikipedia-in-net/

There are some SPARQL libraries available for multiple platforms to make queries easier

How to detect a USB drive has been plugged in?

Here is a code that works for me, which is a part from the website above combined with my early trials: http://www.codeproject.com/KB/system/DriveDetector.aspx

This basically makes your form listen to windows messages, filters for usb drives and (cd-dvds), grabs the lparam structure of the message and extracts the drive letter.

protected override void WndProc(ref Message m)
    {

        if (m.Msg == WM_DEVICECHANGE)
        {
            DEV_BROADCAST_VOLUME vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME));
            if ((m.WParam.ToInt32() == DBT_DEVICEARRIVAL) &&  (vol.dbcv_devicetype == DBT_DEVTYPVOLUME) )
            {
                MessageBox.Show(DriveMaskToLetter(vol.dbcv_unitmask).ToString());
            }
            if ((m.WParam.ToInt32() == DBT_DEVICEREMOVALCOMPLETE) && (vol.dbcv_devicetype == DBT_DEVTYPVOLUME))
            {
                MessageBox.Show("usb out");
            }
        }
        base.WndProc(ref m);
    }

    [StructLayout(LayoutKind.Sequential)] //Same layout in mem
    public struct DEV_BROADCAST_VOLUME
    {
        public int dbcv_size;
        public int dbcv_devicetype;
        public int dbcv_reserved;
        public int dbcv_unitmask;
    }

    private static char DriveMaskToLetter(int mask)
    {
        char letter;
        string drives = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //1 = A, 2 = B, 3 = C
        int cnt = 0;
        int pom = mask / 2;
        while (pom != 0)    // while there is any bit set in the mask shift it right        
        {        
            pom = pom / 2;
            cnt++;
        }
        if (cnt < drives.Length)
            letter = drives[cnt];
        else
            letter = '?';
        return letter;
    }

Do not forget to add this:

using System.Runtime.InteropServices;

and the following constants:

    const int WM_DEVICECHANGE = 0x0219; //see msdn site
    const int DBT_DEVICEARRIVAL = 0x8000;
    const int DBT_DEVICEREMOVALCOMPLETE = 0x8004;
    const int DBT_DEVTYPVOLUME = 0x00000002;  

Looping through JSON with node.js

Not sure if it helps, but it looks like there might be a library for async iteration in node hosted here:

https://github.com/caolan/async

Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript. Although originally designed for use with node.js, it can also be used directly in the browser.

Async provides around 20 functions that include the usual 'functional' suspects (map, reduce, filter, forEach…) as well as some common patterns for asynchronous control flow (parallel, series, waterfall…). All these functions assume you follow the node.js convention of providing a single callback as the last argument of your async function.

What does if __name__ == "__main__": do?

Consider:

print __name__

The output for the above is __main__.

if __name__ == "__main__":
  print "direct method"

The above statement is true and prints "direct method". Suppose if they imported this class in another class it doesn't print "direct method" because, while importing, it will set __name__ equal to "first model name".

How to get the separate digits of an int number?

simple solution

public static void main(String[] args) {
    int v = 12345;
    while (v > 0){
        System.out.println(v % 10);
        v /= 10;
    }
}

Bootstrap how to get text to vertical align in a div container

HTML:

First, we will need to add a class to your text container so that we can access and style it accordingly.

<div class="col-xs-5 textContainer">
     <h3 class="text-left">Link up with other gamers all over the world who share the same tastes in games.</h3>
</div>

CSS:

Next, we will apply the following styles to align it vertically, according to the size of the image div next to it.

.textContainer { 
    height: 345px; 
    line-height: 340px;
}

.textContainer h3 {
    vertical-align: middle;
    display: inline-block;
}

All Done! Adjust the line-height and height on the styles above if you believe that it is still slightly out of align.

WORKING EXAMPLE

Android 'Unable to add window -- token null is not for an application' exception

Hello there if you are using adapter there might be a chance.
All you need to know when you used any dialog in adapter,getContext(),context or activity won't work sometime.

Here is the trick I used v.getRootView().getContext() where v is the view object you are referencing.
Eg.


            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                new DatePickerDialog(v.getRootView().getContext(), date, myCalendar
                        .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                        myCalendar.get(Calendar.DAY_OF_MONTH)).show();
            }
        });  
If you are getting this problem because of alert dialog.
Refer [here][1] But it is same concept.


  [1]: https://stackoverflow.com/questions/6367771/displaying-alertdialog-inside-a-custom-listadapter-class

Hexadecimal To Decimal in Shell Script

The error as reported appears when the variables are null (or empty):

$ unset var3 var4; var5=$(($var4-$var3))
bash: -: syntax error: operand expected (error token is "-")

That could happen because the value given to bc was incorrect. That might well be that bc needs UPPERcase values. It needs BFCA3000, not bfca3000. That is easily fixed in bash, just use the ^^ expansion:

var3=bfca3000; var3=`echo "ibase=16; ${var1^^}" | bc`

That will change the script to this:

#!/bin/bash

var1="bfca3000"
var2="efca3250"

var3="$(echo "ibase=16; ${var1^^}" | bc)"
var4="$(echo "ibase=16; ${var2^^}" | bc)"

var5="$(($var4-$var3))"

echo "Diference $var5"

But there is no need to use bc [1], as bash could perform the translation and substraction directly:

#!/bin/bash

var1="bfca3000"
var2="efca3250"

var5="$(( 16#$var2 - 16#$var1 ))"

echo "Diference $var5"

[1]Note: I am assuming the values could be represented in 64 bit math, as the difference was calculated in bash in your original script. Bash is limited to integers less than ((2**63)-1) if compiled in 64 bits. That will be the only difference with bc which does not have such limit.

Formatting Phone Numbers in PHP

Assuming that your phone numbers always have this exact format, you can use this snippet:

$from = "+11234567890";
$to = sprintf("%s-%s-%s",
              substr($from, 2, 3),
              substr($from, 5, 3),
              substr($from, 8));

Calling Javascript function from server side

You can call the function from code behind like this :

MyForm.aspx.cs

protected void MyButton_Click(object sender, EventArgs e)
{
    Page.ClientScript.RegisterStartupScript(this.GetType(), "myScript", "AnotherFunction();", true);
}

MyForm.aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>My Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    function Test() {
        alert("hi");
        $("#ButtonRow").show();
    }
    function AnotherFunction()
    {
        alert("This is another function");
    }
</script>
</head>
<body>
<form id="form2" runat="server">
<table>
    <tr><td>
            <asp:RadioButtonList ID="SearchCategory" runat="server" onchange="Test()"  RepeatDirection="Horizontal"  BorderStyle="Solid">
               <asp:ListItem>Merchant</asp:ListItem>
               <asp:ListItem>Store</asp:ListItem>
               <asp:ListItem>Terminal</asp:ListItem>
            </asp:RadioButtonList>
        </td>
    </tr>
    <tr id="ButtonRow"style="display:none">
         <td>
            <asp:Button ID="MyButton" runat="server" Text="Click Here" OnClick="MyButton_Click" />
        </td>
    </tr>
    </table> 
</form>

Install a Python package into a different directory using pip?

With pip v1.5.6 on Python v2.7.3 (GNU/Linux), option --root allows to specify a global installation prefix, (apparently) irrespective of specific package's options. Try f.i.,

$ pip install --root=/alternative/prefix/path package_name

Injecting Mockito mocks into a Spring bean

Posting a few examples based on the above approaches

With Spring:

@ContextConfiguration(locations = { "classpath:context.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class TestServiceTest {
    @InjectMocks
    private TestService testService;
    @Mock
    private TestService2 testService2;
}

Without Spring:

@RunWith(MockitoJUnitRunner.class)
public class TestServiceTest {
    @InjectMocks
    private TestService testService = new TestServiceImpl();
    @Mock
    private TestService2 testService2;
}

Only read selected columns

You do it like this:

df = read.table("file.txt", nrows=1, header=TRUE, sep="\t", stringsAsFactors=FALSE)
colClasses = as.list(apply(df, 2, class))
needCols = c("Year", "Jan", "Feb", "Mar", "Apr", "May", "Jun")
colClasses[!names(colClasses) %in% needCols] = list(NULL)
df = read.table("file.txt", header=TRUE, colClasses=colClasses, sep="\t", stringsAsFactors=FALSE)

Get a resource using getResource()

if you are calling from static method, use :

TestGameTable.class.getClassLoader().getResource("dice.jpg");

Where to get this Java.exe file for a SQL Developer installation

Use any JDK installation as long as it is NOT 64bit. The easiest way to find out if it is 64bit installation is to check the folder it resides into. e.g.

C:\Program Files\... is for 64 bit programs
C:\Program Files (x86)\... is for 32 bit programs

How to assert greater than using JUnit Assert?

As I recognize, at the moment, in JUnit, the syntax is like this:

AssertTrue(Long.parseLong(previousTokenValues[1]) > Long.parseLong(currentTokenValues[1]), "your fail message ");

Means that, the condition is in front of the message.

Is HTML considered a programming language?

I get around this problem by not having a "programming languages" section on my resume. Instead I label it simply as "languages", and I stick HTML and CSS at the end. I'd rather make life easier for the reviewer so that they can see whether mine checks-off all their requirements.

Only fools would disregard an applicant because he or she listed HTML under "languages" instead of some other label, especially since there is no industry standard. And who wants to work for fools?