Programs & Examples On #Stack trace

A report of the active stack frames at a certain point in time during the execution of a program.

How do I find the stack trace in Visual Studio?

Using the Call Stack Window

To open the Call Stack window in Visual Studio, from the Debug menu, choose Windows>Call Stack. To set the local context to a particular row in the stack trace display, double click the first column of the row.

http://msdn.microsoft.com/en-us/library/windows/hardware/hh439516(v=vs.85).aspx

How to store printStackTrace into a string

Use the apache commons-lang3 lib

import org.apache.commons.lang3.exception.ExceptionUtils;

//...

String[] ss = ExceptionUtils.getRootCauseStackTrace(e);
logger.error(StringUtils.join(ss, System.lineSeparator()));

Official reasons for "Software caused connection abort: socket write error"

ssl client side will throw such exception in below situation(I had tested), :

server is asked to authenticate client certificate, but the client provide a certificate which Extended Key Usage donot support client auth.

How can I get the current stack trace in Java?

for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
    System.out.println(ste);
}

Print PHP Call Stack

To log the trace

$e = new Exception;
error_log(var_export($e->getTraceAsString(), true));

Thanks @Tobiasz

How can I convert a stack trace to a string?

 import java.io.PrintWriter;
import java.io.StringWriter;

public class PrintStackTrace {

    public static void main(String[] args) {

        try {
            int division = 0 / 0;
        } catch (ArithmeticException e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
            String exceptionAsString = sw.toString();
            System.out.println(exceptionAsString);
        }
    }
}

When you run the program, the output will be something similar:

java.lang.ArithmeticException: / by zero
at PrintStackTrace.main(PrintStackTrace.java:9)

How do I get ruby to print a full backtrace instead of a truncated one?

You could also do this if you'd like a simple one-liner:

puts caller

How to print the current Stack Trace in .NET without any exception?

   private void ExceptionTest()
    {
        try
        {
            int j = 0;
            int i = 5;
            i = 1 / j;
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
            var stList = ex.StackTrace.ToString().Split('\\');
            Console.WriteLine("Exception occurred at " + stList[stList.Count() - 1]);
        }
    }

Seems to work for me

How do I obtain crash-data from my Android application?

It is possible to handle these exceptions with Thread.setDefaultUncaughtExceptionHandler(), however this appears to mess with Android's method of handling exceptions. I attempted to use a handler of this nature:

private class ExceptionHandler implements Thread.UncaughtExceptionHandler {
    @Override
    public void uncaughtException(Thread thread, Throwable ex){
        Log.e(Constants.TAG, "uncaught_exception_handler: uncaught exception in thread " + thread.getName(), ex);

        //hack to rethrow unchecked exceptions
        if(ex instanceof RuntimeException)
            throw (RuntimeException)ex;
        if(ex instanceof Error)
            throw (Error)ex;

        //this should really never happen
        Log.e(Constants.TAG, "uncaught_exception handler: unable to rethrow checked exception");
    }
}

However, even with rethrowing the exceptions, I was unable to get the desired behavior, ie logging the exception while still allowing Android to shutdown the component it had happened it, so I gave up on it after a while.

How can one grab a stack trace in C?

There is no platform independent way to do it.

The nearest thing you can do is to run the code without optimizations. That way you can attach to the process (using the visual c++ debugger or GDB) and get a usable stack trace.

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

The other posts describe what a stack trace is, but it can still be hard to work with.

If you get a stack trace and want to trace the cause of the exception, a good start point in understanding it is to use the Java Stack Trace Console in Eclipse. If you use another IDE there may be a similar feature, but this answer is about Eclipse.

First, ensure that you have all of your Java sources accessible in an Eclipse project.

Then in the Java perspective, click on the Console tab (usually at the bottom). If the Console view is not visible, go to the menu option Window -> Show View and select Console.

Then in the console window, click on the following button (on the right)

Consoles button

and then select Java Stack Trace Console from the drop-down list.

Paste your stack trace into the console. It will then provide a list of links into your source code and any other source code available.

This is what you might see (image from the Eclipse documentation):

Diagram from Eclipse documentation

The most recent method call made will be the top of the stack, which is the top line (excluding the message text). Going down the stack goes back in time. The second line is the method that calls the first line, etc.

If you are using open-source software, you might need to download and attach to your project the sources if you want to examine. Download the source jars, in your project, open the Referenced Libraries folder to find your jar for your open-source module (the one with the class files) then right click, select Properties and attach the source jar.

How to log as much information as possible for a Java Exception?

You can also use Apache's ExceptionUtils.

Example:

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.log4j.Logger;


public class Test {

    static Logger logger = Logger.getLogger(Test.class);

    public static void main(String[] args) {

        try{
            String[] avengers = null;
            System.out.println("Size: "+avengers.length);
        } catch (NullPointerException e){
            logger.info(ExceptionUtils.getFullStackTrace(e));
        }
    }

}

Console output:

java.lang.NullPointerException
    at com.aimlessfist.avengers.ironman.Test.main(Test.java:11)

How to print a stack trace in Node.js?

If you want to only log the stack trace of the error (and not the error message) Node 6 and above automatically includes the error name and message inside the stack trace, which is a bit annoying if you want to do some custom error handling:

console.log(error.stack.replace(error.message, ''))

This workaround will log only the error name and stack trace (so you can, for example, format the error message and display it how you want somewhere else in your code).

The above example would print only the error name follow by the stack trace, for example:

Error: 
    at /Users/cfisher/Git/squashed/execProcess.js:6:17
    at ChildProcess.exithandler (child_process.js:213:5)
    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:191:7)
    at maybeClose (internal/child_process.js:877:16)
    at Socket.<anonymous> (internal/child_process.js:334:11)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at Pipe._handle.close [as _onclose] (net.js:498:12)

Instead of:

Error: Error: Command failed: sh ./commands/getBranchCommitCount.sh HEAD
git: 'rev-lists' is not a git command. See 'git --help'.

Did you mean this?
        rev-list

    at /Users/cfisher/Git/squashed/execProcess.js:6:17
    at ChildProcess.exithandler (child_process.js:213:5)
    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:191:7)
    at maybeClose (internal/child_process.js:877:16)
    at Socket.<anonymous> (internal/child_process.js:334:11)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at Pipe._handle.close [as _onclose] (net.js:498:12)

Why is exception.printStackTrace() considered bad practice?

You are touching multiple issues here:

1) A stack trace should never be visibile to end users (for user experience and security purposes)

Yes, it should be accessible to diagnose problems of end-users, but end-user should not see them for two reasons:

  • They are very obscure and unreadable, the application will look very user-unfriendly.
  • Showing a stack trace to end-user might introduce a potential security risk. Correct me if I'm wrong, PHP actually prints function parameters in stack trace - brilliant, but very dangerous - if you would you get exception while connecting to the database, what are you likely to in the stacktrace?

2) Generating a stack trace is a relatively expensive process (though unlikely to be an issue in most 'exception'al circumstances)

Generating a stack trace happens when the exception is being created/thrown (that's why throwing an exception comes with a price), printing is not that expensive. In fact you can override Throwable#fillInStackTrace() in your custom exception effectively making throwing an exception almost as cheap as a simple GOTO statement.

3) Many logging frameworks will print the stack trace for you (ours does not and no, we can't change it easily)

Very good point. The main issue here is: if the framework logs the exception for you, do nothing (but make sure it does!) If you want to log the exception yourself, use logging framework like Logback or Log4J, to not put them on the raw console because it is very hard to control it.

With logging framework you can easily redirect stack traces to file, console or even send them to a specified e-mail address. With hardcoded printStackTrace() you have to live with the sysout.

4) Printing the stack trace does not constitute error handling. It should be combined with other information logging and exception handling.

Again: log SQLException correctly (with the full stack trace, using logging framework) and show nice: "Sorry, we are currently not able to process your request" message. Do you really think the user is interested in the reasons? Have you seen StackOverflow error screen? It's very humorous, but does not reveal any details. However it ensures the user that the problem will be investigated.

But he will call you immediately and you need to be able to diagnose the problem. So you need both: proper exception logging and user-friendly messages.


To wrap things up: always log exceptions (preferably using logging framework), but do not expose them to the end-user. Think carefully and about error-messages in your GUI, show stack traces only in development mode.

How to Add Stacktrace or debug Option when Building Android Studio Project

my solution is this:

configurations.all {
    resolutionStrategy {
        force 'com.android.support:support-v4:27.1.0'
    }
}

e.printStackTrace equivalent in python

Adding to the other great answers, we can use the Python logging library's debug(), info(), warning(), error(), and critical() methods. Quoting from the docs for Python 3.7.4,

There are three keyword arguments in kwargs which are inspected: exc_info which, if it does not evaluate as false, causes exception information to be added to the logging message.

What this means is, you can use the Python logging library to output a debug(), or other type of message, and the logging library will include the stack trace in its output. With this in mind, we can do the following:

import logging

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

def f():
    a = { 'foo': None }
    # the following line will raise KeyError
    b = a['bar']

def g():
    f()

try:
    g()
except Exception as e:
    logger.error(str(e), exc_info=True)

And it will output:

'bar'
Traceback (most recent call last):
  File "<ipython-input-2-8ae09e08766b>", line 18, in <module>
    g()
  File "<ipython-input-2-8ae09e08766b>", line 14, in g
    f()
  File "<ipython-input-2-8ae09e08766b>", line 10, in f
    b = a['bar']
KeyError: 'bar'

Print current call stack from a method in Python code

Install Inspect-it

pip3 install inspect-it --user

Code

import inspect;print(*['\n\x1b[0;36;1m| \x1b[0;32;1m{:25}\x1b[0;36;1m| \x1b[0;35;1m{}'.format(str(x.function), x.filename+'\x1b[0;31;1m:'+str(x.lineno)+'\x1b[0m') for x in inspect.stack()])

you can Make a snippet of this line

it will show you a list of the function call stack with a filename and line number

list from start to where you put this line

Get exception description and stack trace which caused an exception, all as a string

With Python 3, the following code will format an Exception object exactly as would be obtained using traceback.format_exc():

import traceback

try: 
    method_that_can_raise_an_exception(params)
except Exception as ex:
    print(''.join(traceback.format_exception(etype=type(ex), value=ex, tb=ex.__traceback__)))

The advantage being that only the Exception object is needed (thanks to the recorded __traceback__ attribute), and can therefore be more easily passed as an argument to another function for further processing.

When I catch an exception, how do I get the type, file, and line number?

import sys, os

try:
    raise NotImplementedError("No error")
except Exception as e:
    exc_type, exc_obj, exc_tb = sys.exc_info()
    fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
    print(exc_type, fname, exc_tb.tb_lineno)

How can I find the method that called the current method?

Take a look at Logging method name in .NET. Beware of using it in production code. StackFrame may not be reliable...

Showing the stack trace from a running Python application

>>> import traceback
>>> def x():
>>>    print traceback.extract_stack()

>>> x()
[('<stdin>', 1, '<module>', None), ('<stdin>', 2, 'x', None)]

You can also nicely format the stack trace, see the docs.

Edit: To simulate Java's behavior, as suggested by @Douglas Leeder, add this:

import signal
import traceback

signal.signal(signal.SIGUSR1, lambda sig, stack: traceback.print_stack(stack))

to the startup code in your application. Then you can print the stack by sending SIGUSR1 to the running Python process.

How to automatically generate a stacktrace when my program crashes

I can help with the Linux version: the function backtrace, backtrace_symbols and backtrace_symbols_fd can be used. See the corresponding manual pages.

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

This method does the same thing but a little more simply and possibly a little more performant and in the event you are using reflection, it skips those frames automatically. The only issue is it may not be present in non-Sun JVMs, although it is included in the runtime classes of JRockit 1.4-->1.6. (Point is, it is not a public class).

sun.reflect.Reflection

    /** Returns the class of the method <code>realFramesToSkip</code>
        frames up the stack (zero-based), ignoring frames associated
        with java.lang.reflect.Method.invoke() and its implementation.
        The first frame is that associated with this method, so
        <code>getCallerClass(0)</code> returns the Class object for
        sun.reflect.Reflection. Frames associated with
        java.lang.reflect.Method.invoke() and its implementation are
        completely ignored and do not count toward the number of "real"
        frames skipped. */
    public static native Class getCallerClass(int realFramesToSkip);

As far as what the realFramesToSkip value should be, the Sun 1.5 and 1.6 VM versions of java.lang.System, there is a package protected method called getCallerClass() which calls sun.reflect.Reflection.getCallerClass(3), but in my helper utility class I used 4 since there is the added frame of the helper class invocation.

Couldn't load memtrack module Logcat Error

do you called the ViewTreeObserver and not remove it.

    mEtEnterlive.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
         // do nothing here can cause such problem
    });

How can I get a JavaScript stack trace when I throw an exception?

If you have firebug, there's a break on all errors option in the script tab. Once the script has hit your breakpoint, you can look at firebug's stack window:

screenshot

How to print full stack trace in exception?

Use a function like this:

    public static string FlattenException(Exception exception)
    {
        var stringBuilder = new StringBuilder();

        while (exception != null)
        {
            stringBuilder.AppendLine(exception.Message);
            stringBuilder.AppendLine(exception.StackTrace);

            exception = exception.InnerException;
        }

        return stringBuilder.ToString();
    }

Then you can call it like this:

try
{
    // invoke code above
}
catch(MyCustomException we)
{
    Debug.Writeline(FlattenException(we));
}

C++ display stack trace on exception

Poppy can gather not only the stack trace, but also parameter values, local variables, etc. - everything leading to the crash.

How to send a stacktrace to log4j?

Create this class:

public class StdOutErrLog {

private static final Logger logger = Logger.getLogger(StdOutErrLog.class);

public static void tieSystemOutAndErrToLog() {
    System.setOut(createLoggingProxy(System.out));
    System.setErr(createLoggingProxy(System.err));
}

public static PrintStream createLoggingProxy(final PrintStream realPrintStream) {
    return new PrintStream(realPrintStream) {
        public void print(final String string) {
            logger.info(string);
        }
        public void println(final String string) {
            logger.info(string);
        }
    };
}
}

Call this in your code

StdOutErrLog.tieSystemOutAndErrToLog();

How to printf "unsigned long" in C?

  • %lu for unsigned long
  • %llu for unsigned long long

Should I set max pool size in database connection string? What happens if I don't?

"currently yes but i think it might cause problems at peak moments" I can confirm, that I had a problem where I got timeouts because of peak requests. After I set the max pool size, the application ran without any problems. IIS 7.5 / ASP.Net

Left align and right align within div in Bootstrap

Bootstrap v4 introduces flexbox support

<div class="d-flex justify-content-end">
  <div class="mr-auto p-2">Flex item</div>
  <div class="p-2">Flex item</div>
  <div class="p-2">Flex item</div>
</div>

Learn more at https://v4-alpha.getbootstrap.com/utilities/flexbox/

Reducing the gap between a bullet and text in a list item

If in every li you have only one row of text you can put text indent on li. Like this :

ul {
  list-style: disc;
}
ul li {
   text-indent: 5px;
}

or

ul {
 list-style: disc;
}
ul li {
   text-indent: -5px;
}

How do you set the title color for the new Toolbar?

Option 1) The quick and easy way (Toolbar only)

Since appcompat-v7-r23 you can use the following attributes directly on your Toolbar or its style:

app:titleTextColor="@color/primary_text"
app:subtitleTextColor="@color/secondary_text"

If your minimum SDK is 23 and you use native Toolbar just change the namespace prefix to android.

In Java you can use the following methods:

toolbar.setTitleTextColor(Color.WHITE);
toolbar.setSubtitleTextColor(Color.WHITE);

These methods take a color int not a color resource ID!

Option 2) Override Toolbar style and theme attributes

layout/xxx.xml

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/actionBarSize"
    android:theme="@style/ThemeOverlay.MyApp.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    style="@style/Widget.MyApp.Toolbar.Solid"/>

values/styles.xml

<style name="Widget.MyApp.Toolbar.Solid" parent="Widget.AppCompat.ActionBar">
    <item name="android:background">@color/actionbar_color</item>
    <item name="android:elevation" tools:ignore="NewApi">4dp</item>
    <item name="titleTextAppearance">...</item>
</style>

<style name="ThemeOverlay.MyApp.ActionBar" parent="ThemeOverlay.AppCompat.ActionBar">
    <!-- Parent theme sets colorControlNormal to textColorPrimary. -->
    <item name="android:textColorPrimary">@color/actionbar_title_text</item>
</style>

Help! My icons changed color too!

@PeterKnut reported this affects the color of overflow button, navigation drawer button and back button. It also changes text color of SearchView.

Concerning the icon colors: The colorControlNormal inherits from

  • android:textColorPrimary for dark themes (white on black)
  • android:textColorSecondary for light themes (black on white)

If you apply this to the action bar's theme, you can customize the icon color.

<item name="colorControlNormal">#de000000</item>

There was a bug in appcompat-v7 up to r23 which required you to also override the native counterpart like so:

<item name="android:colorControlNormal" tools:ignore="NewApi">?colorControlNormal</item>

Help! My SearchView is a mess!

Note: This section is possibly obsolete.

Since you use the search widget which for some reason uses different back arrow (not visually, technically) than the one included with appcompat-v7, you have to set it manually in the app's theme. Support library's drawables get tinted correctly. Otherwise it would be always white.

<item name="homeAsUpIndicator">@drawable/abc_ic_ab_back_mtrl_am_alpha</item>

As for the search view text...there's no easy way. After digging through its source I found a way to get to the text view. I haven't tested this so please let me know in the comments if this didn't work.

SearchView sv = ...; // get your search view instance in onCreateOptionsMenu
// prefix identifier with "android:" if you're using native SearchView
TextView tv = sv.findViewById(getResources().getIdentifier("id/search_src_text", null, null));
tv.setTextColor(Color.GREEN); // and of course specify your own color

Bonus: Override ActionBar style and theme attributes

Appropriate styling for a default action appcompat-v7 action bar would look like this:

<!-- ActionBar vs Toolbar. -->
<style name="Widget.MyApp.ActionBar.Solid" parent="Widget.AppCompat.ActionBar.Solid">
    <item name="background">@color/actionbar_color</item> <!-- No prefix. -->
    <item name="elevation">4dp</item> <!-- No prefix. -->
    <item name="titleTextStyle">...</item> <!-- Style vs appearance. -->
</style>

<style name="Theme.MyApp" parent="Theme.AppCompat">
    <item name="actionBarStyle">@style/Widget.MyApp.ActionBar.Solid</item>
    <item name="actionBarTheme">@style/ThemeOverlay.MyApp.ActionBar</item>
    <item name="actionBarPopupTheme">@style/ThemeOverlay.AppCompat.Light</item>
</style>

Emulating a do-while loop in Bash

We can emulate a do-while loop in Bash with while [[condition]]; do true; done like this:

while [[ current_time <= $cutoff ]]
    check_if_file_present
    #do other stuff
do true; done

For an example. Here is my implementation on getting ssh connection in bash script:

#!/bin/bash
while [[ $STATUS != 0 ]]
    ssh-add -l &>/dev/null; STATUS="$?"
    if [[ $STATUS == 127 ]]; then echo "ssh not instaled" && exit 0;
    elif [[ $STATUS == 2 ]]; then echo "running ssh-agent.." && eval `ssh-agent` > /dev/null;
    elif [[ $STATUS == 1 ]]; then echo "get session identity.." && expect $HOME/agent &> /dev/null;
    else ssh-add -l && git submodule update --init --recursive --remote --merge && return 0; fi
do true; done

It will give the output in sequence as below:

Step #0 - "gcloud": intalling expect..
Step #0 - "gcloud": running ssh-agent..
Step #0 - "gcloud": get session identity..
Step #0 - "gcloud": 4096 SHA256:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX /builder/home/.ssh/id_rsa (RSA)
Step #0 - "gcloud": Submodule '.google/cloud/compute/home/chetabahana/.docker/compose' ([email protected]:chetabahana/compose) registered for path '.google/cloud/compute/home/chetabahana/.docker/compose'
Step #0 - "gcloud": Cloning into '/workspace/.io/.google/cloud/compute/home/chetabahana/.docker/compose'...
Step #0 - "gcloud": Warning: Permanently added the RSA host key for IP address 'XXX.XX.XXX.XXX' to the list of known hosts.
Step #0 - "gcloud": Submodule path '.google/cloud/compute/home/chetabahana/.docker/compose': checked out '24a28a7a306a671bbc430aa27b83c09cc5f1c62d'
Finished Step #0 - "gcloud"

Visual Studio Code cannot detect installed git

VSCode 1.50 (Sept 2020) adds an interesting alternative with issue 85734:

Support multiple values for the git.path setting

I use VSCode in three different places; my home computer, my work computer, and as a portable version I carry on a drive when I need to use a machine that doesn't have it.

I use an extension to keep my settings synced up between editors, and the only issue I've encountered so far is that the git path doesn't match between any of them.

  • On my home machine I have it installed to C of course,
  • work likes to be funny and install it on A,
  • and for the one on my drive I have a relative path set so that no matter what letter my drive gets, that VSCode can always find git.

I already attempted to use an array myself just to see if it'd work:

"git.path": ["C:\\Program Files\\Git\\bin\\git.exe", "A:\\Git\\bin\\git.exe", "..\\..\\Git\\bin\\git.exe"],

But VSCode reads it as one entire value.

What I'd like is for it to recognize it as an array and then try each path in order until it finds Git or runs out of paths.

This is addressed with PR 85954 and commit c334da1.

Set cellpadding and cellspacing in CSS?

Also, if you want cellspacing="0", don't forget to add border-collapse: collapse in your table's stylesheet.

chart.js load totally new data

It is an old thread, but in the current version (as of 1-feb-2017), it easy to replace datasets plotted on chart.js:

suppose your new x-axis values are in array x and y-axis values are in array y, you can use below code to update the chart.

var x = [1,2,3];
var y = [1,1,1];

chart.data.datasets[0].data = y;
chart.data.labels = x;

chart.update();

How do I discover memory usage of my application in Android?

In android studio 3.0 they have introduced android-profiler to help you to understand how your app uses CPU, memory, network, and battery resources.

https://developer.android.com/studio/profile/android-profiler

enter image description here

og:type and valid values : constantly being parsed as og:type=website

As of May 2018, you can find the full list here: https://developers.facebook.com/docs/reference/opengraph#object-type

apps.saves An action representing someone saving an app to try later.

article This object represents an article on a website. It is the preferred type for blog posts and news stories.

book This object type represents a book or publication. This is an appropriate type for ebooks, as well as traditional paperback or hardback books. Do not use this type to represent magazines

books.author This object type represents a single author of a book.

books.book This object type represents a book or publication. This is an appropriate type for ebooks, as well as traditional paperback or hardback books

books.genre This object type represents the genre of a book or publication.

books.quotes
Returns no data as of April 4, 2018.

An action representing someone quoting from a book.

books.rates
Returns no data as of April 4, 2018.

An action representing someone rating a book.

books.reads
Returns no data as of April 4, 2018.

An action representing someone reading a book.

books.wants_to_read
Returns no data as of April 4, 2018.

An action representing someone wanting to read a book.

business.business This object type represents a place of business that has a location, operating hours and contact information.

fitness.bikes
Returns no data as of April 4, 2018.

An action representing someone cycling a course.

fitness.course This object type represents the user's activity contributing to a particular run, walk, or bike course.

fitness.runs
Returns no data as of April 4, 2018.

An action representing someone running a course.

fitness.walks
Returns no data as of April 4, 2018.

An action representing someone walking a course.

game.achievement This object type represents a specific achievement in a game. An app must be in the 'Games' category in App Dashboard to be able to use this object type. Every achievement has a game:points value associate with it. This is not related to the points the user has scored in the game, but is a way for the app to indicate the relative importance and scarcity of different achievements: * Each game gets a total of 1,000 points to distribute across its achievements * Each game gets a maximum of 1,000 achievements * Achievements which are scarcer and have higher point values will receive more distribution in Facebook's social channels. For example, achievements which have point values of less than 10 will get almost no distribution. Apps should aim for between 50-100 achievements consisting of a mix of 50 (difficult), 25 (medium), and 10 (easy) point value achievements Read more on how to use achievements in this guide.

games.achieves An action representing someone reaching a game achievement.

games.celebrate An action representing someone celebrating a victory in a game.

games.plays An action representing someone playing a game. Stories for this action will only appear in the activity log.

games.saves An action representing someone saving a game.

music.album This object type represents a music album; in other words, an ordered collection of songs from an artist or a collection of artists. An album can comprise multiple discs.

music.listens
Returns no data as of April 4, 2018.

An action representing someone listening to a song, album, radio station, playlist or musician

music.playlist This object type represents a music playlist, an ordered collection of songs from a collection of artists.

music.playlists
Returns no data as of April 4, 2018.

An action representing someone creating a playlist.

music.radio_station This object type represents a 'radio' station of a stream of audio. The audio properties should be used to identify the location of the stream itself.

music.song This object type represents a single song.

news.publishes An action representing someone publishing a news article.

news.reads
Returns no data as of April 4, 2018.

An action representing someone reading a news article.

og.follows An action representing someone following a Facebook user

og.likes An action representing someone liking any object.

pages.saves An action representing someone saving a place.

place This object type represents a place - such as a venue, a business, a landmark, or any other location which can be identified by longitude and latitude.

product This object type represents a product. This includes both virtual and physical products, but it typically represents items that are available in an online store.

product.group This object type represents a group of product items.

product.item This object type represents a product item.

profile This object type represents a person. While appropriate for celebrities, artists, or musicians, this object type can be used for the profile of any individual. The fb:profile_id field associates the object with a Facebook user.

restaurant.menu This object type represents a restaurant's menu. A restaurant can have multiple menus, and each menu has multiple sections.

restaurant.menu_item This object type represents a single item on a restaurant's menu. Every item belongs within a menu section.

restaurant.menu_section This object type represents a section in a restaurant's menu. A section contains multiple menu items.

restaurant.restaurant This object type represents a restaurant at a specific location.

restaurant.visited An action representing someone visiting a restaurant.

restaurant.wants_to_visit An action representing someone wanting to visit a restaurant

sellers.rates An action representing a commerce seller has been given a rating.

video.episode This object type represents an episode of a TV show and contains references to the actors and other professionals involved in its production. An episode is defined by us as a full-length episode that is part of a series. This type must reference the series this it is part of.

video.movie This object type represents a movie, and contains references to the actors and other professionals involved in its production. A movie is defined by us as a full-length feature or short film. Do not use this type to represent movie trailers, movie clips, user-generated video content, etc.

video.other This object type represents a generic video, and contains references to the actors and other professionals involved in its production. For specific types of video content, use the video.movie or video.tv_show object types. This type is for any other type of video content not represented elsewhere (eg. trailers, music videos, clips, news segments etc.)

video.rates
Returns no data as of April 4, 2018.

An action representing someone rating a movie, TV show, episode or another piece of video content.

video.tv_show This object type represents a TV show, and contains references to the actors and other professionals involved in its production. For individual episodes of a series, use the video.episode object type. A TV show is defined by us as a series or set of episodes that are produced under the same title (eg. a television or online series)

video.wants_to_watch
Returns no data as of April 4, 2018.

An action representing someone wanting to watch video content.

video.watches
Returns no data as of April 4, 2018.

An action representing someone watching video content.

How can I remove all my changes in my SVN working directory?

None of the answers here were quite what I wanted. Here's what I came up with:

# Recursively revert any locally-changed files
svn revert -R .

# Delete any other files in the sandbox (including ignored files),
# being careful to handle files with spaces in the name
svn status --no-ignore | grep '^\?' | \
    perl -ne 'print "$1\n" if $_ =~ /^\S+\s+(.*)$/' | \
    tr '\n' '\0' | xargs -0 rm -rf

Tested on Linux; may work in Cygwin, but relies on (I believe) a GNU-specific extension which allows xargs to split based on '\0' instead of whitespace.

The advantage to the above command is that it does not require any network activity to reset the sandbox. You get exactly what you had before, and you lose all your changes. (disclaimer before someone blames me for this code destroying their work) ;-)

I use this script on a continuous integration system where I want to make sure a clean build is performed after running some tests.

Edit: I'm not sure this works with all versions of Subversion. It's not clear if the svn status command is always formatted consistently. Use at your own risk, as with any command that uses such a blanket rm command.

Excel VBA function to print an array to the workbook

On the same theme as other answers, keeping it simple

Sub PrintArray(Data As Variant, Cl As Range)
    Cl.Resize(UBound(Data, 1), UBound(Data, 2)) = Data
End Sub


Sub Test()
    Dim MyArray() As Variant

    ReDim MyArray(1 To 3, 1 To 3) ' make it flexible

    ' Fill array
    '  ...

    PrintArray MyArray, ActiveWorkbook.Worksheets("Sheet1").[A1]
End Sub

How do you get the length of a list in the JSF expression language?

Yes, since some genius in the Java API creation committee decided that, even though certain classes have size() members or length attributes, they won't implement getSize() or getLength() which JSF and most other standards require, you can't do what you want.

There's a couple ways to do this.

One: add a function to your Bean that returns the length:

In class MyBean:
public int getSomelistLength() { return this.somelist.length; }

In your JSF page:
#{MyBean.somelistLength}

Two: If you're using Facelets (Oh, God, why aren't you using Facelets!), you can add the fn namespace and use the length function

In JSF page:
#{ fn:length(MyBean.somelist) }

Read a XML (from a string) and get some fields - Problems reading XML

You should use LoadXml method, not Load:

xmlDoc.LoadXml(myXML); 

Load method is trying to load xml from a file and LoadXml from a string. You could also use XPath:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);

string xpath = "myDataz/listS/sog";
var nodes = xmlDoc.SelectNodes(xpath);

foreach (XmlNode childrenNode in nodes)
{
    HttpContext.Current.Response.Write(childrenNode.SelectSingleNode("//field1").Value);
} 

Jenkins could not run git

I had the correct path to git in Jenkins, but I had not yet accepted the Xcode build tools EULA on a fresh install of OS X Yosemite, so git looked like it was failing in Jenkins. After trying "git --version" on the git at /usr/bin/git in a terminal, I was given a command-line interface to accept the EULA, and then Jenkins could then access the git URL I had given the build project.

Sort a Map<Key, Value> by values

Best Approach

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry; 

public class OrderByValue {

  public static void main(String a[]){
    Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("java", 20);
    map.put("C++", 45);
    map.put("Unix", 67);
    map.put("MAC", 26);
    map.put("Why this kolavari", 93);
    Set<Entry<String, Integer>> set = map.entrySet();
    List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);
    Collections.sort( list, new Comparator<Map.Entry<String, Integer>>()
    {
        public int compare( Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2 )
        {
            return (o1.getValue()).compareTo( o2.getValue() );//Ascending order
            //return (o2.getValue()).compareTo( o1.getValue() );//Descending order
        }
    } );
    for(Map.Entry<String, Integer> entry:list){
        System.out.println(entry.getKey()+" ==== "+entry.getValue());
    }
  }}

Output

java ==== 20

MAC ==== 26

C++ ==== 45

Unix ==== 67

Why this kolavari ==== 93

Attempt by security transparent method 'WebMatrix.WebData.PreApplicationStartCode.Start()'

I installed webapi with it via the helppages nuget package. That package replaced most of the asp.net mvc 4 binaries with beta versions which didn't work well together with the rest of the project. Fix was to restore the original mvc 4 dll's and all was good.

MongoDB - Update objects in a document's array (nested updating)

We can use $set operator to update the nested array inside object filed update the value

db.getCollection('geolocations').update( 
   {
       "_id" : ObjectId("5bd3013ac714ea4959f80115"), 
       "geolocation.country" : "United States of America"
   }, 
   { $set: 
       {
           "geolocation.$.country" : "USA"
       } 
    }, 
   false,
   true
);

A 'for' loop to iterate over an enum in Java

All the constants of an enum type can be obtained by calling the implicit public static T[] values() method of that type:

 for (Direction d : Direction.values()) {
     System.out.println(d);
 }

Regarding C++ Include another class

When you want to convert your code to result( executable, library or whatever ), there is 2 steps:
1) compile
2) link
In first step compiler should now about some things like sizeof objects that used by you, prototype of functions and maybe inheritance. on the other hand linker want to find implementation of functions and global variables in your code.

Now when you use ClassTwo in File1.cpp compiler know nothing about it and don't know how much memory should allocate for it or for example witch members it have or is it a class and enum or even a typedef of int, so compilation will be failed by the compiler. adding File2.cpp solve the problem of linker that look for implementation but the compiler is still unhappy, because it know nothing about your type.

So remember, in compile phase you always work with just one file( and of course files that included by that one file ) and in link phase you need multiple files that contain implementations. and since C/C++ are statically typed and they allow their identifier to work for many purposes( definition, typedef, enum class, ... ) so you should always identify you identifier to the compiler and then use it and as a rule compiler should always know size of your variable!!

Read String line by line

The easiest and most universal approach would be to just use the regex Linebreak matcher \R which matches Any Unicode linebreak sequence:

Pattern NEWLINE = Pattern.compile("\\R")
String lines[] = NEWLINE.split(input)

@see https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/regex/Pattern.html

Is it possible to append Series to rows of DataFrame without making a list first?

Convert the series to a dataframe and transpose it, then append normally.

srs = srs.to_frame().T
df = df.append(srs)

Remove attribute "checked" of checkbox

Try this to check

$('#captureImage').attr("checked",true).checkboxradio("refresh");

and uncheck

$('#captureImage').attr("checked",false).checkboxradio("refresh");  

Printing Java Collections Nicely (toString Doesn't Return Pretty Output)

System.out.println(Collection c) already print any type of collection in readable format. Only if collection contains user defined objects , then you need to implement toString() in user defined class to display content.

Gson: How to exclude specific fields from Serialization without annotations

I used this strategy: i excluded every field which is not marked with @SerializedName annotation, i.e.:

public class Dummy {

    @SerializedName("VisibleValue")
    final String visibleValue;
    final String hiddenValue;

    public Dummy(String visibleValue, String hiddenValue) {
        this.visibleValue = visibleValue;
        this.hiddenValue = hiddenValue;
    }
}


public class SerializedNameOnlyStrategy implements ExclusionStrategy {

    @Override
    public boolean shouldSkipField(FieldAttributes f) {
        return f.getAnnotation(SerializedName.class) == null;
    }

    @Override
    public boolean shouldSkipClass(Class<?> clazz) {
        return false;
    }
}


Gson gson = new GsonBuilder()
                .setExclusionStrategies(new SerializedNameOnlyStrategy())
                .create();

Dummy dummy = new Dummy("I will see this","I will not see this");
String json = gson.toJson(dummy);

It returns

{"VisibleValue":"I will see this"}

Regular Expression to match valid dates

To control a date validity under the following format :

YYYY/MM/DD or YYYY-MM-DD

I would recommand you tu use the following regular expression :

(((19|20)([2468][048]|[13579][26]|0[48])|2000)[/-]02[/-]29|((19|20)[0-9]{2}[/-](0[4678]|1[02])[/-](0[1-9]|[12][0-9]|30)|(19|20)[0-9]{2}[/-](0[1359]|11)[/-](0[1-9]|[12][0-9]|3[01])|(19|20)[0-9]{2}[/-]02[/-](0[1-9]|1[0-9]|2[0-8])))

Matches

2016-02-29 | 2012-04-30 | 2019/09/31

Non-Matches

2016-02-30 | 2012-04-31 | 2019/09/35

You can customise it if you wants to allow only '/' or '-' separators. This RegEx strictly controls the validity of the date and verify 28,30 and 31 days months, even leap years with 29/02 month.

Try it, it works very well and prevent your code from lot of bugs !

FYI : I made a variant for the SQL datetime. You'll find it there (look for my name) : Regular Expression to validate a timestamp

Feedback are welcomed :)

Error:(1, 0) Plugin with id 'com.android.application' not found

This may also happen when you have both settings.gradle and settings.gradle.kts files are present in project root directory (possibly with the same module included). You should only have one of these files.

java.lang.NoClassDefFoundError: Could not initialize class XXX

Just several days ago, I met the same question just like yours. All code runs well on my local machine, but turns out error(noclassdeffound&initialize). So I post my solution, but I don't know why, I merely advance a possibility. I hope someone know will explain this.@John Vint Firstly, I'll show you my problem. My code has static variable and static block both. When I first met this problem, I tried John Vint's solution, and tried to catch the exception. However, I caught nothing. So I thought it is because the static variable(but now I know they are the same thing) and still found nothing. So, I try to find the difference between the linux machine and my computer. Then I found that this problem happens only when several threads run in one process(By the way, the linux machine has double cores and double processes). That means if there are two tasks(both uses the code which has static block or variables) run in the same process, it goes wrong, but if they run in different processes, both of them are ok. In the Linux machine, I use

mvn -U clean  test -Dtest=path 

to run a task, and because my static variable is to start a container(or maybe you initialize a new classloader), so it will stay until the jvm stop, and the jvm stops only when all the tasks in one process stop. Every task will start a new container(or classloader) and it makes the jvm confused. As a result, the error happens. So, how to solve it? My solution is to add a new command to the maven command, and make every task go to the same container.

-Dxxx.version=xxxxx #sorry can't post more

Maybe you have already solved this problem, but still hope it will help others who meet the same problem.

How to redirect all HTTP requests to HTTPS

This is the proper method of redirecting HTTP to HTTPS using .htaccess according to GoDaddy.com. The first line of code is self-explanatory. The second line of code checks to see if HTTPS is off, and if so it redirects HTTP to HTTPS by running the third line of code, otherwise the third line of code is ignored.

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

https://www.godaddy.com/help/redirect-http-to-https-automatically-8828

DataGridView changing cell background color

I finally managed to get it working. Here the code :

private void dgvStatus_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.ColumnIndex != color.Index)
        return;

    e.CellStyle.BackColor = Color.FromArgb(int.Parse(((DataRowView)dgvStatus.Rows[e.RowIndex].DataBoundItem).Row[4].ToString()));
}

if anyone know a better to do this please don't hesitate to post it. I'm open to suggestion

How do I get the position selected in a RecyclerView?

No need to have your ViewHolder implementing View.OnClickListener. You can get directly the clicked position by setting a click listener in the method onCreateViewHolder of RecyclerView.Adapter here is a sample of code :

public class ItemListAdapterRecycler extends RecyclerView.Adapter<ItemViewHolder>
{

    private final List<Item> items;

    public ItemListAdapterRecycler(List<Item> items)
    {
        this.items = items;
    }

    @Override
    public ItemViewHolder onCreateViewHolder(final ViewGroup parent, int viewType)
    {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row, parent, false);

        view.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                int currentPosition = getClickedPosition(view);
                Log.d("DEBUG", "" + currentPosition);
            }
        });

        return new ItemViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ItemViewHolder itemViewHolder, int position)
    {
        ...
    }

    @Override
    public int getItemCount()
    {
        return items.size();
    }

    private int getClickedPosition(View clickedView)
    {
        RecyclerView recyclerView = (RecyclerView) clickedView.getParent();
        ItemViewHolder currentViewHolder = (ItemViewHolder) recyclerView.getChildViewHolder(clickedView);
        return currentViewHolder.getAdapterPosition();
    }

}

Check if an image is loaded (no errors) with jQuery

Using this JavaScript code you can check image is successfully loaded or not.

document.onready = function(e) {
        var imageobj = new Image();
        imageobj.src = document.getElementById('img-id').src;
        if(!imageobj.complete){ 
            alert(imageobj.src+"  -  Not Found");
        }
}

Try out this

Convert string to BigDecimal in java

The BigDecimal(double) constructor can have unpredictable behaviors. It is preferable to use BigDecimal(String) or BigDecimal.valueOf(double).

System.out.println(new BigDecimal(135.69)); //135.68999999999999772626324556767940521240234375
System.out.println(new BigDecimal("135.69")); // 135.69
System.out.println(BigDecimal.valueOf(135.69)); // 135.69

The documentation for BigDecimal(double) explains in detail:

  1. The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.
  2. The String constructor, on the other hand, is perfectly predictable: writing new BigDecimal("0.1") creates a BigDecimal which is exactly equal to 0.1, as one would expect. Therefore, it is generally recommended that the String constructor be used in preference to this one.
  3. When a double must be used as a source for a BigDecimal, note that this constructor provides an exact conversion; it does not give the same result as converting the double to a String using the Double.toString(double) method and then using the BigDecimal(String) constructor. To get that result, use the static valueOf(double) method.

Run jar file in command prompt

java [any other JVM options you need to give it] -jar foo.jar

How to write palindrome in JavaScript

function isPalindrome(str) {
  var isPalindrome = true;

  if(str.length === 2){
    return isPalindrome;
  }
  for(let i = 0, d = str.length - 1; i<(d-i); i++ )
  {
    if(str[i] !== str[d - i] ){
      return !isPalindrome
    }
  }
   return isPalindrome
  }

Empty or Null value display in SSRS text boxes

Try this

=IIF(IsNothing(Fields!MyField.Value)=TRUE,"NA",Fields!MyFields.Value)

Is nested function a good approach when required by only one function?

It's perfectly OK doing it that way, but unless you need to use a closure or return the function I'd probably put in the module level. I imagine in the second code example you mean:

...
some_data = method_b() # not some_data = method_b

otherwise, some_data will be the function.

Having it at the module level will allow other functions to use method_b() and if you're using something like Sphinx (and autodoc) for documentation, it will allow you to document method_b as well.

You also may want to consider just putting the functionality in two methods in a class if you're doing something that can be representable by an object. This contains logic well too if that's all you're looking for.

How to get size in bytes of a CLOB column in Oracle?

Check the LOB segment name from dba_lobs using the table name.

select TABLE_NAME,OWNER,COLUMN_NAME,SEGMENT_NAME from dba_lobs where TABLE_NAME='<<TABLE NAME>>';

Now use the segment name to find the bytes used in dba_segments.

select s.segment_name, s.partition_name, bytes/1048576 "Size (MB)"
from dba_segments s, dba_lobs l
where s.segment_name = l.segment_name
and s.owner = '<< OWNER >> ' order by s.segment_name, s.partition_name;

What primitive data type is time_t?

It's platform-specific. But you can cast it to a known type.

printf("%lld\n", (long long) time(NULL));

How to use ClassLoader.getResources() correctly?

There is no way to recursively search through the classpath. You need to know the Full pathname of a resource to be able to retrieve it in this way. The resource may be in a directory in the file system or in a jar file so it is not as simple as performing a directory listing of "the classpath". You will need to provide the full path of the resource e.g. '/com/mypath/bla.xml'.

For your second question, getResource will return the first resource that matches the given resource name. The order that the class path is searched is given in the javadoc for getResource.

Nested JSON objects - do I have to use arrays for everything?

Every object has to be named inside the parent object:

{ "data": {
    "stuff": {
        "onetype": [
            { "id": 1, "name": "" },
            { "id": 2, "name": "" }
        ],
        "othertype": [
            { "id": 2, "xyz": [-2, 0, 2], "n": "Crab Nebula", "t": 0, "c": 0, "d": 5 }
        ]
    },
    "otherstuff": {
        "thing":
            [[1, 42], [2, 2]]
    }
}
}

So you cant declare an object like this:

var obj = {property1, property2};

It has to be

var obj = {property1: 'value', property2: 'value'};

Spark : how to run spark file from spark shell

Tested on both spark-shell version 1.6.3 and spark2-shell version 2.3.0.2.6.5.179-4, you can directly pipe to the shell's stdin like

spark-shell <<< "1+1"

or in your use case,

spark-shell < file.spark

Is it possible to get only the first character of a String?

String has a charAt method that returns the character at the specified position. Like arrays and Lists, String is 0-indexed, i.e. the first character is at index 0 and the last character is at index length() - 1.

So, assuming getSymbol() returns a String, to print the first character, you could do:

System.out.println(ld.getSymbol().charAt(0)); // char at index 0

class method generates "TypeError: ... got multiple values for keyword argument ..."

just add 'staticmethod' decorator to function and problem is fixed

class foo(object):
    @staticmethod
    def foodo(thing=None, thong='not underwear'):
        print thing if thing else "nothing" 
        print 'a thong is',thong

Font Awesome not working, icons showing as squares

If you are using the version 5.* or greater, then you have to use the

all.css or all.min.css

Including the fontawesome.css does not work as it has no reference to the webfonts folder and there is no reference to the @font-face or font-family

You can inspect this by searching the code for the font-family property in fontawesome.css or fontawesome.min.css

How to change the color of an svg element?

For Example, in your HTML:

<body>
  <svg viewBox="" width="" height="">
    <path id="struct1" fill="#xxxxxx" d="M203.3,71.6c-.........."></path>
  </svg>
</body>

Use jQuery:

$("#struct1").css("fill","<desired colour>");

Windows Bat file optional argument parsing

The selected answer works, but it could use some improvement.

  • The options should probably be initialized to default values.
  • It would be nice to preserve %0 as well as the required args %1 and %2.
  • It becomes a pain to have an IF block for every option, especially as the number of options grows.
  • It would be nice to have a simple and concise way to quickly define all options and defaults in one place.
  • It would be good to support stand-alone options that serve as flags (no value following the option).
  • We don't know if an arg is enclosed in quotes. Nor do we know if an arg value was passed using escaped characters. Better to access an arg using %~1 and enclose the assignment within quotes. Then the batch can rely on the absence of enclosing quotes, but special characters are still generally safe without escaping. (This is not bullet proof, but it handles most situations)

My solution relies on the creation of an OPTIONS variable that defines all of the options and their defaults. OPTIONS is also used to test whether a supplied option is valid. A tremendous amount of code is saved by simply storing the option values in variables named the same as the option. The amount of code is constant regardless of how many options are defined; only the OPTIONS definition has to change.

EDIT - Also, the :loop code must change if the number of mandatory positional arguments changes. For example, often times all arguments are named, in which case you want to parse arguments beginning at position 1 instead of 3. So within the :loop, all 3 become 1, and 4 becomes 2.

@echo off
setlocal enableDelayedExpansion

:: Define the option names along with default values, using a <space>
:: delimiter between options. I'm using some generic option names, but 
:: normally each option would have a meaningful name.
::
:: Each option has the format -name:[default]
::
:: The option names are NOT case sensitive.
::
:: Options that have a default value expect the subsequent command line
:: argument to contain the value. If the option is not provided then the
:: option is set to the default. If the default contains spaces, contains
:: special characters, or starts with a colon, then it should be enclosed
:: within double quotes. The default can be undefined by specifying the
:: default as empty quotes "".
:: NOTE - defaults cannot contain * or ? with this solution.
::
:: Options that are specified without any default value are simply flags
:: that are either defined or undefined. All flags start out undefined by
:: default and become defined if the option is supplied.
::
:: The order of the definitions is not important.
::
set "options=-username:/ -option2:"" -option3:"three word default" -flag1: -flag2:"

:: Set the default option values
for %%O in (%options%) do for /f "tokens=1,* delims=:" %%A in ("%%O") do set "%%A=%%~B"

:loop
:: Validate and store the options, one at a time, using a loop.
:: Options start at arg 3 in this example. Each SHIFT is done starting at
:: the first option so required args are preserved.
::
if not "%~3"=="" (
  set "test=!options:*%~3:=! "
  if "!test!"=="!options! " (
    rem No substitution was made so this is an invalid option.
    rem Error handling goes here.
    rem I will simply echo an error message.
    echo Error: Invalid option %~3
  ) else if "!test:~0,1!"==" " (
    rem Set the flag option using the option name.
    rem The value doesn't matter, it just needs to be defined.
    set "%~3=1"
  ) else (
    rem Set the option value using the option as the name.
    rem and the next arg as the value
    set "%~3=%~4"
    shift /3
  )
  shift /3
  goto :loop
)

:: Now all supplied options are stored in variables whose names are the
:: option names. Missing options have the default value, or are undefined if
:: there is no default.
:: The required args are still available in %1 and %2 (and %0 is also preserved)
:: For this example I will simply echo all the option values,
:: assuming any variable starting with - is an option.
::
set -

:: To get the value of a single parameter, just remember to include the `-`
echo The value of -username is: !-username!

There really isn't that much code. Most of the code above is comments. Here is the exact same code, without the comments.

@echo off
setlocal enableDelayedExpansion

set "options=-username:/ -option2:"" -option3:"three word default" -flag1: -flag2:"

for %%O in (%options%) do for /f "tokens=1,* delims=:" %%A in ("%%O") do set "%%A=%%~B"
:loop
if not "%~3"=="" (
  set "test=!options:*%~3:=! "
  if "!test!"=="!options! " (
      echo Error: Invalid option %~3
  ) else if "!test:~0,1!"==" " (
      set "%~3=1"
  ) else (
      set "%~3=%~4"
      shift /3
  )
  shift /3
  goto :loop
)
set -

:: To get the value of a single parameter, just remember to include the `-`
echo The value of -username is: !-username!


This solution provides Unix style arguments within a Windows batch. This is not the norm for Windows - batch usually has the options preceding the required arguments and the options are prefixed with /.

The techniques used in this solution are easily adapted for a Windows style of options.

  • The parsing loop always looks for an option at %1, and it continues until arg 1 does not begin with /
  • Note that SET assignments must be enclosed within quotes if the name begins with /.
    SET /VAR=VALUE fails
    SET "/VAR=VALUE" works. I am already doing this in my solution anyway.
  • The standard Windows style precludes the possibility of the first required argument value starting with /. This limitation can be eliminated by employing an implicitly defined // option that serves as a signal to exit the option parsing loop. Nothing would be stored for the // "option".


Update 2015-12-28: Support for ! in option values

In the code above, each argument is expanded while delayed expansion is enabled, which means that ! are most likely stripped, or else something like !var! is expanded. In addition, ^ can also be stripped if ! is present. The following small modification to the un-commented code removes the limitation such that ! and ^ are preserved in option values.

@echo off
setlocal enableDelayedExpansion

set "options=-username:/ -option2:"" -option3:"three word default" -flag1: -flag2:"

for %%O in (%options%) do for /f "tokens=1,* delims=:" %%A in ("%%O") do set "%%A=%%~B"
:loop
if not "%~3"=="" (
  set "test=!options:*%~3:=! "
  if "!test!"=="!options! " (
      echo Error: Invalid option %~3
  ) else if "!test:~0,1!"==" " (
      set "%~3=1"
  ) else (
      setlocal disableDelayedExpansion
      set "val=%~4"
      call :escapeVal
      setlocal enableDelayedExpansion
      for /f delims^=^ eol^= %%A in ("!val!") do endlocal&endlocal&set "%~3=%%A" !
      shift /3
  )
  shift /3
  goto :loop
)
goto :endArgs
:escapeVal
set "val=%val:^=^^%"
set "val=%val:!=^!%"
exit /b
:endArgs

set -

:: To get the value of a single parameter, just remember to include the `-`
echo The value of -username is: !-username!

MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

If the mongoDB server is already installed and if you are unable to connect from a remote host then follow the below steps,

Login to your machine, open mongodb configuration file located at /etc/mongod.conf and change the bindIp field to specific ip / 0.0.0.0 , after that restart mongodb server.

    sudo vi /etc/mongod.conf
  • The file should contain the following kind of content:

      systemLog:
          destination: file
          path: "/var/log/mongodb/mongod.log"
          logAppend: true
      storage:
          journal:
              enabled: true
      processManagement:
          fork: true
      net:
          bindIp: 127.0.0.1  // change here to 0.0.0.0
          port: 27017
      setParameter:
          enableLocalhostAuthBypass: false
    
  • Once you change the bindIp, then you have to restart the mongodb, using the following command

      sudo service mongod restart
    
  • Now you'll be able to connect to the mongodb server, from remote server.

Android: resizing imageview in XML

Please try this one works for me:

<ImageView android:id="@+id/image_view"     
  android:layout_width="wrap_content"  
  android:layout_height="wrap_content"  
  android:adjustViewBounds="true"  
  android:maxWidth="60dp" 
  android:layout_gravity="center" 
  android:maxHeight="60dp"  
  android:scaleType="fitCenter"  
  android:src="@drawable/icon"  
  /> 

Difference between string and text in rails?

If you are using postgres use text wherever you can, unless you have a size constraint since there is no performance penalty for text vs varchar

There is no performance difference among these three types, apart from increased storage space when using the blank-padded type, and a few extra CPU cycles to check the length when storing into a length-constrained column. While character(n) has performance advantages in some other database systems, there is no such advantage in PostgreSQL; in fact character(n) is usually the slowest of the three because of its additional storage costs. In most situations text or character varying should be used instead

PostsgreSQL manual

typescript: error TS2693: 'Promise' only refers to a type, but is being used as a value here

I had this error but I resolved it by using this command, my ts file name is promises-fs.ts:

tsc promises-fs.ts --target es6 && node promises-fs.js

and the error is gone

C fopen vs open

If you have a FILE *, you can use functions like fscanf, fprintf and fgets etc. If you have just the file descriptor, you have limited (but likely faster) input and output routines read, write etc.

SQL DROP TABLE foreign key constraint

Removing Referenced FOREIGN KEY Constraints
Assuming there is a parent and child table Relationship in SQL Server:

--First find the name of the Foreign Key Constraint:
  SELECT * 
  FROM sys.foreign_keys
  WHERE referenced_object_id = object_id('States')

--Then Find foreign keys referencing to dbo.Parent(States) table:
   SELECT name AS 'Foreign Key Constraint Name', 
           OBJECT_SCHEMA_NAME(parent_object_id) + '.' + OBJECT_NAME(parent_object_id) AS 'Child Table'
   FROM sys.foreign_keys 
   WHERE OBJECT_SCHEMA_NAME(referenced_object_id) = 'dbo' AND 
              OBJECT_NAME(referenced_object_id) = 'dbo.State'

 -- Drop the foreign key constraint by its name 
   ALTER TABLE dbo.cities DROP CONSTRAINT FK__cities__state__6442E2C9;

 -- You can also use the following T-SQL script to automatically find 
 --and drop all foreign key constraints referencing to the specified parent 
 -- table:

 BEGIN

DECLARE @stmt VARCHAR(300);

-- Cursor to generate ALTER TABLE DROP CONSTRAINT statements  
 DECLARE cur CURSOR FOR
 SELECT 'ALTER TABLE ' + OBJECT_SCHEMA_NAME(parent_object_id) + '.' + 
 OBJECT_NAME(parent_object_id) +
                ' DROP CONSTRAINT ' + name
 FROM sys.foreign_keys 
 WHERE OBJECT_SCHEMA_NAME(referenced_object_id) = 'dbo' AND 
            OBJECT_NAME(referenced_object_id) = 'states';

 OPEN cur;
 FETCH cur INTO @stmt;

 -- Drop each found foreign key constraint 
  WHILE @@FETCH_STATUS = 0
  BEGIN
    EXEC (@stmt);
    FETCH cur INTO @stmt;
  END

  CLOSE cur;
  DEALLOCATE cur;

  END
  GO

--Now you can drop the parent table:

 DROP TABLE states;
--# Command(s) completed successfully.

How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

A date-time object is not a String

The java.sql.Timestamp class has no format. Its toString method generates a String with a format.

Do not conflate a date-time object with a String that may represent its value. A date-time object can parse strings and generate strings but is not itself a string.

java.time

First convert from the troubled old legacy date-time classes to java.time classes. Use the new methods added to the old classes.

Instant instant = mySqlDate.toInstant() ;

Lose the fraction of a second you don't want.

instant = instant.truncatedTo( ChronoUnit.Seconds );

Assign the time zone to adjust from UTC used by Instant.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z );

Generate a String close to your desired output. Replace its T in the middle with a SPACE.

DateTimeFormatter f = DateTimeFormatter.ISO_LOCAL_DATE_TIME ;
String output = zdt.format( f ).replace( "T" , " " );

@Scope("prototype") bean scope not creating new bean

Just because the bean injected into the controller is prototype-scoped doesn't mean the controller is!

how to parse json using groovy

You can map JSON to specific class in Groovy using as operator:

import groovy.json.JsonSlurper

String json = '''
{
  "name": "John",  
  "age": 20
}
'''

def person = new JsonSlurper().parseText(json) as Person 

with(person) {
    assert name == 'John'
    assert age == 20
}

"Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP

I asked a question about this and I was referred to this post with the message:

This question already has an answer here:

“Notice: Undefined variable”, “Notice: Undefined index”, and “Notice: Undefined offset” using PHP

I am sharing my question and solution here:

This is the error:

enter image description here

Line 154 is the problem. This is what I have in line 154:

153    foreach($cities as $key => $city){
154        if(($city != 'London') && ($city != 'Madrid') && ($citiesCounterArray[$key] >= 1)){

I think the problem is that I am writing if conditions for the variable $city, which is not the key but the value in $key => $city. First, could you confirm if that is the cause of the warning? Second, if that is the problem, why is it that I cannot write a condition based on the value? Does it have to be with the key that I need to write the condition?

UPDATE 1: The problem is that when executing $citiesCounterArray[$key], sometimes the $key corresponds to a key that does not exist in the $citiesCounterArray array, but that is not always the case based on the data of my loop. What I need is to set a condition so that if $key exists in the array, then run the code, otherwise, skip it.

UPDATE 2: This is how I fixed it by using array_key_exists():

foreach($cities as $key => $city){
    if(array_key_exists($key, $citiesCounterArray)){
        if(($city != 'London') && ($city != 'Madrid') && ($citiesCounterArray[$key] >= 1)){

How do I use the lines of a file as arguments of a command?

If your shell is bash (amongst others), a shortcut for $(cat afile) is $(< afile), so you'd write:

mycommand "$(< file.txt)"

Documented in the bash man page in the 'Command Substitution' section.

Alterately, have your command read from stdin, so: mycommand < file.txt

Connect Android to WiFi Enterprise network EAP(PEAP)

Finally, I've defeated my CiSCO EAP-FAST corporate wifi network, and all our Android devices are now able to connect to it.

The walk-around I've performed in order to gain access to this kind of networks from an Android device are easiest than you can imagine.

There's a Wifi Config Editor in the Google Play Store you can use to "activate" the secondary CISCO Protocols when you are setting up a EAP wifi connection.

Its name is Wifi Config Advanced Editor.

  • First, you have to setup your wireless network manually as close as you can to your "official" corporate wifi parameters.

  • Save it.

  • Go to the WCE and edit the parameters of the network you have created in the previous step.

  • There are 3 or 4 series of settings you should activate in order to force the Android device to use them as a way to connect (the main site I think you want to visit is Enterprise Configuration, but don't forget to check all the parameters to change them if needed.
    As a suggestion, even if you have a WPA2 EAP-FAST Cipher, try LEAP in your setup. It worked for me as a charm.

  • When you finished to edit the config, go to the main Android wifi controller, and force to connect to this network.

  • Do not Edit the network again with the Android wifi interface.

I have tested it on Samsung Galaxy 1 and 2, Note mobile devices, and on a Lenovo Thinkpad Tablet.

Variable interpolation in the shell

In Bash:

tail -1 ${filepath}_newstap.sh

How to convert a HTMLElement to a string

The element outerHTML property (note: supported by Firefox after version 11) returns the HTML of the entire element.

Example

<div id="new-element-1">Hello world.</div>

<script type="text/javascript"><!--

var element = document.getElementById("new-element-1");
var elementHtml = element.outerHTML;
// <div id="new-element-1">Hello world.</div>

--></script>

Similarly, you can use innerHTML to get the HTML contained within a given element, or innerText to get the text inside an element (sans HTML markup).

See Also

  1. outerHTML - Javascript Property
  2. Javascript Reference - Elements

Casting a number to a string in TypeScript

"Casting" is different than conversion. In this case, window.location.hash will auto-convert a number to a string. But to avoid a TypeScript compile error, you can do the string conversion yourself:

window.location.hash = ""+page_number; 
window.location.hash = String(page_number); 

These conversions are ideal if you don't want an error to be thrown when page_number is null or undefined. Whereas page_number.toString() and page_number.toLocaleString() will throw when page_number is null or undefined.

When you only need to cast, not convert, this is how to cast to a string in TypeScript:

window.location.hash = <string>page_number; 
// or 
window.location.hash = page_number as string;

The <string> or as string cast annotations tell the TypeScript compiler to treat page_number as a string at compile time; it doesn't convert at run time.

However, the compiler will complain that you can't assign a number to a string. You would have to first cast to <any>, then to <string>:

window.location.hash = <string><any>page_number;
// or
window.location.hash = page_number as any as string;

So it's easier to just convert, which handles the type at run time and compile time:

window.location.hash = String(page_number); 

(Thanks to @RuslanPolutsygan for catching the string-number casting issue.)

Python: finding an element in a list

I found this by adapting some tutos. Thanks to google, and to all of you ;)

def findall(L, test):
    i=0
    indices = []
    while(True):
        try:
            # next value in list passing the test
            nextvalue = filter(test, L[i:])[0]

            # add index of this value in the index list,
            # by searching the value in L[i:] 
            indices.append(L.index(nextvalue, i))

            # iterate i, that is the next index from where to search
            i=indices[-1]+1
        #when there is no further "good value", filter returns [],
        # hence there is an out of range exeption
        except IndexError:
            return indices

A very simple use:

a = [0,0,2,1]
ind = findall(a, lambda x:x>0))

[2, 3]

P.S. scuse my english

Can't draw Histogram, 'x' must be numeric

Use the dec argument to set "," as the decimal point by adding:

 ce <- read.table("file.txt", header = TRUE, dec = ",")

How to fix System.NullReferenceException: Object reference not set to an instance of an object

During debug, break on all exceptions thrown. Debug->Exceptions

Check all 'Thrown' exceptions. F5, the code will stop on the offending line.

pythonic way to do something N times without an index variable?

I just use for _ in range(n), it's straight to the point. It's going to generate the entire list for huge numbers in Python 2, but if you're using Python 3 it's not a problem.

Get file name from URL

Urls can have parameters in the end, this

 /**
 * Getting file name from url without extension
 * @param url string
 * @return file name
 */
public static String getFileName(String url) {
    String fileName;
    int slashIndex = url.lastIndexOf("/");
    int qIndex = url.lastIndexOf("?");
    if (qIndex > slashIndex) {//if has parameters
        fileName = url.substring(slashIndex + 1, qIndex);
    } else {
        fileName = url.substring(slashIndex + 1);
    }
    if (fileName.contains(".")) {
        fileName = fileName.substring(0, fileName.lastIndexOf("."));
    }

    return fileName;
}

Convert char to int in C#

This will convert it to an int:

char foo = '2';
int bar = foo - '0';

This works because each character is internally represented by a number. The characters '0' to '9' are represented by consecutive numbers, so finding the difference between the characters '0' and '2' results in the number 2.

Change status bar color with AppCompat ActionBarActivity

I don't think the status bar color has been implemented in AppCompat yet. These are the attributes which are available:

    <!-- ============= -->
    <!-- Color palette -->
    <!-- ============= -->

    <!-- The primary branding color for the app. By default, this is the color applied to the
         action bar background. -->
    <attr name="colorPrimary" format="color" />

    <!-- Dark variant of the primary branding color. By default, this is the color applied to
         the status bar (via statusBarColor) and navigation bar (via navigationBarColor). -->
    <attr name="colorPrimaryDark" format="color" />

    <!-- Bright complement to the primary branding color. By default, this is the color applied
         to framework controls (via colorControlActivated). -->
    <attr name="colorAccent" format="color" />

    <!-- The color applied to framework controls in their normal state. -->
    <attr name="colorControlNormal" format="color" />

    <!-- The color applied to framework controls in their activated (ex. checked) state. -->
    <attr name="colorControlActivated" format="color" />

    <!-- The color applied to framework control highlights (ex. ripples, list selectors). -->
    <attr name="colorControlHighlight" format="color" />

    <!-- The color applied to framework buttons in their normal state. -->
    <attr name="colorButtonNormal" format="color" />

    <!-- The color applied to framework switch thumbs in their normal state. -->
    <attr name="colorSwitchThumbNormal" format="color" />

(From \sdk\extras\android\support\v7\appcompat\res\values\attrs.xml)

Amazon S3 and Cloudfront cache, how to clear cache or synchronize their cache

S3 is not used for real time development but if you really want to test your freshly deployed website use

http://yourdomain.com/index.html?v=2
http://yourdomain.com/init.js?v=2

Adding a version parameter in the end will stop using the cached version of the file and the browser will get a fresh copy of the file from the server bucket

Check for database connection, otherwise display message

Please check this:

$servername='localhost';
$username='root';
$password='';
$databasename='MyDb';

$connection = mysqli_connect($servername,$username,$password);

if (!$connection) {
die("Connection failed: " . $conn->connect_error);
}

/*mysqli_query($connection, "DROP DATABASE if exists MyDb;");

if(!mysqli_query($connection, "CREATE DATABASE MyDb;")){
echo "Error creating database: " . $connection->error;
}

mysqli_query($connection, "use MyDb;");
mysqli_query($connection, "DROP TABLE if exists employee;");

$table="CREATE TABLE employee (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)"; 
$value="INSERT INTO employee (firstname,lastname,email) VALUES ('john', 'steve', '[email protected]')";
if(!mysqli_query($connection, $table)){echo "Error creating table: " . $connection->error;}
if(!mysqli_query($connection, $value)){echo "Error inserting values: " . $connection->error;}*/

What is an alternative to execfile in Python 3?

You could write your own function:

def xfile(afile, globalz=None, localz=None):
    with open(afile, "r") as fh:
        exec(fh.read(), globalz, localz)

If you really needed to...

Return None if Dictionary key is not available

For those using the dict.get technique for nested dictionaries, instead of explicitly checking for every level of the dictionary, or extending the dict class, you can set the default return value to an empty dictionary except for the out-most level. Here's an example:

my_dict = {'level_1': {
             'level_2': {
                  'level_3': 'more_data'
                  }
              }
           }
result = my_dict.get('level_1', {}).get('level_2', {}).get('level_3')
# result -> 'more_data'
none_result = my_dict.get('level_1', {}).get('what_level', {}).get('level_3')
# none_result -> None

WARNING: Please note that this technique only works if the expected key's value is a dictionary. If the key what_level did exist in the dictionary but its value was a string or integer etc., then it would've raised an AttributeError.

pandas GroupBy columns with NaN (missing) values

This is mentioned in the Missing Data section of the docs:

NA groups in GroupBy are automatically excluded. This behavior is consistent with R

One workaround is to use a placeholder before doing the groupby (e.g. -1):

In [11]: df.fillna(-1)
Out[11]: 
   a   b
0  1   4
1  2  -1
2  3   6

In [12]: df.fillna(-1).groupby('b').sum()
Out[12]: 
    a
b    
-1  2
4   1
6   3

That said, this feels pretty awful hack... perhaps there should be an option to include NaN in groupby (see this github issue - which uses the same placeholder hack).

However, as described in another answer, "from pandas 1.1 you have better control over this behavior, NA values are now allowed in the grouper using dropna=False"

How to check if an object is a list or tuple (but not string)?

assert (type(lst) == list) | (type(lst) == tuple), "Not a valid lst type, cannot be string"

String Comparison in Java

Java lexicographically order:

  1. Numbers -before-
  2. Uppercase -before-
  3. Lowercase

Odd as this seems, it is true...
I have had to write comparator chains to be able to change the default behavior.
Play around with the following snippet with better examples of input strings to verify the order (you will need JSE 8):

import java.util.ArrayList;

public class HelloLambda {

public static void main(String[] args) {
    ArrayList<String> names = new ArrayList<>();
    names.add("Kambiz");
    names.add("kambiz");
    names.add("k1ambiz");
    names.add("1Bmbiza");
    names.add("Samantha");
    names.add("Jakey");
    names.add("Lesley");
    names.add("Hayley");
    names.add("Benjamin");
    names.add("Anthony");

    names.stream().
        filter(e -> e.contains("a")).
        sorted().
        forEach(System.out::println);
}
}

Result

1Bmbiza
Benjamin
Hayley
Jakey
Kambiz
Samantha
k1ambiz
kambiz

Please note this is answer is Locale specific.
Please note that I am filtering for a name containing the lowercase letter a.

How to execute UNION without sorting? (SQL)

I notice this question gets quite a lot of views so I'll first address a question you didn't ask!

Regarding the title. To achieve a "Sql Union All with “distinct”" then simply replace UNION ALL with UNION. This has the effect of removing duplicates.

For your specific question, given the clarification "The first query should have "priority", so duplicates should be removed from bottom" you can use

SELECT col1,
       col2,
       MIN(grp) AS source_group
FROM   (SELECT 1 AS grp,
               col1,
               col2
        FROM   t1
        UNION ALL
        SELECT 2 AS grp,
               col1,
               col2
        FROM   t2) AS t
GROUP  BY col1,
          col2
ORDER  BY MIN(grp),
          col1  

SyntaxError: expected expression, got '<'

I solved this problem with my authenticated ASPNET application by adding WebResource.axd as a location on the web.config so that it's authorized for anonymous users

<location path="WebResource.axd">
  <system.web>
    <authorization>
      <allow users="?"/>
    </authorization>
  </system.web>
</location>

How to get the first 2 letters of a string in Python?

to print first two letter of a string

str = "string"

print(str[0:2])

How to delete a cookie using jQuery?

To delete a cookie with JQuery, set the value to null:

$.cookie("name", null, { path: '/' });

Edit: The final solution was to explicitly specify the path property whenever accessing the cookie, because the OP accesses the cookie from multiple pages in different directories, and thus the default paths were different (this was not described in the original question). The solution was discovered in discussion below, which explains why this answer was accepted - despite not being correct.

For some versions jQ cookie the solution above will set the cookie to string null. Thus not removing the cookie. Use the code as suggested below instead.

$.removeCookie('the_cookie', { path: '/' });

What is the purpose of class methods?

A class defines a set of instances, of course. And the methods of a class work on the individual instances. The class methods (and variables) a place to hang other information that is related to the set of instances over all.

For example if your class defines a the set of students you might want class variables or methods which define things like the set of grade the students can be members of.

You can also use class methods to define tools for working on the entire set. For example Student.all_of_em() might return all the known students. Obviously if your set of instances have more structure than just a set you can provide class methods to know about that structure. Students.all_of_em(grade='juniors')

Techniques like this tend to lead to storing members of the set of instances into data structures that are rooted in class variables. You need to take care to avoid frustrating the garbage collection then.

registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later

For the Swift-inclined:

if let registration: AnyObject = NSClassFromString("UIUserNotificationSettings") { // iOS 8+
    let notificationTypes: UIUserNotificationType = (.Alert | .Badge | .Sound)
    let notificationSettings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil)

    application.registerUserNotificationSettings(notificationSettings)
} else { // iOS 7
    application.registerForRemoteNotificationTypes(.Alert | .Badge | .Sound)
}

How can I remove all objects but one from the workspace in R?

Using the keep function from the gdata package is quite convenient.

> ls()
[1] "a" "b" "c"

library(gdata)
> keep(a) #shows you which variables will be removed
[1] "b" "c"
> keep(a, sure = TRUE) # setting sure to TRUE removes variables b and c
> ls()
[1] "a"

Factorial using Recursion in Java

public class Factorial {

    public static void main(String[] args) {
        System.out.println(factorial(4));
    }

    private static long factorial(int i) {

        if(i<0)  throw new IllegalArgumentException("x must be >= 0"); 
        return i==0||i==1? 1:i*factorial(i-1);
    }
}

Use string contains function in oracle SQL query

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

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

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

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

For the special character, you can do:

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

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

Java FileReader encoding issue

Since Java 11 you may use that:

public FileReader(String fileName, Charset charset) throws IOException;

How to write data to a JSON file using Javascript

JSON can be written into local storage using the JSON.stringify to serialize a JS object. You cannot write to a JSON file using only JS. Only cookies or local storage

    var obj = {"nissan": "sentra", "color": "green"};

localStorage.setItem('myStorage', JSON.stringify(obj));

And to retrieve the object later

var obj = JSON.parse(localStorage.getItem('myStorage'));

SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens on line 102

You didn't bind all your bindings here

$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate     FROM comments WHERE articleid = :art 
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";

$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );

You've declared a binding called :numRows but you never actually bind anything to it.

UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion

Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.

In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)

How to check if a file exists in Go?

What other answers missed, is that the path given to the function could actually be a directory. Following function makes sure, that the path is really a file.

func fileExists(filename string) bool {
    info, err := os.Stat(filename)
    if os.IsNotExist(err) {
        return false
    }
    return !info.IsDir()
}

Another thing to point out: This code could still lead to a race condition, where another thread or process deletes or creates the specified file, while the fileExists function is running.

If you're worried about this, use a lock in your threads, serialize the access to this function or use an inter-process semaphore if multiple applications are involved. If other applications are involved, outside of your control, you're out of luck, I guess.

Jquery button click() function is not working

You need to use the event delegation syntax of .on() here. Change:

$("#add").click(function() {

to

$("#buildyourform").on('click', '#add', function () {

jsFiddle example

download a file from Spring boot rest service

Option 1 using an InputStreamResource

Resource implementation for a given InputStream.

Should only be used if no other specific Resource implementation is > applicable. In particular, prefer ByteArrayResource or any of the file-based Resource implementations where possible.

@RequestMapping(path = "/download", method = RequestMethod.GET)
public ResponseEntity<Resource> download(String param) throws IOException {

    // ...

    InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

    return ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.length())
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(resource);
}

Option2 as the documentation of the InputStreamResource suggests - using a ByteArrayResource:

@RequestMapping(path = "/download", method = RequestMethod.GET)
public ResponseEntity<Resource> download(String param) throws IOException {

    // ...

    Path path = Paths.get(file.getAbsolutePath());
    ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));

    return ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.length())
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(resource);
}

How to get all files under a specific directory in MATLAB?

Update: Given that this post is quite old, and I've modified this utility a lot for my own use during that time, I thought I should post a new version. My newest code can be found on The MathWorks File Exchange: dirPlus.m. You can also get the source from GitHub.

I made a number of improvements. It now gives you options to prepend the full path or return just the file name (incorporated from Doresoom and Oz Radiano) and apply a regular expression pattern to the file names (incorporated from Peter D). In addition, I added the ability to apply a validation function to each file, allowing you to select them based on criteria other than just their names (i.e. file size, content, creation date, etc.).


NOTE: In newer versions of MATLAB (R2016b and later), the dir function has recursive search capabilities! So you can do this to get a list of all *.m files in all subfolders of the current folder:

dirData = dir('**/*.m');

Old code: (for posterity)

Here's a function that searches recursively through all subdirectories of a given directory, collecting a list of all file names it finds:

function fileList = getAllFiles(dirName)

  dirData = dir(dirName);      %# Get the data for the current directory
  dirIndex = [dirData.isdir];  %# Find the index for directories
  fileList = {dirData(~dirIndex).name}';  %'# Get a list of the files
  if ~isempty(fileList)
    fileList = cellfun(@(x) fullfile(dirName,x),...  %# Prepend path to files
                       fileList,'UniformOutput',false);
  end
  subDirs = {dirData(dirIndex).name};  %# Get a list of the subdirectories
  validIndex = ~ismember(subDirs,{'.','..'});  %# Find index of subdirectories
                                               %#   that are not '.' or '..'
  for iDir = find(validIndex)                  %# Loop over valid subdirectories
    nextDir = fullfile(dirName,subDirs{iDir});    %# Get the subdirectory path
    fileList = [fileList; getAllFiles(nextDir)];  %# Recursively call getAllFiles
  end

end

After saving the above function somewhere on your MATLAB path, you can call it in the following way:

fileList = getAllFiles('D:\dic');

How to read a specific line using the specific line number from a file in Java?

It works for me: I have combined the answer of Reading a simple text file

But instead of return a String I am returning a LinkedList of Strings. Then I can select the line that I want.

public static LinkedList<String> readFromAssets(Context context, String filename) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(context.getAssets().open(filename)));
    LinkedList<String>linkedList = new LinkedList<>();
    // do reading, usually loop until end of file reading
    StringBuilder sb = new StringBuilder();
    String mLine = reader.readLine();
    while (mLine != null) {
        linkedList.add(mLine);
        sb.append(mLine); // process line
        mLine = reader.readLine();


    }
    reader.close();
    return linkedList;
}

Convenient C++ struct initialisation

I know this question is old, but there is a way to solve this until C++20 finally brings this feature from C to C++. What you can do to solve this is use preprocessor macros with static_asserts to check your initialization is valid. (I know macros are generally bad, but here I don't see another way.) See example code below:

#define INVALID_STRUCT_ERROR "Instantiation of struct failed: Type, order or number of attributes is wrong."

#define CREATE_STRUCT_1(type, identifier, m_1, p_1) \
{ p_1 };\
static_assert(offsetof(type, m_1) == 0, INVALID_STRUCT_ERROR);\

#define CREATE_STRUCT_2(type, identifier, m_1, p_1, m_2, p_2) \
{ p_1, p_2 };\
static_assert(offsetof(type, m_1) == 0, INVALID_STRUCT_ERROR);\
static_assert(offsetof(type, m_2) >= sizeof(identifier.m_1), INVALID_STRUCT_ERROR);\

#define CREATE_STRUCT_3(type, identifier, m_1, p_1, m_2, p_2, m_3, p_3) \
{ p_1, p_2, p_3 };\
static_assert(offsetof(type, m_1) == 0, INVALID_STRUCT_ERROR);\
static_assert(offsetof(type, m_2) >= sizeof(identifier.m_1), INVALID_STRUCT_ERROR);\
static_assert(offsetof(type, m_3) >= (offsetof(type, m_2) + sizeof(identifier.m_2)), INVALID_STRUCT_ERROR);\

#define CREATE_STRUCT_4(type, identifier, m_1, p_1, m_2, p_2, m_3, p_3, m_4, p_4) \
{ p_1, p_2, p_3, p_4 };\
static_assert(offsetof(type, m_1) == 0, INVALID_STRUCT_ERROR);\
static_assert(offsetof(type, m_2) >= sizeof(identifier.m_1), INVALID_STRUCT_ERROR);\
static_assert(offsetof(type, m_3) >= (offsetof(type, m_2) + sizeof(identifier.m_2)), INVALID_STRUCT_ERROR);\
static_assert(offsetof(type, m_4) >= (offsetof(type, m_3) + sizeof(identifier.m_3)), INVALID_STRUCT_ERROR);\

// Create more macros for structs with more attributes...

Then when you have a struct with const attributes, you can do this:

struct MyStruct
{
    const int attr1;
    const float attr2;
    const double attr3;
};

const MyStruct test = CREATE_STRUCT_3(MyStruct, test, attr1, 1, attr2, 2.f, attr3, 3.);

It's a bit inconvenient, because you need macros for every possible number of attributes and you need to repeat the type and name of your instance in the macro call. Also you cannot use the macro in a return statement, because the asserts come after the initialization.

But it does solve your problem: When you change the struct, the call will fail at compile-time.

If you use C++17, you can even make these macros more strict by forcing the same types, e.g.:

#define CREATE_STRUCT_3(type, identifier, m_1, p_1, m_2, p_2, m_3, p_3) \
{ p_1, p_2, p_3 };\
static_assert(offsetof(type, m_1) == 0, INVALID_STRUCT_ERROR);\
static_assert(offsetof(type, m_2) >= sizeof(identifier.m_1), INVALID_STRUCT_ERROR);\
static_assert(offsetof(type, m_3) >= (offsetof(type, m_2) + sizeof(identifier.m_2)), INVALID_STRUCT_ERROR);\
static_assert(typeid(p_1) == typeid(identifier.m_1), INVALID_STRUCT_ERROR);\
static_assert(typeid(p_2) == typeid(identifier.m_2), INVALID_STRUCT_ERROR);\
static_assert(typeid(p_3) == typeid(identifier.m_3), INVALID_STRUCT_ERROR);\

What is the Gradle artifact dependency graph command?

For those looking to debug gradle dependencies in react-native projects, the command is (executed from projectname/android)

./gradlew app:dependencies --configuration compile

Running Node.Js on Android

J2V8 is best solution of your problem. It's run Nodejs application on jvm(java and android).

J2V8 is Java Bindings for V8, But Node.js integration is available in J2V8 (version 4.4.0)

Github : https://github.com/eclipsesource/J2V8

Example : http://eclipsesource.com/blogs/2016/07/20/running-node-js-on-the-jvm/

How to download Visual Studio Community Edition 2015 (not 2017)

You can use these links to download Visual Studio 2015

Community Edition:

And for anyone in the future who might be looking for the other editions here are the links for them as well:

Professional Edition:

Enterprise Edition:

Split string into array of characters?

the problem is that there is no built in method (or at least none of us could find one) to do this in vb. However, there is one to split a string on the spaces, so I just rebuild the string and added in spaces....

Private Function characterArray(ByVal my_string As String) As String()
  'create a temporary string to store a new string of the same characters with spaces
  Dim tempString As String = ""
  'cycle through the characters and rebuild my_string as a string with spaces 
  'and assign the result to tempString.  
  For Each c In my_string
     tempString &= c & " "
  Next
  'return return tempString as a character array.  
  Return tempString.Split()
End Function

What are the Differences Between "php artisan dump-autoload" and "composer dump-autoload"?

Laravel's Autoload is a bit different:

1) It will in fact use Composer for some stuff

2) It will call Composer with the optimize flag

3) It will 'recompile' loads of files creating the huge bootstrap/compiled.php

4) And also will find all of your Workbench packages and composer dump-autoload them, one by one.

Where in memory are my variables stored in C?

Corrected your wrong sentences

constant data types ----->  code //wrong

local constant variables -----> stack

initialized global constant variable -----> data segment

uninitialized global constant variable -----> bss

variables declared and defined in main function  ----->  heap //wrong

variables declared and defined in main function -----> stack

pointers(ex:char *arr,int *arr) ------->  heap //wrong

dynamically allocated space(using malloc,calloc) --------> stack //wrong

pointers(ex:char *arr,int *arr) -------> size of that pointer variable will be in stack.

Consider that you are allocating memory of n bytes (using malloc or calloc) dynamically and then making pointer variable to point it. Now that n bytes of memory are in heap and the pointer variable requries 4 bytes (if 64 bit machine 8 bytes) which will be in stack to store the starting pointer of the n bytes of memory chunk.

Note : Pointer variables can point the memory of any segment.

int x = 10;
void func()
{
int a = 0;
int *p = &a: //Now its pointing the memory of stack
int *p2 = &x; //Now its pointing the memory of data segment
chat *name = "ashok" //Now its pointing the constant string literal 
                     //which is actually present in text segment.
char *name2 = malloc(10); //Now its pointing memory in heap
...
}

dynamically allocated space(using malloc,calloc) --------> heap

link_to image tag. how to add class to a tag

hi you can try doing this

link_to image_tag("Search.png", border: 0), {action: 'search', controller: 'pages'}, {class: 'dock-item'}

or even

link_to image_tag("Search.png", border: 0), {action: 'search', controller: 'pages'}, class: 'dock-item'

note that the position of the curly braces is very important, because if you miss them out, rails will assume they form a single hash parameters (read more about this here)

and according to the api for link_to:

link_to(name, options = {}, html_options = nil)
  1. the first parameter is the string to be shown (or it can be an image_tag as well)
  2. the second is the parameter for the url of the link
  3. the last item is the optional parameter for declaring the html tag, e.g. class, onchange, etc.

hope it helps! =)

Put request with simple string as request body

This worked for me:

export function modalSave(name,id){
  console.log('modalChanges action ' + name+id);  

  return {
    type: 'EDIT',
    payload: new Promise((resolve, reject) => {
      const value = {
        Name: name,
        ID: id,
      } 

      axios({
        method: 'put',
        url: 'http://localhost:53203/api/values',
        data: value,
        config: { headers: {'Content-Type': 'multipart/form-data' }}
      })
       .then(function (response) {
         if (response.status === 200) {
           console.log("Update Success");
           resolve();
         }
       })
       .catch(function (response) {
         console.log(response);
         resolve();
       });
    })
  };
}

Displaying a message in iOS which has the same functionality as Toast in Android

If you want one with iOS Style, download this framework from Github

iOS Toast Alert View Framework

This examples work on you UIViewController, once you imported the Framework.

Example 1:

//Manual 
let tav = ToastAlertView()
tav.message = "Hey!"
tav.image = UIImage(named: "img1")!
tav.show()
//tav.dismiss() to Hide

Example 2:

//Toast Alert View with Time Dissmis Only
self.showToastAlert("5 Seconds",
                image: UIImage(named: "img1")!,
                hideWithTap: false,
                hideWithTime: true,
                hideTime: 5.0)

Final:

Toast Alert View Image Example

How to read/write from/to file using Go?

Let's make a Go 1-compatible list of all the ways to read and write files in Go.

Because file API has changed recently and most other answers don't work with Go 1. They also miss bufio which is important IMHO.

In the following examples I copy a file by reading from it and writing to the destination file.

Start with the basics

package main

import (
    "io"
    "os"
)

func main() {
    // open input file
    fi, err := os.Open("input.txt")
    if err != nil {
        panic(err)
    }
    // close fi on exit and check for its returned error
    defer func() {
        if err := fi.Close(); err != nil {
            panic(err)
        }
    }()

    // open output file
    fo, err := os.Create("output.txt")
    if err != nil {
        panic(err)
    }
    // close fo on exit and check for its returned error
    defer func() {
        if err := fo.Close(); err != nil {
            panic(err)
        }
    }()

    // make a buffer to keep chunks that are read
    buf := make([]byte, 1024)
    for {
        // read a chunk
        n, err := fi.Read(buf)
        if err != nil && err != io.EOF {
            panic(err)
        }
        if n == 0 {
            break
        }

        // write a chunk
        if _, err := fo.Write(buf[:n]); err != nil {
            panic(err)
        }
    }
}

Here I used os.Open and os.Create which are convenient wrappers around os.OpenFile. We usually don't need to call OpenFile directly.

Notice treating EOF. Read tries to fill buf on each call, and returns io.EOF as error if it reaches end of file in doing so. In this case buf will still hold data. Consequent calls to Read returns zero as the number of bytes read and same io.EOF as error. Any other error will lead to a panic.

Using bufio

package main

import (
    "bufio"
    "io"
    "os"
)

func main() {
    // open input file
    fi, err := os.Open("input.txt")
    if err != nil {
        panic(err)
    }
    // close fi on exit and check for its returned error
    defer func() {
        if err := fi.Close(); err != nil {
            panic(err)
        }
    }()
    // make a read buffer
    r := bufio.NewReader(fi)

    // open output file
    fo, err := os.Create("output.txt")
    if err != nil {
        panic(err)
    }
    // close fo on exit and check for its returned error
    defer func() {
        if err := fo.Close(); err != nil {
            panic(err)
        }
    }()
    // make a write buffer
    w := bufio.NewWriter(fo)

    // make a buffer to keep chunks that are read
    buf := make([]byte, 1024)
    for {
        // read a chunk
        n, err := r.Read(buf)
        if err != nil && err != io.EOF {
            panic(err)
        }
        if n == 0 {
            break
        }

        // write a chunk
        if _, err := w.Write(buf[:n]); err != nil {
            panic(err)
        }
    }

    if err = w.Flush(); err != nil {
        panic(err)
    }
}

bufio is just acting as a buffer here, because we don't have much to do with data. In most other situations (specially with text files) bufio is very useful by giving us a nice API for reading and writing easily and flexibly, while it handles buffering behind the scenes.


Note: The following code is for older Go versions (Go 1.15 and before). Things have changed. For the new way, take a look at this answer.

Using ioutil

package main

import (
    "io/ioutil"
)

func main() {
    // read the whole file at once
    b, err := ioutil.ReadFile("input.txt")
    if err != nil {
        panic(err)
    }

    // write the whole body at once
    err = ioutil.WriteFile("output.txt", b, 0644)
    if err != nil {
        panic(err)
    }
}

Easy as pie! But use it only if you're sure you're not dealing with big files.

babel-loader jsx SyntaxError: Unexpected token

This works perfect for me

{
    test: /\.(js|jsx)$/,
    loader: 'babel-loader',
    exclude: /node_modules/,
    query: {
        presets: ['es2015','react']
    }
},

Build Maven Project Without Running Unit Tests

I like short version: mvn clean install -DskipTests

It's work too: mvn clean install -DskipTests=true

If you absolutely must, you can also use the maven.test.skip property to skip compiling the tests. maven.test.skip is honored by Surefire, Failsafe and the Compiler Plugin. mvn clean install -Dmaven.test.skip=true

and you can add config in maven.xml

<project>
      [...]
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.16</version>
            <configuration>
              <skipTests>true</skipTests>
            </configuration>
          </plugin>
        </plugins>
      </build>
      [...]
    </project>

How to force a html5 form validation without submitting it via jQuery

below code works for me,

$("#btn").click(function () {

    if ($("#frm")[0].checkValidity())
        alert('sucess');
    else
        //Validate Form
        $("#frm")[0].reportValidity()

});

git stash -> merge stashed change with current changes

you can easily

  1. Commit your current changes
  2. Unstash your stash and resolve conflicts
  3. Commit changes from stash
  4. Soft reset to commit you are comming from (last correct commit)

Android Material: Status bar color won't change

This solution sets the statusbar color of Lollipop, Kitkat and some pre Lollipop devices (Samsung and Sony). The SystemBarTintManager is managing the Kitkat devices ;)

@Override
protected void onCreate( Bundle savedInstanceState ) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    hackStatusBarColor(this, R.color.primary_dark);
}

@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
public static View hackStatusBarColor( final Activity act, final int colorResID ) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        try {

            if (act.getWindow() != null) {

                final ViewGroup vg = (ViewGroup) act.getWindow().getDecorView();
                if (vg.getParent() == null && applyColoredStatusBar(act, colorResID)) {
                    final View statusBar = new View(act);

                    vg.post(new Runnable() {
                        @Override
                        public void run() {

                            int statusBarHeight = (int) Math.ceil(25 * vg.getContext().getResources().getDisplayMetrics().density);
                            statusBar.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, statusBarHeight));
                            statusBar.setBackgroundColor(act.getResources().getColor(colorResID));
                            statusBar.setId(13371337);
                            vg.addView(statusBar, 0);
                        }
                    });
                    return statusBar;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    else if (act.getWindow() != null) {
        act.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        act.getWindow().setStatusBarColor(act.getResources().getColor(colorResID));
    }
    return null;
}

private static boolean applyColoredStatusBar( Activity act, int colorResID ) {
    final Window window = act.getWindow();
    final int flag;
    if (window != null) {
        View decor = window.getDecorView();
        if (decor != null) {
            flag = resolveTransparentStatusBarFlag(act);

            if (flag != 0) {
                decor.setSystemUiVisibility(flag);
                return true;
            }
            else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
                act.findViewById(android.R.id.content).setFitsSystemWindows(false);
                setTranslucentStatus(window, true);
                final SystemBarTintManager tintManager = new SystemBarTintManager(act);
                tintManager.setStatusBarTintEnabled(true);
                tintManager.setStatusBarTintColor(colorResID);
            }
        }
    }
    return false;
}

public static int resolveTransparentStatusBarFlag( Context ctx ) {
    String[] libs = ctx.getPackageManager().getSystemSharedLibraryNames();
    String reflect = null;

    if (libs == null)
        return 0;

    final String SAMSUNG = "touchwiz";
    final String SONY = "com.sonyericsson.navigationbar";

    for (String lib : libs) {

        if (lib.equals(SAMSUNG)) {
            reflect = "SYSTEM_UI_FLAG_TRANSPARENT_BACKGROUND";
        }
        else if (lib.startsWith(SONY)) {
            reflect = "SYSTEM_UI_FLAG_TRANSPARENT";
        }
    }

    if (reflect == null)
        return 0;

    try {
        Field field = View.class.getField(reflect);
        if (field.getType() == Integer.TYPE) {
            return field.getInt(null);
        }
    } catch (Exception e) {
    }

    return 0;
}

@TargetApi(Build.VERSION_CODES.KITKAT)
public static void setTranslucentStatus( Window win, boolean on ) {
    WindowManager.LayoutParams winParams = win.getAttributes();
    final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
    if (on) {
        winParams.flags |= bits;
    }
    else {
        winParams.flags &= ~bits;
    }
    win.setAttributes(winParams);
}

How to check if MySQL returns null/empty?

Suppose

$row=mysql_fetch_row($rc)
and if you want to check if row[8] is null then do
$field=$row[8];
   if($field)
echo "";
else
 echo ""; 

Locating child nodes of WebElements in selenium

The toString() method of Selenium's By-Class produces something like "By.xpath: //XpathFoo"

So you could take a substring starting at the colon with something like this:

String selector = divA.toString().substring(s.indexOf(":") + 2);

With this, you could find your element inside your other element with this:

WebElement input = driver.findElement( By.xpath( selector + "//input" ) );

Advantage: You have to search only once on the actual SUT, so it could give you a bonus in performance.

Disadvantage: Ugly... if you want to search for the parent element with css selectory and use xpath for it's childs, you have to check for types before you concatenate... In this case, Slanec's solution (using findElement on a WebElement) is much better.

Retrieving the COM class factory for component failed

I have Done the Following Things in IIS 8.5 (Windows Server 2012 R2)Server and its Worked in My Case Without Restart:

  1. Selecting The Application Pool That Connected to The Application in IIS

  2. And Right Click --> Advanced Settings --> Process Model --> Select Local System Instead of Recommended ApplicationPoolIdentity

  3. And Make Sure C:\Windows\SysWOW64\config\systemprofile\desktop Have Enough Access For Users.

  4. Refresh the Website Link that Connected With this Pool


enter image description here

Formatting a field using ToText in a Crystal Reports formula field

if(isnull({uspRptMonthlyGasRevenueByGas;1.YearTotal})) = true then
   "nd"
else
    totext({uspRptMonthlyGasRevenueByGas;1.YearTotal},'###.00')

The above logic should be what you are looking for.

Invalid attempt to read when no data is present

I was having 2 values which could contain null values.

while(dr.Read())
 {
    Id = dr["Id"] as int? ?? default(int?);
    Alt =  dr["Alt"].ToString() as string ?? default(string);
    Name = dr["Name"].ToString()
 }

resolved the issue

How to remove a TFS Workspace Mapping?

I ran into the same problem, and was able to fix it by manually deleting all the files in the TFS cache, located here:

%LocalAppData%\Microsoft\Team Foundation\3.0\Cache

or 4.0, 5.0, etc.

How do you set a default value for a MySQL Datetime column?

I was able to solve this using this alter statement on my table that had two datetime fields.

ALTER TABLE `test_table`
  CHANGE COLUMN `created_dt` `created_dt` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
  CHANGE COLUMN `updated_dt` `updated_dt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;

This works as you would expect the now() function to work. Inserting nulls or ignoring the created_dt and updated_dt fields results in a perfect timestamp value in both fields. Any update to the row changes the updated_dt. If you insert records via the MySQL query browser you needed one more step, a trigger to handle the created_dt with a new timestamp.

CREATE TRIGGER trig_test_table_insert BEFORE INSERT ON `test_table`
    FOR EACH ROW SET NEW.created_dt = NOW();

The trigger can be whatever you want I just like the naming convention [trig]_[my_table_name]_[insert]

How to get absolute path to file in /resources folder of your project

There are two problems on our way to the absolute path:

  1. The placement found will be not where the source files lie, but where the class is saved. And the resource folder almost surely will lie somewhere in the source folder of the project.
  2. The same functions for retrieving the resource work differently if the class runs in a plugin or in a package directly in the workspace.

The following code will give us all useful paths:

    URL localPackage = this.getClass().getResource("");
    URL urlLoader = YourClassName.class.getProtectionDomain().getCodeSource().getLocation();
    String localDir = localPackage.getPath();
    String loaderDir = urlLoader.getPath();
    System.out.printf("loaderDir = %s\n localDir = %s\n", loaderDir, localDir);

Here both functions that can be used for localization of the resource folder are researched. As for class, it can be got in either way, statically or dynamically.


If the project is not in the plugin, the code if run in JUnit, will print:

loaderDir = /C:.../ws/source.dir/target/test-classes/
 localDir = /C:.../ws/source.dir/target/test-classes/package/

So, to get to src/rest/resources we should go up and down the file tree. Both methods can be used. Notice, we can't use getResource(resourceFolderName), for that folder is not in the target folder. Nobody puts resources in the created folders, I hope.


If the class is in the package that is in the plugin, the output of the same test will be:

loaderDir = /C:.../ws/plugin/bin/
 localDir = /C:.../ws/plugin/bin/package/

So, again we should go up and down the folder tree.


The most interesting is the case when the package is launched in the plugin. As JUnit plugin test, for our example. The output is:

loaderDir = /C:.../ws/plugin/
 localDir = /package/

Here we can get the absolute path only combining the results of both functions. And it is not enough. Between them we should put the local path of the place where the classes packages are, relatively to the plugin folder. Probably, you will have to insert something as src or src/test/resource here.

You can insert the code into yours and see the paths that you have.

Exec : display stdout "live"

child_process.spawn returns an object with stdout and stderr streams. You can tap on the stdout stream to read data that the child process sends back to Node. stdout being a stream has the "data", "end", and other events that streams have. spawn is best used to when you want the child process to return a large amount of data to Node - image processing, reading binary data etc.

so you can solve your problem using child_process.spawn as used below.

var spawn = require('child_process').spawn,
ls = spawn('coffee -cw my_file.coffee');

ls.stdout.on('data', function (data) {
  console.log('stdout: ' + data.toString());
});

ls.stderr.on('data', function (data) {
  console.log('stderr: ' + data.toString());
});

ls.on('exit', function (code) {
  console.log('code ' + code.toString());
});

Mac OS X and multiple Java versions

Here's a more DRY version for bash (Based on Vegard's answer)

Replace 1.7 and 1.8 with whatever versions you are interested with and you'll get an alias called 'javaX'; where 'X' is the java version (7 / 8 in the snippet below) that will allow you to easily switch versions

for version in 1.7 1.8; do
    v="${version: -1}"
    h=JAVA_"$v"_HOME

    export "$h"=$(/usr/libexec/java_home -v $version)

    alias "java$v"="export JAVA_HOME=\$$h"
done

Matplotlib: "Unknown projection '3d'" error

Just to add to Joe Kington's answer (not enough reputation for a comment) there is a good example of mixing 2d and 3d plots in the documentation at http://matplotlib.org/examples/mplot3d/mixed_subplots_demo.html which shows projection='3d' working in combination with the Axes3D import.

from mpl_toolkits.mplot3d import Axes3D
...
ax = fig.add_subplot(2, 1, 1)
...
ax = fig.add_subplot(2, 1, 2, projection='3d')

In fact as long as the Axes3D import is present the line

from mpl_toolkits.mplot3d import Axes3D
...
ax = fig.gca(projection='3d')

as used by the OP also works. (checked with matplotlib version 1.3.1)

Filtering a list of strings based on contents

Tried this out quickly in the interactive shell:

>>> l = ['a', 'ab', 'abc', 'bac']
>>> [x for x in l if 'ab' in x]
['ab', 'abc']
>>>

Why does this work? Because the in operator is defined for strings to mean: "is substring of".

Also, you might want to consider writing out the loop as opposed to using the list comprehension syntax used above:

l = ['a', 'ab', 'abc', 'bac']
result = []
for s in l:
   if 'ab' in s:
       result.append(s)

How do you right-justify text in an HTML textbox?

Using inline styles:

<input type="text" style="text-align: right"/>

or, put it in a style sheet, like so:

<style>
   .rightJustified {
        text-align: right;
    }
</style>

and reference the class:

<input type="text" class="rightJustified"/>

How might I find the largest number contained in a JavaScript array?

You can also use forEach:

_x000D_
_x000D_
var maximum = Number.MIN_SAFE_INTEGER;_x000D_
_x000D_
var array = [-3, -2, 217, 9, -8, 46];_x000D_
array.forEach(function(value){_x000D_
  if(value > maximum) {_x000D_
    maximum = value;_x000D_
  }_x000D_
});_x000D_
_x000D_
console.log(maximum); // 217
_x000D_
_x000D_
_x000D_

Subtracting Dates in Oracle - Number or Interval Datatype?

Ok, I don't normally answer my own questions but after a bit of tinkering, I have figured out definitively how Oracle stores the result of a DATE subtraction.

When you subtract 2 dates, the value is not a NUMBER datatype (as the Oracle 11.2 SQL Reference manual would have you believe). The internal datatype number of a DATE subtraction is 14, which is a non-documented internal datatype (NUMBER is internal datatype number 2). However, it is actually stored as 2 separate two's complement signed numbers, with the first 4 bytes used to represent the number of days and the last 4 bytes used to represent the number of seconds.

An example of a DATE subtraction resulting in a positive integer difference:

select date '2009-08-07' - date '2008-08-08' from dual;

Results in:

DATE'2009-08-07'-DATE'2008-08-08'
---------------------------------
                              364

select dump(date '2009-08-07' - date '2008-08-08') from dual;

DUMP(DATE'2009-08-07'-DATE'2008
-------------------------------
Typ=14 Len=8: 108,1,0,0,0,0,0,0

Recall that the result is represented as a 2 seperate two's complement signed 4 byte numbers. Since there are no decimals in this case (364 days and 0 hours exactly), the last 4 bytes are all 0s and can be ignored. For the first 4 bytes, because my CPU has a little-endian architecture, the bytes are reversed and should be read as 1,108 or 0x16c, which is decimal 364.

An example of a DATE subtraction resulting in a negative integer difference:

select date '1000-08-07' - date '2008-08-08' from dual;

Results in:

DATE'1000-08-07'-DATE'2008-08-08'
---------------------------------
                          -368160

select dump(date '1000-08-07' - date '2008-08-08') from dual;

DUMP(DATE'1000-08-07'-DATE'2008-08-0
------------------------------------
Typ=14 Len=8: 224,97,250,255,0,0,0,0

Again, since I am using a little-endian machine, the bytes are reversed and should be read as 255,250,97,224 which corresponds to 11111111 11111010 01100001 11011111. Now since this is in two's complement signed binary numeral encoding, we know that the number is negative because the leftmost binary digit is a 1. To convert this into a decimal number we would have to reverse the 2's complement (subtract 1 then do the one's complement) resulting in: 00000000 00000101 10011110 00100000 which equals -368160 as suspected.

An example of a DATE subtraction resulting in a decimal difference:

select to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS'
 - to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS') from dual;

TO_DATE('08/AUG/200414:00:00','DD/MON/YYYYHH24:MI:SS')-TO_DATE('08/AUG/20048:00:
--------------------------------------------------------------------------------
                                                                             .25

The difference between those 2 dates is 0.25 days or 6 hours.

select dump(to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS')
 - to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS')) from dual;

DUMP(TO_DATE('08/AUG/200414:00:
-------------------------------
Typ=14 Len=8: 0,0,0,0,96,84,0,0

Now this time, since the difference is 0 days and 6 hours, it is expected that the first 4 bytes are 0. For the last 4 bytes, we can reverse them (because CPU is little-endian) and get 84,96 = 01010100 01100000 base 2 = 21600 in decimal. Converting 21600 seconds to hours gives you 6 hours which is the difference which we expected.

Hope this helps anyone who was wondering how a DATE subtraction is actually stored.


You get the syntax error because the date math does not return a NUMBER, but it returns an INTERVAL:

SQL> SELECT DUMP(SYSDATE - start_date) from test;

DUMP(SYSDATE-START_DATE)
-------------------------------------- 
Typ=14 Len=8: 188,10,0,0,223,65,1,0

You need to convert the number in your example into an INTERVAL first using the NUMTODSINTERVAL Function

For example:

SQL> SELECT (SYSDATE - start_date) DAY(5) TO SECOND from test;

(SYSDATE-START_DATE)DAY(5)TOSECOND
----------------------------------
+02748 22:50:04.000000

SQL> SELECT (SYSDATE - start_date) from test;

(SYSDATE-START_DATE)
--------------------
           2748.9515

SQL> select NUMTODSINTERVAL(2748.9515, 'day') from dual;

NUMTODSINTERVAL(2748.9515,'DAY')
--------------------------------
+000002748 22:50:09.600000000

SQL>

Based on the reverse cast with the NUMTODSINTERVAL() function, it appears some rounding is lost in translation.

How to return temporary table from stored procedure

YES YOU CAN.

In your stored procedure, you fill the table @tbRetour.

At the very end of your stored procedure, you write:

SELECT * FROM @tbRetour 

To execute the stored procedure, you write:

USE [...]
GO

DECLARE @return_value int

EXEC @return_value = [dbo].[getEnregistrementWithDetails]
@id_enregistrement_entete = '(guid)'

GO

Pure JavaScript: a function like jQuery's isNumeric()

function IsNumeric(val) {
    return Number(parseFloat(val)) === val;
}

jquery remove "selected" attribute of option?

Well, I spent a lot of time on this issue. To get an answer working with Chrome AND IE, I had to change my approach. The idea is to avoid removing the selected option (because cannot remove it properly with IE). => this implies to select option not by adding or setting the selected attribute on the option, but to choose an option at the "select" level using the selectedIndex prop.

Before :

$('#myselect option:contains("value")').attr('selected','selected');
$('#myselect option:contains("value")').removeAttr('selected'); => KO with IE

After :

$('#myselect').prop('selectedIndex', $('#myselect option:contains("value")').index());
$('#myselect').prop('selectedIndex','-1'); => OK with all browsers

Hope it will help

Select elements by attribute

I know it's been a long time since the question was asked, but I found the check to be clearer like this :

if ($("#A").is('[myattr]')) {
    // attribute exists
} else {
    // attribute does not exist
}

(As found on this site here)

Documentation about is can be found here

SQL command to display history of queries

You can see the history from ~/.mysql_history. However the content of the file is encoded by wctomb. To view the content:

shell> cat ~/.mysql_history | python2.7 -c "import sys; print(''.join([l.decode('unicode-escape') for l in sys.stdin]))"

Source:Check MySQL query history from command line

AngularJS access parent scope from child controller

From a child component you can access the properties and methods of the parent component with 'require'. Here is an example:

Parent:

.component('myParent', mymodule.MyParentComponent)
...
controllerAs: 'vm',
...
var vm = this;
vm.parentProperty = 'hello from parent';

Child:

require: {
    myParentCtrl: '^myParent'
},
controllerAs: 'vm',
...
var vm = this;
vm.myParentCtrl.parentProperty = 'hello from child';

How to make a redirection on page load in JSF 1.x

FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse)context.getExternalContext().getResponse();
response.sendRedirect("somePage.jsp");

How to install a python library manually

I'm going to assume compiling the QuickFix package does not produce a setup.py file, but rather only compiles the Python bindings and relies on make install to put them in the appropriate place.

In this case, a quick and dirty fix is to compile the QuickFix source, locate the Python extension modules (you indicated on your system these end with a .so extension), and add that directory to your PYTHONPATH environmental variable e.g., add

export PYTHONPATH=~/path/to/python/extensions:PYTHONPATH

or similar line in your shell configuration file.

A more robust solution would include making sure to compile with ./configure --prefix=$HOME/.local. Assuming QuickFix knows to put the Python files in the appropriate site-packages, when you do make install, it should install the files to ~/.local/lib/pythonX.Y/site-packages, which, for Python 2.6+, should already be on your Python path as the per-user site-packages directory.

If, on the other hand, it did provide a setup.py file, simply run

python setup.py install --user

for Python 2.6+.

Is there a way to override class variables in Java?

Why would you want to override variables when you could easily reassign them in the subClasses.

I follow this pattern to work around the language design. Assume a case where you have a weighty service class in your framework which needs be used in different flavours in multiple derived applications.In that case , the best way to configure the super class logic is by reassigning its 'defining' variables.

public interface ExtensibleService{
void init();
}

public class WeightyLogicService implements ExtensibleService{
    private String directoryPath="c:\hello";

    public void doLogic(){
         //never forget to call init() before invocation or build safeguards
         init();
       //some logic goes here
   }

   public void init(){}    

}

public class WeightyLogicService_myAdaptation extends WeightyLogicService {
   @Override
   public void init(){
    directoryPath="c:\my_hello";
   }

}

Creating a BAT file for python script

Here's how you can put both batch code and the python one in single file:

0<0# : ^
''' 
@echo off
echo batch code
python "%~f0" %*
exit /b 0
'''

print("python code")

the ''' respectively starts and ends python multi line comments.

0<0# : ^ is more interesting - due to redirection priority in batch it will be interpreted like :0<0# ^ by the batch script which is a label which execution will be not displayed on the screen. The caret at the end will escape the new line and second line will be attached to the first line.For python it will be 0<0 statement and a start of inline comment.

The credit goes to siberia-man

Base64 PNG data to HTML5 canvas

Jerryf's answer is fine, except for one flaw.

The onload event should be set before the src. Sometimes the src can be loaded instantly and never fire the onload event.

(Like Totty.js pointed out.)

var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");

var image = new Image();
image.onload = function() {
    ctx.drawImage(image, 0, 0);
};
image.src = "data:image/  png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";

javascript how to create a validation error message without using alert

You need to stop the submission if an error occured:

HTML

<form name ="myform" onsubmit="return validation();"> 

JS

if (document.myform.username.value == "") {
     document.getElementById('errors').innerHTML="*Please enter a username*";
     return false;
}

Ruby: Can I write multi-line string with no concatenation?

conn.exec = <<eos
  select attr1, attr2, attr3, attr4, attr5, attr6, attr7
  from table1, table2, table3, etc, etc, etc, etc, etc,
  where etc etc etc etc etc etc etc etc etc etc etc etc etc
eos

differences in application/json and application/x-www-form-urlencoded

webRequest.ContentType = "application/x-www-form-urlencoded";

  1. Where does application/x-www-form-urlencoded's name come from?

    If you send HTTP GET request, you can use query parameters as follows:

    http://example.com/path/to/page?name=ferret&color=purple

    The content of the fields is encoded as a query string. The application/x-www-form- urlencoded's name come from the previous url query parameter but the query parameters is in where the body of request instead of url.

    The whole form data is sent as a long query string.The query string contains name- value pairs separated by & character

    e.g. field1=value1&field2=value2

  2. It can be simple request called simple - don't trigger a preflight check

    Simple request must have some properties. You can look here for more info. One of them is that there are only three values allowed for Content-Type header for simple requests

    • application/x-www-form-urlencoded
    • multipart/form-data
    • text/plain

3.For mostly flat param trees, application/x-www-form-urlencoded is tried and tested.

request.ContentType = "application/json; charset=utf-8";

  1. The data will be json format.

axios and superagent, two of the more popular npm HTTP libraries, work with JSON bodies by default.

{
  "id": 1,
  "name": "Foo",
  "price": 123,
  "tags": [
    "Bar",
    "Eek"
  ],
  "stock": {
    "warehouse": 300,
    "retail": 20
  }
}
  1. "application/json" Content-Type is one of the Preflighted requests.

Now, if the request isn't simple request, the browser automatically sends a HTTP request before the original one by OPTIONS method to check whether it is safe to send the original request. If itis ok, Then send actual request. You can look here for more info.

  1. application/json is beginner-friendly. URL encoded arrays can be a nightmare!

SQL: how to select a single id ("row") that meets multiple criteria from a single column

Try this:

Select user_id
from yourtable
where ancestry in ('England', 'France', 'Germany')
group by user_id
having count(user_id) = 3

The last line means the user's ancestry has all 3 countries.

HTTP Error 503, the service is unavailable

Check Event Viewer - Windows - Application. If there is a red Error line made from IIS-W3SVC-WP and the message is like The Module DLL C:\Windows\system32\inetsrv\rewrite.dll failed to load. The data is the error. then you are missing some Windows Setup features.

In Windows Server 2012 go to Server Manager, Add Roles and Features, Web Server (IIS) and add the matching feature. Usually, most of the Application Development section is installed. Here is a complete list of IIS features and their associated DLL to help in diagnosis.

After going through a few iterations of that I ended on the error message above regarding "rewrite.dll". This led to a direct download and install of Microsoft URL Rewrite tool. Finally all websites came to life.

How do I change the default library path for R packages

Facing the very same problem (avoiding the default path in a network) I came up to this solution with the hints given in other answers.

The solution is editing the Rprofile file to overwrite the variable R_LIBS_USER which by default points to the home directory.

Here the steps:

  1. Create the target destination folder for the libraries, e.g., ~\target.
  2. Find the Rprofile file. In my case it was at C:\Program Files\R\R-3.3.3\library\base\R\Rprofile.
  3. Edit the file and change the definition the variable R_LIBS_USER. In my case, I replaced the this line file.path(Sys.getenv("R_USER"), "R", with file.path("~\target", "R",.

The documentation that support this solution is here

Original file with:

 if(!nzchar(Sys.getenv("R_LIBS_USER")))
     Sys.setenv(R_LIBS_USER=
                file.path(Sys.getenv("R_USER"), "R",
                          "win-library",
                          paste(R.version$major,
                                sub("\\..*$", "", R.version$minor),
                                sep=".")
                          )) 

Modified file:

if(!nzchar(Sys.getenv("R_LIBS_USER")))
     Sys.setenv(R_LIBS_USER=
                file.path("~\target", "R",
                          "win-library",
                          paste(R.version$major,
                                sub("\\..*$", "", R.version$minor),
                                sep=".")
                          ))

Linux: Which process is causing "device busy" when doing umount?

lsof +f -- /mountpoint

(as lists the processes using files on the mount mounted at /mountpoint. Particularly useful for finding which process(es) are using a mounted USB stick or CD/DVD.

How to fix 'Notice: Undefined index:' in PHP form action

Please try this

error_reporting = E_ALL & ~E_NOTICE

in php.ini

Get text from DataGridView selected cells

In this specific case, the ToString() will return the name of the object retruned by the SelectedCell Property.( a collection of the currently selected cells).

This behavior occurs when an object has no specific implenetation for the ToString() methods.

in our case, all you have to do is to iterate the collection of the cells and to accumulate its values to a string. then push this string to the TextBox.

have a look here how to implement the iteration:

msdn

How to set specific Java version to Maven

I just recently, after seven long years with Maven, learned about toolchains.xml. Maven has it even documented and supports it from 2.0.9 - toolchains documentation

So I added a toolchain.xml file to my ~/.m2/ folder with following content:

<toolchains xmlns="http://maven.apache.org/TOOLCHAINS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/TOOLCHAINS/1.1.0 http://maven.apache.org/xsd/toolchains-1.1.0.xsd">
 <!-- JDK toolchains -->
 <toolchain>
   <type>jdk</type>
   <provides>
     <version>1.8</version>
     <vendor>sun</vendor>
   </provides>
   <configuration>
     <jdkHome>/opt/java8</jdkHome>
   </configuration>
 </toolchain>
 <toolchain>
   <type>jdk</type>
   <provides>
     <version>1.7</version>
     <vendor>sun</vendor>
   </provides>
   <configuration>
     <jdkHome>/opt/java7</jdkHome>
   </configuration>
 </toolchain>
</toolchains>

It allows you to define what different JDKs Maven can use to build the project irrespective of the JDK Maven runs with. Sort of like when you define JDK on project level in IDE.

How do I enable --enable-soap in php on linux?

As far as your question goes: no, if activating from .ini is not enough and you can't upgrade PHP, there's not much you can do. Some modules, but not all, can be added without recompilation (zypper install php5-soap, yum install php-soap). If it is not enough, try installing some PEAR class for interpreted SOAP support (NuSOAP, etc.).

In general, the double-dash --switches are designed to be used when recompiling PHP from scratch.

You would download the PHP source package (as a compressed .tgz tarball, say), expand it somewhere and then, e.g. under Linux, run the configure script

./configure --prefix ...

The configure command used by your PHP may be shown with phpinfo(). Repeating it identical should give you an exact copy of the PHP you now have installed. Adding --enable-soap will then enable SOAP in addition to everything else.

That said, if you aren't familiar with PHP recompilation, don't do it. It also requires several ancillary libraries that you might, or might not, have available - freetype, gd, libjpeg, XML, expat, and so on and so forth (it's not enough they are installed; they must be a developer version, i.e. with headers and so on; in most distributions, having libjpeg installed might not be enough, and you might need libjpeg-dev also).

I have to keep a separate virtual machine with everything installed for my recompilation purposes.

Simple state machine example in C#?

Other alternative in this repo https://github.com/lingkodsoft/StateBliss used fluent syntax, supports triggers.

    public class BasicTests
    {
        [Fact]
        public void Tests()
        {
            // Arrange
            StateMachineManager.Register(new [] { typeof(BasicTests).Assembly }); //Register at bootstrap of your application, i.e. Startup
            var currentState = AuthenticationState.Unauthenticated;
            var nextState = AuthenticationState.Authenticated;
            var data = new Dictionary<string, object>();

            // Act
            var changeInfo = StateMachineManager.Trigger(currentState, nextState, data);

            // Assert
            Assert.True(changeInfo.StateChangedSucceeded);
            Assert.Equal("ChangingHandler1", changeInfo.Data["key1"]);
            Assert.Equal("ChangingHandler2", changeInfo.Data["key2"]);
        }

        //this class gets regitered automatically by calling StateMachineManager.Register
        public class AuthenticationStateDefinition : StateDefinition<AuthenticationState>
        {
            public override void Define(IStateFromBuilder<AuthenticationState> builder)
            {
                builder.From(AuthenticationState.Unauthenticated).To(AuthenticationState.Authenticated)
                    .Changing(this, a => a.ChangingHandler1)
                    .Changed(this, a => a.ChangedHandler1);

                builder.OnEntering(AuthenticationState.Authenticated, this, a => a.OnEnteringHandler1);
                builder.OnEntered(AuthenticationState.Authenticated, this, a => a.OnEnteredHandler1);

                builder.OnExiting(AuthenticationState.Unauthenticated, this, a => a.OnExitingHandler1);
                builder.OnExited(AuthenticationState.Authenticated, this, a => a.OnExitedHandler1);

                builder.OnEditing(AuthenticationState.Authenticated, this, a => a.OnEditingHandler1);
                builder.OnEdited(AuthenticationState.Authenticated, this, a => a.OnEditedHandler1);

                builder.ThrowExceptionWhenDiscontinued = true;
            }

            private void ChangingHandler1(StateChangeGuardInfo<AuthenticationState> changeinfo)
            {
                var data = changeinfo.DataAs<Dictionary<string, object>>();
                data["key1"] = "ChangingHandler1";
            }

            private void OnEnteringHandler1(StateChangeGuardInfo<AuthenticationState> changeinfo)
            {
                // changeinfo.Continue = false; //this will prevent changing the state
            }

            private void OnEditedHandler1(StateChangeInfo<AuthenticationState> changeinfo)
            {                
            }

            private void OnExitedHandler1(StateChangeInfo<AuthenticationState> changeinfo)
            {                
            }

            private void OnEnteredHandler1(StateChangeInfo<AuthenticationState> changeinfo)
            {                
            }

            private void OnEditingHandler1(StateChangeGuardInfo<AuthenticationState> changeinfo)
            {
            }

            private void OnExitingHandler1(StateChangeGuardInfo<AuthenticationState> changeinfo)
            {
            }

            private void ChangedHandler1(StateChangeInfo<AuthenticationState> changeinfo)
            {
            }
        }

        public class AnotherAuthenticationStateDefinition : StateDefinition<AuthenticationState>
        {
            public override void Define(IStateFromBuilder<AuthenticationState> builder)
            {
                builder.From(AuthenticationState.Unauthenticated).To(AuthenticationState.Authenticated)
                    .Changing(this, a => a.ChangingHandler2);

            }

            private void ChangingHandler2(StateChangeGuardInfo<AuthenticationState> changeinfo)
            {
                var data = changeinfo.DataAs<Dictionary<string, object>>();
                data["key2"] = "ChangingHandler2";
            }
        }
    }

    public enum AuthenticationState
    {
        Unauthenticated,
        Authenticated
    }
}

Get div tag scroll position using JavaScript

you use the scrollTop attribute

var position = document.getElementById('id').scrollTop;

How to simulate target="_blank" in JavaScript

This is how I do it with jQuery. I have a class for each link that I want to be opened in new window.

$(function(){

    $(".external").click(function(e) {
        e.preventDefault();
        window.open(this.href);
    });
});

How to generate entire DDL of an Oracle schema (scriptable)?

The output of this query is very clean (original here)

clear screen
accept uname prompt 'Enter User Name : '
accept outfile prompt  ' Output filename : '

spool &&outfile..gen

SET LONG 20000 LONGCHUNKSIZE 20000 PAGESIZE 0 LINESIZE 1000 FEEDBACK OFF VERIFY OFF TRIMSPOOL ON

BEGIN
   DBMS_METADATA.set_transform_param (DBMS_METADATA.session_transform, 'SQLTERMINATOR', true);
   DBMS_METADATA.set_transform_param (DBMS_METADATA.session_transform, 'PRETTY', true);
END;
/

SELECT dbms_metadata.get_ddl('USER','&&uname') FROM dual;
SELECT DBMS_METADATA.GET_GRANTED_DDL('SYSTEM_GRANT','&&uname') from dual;
SELECT DBMS_METADATA.GET_GRANTED_DDL('ROLE_GRANT','&&uname') from dual;
SELECT DBMS_METADATA.GET_GRANTED_DDL('OBJECT_GRANT','&&uname') from dual;

spool off

How to add an image in the title bar using html?

it works

Add this inside your head tag

<link rel="shortcut icon" href="http://example.com/myicon.png" />

Gradient text color

You can achieve that effect using a combination of CSS linear-gradient and mix-blend-mode.

HTML

<p>
    Enter your message here... 
    To be or not to be, 
    that is the question...
    maybe, I think, 
    I'm not sure
    wait, you're still reading this?
    Type a good message already!
</p>

CSS

p {
    width: 300px;
    position: relative;
}

p::after {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(45deg, red, orange, yellow, green, blue, purple);
    mix-blend-mode: screen;
}

What this does is add a linear gradient on the paragraph's ::after pseudo-element and make it cover the whole paragraph element. But with mix-blend-mode: screen, the gradient will only show on parts where there is text.

Here's a jsfiddle to show this at work. Just modify the linear-gradient values to achieve what you want.

Is it possible to override / remove background: none!important with jQuery?

With a <script> right after the <style> that applies the !important things, you should be able to do something like this:

var lastStylesheet = document.styleSheets[document.styleSheets.length - 1];
lastStylesheet.disabled = true;

document.write('<style type="text/css">');
// Call fixBackground for each element that needs fixing
document.write('</style>');

lastStylesheet.disabled = false;

function fixBackground(el) {
    document.write('html #' + el.id + ' { background-image: ' +
        document.defaultView.getComputedStyle(el).backgroundImage +
        ' !important; }');
}

This probably depends on what kind of browser compatibility you need, though.

Push JSON Objects to array in localStorage

One thing I can suggest you is to extend the storage object to handle objects and arrays.

LocalStorage can handle only strings so you can achieve that using these methods

Storage.prototype.setObj = function(key, obj) {
    return this.setItem(key, JSON.stringify(obj))
}
Storage.prototype.getObj = function(key) {
    return JSON.parse(this.getItem(key))
}

Using it every values will be converted to json string on set and parsed on get

top -c command in linux to filter processes listed based on processname

@perreal's command works great! If you forget, try in two steps...

example: filter top to display only application called yakuake:

$ pgrep yakuake
1755

$ top -p 1755

useful top interactive commands 'c' : toggle full path vs. command name 'k' : kill by PID 'F' : filter by... select with arrows... then press 's' to set the sort

the answer below is good too... I was looking for that today but couldn't find it. Thanks

How to get changes from another branch

You are almost there :)

All that is left is to

git checkout featurex
git merge our-team

This will merge our-team into featurex.

The above assumes you have already committed/stashed your changes in featurex, if that is not the case you will need to do this first.

How to change port number for apache in WAMP

Change port number for Xampp Go to the file C:\xampp\apache\conf\httpd.conf

#Listen 12.34.56.78:80
Listen 80

Change 80 to 82

as

#Listen 12.34.56.78:82
Listen 82

now your url will be

http://localhost:82

sendmail: how to configure sendmail on ubuntu?

When you typed in sudo sendmailconfig, you should have been prompted to configure sendmail.

For reference, the files that are updated during configuration are located at the following (in case you want to update them manually):

/etc/mail/sendmail.conf
/etc/cron.d/sendmail
/etc/mail/sendmail.mc

You can test sendmail to see if it is properly configured and setup by typing the following into the command line:

$ echo "My test email being sent from sendmail" | /usr/sbin/sendmail [email protected]

The following will allow you to add smtp relay to sendmail:

#Change to your mail config directory:
cd /etc/mail

#Make a auth subdirectory
mkdir auth
chmod 700 auth

#Create a file with your auth information to the smtp server
cd auth
touch client-info

#In the file, put the following, matching up to your smtp server:
AuthInfo:your.isp.net "U:root" "I:user" "P:password"

#Generate the Authentication database, make both files readable only by root
makemap hash client-info < client-info
chmod 600 client-info
cd ..

Add the following lines to sendmail.mc, but before the MAILERDEFINITIONS. Make sure you update your smtp server.

define(`SMART_HOST',`your.isp.net')dnl
define(`confAUTH_MECHANISMS', `EXTERNAL GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
FEATURE(`authinfo',`hash -o /etc/mail/auth/client-info.db')dnl

Invoke creation sendmail.cf (alternatively run make -C /etc/mail):

m4 sendmail.mc > sendmail.cf

Restart the sendmail daemon:

service sendmail restart

how to convert a string to an array in php

explode — Split a string by a string

Syntax :

array explode ( string $delimiter , string $string [, int $limit = PHP_INT_MAX ] )
  • $delimiter : based on which you want to split string
  • $string. : The string you want to split

Example :

// Example 1
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

In your example :

$str = "this is string"; 
$array = explode(' ', $str);

Ruby sleep or delay less than a second?

sleep(1.0/24.0)

As to your follow up question if that's the best way: No, you could get not-so-smooth framerates because the rendering of each frame might not take the same amount of time.

You could try one of these solutions:

  • Use a timer which fires 24 times a second with the drawing code.
  • Create as many frames as possible, create the motion based on the time passed, not per frame.

HTML form action and onsubmit issues

Try:

onsubmit="checkRegistration(event.preventDefault())"

MVC Razor Radio Button

I wanted to share one way to do the radio button (and entire HTML form) without using the @Html.RadioButtonFor helper, although I think @Html.RadioButtonFor is probably the better and newer way (for one thing, it's strongly typed, so is closely linked to theModelProperty). Nevertheless, here's an old-fashioned, different way you can do it:

    <form asp-action="myActionMethod" method="post">
        <h3>Do you like pizza?</h3>
        <div class="checkbox">
            <label>
                <input asp-for="likesPizza"/> Yes
            </label>
        </div>
    </form>

This code can go in a myView.cshtml file, and also uses classes to get the radio-button (checkbox) formatting.

How to copy selected files from Android with adb pull

You can move your files to other folder and then pull whole folder.

adb shell mkdir /sdcard/tmp
adb shell mv /sdcard/mydir/*.jpg /sdcard/tmp # move your jpegs to temporary dir
adb pull /sdcard/tmp/ # pull this directory (be sure to put '/' in the end)
adb shell mv /sdcard/tmp/* /sdcard/mydir/ # move them back
adb shell rmdir /sdcard/tmp # remove temporary directory

How can I get onclick event on webview in android?

WebViewClient.shouldOverrideUrlLoading might be helpful. We are having a similar requirement in one of our app. Not tried yet.

regular expression for Indian mobile numbers

You may use this

/^(?:(?:\+|0{0,2})91(\s*|[\-])?|[0]?)?([6789]\d{2}([ -]?)\d{3}([ -]?)\d{4})$/

Valid Entries:

6856438922
7856128945
8945562713
9998564723
+91-9883443344
09883443344
919883443344
0919883443344
+919883443344
+91-9883443344
0091-9883443344
+91 9883443344
+91-785-612-8945
+91 999 856 4723

Invalid Entries:

WAQU9876567892
ABCD9876541212
0226-895623124
0924645236
0222-895612
098-8956124
022-2413184

Validate it at https://regex101.com/

AttributeError: 'numpy.ndarray' object has no attribute 'append'

I got this error after change a loop in my program, let`s see:

for ...
  for ... 
     x_batch.append(one_hot(int_word, vocab_size))
     y_batch.append(one_hot(int_nb, vocab_size, value))
  ...
  ...
  if ...
        x_batch = np.asarray(x_batch)
        y_batch = np.asarray(y_batch)
...

In fact, I was reusing the variable and forgot to reset them inside the external loop, like the comment of John Lyon:

for ...
  x_batch = []
  y_batch = []
  for ... 
     x_batch.append(one_hot(int_word, vocab_size))
     y_batch.append(one_hot(int_nb, vocab_size, value))
  ...
  ...
  if ...
        x_batch = np.asarray(x_batch)
        y_batch = np.asarray(y_batch)
...

Then, check if you are using np.asarray() or something like that.

Directing print output to a .txt file

Another Variation can be... Be sure to close the file afterwards

import sys
file = open('output.txt', 'a')
sys.stdout = file

print("Hello stackoverflow!") 
print("I have a question.")

file.close()

How to Ping External IP from Java Android

This is a simple ping I use in one of the projects:

public static class Ping {
    public String net = "NO_CONNECTION";
    public String host = "";
    public String ip = "";
    public int dns = Integer.MAX_VALUE;
    public int cnt = Integer.MAX_VALUE;
}

public static Ping ping(URL url, Context ctx) {
    Ping r = new Ping();
    if (isNetworkConnected(ctx)) {
        r.net = getNetworkType(ctx);
        try {
            String hostAddress;
            long start = System.currentTimeMillis();
            hostAddress = InetAddress.getByName(url.getHost()).getHostAddress();
            long dnsResolved = System.currentTimeMillis();
            Socket socket = new Socket(hostAddress, url.getPort());
            socket.close();
            long probeFinish = System.currentTimeMillis();
            r.dns = (int) (dnsResolved - start);
            r.cnt = (int) (probeFinish - dnsResolved);
            r.host = url.getHost();
            r.ip = hostAddress;
        }
        catch (Exception ex) {
            Timber.e("Unable to ping");
        }
    }
    return r;
}

public static boolean isNetworkConnected(Context context) {
    ConnectivityManager cm =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}

@Nullable
public static String getNetworkType(Context context) {
    ConnectivityManager cm =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null) {
        return activeNetwork.getTypeName();
    }
    return null;
}

Usage: ping(new URL("https://www.google.com:443/"), this);

Result: {"cnt":100,"dns":109,"host":"www.google.com","ip":"212.188.10.114","net":"WIFI"}

Get the second highest value in a MySQL table

create table svalue (
name varchar(5),
value int
) engine = myisam;

insert into svalue value ('aaa',30),('bbb',10),('ccc',30),('ddd',20);

select * from svalue where value = (
select value 
from svalue
group by value
order by  value desc limit 1,1)

How do I create an abstract base class in JavaScript?

Javascript can have inheritance, check out the URL below:

http://www.webreference.com/js/column79/

Andrew

Stack array using pop() and push()

Because you initialized the top variable to -1 in your constructor, you need to increment the top variable in your push() method before you access the array. Note that I've changed the assignment to use ++top:

public void push(int i) 
{
    if (top == stack.length)
    {
        extendStack();
    }

    stack[++top]= i;
}

That will fix the ArrayIndexOutOfBoundsException you posted about. I can see other issues in your code, but since this is a homework assignment I'll leave those as "an exercise for the reader." :)

How to get the first column of a pandas DataFrame as a Series?

>>> import pandas as pd
>>> df = pd.DataFrame({'x' : [1, 2, 3, 4], 'y' : [4, 5, 6, 7]})
>>> df
   x  y
0  1  4
1  2  5
2  3  6
3  4  7
>>> s = df.ix[:,0]
>>> type(s)
<class 'pandas.core.series.Series'>
>>>

===========================================================================

UPDATE

If you're reading this after June 2017, ix has been deprecated in pandas 0.20.2, so don't use it. Use loc or iloc instead. See comments and other answers to this question.

Bootstrap 3 Horizontal and Vertical Divider

The <hr> should be placed inside a <div> for proper functioning.

Place it like this to get desired width `

<div class='row'>
        <div class='col-lg-8 col-lg-offset-2'>
        <hr>
       </div>
       </div>

`

Hope this helps a future reader!

Split text with '\r\n'

I took a more compact approach to split an input resulting from a text area into a list of string . You can use this if suits your purpose.

the problem is you cannot split by \r\n so i removed the \n beforehand and split only by \r

var serials = model.List.Replace("\n","").Split('\r').ToList<string>();

I like this approach because you can do it in just one line.

Remove quotes from a character vector in R

nump function :)

> nump <- function(x) print(formatC(x, format="fg", big.mark=","), quote=FALSE)

correct answer:

x <- 1234567890123456

> nump(x)

[1] 1,234,567,890,123,456 

How to represent the double quotes character (") in regex?

you need to use backslash before ". like \"

From the doc here you can see that

A character preceded by a backslash ( \ ) is an escape sequence and has special meaning to the compiler.

and " (double quote) is a escacpe sequence

When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes. To print the sentence

She said "Hello!" to me.

you would write

System.out.println("She said \"Hello!\" to me.");

How do I properly escape quotes inside HTML attributes?

If you are using Javascript and Lodash, then you can use _.escape(), which escapes ", ', <, >, and &.

See here: https://lodash.com/docs/#escape

Owl Carousel, making custom navigation

If you want to use your own custom navigation elements,

For Owl Carousel 1

var owl = $('.owl-carousel');
owl.owlCarousel();
// Go to the next item
$('.customNextBtn').click(function() {
    owl.trigger('owl.prev');
})
// Go to the previous item
$('.customPrevBtn').click(function() {
    owl.trigger('owl.next');
})

For Owl Carousel 2

var owl = $('.owl-carousel');
owl.owlCarousel();
// Go to the next item
$('.customNextBtn').click(function() {
    owl.trigger('next.owl.carousel');
})
// Go to the previous item
$('.customPrevBtn').click(function() {
    // With optional speed parameter
    // Parameters has to be in square bracket '[]'
    owl.trigger('prev.owl.carousel', [300]);
})

How to consume REST in Java

Working example, try this:

package restclient;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class NetClientGet {
    public static void main(String[] args) {
        try {

            URL url = new URL("http://localhost:3002/RestWebserviceDemo/rest/json/product/dynamicData?size=5");//your url i.e fetch data from .
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");
            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP Error code : "
                        + conn.getResponseCode());
            }
            InputStreamReader in = new InputStreamReader(conn.getInputStream());
            BufferedReader br = new BufferedReader(in);
            String output;
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }
            conn.disconnect();

        } catch (Exception e) {
            System.out.println("Exception in NetClientGet:- " + e);
        }
    }
}

Using Enum values as String literals

package com.common.test;

public  enum Days {


    monday(1,"Monday"),tuesday(2,"Tuesday"),wednesday(3,"Wednesday"),
    thrusday(4,"Thrusday"),friday(5,"Friday"),saturday(6,"Saturday"),sunday(7,"Sunday");

    private int id;
    private String desc;


    Days(int id,String desc){
        this.id=id;
        this.desc=desc;
    }

    public static String getDay(int id){

        for (Days day : Days.values()) {
            if (day.getId() == id) {
                return day.getDesc();
            }
        }
        return null;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }



};

How comment a JSP expression?

You can use this comment in jsp page

 <%--your comment --%>

Second way of comment declaration in jsp page you can use the comment of two typ in jsp code

 single line comment
 <% your code //your comment%>

multiple line comment 

<% your code 
/**
your another comment
**/

%>

And you can also comment on jsp page from html code for example:

<!-- your commment -->

Java: int[] array vs int array[]

There is no difference between these two declarations, and both have the same performance.

putting datepicker() on dynamically created elements - JQuery/JQueryUI

Excellent answer by skafandri +1

This is just updated to check for hasDatepicker class.

$('body').on('focus',".datepicker", function(){

    if( $(this).hasClass('hasDatepicker') === false )  {
        $(this).datepicker();
    }

});

Setting java locale settings

For tools like jarsigner which is implemented in Java.

JAVA_TOOL_OPTIONS=-Duser.language=en jarsigner

Android: why setVisibility(View.GONE); or setVisibility(View.INVISIBLE); do not work

Today I had a scenario, where I was performing following:

myViewGroup.setVisibility(View.GONE);

Right on the next frame I was performing an if check somewhere else for visibility state of that view. Guess what? The following condition was passing:

if(myViewGroup.getVisibility() == View.VISIBLE) {
    // this `if` was fulfilled magically
}

Placing breakpoints you can see, that visibility changes to GONE, but right on the next frame it magically becomes VISIBLE. I was trying to understand how the hell this could happen.

Turns out there was an animation applied to this view, which internally caused the view to change it's visibility to VISIBLE until finishing the animation:

public void someFunction() {
    ...
    TransitionManager.beginDelayedTransition(myViewGroup);
    ...

    myViewGroup.setVisibility(View.GONE);
}

If you debug, you'll see that myViewGroup indeed changes its visibility to GONE, but right on the next frame it would again become visible in order to run the animation.

So, if you come across with such a situation, make sure you are not performing an if check in amidst of animating the view.

You can remove all animations on the view via View.clearAnimation().

Setting the default page for ASP.NET (Visual Studio) server configuration

Right click on the web page you want to use as the default page and choose "Set as Start Page" whenever you run the web application from Visual Studio, it will open the selected page.

Disable EditText blinking cursor

  1. Change focus to another view (ex: Any textview or Linearlayout in the XML) using

    android:focusableInTouchMode="true"
    android:focusable="true"
    
  2. set addTextChangedListener to edittext in Activity.

  3. and then on aftertextchanged of Edittext put edittext.clearFocus();

This will enable the cursor when keyboard is open and disable when keyboard is closed.

Regular expression "^[a-zA-Z]" or "[^a-zA-Z]"

Yes, the first means "match all strings that start with a letter", the second means "match all strings that contain a non-letter". The caret ("^") is used in two different ways, one to signal the start of the text, one to negate a character match inside square brackets.

Detect iPad users using jQuery?

I use this:

//http://detectmobilebrowsers.com/ + tablets
(function(a) {
    if(/android|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(ad|hone|od)|iris|kindle|lge |maemo|meego.+mobile|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino|playbook|silk/i.test(a)
    ||
    /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))
    {
        window.location="yourNewIndex.html"
    }
})(navigator.userAgent||navigator.vendor||window.opera);

Use sed to replace all backslashes with forward slashes

You can try

sed 's:\\:\/:g'`

The first \ is to insert an input, the second \ will be the one you want to substitute.

So it is 's ":" First Slash "\" second slash "\" ":" "\" to insert input "/" as the new slash that will be presented ":" g'

\\ \/ 

And that's it. It will work.

How to insert a column in a specific position in oracle without dropping and recreating the table?

Although this is somewhat old I would like to add a slightly improved version that really changes column order. Here are the steps (assuming we have a table TAB1 with columns COL1, COL2, COL3):

  1. Add new column to table TAB1:
alter table TAB1 add (NEW_COL number);
  1. "Copy" table to temp name while changing the column order AND rename the new column:
create table tempTAB1 as select NEW_COL as COL0, COL1, COL2, COL3 from TAB1;
  1. drop existing table:
drop table TAB1;
  1. rename temp tablename to just dropped tablename:
rename tempTAB1 to TAB1;

How to design RESTful search/filtering?

Don't fret too much if your initial API is fully RESTful or not (specially when you are just in the alpha stages). Get the back-end plumbing to work first. You can always do some sort of URL transformation/re-writing to map things out, refining iteratively until you get something stable enough for widespread testing ("beta").

You can define URIs whose parameters are encoded by position and convention on the URIs themselves, prefixed by a path you know you'll always map to something. I don't know PHP, but I would assume that such a facility exists (as it exists in other languages with web frameworks):

.ie. Do a "user" type of search with param[i]=value[i] for i=1..4 on store #1 (with value1,value2,value3,... as a shorthand for URI query parameters):

1) GET /store1/search/user/value1,value2,value3,value4

or

2) GET /store1/search/user,value1,value2,value3,value4

or as follows (though I would not recommend it, more on that later)

3) GET /search/store1,user,value1,value2,value3,value4

With option 1, you map all URIs prefixed with /store1/search/user to the search handler (or whichever the PHP designation) defaulting to do searches for resources under store1 (equivalent to /search?location=store1&type=user.

By convention documented and enforced by the API, parameters values 1 through 4 are separated by commas and presented in that order.

Option 2 adds the search type (in this case user) as positional parameter #1. Either option is just a cosmetic choice.

Option 3 is also possible, but I don't think I would like it. I think the ability of search within certain resources should be presented in the URI itself preceding the search itself (as if indicating clearly in the URI that the search is specific within the resource.)

The advantage of this over passing parameters on the URI is that the search is part of the URI (thus treating a search as a resource, a resource whose contents can - and will - change over time.) The disadvantage is that parameter order is mandatory.

Once you do something like this, you can use GET, and it would be a read-only resource (since you can't POST or PUT to it - it gets updated when it's GET'ed). It would also be a resource that only comes to exist when it is invoked.

One could also add more semantics to it by caching the results for a period of time or with a DELETE causing the cache to be deleted. This, however, might run counter to what people typically use DELETE for (and because people typically control caching with caching headers.)

How you go about it would be a design decision, but this would be the way I'd go about. It is not perfect, and I'm sure there will be cases where doing this is not the best thing to do (specially for very complex search criteria).

Dump a mysql database to a plaintext (CSV) backup from the command line

If you can cope with table-at-a-time, and your data is not binary, use the -B option to the mysql command. With this option it'll generate TSV (tab separated) files which can import into Excel, etc, quite easily:

% echo 'SELECT * FROM table' | mysql -B -uxxx -pyyy database

Alternatively, if you've got direct access to the server's file system, use SELECT INTO OUTFILE which can generate real CSV files:

SELECT * INTO OUTFILE 'table.csv'
    FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
    LINES TERMINATED BY '\n'
FROM table

How to turn on/off MySQL strict mode in localhost (xampp)?

To Change it permanently in ubuntu do the following

in the ubuntu command line

sudo nano /etc/mysql/my.cnf

Then add the following

[mysqld]
sql_mode=

how to open a url in python

import webbrowser  
webbrowser.open(url, new=0, autoraise=True)

Display url using the default browser. If new is 0, the url is opened in the same browser window if possible. If new is 1, a new browser window is opened if possible. If new is 2, a new browser page (“tab”) is opened if possible. If autoraise is True, the window is raised

webbrowser.open_new(url)

Open url in a new window of the default browser

webbrowser.open_new_tab(url)

Open url in a new page (“tab”) of the default browser