Programs & Examples On #Response.write

ASP.Net Download file to client browser

Try changing it to.

 Response.Clear();
 Response.ClearHeaders();
 Response.ClearContent();
 Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
 Response.AddHeader("Content-Length", file.Length.ToString());
 Response.ContentType = "text/plain";
 Response.Flush();
 Response.TransmitFile(file.FullName);
 Response.End();

Typescript: TS7006: Parameter 'xxx' implicitly has an 'any' type

In your tsconfig.json file set the parameter "noImplicitAny": false under compilerOptions to get rid of this error.

Why is printing "B" dramatically slower than printing "#"?

I performed tests on Eclipse vs Netbeans 8.0.2, both with Java version 1.8; I used System.nanoTime() for measurements.

Eclipse:

I got the same time on both cases - around 1.564 seconds.

Netbeans:

  • Using "#": 1.536 seconds
  • Using "B": 44.164 seconds

So, it looks like Netbeans has bad performance on print to console.

After more research I realized that the problem is line-wrapping of the max buffer of Netbeans (it's not restricted to System.out.println command), demonstrated by this code:

for (int i = 0; i < 1000; i++) {
    long t1 = System.nanoTime();
    System.out.print("BBB......BBB"); \\<-contain 1000 "B"
    long t2 = System.nanoTime();
    System.out.println(t2-t1);
    System.out.println("");
}

The time results are less then 1 millisecond every iteration except every fifth iteration, when the time result is around 225 millisecond. Something like (in nanoseconds):

BBB...31744
BBB...31744
BBB...31744
BBB...31744
BBB...226365807
BBB...31744
BBB...31744
BBB...31744
BBB...31744
BBB...226365807
.
.
.

And so on..

Summary:

  1. Eclipse works perfectly with "B"
  2. Netbeans has a line-wrapping problem that can be solved (because the problem does not occur in eclipse)(without adding space after B ("B ")).

Command not found error in Bash variable assignment

Drop the spaces around the = sign:

#!/bin/bash 
STR="Hello World" 
echo $STR 

JavaScript listener, "keypress" doesn't detect backspace?

Try keydown instead of keypress.

The keyboard events occur in this order: keydown, keyup, keypress

The problem with backspace probably is, that the browser will navigate back on keyup and thus your page will not see the keypress event.

How to add noise (Gaussian/salt and pepper etc) to image in Python with OpenCV

just look at cv2.randu() or cv.randn(), it's all pretty similar to matlab already, i guess.

let's play a bit ;) :

import cv2
import numpy as np

>>> im = np.empty((5,5), np.uint8) # needs preallocated input image
>>> im
array([[248, 168,  58,   2,   1],  # uninitialized memory counts as random, too ?  fun ;) 
       [  0, 100,   2,   0, 101],
       [  0,   0, 106,   2,   0],
       [131,   2,   0,  90,   3],
       [  0, 100,   1,   0,  83]], dtype=uint8)
>>> im = np.zeros((5,5), np.uint8) # seriously now.
>>> im
array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]], dtype=uint8)
>>> cv2.randn(im,(0),(99))         # normal
array([[  0,  76,   0, 129,   0],
       [  0,   0,   0, 188,  27],
       [  0, 152,   0,   0,   0],
       [  0,   0, 134,  79,   0],
       [  0, 181,  36, 128,   0]], dtype=uint8)
>>> cv2.randu(im,(0),(99))         # uniform
array([[19, 53,  2, 86, 82],
       [86, 73, 40, 64, 78],
       [34, 20, 62, 80,  7],
       [24, 92, 37, 60, 72],
       [40, 12, 27, 33, 18]], dtype=uint8)

to apply it to an existing image, just generate noise in the desired range, and add it:

img = ...
noise = ...

image = img + noise

Convert array of strings into a string in Java

String array[]={"one","two"};
String s="";

for(int i=0;i<array.length;i++)
{
  s=s+array[i];
}

System.out.print(s);

SQL Server: Difference between PARTITION BY and GROUP BY

They're used in different places. group by modifies the entire query, like:

select customerId, count(*) as orderCount
from Orders
group by customerId

But partition by just works on a window function, like row_number:

select row_number() over (partition by customerId order by orderId)
    as OrderNumberForThisCustomer
from Orders

A group by normally reduces the number of rows returned by rolling them up and calculating averages or sums for each row. partition by does not affect the number of rows returned, but it changes how a window function's result is calculated.

How to get the values of a ConfigurationSection of type NameValueSectionHandler

Try using an AppSettingsSection instead of a NameValueCollection. Something like this:

var section = (AppSettingsSection)config.GetSection(sectionName);
string results = section.Settings[key].Value;

Source: http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/d5079420-40cb-4255-9b3b-f9a41a1f7ad2/

How to select rows where column value IS NOT NULL using CodeIgniter's ActiveRecord?

Much better to use following:

For is not null:

where('archived IS NOT NULL', null);

For is null:

where('archived', null);

MongoDB - admin user not authorized

In addition, notice that if your mongo shell client fails to connect correctly to the mongod instance, you can receive such "Permission Denied" errors.

Make sure that your client opens a connection by checking the connection port, but also that the port you are using in mongod is not in use. You can set a different port by using the --port <port> parameter in both the shell and the process.

how to convert object to string in java

Might not be so related to the issue above. However if you are looking for a way to serialize Java object as string, this could come in hand

package pt.iol.security;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.codec.binary.Base64;

public class ObjectUtil {

    static final Base64 base64 = new Base64();

    public static String serializeObjectToString(Object object) throws IOException {
        try (
                ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
                GZIPOutputStream gzipOutputStream = new GZIPOutputStream(arrayOutputStream);
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(gzipOutputStream);) {
            objectOutputStream.writeObject(object);
            objectOutputStream.flush();
            return new String(base64.encode(arrayOutputStream.toByteArray()));
        }
    }

    public static Object deserializeObjectFromString(String objectString) throws IOException, ClassNotFoundException {
        try (
                ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(base64.decode(objectString));
                GZIPInputStream gzipInputStream = new GZIPInputStream(arrayInputStream);
                ObjectInputStream objectInputStream = new ObjectInputStream(gzipInputStream)) {
            return objectInputStream.readObject();
        }
    }
}

grep regex whitespace behavior

This looks like a behavior difference in the handling of \s between grep 2.5 and newer versions (a bug in old grep?). I confirm your result with grep 2.5.4, but all four of your greps do work when using grep 2.6.3 (Ubuntu 10.10).

Note:

GNU grep 2.5.4
echo "foo bar" | grep "\s"
   (doesn't match)

whereas

GNU grep 2.6.3
echo "foo bar" | grep "\s"
foo bar

Probably less trouble (as \s is not documented):

Both GNU greps
echo "foo bar" | grep "[[:space:]]"
foo bar

My advice is to avoid using \s ... use [ \t]* or [[:space:]] or something like it instead.

Where does git config --global get written to?

I was also looking for the global .gitconfig on my Windows machine and found this neat trick using git.

Do a: git config --global -e and then, if you are lucky, you will get a text editor loaded with your global .gitconfig file. Simply lookup the folder from there (or try a save as...), et voilà! :-)

How to insert data into SQL Server

You have to set Connection property of Command object and use parametersized query instead of hardcoded SQL to avoid SQL Injection.

 using(SqlConnection openCon=new SqlConnection("your_connection_String"))
    {
      string saveStaff = "INSERT into tbl_staff (staffName,userID,idDepartment) VALUES (@staffName,@userID,@idDepartment)";

      using(SqlCommand querySaveStaff = new SqlCommand(saveStaff))
       {
         querySaveStaff.Connection=openCon;
         querySaveStaff.Parameters.Add("@staffName",SqlDbType.VarChar,30).Value=name;
         .....
         openCon.Open();

         querySaveStaff.ExecuteNonQuery();
       }
     }

Difference between a SOAP message and a WSDL?

In a simple terms if you have a web service of calculator. WSDL tells about the functions that you can implement or exposed to the client. For example: add, delete, subtract and so on. Where as using SOAP you actually perform actions like doDelete(), doSubtract(), doAdd(). So SOAP and WSDL are apples and oranges. We should not compare them. They both have their own different functionality.

How to use a decimal range() step value?

Add auto-correction for the possibility of an incorrect sign on step:

def frange(start,step,stop):
    step *= 2*((stop>start)^(step<0))-1
    return [start+i*step for i in range(int((stop-start)/step))]

Negative weights using Dijkstra's Algorithm

You can use dijkstra's algorithm with negative edges not including negative cycle, but you must allow a vertex can be visited multiple times and that version will lose it's fast time complexity.

In that case practically I've seen it's better to use SPFA algorithm which have normal queue and can handle negative edges.

Access-control-allow-origin with multiple domains

After reading every answer and trying them, none of them helped me. What I found while searching elsewhere is that you can create a custom attribute that you can then add to your controller. It overwrites the EnableCors ones and add the whitelisted domains in it.

This solution is working well because it lets you have the whitelisted domains in the webconfig (appsettings) instead of harcoding them in the EnableCors attribute on your controller.

 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class EnableCorsByAppSettingAttribute : Attribute, ICorsPolicyProvider
{
    const string defaultKey = "whiteListDomainCors";
    private readonly string rawOrigins;
    private CorsPolicy corsPolicy;

    /// <summary>
    /// By default uses "cors:AllowedOrigins" AppSetting key
    /// </summary>
    public EnableCorsByAppSettingAttribute()
        : this(defaultKey) // Use default AppSetting key
    {
    }

    /// <summary>
    /// Enables Cross Origin
    /// </summary>
    /// <param name="appSettingKey">AppSetting key that defines valid origins</param>
    public EnableCorsByAppSettingAttribute(string appSettingKey)
    {
        // Collect comma separated origins
        this.rawOrigins = AppSettings.whiteListDomainCors;
        this.BuildCorsPolicy();
    }

    /// <summary>
    /// Build Cors policy
    /// </summary>
    private void BuildCorsPolicy()
    {
        bool allowAnyHeader = String.IsNullOrEmpty(this.Headers) || this.Headers == "*";
        bool allowAnyMethod = String.IsNullOrEmpty(this.Methods) || this.Methods == "*";

        this.corsPolicy = new CorsPolicy
        {
            AllowAnyHeader = allowAnyHeader,
            AllowAnyMethod = allowAnyMethod,
        };

        // Add origins from app setting value
        this.corsPolicy.Origins.AddCommaSeperatedValues(this.rawOrigins);
        this.corsPolicy.Headers.AddCommaSeperatedValues(this.Headers);
        this.corsPolicy.Methods.AddCommaSeperatedValues(this.Methods);
    }

    public string Headers { get; set; }
    public string Methods { get; set; }

    public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request,
                                               CancellationToken cancellationToken)
    {
        return Task.FromResult(this.corsPolicy);
    }
}

    internal static class CollectionExtensions
{
    public static void AddCommaSeperatedValues(this ICollection<string> current, string raw)
    {
        if (current == null)
        {
            return;
        }

        var paths = new List<string>(AppSettings.whiteListDomainCors.Split(new char[] { ',' }));
        foreach (var value in paths)
        {
            current.Add(value);
        }
    }
}

I found this guide online and it worked like a charm :

http://jnye.co/Posts/2032/dynamic-cors-origins-from-appsettings-using-web-api-2-2-cross-origin-support

I thought i'd drop that here for anyone in need.

Chrome disable SSL checking for sites?

Mac Users please execute the below command from terminal to disable the certificate warning.

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --ignore-certificate-errors --ignore-urlfetcher-cert-requests &> /dev/null

Note that this will also have Google Chrome mark all HTTPS sites as insecure in the URL bar.

react-router - pass props to handler component

UPDATE

Since new release, it's possible to pass props directly via the Route component, without using a Wrapper. For example, by using render prop.

Component:

class Greeting extends React.Component {
  render() {
    const {text, match: {params}} = this.props;

    const {name} = params;

    return (
      <React.Fragment>
        <h1>Greeting page</h1>
        <p>
          {text} {name}
        </p>
      </React.Fragment>
    );
  }
}

Usage:

<Route path="/greeting/:name" render={(props) => <Greeting text="Hello, " {...props} />} />

Codesandbox Example


OLD VERSION

My preferred way is wrap the Comments component and pass the wrapper as a route handler.

This is your example with changes applied:

var Dashboard = require('./Dashboard');
var Comments = require('./Comments');

var CommentsWrapper = React.createClass({
  render: function () {
    return (
      <Comments myprop="myvalue"/>
    );
  }
});

var Index = React.createClass({
  render: function () {
    return (
      <div>
        <header>Some header</header>
        <RouteHandler/>
      </div>
    );
  }
});

var routes = (
  <Route path="/" handler={Index}>
    <Route path="comments" handler={CommentsWrapper}/>
    <DefaultRoute handler={Dashboard}/>
  </Route>
);

ReactRouter.run(routes, function (Handler) {
  React.render(<Handler/>, document.body);
});

How can I generate a 6 digit unique number?

<?php echo rand(100000,999999); ?>

you can generate random number

logger configuration to log to file and print to stdout

Just get a handle to the root logger and add the StreamHandler. The StreamHandler writes to stderr. Not sure if you really need stdout over stderr, but this is what I use when I setup the Python logger and I also add the FileHandler as well. Then all my logs go to both places (which is what it sounds like you want).

import logging
logging.getLogger().addHandler(logging.StreamHandler())

If you want to output to stdout instead of stderr, you just need to specify it to the StreamHandler constructor.

import sys
# ...
logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))

You could also add a Formatter to it so all your log lines have a common header.

ie:

import logging
logFormatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s]  %(message)s")
rootLogger = logging.getLogger()

fileHandler = logging.FileHandler("{0}/{1}.log".format(logPath, fileName))
fileHandler.setFormatter(logFormatter)
rootLogger.addHandler(fileHandler)

consoleHandler = logging.StreamHandler()
consoleHandler.setFormatter(logFormatter)
rootLogger.addHandler(consoleHandler)

Prints to the format of:

2012-12-05 16:58:26,618 [MainThread  ] [INFO ]  my message

Can I add and remove elements of enumeration at runtime in Java

A working example in widespread use is in modded Minecraft. See EnumHelper.addEnum() methods on Github

However, note that in rare situations practical experience has shown that adding Enum members can lead to some issues with the JVM optimiser. The exact issues may vary with different JVMs. But broadly it seems the optimiser may assume that some internal fields of an Enum, specifically the size of the Enum's .values() array, will not change. See issue discussion. The recommended solution there is not to make .values() a hotspot for the optimiser. So if adding to an Enum's members at runtime, it should be done once and once only when the application is initialised, and then the result of .values() should be cached to avoid making it a hotspot.

The way the optimiser works and the way it detects hotspots is obscure and may vary between different JVMs and different builds of the JVM. If you don't want to take the risk of this type of issue in production code, then don't change Enums at runtime.

Base64 decode snippet in C++

According to this excellent comparison made by GaspardP I would not choose this solution. It's not the worst, but it's not the best either. The only thing it got going for it is that it's possibly easier to understand.

I found the other two answers to be pretty hard to understand. They also produce some warnings in my compiler and the use of a find function in the decode part should result in a pretty bad efficiency. So I decided to roll my own.

Header:

#ifndef _BASE64_H_
#define _BASE64_H_

#include <vector>
#include <string>
typedef unsigned char BYTE;

class Base64
{
public:
    static std::string encode(const std::vector<BYTE>& buf);
    static std::string encode(const BYTE* buf, unsigned int bufLen);
    static std::vector<BYTE> decode(std::string encoded_string);
};

#endif

Body:

static const BYTE from_base64[] = {    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
                                    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
                                    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,  62, 255,  62, 255,  63,
                                     52,  53,  54,  55,  56,  57,  58,  59,  60,  61, 255, 255, 255, 255, 255, 255,
                                    255,   0,   1,   2,   3,   4,   5,   6,   7,   8,   9,  10,  11,  12,  13,  14,
                                     15,  16,  17,  18,  19,  20,  21,  22,  23,  24,  25, 255, 255, 255, 255,  63,
                                    255,  26,  27,  28,  29,  30,  31,  32,  33,  34,  35,  36,  37,  38,  39,  40,
                                     41,  42,  43,  44,  45,  46,  47,  48,  49,  50,  51, 255, 255, 255, 255, 255};

static const char to_base64[] =
             "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
             "abcdefghijklmnopqrstuvwxyz"
             "0123456789+/";


std::string Base64::encode(const std::vector<BYTE>& buf)
{
    if (buf.empty())
        return ""; // Avoid dereferencing buf if it's empty
    return encode(&buf[0], (unsigned int)buf.size());
}

std::string Base64::encode(const BYTE* buf, unsigned int bufLen)
{
    // Calculate how many bytes that needs to be added to get a multiple of 3
    size_t missing = 0;
    size_t ret_size = bufLen;
    while ((ret_size % 3) != 0)
    {
        ++ret_size;
        ++missing;
    }

    // Expand the return string size to a multiple of 4
    ret_size = 4*ret_size/3;

    std::string ret;
    ret.reserve(ret_size);

    for (unsigned int i=0; i<ret_size/4; ++i)
    {
        // Read a group of three bytes (avoid buffer overrun by replacing with 0)
        size_t index = i*3;
        BYTE b3[3];
        b3[0] = (index+0 < bufLen) ? buf[index+0] : 0;
        b3[1] = (index+1 < bufLen) ? buf[index+1] : 0;
        b3[2] = (index+2 < bufLen) ? buf[index+2] : 0;

        // Transform into four base 64 characters
        BYTE b4[4];
        b4[0] =                            ((b3[0] & 0xfc) >> 2);
        b4[1] = ((b3[0] & 0x03) << 4) +    ((b3[1] & 0xf0) >> 4);
        b4[2] = ((b3[1] & 0x0f) << 2) +    ((b3[2] & 0xc0) >> 6);
        b4[3] = ((b3[2] & 0x3f) << 0);

        // Add the base 64 characters to the return value
        ret.push_back(to_base64[b4[0]]);
        ret.push_back(to_base64[b4[1]]);
        ret.push_back(to_base64[b4[2]]);
        ret.push_back(to_base64[b4[3]]);
    }

    // Replace data that is invalid (always as many as there are missing bytes)
    for (size_t i=0; i<missing; ++i)
        ret[ret_size - i - 1] = '=';

    return ret;
}

std::vector<BYTE> Base64::decode(std::string encoded_string)
{
    // Make sure string length is a multiple of 4
    while ((encoded_string.size() % 4) != 0)
        encoded_string.push_back('=');

    size_t encoded_size = encoded_string.size();
    std::vector<BYTE> ret;
    ret.reserve(3*encoded_size/4);

    for (size_t i=0; i<encoded_size; i += 4)
    {
        // Get values for each group of four base 64 characters
        BYTE b4[4];
        b4[0] = (encoded_string[i+0] <= 'z') ? from_base64[encoded_string[i+0]] : 0xff;
        b4[1] = (encoded_string[i+1] <= 'z') ? from_base64[encoded_string[i+1]] : 0xff;
        b4[2] = (encoded_string[i+2] <= 'z') ? from_base64[encoded_string[i+2]] : 0xff;
        b4[3] = (encoded_string[i+3] <= 'z') ? from_base64[encoded_string[i+3]] : 0xff;

        // Transform into a group of three bytes
        BYTE b3[3];
        b3[0] = ((b4[0] & 0x3f) << 2) + ((b4[1] & 0x30) >> 4);
        b3[1] = ((b4[1] & 0x0f) << 4) + ((b4[2] & 0x3c) >> 2);
        b3[2] = ((b4[2] & 0x03) << 6) + ((b4[3] & 0x3f) >> 0);

        // Add the byte to the return value if it isn't part of an '=' character (indicated by 0xff)
        if (b4[1] != 0xff) ret.push_back(b3[0]);
        if (b4[2] != 0xff) ret.push_back(b3[1]);
        if (b4[3] != 0xff) ret.push_back(b3[2]);
    }

    return ret;
}

Usage:

BYTE buf[] = "ABCD";
std::string encoded = Base64::encode(buf, 4);
// encoded = "QUJDRA=="
std::vector<BYTE> decoded = Base64::decode(encoded);

A bonus here is that the decode function can also decode the URL variant of Base64 encoding.

Argparse optional positional arguments?

As an extension to @VinaySajip answer. There are additional nargs worth mentioning.

  1. parser.add_argument('dir', nargs=1, default=os.getcwd())

N (an integer). N arguments from the command line will be gathered together into a list

  1. parser.add_argument('dir', nargs='*', default=os.getcwd())

'*'. All command-line arguments present are gathered into a list. Note that it generally doesn't make much sense to have more than one positional argument with nargs='*', but multiple optional arguments with nargs='*' is possible.

  1. parser.add_argument('dir', nargs='+', default=os.getcwd())

'+'. Just like '*', all command-line args present are gathered into a list. Additionally, an error message will be generated if there wasn’t at least one command-line argument present.

  1. parser.add_argument('dir', nargs=argparse.REMAINDER, default=os.getcwd())

argparse.REMAINDER. All the remaining command-line arguments are gathered into a list. This is commonly useful for command line utilities that dispatch to other command line utilities

If the nargs keyword argument is not provided, the number of arguments consumed is determined by the action. Generally this means a single command-line argument will be consumed and a single item (not a list) will be produced.

Edit (copied from a comment by @Acumenus) nargs='?' The docs say: '?'. One argument will be consumed from the command line if possible and produced as a single item. If no command-line argument is present, the value from default will be produced.

how to display variable value in alert box?

Clean way with no jQuery:

function check(some_id) {
    var content = document.getElementById(some_id).childNodes[0].nodeValue;
    alert(content);
}

This is assuming each span has only the value as a child and no embedded HTML.

Is there a way to get a textarea to stretch to fit its content without using PHP or JavaScript?

This is a very simple solution, but it works for me:

_x000D_
_x000D_
<!--TEXT-AREA-->_x000D_
<textarea id="textBox1" name="content" TextMode="MultiLine" onkeyup="setHeight('textBox1');" onkeydown="setHeight('textBox1');">Hello World</textarea>_x000D_
_x000D_
<!--JAVASCRIPT-->_x000D_
<script type="text/javascript">_x000D_
function setHeight(fieldId){_x000D_
    document.getElementById(fieldId).style.height = document.getElementById(fieldId).scrollHeight+'px';_x000D_
}_x000D_
setHeight('textBox1');_x000D_
</script>
_x000D_
_x000D_
_x000D_

html5 input for money/currency

More easy and beautiful if you has vue.js v-money-spinner :)

enter image description here

Getting index value on razor foreach

Is there a reason you're not using CSS selectors to style the first and last elements instead of trying to attach a custom class to them? Instead of styling based on alpha or omega, use first-child and last-child.

http://www.quirksmode.org/css/firstchild.html

Unable to login to SQL Server + SQL Server Authentication + Error: 18456

The correct solution to the problem is to make sure SQL server authentication is turned on for your SQL Server.

A monad is just a monoid in the category of endofunctors, what's the problem?

I came to this post by way of better understanding the inference of the infamous quote from Mac Lane's Category Theory For the Working Mathematician.

In describing what something is, it's often equally useful to describe what it's not.

The fact that Mac Lane uses the description to describe a Monad, one might imply that it describes something unique to monads. Bear with me. To develop a broader understanding of the statement, I believe it needs to be made clear that he is not describing something that is unique to monads; the statement equally describes Applicative and Arrows among others. For the same reason we can have two monoids on Int (Sum and Product), we can have several monoids on X in the category of endofunctors. But there is even more to the similarities.

Both Monad and Applicative meet the criteria:

  • endo => any arrow, or morphism that starts and ends in the same place
  • functor => any arrow, or morphism between two Categories

    (e.g., in day to day Tree a -> List b, but in Category Tree -> List)

  • monoid => single object; i.e., a single type, but in this context, only in regards to the external layer; so, we can't have Tree -> List, only List -> List.

The statement uses "Category of..." This defines the scope of the statement. As an example, the Functor Category describes the scope of f * -> g *, i.e., Any functor -> Any functor, e.g., Tree * -> List * or Tree * -> Tree *.

What a Categorical statement does not specify describes where anything and everything is permitted.

In this case, inside the functors, * -> * aka a -> b is not specified which means Anything -> Anything including Anything else. As my imagination jumps to Int -> String, it also includes Integer -> Maybe Int, or even Maybe Double -> Either String Int where a :: Maybe Double; b :: Either String Int.

So the statement comes together as follows:

  • functor scope :: f a -> g b (i.e., any parameterized type to any parameterized type)
  • endo + functor :: f a -> f b (i.e., any one parameterized type to the same parameterized type) ... said differently,
  • a monoid in the category of endofunctor

So, where is the power of this construct? To appreciate the full dynamics, I needed to see that the typical drawings of a monoid (single object with what looks like an identity arrow, :: single object -> single object), fails to illustrate that I'm permitted to use an arrow parameterized with any number of monoid values, from the one type object permitted in Monoid. The endo, ~ identity arrow definition of equivalence ignores the functor's type value and both the type and value of the most inner, "payload" layer. Thus, equivalence returns true in any situation where the functorial types match (e.g., Nothing -> Just * -> Nothing is equivalent to Just * -> Just * -> Just * because they are both Maybe -> Maybe -> Maybe).

Sidebar: ~ outside is conceptual, but is the left most symbol in f a. It also describes what "Haskell" reads-in first (big picture); so Type is "outside" in relation to a Type Value. The relationship between layers (a chain of references) in programming is not easy to relate in Category. The Category of Set is used to describe Types (Int, Strings, Maybe Int etc.) which includes the Category of Functor (parameterized Types). The reference chain: Functor Type, Functor values (elements of that Functor's set, e.g., Nothing, Just), and in turn, everything else each functor value points to. In Category the relationship is described differently, e.g., return :: a -> m a is considered a natural transformation from one Functor to another Functor, different from anything mentioned thus far.

Back to the main thread, all in all, for any defined tensor product and a neutral value, the statement ends up describing an amazingly powerful computational construct born from its paradoxical structure:

  • on the outside it appears as a single object (e.g., :: List); static
  • but inside, permits a lot of dynamics
    • any number of values of the same type (e.g., Empty | ~NonEmpty) as fodder to functions of any arity. The tensor product will reduce any number of inputs to a single value... for the external layer (~fold that says nothing about the payload)
    • infinite range of both the type and values for the inner most layer

In Haskell, clarifying the applicability of the statement is important. The power and versatility of this construct, has absolutely nothing to do with a monad per se. In other words, the construct does not rely on what makes a monad unique.

When trying to figure out whether to build code with a shared context to support computations that depend on each other, versus computations that can be run in parallel, this infamous statement, with as much as it describes, is not a contrast between the choice of Applicative, Arrows and Monads, but rather is a description of how much they are the same. For the decision at hand, the statement is moot.

This is often misunderstood. The statement goes on to describe join :: m (m a) -> m a as the tensor product for the monoidal endofunctor. However, it does not articulate how, in the context of this statement, (<*>) could also have also been chosen. It truly is a an example of six/half dozen. The logic for combining values are exactly alike; same input generates the same output from each (unlike the Sum and Product monoids for Int because they generate different results when combining Ints).

So, to recap: A monoid in the category of endofunctors describes:

   ~t :: m * -> m * -> m *
   and a neutral value for m *

(<*>) and (>>=) both provide simultaneous access to the two m values in order to compute the the single return value. The logic used to compute the return value is exactly the same. If it were not for the different shapes of the functions they parameterize (f :: a -> b versus k :: a -> m b) and the position of the parameter with the same return type of the computation (i.e., a -> b -> b versus b -> a -> b for each respectively), I suspect we could have parameterized the monoidal logic, the tensor product, for reuse in both definitions. As an exercise to make the point, try and implement ~t, and you end up with (<*>) and (>>=) depending on how you decide to define it forall a b.

If my last point is at minimum conceptually true, it then explains the precise, and only computational difference between Applicative and Monad: the functions they parameterize. In other words, the difference is external to the implementation of these type classes.

In conclusion, in my own experience, Mac Lane's infamous quote provided a great "goto" meme, a guidepost for me to reference while navigating my way through Category to better understand the idioms used in Haskell. It succeeds at capturing the scope of a powerful computing capacity made wonderfully accessible in Haskell.

However, there is irony in how I first misunderstood the statement's applicability outside of the monad, and what I hope conveyed here. Everything that it describes turns out to be what is similar between Applicative and Monads (and Arrows among others). What it doesn't say is precisely the small but useful distinction between them.

- E

ImportError: No module named Crypto.Cipher

Well this might appear weird but after installing pycrypto or pycryptodome , we need to update the directory name crypto to Crypto in lib/site-packages

Reference

shared global variables in C

In one header file (shared.h):

extern int this_is_global;

In every file that you want to use this global symbol, include header containing the extern declaration:

#include "shared.h"

To avoid multiple linker definitions, just one declaration of your global symbol must be present across your compilation units (e.g: shared.cpp) :

/* shared.cpp */
#include "shared.h"
int this_is_global;

Why use deflate instead of gzip for text files served by Apache?

mod_deflate requires fewer resources on your server, although you may pay a small penalty in terms of the amount of compression.

If you are serving many small files, I'd recommend benchmarking and load testing your compressed and uncompressed solutions - you may find some cases where enabling compression will not result in savings.

Delete a row in DataGridView Control in VB.NET

Assuming you are using Windows forms, you could allow the user to select a row and in the delete key click event. It is recommended that you allow the user to select 1 row only and not a group of rows (myDataGridView.MultiSelect = false)

Private Sub pbtnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click

        If myDataGridView.SelectedRows.Count > 0 Then
            'you may want to add a confirmation message, and if the user confirms delete
            myDataGridView.Rows.Remove(myDataGridView.SelectedRows(0))
        Else
            MessageBox.Show("Select 1 row before you hit Delete")
        End If

    End Sub

Note that this will not delete the row form the database until you perform the delete in the database.

Convert timestamp long to normal date format

Let me propose this solution for you. So in your managed bean, do this

public String convertTime(long time){
    Date date = new Date(time);
    Format format = new SimpleDateFormat("yyyy MM dd HH:mm:ss");
    return format.format(date);
}

so in your JSF page, you can do this (assuming foo is the object that contain your time)

<h:dataTable value="#{myBean.convertTime(myBean.foo.time)}" />

If you have multiple pages that want to utilize this method, you can put this in an abstract class and have your managed bean extend this abstract class.

EDIT: Return time with TimeZone

unfortunately, I think SimpleDateFormat will always format the time in local time, so we can't use SimpleDateFormat anymore. So to display time in different TimeZone, we can do this

public String convertTimeWithTimeZome(long time){
    Calendar cal = Calendar.getInstance();
    cal.setTimeZone(TimeZone.getTimeZone("UTC"));
    cal.setTimeInMillis(time);
    return (cal.get(Calendar.YEAR) + " " + (cal.get(Calendar.MONTH) + 1) + " " 
            + cal.get(Calendar.DAY_OF_MONTH) + " " + cal.get(Calendar.HOUR_OF_DAY) + ":"
            + cal.get(Calendar.MINUTE));

}

A better solution is to utilize JodaTime. In my opinion, this API is much better than Calendar (lighter weight, faster and provide more functionality). Plus Calendar.Month of January is 0, that force developer to add 1 to the result, and you have to format the time yourself. Using JodaTime, you can fix all of that. Correct me if I am wrong, but I think JodaTime is incorporated in JDK7

You must add a reference to assembly 'netstandard, Version=2.0.0.0

We started getting this error on the production server after deploying the application migrated from 4.6.1 to 4.7.2.

We noticed that the .NET framework 4.7.2 was not installed there. In order to solve this issue we did the following steps:

  1. Installed the .NET Framework 4.7.2 from:

    https://support.microsoft.com/en-us/help/4054530/microsoft-net-framework-4-7-2-offline-installer-for-windows

  2. Restarted the machine

  3. Confirmed the .NET Framework version with the help of How do I find the .NET version?

Running the application again with the .Net Framework 4.7.2 version installed on the machine fixed the issue.

SQL - IF EXISTS UPDATE ELSE INSERT Syntax Error

INSERT INTO component_psar (tbl_id, row_nr, col_1, col_2, col_3, col_4, col_5, col_6, unit, add_info, fsar_lock)
VALUES('2', '1', '1', '1', '1', '1', '1', '1', '1', '1', 'N')
ON DUPLICATE KEY UPDATE col_1 = VALUES(col_1), col_2 = VALUES(col_2), col_3 = VALUES(col_3), col_4 = VALUES(col_4), col_5 = VALUES(col_5), col_6 = VALUES(col_6), unit = VALUES(unit), add_info = VALUES(add_info), fsar_lock = VALUES(fsar_lock)

Would work with tbl_id and row_nr having UNIQUE key.

This is the method DocJonas linked to with an example.

Access Form - Syntax error (missing operator) in query expression

I had this same problem. As Dedren says, the problem is not the query, but the form object's control source. Put [] around each objects Control Source. eg: Contol Source: [Product number], Control Source: Salesperson.[Salesperson number], etc.

Makita recomends going to the original table that you are referencing in your query and rename the field so that there are no spaces eg: SalesPersonNumber, ProductNumber, etc. This will solve many future problems as well. Best of Luck!

Get most recent row for given ID

SELECT *
FROM   tbl
WHERE  id = 1
ORDER  BY signin DESC
LIMIT  1;

The obvious index would be on (id), or a multicolumn index on (id, signin DESC).

Conveniently for the case, MySQL sorts NULL values last in descending order. That's what you typically want if there can be NULL values: the row with the latest not-null signin.

To get NULL values first:

ORDER BY signin IS NOT NULL, signin DESC

You may want to append more expressions to ORDER BY to get a deterministic pick from (potentially) multiple rows with NULL.
The same applies without NULL if signin is not defined UNIQUE.

Related:

The SQL standard does not explicitly define a default sort order for NULL values. The behavior varies quite a bit across different RDBMS. See:

But there are the NULLS FIRST / NULLS LAST clauses defined in the SQL standard and supported by most major RDBMS, but not by MySQL. See:

What is DOM Event delegation?

Event delegation makes use of two often overlooked features of JavaScript events: event bubbling and the target element.When an event is triggered on an element, for example a mouse click on a button, the same event is also triggered on all of that element’s ancestors. This process is known as event bubbling; the event bubbles up from the originating element to the top of the DOM tree.

Imagine an HTML table with 10 columns and 100 rows in which you want something to happen when the user clicks on a table cell. For example, I once had to make each cell of a table of that size editable when clicked. Adding event handlers to each of the 1000 cells would be a major performance problem and, potentially, a source of browser-crashing memory leaks. Instead, using event delegation, you would add only one event handler to the table element, intercept the click event and determine which cell was clicked.

process.waitFor() never returns

Asynchronous reading of stream combined with avoiding Wait with a timeout will solve the problem.

You can find a page explaining this here http://simplebasics.net/.net/process-waitforexit-with-a-timeout-will-not-be-able-to-collect-the-output-message/

Creating a JSON array in C#

You'd better create some class for each item instead of using anonymous objects. And in object you're serializing you should have array of those items. E.g.:

public class Item
{
    public string name { get; set; }
    public string index { get; set; }
    public string optional { get; set; }
}

public class RootObject
{
    public List<Item> items { get; set; }
}

Usage:

var objectToSerialize = new RootObject();
objectToSerialize.items = new List<Item> 
                          {
                             new Item { name = "test1", index = "index1" },
                             new Item { name = "test2", index = "index2" }
                          };

And in the result you won't have to change things several times if you need to change data-structure.

p.s. Here's very nice tool for complex jsons

What is causing ImportError: No module named pkg_resources after upgrade of Python on os X?

[UPDATE] TL;DR pkg_resources is provided by either Distribute or setuptools.

[UPDATE 2] As announced at PyCon 2013, the Distribute and setuptools projects have re-merged. Distribute is now deprecated and you should just use the new current setuptools. Try this:

curl -O https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py
python ez_setup.py

Or, better, use a current pip as the high level interface and which will use setuptools under the covers.

[Longer answer for OP's specific problem]:

You don't say in your question but I'm assuming you upgraded from the Apple-supplied Python (2.5 on 10.5 or 2.6.1 on 10.6) or that you upgraded from a python.org Python 2.5. In any of those cases, the important point is that each Python instance has its own library, including its own site-packages library, which is where additional packages are installed. (And none of them use /usr/local/lib by default, by the way.) That means you'll need to install those additional packages you need for your new python 2.6. The easiest way to do this is to first ensure that the new python2.6 appears first on your search $PATH (that is, typing python2.6 invokes it as expected); the python2.6 installer should have modified your .bash_profile to put its framework bin directory at the front of $PATH. Then install easy_install using setuptools following the instructions there. The pkg_resources module is also automatically installed by this step.

Then use the newly-installed version of easy_install (or pip) to install ipython.

easy_install ipython

or

pip install ipython

It should automatically get installed to the correct site-packages location for that python instance and you should be good to go.

Advantages of std::for_each over for loop

Easy: for_each is useful when you already have a function to handle every array item, so you don't have to write a lambda. Certainly, this

for_each(a.begin(), a.end(), a_item_handler);

is better than

for(auto& item: a) {
    a_item_handler(a);
}

Also, ranged for loop only iterates over whole containers from start to end, whilst for_each is more flexible.

Better way to find control in ASP.NET

FindControl does not search within nested controls recursively. It does only find controls that's NamigContainer is the Control on that you are calling FindControl.

Theres a reason that ASP.Net does not look into your nested controls recursively by default:

  • Performance
  • Avoiding errors
  • Reusability

Consider you want to encapsulate your GridViews, Formviews, UserControls etc. inside of other UserControls for reusability reasons. If you would have implemented all logic in your page and accessed these controls with recursive loops, it'll very difficult to refactor that. If you have implemented your logic and access methods via the event-handlers(f.e. RowDataBound of GridView), it'll be much simpler and less error-prone.

Remove Sub String by using Python

>>> import re
>>> st = " i think mabe 124 + <font color=\"black\"><font face=\"Times New Roman\">but I don't have a big experience it just how I see it in my eyes <font color=\"green\"><font face=\"Arial\">fun stuff"
>>> re.sub("<.*?>","",st)
" i think mabe 124 + but I don't have a big experience it just how I see it in my eyes fun stuff"
>>> 

How do I iterate over a JSON structure?

Please let me know if it is not easy:

var jsonObject = {
  name: 'Amit Kumar',
  Age: '27'
};

for (var prop in jsonObject) {
  alert("Key:" + prop);
  alert("Value:" + jsonObject[prop]);
}

How to create a .jar file or export JAR in IntelliJ IDEA (like Eclipse Java archive export)?

For Intellij IDEA version 11.0.2

File | Project Structure | Artifacts then you should press alt+insert or click the plus icon and create new artifact choose --> jar --> From modules with dependencies.

Next goto Build | Build artifacts --> choose your artifact.

source: http://blogs.jetbrains.com/idea/2010/08/quickly-create-jar-artifact/

Browser Caching of CSS files

Unless you've messed with your server, yes it's cached. All the browsers are supposed to handle it the same. Some people (like me) might have their browsers configured so that it doesn't cache any files though. Closing the browser doesn't invalidate the file in the cache. Changing the file on the server should cause a refresh of the file however.

django change default runserver port

I'm very late to the party here, but if you use an IDE like PyCharm, there's an option in 'Edit Configurations' under the 'Run' menu (Run > Edit Configurations) where you can specify a default port. This of course is relevant only if you are debugging/testing through PyCharm.

What is the reason for a red exclamation mark next to my project in Eclipse?

It means the jar files are missing from the path that you have given while configuring Build Path/adding jars to the project.

Just once again configure the jars.

How to apply !important using .css()?

Another easy method to solve this issue adding the style attribute:

$('.selector').attr('style', 'width:500px !important');

How to split strings over multiple lines in Bash?

In certain scenarios utilizing Bash's concatenation ability might be appropriate.

Example:

temp='this string is very long '
temp+='so I will separate it onto multiple lines'
echo $temp
this string is very long so I will separate it onto multiple lines

From the PARAMETERS section of the Bash Man page:

name=[value]...

...In the context where an assignment statement is assigning a value to a shell variable or array index, the += operator can be used to append to or add to the variable's previous value. When += is applied to a variable for which the integer attribute has been set, value is evaluated as an arithmetic expression and added to the variable's current value, which is also evaluated. When += is applied to an array variable using compound assignment (see Arrays below), the variable's value is not unset (as it is when using =), and new values are appended to the array beginning at one greater than the array's maximum index (for indexed arrays) or added as additional key-value pairs in an associative array. When applied to a string-valued variable, value is expanded and appended to the variable's value.

jQuery: How to get the event object in an event handler function without passing it as an argument?

in IE you can get the event object by window.event in other browsers with no 'use strict' directive, it is possible to get by arguments.callee.caller.arguments[0].

function myFunc(p1, p2, p3) {
    var evt = window.event || arguments.callee.caller.arguments[0];
}

How do DATETIME values work in SQLite?

Store it in a field of type long. See Date.getTime() and new Date(long)

mysql said: Cannot connect: invalid settings. xampp

if you are using google chrome you can fix the problem via , trying any one of the steps mentioned on this page but you need to clear your whole browsing history .... clear all the data that chrome saved onto your computer by pressing ctrl+h and the clearing all the browsing data select all the fields now restart php my admin and all will work

How do you list volumes in docker containers?

I actually googled this, and found my own answer :) My memory these days... And for those that dont know about it commandlinefu is a nice place to find and publish these kinda snippets.

List docker volumes by container.

docker ps -a --format '{{ .ID }}' | xargs -I {} docker inspect -f '{{ .Name }}{{ printf "\n" }}{{ range .Mounts }}{{ printf "\n\t" }}{{ .Type }} {{ if eq .Type "bind" }}{{ .Source }}{{ end }}{{ .Name }} => {{ .Destination }}{{ end }}{{ printf "\n" }}' {}

Example output.

root@jac007-truserv-jhb1-001 ~/gitlab $ docker ps -a --format '{{ .ID }}' | xargs -I {} docker inspect -f '{{ .Name }}{{ printf "\n" }}{{ range .Mounts }}{{ printf "\n\t" }}{{ .Type }} {{ if eq .Type "bind" }}{{ .Source }}{{ end }}{{ .Name }} => {{ .Destination }}{{ end }}{{ printf "\n" }}' {}
/gitlab_server_1

    volume gitlab-data => /var/opt/gitlab
    volume gitlab-config => /etc/gitlab
    volume gitlab-logs => /var/log/gitlab

/gitlab_runner_1

    bind /var/run/docker.sock => /var/run/docker.sock
    volume gitlab-runner-config => /etc/gitlab-runner
    volume 35b5ea874432f55a26c769e1cdb1ee3f06f78759e6f302e3c4b4aa40f3a495aa => /home/gitlab-runner

Update my gradle dependencies in eclipse

I tried all above options but was still getting error, in my case issue was I have not setup gradle installation directory in eclipse, following worked:

eclipse -> Window -> Preferences -> Gradle -> "Select Local Installation Directory"

Click on Browse button and provide path.

Even though question is answered, thought to share in case somebody else is facing similar issue.

Cheers !

Link to download apache http server for 64bit windows.

An unofficial 64-bit Windows build is available from Apache Lounge.

How to: Install Plugin in Android Studio

  1. Launch Android Studio application
  2. Choose Project Settings
  3. Choose Plugin from disk, if on disk then choose that location of *.jar, in my case is GenyMotion jar
  4. Click on Apply and OK.
  5. Then Android studio will ask for Restart.

That's all Folks! enter image description here

git am error: "patch does not apply"

I had the same problem. I had used

git format-patch <commit_hash>

to create the patch. My main problem was patch was failing due to some conflicts, but I could not see any merge conflict in the file content. I had used git am --3way <patch_file_path> to apply the patch.

The correct command to apply the patch should be:

git am --3way --ignore-space-change <patch_file_path>

If you execute the above command for patching, it will create a merge conflict if patch apply fails. Then you can fix the conflict in your files, like the same way merge conflicts are resolved for git merge

Setting user agent of a java URLConnection

HTTP Servers tend to reject old browsers and systems.

The page Tech Blog (wh): Most Common User Agents reflects the user-agent property of your current browser in section "Your user agent is:", which can be applied to set the request property "User-Agent" of a java.net.URLConnection or the system property "http.agent".

Writing data into CSV file in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;

public partial class CS : System.Web.UI.Page
{
    protected void ExportCSV(object sender, EventArgs e)
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers"))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    using (DataTable dt = new DataTable())
                    {
                        sda.Fill(dt);

                        //Build the CSV file data as a Comma separated string.
                        string csv = string.Empty;

                        foreach (DataColumn column in dt.Columns)
                        {
                            //Add the Header row for CSV file.
                            csv += column.ColumnName + ',';
                        }

                        //Add new line.
                        csv += "\r\n";

                        foreach (DataRow row in dt.Rows)
                        {
                            foreach (DataColumn column in dt.Columns)
                            {
                                //Add the Data rows.
                                csv += row[column.ColumnName].ToString().Replace(",", ";") + ',';
                            }

                            //Add new line.
                            csv += "\r\n";
                        }

                        //Download the CSV file.
                        Response.Clear();
                        Response.Buffer = true;
                        Response.AddHeader("content-disposition", "attachment;filename=SqlExport.csv");
                        Response.Charset = "";
                        Response.ContentType = "application/text";
                        Response.Output.Write(csv);
                        Response.Flush();
                        Response.End();
                    }
                }
            }
        }
    }
}

Set the space between Elements in Row Flutter

MainAxisAlignment

start - Place the children as close to the start of the main axis as possible.

enter image description here

end - Place the children as close to the end of the main axis as possible.

enter image description here

center - Place the children as close to the middle of the main axis as possible.

enter image description here

spaceBetween - Place the free space evenly between the children.

enter image description here

spaceAround - Place the free space evenly between the children as well as half of that space before and after the first and last child.

enter image description here

spaceEvenly - Place the free space evenly between the children as well as before and after the first and last child.

enter image description here

Example:

  child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Text('Row1'),
          Text('Row2')
        ],
      )

Laravel check if collection is empty

From php7 you can use Null Coalesce Opperator:

$employee = $mentors->intern ?? $mentors->intern->employee

This will return Null or the employee.

Where do alpha testers download Google Play Android apps?

It should be noted that releasing an alpha app for the first time may take up to a few hours before an opt-in link is available and invitations are sent out to the email addresses in your testers list.

From Google support:

After publishing an alpha/beta app for the first time, it may take a few hours for your test link to be available to testers. If you publish additional changes, they may take several hours to be available for testers. [source]

You may want to wait until you have an initial opt-in link before publishing more changes to the app because doing so is likely to increase your wait time for receiving your tester link; or, may lead to your testers testing with the incorrect version.

Hope that clears things up for anyone confused about why they don't have an opt-in link as depicted in screenshots in this SO thread!

Java, looping through result set

The problem with your code is :

     String  show[]= {rs4.getString(1)};
     String actuate[]={rs4.getString(2)};

This will create a new array every time your loop (an not append as you might be assuming) and hence in the end you will have only one element per array.

Here is one more way to solve this :

    StringBuilder sids = new StringBuilder ();
    StringBuilder lids = new StringBuilder ();

    while (rs4.next()) {
        sids.append(rs4.getString(1)).append(" ");
        lids.append(rs4.getString(2)).append(" ");
    }

    String show[] = sids.toString().split(" "); 
    String actuate[] = lids.toString().split(" ");

These arrays will have all the required element.

.prop('checked',false) or .removeAttr('checked')?

Another alternative to do the same thing is to filter on type=checkbox attribute:

$('input[type="checkbox"]').removeAttr('checked');

or

$('input[type="checkbox"]').prop('checked' , false);

Remeber that The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

Know more...

How to put individual tags for a scatter plot

Perhaps use plt.annotate:

import numpy as np
import matplotlib.pyplot as plt

N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]

plt.subplots_adjust(bottom = 0.1)
plt.scatter(
    data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500,
    cmap=plt.get_cmap('Spectral'))

for label, x, y in zip(labels, data[:, 0], data[:, 1]):
    plt.annotate(
        label,
        xy=(x, y), xytext=(-20, 20),
        textcoords='offset points', ha='right', va='bottom',
        bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
        arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))

plt.show()

enter image description here

A fatal error has been detected by the Java Runtime Environment: SIGSEGV, libjvm

It can happen because of native method calling in your application. For example, in Qtjambi if you use QApplication.quit() instead of QApplication.closeAllWindows() for closing a Java application it generates an error log.

In this case, you can get a stack trace right to your method that called the native code and caused the crash. Just look in the log file it tells you about:

# An error report file with more information is saved as hs_err_pid24139.log.

The stack trace looks quite unusual, since it has native code mixed with VM code and your code, but each line is prefixed so you can tell which lines are your own code. There's a key at the top of the stack trace to explain the prefixes:

Native frames: (J=compiled Java code, A=aot compiled Java code, j=interpreted, Vv=VM code, C=native code)

Removing elements from an array in C

Try this simple code:

#include <stdio.h>
#include <conio.h>
void main(void)
{ 
    clrscr();
    int a[4], i, b;
    printf("enter nos ");
    for (i = 1; i <= 5; i++) {
        scanf("%d", &a[i]);
    }
    for(i = 1; i <= 5; i++) {
        printf("\n%d", a[i]);
    }
    printf("\nenter element you want to delete ");
    scanf("%d", &b);
    for (i = 1; i <= 5; i++) {
        if(i == b) {
            a[i] = i++;
        }
        printf("\n%d", a[i]);
    }
    getch();
}

What is the preferred syntax for defining enums in JavaScript?

your answers are far too complicated

var buildSet = function(array) {
  var set = {};
  for (var i in array) {
    var item = array[i];
    set[item] = item;
  }
  return set;
}

var myEnum = buildSet(['RED','GREEN','BLUE']);
// myEnum.RED == 'RED' ...etc

Openssl is not recognized as an internal or external command

Downloads and Unzip

You can download openssl for windows 32 and 64 bit from the respective links below:

https://code.google.com/archive/p/openssl-for-windows/downloads

OpenSSL for 64 Bits OpenSSL for 32 Bits

keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | **"C:\Users\keshav.gera\openssl-0.9.8k_X64\bin**\openssl.exe" sha1 -binary | **"C:\Users\keshav.gera\openssl-0.9.8k_X64\bin**\openssl.exe" base64

Important change our path Here as well as install open ssl in your system

It's Working No Doubt

C:\Users\keshav.gera>keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | "C:\Users\keshav.gera\openssl-0.9.8k_X64\bin\openssl.exe" sha1 -binary | "C:\Users\keshav.gera\openssl-0.9.8k_X64\bin\openssl.exe" base64

Enter keystore password: android

**ZrRtxw36xWNYL+h3aJdcCeQQxi0=**

=============================================================

using Manually through Coding

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


private void PrintHashKey() {

        try {
            PackageInfo info = getPackageManager().getPackageInfo("**com.keshav.patanjalidemo  Your Package Name Here**", PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");        
                md.update(signature.toByteArray());
                Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

    }

change array size

In case you cannot use Array.Reset (the variable is not local) then Concat & ToArray helps:

anObject.anArray.Concat(new string[] { newArrayItem }).ToArray();

Android Open External Storage directory(sdcard) for storing file

The internal storage is referred to as "external storage" in the API.

As mentioned in the Environment documentation

Note: don't be confused by the word "external" here. This directory can better be thought as media/shared storage. It is a filesystem that can hold a relatively large amount of data and that is shared across all applications (does not enforce permissions). Traditionally this is an SD card, but it may also be implemented as built-in storage in a device that is distinct from the protected internal storage and can be mounted as a filesystem on a computer.

To distinguish whether "Environment.getExternalStorageDirectory()" actually returned physically internal or external storage, call Environment.isExternalStorageEmulated(). If it's emulated, than it's internal. On newer devices that have internal storage and sdcard slot Environment.getExternalStorageDirectory() will always return the internal storage. While on older devices that have only sdcard as a media storage option it will always return the sdcard.

There is no way to retrieve all storages using current Android API.

I've created a helper based on Vitaliy Polchuk's method in the answer below

How can I get the list of mounted external storage of android device

NOTE: starting KitKat secondary storage is accessible only as READ-ONLY, you may want to check for writability using the following method

/**
 * Checks whether the StorageVolume is read-only
 * 
 * @param volume
 *            StorageVolume to check
 * @return true, if volume is mounted read-only
 */
public static boolean isReadOnly(@NonNull final StorageVolume volume) {
    if (volume.mFile.equals(Environment.getExternalStorageDirectory())) {
        // is a primary storage, check mounted state by Environment
        return android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED_READ_ONLY);
    } else {
        if (volume.getType() == Type.USB) {
            return volume.isReadOnly();
        }
        //is not a USB storagem so it's read-only if it's mounted read-only or if it's a KitKat device
        return volume.isReadOnly() || Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
    }
}

StorageHelper class

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.StringTokenizer;

import android.os.Environment;

public final class StorageHelper {

    //private static final String TAG = "StorageHelper";

    private StorageHelper() {
    }

    private static final String STORAGES_ROOT;

    static {
        final String primaryStoragePath = Environment.getExternalStorageDirectory()
                .getAbsolutePath();
        final int index = primaryStoragePath.indexOf(File.separatorChar, 1);
        if (index != -1) {
            STORAGES_ROOT = primaryStoragePath.substring(0, index + 1);
        } else {
            STORAGES_ROOT = File.separator;
        }
    }

    private static final String[] AVOIDED_DEVICES = new String[] {
        "rootfs", "tmpfs", "dvpts", "proc", "sysfs", "none"
    };

    private static final String[] AVOIDED_DIRECTORIES = new String[] {
        "obb", "asec"
    };

    private static final String[] DISALLOWED_FILESYSTEMS = new String[] {
        "tmpfs", "rootfs", "romfs", "devpts", "sysfs", "proc", "cgroup", "debugfs"
    };

    /**
     * Returns a list of mounted {@link StorageVolume}s Returned list always
     * includes a {@link StorageVolume} for
     * {@link Environment#getExternalStorageDirectory()}
     * 
     * @param includeUsb
     *            if true, will include USB storages
     * @return list of mounted {@link StorageVolume}s
     */
    public static List<StorageVolume> getStorages(final boolean includeUsb) {
        final Map<String, List<StorageVolume>> deviceVolumeMap = new HashMap<String, List<StorageVolume>>();

        // this approach considers that all storages are mounted in the same non-root directory
        if (!STORAGES_ROOT.equals(File.separator)) {
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new FileReader("/proc/mounts"));
                String line;
                while ((line = reader.readLine()) != null) {
                    // Log.d(TAG, line);
                    final StringTokenizer tokens = new StringTokenizer(line, " ");

                    final String device = tokens.nextToken();
                    // skipped devices that are not sdcard for sure
                    if (arrayContains(AVOIDED_DEVICES, device)) {
                        continue;
                    }

                    // should be mounted in the same directory to which
                    // the primary external storage was mounted
                    final String path = tokens.nextToken();
                    if (!path.startsWith(STORAGES_ROOT)) {
                        continue;
                    }

                    // skip directories that indicate tha volume is not a storage volume
                    if (pathContainsDir(path, AVOIDED_DIRECTORIES)) {
                        continue;
                    }

                    final String fileSystem = tokens.nextToken();
                    // don't add ones with non-supported filesystems
                    if (arrayContains(DISALLOWED_FILESYSTEMS, fileSystem)) {
                        continue;
                    }

                    final File file = new File(path);
                    // skip volumes that are not accessible
                    if (!file.canRead() || !file.canExecute()) {
                        continue;
                    }

                    List<StorageVolume> volumes = deviceVolumeMap.get(device);
                    if (volumes == null) {
                        volumes = new ArrayList<StorageVolume>(3);
                        deviceVolumeMap.put(device, volumes);
                    }

                    final StorageVolume volume = new StorageVolume(device, file, fileSystem);
                    final StringTokenizer flags = new StringTokenizer(tokens.nextToken(), ",");
                    while (flags.hasMoreTokens()) {
                        final String token = flags.nextToken();
                        if (token.equals("rw")) {
                            volume.mReadOnly = false;
                            break;
                        } else if (token.equals("ro")) {
                            volume.mReadOnly = true;
                            break;
                        }
                    }
                    volumes.add(volume);
                }

            } catch (IOException ex) {
                ex.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException ex) {
                        // ignored
                    }
                }
            }
        }

        // remove volumes that are the same devices
        boolean primaryStorageIncluded = false;
        final File externalStorage = Environment.getExternalStorageDirectory();
        final List<StorageVolume> volumeList = new ArrayList<StorageVolume>();
        for (final Entry<String, List<StorageVolume>> entry : deviceVolumeMap.entrySet()) {
            final List<StorageVolume> volumes = entry.getValue();
            if (volumes.size() == 1) {
                // go ahead and add
                final StorageVolume v = volumes.get(0);
                final boolean isPrimaryStorage = v.file.equals(externalStorage);
                primaryStorageIncluded |= isPrimaryStorage;
                setTypeAndAdd(volumeList, v, includeUsb, isPrimaryStorage);
                continue;
            }
            final int volumesLength = volumes.size();
            for (int i = 0; i < volumesLength; i++) {
                final StorageVolume v = volumes.get(i);
                if (v.file.equals(externalStorage)) {
                    primaryStorageIncluded = true;
                    // add as external storage and continue
                    setTypeAndAdd(volumeList, v, includeUsb, true);
                    break;
                }
                // if that was the last one and it's not the default external
                // storage then add it as is
                if (i == volumesLength - 1) {
                    setTypeAndAdd(volumeList, v, includeUsb, false);
                }
            }
        }
        // add primary storage if it was not found
        if (!primaryStorageIncluded) {
            final StorageVolume defaultExternalStorage = new StorageVolume("", externalStorage, "UNKNOWN");
            defaultExternalStorage.mEmulated = Environment.isExternalStorageEmulated();
            defaultExternalStorage.mType =
                    defaultExternalStorage.mEmulated ? StorageVolume.Type.INTERNAL
                            : StorageVolume.Type.EXTERNAL;
            defaultExternalStorage.mRemovable = Environment.isExternalStorageRemovable();
            defaultExternalStorage.mReadOnly =
                    Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY);
            volumeList.add(0, defaultExternalStorage);
        }
        return volumeList;
    }

    /**
     * Sets {@link StorageVolume.Type}, removable and emulated flags and adds to
     * volumeList
     * 
     * @param volumeList
     *            List to add volume to
     * @param v
     *            volume to add to list
     * @param includeUsb
     *            if false, volume with type {@link StorageVolume.Type#USB} will
     *            not be added
     * @param asFirstItem
     *            if true, adds the volume at the beginning of the volumeList
     */
    private static void setTypeAndAdd(final List<StorageVolume> volumeList,
            final StorageVolume v,
            final boolean includeUsb,
            final boolean asFirstItem) {
        final StorageVolume.Type type = resolveType(v);
        if (includeUsb || type != StorageVolume.Type.USB) {
            v.mType = type;
            if (v.file.equals(Environment.getExternalStorageDirectory())) {
                v.mRemovable = Environment.isExternalStorageRemovable();
            } else {
                v.mRemovable = type != StorageVolume.Type.INTERNAL;
            }
            v.mEmulated = type == StorageVolume.Type.INTERNAL;
            if (asFirstItem) {
                volumeList.add(0, v);
            } else {
                volumeList.add(v);
            }
        }
    }

    /**
     * Resolved {@link StorageVolume} type
     * 
     * @param v
     *            {@link StorageVolume} to resolve type for
     * @return {@link StorageVolume} type
     */
    private static StorageVolume.Type resolveType(final StorageVolume v) {
        if (v.file.equals(Environment.getExternalStorageDirectory())
                && Environment.isExternalStorageEmulated()) {
            return StorageVolume.Type.INTERNAL;
        } else if (containsIgnoreCase(v.file.getAbsolutePath(), "usb")) {
            return StorageVolume.Type.USB;
        } else {
            return StorageVolume.Type.EXTERNAL;
        }
    }

    /**
     * Checks whether the array contains object
     * 
     * @param array
     *            Array to check
     * @param object
     *            Object to find
     * @return true, if the given array contains the object
     */
    private static <T> boolean arrayContains(T[] array, T object) {
        for (final T item : array) {
            if (item.equals(object)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Checks whether the path contains one of the directories
     * 
     * For example, if path is /one/two, it returns true input is "one" or
     * "two". Will return false if the input is one of "one/two", "/one" or
     * "/two"
     * 
     * @param path
     *            path to check for a directory
     * @param dirs
     *            directories to find
     * @return true, if the path contains one of the directories
     */
    private static boolean pathContainsDir(final String path, final String[] dirs) {
        final StringTokenizer tokens = new StringTokenizer(path, File.separator);
        while (tokens.hasMoreElements()) {
            final String next = tokens.nextToken();
            for (final String dir : dirs) {
                if (next.equals(dir)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * Checks ifString contains a search String irrespective of case, handling.
     * Case-insensitivity is defined as by
     * {@link String#equalsIgnoreCase(String)}.
     * 
     * @param str
     *            the String to check, may be null
     * @param searchStr
     *            the String to find, may be null
     * @return true if the String contains the search String irrespective of
     *         case or false if not or {@code null} string input
     */
    public static boolean containsIgnoreCase(final String str, final String searchStr) {
        if (str == null || searchStr == null) {
            return false;
        }
        final int len = searchStr.length();
        final int max = str.length() - len;
        for (int i = 0; i <= max; i++) {
            if (str.regionMatches(true, i, searchStr, 0, len)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Represents storage volume information
     */
    public static final class StorageVolume {

        /**
         * Represents {@link StorageVolume} type
         */
        public enum Type {
            /**
             * Device built-in internal storage. Probably points to
             * {@link Environment#getExternalStorageDirectory()}
             */
            INTERNAL,

            /**
             * External storage. Probably removable, if no other
             * {@link StorageVolume} of type {@link #INTERNAL} is returned by
             * {@link StorageHelper#getStorages(boolean)}, this might be
             * pointing to {@link Environment#getExternalStorageDirectory()}
             */
            EXTERNAL,

            /**
             * Removable usb storage
             */
            USB
        }

        /**
         * Device name
         */
        public final String device;

        /**
         * Points to mount point of this device
         */
        public final File file;

        /**
         * File system of this device
         */
        public final String fileSystem;

        /**
         * if true, the storage is mounted as read-only
         */
        private boolean mReadOnly;

        /**
         * If true, the storage is removable
         */
        private boolean mRemovable;

        /**
         * If true, the storage is emulated
         */
        private boolean mEmulated;

        /**
         * Type of this storage
         */
        private Type mType;

        StorageVolume(String device, File file, String fileSystem) {
            this.device = device;
            this.file = file;
            this.fileSystem = fileSystem;
        }

        /**
         * Returns type of this storage
         * 
         * @return Type of this storage
         */
        public Type getType() {
            return mType;
        }

        /**
         * Returns true if this storage is removable
         * 
         * @return true if this storage is removable
         */
        public boolean isRemovable() {
            return mRemovable;
        }

        /**
         * Returns true if this storage is emulated
         * 
         * @return true if this storage is emulated
         */
        public boolean isEmulated() {
            return mEmulated;
        }

        /**
         * Returns true if this storage is mounted as read-only
         * 
         * @return true if this storage is mounted as read-only
         */
        public boolean isReadOnly() {
            return mReadOnly;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((file == null) ? 0 : file.hashCode());
            return result;
        }

        /**
         * Returns true if the other object is StorageHelper and it's
         * {@link #file} matches this one's
         * 
         * @see Object#equals(Object)
         */
        @Override
        public boolean equals(Object obj) {
            if (obj == this) {
                return true;
            }
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            final StorageVolume other = (StorageVolume) obj;
            if (file == null) {
                return other.file == null;
            }
            return file.equals(other.file);
        }

        @Override
        public String toString() {
            return file.getAbsolutePath() + (mReadOnly ? " ro " : " rw ") + mType + (mRemovable ? " R " : "")
                    + (mEmulated ? " E " : "") + fileSystem;
        }
    }
}

MVC4 input field placeholder

 @Html.TextBoxFor(m => m.UserName, new { @class = "form-control",@placeholder = "Name"  })  

XmlSerializer: remove unnecessary xsi and xsd namespaces

//Create our own namespaces for the output
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

//Add an empty namespace and empty value
ns.Add("", "");

//Create the serializer
XmlSerializer slz = new XmlSerializer(someType);

//Serialize the object with our own namespaces (notice the overload)
slz.Serialize(myXmlTextWriter, someObject, ns)

How to create custom view programmatically in swift having controls text field, button etc

Swift 3 / Swift 4 Update:

let screenSize: CGRect = UIScreen.main.bounds
let myView = UIView(frame: CGRect(x: 0, y: 0, width: screenSize.width - 10, height: 10))
self.view.addSubview(myView)

Send value of submit button when form gets posted

To start, using the same ID twice is not a good idea. ID's should be unique, if you need to style elements you should use a class to apply CSS instead.

At last, you defined the name of your submit button as Tea and Coffee, but in your PHP you are using submit as index. your index should have been $_POST['Tea'] for example. that would require you to check for it being set as it only sends one , you can do that with isset().

Buy anyway , user4035 just beat me to it , his code will "fix" this for you.

Iterating over arrays in Python 3

The for loop iterates over the elements of the array, not its indexes. Suppose you have a list ar = [2, 4, 6]:

When you iterate over it with for i in ar: the values of i will be 2, 4 and 6. So, when you try to access ar[i] for the first value, it might work (as the last position of the list is 2, a[2] equals 6), but not for the latter values, as a[4] does not exist.

If you intend to use indexes anyhow, try using for index, value in enumerate(ar):, then theSum = theSum + ar[index] should work just fine.

Difference between \n and \r?

To complete,

In a shell (bash) script, you can use \r to send cursor, in front on line and, of course \n to put cursor on a new line.

For example, try :

echo -en "AA--AA" ; echo -en "BB" ; echo -en "\rBB"
  • The first "echo" display AA--AA
  • The second : AA--AABB
  • The last : BB--AABB

But don't forget to use -en as parameters.

EOL conversion in notepad ++

That functionality is already built into Notepad++. From the "Edit" menu, select "EOL Conversion" -> "UNIX/OSX Format".

screenshot of the option for even quicker finding (or different language versions)

You can also set the default EOL in notepad++ via "Settings" -> "Preferences" -> "New Document/Default Directory" then select "Unix/OSX" under the Format box.

How to create relationships in MySQL

Certain MySQL engines support foreign keys. For example, InnoDB can establish constraints based on foreign keys. If you try to delete an entry in one table that has dependents in another, the delete will fail.

If you are using a table type in MySQL, such as MyISAM, that doesn't support foreign keys, you don't link the tables anywhere except your diagrams and queries.

For example, in a query you link two tables in a select statement with a join:

SELECT a, b from table1 LEFT JOIN table2 USING (common_field);

How to change the sender's name or e-mail address in mutt?

One special case for this is if you have used a construction like the following in your ~/.muttrc:

# Reset From email to default
send-hook . "my_hdr From: Real Name <[email protected]>"

This send-hook will override either of these:

mutt -e "set [email protected]"
mutt -e "my_hdr From: Other Name <[email protected]>"

Your emails will still go out with the header:

From: Real Name <[email protected]>

In this case, the only command line solution I've found is actually overriding the send-hook itself:

mutt -e "send-hook . \"my_hdr From: Other Name <[email protected]>\""

What is the 'instanceof' operator used for in Java?

class Test48{
public static void main (String args[]){
Object Obj=new Hello();
//Hello obj=new Hello;
System.out.println(Obj instanceof String);
System.out.println(Obj instanceof Hello);
System.out.println(Obj instanceof Object);
Hello h=null;
System.out.println(h instanceof Hello);
System.out.println(h instanceof Object);
}
}  

List of strings to one string

I would go with option A:

String.Join(String.Empty, los.ToArray());

My reasoning is because the Join method was written for that purpose. In fact if you look at Reflector, you'll see that unsafe code was used to really optimize it. The other two also WORK, but I think the Join function was written for this purpose, and I would guess, the most efficient. I could be wrong though...

As per @Nuri YILMAZ without .ToArray(), but this is .NET 4+:

String.Join(String.Empty, los);

How to plot time series in python

Convert your x-axis data from text to datetime.datetime, use datetime.strptime:

>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
 datetime.datetime(2012, 5, 31, 19, 0)

This is an example of how to plot data once you have an array of datetimes:

import matplotlib.pyplot as plt
import datetime
import numpy as np

x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)

plt.plot(x,y)
plt.show()

enter image description here

Changing cell color using apache poi

For apache POI 3.9 you can use the code bellow:

HSSFCellStyle style = workbook.createCellStyle()
style.setFillForegroundColor(HSSFColor.YELLOW.index)
style.setFillPattern((short) FillPatternType.SOLID_FOREGROUND.ordinal())

The methods for 3.9 version accept short and you should pay attention to the inputs.

ORACLE convert number to string

This should solve your problem:

select replace(to_char(a, '90D90'),'.00','')
from
(
select 50 a from dual
union
select 50.57 from dual
union
select 5.57 from dual
union
select 0.35 from dual
union
select 0.4 from dual
);

Give a look also as this SQL Fiddle for test.

Check if process returns 0 with batch file

The project I'm working on, we do something like this. We use the errorlevel keyword so it kind of looks like:

call myExe.exe
if errorlevel 1 (
  goto build_fail
)

That seems to work for us. Note that you can put in multiple commands in the parens like an echo or whatever. Also note that build_fail is defined as:

:build_fail
echo ********** BUILD FAILURE **********
exit /b 1

How can I modify a saved Microsoft Access 2007 or 2010 Import Specification?

Below are three functions you can use to alter and use the MS Access 2010 Import Specification. The third sub changes the name of an existing import specification. The second sub allows you to change any xml text in the import spec. This is useful if you need to change column names, data types, add columns, change the import file location, etc.. In essence anything you want modify for an existing spec. The first Sub is a routine that allows you to call an existing import spec, modify it for a specific file you are attempting to import, importing that file, and then deleting the modified spec, keeping the import spec "template" unaltered and intact. Enjoy.

Public Sub MyExcelTransfer(myTempTable As String, myPath As String)
On Error GoTo ERR_Handler:
    Dim mySpec As ImportExportSpecification
    Dim myNewSpec As ImportExportSpecification
    Dim x As Integer

    For x = 0 To CurrentProject.ImportExportSpecifications.Count - 1
    If CurrentProject.ImportExportSpecifications.Item(x).Name = "TemporaryImport" Then
        CurrentProject.ImportExportSpecifications.Item("TemporaryImport").Delete
        x = CurrentProject.ImportExportSpecifications.Count
    End If
    Next x
    Set mySpec = CurrentProject.ImportExportSpecifications.Item(myTempTable)
    CurrentProject.ImportExportSpecifications.Add "TemporaryImport", mySpec.XML
    Set myNewSpec = CurrentProject.ImportExportSpecifications.Item("TemporaryImport")

    myNewSpec.XML = Replace(myNewSpec.XML, "\\MyComputer\ChangeThis", myPath)
    myNewSpec.Execute
    myNewSpec.Delete
    Set mySpec = Nothing
    Set myNewSpec = Nothing
    exit_ErrHandler:
    For x = 0 To CurrentProject.ImportExportSpecifications.Count - 1
    If CurrentProject.ImportExportSpecifications.Item(x).Name = "TemporaryImport" Then
        CurrentProject.ImportExportSpecifications.Item("TemporaryImport").Delete
        x = CurrentProject.ImportExportSpecifications.Count
    End If
    Next x
Exit Sub    
ERR_Handler:
    MsgBox Err.Description
    Resume exit_ErrHandler
End Sub

Public Sub fixImportSpecs(myTable As String, strFind As String, strRepl As String)
    Dim mySpec As ImportExportSpecification    
    Set mySpec = CurrentProject.ImportExportSpecifications.Item(myTable)    
    mySpec.XML = Replace(mySpec.XML, strFind, strRepl)
    Set mySpec = Nothing
End Sub


Public Sub MyExcelChangeName(OldName As String, NewName As String)
    Dim mySpec As ImportExportSpecification
    Dim myNewSpec As ImportExportSpecification
    Set mySpec = CurrentProject.ImportExportSpecifications.Item(OldName)    
    CurrentProject.ImportExportSpecifications.Add NewName, mySpec.XML
    mySpec.Delete
    Set mySpec = Nothing
    Set myNewSpec = Nothing
End Sub

Drag and drop a DLL to the GAC ("assembly") in windows server 2008 .net 4.0

Other alternatives to an installer and gacutil are GUI tools like Gac Manager or GACAdmin. Or if you like PowerShell you could use PowerShell GAC from which I am the author.

how to use math.pi in java

Your diameter variable won't work because you're trying to store a String into a variable that will only accept a double. In order for it to work you will need to parse it

Ex:

diameter = Double.parseDouble(JOptionPane.showInputDialog("enter the diameter of a sphere.");

How to get a time zone from a location using latitude and longitude coordinates?

_x000D_
_x000D_
  function jsonpRequest(url, data)_x000D_
{_x000D_
    let params = "";_x000D_
    for (let key in data)_x000D_
    {_x000D_
        if (data.hasOwnProperty(key))_x000D_
        {_x000D_
            if (params.length == 0)_x000D_
            {_x000D_
                params += "?";_x000D_
            }_x000D_
            else_x000D_
            {_x000D_
                params += "&";_x000D_
            }_x000D_
            let encodedKey = encodeURIComponent(key);_x000D_
            let encodedValue = encodeURIComponent(data[key]);_x000D_
            params += encodedKey + "=" + encodedValue;_x000D_
         }_x000D_
    }_x000D_
    let script = document.createElement('script');_x000D_
    script.src = url + params;_x000D_
    document.body.appendChild(script);_x000D_
}_x000D_
_x000D_
function getLocation() {_x000D_
  if (navigator.geolocation) {_x000D_
    navigator.geolocation.getCurrentPosition(showPosition);_x000D_
  } else {_x000D_
    x.innerHTML = "Geolocation is not supported by this browser.";_x000D_
  }_x000D_
}_x000D_
let lat_ini=[]; let lon_ini=[];_x000D_
function showPosition(position) {_x000D_
  lat_ini= position.coords.latitude;_x000D_
  lon_ini= position.coords.longitude;_x000D_
}_x000D_
////delay time between lines_x000D_
function sleep(ms) {_x000D_
  return new Promise(resolve => setTimeout(resolve, ms));_x000D_
}_x000D_
///////_x000D_
function getGMT()_x000D_
{_x000D_
  getfinalGMT()_x000D_
  getLocation()_x000D_
  async function sample() {_x000D_
    await sleep(2000);_x000D_
let lat_str=lat_ini.toString();_x000D_
let lng_str=" "+lon_ini.toString();_x000D_
_x000D_
  let url = "https://api.opencagedata.com/geocode/v1/json";_x000D_
  let data = {_x000D_
    callback: "displayGMT",_x000D_
    q: lat_str + lng_str,_x000D_
    key: "fac4471073a347019196c1291e6a97d7"_x000D_
  }_x000D_
  jsonpRequest(url, data)_x000D_
}_x000D_
 sample();_x000D_
 }_x000D_
let your_GMT=[];_x000D_
function displayGMT(data)_x000D_
{_x000D_
your_GMT=(Number(data.results[0].annotations.timezone.offset_string))_x000D_
console.log(your_GMT)_x000D_
}_x000D_
/////_x000D_
function getfinalGMT()_x000D_
{_x000D_
let lat=document.getElementById("lat_id").value; let lng=document.getElementById("lng_id").value;_x000D_
let lat_str=lat.toString();_x000D_
let lng_str=" "+lng.toString();_x000D_
_x000D_
  let url = "https://api.opencagedata.com/geocode/v1/json";_x000D_
  let data = {_x000D_
    callback: "displayfinalGMT",_x000D_
    q: lat + lng_str,_x000D_
    key: "fac4471073a347019196c1291e6a97d7"_x000D_
  }_x000D_
  jsonpRequest(url, data)_x000D_
 }_x000D_
let final_GMT=[];_x000D_
function displayfinalGMT(data)_x000D_
{_x000D_
final_GMT=(Number(data.results[0].annotations.timezone.offset_string))_x000D_
console.log(final_GMT)_x000D_
}_x000D_
/////clock_x000D_
_x000D_
_x000D_
const hourHand = document.querySelector('[data-hour-hand]')_x000D_
const minuteHand = document.querySelector('[data-minute-hand]')_x000D_
const secondHand = document.querySelector('[data-second-hand]')_x000D_
  let dif_overall=[];_x000D_
function setClock() {_x000D_
   let gmt_diff=Number(your_GMT-final_GMT)/100_x000D_
   if (gmt_diff>12){_x000D_
      dif_overall=gmt_diff-12_x000D_
   }_x000D_
   else{_x000D_
     dif_overall=gmt_diff_x000D_
   }_x000D_
    console.log(dif_overall)_x000D_
  const currentDate = new Date()_x000D_
  const secondsRatio = currentDate.getSeconds() / 60_x000D_
  const minutesRatio = (secondsRatio + currentDate.getMinutes()) / 60_x000D_
  const hoursRatio = (minutesRatio + currentDate.getHours() - dif_overall ) / 12_x000D_
  setRotation(secondHand, secondsRatio)_x000D_
  setRotation(minuteHand, minutesRatio)_x000D_
  setRotation(hourHand, hoursRatio)_x000D_
}_x000D_
_x000D_
function setRotation(element, rotationRatio) {_x000D_
  element.style.setProperty('--rotation', rotationRatio * 360)_x000D_
}_x000D_
function activate_clock(){_x000D_
setClock()_x000D_
setInterval(setClock, 1000)_x000D_
}
_x000D_
*, *::after, *::before {_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
_x000D_
body {_x000D_
  background: linear-gradient(to right, hsl(200, 100%, 50%), hsl(175, 100%, 50%));_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
  min-height: 100vh;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
.clock {_x000D_
  width: 200px;_x000D_
  height: 200px;_x000D_
  background-color: rgba(255, 255, 255, .8);_x000D_
  border-radius: 50%;_x000D_
  border: 2px solid black;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.clock .number {_x000D_
  --rotation: 0;_x000D_
  position: absolute;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  text-align: center;_x000D_
  transform: rotate(var(--rotation));_x000D_
  font-size: 1.5rem;_x000D_
}_x000D_
_x000D_
.clock .number1 { --rotation: 30deg; }_x000D_
.clock .number2 { --rotation: 60deg; }_x000D_
.clock .number3 { --rotation: 90deg; }_x000D_
.clock .number4 { --rotation: 120deg; }_x000D_
.clock .number5 { --rotation: 150deg; }_x000D_
.clock .number6 { --rotation: 180deg; }_x000D_
.clock .number7 { --rotation: 210deg; }_x000D_
.clock .number8 { --rotation: 240deg; }_x000D_
.clock .number9 { --rotation: 270deg; }_x000D_
.clock .number10 { --rotation: 300deg; }_x000D_
.clock .number11 { --rotation: 330deg; }_x000D_
_x000D_
.clock .hand {_x000D_
  --rotation: 0;_x000D_
  position: absolute;_x000D_
  bottom: 50%;_x000D_
  left: 50%;_x000D_
  border: 1px solid white;_x000D_
  border-top-left-radius: 10px;_x000D_
  border-top-right-radius: 10px;_x000D_
  transform-origin: bottom;_x000D_
  z-index: 10;_x000D_
  transform: translateX(-50%) rotate(calc(var(--rotation) * 1deg));_x000D_
}_x000D_
_x000D_
.clock::after {_x000D_
  content: '';_x000D_
  position: absolute;_x000D_
  background-color: black;_x000D_
  z-index: 11;_x000D_
  width: 15px;_x000D_
  height: 15px;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  transform: translate(-50%, -50%);_x000D_
  border-radius: 50%;_x000D_
}_x000D_
_x000D_
.clock .hand.second {_x000D_
  width: 3px;_x000D_
  height: 45%;_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
.clock .hand.minute {_x000D_
  width: 7px;_x000D_
  height: 40%;_x000D_
  background-color: black;_x000D_
}_x000D_
_x000D_
.clock .hand.hour {_x000D_
  width: 10px;_x000D_
  height: 35%;_x000D_
  background-color: black;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
/* Background Styles Only */_x000D_
_x000D_
@import url('https://fonts.googleapis.com/css?family=Raleway');_x000D_
_x000D_
* {_x000D_
    font-family: Raleway;_x000D_
}_x000D_
_x000D_
.side-links {_x000D_
  position: absolute;_x000D_
  top: 15px;_x000D_
  right: 15px;_x000D_
}_x000D_
_x000D_
.side-link {_x000D_
  display: flex;_x000D_
  align-items: center;_x000D_
  justify-content: center;_x000D_
  text-decoration: none;_x000D_
  margin-bottom: 10px;_x000D_
  color: white;_x000D_
  width: 180px;_x000D_
  padding: 10px 0;_x000D_
  border-radius: 10px;_x000D_
}_x000D_
_x000D_
.side-link-youtube {_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
.side-link-twitter {_x000D_
  background-color: #1DA1F2;_x000D_
}_x000D_
_x000D_
.side-link-github {_x000D_
  background-color: #6e5494;_x000D_
}_x000D_
_x000D_
.side-link-text {_x000D_
  margin-left: 10px;_x000D_
  font-size: 18px;_x000D_
}_x000D_
_x000D_
.side-link-icon {_x000D_
  color: white;_x000D_
  font-size: 30px;_x000D_
}
_x000D_
   <input type="text" id="lat_id" placeholder="lat"><br><br>_x000D_
  <input type="text" id="lng_id" placeholder="lng"><br><br>_x000D_
<button class="text" onClick="getLocation()">Location</button>_x000D_
<button class="text" onClick="getGMT()"> GMT</button>_x000D_
<button class="text" onClick="activate_clock()"> Activate</button>_x000D_
<div class="clock">_x000D_
  <div class="hand hour" data-hour-hand></div>_x000D_
  <div class="hand minute" data-minute-hand></div>_x000D_
  <div class="hand second" data-second-hand></div>_x000D_
  <div class="number number1">1</div>_x000D_
  <div class="number number2">2</div>_x000D_
  <div class="number number3">3</div>_x000D_
  <div class="number number4">4</div>_x000D_
  <div class="number number5">5</div>_x000D_
  <div class="number number6">6</div>_x000D_
  <div class="number number7">7</div>_x000D_
  <div class="number number8">8</div>_x000D_
  <div class="number number9">9</div>_x000D_
  <div class="number number10">10</div>_x000D_
  <div class="number number11">11</div>_x000D_
  <div class="number number12">12</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Ordering issue with date values when creating pivot tables

Your problem is that excel does not recognize your text strings of "mm/dd/yyyy" as date objects in it's internal memory. Therefore when you create pivottable it doesn't consider these strings to be dates.

You'll need to first convert your dates to actual date values before creating the pivottable. This is a good resource for that: http://office.microsoft.com/en-us/excel-help/convert-dates-stored-as-text-to-dates-HP001162867.aspx

In your spreadsheet I created a second date column in B with the formula =DATEVALUE(A2). Creating a pivot table with this new date column and Count of Sales then sorts correctly in the pivot table (option becomes Sort Oldest to Newest instead of Sort A to Z).

Powershell folder size of folders without listing Subdirectories

My proposal:

$dir="C:\temp\"
get-childitem $dir -file -Rec | group Directory | where Name -eq $dir | select Name, @{N='Size';E={(($_.Group.Length | measure -Sum).Sum / 1MB)}}

How can I generate a random number in a certain range?

Random r = new Random();
int i1 = r.nextInt(45 - 28) + 28;

This gives a random integer between 28 (inclusive) and 45 (exclusive), one of 28,29,...,43,44.

Dark theme in Netbeans 7 or 8

And then there is the original plugin ez-on-da-ice. Better yet, you can complain to me directly if there are issues. I promise you, I am mostly very responsive :).

http://plugins.netbeans.org/plugin/40985/ez-on-da-ice

enter image description here

How to solve the system.data.sqlclient.sqlexception (0x80131904) error

The datasource is by default .\SQLEXPRESS (its the instance where databases are placed by default) or if u changed the name of the instance during installation of sql server so i advise you to do this :

connectionString="Data Source=.\\yourInstance(defaulT Data source is SQLEXPRESS);
       Initial Catalog=databaseName;
       User ID=theuser if u use it;
       Password=thepassword if u use it;
       integrated security=true(if u don t use user and pass; else change it false)"

Without to knowing your instance, I could help with this one. Hope it helped

Is it possible to run one logrotate check manually?

Created a shell script to solve the problem.

https://antofthy.gitlab.io/software/#logrotate_one

This script will run just the single logrotate sub-configuration file found in "/etc/logrotate.d", but include the global settings from in the global configuration file "/etc/logrotate.conf". You can also use other otpions for testing it...

For example...

  logrotate_one -d syslog

How to choose multiple files using File Upload Control?

To add multiple files use below code

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
    .fileUpload{
    width:255px;    
    font-size:11px;
    color:#000000;
    border:solid;
    border-width:1px;
    border-color:#7f9db9;    
    height:17px;
    }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <div id="fileUploadarea"><asp:FileUpload ID="fuPuzzleImage" runat="server" CssClass="fileUpload" /><br /></div><br />
    <div><input style="display:block;" id="btnAddMoreFiles" type="button" value="Add more images" onclick="AddMoreImages();" /><br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Upload" />
        </div>
    </div>
    <script language="javascript" type="text/javascript">
        function AddMoreImages() {
            if (!document.getElementById && !document.createElement)
                return false;
            var fileUploadarea = document.getElementById("fileUploadarea");
            if (!fileUploadarea)
                return false;
            var newLine = document.createElement("br");
            fileUploadarea.appendChild(newLine);
            var newFile = document.createElement("input");
            newFile.type = "file";
            newFile.setAttribute("class", "fileUpload");

            if (!AddMoreImages.lastAssignedId)
                AddMoreImages.lastAssignedId = 100;
            newFile.setAttribute("id", "FileUpload" + AddMoreImages.lastAssignedId);
            newFile.setAttribute("name", "FileUpload" + AddMoreImages.lastAssignedId);
            var div = document.createElement("div");
            div.appendChild(newFile);
            div.setAttribute("id", "div" + AddMoreImages.lastAssignedId);
            fileUploadarea.appendChild(div);
            AddMoreImages.lastAssignedId++;
        }

    </script>
    </form>
</body>
</html>

Server side code:

try
{
    HttpFileCollection hfc = Request.Files;
    for (int i = 0; i < hfc.Count; i++)
    {
        HttpPostedFile hpf = hfc[i];
        if (hpf.ContentLength > 0)
        {                        
            hpf.SaveAs(Server.MapPath("~/uploads/") +System.IO.Path.GetFileName(hpf.FileName);                        
        }
    }
}
catch (Exception)
{
    throw;
}

Bring element to front using CSS

Add z-index:-1 and position:relative to .content

_x000D_
_x000D_
#header {_x000D_
    background: url(http://placehold.it/420x160) center top no-repeat;_x000D_
}_x000D_
#header-inner {_x000D_
    background: url(http://placekitten.com/150/200) right top no-repeat;_x000D_
}_x000D_
.logo-class {_x000D_
    height: 128px;_x000D_
}_x000D_
.content {_x000D_
    margin-left: auto;_x000D_
    margin-right: auto;_x000D_
    table-layout: fixed;_x000D_
    border-collapse: collapse;_x000D_
    z-index: -1;_x000D_
    position:relative;_x000D_
}_x000D_
.td-main {_x000D_
    text-align: center;_x000D_
    padding: 80px 10px 80px 10px;_x000D_
    border: 1px solid #A02422;_x000D_
    background: #ABABAB;_x000D_
}
_x000D_
<body>_x000D_
    <div id="header">_x000D_
        <div id="header-inner">_x000D_
            <table class="content">_x000D_
                <col width="400px" />_x000D_
                <tr>_x000D_
                    <td>_x000D_
                        <table class="content">_x000D_
                            <col width="400px" />_x000D_
                            <tr>_x000D_
                                <td>_x000D_
                                    <div class="logo-class"></div>_x000D_
                                </td>_x000D_
                            </tr>_x000D_
                            <tr>_x000D_
                                <td id="menu"></td>_x000D_
                            </tr>_x000D_
                        </table>_x000D_
                        <table class="content">_x000D_
                            <col width="120px" />_x000D_
                            <col width="160px" />_x000D_
                            <col width="120px" />_x000D_
                            <tr>_x000D_
                                <td class="td-main">text</td>_x000D_
                                <td class="td-main">text</td>_x000D_
                                <td class="td-main">text</td>_x000D_
                            </tr>_x000D_
                        </table>_x000D_
                    </td>_x000D_
                </tr>_x000D_
            </table>_x000D_
        </div>_x000D_
        <!-- header-inner -->_x000D_
    </div>_x000D_
    <!-- header -->_x000D_
</body>
_x000D_
_x000D_
_x000D_

VirtualBox error "Failed to open a session for the virtual machine"

Something that I tried and work for me is simply you create a new virtual machine and you use the existing virtual hard disk file and everything is like you left it.

How comment a JSP expression?

One of:

In html

<!-- map.size here because --> 
<%= map.size() %>

theoretically the following should work, but i never used it this way.

<%= map.size() // map.size here because %>

Add all files to a commit except a single file?

1) To start ignoring changes to a single already versioned file

git update-index --assume-unchanged "main/dontcheckmein.txt"

and to undo that git update-index --no-assume-unchanged "main/dontcheckmein.txt"

github docs to ignore files

2) To completely ignore a specific single file preventing it from being created at repository

First, look at this stackoverflow post: Git global ignore not working

In .gitignore, add the relative path to the file without leading ./.

So, if your file is at MyProject/MyFolder/myfile.txt, (where .git is also in the MyProject folder), add MyFolder/myfile.txt to your at .gitignore file.

You can confirm what rules are associated with ignore via git check-ignore "MyFolder/myfile.txt"

About global ignore

That link talks about ~/.gitignore_global, but the file is related to your project. So, if you put the exclude pattern MyFolder/myfile.txt in ~/.gitignore_global, it will work but will not make much sense...

On the other hand, if you setup your project with git config core.excludesfile .gitignore where .gitignore is in MyProject, the local file will override ~/.gitignore_global, which can have very useful rules...

So, for now, I think it's best to make some script to mix your .gitignore with ~/.gitignore_global at .gitignore.

One last warning
If the file you want to ignore is already in the repository, this method will not work unless you do this: git rm "MyFolder/myfile.txt", but back it up first, as it will be removed locally also! You can copy it back later...

Possible to perform cross-database queries with PostgreSQL?

dblink() -- executes a query in a remote database

dblink executes a query (usually a SELECT, but it can be any SQL statement that returns rows) in a remote database.

When two text arguments are given, the first one is first looked up as a persistent connection's name; if found, the command is executed on that connection. If not found, the first argument is treated as a connection info string as for dblink_connect, and the indicated connection is made just for the duration of this command.

one of the good example:

SELECT * 
FROM   table1 tb1 
LEFT   JOIN (
   SELECT *
   FROM   dblink('dbname=db2','SELECT id, code FROM table2')
   AS     tb2(id int, code text);
) AS tb2 ON tb2.column = tb1.column;

Note: I am giving this information for future reference. Refrence

Disable button in angular with two conditions?

Using the ternary operator is possible like following.[disabled] internally required true or false for its operation.

<button type="button" 
  [disabled]="(testVariable1 != 0 || testVariable2!=0)? true:false"
  mat-button>Button</button>

Android get image from gallery into ImageView

Simple pass Intent first:

Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);

And you will get picture path on your onActivityResult:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            ImageView imageView = (ImageView) findViewById(R.id.imgView);
            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
        }
    }

for full source code here

How to run the Python program forever?

How about this one?

import signal
signal.pause()

This will let your program sleep until it receives a signal from some other process (or itself, in another thread), letting it know it is time to do something.

Find Facebook user (url to profile page) by known email address

In response to the bug filed here: http://developers.facebook.com/bugs/167188686695750 a Facebook engineer replied:

This is by design, searching for users is intended to be a user to user function only, for use in finding new friends or searching by email to find existing contacts on Facebook. The "scraping" mentioned on StackOverflow is specifically against our Terms of Service https://www.facebook.com/terms.php and in fact the only legitimate way to search for users on Facebook is when you are a user.

Class Not Found: Empty Test Suite in IntelliJ

This can happen (at least once for me ;) after installing the new version of IntelliJ and the IntelliJ plugins have not yet updated.

You may have to manually do the Check for updates… from IntelliJ Help menu.

iterating through json object javascript

Here is my recursive approach:

function visit(object) {
    if (isIterable(object)) {
        forEachIn(object, function (accessor, child) {
            visit(child);
        });
    }
    else {
        var value = object;
        console.log(value);
    }
}

function forEachIn(iterable, functionRef) {
    for (var accessor in iterable) {
        functionRef(accessor, iterable[accessor]);
    }
}

function isIterable(element) {
    return isArray(element) || isObject(element);
}

function isArray(element) {
    return element.constructor == Array;
}

function isObject(element) {
    return element.constructor == Object;
}

How to get parameters from the URL with JSP

www.somesite.com/Transaction_List.jsp?accountID=5

For this URL there is a method call request.getParameter in java , if you want a number here cast into int, similarly for string value cast into string. so for your requirement , just copy past below line in page,

int  accountId =(int)request.getParameter("accountID");

you can now call this value useing accountId in whole page.

here accountId is name of parameter you can also get more than one parameters using this, but this not work. It will only work with GET method if you hit POST request then their will be an error.

Hope this is helpful.

Getting Lat/Lng from Google marker

// show the marker position //

console.log( objMarker.position.lat() );
console.log( objMarker.position.lng() );

// create a new point based into marker position //

var deltaLat = 1.002;
var deltaLng = -1.003;

var objPoint = new google.maps.LatLng( 
  parseFloat( objMarker.position.lat() ) + deltaLat, 
  parseFloat( objMarker.position.lng() ) + deltaLng
);

// now center the map using the new point //

objMap.setCenter( objPoint );

Convert factor to integer

You can combine the two functions; coerce to characters thence to numerics:

> fac <- factor(c("1","2","1","2"))
> as.numeric(as.character(fac))
[1] 1 2 1 2

HTTP Status 405 - Request method 'POST' not supported (Spring MVC)

Check if you are returning a @ResponseBody or a @ResponseStatus

I had a similar problem. My Controller looked like that:

@RequestMapping(value="/user", method = RequestMethod.POST)
public String updateUser(@RequestBody User user){
    return userService.updateUser(user).getId();
}

When calling with a POST request I always got the following error:

HTTP Status 405 - Request method 'POST' not supported

After a while I figured out that the method was actually called, but because there is no @ResponseBody and no @ResponseStatus Spring MVC raises the error.

To fix this simply add a @ResponseBody

@RequestMapping(value="/user", method = RequestMethod.POST)
public @ResponseBody String updateUser(@RequestBody User user){
    return userService.updateUser(user).getId();
}

or a @ResponseStatus to your method.

@RequestMapping(value="/user", method = RequestMethod.POST)
@ResponseStatus(value=HttpStatus.OK)
public String updateUser(@RequestBody User user){
    return userService.updateUser(user).getId();
}

Find and Replace string in all files recursive using grep and sed

grep -rl SOSTITUTETHIS . | xargs sed -Ei 's/(.*)SOSTITUTETHIS(.*)/\1WITHTHIS\2/g'

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value

If you have a column that is datetime and allows null you will get this error. I recommend setting a value to pass to the object before .SaveChanges();

get current date from [NSDate date] but set the time to 10:00 am

I just set the timezone with Matthias Bauch answer And it worked for me. else it was adding 18:30 min more.

let cal: NSCalendar = NSCalendar.currentCalendar()
cal.timeZone = NSTimeZone(forSecondsFromGMT: 0)
let newDate: NSDate = cal.dateBySettingHour(1, minute: 0, second: 0, ofDate: NSDate(), options: NSCalendarOptions())!

How to use bootstrap datepicker

Just add this below JS file

<script type="text/javascript">
    $(document).ready(function () {
        $('your input's id or class with # or .').datepicker({
            format: "dd/mm/yyyy"
        });
    });
</script>

Difference between FetchType LAZY and EAGER in Java Persistence API?

Sometimes you have two entities and there's a relationship between them. For example, you might have an entity called University and another entity called Student and a University might have many Students:

The University entity might have some basic properties such as id, name, address, etc. as well as a collection property called students that returns the list of students for a given university:

A university has many students

public class University {
   private String id;
   private String name;
   private String address;
   private List<Student> students;

   // setters and getters
}

Now when you load a University from the database, JPA loads its id, name, and address fields for you. But you have two options for how students should be loaded:

  1. To load it together with the rest of the fields (i.e. eagerly), or
  2. To load it on-demand (i.e. lazily) when you call the university's getStudents() method.

When a university has many students it is not efficient to load all of its students together with it, especially when they are not needed and in suchlike cases you can declare that you want students to be loaded when they are actually needed. This is called lazy loading.

Here's an example, where students is explicitly marked to be loaded eagerly:

@Entity
public class University {

    @Id
    private String id;

    private String name;

    private String address;

    @OneToMany(fetch = FetchType.EAGER)
    private List<Student> students;

    // etc.    
}

And here's an example where students is explicitly marked to be loaded lazily:

@Entity
public class University {

    @Id
    private String id;

    private String name;

    private String address;

    @OneToMany(fetch = FetchType.LAZY)
    private List<Student> students;

    // etc.
}

Best way to check for IE less than 9 in JavaScript without library

You could do it in a quick and dirty fashion with a regular expression and .match():

if (navigator.userAgent.match(/MSIE\s(?!9.0)/)) {
    // ie less than version 9
}

how to add script src inside a View when using Layout

If you are using Razor view engine then edit the _Layout.cshtml file. Move the @Scripts.Render("~/bundles/jquery") present in footer to the header section and write the javascript / jquery code as you want:

@Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
    $(document).ready(function () {
        var divLength = $('div').length;
        alert(divLength);
    });
</script>

Add custom icons to font awesome

Give Icomoon a try. You can upload your own SVGs, add them to the library, then create a custom font combining FontAwesome with your own icons.

Check if element found in array c++

You can use old C-style programming to do the job. This will require little knowledge about C++. Good for beginners.

For modern C++ language you usually accomplish this through lambda, function objects, ... or algorithm: find, find_if, any_of, for_each, or the new for (auto& v : container) { } syntax. find class algorithm takes more lines of code. You may also write you own template find function for your particular need.

Here is my sample code

#include <iostream>
#include <functional>
#include <algorithm>
#include <vector>

using namespace std;

/**
 * This is old C-like style.  It is mostly gong from 
 * modern C++ programming.  You can still use this
 * since you need to know very little about C++.
 * @param storeSize you have to know the size of store
 *    How many elements are in the array.
 * @return the index of the element in the array,
 *   if not found return -1
 */
int in_array(const int store[], const int storeSize, const int query) {
   for (size_t i=0; i<storeSize; ++i) {
      if (store[i] == query) {
         return i;
      }
   }
   return -1;
}

void testfind() {
   int iarr[] = { 3, 6, 8, 33, 77, 63, 7, 11 };

   // for beginners, it is good to practice a looping method
   int query = 7;
   if (in_array(iarr, 8, query) != -1) {
      cout << query << " is in the array\n";
   }

   // using vector or list, ... any container in C++
   vector<int> vecint{ 3, 6, 8, 33, 77, 63, 7, 11 };
   auto it=find(vecint.begin(), vecint.end(), query);
   cout << "using find()\n";
   if (it != vecint.end()) {
      cout << "found " << query << " in the container\n";
   }
   else {
      cout << "your query: " << query << " is not inside the container\n";
   }

   using namespace std::placeholders;
   // here the query variable is bound to the `equal_to` function 
   // object (defined in std)
   cout << "using any_of\n";
   if (any_of(vecint.begin(), vecint.end(), bind(equal_to<int>(), _1, query))) {
      cout << "found " << query << " in the container\n";
   }
   else {
      cout << "your query: " << query << " is not inside the container\n";
   }

   // using lambda, here I am capturing the query variable
   // into the lambda function
   cout << "using any_of with lambda:\n";
   if (any_of(vecint.begin(), vecint.end(),
            [query](int val)->bool{ return val==query; })) {
      cout << "found " << query << " in the container\n";
   }
   else {
      cout << "your query: " << query << " is not inside the container\n";
   }
}

int main(int argc, char* argv[]) {
   testfind();

   return 0;
}

Say this file is named 'testalgorithm.cpp' you need to compile it with

g++ -std=c++11 -o testalgorithm testalgorithm.cpp

Hope this will help. Please update or add if I have made any mistake.

How to keep a git branch in sync with master

concept47's approach is the right way to do it, but I'd advise to merge with the --no-ff option in order to keep your commit history clear.

git checkout develop
git pull --rebase
git checkout NewFeatureBranch
git merge --no-ff master

How to Pass data from child to parent component Angular

Hello you can make use of input and output. Input let you to pass variable form parent to child. Output the same but from child to parent.

The easiest way is to pass "startdate" and "endDate" as input

<calendar [startDateInCalendar]="startDateInSearch" [endDateInCalendar]="endDateInSearch" ></calendar>

In this way you have your startdate and enddate directly in search page. Let me know if it works, or think another way. Thanks

Erasing elements from a vector

To erase 1st element you can use:

vector<int> mV{ 1, 2, 3, 4, 5 }; 
vector<int>::iterator it; 

it = mV.begin(); 
mV.erase(it); 

Set date input field's max date to today

it can be useful : If you want to do it with Symfony forms :

 $today = new DateTime('now');
 $formBuilder->add('startDate', DateType::class, array(
                   'widget' => 'single_text',
                   'data'   => new \DateTime(),
                   'attr'   => ['min' => $today->format('Y-m-d')]
                   ));

ModelState.IsValid == false, why?

Sometimes a binder throwns an exception with no error message. You can retrieve the exception with the following snippet to find out whats wrong:

(Often if the binder is trying to convert strings to complex types etc)

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

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

  }

Cannot open include file 'afxres.h' in VC2010 Express

Had similar issue but the message was shown when I tried to open a project solution. What worked for me was:

TOOLS -> Import and Export Settings...-> Reset all settings

How to select rows with one or more nulls from a pandas DataFrame without listing columns explicitly?

.any() and .all() are great for the extreme cases, but not when you're looking for a specific number of null values. Here's an extremely simple way to do what I believe you're asking. It's pretty verbose, but functional.

import pandas as pd
import numpy as np

# Some test data frame
df = pd.DataFrame({'num_legs':          [2, 4,      np.nan, 0, np.nan],
                   'num_wings':         [2, 0,      np.nan, 0, 9],
                   'num_specimen_seen': [10, np.nan, 1,     8, np.nan]})

# Helper : Gets NaNs for some row
def row_nan_sums(df):
    sums = []
    for row in df.values:
        sum = 0
        for el in row:
            if el != el: # np.nan is never equal to itself. This is "hacky", but complete.
                sum+=1
        sums.append(sum)
    return sums

# Returns a list of indices for rows with k+ NaNs
def query_k_plus_sums(df, k):
    sums = row_nan_sums(df)
    indices = []
    i = 0
    for sum in sums:
        if (sum >= k):
            indices.append(i)
        i += 1
    return indices

# test
print(df)
print(query_k_plus_sums(df, 2))

Output

   num_legs  num_wings  num_specimen_seen
0       2.0        2.0               10.0
1       4.0        0.0                NaN
2       NaN        NaN                1.0
3       0.0        0.0                8.0
4       NaN        9.0                NaN
[2, 4]

Then, if you're like me and want to clear those rows out, you just write this:

# drop the rows from the data frame
df.drop(query_k_plus_sums(df, 2),inplace=True)
# Reshuffle up data (if you don't do this, the indices won't reset)
df = df.sample(frac=1).reset_index(drop=True)
# print data frame
print(df)

Output:

   num_legs  num_wings  num_specimen_seen
0       4.0        0.0                NaN
1       0.0        0.0                8.0
2       2.0        2.0               10.0

PostgreSQL - max number of parameters in "IN" clause?

This is not really an answer to the present question, however it might help others too.

At least I can tell there is a technical limit of 32767 values (=Short.MAX_VALUE) passable to the PostgreSQL backend, using Posgresql's JDBC driver 9.1.

This is a test of "delete from x where id in (... 100k values...)" with the postgresql jdbc driver:

Caused by: java.io.IOException: Tried to send an out-of-range integer as a 2-byte value: 100000
    at org.postgresql.core.PGStream.SendInteger2(PGStream.java:201)

Where is the application.properties file in a Spring Boot project?

Spring Boot will automatically find and load application.properties and application.yaml files from the following locations when your application starts:

  1. The classpath root
  2. The classpath /config package
  3. The current directory
  4. The /config subdirectory in the current directory
  5. Immediate child directories of the /config subdirectory

The list is ordered by precedence (with values from lower items overriding earlier ones).

More info you can find here https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config-files

Parse date string and change format

As this question comes often, here is the simple explanation.

datetime or time module has two important functions.

  • strftime - creates a string representation of date or time from a datetime or time object.
  • strptime - creates a datetime or time object from a string.

In both cases, we need a formating string. It is the representation that tells how the date or time is formatted in your string.

Now lets assume we have a date object.

>>> from datetime import datetime
>>> d = datetime(2010, 2, 15)
>>> d
datetime.datetime(2010, 2, 15, 0, 0)

If we want to create a string from this date in the format 'Mon Feb 15 2010'

>>> s = d.strftime('%a %b %d %y')
>>> print s
Mon Feb 15 10

Lets assume we want to convert this s again to a datetime object.

>>> new_date = datetime.strptime(s, '%a %b %d %y')
>>> print new_date
2010-02-15 00:00:00

Refer This document all formatting directives regarding datetime.

How do I remove a property from a JavaScript object?

Property Removal in JavaScript

There are many different options presented on this page, not because most of the options are wrong—or because the answers are duplicates—but because the appropriate technique depends on the situation you're in and the goals of the tasks you and/or you team are trying to fulfill. To answer you question unequivocally, one needs to know:

  1. The version of ECMAScript you're targeting
  2. The range of object types you want to remove properties on and the type of property names you need to be able to omit (Strings only? Symbols? Weak references mapped from arbitrary objects? These have all been types of property pointers in JavaScript for years now)
  3. The programming ethos/patterns you and your team use. Do you favor functional approaches and mutation is verboten on your team, or do you employ wild west mutative object-oriented techniques?
  4. Are you looking to achieve this in pure JavaScript or are you willing & able to use a 3rd-party library?

Once those four queries have been answered, there are essentially four categories of "property removal" in JavaScript to chose from in order to meet your goals. They are:

Mutative object property deletion, unsafe

This category is for operating on object literals or object instances when you want to retain/continue to use the original reference and aren't using stateless functional principles in your code. An example piece of syntax in this category:

'use strict'
const iLikeMutatingStuffDontI = { myNameIs: 'KIDDDDD!', [Symbol.for('amICool')]: true }
delete iLikeMutatingStuffDontI[Symbol.for('amICool')] // true
Object.defineProperty({ myNameIs: 'KIDDDDD!', 'amICool', { value: true, configurable: false })
delete iLikeMutatingStuffDontI['amICool'] // throws

This category is the oldest, most straightforward & most widely supported category of property removal. It supports Symbol & array indexes in addition to strings and works in every version of JavaScript except for the very first release. However, it's mutative which violates some programming principles and has performance implications. It also can result in uncaught exceptions when used on non-configurable properties in strict mode.

Rest-based string property omission

This category is for operating on plain object or array instances in newer ECMAScript flavors when a non-mutative approach is desired and you don't need to account for Symbol keys:

const foo = { name: 'KIDDDDD!', [Symbol.for('isCool')]: true }
const { name, ...coolio } = foo // coolio doesn't have "name"
const { isCool, ...coolio2 } = foo // coolio2 has everything from `foo` because `isCool` doesn't account for Symbols :(

Mutative object property deletion, safe

This category is for operating on object literals or object instances when you want to retain/continue to use the original reference while guarding against exceptions being thrown on unconfigurable properties:

'use strict'
const iLikeMutatingStuffDontI = { myNameIs: 'KIDDDDD!', [Symbol.for('amICool')]: true }
Reflect.deleteProperty(iLikeMutatingStuffDontI, Symbol.for('amICool')) // true
Object.defineProperty({ myNameIs: 'KIDDDDD!', 'amICool', { value: true, configurable: false })
Reflect.deleteProperty(iLikeMutatingStuffDontI, 'amICool') // false

In addition, while mutating objects in-place isn't stateless, you can use the functional nature of Reflect.deleteProperty to do partial application and other functional techniques that aren't possible with delete statements.

Syntax-based string property omission

This category is for operating on plain object or array instances in newer ECMAScript flavors when a non-mutative approach is desired and you don't need to account for Symbol keys:

const foo = { name: 'KIDDDDD!', [Symbol.for('isCool')]: true }
const { name, ...coolio } = foo // coolio doesn't have "name"
const { isCool, ...coolio2 } = foo // coolio2 has everything from `foo` because `isCool` doesn't account for Symbols :(

Library-based property omission

This category is generally allows for greater functional flexibility, including accounting for Symbols & omitting more than one property in one statement:

const o = require("lodash.omit")
const foo = { [Symbol.for('a')]: 'abc', b: 'b', c: 'c' }
const bar = o(foo, 'a') // "'a' undefined"
const baz = o(foo, [ Symbol.for('a'), 'b' ]) // Symbol supported, more than one prop at a time, "Symbol.for('a') undefined"

Using a cursor with dynamic SQL in a stored procedure

this code can be useful for you.

example of cursor use in sql server

DECLARE sampleCursor CURSOR FOR 
      SELECT K.Id FROM TableA K WHERE ....;
OPEN sampleCursor
FETCH NEXT FROM sampleCursor INTO @Id
WHILE @@FETCH_STATUS <> -1
BEGIN

UPDATE TableB
   SET 
      ...

JComboBox Selection Change Listener?

I would try the itemStateChanged() method of the ItemListener interface if jodonnell's solution fails.

How to generate a HTML page dynamically using PHP?

Just in case someone wants to generate/create actual HTML file...

$myFile = "filename.html"; // or .php   
$fh = fopen($myFile, 'w'); // or die("error");  
$stringData = "your html code php code goes here";   
fwrite($fh, $stringData);
fclose($fh);

Enjoy!

Windows equivalent to UNIX pwd

This prints it in the console:

echo %cd%

or paste this command in CMD, then you'll have pwd:

(echo @echo off
echo echo ^%cd^%) > C:\WINDOWS\pwd.bat

localhost refused to connect Error in visual studio

I had to add https bindings in my local IIS

Google Chrome form autofill and its yellow background

<input type="text" name="foo" autocomplete="off" />

Similar Question: Link

Determine command line working directory when running node bin script

Here's what worked for me:

console.log(process.mainModule.filename);

GROUP BY to combine/concat a column

SELECT
     [User], Activity,
     STUFF(
         (SELECT DISTINCT ',' + PageURL
          FROM TableName
          WHERE [User] = a.[User] AND Activity = a.Activity
          FOR XML PATH (''))
          , 1, 1, '')  AS URLList
FROM TableName AS a
GROUP BY [User], Activity

Get the short Git version hash

You can do just about any format you want with --pretty=format:

git log -1 --pretty=format:%h 

how to select first N rows from a table in T-SQL?

You can also use rowcount, but TOP is probably better and cleaner, hence the upvote for Mehrdad

SET ROWCOUNT 10
SELECT * FROM dbo.Orders
WHERE EmployeeID = 5
ORDER BY OrderDate

SET ROWCOUNT 0

How do I convert a double into a string in C++?

Normaly for this operations you have to use the ecvt, fcvt or gcvt Functions:

/* gcvt example */
#include <stdio.h>
#include <stdlib.h>

main ()
{
  char buffer [20];
  gcvt (1365.249,6,buffer);
  puts (buffer);
  gcvt (1365.249,3,buffer);
  puts (buffer);
  return 0;
}

Output:
1365.25
1.37e+003   

As a Function:

void double_to_char(double f,char * buffer){
  gcvt(f,10,buffer);
}

JavaScript adding decimal numbers issue

Use toFixed to convert it to a string with some decimal places shaved off, and then convert it back to a number.

+(0.1 + 0.2).toFixed(12) // 0.3

It looks like IE's toFixed has some weird behavior, so if you need to support IE something like this might be better:

Math.round((0.1 + 0.2) * 1e12) / 1e12

Pure JavaScript Send POST Data Without a Form

You can use XMLHttpRequest, fetch API, ...

If you want to use XMLHttpRequest you can do the following

var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
    name: "Deska",
    email: "[email protected]",
    phone: "342234553"
 }));
xhr.onload = function() {
    var data = JSON.parse(this.responseText);
    console.log(data);
};

Or if you want to use fetch API

fetch(url, {
    method:"POST",
    body: JSON.stringify({
        name: "Deska",
        email: "[email protected]",
        phone: "342234553"
        })
    })
    .then(result => {
        // do something with the result
        console.log("Completed with result:", result);
    });

"Connection for controluser as defined in your configuration failed" with phpMyAdmin in XAMPP

on ubuntu 18.04 in etc/phpmyadmin/config.inc.php comment all the block

Optional: User for advanced features

destination path already exists and is not an empty directory

This error comes up when you try to clone a repository in a folder which still contains .git folder (Hidden folder).

If the earlier answers doesn't work then you can proceed with my answer. Hope it will solve your issue.

Open terminal & change the directory to the destination folder (where you want to clone).

Now type: ls -a

You may see a folder named .git.

You have to remove that folder by the following command: rm -rf .git

Now you are ready to clone your project.

How to remove focus border (outline) around text/input boxes? (Chrome)

this remove orange frame in chrome from all and any element no matter what and where is it

*:focus {
    outline: none;
}

How to set user environment variables in Windows Server 2008 R2 as a normal user?

Under "Start" enter "environment" in the search field. That will list the option to change the system variables directly in the start menu.

Codeigniter LIKE with wildcard(%)

$this->db->like()

This method enables you to generate LIKE clauses, useful for doing searches.

$this->db->like('title', 'match');

Produces: WHERE title LIKE '%match%'

If you want to control where the wildcard (%) is placed, you can use an optional third argument. Your options are ‘before’, ‘after’, ‘none’ and ‘both’ (which is the default).

$this->db->like('title', 'match', 'before');

Produces: WHERE title LIKE '%match'

$this->db->like('title', 'match', 'after');

Produces: WHERE title LIKE 'match%'

$this->db->like('title', 'match', 'none');

Produces: WHERE title LIKE 'match'

$this->db->like('title', 'match', 'both');

Produces: WHERE title LIKE '%match%'

how to empty recyclebin through command prompt?

I know I'm a little late to the party, but I thought I might contribute my subjectively more graceful solution.

I was looking for a script that would empty the Recycle Bin with an API call, rather than crudely deleting all files and folders from the filesystem. Having failed in my attempts to RecycleBinObject.InvokeVerb("Empty Recycle &Bin") (which apparently only works in XP or older), I stumbled upon discussions of using a function embedded in shell32.dll called SHEmptyRecycleBin() from a compiled language. I thought, hey, I can do that in PowerShell and wrap it in a batch script hybrid.

Save this with a .bat extension and run it to empty your Recycle Bin. Run it with a /y switch to skip the confirmation.

<# : batch portion (begins PowerShell multi-line comment block)
:: empty.bat -- http://stackoverflow.com/a/41195176/1683264

@echo off & setlocal

if /i "%~1"=="/y" goto empty

choice /n /m "Are you sure you want to empty the Recycle Bin? [y/n] "
if not errorlevel 2 goto empty
goto :EOF

:empty
powershell -noprofile "iex (${%~f0} | out-string)" && (
    echo Recycle Bin successfully emptied.
)
goto :EOF

: end batch / begin PowerShell chimera #>
Add-Type shell32 @'
    [DllImport("shell32.dll")]
    public static extern int SHEmptyRecycleBin(IntPtr hwnd, string pszRootPath,
        int dwFlags);
'@ -Namespace System

$SHERB_NOCONFIRMATION = 0x1
$SHERB_NOPROGRESSUI = 0x2
$SHERB_NOSOUND = 0x4

$dwFlags = $SHERB_NOCONFIRMATION
$res = [shell32]::SHEmptyRecycleBin([IntPtr]::Zero, $null, $dwFlags)

if ($res) { "Error 0x{0:x8}: {1}" -f $res,`
    (New-Object ComponentModel.Win32Exception($res)).Message }
exit $res

Here's a more complex version which first invokes SHQueryRecycleBin() to determine whether the bin is already empty prior to invoking SHEmptyRecycleBin(). For this one, I got rid of the choice confirmation and /y switch.

<# : batch portion (begins PowerShell multi-line comment block)
:: empty.bat -- http://stackoverflow.com/a/41195176/1683264

@echo off & setlocal
powershell -noprofile "iex (${%~f0} | out-string)"
goto :EOF

: end batch / begin PowerShell chimera #>
Add-Type @'

using System;
using System.Runtime.InteropServices;

namespace shell32 {
    public struct SHQUERYRBINFO {
        public Int32 cbSize; public UInt64 i64Size; public UInt64 i64NumItems;
    };

    public static class dll {
        [DllImport("shell32.dll")]
        public static extern int SHQueryRecycleBin(string pszRootPath,
            out SHQUERYRBINFO pSHQueryRBInfo);

        [DllImport("shell32.dll")]
        public static extern int SHEmptyRecycleBin(IntPtr hwnd, string pszRootPath,
            int dwFlags);
    }
}
'@

$rb = new-object shell32.SHQUERYRBINFO

# for Win 10 / PowerShell v5
try { $rb.cbSize = [Runtime.InteropServices.Marshal]::SizeOf($rb) }
# for Win 7 / PowerShell v2
catch { $rb.cbSize = [Runtime.InteropServices.Marshal]::SizeOf($rb.GetType()) }

[void][shell32.dll]::SHQueryRecycleBin($null, [ref]$rb)
"Current size of Recycle Bin: {0:N0} bytes" -f $rb.i64Size
"Recycle Bin contains {0:N0} item{1}." -f $rb.i64NumItems, ("s" * ($rb.i64NumItems -ne 1))

if (-not $rb.i64NumItems) { exit 0 }

$dwFlags = @{
    "SHERB_NOCONFIRMATION" = 0x1
    "SHERB_NOPROGRESSUI" = 0x2
    "SHERB_NOSOUND" = 0x4
}
$flags = $dwFlags.SHERB_NOCONFIRMATION
$res = [shell32.dll]::SHEmptyRecycleBin([IntPtr]::Zero, $null, $flags)

if ($res) { 
    write-host -f yellow ("Error 0x{0:x8}: {1}" -f $res,`
        (New-Object ComponentModel.Win32Exception($res)).Message)
} else {
    write-host "Recycle Bin successfully emptied." -f green
}
exit $res

fatal: Not a valid object name: 'master'

Git creates a master branch once you've done your first commit. There's nothing to have a branch for if there's no code in the repository.

how to change background image of button when clicked/focused?

You just need to set background and give previous.xml file in background of button in your layout file.

<Button
 android:id="@+id/button1"
 android:background="@drawable/previous"
 android:layout_width="200dp"
 android:layout_height="126dp"
 android:text="Hello" />

and done.Edit Following is previous.xml file in drawable directory

<?xml version="1.0" encoding="utf-8"?>

<item android:drawable="@drawable/onclick" android:state_selected="true"></item>
<item android:drawable="@drawable/onclick" android:state_pressed="true"></item>
<item android:drawable="@drawable/normal"></item>

Flatten an irregular list of lists

Here's the compiler.ast.flatten implementation in 2.7.5:

def flatten(seq):
    l = []
    for elt in seq:
        t = type(elt)
        if t is tuple or t is list:
            for elt2 in flatten(elt):
                l.append(elt2)
        else:
            l.append(elt)
    return l

There are better, faster methods (If you've reached here, you have seen them already)

Also note:

Deprecated since version 2.6: The compiler package has been removed in Python 3.

how to play video from url

pDialog = new ProgressDialog(this);

    // Set progressbar message
    pDialog.setMessage("Buffering...");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(false);
    // Show progressbar
    pDialog.show();

    try {
        // Start the MediaController
        MediaController mediacontroller = new MediaController(this);
        mediacontroller.setAnchorView(mVideoView);      

        Uri videoUri = Uri.parse(videoUrl);
        mVideoView.setMediaController(mediacontroller);
        mVideoView.setVideoURI(videoUri);

    } catch (Exception e) {

        e.printStackTrace();
    }

    mVideoView.requestFocus();
    mVideoView.setOnPreparedListener(new OnPreparedListener() {
        // Close the progress bar and play the video
        public void onPrepared(MediaPlayer mp) {
            pDialog.dismiss();
            mVideoView.start();
        }
    });
    mVideoView.setOnCompletionListener(new OnCompletionListener() {

        public void onCompletion(MediaPlayer mp) {
            if (pDialog.isShowing()) {
                pDialog.dismiss();
            }
            finish();               
        }
    });

Difference between parameter and argument

They are often used interchangeably in text, but in most standards the distinction is that an argument is an expression passed to a function, where a parameter is a reference declared in a function declaration.

Basic Authentication Using JavaScript

After Spending quite a bit of time looking into this, i came up with the solution for this; In this solution i am not using the Basic authentication but instead went with the oAuth authentication protocol. But to use Basic authentication you should be able to specify this in the "setHeaderRequest" with minimal changes to the rest of the code example. I hope this will be able to help someone else in the future:

var token_ // variable will store the token
var userName = "clientID"; // app clientID
var passWord = "secretKey"; // app clientSecret
var caspioTokenUrl = "https://xxx123.caspio.com/oauth/token"; // Your application token endpoint  
var request = new XMLHttpRequest(); 

function getToken(url, clientID, clientSecret) {
    var key;           
    request.open("POST", url, true); 
    request.setRequestHeader("Content-type", "application/json");
    request.send("grant_type=client_credentials&client_id="+clientID+"&"+"client_secret="+clientSecret); // specify the credentials to receive the token on request
    request.onreadystatechange = function () {
        if (request.readyState == request.DONE) {
            var response = request.responseText;
            var obj = JSON.parse(response); 
            key = obj.access_token; //store the value of the accesstoken
            token_ = key; // store token in your global variable "token_" or you could simply return the value of the access token from the function
        }
    }
}
// Get the token
getToken(caspioTokenUrl, userName, passWord);

If you are using the Caspio REST API on some request it may be imperative that you to encode the paramaters for certain request to your endpoint; see the Caspio documentation on this issue;

NOTE: encodedParams is NOT used in this example but was used in my solution.

Now that you have the token stored from the token endpoint you should be able to successfully authenticate for subsequent request from the caspio resource endpoint for your application

function CallWebAPI() {
    var request_ = new XMLHttpRequest();        
    var encodedParams = encodeURIComponent(params);
    request_.open("GET", "https://xxx123.caspio.com/rest/v1/tables/", true);
    request_.setRequestHeader("Authorization", "Bearer "+ token_);
    request_.send();
    request_.onreadystatechange = function () {
        if (request_.readyState == 4 && request_.status == 200) {
            var response = request_.responseText;
            var obj = JSON.parse(response); 
            // handle data as needed... 

        }
    }
} 

This solution does only considers how to successfully make the authenticated request using the Caspio API in pure javascript. There are still many flaws i am sure...

How to Save Console.WriteLine Output to Text File

do you want to write code for that or just use command-line feature 'command redirection' as follows:

app.exe >> output.txt

as demonstrated here: http://discomoose.org/2006/05/01/output-redirection-to-a-file-from-the-windows-command-line/ (Archived at archive.org)

EDIT: link dead, here's another example: http://pcsupport.about.com/od/commandlinereference/a/redirect-command-output-to-file.htm

How do I access my webcam in Python?

John Montgomery's, answer is great, but at least on Windows, it is missing the line

vc.release()

before

cv2.destroyWindow("preview")

Without it, the camera resource is locked, and can not be captured again before the python console is killed.

JavaScript alert box with timer

If you are looking for an alert that dissapears after an interval you could try the jQuery UI Dialog widget.

Scanner only reads first word instead of line

Replace next() with nextLine():

String productDescription = input.nextLine();

Selenium and xpath: finding a div with a class/id and verifying text inside

For class and text xpath-

//div[contains(@class,'Caption') and (text(),'Model saved')]

and

For class and id xpath-

//div[contains(@class,'gwt-HTML') and @id="alertLabel"]

Python, Pandas : write content of DataFrame into text File

You can use pandas.DataFrame.to_csv(), and setting both index and header to False:

In [97]: print df.to_csv(sep=' ', index=False, header=False)
18 55 1 70
18 55 2 67
18 57 2 75
18 58 1 35
19 54 2 70

pandas.DataFrame.to_csv can write to a file directly, for more info you can refer to the docs linked above.

How to convert the ^M linebreak to 'normal' linebreak in a file opened in vim?

^M gives unwanted line breaks. To handle this we can use the sed command as follows:

sed 's/\r//g'

Stop Excel from automatically converting certain text values to dates

I have found that putting an '=' before the double quotes will accomplish what you want. It forces the data to be text.

eg. ="2008-10-03",="more text"

EDIT (according to other posts): because of the Excel 2007 bug noted by Jeffiekins one should use the solution proposed by Andrew: "=""2008-10-03"""

How to implement reCaptcha for ASP.NET MVC?

Simple and Complete Solution working for me. Supports ASP.NET MVC 4 and 5 (Supports ASP.NET 4.0, 4.5, and 4.5.1)

Step 1: Install NuGet Package by "Install-Package reCAPTCH.MVC"

Step 2: Add your Public and Private key to your web.config file in appsettings section

<appSettings>
    <add key="ReCaptchaPrivateKey" value=" -- PRIVATE_KEY -- " />
    <add key="ReCaptchaPublicKey" value=" -- PUBLIC KEY -- " />
</appSettings>  

You can create an API key pair for your site at https://www.google.com/recaptcha/intro/index.html and click on Get reCAPTCHA at top of the page

Step 3: Modify your form to include reCaptcha

@using reCAPTCHA.MVC
@using (Html.BeginForm())
{
    @Html.Recaptcha()
    @Html.ValidationMessage("ReCaptcha")
    <input type="submit" value="Register" />
}

Step 4: Implement the Controller Action that will handle the form submission and Captcha validation

[CaptchaValidator(
PrivateKey = "your private reCaptcha Google Key",
ErrorMessage = "Invalid input captcha.",
RequiredMessage = "The captcha field is required.")]
public ActionResult MyAction(myVM model)
{
    if (ModelState.IsValid) //this will take care of captcha
    {
    }
}

OR

public ActionResult MyAction(myVM model, bool captchaValid)
{
    if (captchaValid) //manually check for captchaValid 
    {
    }
}

VBA changing active workbook

Use ThisWorkbook which will refer to the original workbook which holds the code.

Alternatively at code start

Dim Wb As Workbook
Set Wb = ActiveWorkbook

sample code that activates all open books before returning to ThisWorkbook

Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
    Wb2.Activate
Next
Wb.Activate
End Sub

error CS0234: The type or namespace name 'Script' does not exist in the namespace 'System.Web'

I had the same. Script been underlined. I added a reference to System.Web.Extensions. Thereafter the Script was no longer underlined. Hope this helps someone.

Get encoding of a file in Windows

The (Linux) command-line tool 'file' is available on Windows via GnuWin32:

http://gnuwin32.sourceforge.net/packages/file.htm

If you have git installed, it's located in C:\Program Files\git\usr\bin.

Example:

    C:\Users\SH\Downloads\SquareRoot>file *
    _UpgradeReport_Files;         directory
    Debug;                        directory
    duration.h;                   ASCII C++ program text, with CRLF line terminators
    ipch;                         directory
    main.cpp;                     ASCII C program text, with CRLF line terminators
    Precision.txt;                ASCII text, with CRLF line terminators
    Release;                      directory
    Speed.txt;                    ASCII text, with CRLF line terminators
    SquareRoot.sdf;               data
    SquareRoot.sln;               UTF-8 Unicode (with BOM) text, with CRLF line terminators
    SquareRoot.sln.docstates.suo; PCX ver. 2.5 image data
    SquareRoot.suo;               CDF V2 Document, corrupt: Cannot read summary info
    SquareRoot.vcproj;            XML  document text
    SquareRoot.vcxproj;           XML document text
    SquareRoot.vcxproj.filters;   XML document text
    SquareRoot.vcxproj.user;      XML document text
    squarerootmethods.h;          ASCII C program text, with CRLF line terminators
    UpgradeLog.XML;               XML  document text

    C:\Users\SH\Downloads\SquareRoot>file --mime-encoding *
    _UpgradeReport_Files;         binary
    Debug;                        binary
    duration.h;                   us-ascii
    ipch;                         binary
    main.cpp;                     us-ascii
    Precision.txt;                us-ascii
    Release;                      binary
    Speed.txt;                    us-ascii
    SquareRoot.sdf;               binary
    SquareRoot.sln;               utf-8
    SquareRoot.sln.docstates.suo; binary
    SquareRoot.suo;               CDF V2 Document, corrupt: Cannot read summary infobinary
    SquareRoot.vcproj;            us-ascii
    SquareRoot.vcxproj;           utf-8
    SquareRoot.vcxproj.filters;   utf-8
    SquareRoot.vcxproj.user;      utf-8
    squarerootmethods.h;          us-ascii
    UpgradeLog.XML;               us-ascii

How can I display an RTSP video stream in a web page?

If you want to stream RTSP directly to web page, then I am afraid your only option is to use an ActiveX control viewer that comes with the camera. This is a direct connection IP Cam -> Viewer, and should really be the fastest. Not sure why you having issues; Axis ActiveX works pretty good for me.

However, this option is not really bandwidth-efficient and you can not serve multiple concurrent viewers (most of IP Cams have 10 viewers limit). The better option is to upload a single RTSP stream to centrally-hosted streaming server, which will convert your stream to RTMP/MPEG-TS and publish it to Flash players/Set-Top boxes.

Wowza, Erlyvideo, Unreal Media Server, Red5 are your options.

Axios get in url works but with second parameter as object it doesn't

axios.get accepts a request config as the second parameter (not query string params).

You can use the params config option to set query string params as follows:

axios.get('/api', {
  params: {
    foo: 'bar'
  }
});

How to vertically align a html radio button to it's label?

I like putting the inputs inside the labels (added bonus: now you don't need the for attribute on the label), and put vertical-align: middle on the input.

_x000D_
_x000D_
label > input[type=radio] {_x000D_
    vertical-align: middle;_x000D_
    margin-top: -2px;_x000D_
}_x000D_
_x000D_
#d2 {  _x000D_
    font-size: 30px;_x000D_
}
_x000D_
<div>_x000D_
 <label><input type="radio" name="radio" value="1">Good</label>_x000D_
 <label><input type="radio" name="radio" value="2">Excellent</label>_x000D_
<div>_x000D_
<br>_x000D_
<div id="d2">_x000D_
 <label><input type="radio" name="radio2" value="1">Good</label>_x000D_
 <label><input type="radio" name="radio2" value="2">Excellent</label>_x000D_
<div>
_x000D_
_x000D_
_x000D_

(The -2px margin-top is a matter of taste.)

Another option I really like is using a table. (Hold your pitch forks! It's really nice!) It does mean you need to add the for attribute to all your labels and ids to your inputs. I'd recommended this option for labels with long text content, over multiple lines.

_x000D_
_x000D_
<table><tr><td>_x000D_
    <input id="radioOption" name="radioOption" type="radio" />_x000D_
    </td><td>_x000D_
    <label for="radioOption">                     _x000D_
        Really good option_x000D_
    </label>_x000D_
</td></tr></table>
_x000D_
_x000D_
_x000D_

How to convert color code into media.brush?

You could use the same mechanism the XAML reading system uses: Type converters

var converter = new System.Windows.Media.BrushConverter();
var brush = (Brush)converter.ConvertFromString("#FFFFFF90");
Fill = brush;

SQL Server : export query as a .txt file

The BCP Utility can also be used in the form of a .bat file, but be cautious of escape sequences (ie quotes "" must be used in conjunction with ) and the appropriate tags.

.bat Example:

C:
bcp "\"YOUR_SERVER\".dbo.Proc" queryout C:\FilePath.txt -T -c -q
-- Add PAUSE here if you'd like to see the completed batch

-q MUST be used in the presence of quotations within the query itself.

BCP can also run Stored Procedures if necessary. Again, be cautious: Temporary Tables must be created prior to execution or else you should consider using Table Variables.

Youtube - How to force 480p video quality in embed link / <iframe>

You can also use for 1080 hd values:

240p: &vq=small , 360p: &vq=medium , 480p: &vq=large , 720p: &vq=hd720 , &vq=hd1080

Loading cross-domain endpoint with AJAX

You need CORS proxy which proxies your request from your browser to requested service with appropriate CORS headers. List of such services are in code snippet below. You can also run provided code snippet to see ping to such services from your location.

_x000D_
_x000D_
$('li').each(function() {_x000D_
  var self = this;_x000D_
  ping($(this).text()).then(function(delta) {_x000D_
    console.log($(self).text(), delta, ' ms');_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdn.rawgit.com/jdfreder/pingjs/c2190a3649759f2bd8569a72ae2b597b2546c871/ping.js"></script>_x000D_
<ul>_x000D_
  <li>https://crossorigin.me/</li>_x000D_
  <li>https://cors-anywhere.herokuapp.com/</li>_x000D_
  <li>http://cors.io/</li>_x000D_
  <li>https://cors.5apps.com/?uri=</li>_x000D_
  <li>http://whateverorigin.org/get?url=</li>_x000D_
  <li>https://anyorigin.com/get?url=</li>_x000D_
  <li>http://corsproxy.nodester.com/?src=</li>_x000D_
  <li>https://jsonp.afeld.me/?url=</li>_x000D_
  <li>http://benalman.com/code/projects/php-simple-proxy/ba-simple-proxy.php?url=</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

How to modify memory contents using GDB?

Expanding on the answers provided here.

You can just do set idx = 1 to set a variable, but that syntax is not recommended because the variable name may clash with a set sub-command. As an example set w=1 would not be valid.

This means that you should prefer the syntax: set variable idx = 1 or set var idx = 1.

Last but not least, you can just use your trusty old print command, since it evaluates an expression. The only difference being that he also prints the result of the expression.

(gdb) p idx = 1
$1 = 1

You can read more about gdb here.

Is it possible to style a select box?

If have a solution without jQuery. A link where you can see a working example: http://www.letmaier.com/_selectbox/select_general_code.html (styled with more css)

The style-section of my solution:

<style>
#container { margin: 10px; padding: 5px; background: #E7E7E7; width: 300px; background: #ededed); }
#ul1 { display: none; list-style-type: none; list-style-position: outside; margin: 0px; padding: 0px; }
#container a {  color: #333333; text-decoration: none; }
#container ul li {  padding: 3px;   padding-left: 0px;  border-bottom: 1px solid #aaa;  font-size: 0.8em; cursor: pointer; }
#container ul li:hover { background: #f5f4f4; }
</style>

Now the HTML-code inside the body-tag:

<form>
<div id="container" onMouseOver="document.getElementById('ul1').style.display = 'block';" onMouseOut="document.getElementById('ul1').style.display = 'none';">
Select one entry: <input name="entrytext" type="text" disabled readonly>
<ul id="ul1">
    <li onClick="document.forms[0].elements['entrytext'].value='Entry 1'; document.getElementById('ul1').style.display = 'none';"><a href="#">Entry 1</a></li>
    <li onClick="document.forms[0].elements['entrytext'].value='Entry 2'; document.getElementById('ul1').style.display = 'none';"><a href="#">Entry 2</a></li>
    <li onClick="document.forms[0].elements['entrytext'].value='Entry 3'; document.getElementById('ul1').style.display = 'none';"><a href="#">Entry 3</a></li>
</ul>
</div>
</form>

Write a function that returns the longest palindrome in a given string

Here i have written a logic try it :)

public class palindromeClass{

public  static String longestPalindromeString(String in) {
        char[] input = in.toCharArray();
        int longestPalindromeStart = 0;
        int longestPalindromeEnd = 0;

        for (int mid = 0; mid < input.length; mid++) {
            // for odd palindrome case like 14341, 3 will be the mid
            int left = mid-1;
            int right = mid+1;
            // we need to move in the left and right side by 1 place till they reach the end
            while (left >= 0 && right < input.length) {
                // below check to find out if its a palindrome
                if (input[left] == input[right]) {
                    // update global indexes only if this is the longest one till now
                    if (right - left > longestPalindromeEnd
                            - longestPalindromeStart) {
                        longestPalindromeStart = left;
                        longestPalindromeEnd = right;
                    }
                }
                else
                    break;
                left--;
                right++;
            }
            // for even palindrome, we need to have similar logic with mid size 2
            // for that we will start right from one extra place
            left = mid;
            right = mid + 1;// for example 12333321 when we choose 33 as mid
            while (left >= 0 && right < input.length)
            {
                if (input[left] == input[right]) {
                    if (right - left > longestPalindromeEnd
                            - longestPalindromeStart) {
                        longestPalindromeStart = left;
                        longestPalindromeEnd = right;
                    }
                }
                else
                    break;
                left--;
                right++;
            }


        }
        // we have the start and end indexes for longest palindrome now
        return in.substring(longestPalindromeStart, longestPalindromeEnd + 1);
    }
public static void main(String args[]){
System.out.println(longestPalindromeString("HYTBCABADEFGHABCDEDCBAGHTFYW12345678987654321ZWETYGDE"));
}

}

How to use a variable inside a regular expression?

rx = r'\b(?<=\w){0}\b(?!\w)'.format(TEXTO)

C# static class constructor

A static constructor looks like this

static class Foo
{
    static Foo()
    {
         // Static initialization code here
    }
}

It is executed only once when the type is first used. All classes can have static constructors, not just static classes.

Skip rows during csv import pandas

skip[1] will skip second line, not the first one.

Maven not found in Mac OSX mavericks

if you don't want to install homebrew (or any other package manager) just for installing maven, you can grab the binary from their site:

http://maven.apache.org/download.cgi

extract the content to a folder (e.g. /Applications/apache-maven-3.1.1) with

$ tar -xvf apache-maven-3.1.1-bin.tar.gz

and finally adjust your ~/.bash_profile with any texteditor you like to include

export M2_HOME=/Applications/apache-maven-3.1.1
export PATH=$PATH:$M2_HOME/bin

restart the terminal and test it with

$ mvn -version

Apache Maven 3.1.1 (0728685237757ffbf44136acec0402957f723d9a; 2013-09-17 17:22:22+0200)
Maven home: /Applications/apache-maven-3.1.1
Java version: 1.6.0_65, vendor: Apple Inc.
Java home: /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
Default locale: de_DE, platform encoding: MacRoman
OS name: "mac os x", version: "10.9", arch: "x86_64", family: "mac"

UITableView with fixed section headers

You can also set the tableview's bounces property to NO. This will keep the section headers non-floating/static, but then you also lose the bounce property of the tableview.

Oracle SQL Where clause to find date records older than 30 days

Use:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= TRUNC(SYSDATE) - 30

SYSDATE returns the date & time; TRUNC resets the date to being as of midnight so you can omit it if you want the creation_date that is 30 days previous including the current time.

Depending on your needs, you could also look at using ADD_MONTHS:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= ADD_MONTHS(TRUNC(SYSDATE), -1)

Allowing Untrusted SSL Certificates with HttpClient

With Windows 8.1, you can now trust invalid SSL certs. You have to either use the Windows.Web.HttpClient or if you want to use the System.Net.Http.HttpClient, you can use the message handler adapter I wrote: http://www.nuget.org/packages/WinRtHttpClientHandler

Docs are on the GitHub: https://github.com/onovotny/WinRtHttpClientHandler

Map enum in JPA with fixed values?

My own solution to solve this kind of Enum JPA mapping is the following.

Step 1 - Write the following interface that we will use for all enums that we want to map to a db column:

public interface IDbValue<T extends java.io.Serializable> {

    T getDbVal();

}

Step 2 - Implement a custom generic JPA converter as follows:

import javax.persistence.AttributeConverter;

public abstract class EnumDbValueConverter<T extends java.io.Serializable, E extends Enum<E> & IDbValue<T>>
        implements AttributeConverter<E, T> {

    private final Class<E> clazz;

    public EnumDbValueConverter(Class<E> clazz){
        this.clazz = clazz;
    }

    @Override
    public T convertToDatabaseColumn(E attribute) {
        if (attribute == null) {
            return null;
        }
        return attribute.getDbVal();
    }

    @Override
    public E convertToEntityAttribute(T dbData) {
        if (dbData == null) {
            return null;
        }
        for (E e : clazz.getEnumConstants()) {
            if (dbData.equals(e.getDbVal())) {
                return e;
            }
        }
        // handle error as you prefer, for example, using slf4j:
        // log.error("Unable to convert {} to enum {}.", dbData, clazz.getCanonicalName());
        return null;
    }

}

This class will convert the enum value E to a database field of type T (e.g. String) by using the getDbVal() on enum E, and vice versa.

Step 3 - Let the original enum implement the interface we defined in step 1:

public enum Right implements IDbValue<Integer> {
    READ(100), WRITE(200), EDITOR (300);

    private final Integer dbVal;

    private Right(Integer dbVal) {
        this.dbVal = dbVal;
    }

    @Override
    public Integer getDbVal() {
        return dbVal;
    }
}

Step 4 - Extend the converter of step 2 for the Right enum of step 3:

public class RightConverter extends EnumDbValueConverter<Integer, Right> {
    public RightConverter() {
        super(Right.class);
    }
}

Step 5 - The final step is to annotate the field in the entity as follows:

@Column(name = "RIGHT")
@Convert(converter = RightConverter.class)
private Right right;

Conclusion

IMHO this is the cleanest and most elegant solution if you have many enums to map and you want to use a particular field of the enum itself as mapping value.

For all others enums in your project that need similar mapping logic, you only have to repeat steps 3 to 5, that is:

  • implement the interface IDbValue on your enum;
  • extend the EnumDbValueConverter with only 3 lines of code (you may also do this within your entity to avoid creating a separated class);
  • annotate the enum attribute with @Convert from javax.persistence package.

Hope this helps.

javascript popup alert on link click

Single line works just fine:

<a href="http://example.com/"
 onclick="return confirm('Please click on OK to continue.');">click me</a>

Adding another line with a different link on the same page works fine too:

<a href="http://stackoverflow.com/"
 onclick="return confirm('Click on another OK to continue.');">another link</a>

Creating an R dataframe row-by-row

If you have vectors destined to become rows, concatenate them using c(), pass them to a matrix row-by-row, and convert that matrix to a dataframe.

For example, rows

dummydata1=c(2002,10,1,12.00,101,426340.0,4411238.0,3598.0,0.92,57.77,4.80,238.29,-9.9)
dummydata2=c(2002,10,2,12.00,101,426340.0,4411238.0,3598.0,-3.02,78.77,-9999.00,-99.0,-9.9)
dummydata3=c(2002,10,8,12.00,101,426340.0,4411238.0,3598.0,-5.02,88.77,-9999.00,-99.0,-9.9)

can be converted to a data frame thus:

dummyset=c(dummydata1,dummydata2,dummydata3)
col.len=length(dummydata1)
dummytable=data.frame(matrix(data=dummyset,ncol=col.len,byrow=TRUE))

Admittedly, I see 2 major limitations: (1) this only works with single-mode data, and (2) you must know your final # columns for this to work (i.e., I'm assuming that you're not working with a ragged array whose greatest row length is unknown a priori).

This solution seems simple, but from my experience with type conversions in R, I'm sure it creates new challenges down-the-line. Can anyone comment on this?

Asking the user for input until they give a valid response

Yeah I'm 6 years late from the but this question deserves more up-to-date answer.

Separation of concerns

I am a big fan of Unix philosophy "Do one thing and do it well". In this type of problem, it is better practice to split the problem to

  • Ask input with get_input until the input is ok.
  • Validate in validator function. You could write different validators for different input queries.

Asking for input

It can be kept as simple as (Python 3+)

def myvalidator(value):
    try:
        value = int(value)
    except ValueError:
        return False
    return value >= 0

def get_input(prompt, validator, on_validationerror):
    while True:
        value = input(prompt)
        if validator(value):
            return value
        print(on_validationerror)

Example

In [2]: get_input('Give a positive number: ', myvalidator, 'Please, try again')
Give a positive number: foobar
Please, try again
Give a positive number: -10
Please, try again
Give a positive number: 42
Out[2]: '42'

Python 3.8+ Note

In Python 3.8+ you could use the walrus operator

def get_input(prompt, validator, on_validationerror):
    while not validator(value := input(prompt)):
        print(on_validationerror)
    return value 

Execute Python script via crontab

As you have mentioned it doesn't change anything.

First, you should redirect both standard input and standard error from the crontab execution like below:

*/2 * * * * /usr/bin/python /home/souza/Documets/Listener/listener.py > /tmp/listener.log 2>&1

Then you can view the file /tmp/listener.log to see if the script executed as you expected.

Second, I guess what you mean by change anything is by watching the files created by your program:

f = file('counter', 'r+w')
json_file = file('json_file_create_server.json', 'r+w')

The crontab job above won't create these file in directory /home/souza/Documets/Listener, as the cron job is not executed in this directory, and you use relative path in the program. So to create this file in directory /home/souza/Documets/Listener, the following cron job will do the trick:

*/2 * * * * cd /home/souza/Documets/Listener && /usr/bin/python listener.py > /tmp/listener.log 2>&1

Change to the working directory and execute the script from there, and then you can view the files created in place.