Programs & Examples On #Rcurl

RCurl is an R package that provides an R-friendly wrapper for the libcurl C library.

Problems installing the devtools package

CentOS 7:

I tried solutions in this post

sudo yum -y install libcurl libcurl-devel
sudo yum -y install openssl-devel

but wasn't enough.

Checking R error in Console gave me the anwser. In my case it was lacking libxml-2.0 below (and Console printed an explanation with package name to different Linux versions and other possible R configs)

sudo yum -y install libxml2-devel

Add legend to ggplot2 line plot

I really like the solution proposed by @Brian Diggs. However, in my case, I create the line plots in a loop rather than giving them explicitly because I do not know apriori how many plots I will have. When I tried to adapt the @Brian's code I faced some problems with handling the colors correctly. Turned out I needed to modify the aesthetic functions. In case someone has the same problem, here is the code that worked for me.

I used the same data frame as @Brian:

data <- structure(list(month = structure(c(1317452400, 1317538800, 1317625200, 1317711600, 
                                       1317798000, 1317884400, 1317970800, 1318057200, 
                                       1318143600, 1318230000, 1318316400, 1318402800, 
                                       1318489200, 1318575600, 1318662000, 1318748400, 
                                       1318834800, 1318921200, 1319007600, 1319094000), 
                                     class = c("POSIXct", "POSIXt"), tzone = ""),
                   TempMax = c(26.58, 27.78, 27.9, 27.44, 30.9, 30.44, 27.57, 25.71, 
                               25.98, 26.84, 33.58, 30.7, 31.3, 27.18, 26.58, 26.18, 
                               25.19, 24.19, 27.65, 23.92), 
                   TempMed = c(22.88, 22.87, 22.41, 21.63, 22.43, 22.29, 21.89, 20.52,
                                 19.71, 20.73, 23.51, 23.13, 22.95, 21.95, 21.91, 20.72, 
                                 20.45, 19.42, 19.97, 19.61), 
                   TempMin = c(19.34, 19.14, 18.34, 17.49, 16.75, 16.75, 16.88, 16.82, 
                               14.82, 16.01, 16.88, 17.55, 16.75, 17.22, 19.01, 16.95, 
                               17.55, 15.21, 14.22, 16.42)), 
              .Names = c("month", "TempMax", "TempMed", "TempMin"), 
              row.names = c(NA, 20L), class = "data.frame")  

In my case, I generate my.cols and my.names dynamically, but I don't want to make things unnecessarily complicated so I give them explicitly here. These three lines make the ordering of the legend and assigning colors easier.

my.cols <- heat.colors(3, alpha=1)
my.names <- c("TempMin", "TempMed", "TempMax")
names(my.cols) <- my.names

And here is the plot:

p <-  ggplot(data, aes(x = month))

for (i in 1:3){
  p <- p + geom_line(aes_(y = as.name(names(data[i+1])), colour = 
colnames(data[i+1])))#as.character(my.names[i])))
}
p + scale_colour_manual("", 
                        breaks = as.character(my.names),
                        values = my.cols)
p

enter image description here

Proxy setting for R

The problem is with your curl options – the RCurl package doesn't seem to use internet2.dll. You need to specify the port separately, and will probably need to give your user login details as network credentials, e.g.,

opts <- list(
  proxy         = "999.999.999.999", 
  proxyusername = "mydomain\\myusername", 
  proxypassword = "mypassword", 
  proxyport     = 8080
)
getURL("http://stackoverflow.com", .opts = opts)

Remember to escape any backslashes in your password. You may also need to wrap the URL in a call to curlEscape.

Seconds CountDown Timer

Hey please add code in your project,it is easy and i think will solve your problem.

    int count = 10;

    private void timer1_Tick(object sender, EventArgs e)
    {
        count--;
        if (count != 0 && count > 0)
        {
            label1.Text = count / 60 + ":" + ((count % 60) >= 10 ? (count % 60).ToString() : "0" + (count % 60));
        }
        else
        {
            label1.Text = "game over";

        }

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        timer1 = new System.Windows.Forms.Timer();
        timer1.Interval = 1;

        timer1.Tick += new EventHandler(timer1_Tick);

    }

Convert Pandas DataFrame to JSON format

instead of using dataframe.to_json(orient = “records”) use dataframe.to_json(orient = “index”) my above code convert the dataframe into json format of dict like {index -> {column -> value}}

Maven2 property that indicates the parent directory

Another alternative:

in the parent pom, use:

<properties>
   <rootDir>${session.executionRootDirectory}</rootDir>
<properties>

In the children poms, you can reference this variable.

Main caveat: It forces you to always execute command from the main parent pom directory. Then if you want to run commands (test for example) only for some specific module, use this syntax:

mvn test --projects

The configuration of surefire to parametize a "path_to_test_data" variable may then be:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>${surefire.plugin.version}</version>
    <configuration>
        <systemPropertyVariables>
            <path_to_test_data>${rootDir}/../testdata</path_to_test_data>
        </systemPropertyVariables>
    </configuration>
</plugin>

Call PHP function from Twig template

If you really know what you do and you don't mind the evil ways, this is the only additional Twig extension you'll ever need:

function evilEvalPhp($eval, $args = null)
{
    $result = null;
    eval($eval);
    return $result;
}

Split string in Lua?

I like this short solution

function split(s, delimiter)
    result = {};
    for match in (s..delimiter):gmatch("(.-)"..delimiter) do
        table.insert(result, match);
    end
    return result;
end

Multi-threading in VBA

As you probably learned VBA does not natively support multithreading but. There are 3 methods to achieve multithreading:

  1. COM/dlls - e.g. C# and the Parallel class to run in separate threads
  2. Using VBscript worker threads - run your VBA code in separate VBscript threads
  3. Using VBA worker threads executed e.g. via VBscript - copy the Excel workbook and run your macro in parallel.

I compared all thread approaches here: http://analystcave.com/excel-multithreading-vba-vs-vbscript-vs-c-net/

Considering approach #3 I also made a VBA Multithreading Tool that allows you to easily add multithreading to VBA: http://analystcave.com/excel-vba-multithreading-tool/

See the examples below:

Multithreading a For Loop

Sub RunForVBA(workbookName As String, seqFrom As Long, seqTo As Long)
    For i = seqFrom To seqTo
        x = seqFrom / seqTo
    Next i
End Sub

Sub RunForVBAMultiThread()
    Dim parallelClass As Parallel 

    Set parallelClass = New Parallel 

    parallelClass.SetThreads 4 

    Call parallelClass.ParallelFor("RunForVBA", 1, 1000) 
End Sub

Run an Excel macro asynchronously

Sub RunAsyncVBA(workbookName As String, seqFrom As Long, seqTo As Long)
    For i = seqFrom To seqTo
        x = seqFrom / seqTo
    Next i
End Sub

Sub RunForVBAAndWait()
    Dim parallelClass As Parallel

    Set parallelClass  = New Parallel

    Call parallelClass.ParallelAsyncInvoke("RunAsyncVBA", ActiveWorkbook.Name, 1, 1000) 
    'Do other operations here
    '....

    parallelClass.AsyncThreadJoin 
End Sub

Java: object to byte[] and byte[] to object converter (for Tokyo Cabinet)

Use serialize and deserialize methods in SerializationUtils from commons-lang.

What is the difference between i++ and ++i?

The way the operator works is that it gets incremented at the same time, but if it is before a variable, the expression will evaluate with the incremented/decremented variable:

int x = 0;   //x is 0
int y = ++x; //x is 1 and y is 1

If it is after the variable the current statement will get executed with the original variable, as if it had not yet been incremented/decremented:

int x = 0;   //x is 0
int y = x++; //'y = x' is evaluated with x=0, but x is still incremented. So, x is 1, but y is 0

I agree with dcp in using pre-increment/decrement (++x) unless necessary. Really the only time I use the post-increment/decrement is in while loops or loops of that sort. These loops are the same:

while (x < 5)  //evaluates conditional statement
{
    //some code
    ++x;       //increments x
}

or

while (x++ < 5) //evaluates conditional statement with x value before increment, and x is incremented
{
    //some code
}

You can also do this while indexing arrays and such:

int i = 0;
int[] MyArray = new int[2];
MyArray[i++] = 1234; //sets array at index 0 to '1234' and i is incremented
MyArray[i] = 5678;   //sets array at index 1 to '5678'
int temp = MyArray[--i]; //temp is 1234 (becasue of pre-decrement);

Etc, etc...

Android Studio - Importing external Library/Jar

I'm using Android Studio 0.5.2. So if your version is lower than mine my answer may not work for you.

3 ways to add a new Jar to your project:

  1. Menu under Files-->Project Structure
  2. Just press 'F4'
  3. under Project navigation, right clink on any java library and a context menu will show then click on 'Open Library Settings'

A Project Structure window will popup.

On the left column click on 'Libraries' then look at the right pane where there is a plus sign '+' and click on it then enter the path to your new library.

Make sure the new library is under the 'project\libs\' folder otherwise you may get a broken link when you save your project source code.

font awesome icon in select option

Another solution is setting the size attribute on the select box.

Thus taking back control of the styling of the dropdown from the Apple style and displaying Font Awesome Icons correctly.

What does the question mark and the colon (?: ternary operator) mean in objective-c?

I just learned something new about the ternary operator. The short form that omits the middle operand is truly elegant, and is one of the many reasons that C remains relevant. FYI, I first really got my head around this in the context of a routine implemented in C#, which also supports the ternary operator. Since the ternary operator is in C, it stands to reason that it would be in other languages that are essentially extensions thereof (e. g., Objective-C, C#).

How to declare a global variable in a .js file

Just define your variables in global.js outside a function scope:

// global.js
var global1 = "I'm a global!";
var global2 = "So am I!";

// other js-file
function testGlobal () {
    alert(global1);
}

To make sure that this works you have to include/link to global.js before you try to access any variables defined in that file:

<html>
    <head>
        <!-- Include global.js first -->
        <script src="/YOUR_PATH/global.js" type="text/javascript"></script>
        <!-- Now we can reference variables, objects, functions etc. 
             defined in global.js -->
        <script src="/YOUR_PATH/otherJsFile.js" type="text/javascript"></script>
    </head>
    [...]
</html>

You could, of course, link in the script tags just before the closing <body>-tag if you do not want the load of js-files to interrupt the initial page load.

Centering controls within a form in .NET (Winforms)?

I found a great way to do this and it will work with multiple controls. Add a TableLayout with 3 columns. Make the center column an absolute size (however much room you need). Set the two outside columns to 100%. Add a Panel to the center column and add any controls you need and place them where you want. That center panel will now remain centered in your form.

Reset/remove CSS styles for element only

If anyone is coming here looking for an answer that utilizes iframe here it is

<iframe srcdoc="<html><body>your-html-here</body></html>" />

https://caniuse.com/iframe-srcdoc

Declare a variable in DB2 SQL

I'm coming from a SQL Server background also and spent the past 2 weeks figuring out how to run scripts like this in IBM Data Studio. Hope it helps.

CREATE VARIABLE v_lookupid INTEGER DEFAULT (4815162342); --where 4815162342 is your variable data 
  SELECT * FROM DB1.PERSON WHERE PERSON_ID = v_lookupid;
  SELECT * FROM DB1.PERSON_DATA WHERE PERSON_ID = v_lookupid;
  SELECT * FROM DB1.PERSON_HIST WHERE PERSON_ID = v_lookupid;
DROP VARIABLE v_lookupid; 

Why ModelState.IsValid always return false in mvc

As Brad Wilson states in his answer here:

ModelState.IsValid tells you if any model errors have been added to ModelState.

The default model binder will add some errors for basic type conversion issues (for example, passing a non-number for something which is an "int"). You can populate ModelState more fully based on whatever validation system you're using.

Try using :-

if (!ModelState.IsValid)
{
    var errors = ModelState.SelectMany(x => x.Value.Errors.Select(z => z.Exception));

    // Breakpoint, Log or examine the list with Exceptions.
}

If it helps catching you the error. Courtesy this and this

Css pseudo classes input:not(disabled)not:[type="submit"]:focus

Your syntax is pretty screwy.

Change this:

input:not(disabled)not:[type="submit"]:focus{

to:

input:not(:disabled):not([type="submit"]):focus{

Seems that many people don't realize :enabled and :disabled are valid CSS selectors...

android : Error converting byte to dex

If you are applying any plugins. Then, in your module Gradle file (usually the app/build.gradle),make sure you add the apply plugin line at the bottom of the file to enable the Gradle plugin.

e.g.

For Example:

Need to remove href values when printing in Chrome

If you use the following CSS

<link href="~/Content/common/bootstrap.css" rel="stylesheet" type="text/css"    />
<link href="~/Content/common/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/common/site.css" rel="stylesheet" type="text/css" />

just change it into the following style by adding media="screen"

<link href="~/Content/common/bootstrap.css" rel="stylesheet" **media="screen"** type="text/css" />
<link href="~/Content/common/bootstrap.min.css" rel="stylesheet" **media="screen"** type="text/css" />
<link href="~/Content/common/site.css" rel="stylesheet" **media="screen"** type="text/css" />

I think it will work.

the former answers like

    @media print {
  a[href]:after {
    content: none !important;
  }
}

were not worked well in the chrome browse.

What is tail recursion?

This is an excerpt from Structure and Interpretation of Computer Programs about tail recursion.

In contrasting iteration and recursion, we must be careful not to confuse the notion of a recursive process with the notion of a recursive procedure. When we describe a procedure as recursive, we are referring to the syntactic fact that the procedure definition refers (either directly or indirectly) to the procedure itself. But when we describe a process as following a pattern that is, say, linearly recursive, we are speaking about how the process evolves, not about the syntax of how a procedure is written. It may seem disturbing that we refer to a recursive procedure such as fact-iter as generating an iterative process. However, the process really is iterative: Its state is captured completely by its three state variables, and an interpreter need keep track of only three variables in order to execute the process.

One reason that the distinction between process and procedure may be confusing is that most implementations of common languages (including Ada, Pascal, and C) are designed in such a way that the interpretation of any recursive procedure consumes an amount of memory that grows with the number of procedure calls, even when the process described is, in principle, iterative. As a consequence, these languages can describe iterative processes only by resorting to special-purpose “looping constructs” such as do, repeat, until, for, and while. The implementation of Scheme does not share this defect. It will execute an iterative process in constant space, even if the iterative process is described by a recursive procedure. An implementation with this property is called tail-recursive. With a tail-recursive implementation, iteration can be expressed using the ordinary procedure call mechanism, so that special iteration constructs are useful only as syntactic sugar.

Remote desktop connection protocol error 0x112f

Might not be a solution for all but I found that if I reduced the screen resolution of the RDP session, I was able to get in. The server was at 95% capacity I went from 3 high res monitors to 1 800x600 window.

Converting between datetime and Pandas Timestamp objects

Pandas Timestamp to datetime.datetime:

pd.Timestamp('2014-01-23 00:00:00', tz=None).to_pydatetime()

datetime.datetime to Timestamp

pd.Timestamp(datetime(2014, 1, 23))

How to throw a C++ exception

Just add throw where needed, and try block to the caller that handles the error. By convention you should only throw things that derive from std::exception, so include <stdexcept> first.

int compare(int a, int b) {
    if (a < 0 || b < 0) {
        throw std::invalid_argument("a or b negative");
    }
}

void foo() {
    try {
        compare(-1, 0);
    } catch (const std::invalid_argument& e) {
        // ...
    }
}

Also, look into Boost.Exception.

ARG or ENV, which one to use in this case?

From Dockerfile reference:

  • The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg <varname>=<value> flag.

  • The ENV instruction sets the environment variable <key> to the value <value>.
    The environment variables set using ENV will persist when a container is run from the resulting image.

So if you need build-time customization, ARG is your best choice.
If you need run-time customization (to run the same image with different settings), ENV is well-suited.

If I want to add let's say 20 (a random number) of extensions or any other feature that can be enable|disable

Given the number of combinations involved, using ENV to set those features at runtime is best here.

But you can combine both by:

  • building an image with a specific ARG
  • using that ARG as an ENV

That is, with a Dockerfile including:

ARG var
ENV var=${var}

You can then either build an image with a specific var value at build-time (docker build --build-arg var=xxx), or run a container with a specific runtime value (docker run -e var=yyy)

get data from mysql database to use in javascript

Do you really need to "build" it from javascript or can you simply return the built HTML from PHP and insert it into the DOM?

  1. Send AJAX request to php script
  2. PHP script processes request and builds table
  3. PHP script sends response back to JS in form of encoded HTML
  4. JS takes response and inserts it into the DOM

What is AF_INET, and why do I need it?

The primary purpose of AF_INET was to allow for other possible network protocols or address families (AF is for address family; PF_INET is for the (IPv4) internet protocol family). For example, there probably are a few Netware SPX/IPX networks around still; there were other network systems like DECNet, StarLAN and SNA, not to mention the ill-begotten ISO OSI (Open Systems Interconnection), and these did not necessarily use the now ubiquitous IP address to identify the peer host in network connections.

The ubiquitous alternative to AF_INET (which, in retrospect, should have been named AF_INET4) is AF_INET6, for the IPv6 address family. IPv4 uses 32-bit addresses; IPv6 uses 128-bit addresses.

You may see some other values - but they are unusual. It is there to allow for alternatives and future directions. The sockets interface is actually very general indeed - which is one of the reasons it has thrived where other networking interfaces have withered.

Life has (mostly) gotten simpler - be grateful.

How to 'update' or 'overwrite' a python list

What about replace the item if you know the position:

aList[0]=2014

Or if you don't know the position loop in the list, find the item and then replace it

aList = [123, 'xyz', 'zara', 'abc']
    for i,item in enumerate(aList):
      if item==123:
        aList[i]=2014
        break
    
    print aList

How to convert a string to ASCII

For Any String try this:

string s = Console.ReadLine();
foreach( char c in s)
{
    Console.WriteLine(System.Convert.ToInt32(c));
}
Console.ReadKey();

How to set URL query params in Vue with Vue-Router

For adding multiple query params, this is what worked for me (from here https://forum.vuejs.org/t/vue-router-programmatically-append-to-querystring/3655/5).

an answer above was close … though with Object.assign it will mutate this.$route.query which is not what you want to do … make sure the first argument is {} when doing Object.assign

this.$router.push({ query: Object.assign({}, this.$route.query, { newKey: 'newValue' }) });

How do I get a Cron like scheduler in Python?

More or less same as above but concurrent using gevent :)

"""Gevent based crontab implementation"""

from datetime import datetime, timedelta
import gevent

# Some utility classes / functions first
def conv_to_set(obj):
    """Converts to set allowing single integer to be provided"""

    if isinstance(obj, (int, long)):
        return set([obj])  # Single item
    if not isinstance(obj, set):
        obj = set(obj)
    return obj

class AllMatch(set):
    """Universal set - match everything"""
    def __contains__(self, item): 
        return True

allMatch = AllMatch()

class Event(object):
    """The Actual Event Class"""

    def __init__(self, action, minute=allMatch, hour=allMatch, 
                       day=allMatch, month=allMatch, daysofweek=allMatch, 
                       args=(), kwargs={}):
        self.mins = conv_to_set(minute)
        self.hours = conv_to_set(hour)
        self.days = conv_to_set(day)
        self.months = conv_to_set(month)
        self.daysofweek = conv_to_set(daysofweek)
        self.action = action
        self.args = args
        self.kwargs = kwargs

    def matchtime(self, t1):
        """Return True if this event should trigger at the specified datetime"""
        return ((t1.minute     in self.mins) and
                (t1.hour       in self.hours) and
                (t1.day        in self.days) and
                (t1.month      in self.months) and
                (t1.weekday()  in self.daysofweek))

    def check(self, t):
        """Check and run action if needed"""

        if self.matchtime(t):
            self.action(*self.args, **self.kwargs)

class CronTab(object):
    """The crontab implementation"""

    def __init__(self, *events):
        self.events = events

    def _check(self):
        """Check all events in separate greenlets"""

        t1 = datetime(*datetime.now().timetuple()[:5])
        for event in self.events:
            gevent.spawn(event.check, t1)

        t1 += timedelta(minutes=1)
        s1 = (t1 - datetime.now()).seconds + 1
        print "Checking again in %s seconds" % s1
        job = gevent.spawn_later(s1, self._check)

    def run(self):
        """Run the cron forever"""

        self._check()
        while True:
            gevent.sleep(60)

import os 
def test_task():
    """Just an example that sends a bell and asd to all terminals"""

    os.system('echo asd | wall')  

cron = CronTab(
  Event(test_task, 22, 1 ),
  Event(test_task, 0, range(9,18,2), daysofweek=range(0,5)),
)
cron.run()

Copy a git repo without history

Use the following command:

git clone --depth <depth> -b <branch> <repo_url>

Where:

  • depth is the amount of commits you want to include. i.e. if you just want the latest commit use git clone --depth 1
  • branch is the name of the remote branch that you want to clone from. i.e. if you want the last 3 commits from master branch use git clone --depth 3 -b master
  • repo_url is the url of your repository

How to use Tomcat 8.5.x and TomEE 7.x with Eclipse?

This workaround worked for me. I edited the serverInfo.properties file as given below:

server.info=Apache Tomcat/8.0.0
server.number=8.0.0.0
server.built=Oct 6 2016 20:15:31 UTC

TypeError: list indices must be integers or slices, not str

First, array_length should be an integer and not a string:

array_length = len(array_dates)

Second, your for loop should be constructed using range:

for i in range(array_length):  # Use `xrange` for python 2.

Third, i will increment automatically, so delete the following line:

i += 1

Note, one could also just zip the two lists given that they have the same length:

import csv

dates = ['2020-01-01', '2020-01-02', '2020-01-03']
urls = ['www.abc.com', 'www.cnn.com', 'www.nbc.com']

csv_file_patch = '/path/to/filename.csv'

with open(csv_file_patch, 'w') as fout:
    csv_file = csv.writer(fout, delimiter=';', lineterminator='\n')
    result_array = zip(dates, urls)
    csv_file.writerows(result_array)

What is the default text size on Android?

This will return default size of text on button in pixels.


Kotlin

val size = Button(this).textSize


Java

float size = new Button(this).getTextSize();

How to get a unix script to run every 15 seconds?

#! /bin/sh

# Run all programs in a directory in parallel
# Usage: run-parallel directory delay
# Copyright 2013 by Marc Perkel
# docs at http://wiki.junkemailfilter.com/index.php/How_to_run_a_Linux_script_every_few_seconds_under_cron"
# Free to use with attribution

if [ $# -eq 0 ]
then
   echo
   echo "run-parallel by Marc Perkel"
   echo
   echo "This program is used to run all programs in a directory in parallel" 
   echo "or to rerun them every X seconds for one minute."
   echo "Think of this program as cron with seconds resolution."
   echo
   echo "Usage: run-parallel [directory] [delay]"
   echo
   echo "Examples:"
   echo "   run-parallel /etc/cron.20sec 20"
   echo "   run-parallel 20"
   echo "   # Runs all executable files in /etc/cron.20sec every 20 seconds or 3 times a minute."
   echo 
   echo "If delay parameter is missing it runs everything once and exits."
   echo "If only delay is passed then the directory /etc/cron.[delay]sec is assumed."
   echo
   echo 'if "cronsec" is passed then it runs all of these delays 2 3 4 5 6 10 12 15 20 30'
   echo "resulting in 30 20 15 12 10 6 5 4 3 2 executions per minute." 
   echo
   exit
fi

# If "cronsec" is passed as a parameter then run all the delays in parallel

if [ $1 = cronsec ]
then
   $0 2 &
   $0 3 &
   $0 4 &
   $0 5 &
   $0 6 &
   $0 10 &
   $0 12 &
   $0 15 &
   $0 20 &
   $0 30 &
   exit
fi

# Set the directory to first prameter and delay to second parameter

dir=$1
delay=$2

# If only parameter is 2,3,4,5,6,10,12,15,20,30 then automatically calculate 
# the standard directory name /etc/cron.[delay]sec

if [[ "$1" =~ ^(2|3|4|5|6|10|12|15|20|30)$ ]]
then
   dir="/etc/cron.$1sec"
   delay=$1
fi

# Exit if directory doesn't exist or has no files

if [ ! "$(ls -A $dir/)" ]
then
   exit
fi

# Sleep if both $delay and $counter are set

if [ ! -z $delay ] && [ ! -z $counter ]
then
   sleep $delay
fi

# Set counter to 0 if not set

if [ -z $counter ]
then
   counter=0
fi

# Run all the programs in the directory in parallel
# Use of timeout ensures that the processes are killed if they run too long

for program in $dir/* ; do
   if [ -x $program ] 
   then
      if [ "0$delay" -gt 1 ] 
      then
         timeout $delay $program &> /dev/null &
      else
         $program &> /dev/null &
      fi
   fi
done

# If delay not set then we're done

if [ -z $delay ]
then
   exit
fi

# Add delay to counter

counter=$(( $counter + $delay ))

# If minute is not up - call self recursively

if [ $counter -lt 60 ]
then
   . $0 $dir $delay &
fi

# Otherwise we're done

What does %~dp0 mean, and how does it work?

An example would be nice - here's a trivial one

for %I in (*.*) do @echo %~xI

it lists only the EXTENSIONS of each file in current folder

for more useful variable combinations (also listed in previous response) from the CMD prompt execute: HELP FOR which contains this snippet

The modifiers can be combined to get compound results:

%~dpI       - expands %I to a drive letter and path only
%~nxI       - expands %I to a file name and extension only
%~fsI       - expands %I to a full path name with short names only
%~dp$PATH:I - searches the directories listed in the PATH
               environment variable for %I and expands to the
               drive letter and path of the first one found.
%~ftzaI     - expands %I to a DIR like output line

Pipe to/from the clipboard in Bash script

On the Windows subsystem for Linux you can copy to the clipboard with clip.exe.

cat file | clip.exe

Keep in mind to use the | pipe command. And not a > command, since that will not work.

How to read existing text files without defining path

There are many ways to get a path. See CurrentDirrectory mentioned. Also, you can get the full file name of your application by using Assembly.GetExecutingAssembly().Location and then use Path class to get a directory name.

Bad Request - Invalid Hostname IIS7

This page by Microsoft describes how to set up access to IIS Server Express from other computers on the local network.

In a nutshell:

1) from a command prompt with admin privileges:

netsh http add urlacl url=http://[your ip address]:8181/ user=everyone

2) In Windows Firewall with Advanced Security, create a new inbound rule for port 8181 to allow external connections

3) In applicationhost.config, in the node for your project, add:

<binding protocol="http" bindingInformation="*:8181:[your ip address]" />

Do NOT add (as was suggested in another answer):

<binding protocol="http" bindingInformation="*:8181:*" />

The above wildcard binding broke my access from http://192.168.1.6:8181/

Is there a way to use two CSS3 box shadows on one element?

You can comma-separate shadows:

box-shadow: inset 0 2px 0px #dcffa6, 0 2px 5px #000;

This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint

From Android Studio v3 and up, Infer Constraint was removed from the dropdown.

Use the magic wand icon in the toolbar menu above the design preview; there is the "Infer Constraints" button. Click on this button, this will automatically add some lines in the text field and the red line will be removed.

enter image description here

Find the version of an installed npm package

Another quick way of finding out what packages are installed locally and without their dependencies is to use:

npm list --depth=0

Which gives you something like

+-- [email protected]
+-- [email protected]
+-- [email protected]
+-- [email protected]
+-- [email protected]
+-- [email protected]
+-- [email protected]
+-- [email protected]
+-- [email protected]
+-- [email protected]
+-- [email protected]
+-- [email protected]

Obviously, the same can be done globally with npm list -g --depth=0.

This method is clearer in case you have installed a lot of packages.

To find out which packages need to be updated, you can use npm outdated -g --depth=0.

How to get mouse position in jQuery without mouse-events?

var CurrentMouseXPostion;
var CurrentMouseYPostion;

$(document).mousemove(function(event) {
    CurrentMouseXPostion = event.pageX;
    CurrentMouseYPostion = event.pageY;
});

Make an eventListener on the main object , in my case the document object, to get the mouse coords every frame and store them in global variables, and like that you can read mouse Y & Z whenever youlike , wherever you like.

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger

Had the same problem, it was indeed caused by weblogic stupidly using its own opensaml implementation. To solve it, you have to tell it to load classes from WEB-INF/lib for this package in weblogic.xml:

    <prefer-application-packages>
        <package-name>org.opensaml.*</package-name>
    </prefer-application-packages>

maybe <prefer-web-inf-classes>true</prefer-web-inf-classes> would work too.

Trying to check if username already exists in MySQL database using PHP

Here's one that i wrote:

$error = false;
$sql= "SELECT username FROM users WHERE username = '$username'";
$checkSQL = mysqli_query($db, $checkSQL);

if(mysqli_num_rows($checkSQL) != 0) {
   $error = true;
   echo '<span class="error">Username taken.</span>';
}

Works like a charm!

Which programming languages can be used to develop in Android?

Here's a list of languages that can be used to develop on android:

  • Java - primary android development language

  • Kotlin, language from JetBrains which received first-party support from Google, announced in Google I/O 2017

  • C++ - NDK for libraries, not apps

  • Python, bash, et. al. - Via the Scripting Environment

  • Corona- One is to use the Corona SDK . Corona is a high level SDK built on the Lua programming language. Lua is much simpler to learn than Java and the SDK takes away a lot of the pain in developing Android app.

  • Cordova - which uses HTML5, JavaScript, CSS, and can be extended with Java

  • Xamarin technology - that uses c# and in which mono is used for that. Here MonoTouch and Mono for Android are cross-platform implementations of the Common Language Infrastructure (CLI) and Common Language Specifications.

As for your second question: android is highly dependent on it's java architecture, I find it unlikely that there will be other primary development languages available any time soon. However, there's no particular reason why someone couldn't implement another language in Java (something like Jython) and use that. However, that surely won't be easier or as performant as just writing the code in Java.

Filename too long in Git for Windows

Create .gitconfig and add

[core]
longpaths = true

You can create the file in a project location (not sure) and also in the global location. In my case the location is C:\Users\{name}\.

SQL "between" not inclusive

cast(created_at as date)

That will work only in 2008 and newer versions of SQL Server

If you are using older version then use

convert(varchar, created_at, 101)

How do I use the ternary operator ( ? : ) in PHP as a shorthand for "if / else"?

Conditional Welcome Message

echo 'Welcome '.($user['is_logged_in'] ? $user['first_name'] : 'Guest').'!';

Nested PHP Shorthand

echo 'Your score is:  '.($score > 10 ? ($age > 10 ? 'Average' : 'Exceptional') : ($age > 10 ? 'Horrible' : 'Average') );

Best way to do a split pane in HTML

I wanted a vanilla, lightweight (jQuery UI Layout weighs in at 185 KB), no dependency option (all existing libraries require jQuery), so I wrote Split.js.

It weights less than 2 KB and does not require any special markup. It supports older browsers back to Internet Explorer 9 (or Internet Explorer 8 with polyfills). For modern browsers, you can use it with Flexbox and grid layouts.

Auto-size dynamic text to fill fixed size container

I had exactly the same problem with my website. I have a page that is displayed on a projector, on walls, big screens..

As I don't know the max size of my font, I re-used the plugin above of @GeekMonkey but incrementing the fontsize :

$.fn.textfill = function(options) {
        var defaults = { innerTag: 'span', padding: '10' };
        var Opts = jQuery.extend(defaults, options);

        return this.each(function() {
            var ourText = $(Opts.innerTag + ':visible:first', this);
            var fontSize = parseFloat(ourText.css('font-size'),10);
            var doNotTrepass = $(this).height()-2*Opts.padding ;
            var textHeight;

            do {
                ourText.css('font-size', fontSize);
                textHeight = ourText.height();
                fontSize = fontSize + 2;
            } while (textHeight < doNotTrepass );
        });
    };

How to create a custom string representation for a class object?

Ignacio Vazquez-Abrams' approved answer is quite right. It is, however, from the Python 2 generation. An update for the now-current Python 3 would be:

class MC(type):
  def __repr__(self):
    return 'Wahaha!'

class C(object, metaclass=MC):
    pass

print(C)

If you want code that runs across both Python 2 and Python 3, the six module has you covered:

from __future__ import print_function
from six import with_metaclass

class MC(type):
  def __repr__(self):
    return 'Wahaha!'

class C(with_metaclass(MC)):
    pass

print(C)

Finally, if you have one class that you want to have a custom static repr, the class-based approach above works great. But if you have several, you'd have to generate a metaclass similar to MC for each, and that can get tiresome. In that case, taking your metaprogramming one step further and creating a metaclass factory makes things a bit cleaner:

from __future__ import print_function
from six import with_metaclass

def custom_class_repr(name):
    """
    Factory that returns custom metaclass with a class ``__repr__`` that
    returns ``name``.
    """
    return type('whatever', (type,), {'__repr__': lambda self: name})

class C(with_metaclass(custom_class_repr('Wahaha!'))): pass

class D(with_metaclass(custom_class_repr('Booyah!'))): pass

class E(with_metaclass(custom_class_repr('Gotcha!'))): pass

print(C, D, E)

prints:

Wahaha! Booyah! Gotcha!

Metaprogramming isn't something you generally need everyday—but when you need it, it really hits the spot!

How to align this span to the right of the div?

If you can modify the HTML: http://jsfiddle.net/8JwhZ/3/

<div class="title">
  <span class="name">Cumulative performance</span>
  <span class="date">20/02/2011</span>
</div>

.title .date { float:right }
.title .name { float:left }

How to remove special characters from a string?

To Remove Special character

String t2 = "!@#$%^&*()-';,./?><+abdd";

t2 = t2.replaceAll("\\W+","");

Output will be : abdd.

This works perfectly.

How can I import a database with MySQL from terminal?

After struggling for sometime I found the information in https://tommcfarlin.com/importing-a-large-database/

  1. Connect to Mysql (let's use root for both username and password):

    mysql -uroot -proot
    
  2. Connect to the database (let's say it is called emptyDatabase (your should get a confirmation message):

    connect emptyDatabase
    

3 Import the source code, lets say the file is called mySource.sql and it is in a folder called mySoureDb under the profile of a user called myUser:

source /Users/myUser/mySourceDB/mySource.sql

Multiple parameters in a List. How to create without a class?

Another solution create generic list of anonymous type.

 var list = new[]
 { 
    new { Number = 10, Name = "Smith" },
    new { Number = 10, Name = "John" } 
 }.ToList();

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

This also gives you intellisense support, I think in some situations its better than Tuple and Dictionary.

How do I drag and drop files into an application?

You need to be aware of a gotcha. Any class that you pass around as the DataObject in the drag/drop operation has to be Serializable. So if you try and pass an object, and it is not working, ensure it can be serialized as that is almost certainly the problem. This has caught me out a couple of times!

C# Java HashMap equivalent

Use Dictionary - it uses hashtable but is typesafe.

Also, your Java code for

int a = map.get(key);
//continue with your logic

will be best coded in C# this way:

int a;
if(dict.TryGetValue(key, out a)){
//continue with your logic
}

This way, you can scope the need of variable "a" inside a block and it is still accessible outside the block if you need it later.

How can I slice an ArrayList out of an ArrayList in Java?

I have found a way if you know startIndex and endIndex of the elements one need to remove from ArrayList

Let al be the original ArrayList and startIndex,endIndex be start and end index to be removed from the array respectively:

al.subList(startIndex, endIndex + 1).clear();

How to auto-indent code in the Atom editor?

I was working on some groovy code, which doesn't auto-format on save. What I did was right-click on the code pane, then chose ESLint Fix. That fixed my indents.

enter image description here

PHP PDO returning single row

Did you try:

$DBH = new PDO( "connection string goes here" );
$row = $DBH->query( "select figure from table1" )->fetch();
echo $row["figure"];
$DBH = null;

"use database_name" command in PostgreSQL

When you get a connection to PostgreSQL it is always to a particular database. To access a different database, you must get a new connection.

Using \c in psql closes the old connection and acquires a new one, using the specified database and/or credentials. You get a whole new back-end process and everything.

Make a simple fade in animation in Swift?

If you want repeatable fade animation you can do that by using CABasicAnimation like below :

First create handy UIView extension :

extension UIView {

    enum AnimationKeyPath: String {
        case opacity = "opacity"
    }

    func flash(animation: AnimationKeyPath ,withDuration duration: TimeInterval = 0.5, repeatCount: Float = 5){
        let flash = CABasicAnimation(keyPath: animation.rawValue)
        flash.duration = duration
        flash.fromValue = 1 // alpha
        flash.toValue = 0 // alpha
        flash.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
        flash.autoreverses = true
        flash.repeatCount = repeatCount

        layer.add(flash, forKey: nil)
    }
}

How to use it:

    // You can use it with all kind of UIViews e.g. UIButton, UILabel, UIImage, UIImageView, ...
    imageView.flash(animation: .opacity, withDuration: 1, repeatCount: 5)
    titleLabel.flash(animation: .opacity, withDuration: 1, repeatCount: 5)

How can I make a UITextField move up when the keyboard is present - on starting to edit?

I use Swift and auto layout (but can't comment on the previous Swift answer); here's how I do it without a scroll view:

I layout my form in IB with vertical constraints between the fields to separate them. I add a vertical constraint from the topmost field to the container view, and create an outlet to that (topSpaceForFormConstraint in the code below). All that's needed is to update this constraint, which I do in an animation block for a nice soft motion. The height check is optional of course, in this case I needed to do it just for the smallest screen size.

This can be called using any of the usual textFieldDidBeginEditing or keyboardWillShow methods.

func setFormHeight(top: CGFloat)
{
    let height = UIScreen.mainScreen().bounds.size.height

    // restore text input fields for iPhone 4/4s
    if (height < 568) {
        UIView.animateWithDuration(0.2, delay: 0.0, options: nil, animations: {
            self.topSpaceForFormConstraint.constant = top
            self.view.layoutIfNeeded()
            }, completion: nil)
    }

}

Can the :not() pseudo-class have multiple arguments?

If you're using SASS in your project, I've built this mixin to make it work the way we all want it to:

@mixin not($ignorList...) {
    //if only a single value given
    @if (length($ignorList) == 1){
        //it is probably a list variable so set ignore list to the variable
        $ignorList: nth($ignorList,1);
    }
    //set up an empty $notOutput variable
    $notOutput: '';
    //for each item in the list
    @each $not in $ignorList {
        //generate a :not([ignored_item]) segment for each item in the ignore list and put them back to back
        $notOutput: $notOutput + ':not(#{$not})';
    }
    //output the full :not() rule including all ignored items
    &#{$notOutput} {
        @content;
    }
}

it can be used in 2 ways:

Option 1: list the ignored items inline

input {
  /*non-ignored styling goes here*/
  @include not('[type="radio"]','[type="checkbox"]'){
    /*ignored styling goes here*/
  }
}

Option 2: list the ignored items in a variable first

$ignoredItems:
  '[type="radio"]',
  '[type="checkbox"]'
;

input {
  /*non-ignored styling goes here*/
  @include not($ignoredItems){
    /*ignored styling goes here*/
  }
}

Outputted CSS for either option

input {
    /*non-ignored styling goes here*/
}

input:not([type="radio"]):not([type="checkbox"]) {
    /*ignored styling goes here*/
}

How to build splash screen in windows forms application?

Maybe a bit late to answer but i would like to share my way. I found an easy way with threads in the main program for a winform application.

Lets say you have your form "splashscreen" with an animation, and your "main" which has all your application code.

 [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Thread mythread;
        mythread = new Thread(new ThreadStart(ThreadLoop));
        mythread.Start();
        Application.Run(new MainForm(mythread));           
    }

    public static void ThreadLoop()
    {
        Application.Run(new SplashScreenForm());           
    }

In your main form in the constructor:

 public MainForm(Thread splashscreenthread)
    {
        InitializeComponent();

        //add your constructor code

        splashscreenthread.Abort();            
    }

This way the splashscreen will last just the time for your main form to load.

Your splashcreen form should have his own way to animate/display information. In my project my splashscreen start a new thread, and every x milliseconds it changes his main picture to another which is a slightly different gear, giving the illusion of a rotation.

example of my splashscreen:

int status = 0;
private bool IsRunning = false;
    public Form1()
    {
        InitializeComponent();
        StartAnimation();
    }

    public void StartAnimation()
    {
        backgroundWorker1.WorkerReportsProgress = false;
        backgroundWorker1.WorkerSupportsCancellation = true;
        IsRunning = true;
        backgroundWorker1.RunWorkerAsync();
    }


    public void StopAnimation()
    {
        backgroundWorker1.CancelAsync();
    }

    delegate void UpdatingThreadAnimation();
    public void UpdateAnimationFromThread()
    {

        try
        {
            if (label1.InvokeRequired == false)
            {
                UpdateAnimation();
            }
            else
            {
                UpdatingThreadAnimation d = new UpdatingThreadAnimation(UpdateAnimationFromThread);
                this.Invoke(d, new object[] { });
            }
        }
        catch(Exception e)
        {

        }
    }

 private void UpdateAnimation()
    {
    if(status ==0) 
    {
    // mypicture.image = image1
     }else if(status ==1)
     {
    // mypicture.image = image2
     }
    //doing as much as needed

      status++;
        if(status>1) //change here if you have more image, the idea is to set a cycle of images
        {
            status = 0;
        }
        this.Refresh();
    }

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = sender as BackgroundWorker;
        while (IsRunning == true)
        {
            System.Threading.Thread.Sleep(100);
            UpdateAnimationFromThread();
        }
    }

Hope this will help some people. Sorry if i have made some mistakes. English is not my first language.

Android WebView progress bar

I have just found a really good example of how to do this here: http://developer.android.com/reference/android/webkit/WebView.html . You just need to change the setprogress from:

activity.setProgress(progress * 1000);

to

activity.setProgress(progress * 100);

Get UserDetails object from Security Context in Spring MVC controller

if you are using spring security then you can get the current logged in user by

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
     String name = auth.getName(); //get logged in username

Is ini_set('max_execution_time', 0) a bad idea?

Reason is to have some value other than zero. General practice to have it short globally and long for long working scripts like parsers, crawlers, dumpers, exporting & importing scripts etc.

  1. You can halt server, corrupt work of other people by memory consuming script without even knowing it.
  2. You will not be seeing mistakes where something, let's say, infinite loop happened, and it will be harder to diagnose.
  3. Such site may be easily DoSed by single user, when requesting pages with long execution time

Android view layout_width - how to change programmatically?

try using

View view_instance = (View)findViewById(R.id.nutrition_bar_filled);
view_instance.setWidth(10);

use Layoutparams to do so where you can set width and height like below.

LayoutParams lp = new LayoutParams(10,LayoutParams.wrap_content);
View_instance.setLayoutParams(lp);

How to call a function after a div is ready?

inside your <div></div> element you can call the $(document).ready(function(){}); execute a command, something like

<div id="div1">
    <script>
        $(document).ready(function(){
         //do something
        });
    </script>
</div>

and you can do the same to other divs that you have. this was suitable if you loading your div via partial view

implementing merge sort in C++

Based on the code here: http://cplusplus.happycodings.com/algorithms/code17.html

// Merge Sort

#include <iostream>
using namespace std;

int a[50];
void merge(int,int,int);
void merge_sort(int low,int high)
{
 int mid;
 if(low<high)
 {
  mid = low + (high-low)/2; //This avoids overflow when low, high are too large
  merge_sort(low,mid);
  merge_sort(mid+1,high);
  merge(low,mid,high);
 }
}
void merge(int low,int mid,int high)
{
 int h,i,j,b[50],k;
 h=low;
 i=low;
 j=mid+1;

 while((h<=mid)&&(j<=high))
 {
  if(a[h]<=a[j])
  {
   b[i]=a[h];
   h++;
  }
  else
  {
   b[i]=a[j];
   j++;
  }
  i++;
 }
 if(h>mid)
 {
  for(k=j;k<=high;k++)
  {
   b[i]=a[k];
   i++;
  }
 }
 else
 {
  for(k=h;k<=mid;k++)
  {
   b[i]=a[k];
   i++;
  }
 }
 for(k=low;k<=high;k++) a[k]=b[k];
}
int main()
{
 int num,i;

cout<<"*******************************************************************
*************"<<endl;
 cout<<"                             MERGE SORT PROGRAM
"<<endl;

cout<<"*******************************************************************
*************"<<endl;
 cout<<endl<<endl;
 cout<<"Please Enter THE NUMBER OF ELEMENTS you want to sort [THEN 
PRESS
ENTER]:"<<endl;
 cin>>num;
 cout<<endl;
 cout<<"Now, Please Enter the ( "<< num <<" ) numbers (ELEMENTS) [THEN
PRESS ENTER]:"<<endl;
 for(i=1;i<=num;i++)
 {
  cin>>a[i] ;
 }
 merge_sort(1,num);
 cout<<endl;
 cout<<"So, the sorted list (using MERGE SORT) will be :"<<endl;
 cout<<endl<<endl;

 for(i=1;i<=num;i++)
 cout<<a[i]<<"  ";

 cout<<endl<<endl<<endl<<endl;
return 1;

}

Bootstrap Element 100% Width

Instead of

style="width:100%"

try using

class="col-xs-12"

it will save you 1 character :)

A CSS selector to get last visible div

If you no longer need the hided elements, just use element.remove() instead of element.style.display = 'none';.

adding and removing classes in angularJs using ng-click

I want to add or remove "active" class in my code dynamically on ng-click, here what I have done.

<ul ng-init="selectedTab = 'users'">
   <li ng-class="{'active':selectedTab === 'users'}" ng-click="selectedTab = 'users'"><a href="#users" >Users</a></li>
   <li ng-class="{'active':selectedTab === 'items'}" ng-click="selectedTab = 'items'"><a href="#items" >Items</a></li>
</ul>

span with onclick event inside a tag

use onmouseup

try something like this

        <html>
        <head>
        <script type="text/javascript">
        function hide(){
        document.getElementById('span_hide').style.display="none";
        }
        </script>
        </head>

        <body>
        <a href="page" style="text-decoration:none;display:block;">
        <span   onmouseup="hide()" id="span_hide">Hide me</span>
        </a>
        </body>
        </html>

EDIT:

          <html>
        <head>
        <script type="text/javascript">
        $(document).ready(function(){
         $("a").click(function () { 
         $(this).fadeTo("fast", .5).removeAttr("href"); 
        });
        });
        function hide(){
        document.getElementById('span_hide').style.display="none";
        }
        </script>
        </head>

        <body>
        <a href="page.html" style="text-decoration:none;display:block;" onclick="return false" >
        <span   onmouseup="hide()" id="span_hide">Hide me</span>
        </a>
        </body>
        </html>

How do I hide anchor text without hiding the anchor?

I was able to fix this problem by setting font-size: 0 .

iptables block access to port 8000 except from IP address

This question should be on Server Fault. Nevertheless, the following should do the trick, assuming you're talking about TCP and the IP you want to allow is 1.2.3.4:

iptables -A INPUT -p tcp --dport 8000 -s 1.2.3.4 -j ACCEPT
iptables -A INPUT -p tcp --dport 8000 -j DROP

"An access token is required to request this resource" while accessing an album / photo with Facebook php sdk

There are 3 things you need.

  1. You need to oAuth with the owner of those photos. (with the 'user_photos' extended permission)

  2. You need the access token (which you get returned in the URL box after the oAuth is done.)

  3. When those are complete you can then access the photos like so https://graph.facebook.com/me?access_token=ACCESS_TOKEN

You can find all of the information in more detail here: http://developers.facebook.com/docs/authentication

String contains - ignore case

You can use

org.apache.commons.lang3.StringUtils.containsIgnoreCase(CharSequence str,
                                     CharSequence searchStr);

Checks if CharSequence contains a search CharSequence irrespective of case, handling null. Case-insensitivity is defined as by String.equalsIgnoreCase(String).

A null CharSequence will return false.

This one will be better than regex as regex is always expensive in terms of performance.

For official doc, refer to : StringUtils.containsIgnoreCase

Update :

If you are among the ones who

  • don't want to use Apache commons library
  • don't want to go with the expensive regex/Pattern based solutions,
  • don't want to create additional string object by using toLowerCase,

you can implement your own custom containsIgnoreCase using java.lang.String.regionMatches

public boolean regionMatches(boolean ignoreCase,
                             int toffset,
                             String other,
                             int ooffset,
                             int len)

ignoreCase : if true, ignores case when comparing characters.

public static boolean containsIgnoreCase(String str, String searchStr)     {
    if(str == null || searchStr == null) return false;

    final int length = searchStr.length();
    if (length == 0)
        return true;

    for (int i = str.length() - length; i >= 0; i--) {
        if (str.regionMatches(true, i, searchStr, 0, length))
            return true;
    }
    return false;
}

How do you handle multiple submit buttons in ASP.NET MVC Framework?

My Solution was to use 2 asp panels:

<asp:Panel ID=”..” DefaultButton=”ID_OF_SHIPPING_SUBMIT_BUTTON”….></asp:Panel>

How to set a tkinter window to a constant size

Try parent_window.maxsize(x,x); to set the maximum size. It shouldn't get larger even if you set the background, etc.

Edit: use parent_window.minsize(x,x) also to set it to a constant size!

How to get last inserted row ID from WordPress database?

I needed to get the last id way after inserting it, so

$lastid = $wpdb->insert_id;

Was not an option.

Did the follow:

global $wpdb;
$id = $wpdb->get_var( 'SELECT id FROM ' . $wpdb->prefix . 'table' . ' ORDER BY id DESC LIMIT 1');

Live Video Streaming with PHP

PHP will let you build the pages of your site that make up your video conferencing and chat applications, but it won't deliver or stream video for you - PHP runs on the server only and renders out HTML to a client browser.

For the video, the first thing you'll need is a live streaming account with someone like akamai or the numerous others in the field. Using this account gives you an ingress point for your video - ie: the server that you will stream your live video up to.

Next, you want to get your video out to the browsers - windows media player, flash or silverlight will let you achieve this - embedding the appropriate control for your chosen technology into your page (using PHP or whatever) and given the address of your live video feed.

PHP (or other scripting language) would be used to build the chat part of the application and bring the whole thing together (the chat and the embedded video player).

Hope this helps.

asp.net: Invalid postback or callback argument

I had a similar problem because of copy paste from another page, what I got:

<form id="form1" runat="server">
    ...
    <form id="form2" runat="server">
    ....
    </form>
</form>

I just removed form with id="form2" inside form with id="form1" and issue gone. This could be not your problem but it could be something similar.

How to change the remote a branch is tracking?

If you're sane about it, editing the config file's safe enough. If you want to be a little more paranoid, you can use the porcelain command to modify it:

git config branch.master.remote newserver

Of course, if you look at the config before and after, you'll see that it did exactly what you were going to do.

But in your individual case, what I'd do is:

git remote rename origin old-origin
git remote rename new-origin origin

That is, if the new server is going to be the canonical remote, why not call it origin as if you'd originally cloned from it?

Divide a number by 3 without using *, /, +, -, % operators

Didn't cross-check if this answer is already published. If the program need to be extended to floating numbers, the numbers can be multiplied by 10*number of precision needed and then the following code can be again applied.

#include <stdio.h>

int main()
{
    int aNumber = 500;
    int gResult = 0;

    int aLoop = 0;

    int i = 0;
    for(i = 0; i < aNumber; i++)
    {
        if(aLoop == 3)
        {
           gResult++;
           aLoop = 0;
        }  
        aLoop++;
    }

    printf("Reulst of %d / 3 = %d", aNumber, gResult);

    return 0;
}

VBA vlookup reference in different sheet

Your code work fine, provided the value in Sheet2!D2 exists in Sheet1!A:A. If it does not then error 1004 is raised.

To handle this case, try

Sub Demo()
    Dim MyStringVar1 As Variant
    On Error Resume Next
    MyStringVar1 = Application.WorksheetFunction.VLookup(Range("D2"), _
      Worksheets("Sheet1").Range("A:C"), 1, False)
    On Error GoTo 0
    If IsEmpty(MyStringVar1) Then
        MsgBox "Value not found!"
    End If

    Range("E2") = MyStringVar1

End Sub

How should I import data from CSV into a Postgres table using pgAdmin 3?

pgAdmin has GUI for data import since 1.16. You have to create your table first and then you can import data easily - just right-click on the table name and click on Import.

enter image description here

enter image description here

Hexadecimal To Decimal in Shell Script

In dash and other shells, you can use

printf "%d\n" (your hexadecimal number)

to convert a hexadecimal number to decimal. This is not bash, or ksh, specific.

How to create a table from select query result in SQL Server 2008

Select [Column Name] into [New Table] from [Source Table]

Is there a .NET/C# wrapper for SQLite?

I'd definitely go with System.Data.SQLite (as previously mentioned: http://sqlite.phxsoftware.com/)

It is coherent with ADO.NET (System.Data.*), and is compiled into a single DLL. No sqlite3.dll - because the C code of SQLite is embedded within System.Data.SQLite.dll. A bit of managed C++ magic.

How to keep :active css style after click a button

CSS

:active denotes the interaction state (so for a button will be applied during press), :focus may be a better choice here. However, the styling will be lost once another element gains focus.

The final potential alternative using CSS would be to use :target, assuming the items being clicked are setting routes (e.g. anchors) within the page- however this can be interrupted if you are using routing (e.g. Angular), however this doesnt seem the case here.

_x000D_
_x000D_
.active:active {_x000D_
  color: red;_x000D_
}_x000D_
.focus:focus {_x000D_
  color: red;_x000D_
}_x000D_
:target {_x000D_
  color: red;_x000D_
}
_x000D_
<button class='active'>Active</button>_x000D_
<button class='focus'>Focus</button>_x000D_
<a href='#target1' id='target1' class='target'>Target 1</a>_x000D_
<a href='#target2' id='target2' class='target'>Target 2</a>_x000D_
<a href='#target3' id='target3' class='target'>Target 3</a>
_x000D_
_x000D_
_x000D_

Javascript / jQuery

As such, there is no way in CSS to absolutely toggle a styled state- if none of the above work for you, you will either need to combine with a change in your HTML (e.g. based on a checkbox) or programatically apply/remove a class using e.g. jQuery

_x000D_
_x000D_
$('button').on('click', function(){_x000D_
    $('button').removeClass('selected');_x000D_
    $(this).addClass('selected');_x000D_
});
_x000D_
button.selected{_x000D_
  color:red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<button>Item</button><button>Item</button><button>Item</button>_x000D_
  
_x000D_
_x000D_
_x000D_

EPPlus - Read Excel Table

I have got an error on the first answer so I have changed some code line.

Please try my new code, it's working for me.

using OfficeOpenXml;
using OfficeOpenXml.Table;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

public static class ImportExcelReader
{
    public static List<T> ImportExcelToList<T>(this ExcelWorksheet worksheet) where T : new()
    {
        //DateTime Conversion
        Func<double, DateTime> convertDateTime = new Func<double, DateTime>(excelDate =>
        {
            if (excelDate < 1)
            {
                throw new ArgumentException("Excel dates cannot be smaller than 0.");
            }

            DateTime dateOfReference = new DateTime(1900, 1, 1);

            if (excelDate > 60d)
            {
                excelDate = excelDate - 2;
            }
            else
            {
                excelDate = excelDate - 1;
            }

            return dateOfReference.AddDays(excelDate);
        });

        ExcelTable table = null;

        if (worksheet.Tables.Any())
        {
            table = worksheet.Tables.FirstOrDefault();
        }
        else
        {
            table = worksheet.Tables.Add(worksheet.Dimension, "tbl" + ShortGuid.NewGuid().ToString());

            ExcelAddressBase newaddy = new ExcelAddressBase(table.Address.Start.Row, table.Address.Start.Column, table.Address.End.Row + 1, table.Address.End.Column);

            //Edit the raw XML by searching for all references to the old address
            table.TableXml.InnerXml = table.TableXml.InnerXml.Replace(table.Address.ToString(), newaddy.ToString());
        }

        //Get the cells based on the table address
        List<IGrouping<int, ExcelRangeBase>> groups = table.WorkSheet.Cells[table.Address.Start.Row, table.Address.Start.Column, table.Address.End.Row, table.Address.End.Column]
            .GroupBy(cell => cell.Start.Row)
            .ToList();

        //Assume the second row represents column data types (big assumption!)
        List<Type> types = groups.Skip(1).FirstOrDefault().Select(rcell => rcell.Value.GetType()).ToList();

        //Get the properties of T
        List<PropertyInfo> modelProperties = new T().GetType().GetProperties().ToList();

        //Assume first row has the column names
        var colnames = groups.FirstOrDefault()
            .Select((hcell, idx) => new
            {
                Name = hcell.Value.ToString(),
                index = idx
            })
            .Where(o => modelProperties.Select(p => p.Name).Contains(o.Name))
            .ToList();

        //Everything after the header is data
        List<List<object>> rowvalues = groups
            .Skip(1) //Exclude header
            .Select(cg => cg.Select(c => c.Value).ToList()).ToList();

        //Create the collection container
        List<T> collection = new List<T>();
        foreach (List<object> row in rowvalues)
        {
            T tnew = new T();
            foreach (var colname in colnames)
            {
                //This is the real wrinkle to using reflection - Excel stores all numbers as double including int
                object val = row[colname.index];
                Type type = types[colname.index];
                PropertyInfo prop = modelProperties.FirstOrDefault(p => p.Name == colname.Name);

                //If it is numeric it is a double since that is how excel stores all numbers
                if (type == typeof(double))
                {
                    //Unbox it
                    double unboxedVal = (double)val;

                    //FAR FROM A COMPLETE LIST!!!
                    if (prop.PropertyType == typeof(int))
                    {
                        prop.SetValue(tnew, (int)unboxedVal);
                    }
                    else if (prop.PropertyType == typeof(double))
                    {
                        prop.SetValue(tnew, unboxedVal);
                    }
                    else if (prop.PropertyType == typeof(DateTime))
                    {
                        prop.SetValue(tnew, convertDateTime(unboxedVal));
                    }
                    else if (prop.PropertyType == typeof(string))
                    {
                        prop.SetValue(tnew, val.ToString());
                    }
                    else
                    {
                        throw new NotImplementedException(string.Format("Type '{0}' not implemented yet!", prop.PropertyType.Name));
                    }
                }
                else
                {
                    //Its a string
                    prop.SetValue(tnew, val);
                }
            }
            collection.Add(tnew);
        }

        return collection;
    }
}

How to call this function? please view below code;

private List<FundraiserStudentListModel> GetStudentsFromExcel(HttpPostedFileBase file)
    {
        List<FundraiserStudentListModel> list = new List<FundraiserStudentListModel>();
        if (file != null)
        {
            try
            {
                using (ExcelPackage package = new ExcelPackage(file.InputStream))
                {
                    ExcelWorkbook workbook = package.Workbook;
                    if (workbook != null)
                    {
                        ExcelWorksheet worksheet = workbook.Worksheets.FirstOrDefault();
                        if (worksheet != null)
                        {
                            list = worksheet.ImportExcelToList<FundraiserStudentListModel>();
                        }
                    }
                }
            }
            catch (Exception err)
            {
                //save error log
            }
        }
        return list;
    }

FundraiserStudentListModel here:

 public class FundraiserStudentListModel
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
}

Internet Explorer 11 detection

I use the following function to detect version 9, 10 and 11 of IE:

function ieVersion() {
    var ua = window.navigator.userAgent;
    if (ua.indexOf("Trident/7.0") > -1)
        return 11;
    else if (ua.indexOf("Trident/6.0") > -1)
        return 10;
    else if (ua.indexOf("Trident/5.0") > -1)
        return 9;
    else
        return 0;  // not IE9, 10 or 11
}  

Download large file in python with requests

Your chunk size could be too large, have you tried dropping that - maybe 1024 bytes at a time? (also, you could use with to tidy up the syntax)

def DownloadFile(url):
    local_filename = url.split('/')[-1]
    r = requests.get(url)
    with open(local_filename, 'wb') as f:
        for chunk in r.iter_content(chunk_size=1024): 
            if chunk: # filter out keep-alive new chunks
                f.write(chunk)
    return 

Incidentally, how are you deducing that the response has been loaded into memory?

It sounds as if python isn't flushing the data to file, from other SO questions you could try f.flush() and os.fsync() to force the file write and free memory;

    with open(local_filename, 'wb') as f:
        for chunk in r.iter_content(chunk_size=1024): 
            if chunk: # filter out keep-alive new chunks
                f.write(chunk)
                f.flush()
                os.fsync(f.fileno())

ORDER BY date and time BEFORE GROUP BY name in mysql

Another method:

SELECT * 
FROM (
    SELECT * FROM table_name
    ORDER BY date ASC, time ASC 
) AS sub
GROUP BY name

GROUP BY groups on the first matching result it hits. If that first matching hit happens to be the one you want then everything should work as expected.

I prefer this method as the subquery makes logical sense rather than peppering it with other conditions.

HTTP authentication logout via PHP

Method that works nicely in Safari. Also works in Firefox and Opera, but with a warning.

Location: http://[email protected]/

This tells browser to open URL with new username, overriding previous one.

What is and how to fix System.TypeInitializationException error?

I had this problem. As stated it is probably a static declaration issue. In my case it was because I had a static within a DEBUG clause. That is (in c#)

#if DEBUG
    public static bool DOTHISISINDEBUGONLY = false;
#endif

Everything worked fine until I complied a Release version of the code and after that I got this error - even on old release versions of the code. Once I took the variable out of the DEBUG clause everything returned to normal.

GitHub "fatal: remote origin already exists"

The concept of remote is simply the URL of your remote repository.

The origin is an alias pointing to that URL. So instead of writing the whole URL every single time we want to push something to our repository, we just use this alias and run:

git push -u origin master

Telling to git to push our code from our local master branch to the remote origin repository.

Whenever we clone a repository, git creates this alias for us by default. Also whenever we create a new repository, we just create it our self.

Whatever the case it is, we can always change this name to anything we like, running this:

git remote rename [current-name] [new-name]

Since it is stored on the client side of the git application (on our machine) changing it will not affect anything in our development process, neither at our remote repository. Remember, it is only a name pointing to an address.

The only thing that changes here by renaming the alias, is that we have to declare this new name every time we push something to our repository.

git push -u my-remote-alias master

Obviously a single name can not point to two different addresses. That's why you get this error message. There is already an alias named origin at your local machine. To see how many aliases you have and what are they, you can initiate this command:

git remote -v

This will show you all the aliases you have plus the corresponding URLs.

You can remove them as well if you like running this:

git remote rm my-remote-alias

So in brief:

  • find out what do you have already,
  • remove or rename them,
  • add your new aliases.

Happy coding.

How can I detect if Flash is installed and if not, display a hidden div that informs the user?

I used Adobe's detection kit, originally suggested by justpassinby. Their system is nice because it detects the version number and compares it for you against your 'required version'

One bad thing is it does an alert showing the detected version of flash, which isn't very user friendly. All of a sudden a box pops up with some seemingly random numbers.

Some modifications you might want to consider:

  • remove the alert
  • change it so it returns an object (or array) --- first element is boolean true/false for "was the required version found on user's machine" --- second element is the actual version number found on user's machine

Excel formula to get week number in month (having Monday)

Finding of week number for each date of a month (considering Monday as beginning of the week)

Keep the first date of month contant $B$13

=WEEKNUM(B18,2)-WEEKNUM($B$13,2)+1

WEEKNUM(B18,2) - returns the week number of the date mentioned in cell B18

WEEKNUM($B$13,2) - returns the week number of the 1st date of month in cell B13

How do I render a shadow?

  panel: {
    // ios
    backgroundColor: '#03A9F4',
    alignItems: 'center', 
    shadowOffset: {width: 0, height: 13}, 
    shadowOpacity: 0.3,
    shadowRadius: 6,

    // android (Android +5.0)
    elevation: 3,
  }

or you can use react-native-shadow for android

Disable a link in Bootstrap

I think you need the btn class.
It would be like this:

<a class="btn disabled" href="#">Disabled link</a>

How do you calculate program run time in python?

@JoshAdel covered a lot of it, but if you just want to time the execution of an entire script, you can run it under time on a unix-like system.

kotai:~ chmullig$ cat sleep.py 
import time

print "presleep"
time.sleep(10)
print "post sleep"
kotai:~ chmullig$ python sleep.py 
presleep
post sleep
kotai:~ chmullig$ time python sleep.py 
presleep
post sleep

real    0m10.035s
user    0m0.017s
sys 0m0.016s
kotai:~ chmullig$ 

SQL Data Reader - handling Null column values

None of these was quite what i wanted:

 public static T GetFieldValueOrDefault<T>(this SqlDataReader reader, string name)
 {
     int index = reader.GetOrdinal(name);
     T value = reader.IsDBNull(index) ? default(T) : reader.GetFieldValue<T>(index);
     return value;
 }

Get Substring - everything before certain char

Building on BrainCore's answer:

    int index = 0;   
    str = "223232-1.jpg";

    //Assuming we trust str isn't null 
    if (str.Contains('-') == "true")
    {
      int index = str.IndexOf('-');
    }

    if(index > 0) {
        return str.Substring(0, index);
    }
    else {
       return str;
    }

PHP php_network_getaddresses: getaddrinfo failed: No such host is known

A weird thing I found was that the environment variable SYSTEMROOT must be set otherwise getaddrinfo() will fail on Windows 10.

Does it make sense to use Require.js with Angular.js?

It makes sense to use requirejs with angularjs if you plan on lazy loading controllers and directives etc, while also combining multiple lazy dependencies into single script files for much faster lazy loading. RequireJS has an optimisation tool that makes the combining easy. See http://ify.io/using-requirejs-with-optimisation-for-lazy-loading-angularjs-artefacts/

Pass object to javascript function

when you pass an object within curly braces as an argument to a function with one parameter , you're assigning this object to a variable which is the parameter in this case

Check number of arguments passed to a Bash script

In case you want to be on the safe side, I recommend to use getopts.

Here is a small example:

    while getopts "x:c" opt; do
      case $opt in
        c)
          echo "-$opt was triggered, deploy to ci account" >&2
          DEPLOY_CI_ACCT="true"
          ;;
            x)
              echo "-$opt was triggered, Parameter: $OPTARG" >&2 
              CMD_TO_EXEC=${OPTARG}
              ;;
            \?)
              echo "Invalid option: -$OPTARG" >&2 
              Usage
              exit 1
              ;;
            :)
              echo "Option -$OPTARG requires an argument." >&2 
              Usage
              exit 1
              ;;
          esac
        done

see more details here for example http://wiki.bash-hackers.org/howto/getopts_tutorial

How to stop and restart memcached server?

To shutdown memcache daemon:

sudo service memcached stop

To start memcached daemon:

sudo service memcached start

Restart memcached server:

sudo service memcached restart

You can see if Memcache is currently runing:

sudo ps -e | grep memcached

And you can check the TCP or UDP ports if something (e.g. Memcache) is listening to it:

netstat -ap | grep TheChosenPort#
netstat -ap | grep 11211

For some Linuxes you need to change your commands like:

sudo /etc/init.d/memcached start
sudo /etc/init.d/memcached restart
sudo /etc/init.d/memcached stop

Is Python faster and lighter than C++?

Source size is not really a sensible thing to measure. For example, the following shell script:

cat foobar

is much shorter than either its Python or C++ equivalents.

iOS 7 UIBarButton back button arrow color

UINavigationBar *nbar = self.navigationController.navigationBar;

if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
   //iOS 7
   nbar.barTintColor = [UIColor blueColor]; // bar color
   //or custom color 
   //[UIColor colorWithRed:19.0/255.0 green:86.0/255.0 blue:138.0/255.0 alpha:1];

   nbar.navigationBar.translucent = NO;

   nbar.tintColor = [UIColor blueColor]; //bar button item color

} else {
   //ios 4,5,6
   nbar.tintColor = [UIColor whiteColor];
   //or custom color
   //[UIColor colorWithRed:19.0/255.0 green:86.0/255.0 blue:138.0/255.0 alpha:1];

}

How to Configure SSL for Amazon S3 bucket

It is not possible directly with S3, but you can create a Cloud Front distribution from you bucket. Then go to certificate manager and request a certificate. Amazon gives them for free. Ones you have successfully confirmed the certification, assign it to your Cloud Front distribution. Also remember to set the rule to re-direct http to https.

I'm hosting couple of static websites on Amazon S3, like my personal website to which I have assigned the SSL certificate as they have the Cloud Front distribution.

Invoke a second script with arguments from a script

You can execute it same as SQL query. first, build your command/Expression and store in a variable and execute/invoke.

$command =  ".\yourExternalScriptFile.ps1" + " -param1 '$paramValue'"

It is pretty forward, I don't think it needs explanations. So all set to execute your command now,

Invoke-Expression $command

I would recommend catching the exception here

Sql Server 'Saving changes is not permitted' error ? Prevent saving changes that require table re-creation

It is very easy and simple setting problem that can be fixed in 5 seconds by following these steps

To allow you to save changes after you alter table, Please follow these steps for your sql setting:

  1. Open Microsoft SQL Server Management Studio 2008
  2. Click Tools menu options, then click Options
  3. Select Designers
  4. Uncheck "prevent saving changes that require table re-creation" option
  5. Click OK
  6. Try to alter your table
  7. Your changes will performed as desired

Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:

You need to provide a candidate for autowire. That means that an instance of PasswordHint must be known to spring in a way that it can guess that it must reference it.

Please provide the class head of PasswordHint and/or the spring bean definition of that class for further assistance.

Try changing the name of

PasswordHintAction action;

to

PasswordHintAction passwordHintAction;

so that it matches the bean definition.

How to upgrade Python version to 3.7?

On ubuntu you can add this PPA Repository and use it to install python 3.7: https://launchpad.net/~jonathonf/+archive/ubuntu/python-3.7

Or a different PPA that provides several Python versions is Deadsnakes: https://launchpad.net/~deadsnakes/+archive/ubuntu/ppa

See also here: https://askubuntu.com/questions/865554/how-do-i-install-python-3-6-using-apt-get (I know it says 3.6 in the url, but the deadsnakes ppa also contains 3.7 so you can use it for 3.7 just the same)

If you want "official" you'd have to install it from the sources from the site, get the code (which you already downloaded) and do this:

tar -xf Python-3.7.0.tar.xz
cd Python-3.7.0
./configure
make
sudo make install        <-- sudo is required.

This might take a while

Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop

I suspect that the problem lies in the fact that you are calling your state setter immediately inside the function component body, which forces React to re-invoke your function again, with the same props, which ends up calling the state setter again, which triggers React to call your function again.... and so on.

const SingInContainer = ({ message, variant}) => {
    const [open, setSnackBarState] = useState(false);
    const handleClose = (reason) => {
        if (reason === 'clickaway') {
          return;
        }
        setSnackBarState(false)

      };

    if (variant) {
        setSnackBarState(true); // HERE BE DRAGONS
    }
    return (
        <div>
        <SnackBar
            open={open}
            handleClose={handleClose}
            variant={variant}
            message={message}
            />
        <SignInForm/>
        </div>
    )
}

Instead, I recommend you just conditionally set the default value for the state property using a ternary, so you end up with:

const SingInContainer = ({ message, variant}) => {
    const [open, setSnackBarState] = useState(variant ? true : false); 
                                  // or useState(!!variant); 
                                  // or useState(Boolean(variant));
    const handleClose = (reason) => {
        if (reason === 'clickaway') {
          return;
        }
        setSnackBarState(false)

      };

    return (
        <div>
        <SnackBar
            open={open}
            handleClose={handleClose}
            variant={variant}
            message={message}
            />
        <SignInForm/>
        </div>
    )
}

Comprehensive Demo

See this CodeSandbox.io demo for a comprehensive demo of it working, plus the broken component you had, and you can toggle between the two.

Volatile boolean vs AtomicBoolean

Both are of same concept but in atomic boolean it will provide atomicity to the operation in case the cpu switch happens in between.

How to stop tracking and ignore changes to a file in Git?

The problem may be caused by the order of operation. If you modified the .gitignore first, then git rm --cached xxx,you may have to continue to encounter this problem.

Correct solution:

  1. git rm --cached xxx
  2. modified the .gitignore

Order invariant!

The .gitignore reload after modification!

svn list of files that are modified in local copy

If you only want the filenames and also want any files that have been added (A).

svn st | grep ^[AM] | cut -c9-

Note: The first 7 columns are each one character wide followed by a space then the filename.

Java: How to convert String[] to List or Set

If you really want to use a set:

String[] strArray = {"foo", "foo", "bar"};  
Set<String> mySet = new HashSet<String>(Arrays.asList(strArray));
System.out.println(mySet);

output:

[foo, bar]

How to make the checkbox unchecked by default always

No, there is no way in simple HTML. Javascript might be your only solution at this time..

Loop through all checkboxes in javascript and set them to unchecked:

var checkboxes = document.getElementsByTagName('input');

for (var i=0; i<checkboxes.length; i++)  {
  if (checkboxes[i].type == 'checkbox')   {
    checkboxes[i].checked = false;
  }
}

wrap it up in a onload listener and you should be fine then :)

How do you change the server header returned by nginx?

There is a special module: http://wiki.nginx.org/NginxHttpHeadersMoreModule

This module allows you to add, set, or clear any output or input header that you specify.

This is an enhanced version of the standard headers module because it provides more utilities like resetting or clearing "builtin headers" like Content-Type, Content-Length, and Server.

It also allows you to specify an optional HTTP status code criteria using the -s option and an optional content type criteria using the -t option while modifying the output headers with the more_set_headers and more_clear_headers directives...

With Spring can I make an optional path variable?

Check this Spring 3 WebMVC - Optional Path Variables. It shows an article of making an extension to AntPathMatcher to enable optional path variables and might be of help. All credits to Sebastian Herold for posting the article.

How to find longest string in the table column data

The easiest way is:

select top 1 CR
from table t
order by len(CR) desc

Note that this will only return one value if there are multiple with the same longest length.

Set a button group's width to 100% and make buttons equal width?

There's no need for extra css the .btn-group-justified class does this.

You have to add this to the parent element and then wrap each btn element in a div with .btn-group like this

    <div class="form-group">

            <div class="btn-group btn-group-justified">
                <div class="btn-group">
                    <button type="submit" id="like" class="btn btn-lg btn-success ">Like</button>
                </div>
                <div class="btn-group">
                    <button type="submit" id="nope" class="btn btn-lg btn-danger ">Nope</button>
                </div>
            </div>

        </div>

insert data from one table to another in mysql

INSERT INTO destination_table ( 
      Field_1, 
      Field_2, 
      Field_3) 
SELECT Field_1, 
      Field_2, 
      Field_3 
      FROM source_table;

BUT this is a BAD MYSQL

Do this instead:

  1. drop the destination table: DROP DESTINATION_TABLE;
  2. CREATE TABLE DESTINATION_TABLE AS (SELECT * FROM SOURCE_TABLE);

Oracle comparing timestamp with date

You can truncate the date part:

select * from table1 where trunc(field1) = to_date('2012-01-01', 'YYYY-MM-DD')

The trouble with this approach is that any index on field1 wouldn't be used due to the function call.

Alternatively (and more index friendly)

select * from table1 
 where field1 >= to_timestamp('2012-01-01', 'YYYY-MM-DD') 
   and field1 < to_timestamp('2012-01-02', 'YYYY-MM-DD')

Reading JSON POST using PHP

You have empty $_POST. If your web-server wants see data in json-format you need to read the raw input and then parse it with JSON decode.

You need something like that:

$json = file_get_contents('php://input');
$obj = json_decode($json);

Also you have wrong code for testing JSON-communication...

CURLOPT_POSTFIELDS tells curl to encode your parameters as application/x-www-form-urlencoded. You need JSON-string here.

UPDATE

Your php code for test page should be like that:

$data_string = json_encode($data);

$ch = curl_init('http://webservice.local/');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($data_string))
);

$result = curl_exec($ch);
$result = json_decode($result);
var_dump($result);

Also on your web-service page you should remove one of the lines header('Content-type: application/json');. It must be called only once.

What is Persistence Context?

While @pritam kumar gives a good overview the 5th point is not true.

Persistence Context can be either Transaction Scoped-- the Persistence Context 'lives' for the length of the transaction, or Extended-- the Persistence Context spans multiple transactions.

https://blogs.oracle.com/carolmcdonald/entry/jpa_caching

JPA's EntityManager and Hibernate's Session offer an extended Persistence Context.

Django request.GET

since your form has a field called 'q', leaving it blank still sends an empty string.

try

if 'q' in request.GET and request.GET['q'] != "" :
     message
else
     error message

iOS detect if user is on an iPad

This is part of UIDevice as of iOS 3.2, e.g.:

[UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad

How to install MySQLi on MacOS

On php 5.3.0 and later version you dont need to specially install mysqli on windows. Rather follow simple steps as shown below.

Locate php.ini file [ if not there it means you have not copied php.ini-development or php.ini-production file as php.ini to make your configurations ]

There are 2 things to be done 1. Uncomment and set right path to extension_dir = "ext" Basically set the path where you find ext folder in php even if its in same folder from where you are running php-cgi.ex

  1. uncomment mysqli library extention extension=mysqli

Note: uncommenting in this php.ini file is by removing starting ; from the line.

rename the columns name after cbind the data

If you pass only vectors to cbind() it creates a matrix, not a dataframe. Read ?data.frame.

How do I use CREATE OR REPLACE?

One of the nice things about the syntax is that you can be sure that a CREATE OR REPLACE will never cause you to lose data (the most you will lose is code, which hopefully you'll have stored in source control somewhere).

The equivalent syntax for tables is ALTER, which means you have to explicitly enumerate the exact changes that are required.

EDIT: By the way, if you need to do a DROP + CREATE in a script, and you don't care for the spurious "object does not exist" errors (when the DROP doesn't find the table), you can do this:

BEGIN
  EXECUTE IMMEDIATE 'DROP TABLE owner.mytable';
EXCEPTION
  WHEN OTHERS THEN
    IF sqlcode != -0942 THEN RAISE; END IF;
END;
/

Docker remove <none> TAG images

The dangling images are ghosts from the previous builds and pulls, simply delete them with : docker rmi $(docker images -f "dangling=true" -q)

How to cast DATETIME as a DATE in mysql?

Use DATE() function:

select * from follow_queue group by DATE(follow_date)

Why call super() in a constructor?

We can Access SuperClass members using super keyword

If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged). Consider this class, Superclass:

public class Superclass {

    public void printMethod() {
        System.out.println("Printed in Superclass.");
    }
}

// Here is a subclass, called Subclass, that overrides printMethod():

public class Subclass extends Superclass {

    // overrides printMethod in Superclass
    public void printMethod() {
        super.printMethod();
        System.out.println("Printed in Subclass");
    }
    public static void main(String[] args) {
        Subclass s = new Subclass();
        s.printMethod();    
    }
}

Within Subclass, the simple name printMethod() refers to the one declared in Subclass, which overrides the one in Superclass. So, to refer to printMethod() inherited from Superclass, Subclass must use a qualified name, using super as shown. Compiling and executing Subclass prints the following:

Printed in Superclass.
Printed in Subclass

What is the equivalent of ngShow and ngHide in Angular 2+?

If you are using Bootstrap is as simple as this:

<div [class.hidden]="myBooleanValue"></div>

How to increase apache timeout directive in .htaccess?

Just in case this helps anyone else:

If you're going to be adding the TimeOut directive, and your website uses multiple vhosts (eg. one for port 80, one for port 443), then don't forget to add the directive to all of them!

Using OR & AND in COUNTIFS

i found i had to do something akin to

=(countifs (A1:A196,"yes", j1:j196, "agree") + (countifs (A1:A196,"no", j1:j196, "agree"))

Adding Image to xCode by dragging it from File

Add the image to Your project by clicking File -> "Add Files to ...".

Then choose the image in ImageView properties (Utilities -> Attributes Inspector).

Is a Python dictionary an example of a hash table?

Yes. Internally it is implemented as open hashing based on a primitive polynomial over Z/2 (source).

Return True, False and None in Python

It's impossible to say without seeing your actual code. Likely the reason is a code path through your function that doesn't execute a return statement. When the code goes down that path, the function ends with no value returned, and so returns None.

Updated: It sounds like your code looks like this:

def b(self, p, data): 
    current = p 
    if current.data == data: 
        return True 
    elif current.data == 1:
        return False 
    else: 
        self.b(current.next, data)

That else clause is your None path. You need to return the value that the recursive call returns:

    else:
        return self.b(current.next, data)

BTW: using recursion for iterative programs like this is not a good idea in Python. Use iteration instead. Also, you have no clear termination condition.

How do I clone into a non-empty directory?

Maybe I misunderstood your question, but wouldn't it be simpler if you copy/move the files from A to the git repo B and add the needed ones with git add?

UPDATE: From the git doc:

Cloning into an existing directory is only allowed if the directory is empty.

SOURCE: http://git-scm.com/docs/git-clone

How to order results with findBy() in Doctrine

$cRepo = $em->getRepository('KaleLocationBundle:Country');

// Leave the first array blank
$countries = $cRepo->findBy(array(), array('name'=>'asc'));

Overriding fields or properties in subclasses

option 2 is a bad idea. It will result in something called shadowing; Basically you have two different "MyInt" members, one in the mother, and the other in the daughter. The problem with this, is that methods that are implemented in the mother will reference the mother's "MyInt" while methods implemented in the daughter will reference the daughter's "MyInt". this can cause some serious readability issues, and confusion later down the line.

Personally, I think the best option is 3; because it provides a clear centralized value, and can be referenced internally by children without the hassle of defining their own fields -- which is the problem with option 1.

Summing elements in a list

You can use map function and pythons inbuilt sum() function. It simplifies the solution. And reduces the complexity.
a=map(int,raw_input().split())
sum(a)
Done!

REST API - Use the "Accept: application/json" HTTP Header

Here's a handy site to test out your headers. You can see your browser headers and also use cURL to reflect back whatever headers you send.

For example, you can validate the content negotiation like this.

This Accept header prefers plain text so returns in that format:-

$ curl -H "Accept: application/json;q=0.9,text/plain" http://gethttp.info/Accept
application/json;q=0.9,text/plain

Whereas this one prefers JSON and so returns in that format:-

$ curl -H "Accept: application/json,text/*;q=0.99" http://gethttp.info/Accept
{
   "Accept": "application/json,text/*;q=0.99"
}

CSS: How to align vertically a "label" and "input" inside a "div"?

This works cross-browser, provides more accessibility and comes with less markup. ditch the div. Wrap the label

label{
     display: block; 
     height: 35px; 
     line-height: 35px; 
     border: 1px solid #000; 
}

input{margin-top:15px; height:20px}

<label for="name">Name: <input type="text" id="name" /></label>

Get month name from number

import datetime
mydate = datetime.datetime.now()
mydate.strftime("%B")

Returns: December

Some more info on the Python doc website


[EDIT : great comment from @GiriB] You can also use %b which returns the short notation for month name.

mydate.strftime("%b")

For the example above, it would return Dec.

How does the JPA @SequenceGenerator annotation work

Now, back to your questions:

Q1. Does this sequence generator make use of the database's increasing numeric value generating capability or generates the number on its own?

By using the GenerationType.SEQUENCE strategy on the @GeneratedValue annotation, the JPA provider will try to use a database sequence object of the underlying database that supports this feature (e.g., Oracle, SQL Server, PostgreSQL, MariaDB).

If you are using MySQL, which doesn't support database sequence objects, then Hibernate is going to fall back to using the GenerationType.TABLE instead, which is undesirable since the TABLE generation performs badly.

So, don't use the GenerationType.SEQUENCE strategy with MySQL.

Q2. If JPA uses a database auto-increment feature, then will it work with datastores that don't have auto-increment feature?

I assume you are talking about the GenerationType.IDENTITY when you say database auto-increment feature.

To use an AUTO_INCREMENT or IDENTITY column, you need to use the GenerationType.IDENTITYstrategy on the @GeneratedValue annotation.

Q3. If JPA generates numeric value on its own, then how does the JPA implementation know which value to generate next? Does it consult with the database first to see what value was stored last in order to generate the value (last + 1)?

The only time when the JPA provider generates values on its own is when you are using the sequence-based optimizers, like:

These optimizers are meat to reduce the number of database sequence calls, so they multiply the number of identifier values that can be generated using a single database sequence call.

To avoid conflicts between Hibernate identifier optimizers and other 3rd-party clients, you should use pooled or pooled-lo instead of hi/lo. Even if you are using a legacy application that was designed to use hi/lo, you can migrate to the pooled or pooled-lo optimizers.

Q4. Please also shed some light on sequenceName and allocationSize properties of @SequenceGenerator annotation.

The sequenceName attribute defines the database sequence object to be used to generate the identifier values. IT's the object you created using the CREATE SEQUENCE DDL statement.

So, if you provide this mapping:

@Id
@GeneratedValue(
    strategy = GenerationType.SEQUENCE,
    generator = "seq_post"
)
@SequenceGenerator(
    name = "seq_post"
)
private Long id;

Hibernate is going to use the seq_post database object to generate the identifier values:

SELECT nextval('hibernate_sequence')

The allocationSize defines the identifier value multiplier, and if you provide a value that's greater than 1, then Hibernate is going to use the pooled optimizer, to reduce the number of database sequence calls.

So, if you provide this mapping:

@Id
@GeneratedValue(
    strategy = GenerationType.SEQUENCE,
    generator = "seq_post"
)
@SequenceGenerator(
    name = "seq_post",
    allocationSize = 5
)
private Long id;

Then, when you persist 5 entities:

for (int i = 1; i <= 5; i++) {
    entityManager.persist(
        new Post().setTitle(
            String.format(
                "High-Performance Java Persistence, Part %d",
                i
            )
        )
    );
}

Only 2 database sequence calls will be executed, instead of 5:

SELECT nextval('hibernate_sequence')
SELECT nextval('hibernate_sequence')
 
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 1', 1)
 
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 2', 2)
 
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 3', 3)
 
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 4', 4)
 
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 5', 5)

XSLT string replace

Here is the XSLT function which will work similar to the String.Replace() function of C#.

This template has the 3 Parameters as below

text :- your main string

replace :- the string which you want to replace

by :- the string which will reply by new string

Below are the Template

<xsl:template name="string-replace-all">
  <xsl:param name="text" />
  <xsl:param name="replace" />
  <xsl:param name="by" />
  <xsl:choose>
    <xsl:when test="contains($text, $replace)">
      <xsl:value-of select="substring-before($text,$replace)" />
      <xsl:value-of select="$by" />
      <xsl:call-template name="string-replace-all">
        <xsl:with-param name="text" select="substring-after($text,$replace)" />
        <xsl:with-param name="replace" select="$replace" />
        <xsl:with-param name="by" select="$by" />
      </xsl:call-template>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="$text" />
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

Below sample shows how to call it

<xsl:variable name="myVariable ">
  <xsl:call-template name="string-replace-all">
    <xsl:with-param name="text" select="'This is a {old} text'" />
    <xsl:with-param name="replace" select="'{old}'" />
    <xsl:with-param name="by" select="'New'" />
  </xsl:call-template>
</xsl:variable>

You can also refer the below URL for the details.

How to install Visual Studio 2015 on a different drive

Uninstall the plugins first. And then try this. This uninstaller worked like a charm (I didn't even uninstall 2015 myself, it did everything on its own)!

Invalid syntax when using "print"?

The syntax is changed in new 3.x releases rather than old 2.x releases: for example in python 2.x you can write: print "Hi new world" but in the new 3.x release you need to use the new syntax and write it like this: print("Hi new world")

check the documentation: http://docs.python.org/3.3/library/functions.html?highlight=print#print

Mocha / Chai expect.to.throw not catching thrown errors

One other possible implementation, more cumbersome than the .bind() solution, but one that helps to make the point that expect() requires a function that provides a this context to the covered function, you can use a call(), e.g.,

expect(function() {model.get.call(model, 'z');}).to.throw('...');

How to compare two Carbon Timestamps?

First, convert the timestamp using the built-in eloquent functionality, as described in this answer.

Then you can just use Carbon's min() or max() function for comparison. For example:

$dt1 = Carbon::create(2012, 1, 1, 0, 0, 0); $dt2 = Carbon::create(2014, 1, 30, 0, 0, 0); echo $dt1->min($dt2);

This will echo the lesser of the two dates, which in this case is $dt1.

See http://carbon.nesbot.com/docs/

How To: Execute command line in C#, get STD OUT results

You can launch any command line program using the Process class, and set the StandardOutput property of the Process instance with a stream reader you create (either based on a string or a memory location). After the process completes, you can then do whatever diff you need to on that stream.

Adding parameter to ng-click function inside ng-repeat doesn't seem to work

Also worth noting, for people who find this in their searches, is this...

<div ng-repeat="button in buttons" class="bb-button" ng-click="goTo(button.path)">
  <div class="bb-button-label">{{ button.label }}</div>
  <div class="bb-button-description">{{ button.description }}</div>
</div>

Note the value of ng-click. The parameter passed to goTo() is a string from a property of the binding object (the button), but it is not wrapped in quotes. Looks like AngularJS handles that for us. I got hung up on that for a few minutes.

Linux command (like cat) to read a specified quantity of characters

head works too:

head -c 100 file  # returns the first 100 bytes in the file

..will extract the first 100 bytes and return them.

What's nice about using head for this is that the syntax for tail matches:

tail -c 100 file  # returns the last 100 bytes in the file

You can combine these to get ranges of bytes. For example, to get the second 100 bytes from a file, read the first 200 with head and use tail to get the last 100:

head -c 200 file | tail -c 100

Angular - "has no exported member 'Observable'"

Update angular-in-memory-web-api version. The default angular-in-memory-web-api version installed during the tutorial angular-tour-of-heroes was 0.4. It worked like a charm in my case. (Using Angular 7 with RxJS 6)

npm i [email protected]

How to set a DateTime variable in SQL Server 2008?

Check This:

DECLARE
    @_month TINYINT         = 5,
    @_year SMALLINT         = 2020,
    @date_ref DATETIME      = NULL 


    IF @_year IS NULL
        SET @date_ref = GETDATE() - 430
    ELSE
    BEGIN
        SELECT @date_ref = CAST ( CAST ( @_year AS VARCHAR (4)) 
            + 
            CASE 
                WHEN @_month < 10 THEN '0' + CAST ( @_month AS VARCHAR(1)) 
                ELSE CAST ( @_month AS VARCHAR(2)) 
            END 
            + 
            '01' AS DATETIME )
    END

jQuery val is undefined?

This is stupid but for future reference. I did put all my code in:

$(document).ready(function () {
    //your jQuery function
});

But still it wasn't working and it was returning undefined value. I check my HTML DOM

<input id="username" placeholder="Username"></input>

and I realised that I was referencing it wrong in jQuery:

var user_name = $('#user_name').val();

Making it:

var user_name = $('#username').val();

solved my problem.

So it's always better to check your previous code.

Express.js - app.listen vs server.listen

I came with same question but after google, I found there is no big difference :)

From Github

If you wish to create both an HTTP and HTTPS server you may do so with the "http" and "https" modules as shown here.

/**
 * Listen for connections.
 *
 * A node `http.Server` is returned, with this
 * application (which is a `Function`) as its
 * callback. If you wish to create both an HTTP
 * and HTTPS server you may do so with the "http"
 * and "https" modules as shown here:
 *
 *    var http = require('http')
 *      , https = require('https')
 *      , express = require('express')
 *      , app = express();
 *
 *    http.createServer(app).listen(80);
 *    https.createServer({ ... }, app).listen(443);
 *
 * @return {http.Server}
 * @api public
 */

app.listen = function(){
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};

Also if you want to work with socket.io see their example

See this

I prefer app.listen() :)

SQL Server Text type vs. varchar data type

TEXT is used for large pieces of string data. If the length of the field exceeed a certain threshold, the text is stored out of row.

VARCHAR is always stored in row and has a limit of 8000 characters. If you try to create a VARCHAR(x), where x > 8000, you get an error:

Server: Msg 131, Level 15, State 3, Line 1

The size () given to the type ‘varchar’ exceeds the maximum allowed for any data type (8000)

These length limitations do not concern VARCHAR(MAX) in SQL Server 2005, which may be stored out of row, just like TEXT.

Note that MAX is not a kind of constant here, VARCHAR and VARCHAR(MAX) are very different types, the latter being very close to TEXT.

In prior versions of SQL Server you could not access the TEXT directly, you only could get a TEXTPTR and use it in READTEXT and WRITETEXT functions.

In SQL Server 2005 you can directly access TEXT columns (though you still need an explicit cast to VARCHAR to assign a value for them).

TEXT is good:

  • If you need to store large texts in your database
  • If you do not search on the value of the column
  • If you select this column rarely and do not join on it.

VARCHAR is good:

  • If you store little strings
  • If you search on the string value
  • If you always select it or use it in joins.

By selecting here I mean issuing any queries that return the value of the column.

By searching here I mean issuing any queries whose result depends on the value of the TEXT or VARCHAR column. This includes using it in any JOIN or WHERE condition.

As the TEXT is stored out of row, the queries not involving the TEXT column are usually faster.

Some examples of what TEXT is good for:

  • Blog comments
  • Wiki pages
  • Code source

Some examples of what VARCHAR is good for:

  • Usernames
  • Page titles
  • Filenames

As a rule of thumb, if you ever need you text value to exceed 200 characters AND do not use join on this column, use TEXT.

Otherwise use VARCHAR.

P.S. The same applies to UNICODE enabled NTEXT and NVARCHAR as well, which you should use for examples above.

P.P.S. The same applies to VARCHAR(MAX) and NVARCHAR(MAX) that SQL Server 2005+ uses instead of TEXT and NTEXT. You'll need to enable large value types out of row for them with sp_tableoption if you want them to be always stored out of row.

As mentioned above and here, TEXT is going to be deprecated in future releases:

The text in row option will be removed in a future version of SQL Server. Avoid using this option in new development work, and plan to modify applications that currently use text in row. We recommend that you store large data by using the varchar(max), nvarchar(max), or varbinary(max) data types. To control in-row and out-of-row behavior of these data types, use the large value types out of row option.

JavaScript: Create and save file

This project on github looks promising:

https://github.com/eligrey/FileSaver.js

FileSaver.js implements the W3C saveAs() FileSaver interface in browsers that do not natively support it.

Also have a look at the demo here:

http://eligrey.com/demos/FileSaver.js/

Foreign key constraints: When to use ON UPDATE and ON DELETE

You'll need to consider this in context of the application. In general, you should design an application, not a database (the database simply being part of the application).

Consider how your application should respond to various cases.

The default action is to restrict (i.e. not permit) the operation, which is normally what you want as it prevents stupid programming errors. However, on DELETE CASCADE can also be useful. It really depends on your application and how you intend to delete particular objects.

Personally, I'd use InnoDB because it doesn't trash your data (c.f. MyISAM, which does), rather than because it has FK constraints.

Test if string is a number in Ruby on Rails

If you prefer not to use exceptions as part of the logic, you might try this:

class String
   def numeric?
    !!(self =~ /^-?\d+(\.\d*)?$/)
  end
end

Or, if you want it to work across all object classes, replace class String with class Object an convert self to a string: !!(self.to_s =~ /^-?\d+(\.\d*)?$/)

Why does HTML think “chucknorris” is a color?

I now this this is not an image made by me, but this image can help a lot... enter image description here

So, here is an little app that I created so you can play with the values

_x000D_
_x000D_
function parseColor(input) {
  input = input.trim();
  if (input.length > 128) {
    input = input.slice(0, 128);
  }
  if (input.charAt(0) === "#") {
    input = input.slice(1);
  }
  input = input.replace(/[^0-9A-Fa-f]/g, "0");
  while (input.length === 0 || input.length % 3 > 0) {
    input += "0";
  }
  var r = input.slice(0, input.length / 3);
  var g = input.slice(input.length / 3, input.length * 2 / 3);
  var b = input.slice(input.length * 2 / 3);
  if (r.length > 8) {
    r = r.slice(-8);
    g = g.slice(-8);
    b = b.slice(-8);
  }
  while (r.length > 2 && r.charAt(0) === "0" && g.charAt(0) === "0" && b.charAt(0) === "0") {
    r = r.slice(1);
    g = g.slice(1);
    b = b.slice(1);
  }
  if (r.length > 2) {
    r = r.slice(0, 2);
    g = g.slice(0, 2);
    b = b.slice(0, 2);
  }
  return "#" + r.padStart(2, "0") + g.padStart(2, "0") + b.padStart(2, "0");
}

$(function() {
  $("#input").on("change", function() {
    var input = $(this).val();
    var color = parseColor(input);
    var $cells = $("#result tbody td");
    $cells.eq(0).attr("bgcolor", input);
    $cells.eq(1).attr("bgcolor", color);

    var color1 = $cells.eq(0).css("background-color");
    var color2 = $cells.eq(1).css("background-color");
    $cells.eq(2).empty().append("background-color: " + input, "<br>", "getComputedStyle: " + color1);
    $cells.eq(3).empty().append("background-color: " + color, "<br>", "getComputedStyle: " + color2);
  });
});
_x000D_
* { font: monospace; }
input { width: 100hv; }
table { table-layout: fixed; width: 100%; }
input {border: 1px solid black;border-radius: 5px;outline:none;padding: 10px; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<p><input id="input" placeholder="Enter color e.g. demofothedayischur000! or ffffssssrrrddswww!"></p><details>
<summary>Color examples (drag-and-drop)</summary>
Try this colors:<br>
Batato<br>
Muatre!<br>
fsdyelow"<br>
000meandthis<br>
!!!!!<br>
entrcolor<br>
yellowofthe!<br>
!!!me!!!you!!!aregre!:;H<br>
!"#$%&/()=<br>
/()=??»»<br>
thsdem<br></details>
<details>
<summary>
Or.... Want a big example?
</summary>
Here it goes:<br>
Batato Muatre! dtexbtfe dodx42 f 1dzxwq lorem ip os dh4huryx nyxze eimqdmuezo fsdyelow" 000meandthis !!!!! entrcolor yellowofthe! !!!me!!!you!!!aregre!:;H !"#$%&/()= /()=??»» thsdem
</details>
<table id="result">
  <thead>
    <tr>
      <th>Left Color</th>
      <th>Right Color</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
  </tbody>
</table>
_x000D_
_x000D_
_x000D_

Easy way to convert a unicode list to a list containing python strings?

[str(x) for x in EmployeeList] would do a conversion, but it would fail if the unicode string characters do not lie in the ascii range.

>>> EmployeeList = [u'1001', u'Karick', u'14-12-2020', u'1$']
>>> [str(x) for x in EmployeeList]
['1001', 'Karick', '14-12-2020', '1$']


>>> EmployeeList = [u'1001', u'????', u'14-12-2020', u'1$']
>>> [str(x) for x in EmployeeList]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)

Git undo local branch delete

Follow these Steps:

1: Enter:

git reflog show 

This will display all the Commit history, you need to select the sha-1 that has the last commit that you want to get back

2: create a branch name with the Sha-1 ID you selected eg: 8c87714

git branch your-branch-name 8c87714

Java Date - Insert into database

Granted, PreparedStatement will make your code better, but to answer your question you need to tell the DBMS the format of your string representation of the Date. In Oracle (you don't name your database vendor) a string date is converted to Date using the TO_DATE() function:

INSERT INTO TABLE_NAME(
  date_column
)values(
  TO_DATE('06/06/2006', 'mm/dd/yyyy')
)

Super-simple example of C# observer/observable with delegates

In this model, you have publishers who will do some logic and publish an "event."
Publishers will then send out their event only to subscribers who have subscribed to receive the specific event.

In C#, any object can publish a set of events to which other applications can subscribe.
When the publishing class raises an event, all the subscribed applications are notified.
The following figure shows this mechanism.

enter image description here

Simplest Example possible on Events and Delegates in C#:

code is self explanatory, Also I've added the comments to clear out the code.

  using System;

public class Publisher //main publisher class which will invoke methods of all subscriber classes
{
    public delegate void TickHandler(Publisher m, EventArgs e); //declaring a delegate
    public TickHandler Tick;     //creating an object of delegate
    public EventArgs e = null;   //set 2nd paramter empty
    public void Start()     //starting point of thread
    {
        while (true)
        {
            System.Threading.Thread.Sleep(300);
            if (Tick != null)   //check if delegate object points to any listener classes method
            {
                Tick(this, e);  //if it points i.e. not null then invoke that method!
            }
        }
    }
}

public class Subscriber1                //1st subscriber class
{
    public void Subscribe(Publisher m)  //get the object of pubisher class
    {
        m.Tick += HeardIt;              //attach listener class method to publisher class delegate object
    }
    private void HeardIt(Publisher m, EventArgs e)   //subscriber class method
    {
        System.Console.WriteLine("Heard It by Listener");
    }

}
public class Subscriber2                   //2nd subscriber class
{
    public void Subscribe2(Publisher m)    //get the object of pubisher class
    {
        m.Tick += HeardIt;               //attach listener class method to publisher class delegate object
    }
    private void HeardIt(Publisher m, EventArgs e)   //subscriber class method
    {
        System.Console.WriteLine("Heard It by Listener2");
    }

}

class Test
{
    static void Main()
    {
        Publisher m = new Publisher();      //create an object of publisher class which will later be passed on subscriber classes
        Subscriber1 l = new Subscriber1();  //create object of 1st subscriber class
        Subscriber2 l2 = new Subscriber2(); //create object of 2nd subscriber class
        l.Subscribe(m);     //we pass object of publisher class to access delegate of publisher class
        l2.Subscribe2(m);   //we pass object of publisher class to access delegate of publisher class

        m.Start();          //starting point of publisher class
    }
}

Output:

Heard It by Listener

Heard It by Listener2

Heard It by Listener

Heard It by Listener2

Heard It by Listener . . . (infinite times)

Color text in terminal applications in UNIX

You probably want ANSI color codes. Most *nix terminals support them.

Angular.js and HTML5 date input value -- how to get Firefox to show a readable date value in a date input?

In my case, I have solved this way:

$scope.MyObject = // get from database or other sources;
$scope.MyObject.Date = new Date($scope.MyObject.Date);

and input type date is ok

How to add an element at the end of an array?

Arrays in Java have a fixed length that cannot be changed. So Java provides classes that allow you to maintain lists of variable length.

Generally, there is the List<T> interface, which represents a list of instances of the class T. The easiest and most widely used implementation is the ArrayList. Here is an example:

List<String> words = new ArrayList<String>();
words.add("Hello");
words.add("World");
words.add("!");

List.add() simply appends an element to the list and you can get the size of a list using List.size().

Marquee text in Android

You can use

android:ellipsize="marquee"

with your textview.

But remember to put focus on the desired textview.

Convert image from PIL to openCV format

The code commented works as well, just choose which do you prefer

import numpy as np
from PIL import Image


def convert_from_cv2_to_image(img: np.ndarray) -> Image:
    # return Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    return Image.fromarray(img)


def convert_from_image_to_cv2(img: Image) -> np.ndarray:
    # return cv2.cvtColor(numpy.array(img), cv2.COLOR_RGB2BGR)
    return np.asarray(img)

Uncaught TypeError: Cannot set property 'value' of null

It seems to be this function

h_url=document.getElementById("u").value;

You can help yourself using some 'console.log' to see what object is Null.

Find location of a removable SD card

You can try to use the support library function called of ContextCompat.getExternalFilesDirs() :

      final File[] appsDir=ContextCompat.getExternalFilesDirs(getActivity(),null);
      final ArrayList<File> extRootPaths=new ArrayList<>();
      for(final File file : appsDir)
        extRootPaths.add(file.getParentFile().getParentFile().getParentFile().getParentFile());

The first one is the primary external storage, and the rest are supposed to be real SD-cards paths.

The reason for the multiple ".getParentFile()" is to go up another folder, since the original path is

.../Android/data/YOUR_APP_PACKAGE_NAME/files/

EDIT: here's a more comprehensive way I've created, to get the sd-cards paths:

  /**
   * returns a list of all available sd cards paths, or null if not found.
   *
   * @param includePrimaryExternalStorage set to true if you wish to also include the path of the primary external storage
   */
  @TargetApi(Build.VERSION_CODES.HONEYCOMB)
  public static List<String> getSdCardPaths(final Context context, final boolean includePrimaryExternalStorage)
    {
    final File[] externalCacheDirs=ContextCompat.getExternalCacheDirs(context);
    if(externalCacheDirs==null||externalCacheDirs.length==0)
      return null;
    if(externalCacheDirs.length==1)
      {
      if(externalCacheDirs[0]==null)
        return null;
      final String storageState=EnvironmentCompat.getStorageState(externalCacheDirs[0]);
      if(!Environment.MEDIA_MOUNTED.equals(storageState))
        return null;
      if(!includePrimaryExternalStorage&&VERSION.SDK_INT>=VERSION_CODES.HONEYCOMB&&Environment.isExternalStorageEmulated())
        return null;
      }
    final List<String> result=new ArrayList<>();
    if(includePrimaryExternalStorage||externalCacheDirs.length==1)
      result.add(getRootOfInnerSdCardFolder(externalCacheDirs[0]));
    for(int i=1;i<externalCacheDirs.length;++i)
      {
      final File file=externalCacheDirs[i];
      if(file==null)
        continue;
      final String storageState=EnvironmentCompat.getStorageState(file);
      if(Environment.MEDIA_MOUNTED.equals(storageState))
        result.add(getRootOfInnerSdCardFolder(externalCacheDirs[i]));
      }
    if(result.isEmpty())
      return null;
    return result;
    }

  /** Given any file/folder inside an sd card, this will return the path of the sd card */
  private static String getRootOfInnerSdCardFolder(File file)
    {
    if(file==null)
      return null;
    final long totalSpace=file.getTotalSpace();
    while(true)
      {
      final File parentFile=file.getParentFile();
      if(parentFile==null||parentFile.getTotalSpace()!=totalSpace||!parentFile.canRead())
        return file.getAbsolutePath();
      file=parentFile;
      }
    }

Why avoid increment ("++") and decrement ("--") operators in JavaScript?

In my view, "Explicit is always better than implicit." Because at some point, you may got confused with this increments statement y+ = x++ + ++y. A good programmer always makes his or her code more readable.

how do I insert a column at a specific column index in pandas?

Here is a very simple answer to this(only one line).

You can do that after you added the 'n' column into your df as follows.

import pandas as pd
df = pd.DataFrame({'l':['a','b','c','d'], 'v':[1,2,1,2]})
df['n'] = 0

df
    l   v   n
0   a   1   0
1   b   2   0
2   c   1   0
3   d   2   0

# here you can add the below code and it should work.
df = df[list('nlv')]
df

    n   l   v
0   0   a   1
1   0   b   2
2   0   c   1
3   0   d   2



However, if you have words in your columns names instead of letters. It should include two brackets around your column names. 

import pandas as pd
df = pd.DataFrame({'Upper':['a','b','c','d'], 'Lower':[1,2,1,2]})
df['Net'] = 0
df['Mid'] = 2
df['Zsore'] = 2

df

    Upper   Lower   Net Mid Zsore
0   a       1       0   2   2
1   b       2       0   2   2
2   c       1       0   2   2
3   d       2       0   2   2

# here you can add below line and it should work 
df = df[list(('Mid','Upper', 'Lower', 'Net','Zsore'))]
df

   Mid  Upper   Lower   Net Zsore
0   2   a       1       0   2
1   2   b       2       0   2
2   2   c       1       0   2
3   2   d       2       0   2

How to activate virtualenv?

You can do

source ./python_env/bin/activate

or just go to the directory

cd /python_env/bin/

and then

source ./activate

Good Luck.

Use RSA private key to generate public key?

openssl genrsa -out mykey.pem 1024

will actually produce a public - private key pair. The pair is stored in the generated mykey.pem file.

openssl rsa -in mykey.pem -pubout > mykey.pub

will extract the public key and print that out. Here is a link to a page that describes this better.

EDIT: Check the examples section here. To just output the public part of a private key:

openssl rsa -in key.pem -pubout -out pubkey.pem

To get a usable public key for SSH purposes, use ssh-keygen:

ssh-keygen -y -f key.pem > key.pub

How to perform a fade animation on Activity transition?

you can also add animation in your activity, in onCreate method like below becasue overridePendingTransition is not working with some mobile, or it depends on device settings...

View view = findViewById(android.R.id.content);
Animation mLoadAnimation = AnimationUtils.loadAnimation(getApplicationContext(), android.R.anim.fade_in);
mLoadAnimation.setDuration(2000);
view.startAnimation(mLoadAnimation);

Embed youtube videos that play in fullscreen automatically

This was pretty well answered over here: How to make a YouTube embedded video a full page width one?

If you add '?rel=0&autoplay=1' to the end of the url in the embed code (like this)

<iframe id="video" src="//www.youtube.com/embed/5iiPC-VGFLU?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>

of the video it should play on load. Here's a demo over at jsfiddle.

Oracle SQL Developer: Unable to find a JVM

The Oracle SQL developer is not supported by the 64bit JDK. To resolve this issue:

  1. Install a 32bit JDK (x86)
  2. Update your SQL developer config file (It should now point to the new 32bit JDK).
  3. Edit the sqldeveloper.conf, which can be found under {ORACLE_HOME}\sqldeveloper\sqldeveloper\bin\sqldeveloper.conf
  4. Make sure SetJavaHome is pointing to your 32bit JDK.

For example:

SetJavaHome C:\Program Files (x86) \Java\jdk1.6.0_13

How to add an extra source directory for maven to compile and include in the build jar?

NOTE: This solution will just move the java source files to the target/classes directory and will not compile the sources.

Update the pom.xml as -

<project>   
 ....
    <build>
      <resources>
        <resource>
          <directory>src/main/config</directory>
        </resource>
      </resources>
     ...
    </build>
...
</project>

How to have multiple colors in a Windows batch file?

Without external tools.This is a self-compiled bat/.net hybrid (should be saved as .BAT) that can be used on any system that have installed .net framework (it's a rare thing to see an windows without .NET framework even for the oldest XP/2003 installations) . It uses jscript.net compiler to create an exe capable to print strings with different background/foreground color only for the current line.

@if (@X)==(@Y) @end /* JScript comment
@echo off
setlocal

for /f "tokens=* delims=" %%v in ('dir /b /s /a:-d  /o:-n "%SystemRoot%\Microsoft.NET\Framework\*jsc.exe"') do (
   set "jsc=%%v"
)

if not exist "%~n0.exe" (
    "%jsc%" /nologo /out:"%~n0.exe" "%~dpsfnx0"
)

%~n0.exe %*

endlocal & exit /b %errorlevel%

*/

import System;

var arguments:String[] = Environment.GetCommandLineArgs();

var newLine = false;
var output = "";
var foregroundColor = Console.ForegroundColor;
var backgroundColor = Console.BackgroundColor;
var evaluate = false;
var currentBackground=Console.BackgroundColor;
var currentForeground=Console.ForegroundColor;


//http://stackoverflow.com/a/24294348/388389
var jsEscapes = {
  'n': '\n',
  'r': '\r',
  't': '\t',
  'f': '\f',
  'v': '\v',
  'b': '\b'
};

function decodeJsEscape(_, hex0, hex1, octal, other) {
  var hex = hex0 || hex1;
  if (hex) { return String.fromCharCode(parseInt(hex, 16)); }
  if (octal) { return String.fromCharCode(parseInt(octal, 8)); }
  return jsEscapes[other] || other;
}

function decodeJsString(s) {
  return s.replace(
      // Matches an escape sequence with UTF-16 in group 1, single byte hex in group 2,
      // octal in group 3, and arbitrary other single-character escapes in group 4.
      /\\(?:u([0-9A-Fa-f]{4})|x([0-9A-Fa-f]{2})|([0-3][0-7]{0,2}|[4-7][0-7]?)|(.))/g,
      decodeJsEscape);
}


function printHelp( ) {
   print( arguments[0] + "  -s string [-f foreground] [-b background] [-n] [-e]" );
   print( " " );
   print( " string          String to be printed" );
   print( " foreground      Foreground color - a " );
   print( "                 number between 0 and 15." );
   print( " background      Background color - a " );
   print( "                 number between 0 and 15." );
   print( " -n              Indicates if a new line should" );
   print( "                 be written at the end of the ");
   print( "                 string(by default - no)." );
   print( " -e              Evaluates special character " );
   print( "                 sequences like \\n\\b\\r and etc ");
   print( "" );
   print( "Colors :" );
   for ( var c = 0 ; c < 16 ; c++ ) {

        Console.BackgroundColor = c;
        Console.Write( " " );
        Console.BackgroundColor=currentBackground;
        Console.Write( "-"+c );
        Console.WriteLine( "" );
   }
   Console.BackgroundColor=currentBackground;



}

function errorChecker( e:Error ) {
        if ( e.message == "Input string was not in a correct format." ) {
            print( "the color parameters should be numbers between 0 and 15" );
            Environment.Exit( 1 );
        } else if (e.message == "Index was outside the bounds of the array.") {
            print( "invalid arguments" );
            Environment.Exit( 2 );
        } else {
            print ( "Error Message: " + e.message );
            print ( "Error Code: " + ( e.number & 0xFFFF ) );
            print ( "Error Name: " + e.name );
            Environment.Exit( 666 );
        }
}

function numberChecker( i:Int32 ){
    if( i > 15 || i < 0 ) {
        print("the color parameters should be numbers between 0 and 15");
        Environment.Exit(1);
    }
}


if ( arguments.length == 1 || arguments[1].toLowerCase() == "-help" || arguments[1].toLowerCase() == "-help"   ) {
    printHelp();
    Environment.Exit(0);
}

for (var arg = 1; arg <= arguments.length-1; arg++ ) {
    if ( arguments[arg].toLowerCase() == "-n" ) {
        newLine=true;
    }

    if ( arguments[arg].toLowerCase() == "-e" ) {
        evaluate=true;
    }

    if ( arguments[arg].toLowerCase() == "-s" ) {
        output=arguments[arg+1];
    }


    if ( arguments[arg].toLowerCase() == "-b" ) {

        try {
            backgroundColor=Int32.Parse( arguments[arg+1] );
        } catch(e) {
            errorChecker(e);
        }
    }

    if ( arguments[arg].toLowerCase() == "-f" ) {
        try {
            foregroundColor=Int32.Parse(arguments[arg+1]);
        } catch(e) {
            errorChecker(e);
        }
    }
}

Console.BackgroundColor = backgroundColor ;
Console.ForegroundColor = foregroundColor ;

if ( evaluate ) {
    output=decodeJsString(output);
}

if ( newLine ) {
    Console.WriteLine(output);  
} else {
    Console.Write(output);

}

Console.BackgroundColor = currentBackground;
Console.ForegroundColor = currentForeground;

Example coloroutput.bat -s "aa\nbb\n\u0025cc" -b 10 -f 3 -n -e

You can also check carlos' color function -> http://www.dostips.com/forum/viewtopic.php?f=3&t=4453

How to get first/top row of the table in Sqlite via Sql Query

Use the following query:

SELECT * FROM SAMPLE_TABLE ORDER BY ROWID ASC LIMIT 1

Note: Sqlite's row id references are detailed here.

How can I select an element with multiple classes in jQuery?

You can do this using the filter() function:

$(".a").filter(".b")

Async/Await Class Constructor

The stopgap solution

You can create an async init() {... return this;} method, then instead do new MyClass().init() whenever you'd normally just say new MyClass().

This is not clean because it relies on everyone who uses your code, and yourself, to always instantiate the object like so. However if you're only using this object in a particular place or two in your code, it could maybe be fine.

A significant problem though occurs because ES has no type system, so if you forget to call it, you've just returned undefined because the constructor returns nothing. Oops. Much better would be to do something like:

The best thing to do would be:

class AsyncOnlyObject {
    constructor() {
    }
    async init() {
        this.someField = await this.calculateStuff();
    }

    async calculateStuff() {
        return 5;
    }
}

async function newAsync_AsyncOnlyObject() {
    return await new AsyncOnlyObject().init();
}

newAsync_AsyncOnlyObject().then(console.log);
// output: AsyncOnlyObject {someField: 5}

The factory method solution (slightly better)

However then you might accidentally do new AsyncOnlyObject, you should probably just create factory function that uses Object.create(AsyncOnlyObject.prototype) directly:

async function newAsync_AsyncOnlyObject() {
    return await Object.create(AsyncOnlyObject.prototype).init();
}

newAsync_AsyncOnlyObject().then(console.log);
// output: AsyncOnlyObject {someField: 5}

However say you want to use this pattern on many objects... you could abstract this as a decorator or something you (verbosely, ugh) call after defining like postProcess_makeAsyncInit(AsyncOnlyObject), but here I'm going to use extends because it sort of fits into subclass semantics (subclasses are parent class + extra, in that they should obey the design contract of the parent class, and may do additional things; an async subclass would be strange if the parent wasn't also async, because it could not be initialized the same way):


Abstracted solution (extends/subclass version)

class AsyncObject {
    constructor() {
        throw new Error('classes descended from AsyncObject must be initialized as (await) TheClassName.anew(), rather than new TheClassName()');
    }

    static async anew(...args) {
        var R = Object.create(this.prototype);
        R.init(...args);
        return R;
    }
}

class MyObject extends AsyncObject {
    async init(x, y=5) {
        this.x = x;
        this.y = y;
        // bonus: we need not return 'this'
    }
}

MyObject.anew('x').then(console.log);
// output: MyObject {x: "x", y: 5}

(do not use in production: I have not thought through complicated scenarios such as whether this is the proper way to write a wrapper for keyword arguments.)