Programs & Examples On #Inputstream

An abstract mechanism for reading a data stream in Java

Convert InputStream to JSONObject

use JsonReader in order to parse the InputStream. See example inside the API: http://developer.android.com/reference/android/util/JsonReader.html

Getting the inputstream from a classpath resource (XML file)

ClassLoader.class.getResourceAsStream("/path/file.ext");

Open URL in Java to get the content

Following code should work,

URL url = new URL("http://maps.google.at/maps?saddr=4714&daddr=Marchtrenk&hl=de");
InputStream is = url.openConnection().getInputStream();

BufferedReader reader = new BufferedReader( new InputStreamReader( is )  );

String line = null;
while( ( line = reader.readLine() ) != null )  {
   System.out.println(line);
}
reader.close();

How to convert OutputStream to InputStream?

An OutputStream is one where you write data to. If some module exposes an OutputStream, the expectation is that there is something reading at the other end.

Something that exposes an InputStream, on the other hand, is indicating that you will need to listen to this stream, and there will be data that you can read.

So it is possible to connect an InputStream to an OutputStream

InputStream----read---> intermediateBytes[n] ----write----> OutputStream

As someone metioned, this is what the copy() method from IOUtils lets you do. It does not make sense to go the other way... hopefully this makes some sense

UPDATE:

Of course the more I think of this, the more I can see how this actually would be a requirement. I know some of the comments mentioned Piped input/ouput streams, but there is another possibility.

If the output stream that is exposed is a ByteArrayOutputStream, then you can always get the full contents by calling the toByteArray() method. Then you can create an input stream wrapper by using the ByteArrayInputStream sub-class. These two are pseudo-streams, they both basically just wrap an array of bytes. Using the streams this way, therefore, is technically possible, but to me it is still very strange...

Java - How Can I Write My ArrayList to a file, and Read (load) that file to the original ArrayList?

As an exercise, I would suggest doing the following:

public void save(String fileName) throws FileNotFoundException {
    PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));
    for (Club club : clubs)
        pw.println(club.getName());
    pw.close();
}

This will write the name of each club on a new line in your file.

Soccer
Chess
Football
Volleyball
...

I'll leave the loading to you. Hint: You wrote one line at a time, you can then read one line at a time.

Every class in Java extends the Object class. As such you can override its methods. In this case, you should be interested by the toString() method. In your Club class, you can override it to print some message about the class in any format you'd like.

public String toString() {
    return "Club:" + name;
}

You could then change the above code to:

public void save(String fileName) throws FileNotFoundException {
    PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));
    for (Club club : clubs)
         pw.println(club); // call toString() on club, like club.toString()
    pw.close();
}

How to create streams from string in Node.Js?

Do not use Jo Liss's resumer answer. It will work in most cases, but in my case it lost me a good 4 or 5 hours bug finding. There is no need for third party modules to do this.

NEW ANSWER:

var Readable = require('stream').Readable

var s = new Readable()
s.push('beep')    // the string you want
s.push(null)      // indicates end-of-file basically - the end of the stream

This should be a fully compliant Readable stream. See here for more info on how to use streams properly.

OLD ANSWER: Just use the native PassThrough stream:

var stream = require("stream")
var a = new stream.PassThrough()
a.write("your string")
a.end()

a.pipe(process.stdout) // piping will work as normal
/*stream.on('data', function(x) {
   // using the 'data' event works too
   console.log('data '+x)
})*/
/*setTimeout(function() {
   // you can even pipe after the scheduler has had time to do other things
   a.pipe(process.stdout) 
},100)*/

a.on('end', function() {
    console.log('ended') // the end event will be called properly
})

Note that the 'close' event is not emitted (which is not required by the stream interfaces).

Connecting an input stream to an outputstream

Use org.apache.commons.io.IOUtils

InputStream inStream = new ...
OutputStream outStream = new ...
IOUtils.copy(inStream, outStream);

or copyLarge for size >2GB

Read input stream twice

You can use org.apache.commons.io.IOUtils.copy to copy the contents of the InputStream to a byte array, and then repeatedly read from the byte array using a ByteArrayInputStream. E.g.:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
org.apache.commons.io.IOUtils.copy(in, baos);
byte[] bytes = baos.toByteArray();

// either
while (needToReadAgain) {
    ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    yourReadMethodHere(bais);
}

// or
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
while (needToReadAgain) {
    bais.reset();
    yourReadMethodHere(bais);
}

Determine the size of an InputStream

You can't determine the amount of data in a stream without reading it; you can, however, ask for the size of a file:

http://java.sun.com/javase/6/docs/api/java/io/File.html#length()

If that isn't possible, you can write the bytes you read from the input stream to a ByteArrayOutputStream which will grow as required.

How to get access to raw resources that I put in res folder?

An advance approach is using Kotlin Extension function

fun Context.getRawInput(@RawRes resourceId: Int): InputStream {
    return resources.openRawResource(resourceId)
}

One more interesting thing is extension function use that is defined in Closeable scope

For example you can work with input stream in elegant way without handling Exceptions and memory managing

fun Context.readRaw(@RawRes resourceId: Int): String {
    return resources.openRawResource(resourceId).bufferedReader(Charsets.UTF_8).use { it.readText() }
}

Reading InputStream as UTF-8

Solved my own problem. This line:

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

needs to be:

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));

or since Java 7:

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8));

Different ways of loading a file as an InputStream

After trying some ways to load the file with no success, I remembered I could use FileInputStream, which worked perfectly.

InputStream is = new FileInputStream("file.txt");

This is another way to read a file into an InputStream, it reads the file from the currently running folder.

Convert InputStream to BufferedReader

A BufferedReader constructor takes a reader as argument, not an InputStream. You should first create a Reader from your stream, like so:

Reader reader = new InputStreamReader(is);
BufferedReader br = new BufferedReader(reader);

Preferrably, you also provide a Charset or character encoding name to the StreamReader constructor. Since a stream just provides bytes, converting these to text means the encoding must be known. If you don't specify it, the system default is assumed.

How do I convert a String to an InputStream in Java?

There are two ways we can convert String to InputStream in Java,

  1. Using ByteArrayInputStream

Example :-

String str = "String contents";
InputStream is = new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8));
  1. Using Apache Commons IO

Example:-

String str = "String contents"
InputStream is = IOUtils.toInputStream(str, StandardCharsets.UTF_8);

How to convert an Stream into a byte[] in C#?

Ok, maybe I'm missing something here, but this is the way I do it:

public static Byte[] ToByteArray(this Stream stream) {
    Int32 length = stream.Length > Int32.MaxValue ? Int32.MaxValue : Convert.ToInt32(stream.Length);
    Byte[] buffer = new Byte[length];
    stream.Read(buffer, 0, length);
    return buffer;
}

Capture characters from standard input without waiting for enter to be pressed

The following is a solution extracted from Expert C Programming: Deep Secrets, which is supposed to work on SVr4. It uses stty and ioctl.

#include <sys/filio.h>
int kbhit()
{
 int i;
 ioctl(0, FIONREAD, &i);
 return i; /* return a count of chars available to read */
}
main()
{
 int i = 0;
 intc='';
 system("stty raw -echo");
 printf("enter 'q' to quit \n");
 for (;c!='q';i++) {
    if (kbhit()) {
        c=getchar();
       printf("\n got %c, on iteration %d",c, i);
    }
}
 system("stty cooked echo");
}

byte[] to file in Java

Without any libraries:

try (FileOutputStream stream = new FileOutputStream(path)) {
    stream.write(bytes);
}

With Google Guava:

Files.write(bytes, new File(path));

With Apache Commons:

FileUtils.writeByteArrayToFile(new File(path), bytes);

All of these strategies require that you catch an IOException at some point too.

How to read all of Inputstream in Server Socket JAVA

You can read your BufferedInputStream like this. It will read data till it reaches end of stream which is indicated by -1.

inputS = new BufferedInputStream(inBS);
byte[] buffer = new byte[1024];    //If you handle larger data use a bigger buffer size
int read;
while((read = inputS.read(buffer)) != -1) {
    System.out.println(read);
    // Your code to handle the data
}

AmazonS3 putObject with InputStream length example

For uploading, the S3 SDK has two putObject methods:

PutObjectRequest(String bucketName, String key, File file)

and

PutObjectRequest(String bucketName, String key, InputStream input, ObjectMetadata metadata)

The inputstream+ObjectMetadata method needs a minimum metadata of Content Length of your inputstream. If you don't, then it will buffer in-memory to get that information, this could cause OOM. Alternatively, you could do your own in-memory buffering to get the length, but then you need to get a second inputstream.

Not asked by the OP (limitations of his environment), but for someone else, such as me. I find it easier, and safer (if you have access to temp file), to write the inputstream to a temp file, and put the temp file. No in-memory buffer, and no requirement to create a second inputstream.

AmazonS3 s3Service = new AmazonS3Client(awsCredentials);
File scratchFile = File.createTempFile("prefix", "suffix");
try {
    FileUtils.copyInputStreamToFile(inputStream, scratchFile);    
    PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, id, scratchFile);
    PutObjectResult putObjectResult = s3Service.putObject(putObjectRequest);

} finally {
    if(scratchFile.exists()) {
        scratchFile.delete();
    }
}

Convert InputStream to byte array in Java

Use vanilla Java's DataInputStream and its readFully Method (exists since at least Java 1.4):

...
byte[] bytes = new byte[(int) file.length()];
DataInputStream dis = new DataInputStream(new FileInputStream(file));
dis.readFully(bytes);
...

There are some other flavors of this method, but I use this all the time for this use case.

How to clone an InputStream?

Cloning an input stream might not be a good idea, because this requires deep knowledge about the details of the input stream being cloned. A workaround for this is to create a new input stream that reads from the same source again.

So using some Java 8 features this would look like this:

public class Foo {

    private Supplier<InputStream> inputStreamSupplier;

    public void bar() {
        procesDataThisWay(inputStreamSupplier.get());
        procesDataTheOtherWay(inputStreamSupplier.get());
    }

    private void procesDataThisWay(InputStream) {
        // ...
    }

    private void procesDataTheOtherWay(InputStream) {
        // ...
    }
}

This method has the positive effect that it will reuse code that is already in place - the creation of the input stream encapsulated in inputStreamSupplier. And there is no need to maintain a second code path for the cloning of the stream.

On the other hand, if reading from the stream is expensive (because a it's done over a low bandwith connection), then this method will double the costs. This could be circumvented by using a specific supplier that will store the stream content locally first and provide an InputStream for that now local resource.

InputStream from a URL

Here is a full example which reads the contents of the given web page. The web page is read from an HTML form. We use standard InputStream classes, but it could be done more easily with JSoup library.

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>

</dependency>

<dependency>
    <groupId>commons-validator</groupId>
    <artifactId>commons-validator</artifactId>
    <version>1.6</version>
</dependency>  

These are the Maven dependencies. We use Apache Commons library to validate URL strings.

package com.zetcode.web;

import com.zetcode.service.WebPageReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "ReadWebPage", urlPatterns = {"/ReadWebPage"})
public class ReadWebpage extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/plain;charset=UTF-8");

        String page = request.getParameter("webpage");

        String content = new WebPageReader().setWebPageName(page).getWebPageContent();

        ServletOutputStream os = response.getOutputStream();
        os.write(content.getBytes(StandardCharsets.UTF_8));
    }
}

The ReadWebPage servlet reads the contents of the given web page and sends it back to the client in plain text format. The task of reading the page is delegated to WebPageReader.

package com.zetcode.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import org.apache.commons.validator.routines.UrlValidator;

public class WebPageReader {

    private String webpage;
    private String content;

    public WebPageReader setWebPageName(String name) {

        webpage = name;
        return this;
    }

    public String getWebPageContent() {

        try {

            boolean valid = validateUrl(webpage);

            if (!valid) {

                content = "Invalid URL; use http(s)://www.example.com format";
                return content;
            }

            URL url = new URL(webpage);

            try (InputStream is = url.openStream();
                    BufferedReader br = new BufferedReader(
                            new InputStreamReader(is, StandardCharsets.UTF_8))) {

                content = br.lines().collect(
                      Collectors.joining(System.lineSeparator()));
            }

        } catch (IOException ex) {

            content = String.format("Cannot read webpage %s", ex);
            Logger.getLogger(WebPageReader.class.getName()).log(Level.SEVERE, null, ex);
        }

        return content;
    }

    private boolean validateUrl(String webpage) {

        UrlValidator urlValidator = new UrlValidator();

        return urlValidator.isValid(webpage);
    }
}

WebPageReader validates the URL and reads the contents of the web page. It returns a string containing the HTML code of the page.

<!DOCTYPE html>
<html>
    <head>
        <title>Home page</title>
        <meta charset="UTF-8">
    </head>
    <body>
        <form action="ReadWebPage">

            <label for="page">Enter a web page name:</label>
            <input  type="text" id="page" name="webpage">

            <button type="submit">Submit</button>

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

Finally, this is the home page containing the HTML form. This is taken from my tutorial about this topic.

Can we convert a byte array into an InputStream in Java?

Use ByteArrayInputStream:

InputStream is = new ByteArrayInputStream(decodedBytes);

Creating a byte array from a stream

It really depends on whether or not you can trust s.Length. For many streams, you just don't know how much data there will be. In such cases - and before .NET 4 - I'd use code like this:

public static byte[] ReadFully(Stream input)
{
    byte[] buffer = new byte[16*1024];
    using (MemoryStream ms = new MemoryStream())
    {
        int read;
        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            ms.Write(buffer, 0, read);
        }
        return ms.ToArray();
    }
}

With .NET 4 and above, I'd use Stream.CopyTo, which is basically equivalent to the loop in my code - create the MemoryStream, call stream.CopyTo(ms) and then return ms.ToArray(). Job done.

I should perhaps explain why my answer is longer than the others. Stream.Read doesn't guarantee that it will read everything it's asked for. If you're reading from a network stream, for example, it may read one packet's worth and then return, even if there will be more data soon. BinaryReader.Read will keep going until the end of the stream or your specified size, but you still have to know the size to start with.

The above method will keep reading (and copying into a MemoryStream) until it runs out of data. It then asks the MemoryStream to return a copy of the data in an array. If you know the size to start with - or think you know the size, without being sure - you can construct the MemoryStream to be that size to start with. Likewise you can put a check at the end, and if the length of the stream is the same size as the buffer (returned by MemoryStream.GetBuffer) then you can just return the buffer. So the above code isn't quite optimised, but will at least be correct. It doesn't assume any responsibility for closing the stream - the caller should do that.

See this article for more info (and an alternative implementation).

What is InputStream & Output Stream? Why and when do we use them?

Stream: In laymen terms stream is data , most generic stream is binary representation of data.

Input Stream : If you are reading data from a file or any other source , stream used is input stream. In a simpler terms input stream acts as a channel to read data.

Output Stream : If you want to read and process data from a source (file etc) you first need to save the data , the mean to store data is output stream .

FileNotFoundException while getting the InputStream object from HttpURLConnection

FileNotFound in this case means you got a 404 from your server

You Have to Set the Request Content-Type Header Parameter Set “content-type” request header to “application/json” to send the request content in JSON form.

This parameter has to be set to send the request body in JSON format.

Failing to do so, the server returns HTTP status code “400-bad request”.

con.setRequestProperty("Content-Type", "application/json; utf-8");

Full Script ->

public class SendDeviceDetails extends AsyncTask<String, Void, String> {

@Override
protected String doInBackground(String... params) {

    String data = "";
    String url = "";

    HttpURLConnection con = null;
    try {

        // From the above URL object,
        // we can invoke the openConnection method to get the HttpURLConnection object.
        // We can't instantiate HttpURLConnection directly, as it's an abstract class:
        con = (HttpURLConnection)new URL(url).openConnection();
        //To send a POST request, we'll have to set the request method property to POST:
        con.setRequestMethod("POST");

        // Set the Request Content-Type Header Parameter
        // Set “content-type” request header to “application/json” to send the request content in JSON form.
        // This parameter has to be set to send the request body in JSON format.
        //Failing to do so, the server returns HTTP status code “400-bad request”.
        con.setRequestProperty("Content-Type", "application/json; utf-8");
        //Set Response Format Type
        //Set the “Accept” request header to “application/json” to read the response in the desired format:
        con.setRequestProperty("Accept", "application/json");

        //To send request content, let's enable the URLConnection object's doOutput property to true.
        //Otherwise, we'll not be able to write content to the connection output stream:
        con.setDoOutput(true);

        //JSON String need to be constructed for the specific resource.
        //We may construct complex JSON using any third-party JSON libraries such as jackson or org.json
        String jsonInputString = params[0];

        try(OutputStream os = con.getOutputStream()){
            byte[] input = jsonInputString.getBytes("utf-8");
            os.write(input, 0, input.length);
        }

        int code = con.getResponseCode();
        System.out.println(code);

        //Get the input stream to read the response content.
        // Remember to use try-with-resources to close the response stream automatically.
        try(BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))){
            StringBuilder response = new StringBuilder();
            String responseLine = null;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }
            System.out.println(response.toString());
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (con != null) {
            con.disconnect();
        }
    }

    return data;
}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    Log.e("TAG", result); // this is expecting a response code to be sent from your server upon receiving the POST data
}

and call it

new SendDeviceDetails().execute("");

you can find more details in this tutorial

https://www.baeldung.com/httpurlconnection-post

Can you explain the HttpURLConnection connection process?

On which point does HTTPURLConnection try to establish a connection to the given URL?

On the port named in the URL if any, otherwise 80 for HTTP and 443 for HTTPS. I believe this is documented.

On which point can I know that I was able to successfully establish a connection?

When you call getInputStream() or getOutputStream() or getResponseCode() without getting an exception.

Are establishing a connection and sending the actual request done in one step/method call? What method is it?

No and none.

Can you explain the function of getOutputStream() and getInputStream() in layman's term?

Either of them first connects if necessary, then returns the required stream.

I notice that when the server I'm trying to connect to is down, I get an Exception at getOutputStream(). Does it mean that HTTPURLConnection will only start to establish a connection when I invoke getOutputStream()? How about the getInputStream()? Since I'm only able to get the response at getInputStream(), then does it mean that I didn't send any request at getOutputStream() yet but simply establishes a connection? Do HttpURLConnection go back to the server to request for response when I invoke getInputStream()?

See above.

Am I correct to say that openConnection() simply creates a new connection object but does not establish any connection yet?

Yes.

How can I measure the read overhead and connect overhead?

Connect: take the time getInputStream() or getOutputStream() takes to return, whichever you call first. Read: time from starting first read to getting the EOS.

How can I check if an InputStream is empty without reading from it?

Based on the suggestion of using the PushbackInputStream, you'll find an exemple implementation here:

/**
 * @author Lorber Sebastien <i>([email protected])</i>
 */
public class NonEmptyInputStream extends FilterInputStream {

  /**
   * Once this stream has been created, do not consume the original InputStream 
   * because there will be one missing byte...
   * @param originalInputStream
   * @throws IOException
   * @throws EmptyInputStreamException
   */
  public NonEmptyInputStream(InputStream originalInputStream) throws IOException, EmptyInputStreamException {
    super( checkStreamIsNotEmpty(originalInputStream) );
  }


  /**
   * Permits to check the InputStream is empty or not
   * Please note that only the returned InputStream must be consummed.
   *
   * see:
   * http://stackoverflow.com/questions/1524299/how-can-i-check-if-an-inputstream-is-empty-without-reading-from-it
   *
   * @param inputStream
   * @return
   */
  private static InputStream checkStreamIsNotEmpty(InputStream inputStream) throws IOException, EmptyInputStreamException {
    Preconditions.checkArgument(inputStream != null,"The InputStream is mandatory");
    PushbackInputStream pushbackInputStream = new PushbackInputStream(inputStream);
    int b;
    b = pushbackInputStream.read();
    if ( b == -1 ) {
      throw new EmptyInputStreamException("No byte can be read from stream " + inputStream);
    }
    pushbackInputStream.unread(b);
    return pushbackInputStream;
  }

  public static class EmptyInputStreamException extends RuntimeException {
    public EmptyInputStreamException(String message) {
      super(message);
    }
  }

}

And here are some passing tests:

  @Test(expected = EmptyInputStreamException.class)
  public void test_check_empty_input_stream_raises_exception_for_empty_stream() throws IOException {
    InputStream emptyStream = new ByteArrayInputStream(new byte[0]);
    new NonEmptyInputStream(emptyStream);
  }

  @Test
  public void test_check_empty_input_stream_ok_for_non_empty_stream_and_returned_stream_can_be_consummed_fully() throws IOException {
    String streamContent = "HELLooooô wörld";
    InputStream inputStream = IOUtils.toInputStream(streamContent, StandardCharsets.UTF_8);
    inputStream = new NonEmptyInputStream(inputStream);
    assertThat(IOUtils.toString(inputStream,StandardCharsets.UTF_8)).isEqualTo(streamContent);
  }

Difference between Console.Read() and Console.ReadLine()?

Console.Read() reads only the next character from standard input, and Console.ReadLine() reads the next line of characters from the standard input stream.

Standard input in case of Console Application is input from the user typed words in console UI of your application. Try to create it by Visual studio, and see by yourself.

Byte[] to InputStream or OutputStream

There is no conversion between InputStream/OutputStream and the bytes they are working with. They are made for binary data, and just read (or write) the bytes one by one as is.

A conversion needs to happen when you want to go from byte to char. Then you need to convert using a character set. This happens when you make String or Reader from bytes, which are made for character data.

getResourceAsStream() is always returning null

I don't know if this applies to JAX-WS, but for JAX-RS I was able to access a file by injecting a ServletContext and then calling getResourceAsStream() on it:

@Context ServletContext servletContext;
...
InputStream is = servletContext.getResourceAsStream("/WEB-INF/test_model.js");

Note that, at least in GlassFish 3.1, the path had to be absolute, i.e., start with slash. More here: How do I use a properties file with jax-rs?

How do I read / convert an InputStream into a String in Java?

ISO-8859-1

Here is a very performant way to do this if you know your input stream's encoding is ISO-8859-1 or ASCII. It (1) avoids the unnecessary synchronization present in StringWriter's internal StringBuffer, (2) avoids the overhead of InputStreamReader, and (3) minimizes the number of times StringBuilder's internal char array must be copied.

public static String iso_8859_1(InputStream is) throws IOException {
    StringBuilder chars = new StringBuilder(Math.max(is.available(), 4096));
    byte[] buffer = new byte[4096];
    int n;
    while ((n = is.read(buffer)) != -1) {
        for (int i = 0; i < n; i++) {
            chars.append((char)(buffer[i] & 0xFF));
        }
    }
    return chars.toString();
}

UTF-8

The same general strategy may be used for a stream encoded with UTF-8:

public static String utf8(InputStream is) throws IOException {
    StringBuilder chars = new StringBuilder(Math.max(is.available(), 4096));
    byte[] buffer = new byte[4096];
    int n;
    int state = 0;
    while ((n = is.read(buffer)) != -1) {
        for (int i = 0; i < n; i++) {
            if ((state = nextStateUtf8(state, buffer[i])) >= 0) {
                chars.appendCodePoint(state);
            } else if (state == -1) { //error
                state = 0;
                chars.append('\uFFFD'); //replacement char
            }
        }
    }
    return chars.toString();
}

where the nextStateUtf8() function is defined as follows:

/**
 * Returns the next UTF-8 state given the next byte of input and the current state.
 * If the input byte is the last byte in a valid UTF-8 byte sequence,
 * the returned state will be the corresponding unicode character (in the range of 0 through 0x10FFFF).
 * Otherwise, a negative integer is returned. A state of -1 is returned whenever an
 * invalid UTF-8 byte sequence is detected.
 */
static int nextStateUtf8(int currentState, byte nextByte) {
    switch (currentState & 0xF0000000) {
        case 0:
            if ((nextByte & 0x80) == 0) { //0 trailing bytes (ASCII)
                return nextByte;
            } else if ((nextByte & 0xE0) == 0xC0) { //1 trailing byte
                if (nextByte == (byte) 0xC0 || nextByte == (byte) 0xC1) { //0xCO & 0xC1 are overlong
                    return -1;
                } else {
                    return nextByte & 0xC000001F;
                }
            } else if ((nextByte & 0xF0) == 0xE0) { //2 trailing bytes
                if (nextByte == (byte) 0xE0) { //possibly overlong
                    return nextByte & 0xA000000F;
                } else if (nextByte == (byte) 0xED) { //possibly surrogate
                    return nextByte & 0xB000000F;
                } else {
                    return nextByte & 0x9000000F;
                }
            } else if ((nextByte & 0xFC) == 0xF0) { //3 trailing bytes
                if (nextByte == (byte) 0xF0) { //possibly overlong
                    return nextByte & 0x80000007;
                } else {
                    return nextByte & 0xE0000007;
                }
            } else if (nextByte == (byte) 0xF4) { //3 trailing bytes, possibly undefined
                return nextByte & 0xD0000007;
            } else {
                return -1;
            }
        case 0xE0000000: //3rd-to-last continuation byte
            return (nextByte & 0xC0) == 0x80 ? currentState << 6 | nextByte & 0x9000003F : -1;
        case 0x80000000: //3rd-to-last continuation byte, check overlong
            return (nextByte & 0xE0) == 0xA0 || (nextByte & 0xF0) == 0x90 ? currentState << 6 | nextByte & 0x9000003F : -1;
        case 0xD0000000: //3rd-to-last continuation byte, check undefined
            return (nextByte & 0xF0) == 0x80 ? currentState << 6 | nextByte & 0x9000003F : -1;
        case 0x90000000: //2nd-to-last continuation byte
            return (nextByte & 0xC0) == 0x80 ? currentState << 6 | nextByte & 0xC000003F : -1;
        case 0xA0000000: //2nd-to-last continuation byte, check overlong
            return (nextByte & 0xE0) == 0xA0 ? currentState << 6 | nextByte & 0xC000003F : -1;
        case 0xB0000000: //2nd-to-last continuation byte, check surrogate
            return (nextByte & 0xE0) == 0x80 ? currentState << 6 | nextByte & 0xC000003F : -1;
        case 0xC0000000: //last continuation byte
            return (nextByte & 0xC0) == 0x80 ? currentState << 6 | nextByte & 0x3F : -1;
        default:
            return -1;
    }
}

Auto-Detect Encoding

If your input stream was encoded using either ASCII or ISO-8859-1 or UTF-8, but you're not sure which, we can use a similar method to the last, but with an additional encoding-detection component to auto-detect the encoding before returning the string.

public static String autoDetect(InputStream is) throws IOException {
    StringBuilder chars = new StringBuilder(Math.max(is.available(), 4096));
    byte[] buffer = new byte[4096];
    int n;
    int state = 0;
    boolean ascii = true;
    while ((n = is.read(buffer)) != -1) {
        for (int i = 0; i < n; i++) {
            if ((state = nextStateUtf8(state, buffer[i])) > 0x7F)
                ascii = false;
            chars.append((char)(buffer[i] & 0xFF));
        }
    }

    if (ascii || state < 0) { //probably not UTF-8
        return chars.toString();
    }
    //probably UTF-8
    int pos = 0;
    char[] charBuf = new char[2];
    for (int i = 0, len = chars.length(); i < len; i++) {
        if ((state = nextStateUtf8(state, (byte)chars.charAt(i))) >= 0) {
            boolean hi = Character.toChars(state, charBuf, 0) == 2;
            chars.setCharAt(pos++, charBuf[0]);
            if (hi) {
                chars.setCharAt(pos++, charBuf[1]);
            }
        }
    }
    return chars.substring(0, pos);
}

If your input stream has an encoding that is neither ISO-8859-1 nor ASCII nor UTF-8, then I defer to the other answers already present.

Is it possible to read from a InputStream with a timeout?

Assuming your stream is not backed by a socket (so you can't use Socket.setSoTimeout()), I think the standard way of solving this type of problem is to use a Future.

Suppose I have the following executor and streams:

    ExecutorService executor = Executors.newFixedThreadPool(2);
    final PipedOutputStream outputStream = new PipedOutputStream();
    final PipedInputStream inputStream = new PipedInputStream(outputStream);

I have writer that writes some data then waits for 5 seconds before writing the last piece of data and closing the stream:

    Runnable writeTask = new Runnable() {
        @Override
        public void run() {
            try {
                outputStream.write(1);
                outputStream.write(2);
                Thread.sleep(5000);
                outputStream.write(3);
                outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    executor.submit(writeTask);

The normal way of reading this is as follows. The read will block indefinitely for data and so this completes in 5s:

    long start = currentTimeMillis();
    int readByte = 1;
    // Read data without timeout
    while (readByte >= 0) {
        readByte = inputStream.read();
        if (readByte >= 0)
            System.out.println("Read: " + readByte);
    }
    System.out.println("Complete in " + (currentTimeMillis() - start) + "ms");

which outputs:

Read: 1
Read: 2
Read: 3
Complete in 5001ms

If there was a more fundamental problem, like the writer not responding, the reader would block for ever. If I wrap the read in a future, I can then control the timeout as follows:

    int readByte = 1;
    // Read data with timeout
    Callable<Integer> readTask = new Callable<Integer>() {
        @Override
        public Integer call() throws Exception {
            return inputStream.read();
        }
    };
    while (readByte >= 0) {
        Future<Integer> future = executor.submit(readTask);
        readByte = future.get(1000, TimeUnit.MILLISECONDS);
        if (readByte >= 0)
            System.out.println("Read: " + readByte);
    }

which outputs:

Read: 1
Read: 2
Exception in thread "main" java.util.concurrent.TimeoutException
    at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:228)
    at java.util.concurrent.FutureTask.get(FutureTask.java:91)
    at test.InputStreamWithTimeoutTest.main(InputStreamWithTimeoutTest.java:74)

I can catch the TimeoutException and do whatever cleanup I want.

Reading a binary input stream into a single byte array in Java

The simplest approach IMO is to use Guava and its ByteStreams class:

byte[] bytes = ByteStreams.toByteArray(in);

Or for a file:

byte[] bytes = Files.toByteArray(file);

Alternatively (if you didn't want to use Guava), you could create a ByteArrayOutputStream, and repeatedly read into a byte array and write into the ByteArrayOutputStream (letting that handle resizing), then call ByteArrayOutputStream.toByteArray().

Note that this approach works whether you can tell the length of your input or not - assuming you have enough memory, of course.

ImportError: No module named 'MySQL'

Try that out bud

sudo wget http://cdn.mysql.com//Downloads/Connector-Python/mysql-connector-python-2.1.3.tar.gz

gunzip mysql-connector-python-2.1.3.tar.gz

tar xf mysql-connector-python-2.1.3.tar

cd mysql-connector-python-2.1.3

sudo python3 setup.py install

How to make a simple rounded button in Storyboard?

You can do something like this:

@IBDesignable class MyButton: UIButton
{
    override func layoutSubviews() {
        super.layoutSubviews()

        updateCornerRadius()
    }

    @IBInspectable var rounded: Bool = false {
        didSet {
            updateCornerRadius()
        }
    }

    func updateCornerRadius() {
        layer.cornerRadius = rounded ? frame.size.height / 2 : 0
    }
}

Set class to MyButton in Identity Inspector and in IB you will have rounded property:

enter image description here

Collection was modified; enumeration operation may not execute

There is one link where it elaborated very well & solution is also given. Try it if you got proper solution please post here so other can understand. Given solution is ok then like the post so other can try these solution.

for you reference original link :- https://bensonxion.wordpress.com/2012/05/07/serializing-an-ienumerable-produces-collection-was-modified-enumeration-operation-may-not-execute/

When we use .Net Serialization classes to serialize an object where its definition contains an Enumerable type, i.e. collection, you will be easily getting InvalidOperationException saying "Collection was modified; enumeration operation may not execute" where your coding is under multi-thread scenarios. The bottom cause is that serialization classes will iterate through collection via enumerator, as such, problem goes to trying to iterate through a collection while modifying it.

First solution, we can simply use lock as a synchronization solution to ensure that the operation to the List object can only be executed from one thread at a time. Obviously, you will get performance penalty that if you want to serialize a collection of that object, then for each of them, the lock will be applied.

Well, .Net 4.0 which makes dealing with multi-threading scenarios handy. for this serializing Collection field problem, I found we can just take benefit from ConcurrentQueue(Check MSDN)class, which is a thread-safe and FIFO collection and makes code lock-free.

Using this class, in its simplicity, the stuff you need to modify for your code are replacing Collection type with it, use Enqueue to add an element to the end of ConcurrentQueue, remove those lock code. Or, if the scenario you are working on do require collection stuff like List, you will need a few more code to adapt ConcurrentQueue into your fields.

BTW, ConcurrentQueue doesnât have a Clear method due to underlying algorithm which doesnât permit atomically clearing of the collection. so you have to do it yourself, the fastest way is to re-create a new empty ConcurrentQueue for a replacement.

How to get a parent element to appear above child

Some of these answers do work, but setting position: absolute; and z-index: 10; seemed pretty strong just to achieve the required effect. I found the following was all that was required, though unfortunately, I've not been able to reduce it any further.

HTML:

<div class="wrapper">
    <div class="parent">
        <div class="child">
            ...
        </div>
    </div>
</div>

CSS:

.wrapper {
    position: relative;
    z-index: 0;
}

.child {
    position: relative;
    z-index: -1;
}

I used this technique to achieve a bordered hover effect for image links. There's a bit more code here but it uses the concept above to show the border over the top of the image.

http://jsfiddle.net/g7nP5/

How to do case insensitive search in Vim

You can use in your vimrc those commands:

  • set ignorecase - All your searches will be case insensitive
  • set smartcase - Your search will be case sensitive if it contains an uppercase letter

You need to set ignorecase if you want to use what smartcase provides.

I wrote recently an article about Vim search commands (both built in command and the best plugins to search efficiently).

Swift alert view with OK and Cancel: which button tapped?

You can easily do this by using UIAlertController

let alertController = UIAlertController(
       title: "Your title", message: "Your message", preferredStyle: .alert)
let defaultAction = UIAlertAction(
       title: "Close Alert", style: .default, handler: nil)
//you can add custom actions as well 
alertController.addAction(defaultAction)

present(alertController, animated: true, completion: nil)

.

Reference: iOS Show Alert

Getting list of Facebook friends with latest API

friends.get

Is function to get a list of friend's

And yes this is best

    $friends = $facebook->api('/me/friends');

    echo '<ul>';
    foreach ($friends["data"] as $value) {
        echo '<li>';
        echo '<div class="pic">';
        echo '<img src="https://graph.facebook.com/' . $value["id"] . '/picture"/>';
        echo '</div>';
        echo '<div class="picName">'.$value["name"].'</div>'; 
        echo '</li>';
    }
    echo '</ul>';

How to make Unicode charset in cmd.exe by default?

Open an elevated Command Prompt (run cmd as administrator). query your registry for available TT fonts to the console by:

    REG query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont"

You'll see an output like :

    0    REG_SZ    Lucida Console
    00    REG_SZ    Consolas
    936    REG_SZ    *???
    932    REG_SZ    *MS ????

Now we need to add a TT font that supports the characters you need like Courier New, we do this by adding zeros to the string name, so in this case the next one would be "000" :

    REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont" /v 000 /t REG_SZ /d "Courier New"

Now we implement UTF-8 support:

    REG ADD HKCU\Console /v CodePage /t REG_DWORD /d 65001 /f

Set default font to "Courier New":

    REG ADD HKCU\Console /v FaceName /t REG_SZ /d "Courier New" /f

Set font size to 20 :

    REG ADD HKCU\Console /v FontSize /t REG_DWORD /d 20 /f

Enable quick edit if you like :

    REG ADD HKCU\Console /v QuickEdit /t REG_DWORD /d 1 /f

CSS centred header image

If you set the margin to be margin:0 auto the image will be centered.

This will give top + bottom a margin of 0, and left and right a margin of 'auto'. Since the div has a width (200px), the image will be 200px wide and the browser will auto set the left and right margin to half of what is left on the page, which will result in the image being centered.

Visual Studio Expand/Collapse keyboard shortcuts

Go to Tools->Options->Text Editor->c#->Advanced and uncheck the first checkbox Enter outlining mode when files open.

This will solve this problem forever

Solution to INSTALL_FAILED_INSUFFICIENT_STORAGE error on Android

If you're using a real device, you've simply run out of internal memory. Just go to Android settings -> Applications, and move some apps to the SD card or uninstall some apps.

If you're using the emulator, see RacZo's answer.

GoogleTest: How to skip a test?

I prefer to do it in code:

// Run a specific test only
//testing::GTEST_FLAG(filter) = "MyLibrary.TestReading"; // I'm testing a new feature, run something quickly

// Exclude a specific test
testing::GTEST_FLAG(filter) = "-MyLibrary.TestWriting"; // The writing test is broken, so skip it

I can either comment out both lines to run all tests, uncomment out the first line to test a single feature that I'm investigating/working on, or uncomment the second line if a test is broken but I want to test everything else.
You can also test/exclude a suite of features by using wildcards and writing a list, "MyLibrary.TestNetwork*" or "-MyLibrary.TestFileSystem*".

How to call multiple JavaScript functions in onclick event?

Sure, simply bind multiple listeners to it.

Short cutting with jQuery

_x000D_
_x000D_
$("#id").bind("click", function() {_x000D_
  alert("Event 1");_x000D_
});_x000D_
$(".foo").bind("click", function() {_x000D_
  alert("Foo class");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="foo" id="id">Click</div>
_x000D_
_x000D_
_x000D_

Converting a Java Keystore into PEM Format

In case you don't have openssl installed and you are looking for a quick solution, there is software called portcle which is very useful and small to download.

The disadvantage is that there is no command line as far as I know. But from the GUI, it is pretty straight forward to export a PEM private key:

  1. Open you JKS key store
  2. Right click over your private key entry and select export
  3. Select Private Key and certificates and PEM format

    Export PEM private key from JKS with Portcle

How to input automatically when running a shell over SSH?

ssh-key with passphrase, with keychain

keychain is a small utility which manages ssh-agent on your behalf and allows the ssh-agent to remain running when the login session ends. On subsequent logins, keychain will connect to the existing ssh-agent instance. In practice, this means that the passphrase must be be entered only during the first login after a reboot. On subsequent logins, the unencrypted key from the existing ssh-agent instance is used. This can also be useful for allowing passwordless RSA/DSA authentication in cron jobs without passwordless ssh-keys.

To enable keychain, install it and add something like the following to ~/.bash_profile:

eval keychain --agents ssh --eval id_rsa From a security point of view, ssh-ident and keychain are worse than ssh-agent instances limited to the lifetime of a particular session, but they offer a high level of convenience. To improve the security of keychain, some people add the --clear option to their ~/.bash_profile keychain invocation. By doing this passphrases must be re-entered on login as above, but cron jobs will still have access to the unencrypted keys after the user logs out. The keychain wiki page has more information and examples.

Got this info from;

https://unix.stackexchange.com/questions/90853/how-can-i-run-ssh-add-automatically-without-password-prompt

Hope this helps

I have personally been able to automatically enter my passphrase upon terminal launch by doing this: (you can, of course, modify the script and fit it to your needs)

  1. edit the bashrc file to add this script;

    Check if the SSH agent is awake

    if [ -z "$SSH_AUTH_SOCK" ] ; then exec ssh-agent bash -c "ssh-add ; $0" echo "The SSH agent was awakened" exit fi

    Above line will start the expect script upon terminal launch.

    ./ssh.exp

here's the content of this expect script

#!/usr/bin/expect

set timeout 20

set passphrase "test"

spawn "./keyadding.sh"

expect "Enter passphrase for /the/path/of/yourkey_id_rsa:"

send "$passphrase\r";

interact

Here's the content of my keyadding.sh script (you must put both scripts in your home folder, usually /home/user)

#!/bin/bash

ssh-add /the/path/of/yourkey_id_rsa

exit 0

I would HIGHLY suggest encrypting the password on the .exp script as well as renaming this .exp file to something like term_boot.exp or whatever else for security purposes. Don't forget to create the files directly from the terminal using nano or vim (ex: nano ~/.bashrc | nano term_boot.exp) and also a chmod +x script.sh to make it executable. A chmod +r term_boot.exp would be also useful but you'll have to add sudo before ./ssh.exp in your bashrc file. So you'll have to enter your sudo password each time you launch your terminal. For me, it's more convenient than the passphrase cause I remember my admin (sudo) password by the hearth.

Also, here's another way to do it I think; https://www.cyberciti.biz/faq/noninteractive-shell-script-ssh-password-provider/

Will certainly change my method for this one when I'll have the time.

What's the difference between F5 refresh and Shift+F5 in Google Chrome browser?

It ignores the cached content when refreshing...

https://support.google.com/a/answer/3001912?hl=en

F5 or Control + R = Reload the current page
Control+Shift+R or Shift + F5 = Reload your current page, ignoring cached content

span with onclick event inside a tag

I would use jQuery to get the results that you're looking for. You wouldn't need to use an anchor tag at that point but if you did it would look like:

<a href="page" style="text-decoration:none;display:block;">

<span onclick="hide()">Hide me</span>

</a>

<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.2.min.js' /
<script type='text/javascript'>
$(document).ready(function(){
     $('span').click(function(){
           $(this).hide();
     }
}

How to assign a select result to a variable?

In order to assign a variable safely you have to use the SET-SELECT statement:

SET @PrimaryContactKey = (SELECT c.PrimaryCntctKey
    FROM tarcustomer c, tarinvoice i
    WHERE i.custkey = c.custkey 
    AND i.invckey = @tmp_key)

Make sure you have both a starting and an ending parenthesis!

The reason the SET-SELECT version is the safest way to set a variable is twofold.

1. The SELECT returns several posts

What happens if the following select results in several posts?

SELECT @PrimaryContactKey = c.PrimaryCntctKey
FROM tarcustomer c, tarinvoice i
WHERE i.custkey = c.custkey 
    AND i.invckey = @tmp_key

@PrimaryContactKey will be assigned the value from the last post in the result.

In fact @PrimaryContactKey will be assigned one value per post in the result, so it will consequently contain the value of the last post the SELECT-command was processing.

Which post is "last" is determined by any clustered indexes or, if no clustered index is used or the primary key is clustered, the "last" post will be the most recently added post. This behavior could, in a worst case scenario, be altered every time the indexing of the table is changed.

With a SET-SELECT statement your variable will be set to null.

2. The SELECT returns no posts

What happens, when using the second version of the code, if your select does not return a result at all?

In a contrary to what you may believe the value of the variable will not be null - it will retain it's previous value!

This is because, as stated above, SQL will assign a value to the variable once per post - meaning it won't do anything with the variable if the result contains no posts. So, the variable will still have the value it had before you ran the statement.

With the SET-SELECT statement the value will be null.

See also: SET versus SELECT when assigning variables?

Check if an element is a child of a parent

.has() seems to be designed for this purpose. Since it returns a jQuery object, you have to test for .length as well:

if ($('div#hello').has(target).length) {
   alert('Target is a child of #hello');
}

VHDL - How should I create a clock in a testbench?

My favoured technique:

signal clk : std_logic := '0'; -- make sure you initialise!
...
clk <= not clk after half_period;

I usually extend this with a finished signal to allow me to stop the clock:

clk <= not clk after half_period when finished /= '1' else '0';

Gotcha alert: Care needs to be taken if you calculate half_period from another constant by dividing by 2. The simulator has a "time resolution" setting, which often defaults to nanoseconds... In which case, 5 ns / 2 comes out to be 2 ns so you end up with a period of 4ns! Set the simulator to picoseconds and all will be well (until you need fractions of a picosecond to represent your clock time anyway!)

Authenticating in PHP using LDAP through Active Directory

I do this simply by passing the user credentials to ldap_bind().

http://php.net/manual/en/function.ldap-bind.php

If the account can bind to LDAP, it's valid; if it can't, it's not. If all you're doing is authentication (not account management), I don't see the need for a library.

Read entire file in Scala?

You can use

Source.fromFile(fileName).getLines().mkString

however it should be noticed that getLines() removes all new line characters. If you want save formatting you should use

Source.fromFile(fileName).iter.mkString

How to insert a data table into SQL Server database table?

I found that it was better to add to the table row by row if your table has a primary key. Inserting the entire table at once creates a conflict on the auto increment.

Here's my stored Proc

CREATE PROCEDURE dbo.usp_InsertRowsIntoTable
@Year       int,
@TeamName   nvarchar(50),
AS
INSERT INTO [dbo.TeamOverview]
(Year,TeamName)
VALUES (@Year, @TeamName);
RETURN

I put this code in a loop for every row that I need to add to my table:

insertRowbyRowIntoTable(Convert.ToInt16(ddlChooseYear.SelectedValue), name);

And here is my Data Access Layer code:

        public void insertRowbyRowIntoTable(int ddlValue, string name)
    { 
        SqlConnection cnTemp = null;
        string spName = null;
        SqlCommand sqlCmdInsert = null;

        try
        {
            cnTemp = helper.GetConnection();
            using (SqlConnection connection = cnTemp)
            {
                if (cnTemp.State != ConnectionState.Open)
                    cnTemp.Open();
                using (sqlCmdInsert = new SqlCommand(spName, cnTemp))
                {
                    spName = "dbo.usp_InsertRowsIntoOverview";
                    sqlCmdInsert = new SqlCommand(spName, cnTemp);
                    sqlCmdInsert.CommandType = CommandType.StoredProcedure;

                    sqlCmdInsert.Parameters.AddWithValue("@Year", ddlValue);
                    sqlCmdInsert.Parameters.AddWithValue("@TeamName", name);

                    sqlCmdInsert.ExecuteNonQuery();

                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            if (sqlCmdInsert != null)
                sqlCmdInsert.Dispose();

            if (cnTemp.State == ConnectionState.Open)
                cnTemp.Close();
        }

    }

python-How to set global variables in Flask?

With:

global index_add_counter

You are not defining, just declaring so it's like saying there is a global index_add_counter variable elsewhere, and not create a global called index_add_counter. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global keyword and initialize your variable:

index_add_counter = 0

Now you can import it with:

from app import index_add_counter

The construction:

global index_add_counter

is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:

index_add_counter = 0
def test():
  global index_add_counter # means: in this scope, use the global name
  print(index_add_counter)

Clearing NSUserDefaults

Did you try using -removeObjectForKey?

 [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"defunctPreference"];

About "*.d.ts" in TypeScript

The "d.ts" file is used to provide typescript type information about an API that's written in JavaScript. The idea is that you're using something like jQuery or underscore, an existing javascript library. You want to consume those from your typescript code.

Rather than rewriting jquery or underscore or whatever in typescript, you can instead write the d.ts file, which contains only the type annotations. Then from your typescript code you get the typescript benefits of static type checking while still using a pure JS library.

How to save a spark DataFrame as csv on disk?

I had similar problem. I needed to write down csv file on driver while I was connect to cluster in client mode.

I wanted to reuse the same CSV parsing code as Apache Spark to avoid potential errors.

I checked spark-csv code and found code responsible for converting dataframe into raw csv RDD[String] in com.databricks.spark.csv.CsvSchemaRDD.

Sadly it is hardcoded with sc.textFile and the end of relevant method.

I copy-pasted that code and removed last lines with sc.textFile and returned RDD directly instead.

My code:

/*
  This is copypasta from com.databricks.spark.csv.CsvSchemaRDD
  Spark's code has perfect method converting Dataframe -> raw csv RDD[String]
  But in last lines of that method it's hardcoded against writing as text file -
  for our case we need RDD.
 */
object DataframeToRawCsvRDD {

  val defaultCsvFormat = com.databricks.spark.csv.defaultCsvFormat

  def apply(dataFrame: DataFrame, parameters: Map[String, String] = Map())
           (implicit ctx: ExecutionContext): RDD[String] = {
    val delimiter = parameters.getOrElse("delimiter", ",")
    val delimiterChar = if (delimiter.length == 1) {
      delimiter.charAt(0)
    } else {
      throw new Exception("Delimiter cannot be more than one character.")
    }

    val escape = parameters.getOrElse("escape", null)
    val escapeChar: Character = if (escape == null) {
      null
    } else if (escape.length == 1) {
      escape.charAt(0)
    } else {
      throw new Exception("Escape character cannot be more than one character.")
    }

    val quote = parameters.getOrElse("quote", "\"")
    val quoteChar: Character = if (quote == null) {
      null
    } else if (quote.length == 1) {
      quote.charAt(0)
    } else {
      throw new Exception("Quotation cannot be more than one character.")
    }

    val quoteModeString = parameters.getOrElse("quoteMode", "MINIMAL")
    val quoteMode: QuoteMode = if (quoteModeString == null) {
      null
    } else {
      QuoteMode.valueOf(quoteModeString.toUpperCase)
    }

    val nullValue = parameters.getOrElse("nullValue", "null")

    val csvFormat = defaultCsvFormat
      .withDelimiter(delimiterChar)
      .withQuote(quoteChar)
      .withEscape(escapeChar)
      .withQuoteMode(quoteMode)
      .withSkipHeaderRecord(false)
      .withNullString(nullValue)

    val generateHeader = parameters.getOrElse("header", "false").toBoolean
    val headerRdd = if (generateHeader) {
      ctx.sparkContext.parallelize(Seq(
        csvFormat.format(dataFrame.columns.map(_.asInstanceOf[AnyRef]): _*)
      ))
    } else {
      ctx.sparkContext.emptyRDD[String]
    }

    val rowsRdd = dataFrame.rdd.map(row => {
      csvFormat.format(row.toSeq.map(_.asInstanceOf[AnyRef]): _*)
    })

    headerRdd union rowsRdd
  }

}

How do I print out the contents of a vector?

You can use an iterator:

std::vector<char> path;
// ...
for (std::vector<char>::const_iterator i = path.begin(); i != path.end(); ++i)
    std::cout << *i << ' ';

If you want to modify the vector's contents in the for loop, then use iterator rather than const_iterator.

But there's lots more that can be said about this. If you just want an answer you can use, then you can stop here; otherwise, read on.

auto (C++11) / typedef / type alias (C++11)

This is not another solution, but a supplement to the above iterator solution. If you are using the C++11 standard (or later), then you can use the auto keyword to help the readability:

for (auto i = path.begin(); i != path.end(); ++i)
    std::cout << *i << ' ';

But the type of i will be non-const (i.e., the compiler will use std::vector<char>::iterator as the type of i).

In this case, you might as well just use a typedef, which also brings with it its own benefits (which I won't expound upon here):

typedef std::vector<char> Path; // 'Path' now a synonym for the vector
Path path;
// ...
for (Path::const_iterator i = path.begin(); i != path.end(); ++i)
    std::cout << *i << ' ';

C++11 also introduced a type alias, which does the same job as a typedef and you may find more readable than using typedef:

using Path = std::vector<char>; // C++11 onwards only
Path path;
// ...
for (Path::const_iterator i = path.begin(); i != path.end(); ++i)
    std::cout << *i << ' ';

counter

You can, of course, use a integer type to record your position in the for loop:

for(int i=0; i<path.size(); ++i)
  std::cout << path[i] << ' ';

If you are going to do this, it's better to use the container's member types, if they are available and appropriate. std::vector has a member type called size_type for this job: it is the type returned by the size method.

// Path typedef'd to std::vector<char>
for( Path::size_type i=0; i<path.size(); ++i)
  std::cout << path[i] << ' ';

Why not just use this over the iterator solution? For simple cases you might as well, but the point is that an iterator is an object designed to do this job for more complicated objects where this solution is not going to be ideal.

range-based for loop (C++11)

See Jefffrey's solution. In C++11 (and later) you can use the new range-based for loop, which looks like this:

for (auto i: path)
  std::cout << i << ' ';

Since path is a vector of items (explicitly std::vector<char>), the object i is of type of the item of the vector (i.e., explicitly, it is of type char). The object i has a value that is a copy of the actual item in the path object. Thus, all changes to i in the loop are not preserved in path itself. Additionally, if you would like to enforce the fact that you don't want to be able to change the copied value of i in the loop, you can force the type of i to be const char like this:

for (const auto i: path)
  std::cout << i << ' ';

If you would like to modify the items in path, you can use a reference:

for (auto& i: path)
  std::cout << i << ' ';

and even if you don't want to modify path, if the copying of objects is expensive you should use a const reference instead of copying by value:

for (const auto& i: path)
  std::cout << i << ' ';

std::copy (C++11)

See Joshua's answer. You can use the STL algorithm std::copy to copy the vector contents onto the output stream. This is an elegant solution if you are comfortable with it. Getting more familiar with STL algorithms should be encouraged, and they provide a lot of functionality that beginners may fall into reinventing themselves. Read Joshua's post for more info.

overload std::ostream::operator<<

See Chris's answer, this is more a complement to the other answers since you will still need to implement one of the solutions above in the overloading. In his example he used a counter in a for loop. For example, this is how you could quickly use Joshua's solution:

#include <iterator> // needed for std::ostram_iterator

template <typename T>
std::ostream& operator<< (std::ostream& out, const std::vector<T>& v) {
  if ( !v.empty() ) {
    out << '[';
    std::copy (v.begin(), v.end(), std::ostream_iterator<T>(out, ", "));
    out << "\b\b]";
  }
  return out;
}

Using any of the other solutions should be equally straightforward.

conclusion

Any of the solutions presented here will work. It's up to you and the code on which one is the "best". Anything more detailed than this is probably best left for another question where the pros/cons can be properly evaluated; but as always user preference will always play a part: none of the solutions presented are wrong, but some will look nicer to each individual coder.

addendum

This is an expanded solution of an earlier one I posted. Since that post kept getting attention, I decided to expand on it and refer to the other excellent solutions that were posted here. My original post had a remark that mentioned that if you were intending on modifying your vector inside a for loop then there are two methods provided by std::vector to access elements: std::vector::operator[] which does not do bounds checking, and std::vector::at which does perform bounds checking. In other words, at will throw if you try to access an element outside the vector and operator[] wouldn't. I only added this comment, originally, for the sake of mentioning something that it might be useful to know of if anyone already didn't. And I see no difference now. Hence this addendum.

Iterate through dictionary values?

You can just look for the value that corresponds with the key and then check if the input is equal to the key.

for key in PIX0:
    NUM = input("Which standard has a resolution of %s " % PIX0[key])
    if NUM == key:

Also, you will have to change the last line to fit in, so it will print the key instead of the value if you get the wrong answer.

print("I'm sorry but thats wrong. The correct answer was: %s." % key )

Also, I would recommend using str.format for string formatting instead of the % syntax.

Your full code should look like this (after adding in string formatting)

PIX0 = {"QVGA":"320x240", "VGA":"640x480", "SVGA":"800x600"}

for key in PIX0:
    NUM = input("Which standard has a resolution of {}".format(PIX0[key]))
    if NUM == key:
        print ("Nice Job!")
        count = count + 1
    else:
        print("I'm sorry but that's wrong. The correct answer was: {}.".format(key))

Python: URLError: <urlopen error [Errno 10060]

This is because of the proxy settings. I also had the same problem, under which I could not use any of the modules which were fetching data from the internet. There are simple steps to follow:
1. open the control panel
2. open internet options
3. under connection tab open LAN settings
4. go to advance settings and unmark everything, delete every proxy in there. Or u can just unmark the checkbox in proxy server this will also do the same
5. save all the settings by clicking ok.
you are done. try to run the programme again, it must work it worked for me at least

Cannot bulk load. Operating system error code 5 (Access is denied.)

This error appears when you are using SQL Server Authentication and SQL Server is not allowed to access the bulk load folder.

So giving SQL server access to the folder will solve the issue. enter image description here

Here is how to: Go to the folder right click ->properties->Security tab->Edit->Add(on the new window) ->Advanced -> Find Now. Under the users list in the search results, find something like SQLServerMSSQLUser$UserName$SQLExpress and click ok, to all the dialogs opened.

MySQL: Quick breakdown of the types of joins

Full Outer join don't exist in mysql , you might need to use a combination of left and right join.

Spring Boot Multiple Datasource

Update 2018-01-07 with Spring Boot 1.5.8.RELEASE

If you want to know how to config it, how to use it, and how to control transaction. I may have answers for you.

You can see the runnable example and some explanation in https://www.surasint.com/spring-boot-with-multiple-databases-example/

I copied some code here.

First you have to set application.properties like this

#Database
database1.datasource.url=jdbc:mysql://localhost/testdb
database1.datasource.username=root
database1.datasource.password=root
database1.datasource.driver-class-name=com.mysql.jdbc.Driver

database2.datasource.url=jdbc:mysql://localhost/testdb2
database2.datasource.username=root
database2.datasource.password=root
database2.datasource.driver-class-name=com.mysql.jdbc.Driver

Then define them as providers (@Bean) like this:

@Bean(name = "datasource1")
@ConfigurationProperties("database1.datasource")
@Primary
public DataSource dataSource(){
    return DataSourceBuilder.create().build();
}

@Bean(name = "datasource2")
@ConfigurationProperties("database2.datasource")
public DataSource dataSource2(){
    return DataSourceBuilder.create().build();
}

Note that I have @Bean(name="datasource1") and @Bean(name="datasource2"), then you can use it when we need datasource as @Qualifier("datasource1") and @Qualifier("datasource2") , for example

@Qualifier("datasource1")
@Autowired
private DataSource dataSource;

If you do care about transaction, you have to define DataSourceTransactionManager for both of them, like this:

@Bean(name="tm1")
@Autowired
@Primary
DataSourceTransactionManager tm1(@Qualifier ("datasource1") DataSource datasource) {
    DataSourceTransactionManager txm  = new DataSourceTransactionManager(datasource);
    return txm;
}

@Bean(name="tm2")
@Autowired
DataSourceTransactionManager tm2(@Qualifier ("datasource2") DataSource datasource) {
    DataSourceTransactionManager txm  = new DataSourceTransactionManager(datasource);
    return txm;
}

Then you can use it like

@Transactional //this will use the first datasource because it is @primary

or

@Transactional("tm2")

This should be enough. See example and detail in the link above.

Could not create work tree dir 'example.com'.: Permission denied

use this for all user

sudo chown -R $(whoami):$(whoami) /var/..

Setting a system environment variable from a Windows batch file?

For XP, I used a (free/donateware) tool called "RAPIDEE" (Rapid Environment Editor), but SETX is definitely sufficient for Win 7 (I did not know about this before).

Winforms issue - Error creating window handle

Have you run Process Explorer or the Windows Task Manager to look at the GDI Objects, Handles, Threads and USER objects? If not, select those columns to be viewed (Task Manager choose View->Select Columns... Then run your app and take a look at those columns for that app and see if one of those is growing really large.

It might be that you've got UI components that you think are cleaned up but haven't been Disposed.

Here's a link about this that might be helpful.

Good Luck!

Remove portion of a string after a certain character

If you're using PHP 5.3+ take a look at the $before_needle flag of strstr()

$s = 'Posted On April 6th By Some Dude';
echo strstr($s, 'By', true);

Why does background-color have no effect on this DIV?

Floats don't have a height so the containing div has a height of zero.

<div style="background-color:black; overflow:hidden;zoom:1" onmouseover="this.bgColor='white'">
<div style="float:left">hello</div>
<div style="float:right">world</div>
</div>

overflow:hidden clears the float for most browsers.

zoom:1 clears the float for IE.

REST API Best practices: Where to put parameters?

As per the REST Implementation,

1) Path variables are used for the direct action on the resources, like a contact or a song ex..
GET etc /api/resource/{songid} or
GET etc /api/resource/{contactid} will return respective data.

2) Query perms/argument are used for the in-direct resources like metadata of a song ex.., GET /api/resource/{songid}?metadata=genres it will return the genres data for that particular song.

How to read HDF5 files in Python

Using bits of answers from this question and the latest doc, I was able to extract my numerical arrays using

import h5py
with h5py.File(filename, 'r') as h5f:
    h5x = h5f[list(h5f.keys())[0]]['x'][()]

Where 'x' is simply the X coordinate in my case.

PHP move_uploaded_file() error?

On virtual hosting check your disk quota.

if quota exceed, move_uploaded_file return error.

PS : I've been looking for this for a long time :)

Python: create dictionary using dict() with integer keys?

a = dict(one=1, two=2, three=3)

Providing keyword arguments as in this example only works for keys that are valid Python identifiers. Otherwise, any valid keys can be used.

How to display HTML tags as plain text

You should use htmlspecialchars. It replaces characters as below:

  • & (ampersand) becomes &amp;
  • " (double quote) becomes &quot; when ENT_NOQUOTES is not set.
  • ' (single quote) becomes &#039; only when ENT_QUOTES is set.
  • < (less than) becomes &lt;
  • > (greater than) becomes &gt;

Converting List<Integer> to List<String>

Lambdaj allows to do that in a very simple and readable way. For example, supposing you have a list of Integer and you want to convert them in the corresponding String representation you could write something like that;

List<Integer> ints = asList(1, 2, 3, 4);
Iterator<String> stringIterator = convertIterator(ints, new Converter<Integer, String> {
    public String convert(Integer i) { return Integer.toString(i); }
}

Lambdaj applies the conversion function only while you're iterating on the result.

How to reload a page using Angularjs?

Be sure to include the $route service into your scope and do this:

$route.reload();

See this:

How to reload or re-render the entire page using AngularJS

How to call a method after a delay in Android

If you have to use the Handler, but you are into another thread, you can use runonuithread to run the handler in UI thread. This will save you from Exceptions thrown asking to call Looper.Prepare()

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //Do something after 1 second
            }
        }, 1000);
    }
});

Looks quite messy, but this is one of the way.

Remove NaN from pandas series

>>> s = pd.Series([1,2,3,4,np.NaN,5,np.NaN])
>>> s[~s.isnull()]
0    1
1    2
2    3
3    4
5    5

update or even better approach as @DSM suggested in comments, using pandas.Series.dropna():

>>> s.dropna()
0    1
1    2
2    3
3    4
5    5

Python slice first and last element in list

What about this?

>>> first_element, last_element = some_list[0], some_list[-1]

MySQL match() against() - order by relevance and column?

I was just playing around with this, too. One way you can add extra weight is in the ORDER BY area of the code.

For example, if you were matching 3 different columns and wanted to more heavily weight certain columns:

SELECT search.*,
MATCH (name) AGAINST ('black' IN BOOLEAN MODE) AS name_match,
MATCH (keywords) AGAINST ('black' IN BOOLEAN MODE) AS keyword_match,
MATCH (description) AGAINST ('black' IN BOOLEAN MODE) AS description_match
FROM search
WHERE MATCH (name, keywords, description) AGAINST ('black' IN BOOLEAN MODE)
ORDER BY (name_match * 3  + keyword_match * 2  + description_match) DESC LIMIT 0,100;

Node.js Best Practice Exception Handling

You can catch uncaught exceptions, but it's of limited use. See http://debuggable.com/posts/node-js-dealing-with-uncaught-exceptions:4c933d54-1428-443c-928d-4e1ecbdd56cb

monit, forever or upstart can be used to restart node process when it crashes. A graceful shutdown is best you can hope for (e.g. save all in-memory data in uncaught exception handler).

const char* concatenation

One more example:

// calculate the required buffer size (also accounting for the null terminator):
int bufferSize = strlen(one) + strlen(two) + 1;

// allocate enough memory for the concatenated string:
char* concatString = new char[ bufferSize ];

// copy strings one and two over to the new buffer:
strcpy( concatString, one );
strcat( concatString, two );

...

// delete buffer:
delete[] concatString;

But unless you specifically don't want or can't use the C++ standard library, using std::string is probably safer.

How to wrap text of HTML button with fixed width?

Multi-line buttons like that are not really trivial to implement. This page has an interesting (though somewhat dated) discussion on the subject. Your best bet would probably be to either drop the multi-line requirement or to create a custom button using e.g. divs and CSS, and adding some JavaScript to make it work as a button.

Volatile boolean vs AtomicBoolean

If you have only one thread modifying your boolean, you can use a volatile boolean (usually you do this to define a stop variable checked in the thread's main loop).

However, if you have multiple threads modifying the boolean, you should use an AtomicBoolean. Else, the following code is not safe:

boolean r = !myVolatileBoolean;

This operation is done in two steps:

  1. The boolean value is read.
  2. The boolean value is written.

If an other thread modify the value between #1 and 2#, you might got a wrong result. AtomicBoolean methods avoid this problem by doing steps #1 and #2 atomically.

Generate C# class from XML

I realise that this is a rather old post and you have probably moved on.

But I had the same problem as you so I decided to write my own program.

The problem with the "xml -> xsd -> classes" route for me was that it just generated a lump of code that was completely unmaintainable and I ended up turfing it.

It is in no way elegant but it did the job for me.

You can get it here: Please make suggestions if you like it.

SimpleXmlToCode

How can I pass command-line arguments to a Perl program?

If you just want some values, you can just use the @ARGV array. But if you are looking for something more powerful in order to do some command line options processing, you should use Getopt::Long.

cut or awk command to print first field of first row

try this:

head -1 /etc/*release | awk '{print $1}'

Good Hash Function for Strings

This will avoid any collision and it will be fast until we use the shifting in calculations.

 int k = key.length();
    int sum = 0;
    for(int i = 0 ; i < k-1 ; i++){
        sum += key.charAt(i)<<(5*i);
    }

Round up double to 2 decimal places

Updated to SWIFT 4 and the proper answer for the question

If you want to round up to 2 decimal places you should multiply with 100 then round it off and then divide by 100

var x = 1.5657676754 
var y = (x*100).rounded()/100
print(y)  // 1.57 

How do I kill this tomcat process in Terminal?

ps -Af | grep "tomcat" | grep -v grep | awk '{print$2}' | xargs kill -9

How to get JSON response from http.Get

The results from json.Unmarshal (into var data interface{}) do not directly match your Go type and variable declarations. For example,

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "os"
)

type Tracks struct {
    Toptracks []Toptracks_info
}

type Toptracks_info struct {
    Track []Track_info
    Attr  []Attr_info
}

type Track_info struct {
    Name       string
    Duration   string
    Listeners  string
    Mbid       string
    Url        string
    Streamable []Streamable_info
    Artist     []Artist_info
    Attr       []Track_attr_info
}

type Attr_info struct {
    Country    string
    Page       string
    PerPage    string
    TotalPages string
    Total      string
}

type Streamable_info struct {
    Text      string
    Fulltrack string
}

type Artist_info struct {
    Name string
    Mbid string
    Url  string
}

type Track_attr_info struct {
    Rank string
}

func get_content() {
    // json data
    url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"
    url += "&limit=1" // limit data for testing
    res, err := http.Get(url)
    if err != nil {
        panic(err.Error())
    }
    body, err := ioutil.ReadAll(res.Body)
    if err != nil {
        panic(err.Error())
    }
    var data interface{} // TopTracks
    err = json.Unmarshal(body, &data)
    if err != nil {
        panic(err.Error())
    }
    fmt.Printf("Results: %v\n", data)
    os.Exit(0)
}

func main() {
    get_content()
}

Output:

Results: map[toptracks:map[track:map[name:Get Lucky (feat. Pharrell Williams) listeners:1863 url:http://www.last.fm/music/Daft+Punk/_/Get+Lucky+(feat.+Pharrell+Williams) artist:map[name:Daft Punk mbid:056e4f3e-d505-4dad-8ec1-d04f521cbb56 url:http://www.last.fm/music/Daft+Punk] image:[map[#text:http://userserve-ak.last.fm/serve/34s/88137413.png size:small] map[#text:http://userserve-ak.last.fm/serve/64s/88137413.png size:medium] map[#text:http://userserve-ak.last.fm/serve/126/88137413.png size:large] map[#text:http://userserve-ak.last.fm/serve/300x300/88137413.png size:extralarge]] @attr:map[rank:1] duration:369 mbid: streamable:map[#text:1 fulltrack:0]] @attr:map[country:Netherlands page:1 perPage:1 totalPages:500 total:500]]]

How to change color in circular progress bar?

check this answer out:

for me, these two lines had to be there for it to work and change the color:

android:indeterminateTint="@color/yourColor"
android:indeterminateTintMode="src_in"

PS: but its only available from android 21

How do I create batch file to rename large number of files in a folder?

dir /b *.jpg >file.bat

This will give you lines such as:

Vacation2010 001.jpg
Vacation2010 002.jpg
Vacation2010 003.jpg

Edit file.bat in your favorite Windows text-editor, doing the equivalent of:

s/Vacation2010(.+)/rename "&" "December \1"/

That's a regex; many editors support them, but none that come default with Windows (as far as I know). You can also get a command line tool such as sed or perl which can take the exact syntax I have above, after escaping for the command line.

The resulting lines will look like:

rename "Vacation2010 001.jpg" "December 001.jpg"
rename "Vacation2010 002.jpg" "December 002.jpg"
rename "Vacation2010 003.jpg" "December 003.jpg"

You may recognize these lines as rename commands, one per file from the original listing. ;) Run that batch file in cmd.exe.

List Highest Correlation Pairs from a Large Correlation Matrix in Pandas?

You can use DataFrame.values to get an numpy array of the data and then use NumPy functions such as argsort() to get the most correlated pairs.

But if you want to do this in pandas, you can unstack and sort the DataFrame:

import pandas as pd
import numpy as np

shape = (50, 4460)

data = np.random.normal(size=shape)

data[:, 1000] += data[:, 2000]

df = pd.DataFrame(data)

c = df.corr().abs()

s = c.unstack()
so = s.sort_values(kind="quicksort")

print so[-4470:-4460]

Here is the output:

2192  1522    0.636198
1522  2192    0.636198
3677  2027    0.641817
2027  3677    0.641817
242   130     0.646760
130   242     0.646760
1171  2733    0.670048
2733  1171    0.670048
1000  2000    0.742340
2000  1000    0.742340
dtype: float64

Why does the C++ STL not provide any "tree" containers?

In a way, std::map is a tree (it is required to have the same performance characteristics as a balanced binary tree) but it doesn't expose other tree functionality. The likely reasoning behind not including a real tree data structure was probably just a matter of not including everything in the stl. The stl can be looked as a framework to use in implementing your own algorithms and data structures.

In general, if there's a basic library functionality that you want, that's not in the stl, the fix is to look at BOOST.

Otherwise, there's a bunch of libraries out there, depending on the needs of your tree.

Maximum number of rows in an MS Access database engine table?

We're not necessarily talking theoretical limits here, we're talking about real world limits of the 2GB max file size AND database schema.

  • Is your db a single table or multiple?
  • How many columns does each table have?
  • What are the datatypes?

The schema is on even footing with the row count in determining how many rows you can have.

We have used Access MDBs to store exports of MS-SQL data for statistical analysis by some of our corporate users. In those cases we've exported our core table structure, typically four tables with 20 to 150 columns varying from a hundred bytes per row to upwards of 8000 bytes per row. In these cases, we would bump up against a few hundred thousand rows of data were permissible PER MDB that we would ship them.

So, I just don't think that this question has an answer in absence of your schema.

tar: Error is not recoverable: exiting now

use sudo

sudo tar -zxvf xxxxxxxxx.tar.gz

Does C# have an equivalent to JavaScript's encodeURIComponent()?

Try Server.UrlEncode(), or System.Web.HttpUtility.UrlEncode() for instances when you don't have access to the Server object. You can also use System.Uri.EscapeUriString() to avoid adding a reference to the System.Web assembly.

You should not use <Link> outside a <Router>

I kinda come up with this code :

import React from 'react';
import { render } from 'react-dom';

// import componentns
import Main from './components/Main';
import PhotoGrid from './components/PhotoGrid';
import Single from './components/Single';

// import react router
import { Router, Route, IndexRoute, BrowserRouter, browserHistory} from 'react-router-dom'

class MainComponent extends React.Component {
  render() {
    return (
      <div>
        <BrowserRouter history={browserHistory}>
          <Route path="/" component={Main} >
            <IndexRoute component={PhotoGrid}></IndexRoute>
            <Route path="/view/:postId" component={Single}></Route>
          </Route>
        </BrowserRouter>
      </div>
    );
  }
}

render(<MainComponent />, document.getElementById('root'));

I think the error was because you were rendering the Main component, and the Main component didn't know anything about Router, so you have to render its father component.

Return array from function

neater:

function BlockID() {
  return {
    "s":"Images/Block_01.png",
    "g":"Images/Block_02.png",
    "C":"Images/Block_03.png",
    "d":"Images/Block_04.png"
   }
}

or just

var images = {
  "s":"Images/Block_01.png",
  "g":"Images/Block_02.png",
  "C":"Images/Block_03.png",
  "d":"Images/Block_04.png"
}

Calculate age given the birth date in the format YYYYMMDD

Try this.

function getAge(dateString) {
    var today = new Date();
    var birthDate = new Date(dateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;
}

I believe the only thing that looked crude on your code was the substr part.

Fiddle: http://jsfiddle.net/codeandcloud/n33RJ/

When to use SELECT ... FOR UPDATE?

Short answers:

Q1: Yes.

Q2: Doesn't matter which you use.

Long answer:

A select ... for update will (as it implies) select certain rows but also lock them as if they have already been updated by the current transaction (or as if the identity update had been performed). This allows you to update them again in the current transaction and then commit, without another transaction being able to modify these rows in any way.

Another way of looking at it, it is as if the following two statements are executed atomically:

select * from my_table where my_condition;

update my_table set my_column = my_column where my_condition;

Since the rows affected by my_condition are locked, no other transaction can modify them in any way, and hence, transaction isolation level makes no difference here.

Note also that transaction isolation level is independent of locking: setting a different isolation level doesn't allow you to get around locking and update rows in a different transaction that are locked by your transaction.

What transaction isolation levels do guarantee (at different levels) is the consistency of data while transactions are in progress.

Creation timestamp and last update timestamp with Hibernate and MySQL

Just to reinforce: java.util.Calender is not for Timestamps. java.util.Date is for a moment in time, agnostic of regional things like timezones. Most database store things in this fashion (even if they appear not to; this is usually a timezone setting in the client software; the data is good)

java, get set methods

your panel class don't have a constructor that accepts a string

try change

RLS_strid_panel p = new RLS_strid_panel(namn1);

to

RLS_strid_panel p = new RLS_strid_panel();
p.setName1(name1);

How to create user for a db in postgresql?

From CLI:

$ su - postgres 
$ psql template1
template1=# CREATE USER tester WITH PASSWORD 'test_password';
template1=# GRANT ALL PRIVILEGES ON DATABASE "test_database" to tester;
template1=# \q

PHP (as tested on localhost, it works as expected):

  $connString = 'port=5432 dbname=test_database user=tester password=test_password';
  $connHandler = pg_connect($connString);
  echo 'Connected to '.pg_dbname($connHandler);

How to include a PHP variable inside a MySQL statement

The rules of adding a PHP variable inside of any MySQL statement are plain and simple:

  1. Any variable that represents an SQL data literal, (or, to put it simply - an SQL string, or a number) MUST be added through a prepared statement. No exceptions.
  2. Any other query part, such as an SQL keyword, a table or a field name, or an operator - must be filtered through a white list.

So as your example only involves data literals, then all variables must be added through placeholders (also called parameters). To do so:

  • In your SQL statement, replace all variables with placeholders
  • prepare the resulting query
  • bind variables to placeholders
  • execute the query

And here is how to do it with all popular PHP database drivers:

Adding data literals using mysql ext

Such a driver doesn't exist.

Adding data literals using mysqli

$type = 'testing';
$reporter = "John O'Hara";
$query = "INSERT INTO contents (type, reporter, description) 
             VALUES(?, ?, 'whatever')";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("ss", $type, $reporter);
$stmt->execute();

The code is a bit complicated but the detailed explanation of all these operators can be found in my article, How to run an INSERT query using Mysqli, as well as a solution that eases the process dramatically.

For a SELECT query you will need to add just a call to get_result() method to get a familiar mysqli_result from which you can fetch the data the usual way:

$reporter = "John O'Hara";
$stmt = $mysqli->prepare("SELECT * FROM users WHERE name=?");
$stmt->bind_param("s", $reporter);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc(); // or while (...)

Adding data literals using PDO

$type = 'testing';
$reporter = "John O'Hara";
$query = "INSERT INTO contents (type, reporter, description) 
             VALUES(?, ?, 'whatever')";
$stmt = $pdo->prepare($query);
$stmt->execute([$type, $reporter]);

In PDO, we can have the bind and execute parts combined, which is very convenient. PDO also supports named placeholders which some find extremely convenient.

Adding keywords or identifiers

Sometimes we have to add a variable that represents another part of a query, such as a keyword or an identifier (a database, table or a field name). It's a rare case but it's better to be prepared.

In this case, your variable must be checked against a list of values explicitly written in your script. This is explained in my other article, Adding a field name in the ORDER BY clause based on the user's choice:

Unfortunately, PDO has no placeholder for identifiers (table and field names), therefore a developer must filter them out manually. Such a filter is often called a "white list" (where we only list allowed values) as opposed to a "black-list" where we list disallowed values.

So we have to explicitly list all possible variants in the PHP code and then choose from them.

Here is an example:

$orderby = $_GET['orderby'] ?: "name"; // set the default value
$allowed = ["name","price","qty"]; // the white list of allowed field names
$key = array_search($orderby, $allowed, true); // see if we have such a name
if ($key === false) { 
    throw new InvalidArgumentException("Invalid field name"); 
}

Exactly the same approach should be used for the direction,

$direction = $_GET['direction'] ?: "ASC";
$allowed = ["ASC","DESC"];
$key = array_search($direction, $allowed, true);
if ($key === false) { 
    throw new InvalidArgumentException("Invalid ORDER BY direction"); 
}

After such a code, both $direction and $orderby variables can be safely put in the SQL query, as they are either equal to one of the allowed variants or there will be an error thrown.

The last thing to mention about identifiers, they must be also formatted according to the particular database syntax. For MySQL it should be backtick characters around the identifier. So the final query string for our order by example would be

$query = "SELECT * FROM `table` ORDER BY `$orderby` $direction";

Is there any way I can define a variable in LaTeX?

If you want to use \newcommand, you can also include \usepackage{xspace} and define command by \newcommand{\newCommandName}{text to insert\xspace}. This can allow you to just use \newCommandName rather than \newCommandName{}.

For more detail, http://www.math.tamu.edu/~harold.boas/courses/math696/why-macros.html

Toggle display:none style with JavaScript

Others have answered your question perfectly, but I just thought I would throw out another way. It's always a good idea to separate HTML markup, CSS styling, and javascript code when possible. The cleanest way to hide something, with that in mind, is using a class. It allows the definition of "hide" to be defined in the CSS where it belongs. Using this method, you could later decide you want the ul to hide by scrolling up or fading away using CSS transition, all without changing your HTML or code. This is longer, but I feel it's a better overall solution.

Demo: http://jsfiddle.net/ThinkingStiff/RkQCF/

HTML:

<a id="showTags" href="#" title="Show Tags">Show All Tags</a>
<ul id="subforms" class="subforums hide"><li>one</li><li>two</li><li>three</li></ul>

CSS:

#subforms {
    overflow-x: visible; 
    overflow-y: visible;
}

.hide {
    display: none; 
}

Script:

document.getElementById( 'showTags' ).addEventListener( 'click', function () {
    document.getElementById( 'subforms' ).toggleClass( 'hide' );
}, false );

Element.prototype.toggleClass = function ( className ) {
    if( this.className.split( ' ' ).indexOf( className ) == -1 ) {
        this.className = ( this.className + ' ' + className ).trim();
    } else {
        this.className = this.className.replace( new RegExp( '(\\s|^)' + className + '(\\s|$)' ), ' ' ).trim();
    };
};

memory error in python

check program with this input:abc/if you got something like ab ac bc abc program works well and you need a stronger RAM otherwise the program is wrong.

Check if a temporary table exists and delete if it exists before creating a temporary table

Note: This also works for ## temp tables.

i.e.

IF OBJECT_ID('tempdb.dbo.##AuditLogTempTable1', 'U') IS NOT NULL
DROP TABLE ##AuditLogTempTable1

Note: This type of command only suitable post SQL Server 2016. Ask yourself .. Do I have any customers that are still on SQL Server 2012 ?

DROP TABLE IF EXISTS ##AuditLogTempTable1

YouTube Video Embedded via iframe Ignoring z-index?

Try adding wmode, it seems to have two parameters.

&wmode=Opaque

&wmode=transparent

I can't find a technical reason why it works, or much more explanation but take at look at this query.

<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/lzQgAR_J1PI?wmode=transparent" frameborder="0" wmode="Opaque">

or this

//Fix z-index youtube video embedding
$(document).ready(function (){
    $('iframe').each(function(){
        var url = $(this).attr("src");
        $(this).attr("src",url+"?wmode=transparent");
    });
});

Why does flexbox stretch my image rather than retaining aspect ratio?

It is stretching because align-self default value is stretch. there is two solution for this case : 1. set img align-self : center OR 2. set parent align-items : center

img {

   align-self: center
}

OR

.parent {
  align-items: center
}

Component is not part of any NgModule or the module has not been imported into your module

In my case, I only need to restart the server (that is if you're using ng serve).

It happens to me every time I add a new module while the server is running.

Android DialogFragment vs Dialog

DialogFragment is basically a Fragment that can be used as a dialog.

Using DialogFragment over Dialog due to the following reasons:

  • DialogFragment is automatically re-created after configuration changes and save & restore flow
  • DialogFragment inherits full Fragment’s lifecycle
  • No more IllegalStateExceptions and leaked window crashes. This was pretty common when the activity was destroyed with the Alert Dialog still there.

More detail

Cross Domain Form POSTing

It is possible to build an arbitrary GET or POST request and send it to any server accessible to a victims browser. This includes devices on your local network, such as Printers and Routers.

There are many ways of building a CSRF exploit. A simple POST based CSRF attack can be sent using .submit() method. More complex attacks, such as cross-site file upload CSRF attacks will exploit CORS use of the xhr.withCredentals behavior.

CSRF does not violate the Same-Origin Policy For JavaScript because the SOP is concerned with JavaScript reading the server's response to a clients request. CSRF attacks don't care about the response, they care about a side-effect, or state change produced by the request, such as adding an administrative user or executing arbitrary code on the server.

Make sure your requests are protected using one of the methods described in the OWASP CSRF Prevention Cheat Sheet. For more information about CSRF consult the OWASP page on CSRF.

Javascript window.open pass values using POST

For what it's worth, here's the previously provided code encapsulated within a function.

openWindowWithPost("http://www.example.com/index.php", {
    p: "view.map",
    coords: encodeURIComponent(coords)
});

Function definition:

function openWindowWithPost(url, data) {
    var form = document.createElement("form");
    form.target = "_blank";
    form.method = "POST";
    form.action = url;
    form.style.display = "none";

    for (var key in data) {
        var input = document.createElement("input");
        input.type = "hidden";
        input.name = key;
        input.value = data[key];
        form.appendChild(input);
    }

    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form);
}

Remove duplicates from dataframe, based on two columns A,B, keeping row with max value in another column C

You can do this simply by using pandas drop duplicates function

df.drop_duplicates(['A','B'],keep= 'last')

Send file using POST from a Python script

Chris Atlee's poster library works really well for this (particularly the convenience function poster.encode.multipart_encode()). As a bonus, it supports streaming of large files without loading an entire file into memory. See also Python issue 3244.

How to turn on line numbers in IDLE?

If you are trying to track down which line caused an error, if you right-click in the Python shell where the line error is displayed it will come up with a "Go to file/line" which takes you directly to the line in question.

How to connect Robomongo to MongoDB

If there is no authentication enabled (username/password) and still unable to connect. Just use localhost and default port. Click Test and Save, if test connection is successful.

enter image description here

enter image description here

enter image description here

enter image description here

Regards Jagdish

Why should hash functions use a prime number modulus?

I would say the first answer at this link is the clearest answer I found regarding this question.

Consider the set of keys K = {0,1,...,100} and a hash table where the number of buckets is m = 12. Since 3 is a factor of 12, the keys that are multiples of 3 will be hashed to buckets that are multiples of 3:

  • Keys {0,12,24,36,...} will be hashed to bucket 0.
  • Keys {3,15,27,39,...} will be hashed to bucket 3.
  • Keys {6,18,30,42,...} will be hashed to bucket 6.
  • Keys {9,21,33,45,...} will be hashed to bucket 9.

If K is uniformly distributed (i.e., every key in K is equally likely to occur), then the choice of m is not so critical. But, what happens if K is not uniformly distributed? Imagine that the keys that are most likely to occur are the multiples of 3. In this case, all of the buckets that are not multiples of 3 will be empty with high probability (which is really bad in terms of hash table performance).

This situation is more common that it may seem. Imagine, for instance, that you are keeping track of objects based on where they are stored in memory. If your computer's word size is four bytes, then you will be hashing keys that are multiples of 4. Needless to say that choosing m to be a multiple of 4 would be a terrible choice: you would have 3m/4 buckets completely empty, and all of your keys colliding in the remaining m/4 buckets.

In general:

Every key in K that shares a common factor with the number of buckets m will be hashed to a bucket that is a multiple of this factor.

Therefore, to minimize collisions, it is important to reduce the number of common factors between m and the elements of K. How can this be achieved? By choosing m to be a number that has very few factors: a prime number.

FROM THE ANSWER BY Mario.

onclick="location.href='link.html'" does not load page in Safari

Use jQuery....I know you say you're trying to teach someone javascript, but teach him a cleaner technique... for instance, I could:

<select id="navigation">
    <option value="unit_01.htm">Unit 1</option>
    <option value="#5.2">Bookmark 2</option>
</select>

And with a little jQuery, you could do:

$("#navigation").change(function()
{
    document.location.href = $(this).val();
});

Unobtrusive, and with clean separation of logic and UI.

ASP.NET MVC Dropdown List From SelectList

Just try this in razor

@{
    var selectList = new SelectList(
        new List<SelectListItem>
        {
            new SelectListItem {Text = "Google", Value = "Google"},
            new SelectListItem {Text = "Other", Value = "Other"},
        }, "Value", "Text");
}

and then

@Html.DropDownListFor(m => m.YourFieldName, selectList, "Default label", new { @class = "css-class" })

or

@Html.DropDownList("ddlDropDownList", selectList, "Default label", new { @class = "css-class" })

How to generate a random alpha-numeric string

This is easily achievable without any external libraries.

1. Cryptographic Pseudo Random Data Generation (PRNG)

First you need a cryptographic PRNG. Java has SecureRandom for that and typically uses the best entropy source on the machine (e.g. /dev/random). Read more here.

SecureRandom rnd = new SecureRandom();
byte[] token = new byte[byteLength];
rnd.nextBytes(token);

Note: SecureRandom is the slowest, but most secure way in Java of generating random bytes. I do however recommend not considering performance here since it usually has no real impact on your application unless you have to generate millions of tokens per second.

2. Required Space of Possible Values

Next you have to decide "how unique" your token needs to be. The whole and only point of considering entropy is to make sure that the system can resist brute force attacks: the space of possible values must be so large that any attacker could only try a negligible proportion of the values in non-ludicrous time1.

Unique identifiers such as random UUID have 122 bit of entropy (i.e., 2^122 = 5.3x10^36) - the chance of collision is "*(...) for there to be a one in a billion chance of duplication, 103 trillion version 4 UUIDs must be generated2". We will choose 128 bits since it fits exactly into 16 bytes and is seen as highly sufficient for being unique for basically every, but the most extreme, use cases and you don't have to think about duplicates. Here is a simple comparison table of entropy including simple analysis of the birthday problem.

Comparison of token sizes

For simple requirements, 8 or 12 byte length might suffice, but with 16 bytes you are on the "safe side".

And that's basically it. The last thing is to think about encoding so it can be represented as a printable text (read, a String).

3. Binary to Text Encoding

Typical encodings include:

  • Base64 every character encodes 6 bit, creating a 33% overhead. Fortunately there are standard implementations in Java 8+ and Android. With older Java you can use any of the numerous third-party libraries. If you want your tokens to be URL safe use the URL-safe version of RFC4648 (which usually is supported by most implementations). Example encoding 16 bytes with padding: XfJhfv3C0P6ag7y9VQxSbw==

  • Base32 every character encodes 5 bit, creating a 40% overhead. This will use A-Z and 2-7, making it reasonably space efficient while being case-insensitive alpha-numeric. There isn't any standard implementation in the JDK. Example encoding 16 bytes without padding: WUPIL5DQTZGMF4D3NX5L7LNFOY

  • Base16 (hexadecimal) every character encodes four bit, requiring two characters per byte (i.e., 16 bytes create a string of length 32). Therefore hexadecimal is less space efficient than Base32, but it is safe to use in most cases (URL) since it only uses 0-9 and A to F. Example encoding 16 bytes: 4fa3dd0f57cb3bf331441ed285b27735. See a Stack Overflow discussion about converting to hexadecimal here.

Additional encodings like Base85 and the exotic Base122 exist with better/worse space efficiency. You can create your own encoding (which basically most answers in this thread do), but I would advise against it, if you don't have very specific requirements. See more encoding schemes in the Wikipedia article.

4. Summary and Example

  • Use SecureRandom
  • Use at least 16 bytes (2^128) of possible values
  • Encode according to your requirements (usually hex or base32 if you need it to be alpha-numeric)

Don't

  • ... use your home brew encoding: better maintainable and readable for others if they see what standard encoding you use instead of weird for loops creating characters at a time.
  • ... use UUID: it has no guarantees on randomness; you are wasting 6 bits of entropy and have a verbose string representation

Example: Hexadecimal Token Generator

public static String generateRandomHexToken(int byteLength) {
    SecureRandom secureRandom = new SecureRandom();
    byte[] token = new byte[byteLength];
    secureRandom.nextBytes(token);
    return new BigInteger(1, token).toString(16); // Hexadecimal encoding
}

//generateRandomHexToken(16) -> 2189df7475e96aa3982dbeab266497cd

Example: Base64 Token Generator (URL Safe)

public static String generateRandomBase64Token(int byteLength) {
    SecureRandom secureRandom = new SecureRandom();
    byte[] token = new byte[byteLength];
    secureRandom.nextBytes(token);
    return Base64.getUrlEncoder().withoutPadding().encodeToString(token); //base64 encoding
}

//generateRandomBase64Token(16) -> EEcCCAYuUcQk7IuzdaPzrg

Example: Java CLI Tool

If you want a ready-to-use CLI tool you may use dice:

Example: Related issue - Protect Your Current Ids

If you already have an id you can use (e.g., a synthetic long in your entity), but don't want to publish the internal value, you can use this library to encrypt it and obfuscate it: https://github.com/patrickfav/id-mask

IdMask<Long> idMask = IdMasks.forLongIds(Config.builder(key).build());
String maskedId = idMask.mask(id);
// Example: NPSBolhMyabUBdTyanrbqT8
long originalId = idMask.unmask(maskedId);

Retrieve all values from HashMap keys in an ArrayList Java

Try it this way...

I am considering the HashMap with key and value of type String, HashMap<String,String>

HashMap<String,String> hmap = new HashMap<String,String>();

hmap.put("key1","Val1");
hmap.put("key2","Val2");

ArrayList<String> arList = new ArrayList<String>();

for(Map.Entry<String,String> map : hmap.entrySet()){

     arList.add(map.getValue());

}

Angular expression if array contains

You can accomplish this with a slightly different syntax:

ng-class="{'approved': selectedForApproval.indexOf(jobSet) === -1}"

Plnkr

How do I pass a variable by reference?

Here is the simple (I hope) explanation of the concept pass by object used in Python.
Whenever you pass an object to the function, the object itself is passed (object in Python is actually what you'd call a value in other programming languages) not the reference to this object. In other words, when you call:

def change_me(list):
   list = [1, 2, 3]

my_list = [0, 1]
change_me(my_list)

The actual object - [0, 1] (which would be called a value in other programming languages) is being passed. So in fact the function change_me will try to do something like:

[0, 1] = [1, 2, 3]

which obviously will not change the object passed to the function. If the function looked like this:

def change_me(list):
   list.append(2)

Then the call would result in:

[0, 1].append(2)

which obviously will change the object. This answer explains it well.

What is Gradle in Android Studio?

The Android Studio build system is based on Gradle, and the Android Gradle plugin adds several features that are specific to building Android apps. Although the Android plugin is typically updated in lock-step with Android Studio, the plugin (and the rest of the Gradle system) can run independent of Android Studio and be updated separately.

For more details you can refer:

  1. https://developer.android.com/studio/releases/gradle-plugin?gclid=Cj0KCQiAlZH_BRCgARIsAAZHSBndmJC_myjKnuCBZbe7u9nyzMjbFGES2SVvedq4nxyqdqJnqq0xxlAaAvGMEALw_wcB&gclsrc=aw.ds
  2. https://gradle.org/

Kotlin - How to correctly concatenate a String

Try this, I think this is a natively way to concatenate strings in Kotlin:

val result = buildString{
    append("a")
    append("b")
}

println(result)

// you will see "ab" in console.

How can I find the last element in a List<>?

In C# 8.0 you can get the last item with ^ operator full explanation

List<char> list = ...;
var value = list[^1]; 

// Gets translated to 
var value = list[list.Count - 1];

how to add value to a tuple?

    list_of_tuples = [('1', '2', '3', '4'),
                      ('2', '3', '4', '5'),
                      ('3', '4', '5', '6'),
                      ('4', '5', '6', '7')]


    def mod_tuples(list_of_tuples):
        for i in range(0, len(list_of_tuples)):
            addition = ''
            for x in list_of_tuples[i]:
                addition = addition + x
            list_of_tuples[i] = list_of_tuples[i] + (addition,)
        return list_of_tuples

    # check: 
    print mod_tuples(list_of_tuples)

How do you print in a Go test using the "testing" package?

In case your using testing.M and associated setup/teardown; -v is valid here as well.

package g 

import (
    "os"
    "fmt"
    "testing"
)

func TestSomething(t *testing.T) {
    t.Skip("later")
}

func setup() {
    fmt.Println("setting up")
}

func teardown() {
    fmt.Println("tearing down")
}

func TestMain(m *testing.M) {
    setup()
    result := m.Run()
    teardown()
    os.Exit(result)
}
$ go test -v g_test.go 
setting up
=== RUN   TestSomething
    g_test.go:10: later
--- SKIP: TestSomething (0.00s)
PASS
tearing down
ok      command-line-arguments  0.002s

Cannot find vcvarsall.bat when running a Python script

In 2015, if you still getting this confusing error, blame python default setuptools that PIP uses.

  1. Download and install minimal Microsoft Visual C++ Compiler for Python 2.7 required to compile python 2.7 modules from http://www.microsoft.com/en-in/download/details.aspx?id=44266
  2. Update your setuptools - pip install -U setuptools
  3. Install whatever python package you want that require C compilation. pip install blahblah

It will work fine.

UPDATE: It won't work fine for all libraries. I still get some error with few modules, that require lib-headers. They only thing that work flawlessly is Linux platform

Why are Python lambdas useful?

lambda is just a fancy way of saying function. Other than its name, there is nothing obscure, intimidating or cryptic about it. When you read the following line, replace lambda by function in your mind:

>>> f = lambda x: x + 1
>>> f(3)
4

It just defines a function of x. Some other languages, like R, say it explicitly:

> f = function(x) { x + 1 }
> f(3)
4

You see? It's one of the most natural things to do in programming.

Validate phone number using angular js

An even cleaner and more professional look I have found is to use AngularUI Mask. Very simple to implement and the mask can be customized for other inputs as well. Then a simple required validation is all you need.

https://angular-ui.github.io/

convert an enum to another type of enum

Here's an extension method version if anyone is interested

public static TEnum ConvertEnum<TEnum >(this Enum source)
    {
        return (TEnum)Enum.Parse(typeof(TEnum), source.ToString(), true);
    }

// Usage
NewEnumType newEnum = oldEnumVar.ConvertEnum<NewEnumType>();

Spring RequestMapping for controllers that produce and consume JSON

You shouldn't need to configure the consumes or produces attribute at all. Spring will automatically serve JSON based on the following factors.

  • The accepts header of the request is application/json
  • @ResponseBody annotated method
  • Jackson library on classpath

You should also follow Wim's suggestion and define your controller with the @RestController annotation. This will save you from annotating each request method with @ResponseBody

Another benefit of this approach would be if a client wants XML instead of JSON, they would get it. They would just need to specify xml in the accepts header.

How can I stop the browser back button using JavaScript?

This code will disable the back button for modern browsers which support the HTML5 History API. Under normal circumstances, pushing the back button goes back one step, to the previous page. If you use history.pushState(), you start adding extra sub-steps to the current page. The way it works is, if you were to use history.pushState() three times, then start pushing the back button, the first three times it would navigate back in these sub-steps, and then the fourth time it would go back to the previous page.

If you combine this behaviour with an event listener on the popstate event, you can essentially set up an infinite loop of sub-states. So, you load the page, push a sub-state, then hit the back button, which pops a sub-state and also pushes another one, so if you push the back button again it will never run out of sub-states to push. If you feel that it's necessary to disable the back button, this will get you there.

history.pushState(null, null, 'no-back-button');
window.addEventListener('popstate', function(event) {
  history.pushState(null, null, 'no-back-button');
});

How do I make calls to a REST API using C#?

    var TakingRequset = WebRequest.Create("http://xxx.acv.com/MethodName/Get");
    TakingRequset.Method = "POST";
    TakingRequset.ContentType = "text/xml;charset=utf-8";
    TakingRequset.PreAuthenticate = true;

    //---Serving Request path query
     var PAQ = TakingRequset.RequestUri.PathAndQuery;

    //---creating your xml as per the host reqirement
    string xmlroot=@"<root><childnodes>passing parameters</childnodes></root>";
    string xmlroot2=@"<root><childnodes>passing parameters</childnodes></root>";

    //---Adding Headers as requested by host 
    xmlroot2 = (xmlroot2 + "XXX---");
    //---Adding Headers Value as requested by host 
  //  var RequestheaderVales = Method(xmlroot2);

    WebProxy proxy = new WebProxy("XXXXX-----llll", 8080);
    proxy.Credentials = new NetworkCredential("XXX---uuuu", "XXX----", "XXXX----");
    System.Net.WebRequest.DefaultWebProxy = proxy;


    // Adding The Request into Headers
    TakingRequset.Headers.Add("xxx", "Any Request Variable ");
    TakingRequset.Headers.Add("xxx", "Any Request Variable");

    byte[] byteData = Encoding.UTF8.GetBytes(xmlroot);
    TakingRequset.ContentLength = byteData.Length;

    using (Stream postStream = TakingRequset.GetRequestStream())
    {
        postStream.Write(byteData, 0, byteData.Length);
        postStream.Close();
    }



    StreamReader stredr = new StreamReader(TakingRequset.GetResponse().GetResponseStream());
    string response = stredr.ReadToEnd();

How is attr_accessible used in Rails 4?

Rails 4 now uses strong parameters.

Protecting attributes is now done in the controller. This is an example:

class PeopleController < ApplicationController
  def create
    Person.create(person_params)
  end

  private

  def person_params
    params.require(:person).permit(:name, :age)
  end
end

No need to set attr_accessible in the model anymore.

Dealing with accepts_nested_attributes_for

In order to use accepts_nested_attribute_for with strong parameters, you will need to specify which nested attributes should be whitelisted.

class Person
  has_many :pets
  accepts_nested_attributes_for :pets
end

class PeopleController < ApplicationController
  def create
    Person.create(person_params)
  end

  # ...

  private

  def person_params
    params.require(:person).permit(:name, :age, pets_attributes: [:name, :category])
  end
end

Keywords are self-explanatory, but just in case, you can find more information about strong parameters in the Rails Action Controller guide.

Note: If you still want to use attr_accessible, you need to add protected_attributes to your Gemfile. Otherwise, you will be faced with a RuntimeError.

Change Select List Option background colour on hover

The problem is that even JavaScript does not see the option element being hovered. This is just to put emphasis on how it's not going to be solved (any time soon at least) by using just CSS:

window.onmouseover = function(e)
{
 console.log(e.target.nodeName);
}

The only way to resolve this issue (besides waiting a millennia for browser vendors to fix bugs, let alone one that afflicts what you're trying to do) is to replace the drop-down menu with your own HTML/XML using JavaScript. This would likely involve the use of replacing the select element with a ul element and the use of a radio input element per li element.

checking memory_limit in PHP

Try to convert the value first (eg: 64M -> 64 * 1024 * 1024). After that, do comparison and print the result.

<?php
$memory_limit = ini_get('memory_limit');
if (preg_match('/^(\d+)(.)$/', $memory_limit, $matches)) {
    if ($matches[2] == 'M') {
        $memory_limit = $matches[1] * 1024 * 1024; // nnnM -> nnn MB
    } else if ($matches[2] == 'K') {
        $memory_limit = $matches[1] * 1024; // nnnK -> nnn KB
    }
}

$ok = ($memory_limit >= 64 * 1024 * 1024); // at least 64M?

echo '<phpmem>';
echo '<val>' . $memory_limit . '</val>';
echo '<ok>' . ($ok ? 1 : 0) . '</ok>';
echo '</phpmem>';

Please note that the above code is just an idea. Don't forget to handle -1 (no memory limit), integer-only value (value in bytes), G (value in gigabytes), k/m/g (value in kilobytes, megabytes, gigabytes because shorthand is case-insensitive), etc.

surface plots in matplotlib

check the official example. X,Y and Z are indeed 2d arrays, numpy.meshgrid() is a simple way to get 2d x,y mesh out of 1d x and y values.

http://matplotlib.sourceforge.net/mpl_examples/mplot3d/surface3d_demo.py

here's pythonic way to convert your 3-tuples to 3 1d arrays.

data = [(1,2,3), (10,20,30), (11, 22, 33), (110, 220, 330)]
X,Y,Z = zip(*data)
In [7]: X
Out[7]: (1, 10, 11, 110)
In [8]: Y
Out[8]: (2, 20, 22, 220)
In [9]: Z
Out[9]: (3, 30, 33, 330)

Here's mtaplotlib delaunay triangulation (interpolation), it converts 1d x,y,z into something compliant (?):

http://matplotlib.sourceforge.net/api/mlab_api.html#matplotlib.mlab.griddata

How large should my recv buffer be when calling recv in the socket library

For SOCK_STREAM socket, the buffer size does not really matter, because you are just pulling some of the waiting bytes and you can retrieve more in a next call. Just pick whatever buffer size you can afford.

For SOCK_DGRAM socket, you will get the fitting part of the waiting message and the rest will be discarded. You can get the waiting datagram size with the following ioctl:

#include <sys/ioctl.h>
int size;
ioctl(sockfd, FIONREAD, &size);

Alternatively you can use MSG_PEEK and MSG_TRUNC flags of the recv() call to obtain the waiting datagram size.

ssize_t size = recv(sockfd, buf, len, MSG_PEEK | MSG_TRUNC);

You need MSG_PEEK to peek (not receive) the waiting message - recv returns the real, not truncated size; and you need MSG_TRUNC to not overflow your current buffer.

Then you can just malloc(size) the real buffer and recv() datagram.

Convert JsonObject to String

You can try Gson convertor, to get the exact conversion like json.stringify

val jsonString:String = jsonObject.toString()
val gson:Gson = GsonBuilder().setPrettyPrinting().create()
val json:JsonElement = gson.fromJson(jsonString,JsonElement.class)
val jsonInString:String= gson.toJson(json)
println(jsonInString)

Access to file download dialog in Firefox

I had the same problem, I wanted no access of Save Dialogue.

Below code can help:

    FirefoxProfile fp = new FirefoxProfile();
    fp.setPreference("browser.download.folderList",2);
    fp.setPreference("browser.download.manager.showWhenStarting",false);
    fp.setPreference("browser.helperApps.alwaysAsk.force", false);
    // Below you have to set the content-type of downloading file(I have set simple CSV file)
    fp.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv");

According to the file type which is being downloaded, You need to specify content types.

You can specify multiple content-types separated with ' ; '

e.g:

    fp.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv;application/vnd.ms-excel;application/msword");

Full width image with fixed height

<div id="container">
    <img style="width: 100%; height: 40%;" id="image" src="...">
</div>

I hope this will serve your purpose.

How do you programmatically set an attribute?

Usually, we define classes for this.

class XClass( object ):
   def __init__( self ):
       self.myAttr= None

x= XClass()
x.myAttr= 'magic'
x.myAttr

However, you can, to an extent, do this with the setattr and getattr built-in functions. However, they don't work on instances of object directly.

>>> a= object()
>>> setattr( a, 'hi', 'mom' )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'hi'

They do, however, work on all kinds of simple classes.

class YClass( object ):
    pass

y= YClass()
setattr( y, 'myAttr', 'magic' )
y.myAttr

Load content with ajax in bootstrap modal

Here is how I solved the issue, might be useful to some:

Ajax modal doesn't seem to be available with boostrap 2.1.1

So I ended up coding it myself:

$('[data-toggle="modal"]').click(function(e) {
  e.preventDefault();
  var url = $(this).attr('href');
  //var modal_id = $(this).attr('data-target');
  $.get(url, function(data) {
      $(data).modal();
  });
});

Example of a link that calls a modal:

<a href="{{ path('ajax_get_messages', { 'superCategoryID': 6, 'sex': sex }) }}" data-toggle="modal">
    <img src="{{ asset('bundles/yopyourownpoet/images/messageCategories/BirthdaysAnniversaries.png') }}" alt="Birthdays" height="120" width="109"/>
</a>

I now send the whole modal markup through ajax.

Credits to drewjoh

How to temporarily disable a click handler in jQuery?

This is a more idiomatic alternative to the artificial state variable solutions:

$("#button_id").one('click', DoSomething);

function DoSomething() {
  // do something.

  $("#button_id").one('click', DoSomething);
}

One will only execute once (until attached again). More info here: http://docs.jquery.com/Events/one

How do shift operators work in Java?

I think it would be the following, for example:

  • Signed left shift

[ 2 << 1 ] is => [10 (binary of 2) add 1 zero at the end of the binary string] Hence 10 will be 100 which becomes 4.

Signed left shift uses multiplication... So this could also be calculated as 2 * (2^1) = 4. Another example [2 << 11] = 2 *(2^11) = 4096

  • Signed right shift

[ 4 >> 1 ] is => [100 (binary of 4) remove 1 zero at the end of the binary string] Hence 100 will be 10 which becomes 2.

Signed right shift uses division... So this could also be calculated as 4 / (2^1) = 2 Another example [4096 >> 11] = 4096 / (2^11) = 2

Fatal error: Call to undefined function pg_connect()

  1. Add 'PHPIniDir "C:/php"' into the httpd.conf file.(provided you have your PHP saved in C:, or else give the location where PHP is saved.)
  2. Uncomment following 'extension=php_pgsql.dll' in php.ini file
  3. Uncomment ';extension_dir = "ext"' in php.ini directory

What does "<html xmlns="http://www.w3.org/1999/xhtml">" do?

The namespace name http://www.w3.org/1999/xhtml 
is intended for use in various specifications such as:

Recommendations:

    XHTML™ 1.0: The Extensible HyperText Markup Language
    XHTML Modularization
    XHTML 1.1
    XHTML Basic
    XHTML Print
    XHTML+RDFa

Check here for more detail

HTTP authentication logout via PHP

The only effective way I've found to wipe out the PHP_AUTH_DIGEST or PHP_AUTH_USER AND PHP_AUTH_PW credentials is to call the header HTTP/1.1 401 Unauthorized.

function clear_admin_access(){
    header('HTTP/1.1 401 Unauthorized');
    die('Admin access turned off');
}

How does Java import work?

javac (or java during runtime) looks for the classes being imported in the classpath. If they are not there in the classpath then classnotfound exceptions are thrown.

classpath is just like the path variable in a shell, which is used by the shell to find a command or executable.

Entire directories or individual jar files can be put in the classpath. Also, yes a classpath can perhaps include a path which is not local but is somewhere on the internet. Please read more about classpath to resolve your doubts.

how to display a div triggered by onclick event

function showstuff(boxid){
   document.getElementById(boxid).style.visibility="visible";
}
<button onclick="showstuff('id_to_show');" />

This will help you, I think.

How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

Here is my attempt:

Function RegParse(ByVal pattern As String, ByVal html As String)
    Dim regex   As RegExp
    Set regex = New RegExp

    With regex
        .IgnoreCase = True  'ignoring cases while regex engine performs the search.
        .pattern = pattern  'declaring regex pattern.
        .Global = False     'restricting regex to find only first match.

        If .Test(html) Then         'Testing if the pattern matches or not
            mStr = .Execute(html)(0)        '.Execute(html)(0) will provide the String which matches with Regex
            RegParse = .Replace(mStr, "$1") '.Replace function will replace the String with whatever is in the first set of braces - $1.
        Else
            RegParse = "#N/A"
        End If

    End With
End Function

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

How about this: http://jsfiddle.net/5bNx4/

Please use .on if you are using jq1.7 et al.

Behaviour: When you type anything or paste anything on the 1st textarea the teaxtarea below captures the cahnge.

Rest I hope it helps the cause. :)

Helpful link =>

How do you handle oncut, oncopy, and onpaste in jQuery?

Catch paste input

code

$(document).ready(function() {
    var $editor    = $('#editor');
    var $clipboard = $('<textarea />').insertAfter($editor);

    if(!document.execCommand('StyleWithCSS', false, false)) {
        document.execCommand('UseCSS', false, true);
    }

    $editor.on('paste, keydown', function() {
        var $self = $(this);            
        setTimeout(function(){ 
            var $content = $self.html();             
            $clipboard.val($content);
        },100);
     });
});

Difference between Java SE/EE/ME?

As I come across this question, I found the information provided on the Oracle's tutorial very complete and worth to share:

The Java Programming Language Platforms

There are four platforms of the Java programming language:

  • Java Platform, Standard Edition (Java SE)

  • Java Platform, Enterprise Edition (Java EE)

  • Java Platform, Micro Edition (Java ME)

  • JavaFX

All Java platforms consist of a Java Virtual Machine (VM) and an application programming interface (API). The Java Virtual Machine is a program, for a particular hardware and software platform, that runs Java technology applications. An API is a collection of software components that you can use to create other software components or applications. Each Java platform provides a virtual machine and an API, and this allows applications written for that platform to run on any compatible system with all the advantages of the Java programming language: platform-independence, power, stability, ease-of-development, and security.

Java SE

When most people think of the Java programming language, they think of the Java SE API. Java SE's API provides the core functionality of the Java programming language. It defines everything from the basic types and objects of the Java programming language to high-level classes that are used for networking, security, database access, graphical user interface (GUI) development, and XML parsing.

In addition to the core API, the Java SE platform consists of a virtual machine, development tools, deployment technologies, and other class libraries and toolkits commonly used in Java technology applications.

Java EE

The Java EE platform is built on top of the Java SE platform. The Java EE platform provides an API and runtime environment for developing and running large-scale, multi-tiered, scalable, reliable, and secure network applications.

Java ME

The Java ME platform provides an API and a small-footprint virtual machine for running Java programming language applications on small devices, like mobile phones. The API is a subset of the Java SE API, along with special class libraries useful for small device application development. Java ME applications are often clients of Java EE platform services.

JavaFX

JavaFX is a platform for creating rich internet applications using a lightweight user-interface API. JavaFX applications use hardware-accelerated graphics and media engines to take advantage of higher-performance clients and a modern look-and-feel as well as high-level APIs for connecting to networked data sources. JavaFX applications may be clients of Java EE platform services.

How to choose the right bean scope?

Introduction

It represents the scope (the lifetime) of the bean. This is easier to understand if you are familiar with "under the covers" working of a basic servlet web application: How do servlets work? Instantiation, sessions, shared variables and multithreading.


@Request/View/Flow/Session/ApplicationScoped

A @RequestScoped bean lives as long as a single HTTP request-response cycle (note that an Ajax request counts as a single HTTP request too). A @ViewScoped bean lives as long as you're interacting with the same JSF view by postbacks which call action methods returning null/void without any navigation/redirect. A @FlowScoped bean lives as long as you're navigating through the specified collection of views registered in the flow configuration file. A @SessionScoped bean lives as long as the established HTTP session. An @ApplicationScoped bean lives as long as the web application runs. Note that the CDI @Model is basically a stereotype for @Named @RequestScoped, so same rules apply.

Which scope to choose depends solely on the data (the state) the bean holds and represents. Use @RequestScoped for simple and non-ajax forms/presentations. Use @ViewScoped for rich ajax-enabled dynamic views (ajaxbased validation, rendering, dialogs, etc). Use @FlowScoped for the "wizard" ("questionnaire") pattern of collecting input data spread over multiple pages. Use @SessionScoped for client specific data, such as the logged-in user and user preferences (language, etc). Use @ApplicationScoped for application wide data/constants, such as dropdown lists which are the same for everyone, or managed beans without any instance variables and having only methods.

Abusing an @ApplicationScoped bean for session/view/request scoped data would make it to be shared among all users, so anyone else can see each other's data which is just plain wrong. Abusing a @SessionScoped bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. Abusing a @RequestScoped bean for view scoped data would make view scoped data to be reinitialized to default on every single (ajax) postback, causing possibly non-working forms (see also points 4 and 5 here). Abusing a @ViewScoped bean for request, session or application scoped data, and abusing a @SessionScoped bean for application scoped data doesn't affect the client, but it unnecessarily occupies server memory and is plain inefficient.

Note that the scope should rather not be chosen based on performance implications, unless you really have a low memory footprint and want to go completely stateless; you'd need to use exclusively @RequestScoped beans and fiddle with request parameters to maintain the client's state. Also note that when you have a single JSF page with differently scoped data, then it's perfectly valid to put them in separate backing beans in a scope matching the data's scope. The beans can just access each other via @ManagedProperty in case of JSF managed beans or @Inject in case of CDI managed beans.

See also:


@CustomScoped/NoneScoped/Dependent

It's not mentioned in your question, but (legacy) JSF also supports @CustomScoped and @NoneScoped, which are rarely used in real world. The @CustomScoped must refer a custom Map<K, Bean> implementation in some broader scope which has overridden Map#put() and/or Map#get() in order to have more fine grained control over bean creation and/or destroy.

The JSF @NoneScoped and CDI @Dependent basically lives as long as a single EL-evaluation on the bean. Imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. You normally want to use this scope only on beans which should live as long as the bean where it's being injected. So if a @NoneScoped or @Dependent is injected in a @SessionScoped, then it will live as long as the @SessionScoped bean.

See also:


Flash scope

As last, JSF also supports the flash scope. It is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.

This is actually not available as a managed bean scope, i.e. there's no such thing as @FlashScoped. The flash scope is only available as a map via ExternalContext#getFlash() in managed beans and #{flash} in EL.

See also:

What is an undefined reference/unresolved external symbol error and how do I fix it?

When your include paths are different

Linker errors can happen when a header file and its associated shared library (.lib file) go out of sync. Let me explain.

How do linkers work? The linker matches a function declaration (declared in the header) with its definition (in the shared library) by comparing their signatures. You can get a linker error if the linker doesn't find a function definition that matches perfectly.

Is it possible to still get a linker error even though the declaration and the definition seem to match? Yes! They might look the same in source code, but it really depends on what the compiler sees. Essentially you could end up with a situation like this:

// header1.h
typedef int Number;
void foo(Number);

// header2.h
typedef float Number;
void foo(Number); // this only looks the same lexically

Note how even though both the function declarations look identical in source code, but they are really different according to the compiler.

You might ask how one ends up in a situation like that? Include paths of course! If when compiling the shared library, the include path leads to header1.h and you end up using header2.h in your own program, you'll be left scratching your header wondering what happened (pun intended).

An example of how this can happen in the real world is explained below.

Further elaboration with an example

I have two projects: graphics.lib and main.exe. Both projects depend on common_math.h. Suppose the library exports the following function:

// graphics.lib    
#include "common_math.h" 
   
void draw(vec3 p) { ... } // vec3 comes from common_math.h

And then you go ahead and include the library in your own project.

// main.exe
#include "other/common_math.h"
#include "graphics.h"

int main() {
    draw(...);
}

Boom! You get a linker error and you have no idea why it's failing. The reason is that the common library uses different versions of the same include common_math.h (I have made it obvious here in the example by including a different path, but it might not always be so obvious. Maybe the include path is different in the compiler settings).

Note in this example, the linker would tell you it couldn't find draw(), when in reality you know it obviously is being exported by the library. You could spend hours scratching your head wondering what went wrong. The thing is, the linker sees a different signature because the parameter types are slightly different. In the example, vec3 is a different type in both projects as far as the compiler is concerned. This could happen because they come from two slightly different include files (maybe the include files come from two different versions of the library).

Debugging the linker

DUMPBIN is your friend, if you are using Visual Studio. I'm sure other compilers have other similar tools.

The process goes like this:

  1. Note the weird mangled name given in the linker error. (eg. draw@graphics@XYZ).
  2. Dump the exported symbols from the library into a text file.
  3. Search for the exported symbol of interest, and notice that the mangled name is different.
  4. Pay attention to why the mangled names ended up different. You would be able to see that the parameter types are different, even though they look the same in the source code.
  5. Reason why they are different. In the example given above, they are different because of different include files.

[1] By project I mean a set of source files that are linked together to produce either a library or an executable.

EDIT 1: Rewrote first section to be easier to understand. Please comment below to let me know if something else needs to be fixed. Thanks!

Check if enum exists in Java

Since Java 8, we could use streams instead of for loops. Also, it might be apropriate to return an Optional if the enum does not have an instance with such a name.

I have come up with the following three alternatives on how to look up an enum:

private enum Test {
    TEST1, TEST2;

    public Test fromNameOrThrowException(String name) {
        return Arrays.stream(values())
                .filter(e -> e.name().equals(name))
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException("No enum with name " + name));
    }

    public Test fromNameOrNull(String name) {
        return Arrays.stream(values()).filter(e -> e.name().equals(name)).findFirst().orElse(null);
    }

    public Optional<Test> fromName(String name) {
        return Arrays.stream(values()).filter(e -> e.name().equals(name)).findFirst();
    }
}

Why use Gradle instead of Ant or Maven?

Gradle put the fun back into building/assembling software. I used ant to build software my entire career and I have always considered the actual "buildit" part of the dev work being a necessary evil. A few months back our company grew tired of not using a binary repo (aka checking in jars into the vcs) and I was given the task to investigate this. Started with ivy since it could be bolted on top of ant, didn't have much luck getting my built artifacts published like I wanted. I went for maven and hacked away with xml, worked splendid for some simple helper libs but I ran into serious problems trying to bundle applications ready for deploy. Hassled quite a while googling plugins and reading forums and wound up downloading trillions of support jars for various plugins which I had a hard time using. Finally I went for gradle (getting quite bitter at this point, and annoyed that "It shouldn't be THIS hard!")

But from day one my mood started to improve. I was getting somewhere. Took me like two hours to migrate my first ant module and the build file was basically nothing. Easily fitted one screen. The big "wow" was: build scripts in xml, how stupid is that? the fact that declaring one dependency takes ONE row is very appealing to me -> you can easily see all dependencies for a certain project on one page. From then on I been on a constant roll, for every problem I faced so far there is a simple and elegant solution. I think these are the reasons:

  • groovy is very intuitive for java developers
  • documentation is great to awesome
  • the flexibility is endless

Now I spend my days trying to think up new features to add to our build process. How sick is that?

Git pull after forced update

To receive the new commits

git fetch

Reset

You can reset the commit for a local branch using git reset.

To change the commit of a local branch:

git reset origin/master --hard

Be careful though, as the documentation puts it:

Resets the index and working tree. Any changes to tracked files in the working tree since <commit> are discarded.

If you want to actually keep whatever changes you've got locally - do a --soft reset instead. Which will update the commit history for the branch, but not change any files in the working directory (and you can then commit them).

Rebase

You can replay your local commits on top of any other commit/branch using git rebase:

git rebase -i origin/master

This will invoke rebase in interactive mode where you can choose how to apply each individual commit that isn't in the history you are rebasing on top of.

If the commits you removed (with git push -f) have already been pulled into the local history, they will be listed as commits that will be reapplied - they would need to be deleted as part of the rebase or they will simply be re-included into the history for the branch - and reappear in the remote history on the next push.

Use the help git command --help for more details and examples on any of the above (or other) commands.

How to edit a JavaScript alert box title?

There's quite a nice 'hack' here - https://stackoverflow.com/a/14565029 where you use an iframe with an empty src to generate the alert / confirm message - it doesn't work on Android (for security's sake) - but may suit your scenario.

What is the LD_PRELOAD trick?

With LD_PRELOAD you can give libraries precedence.

For example you can write a library which implement malloc and free. And by loading these with LD_PRELOAD your malloc and free will be executed rather than the standard ones.

Failed to serialize the response in Web API with Json

If you are working with EF, besides adding the code below on Global.asax

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings
    .ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters
    .Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);          

Dont`t forget to import

using System.Data.Entity;

Then you can return your own EF Models

Simple as that!

How to replace sql field value

You could just use REPLACE:

UPDATE myTable SET emailCol = REPLACE(emailCol, '.com', '.org')`.

But take into account an email address such as [email protected] will be updated to [email protected].

If you want to be on a safer side, you should check for the last 4 characters using RIGHT, and append .org to the SUBSTRING manually instead. Notice the usage of UPPER to make the search for the .com ending case insensitive.

UPDATE myTable 
SET emailCol = SUBSTRING(emailCol, 1, LEN(emailCol)-4) + '.org'
WHERE UPPER(RIGHT(emailCol,4)) = '.COM';

See it working in this SQLFiddle.

How to stop/kill a query in postgresql?

What I did is first check what are the running processes by

SELECT * FROM pg_stat_activity WHERE state = 'active';

Find the process you want to kill, then type:

SELECT pg_cancel_backend(<pid of the process>)

This basically "starts" a request to terminate gracefully, which may be satisfied after some time, though the query comes back immediately.

If the process cannot be killed, try:

SELECT pg_terminate_backend(<pid of the process>)

Change project name on Android Studio

I just went into the manifest and changed android:label="...." to the name of the application. Once Id changed this, the title and the actual app name changed to that :)

Xampp MySQL not starting - "Attempting to start MySQL service..."

I can share how I solved the problem in my case.

It seems that somehow I had mySQL Server 5.7 installed. It didn't show on Add/Remove Programs list in Windows tough so I wasn't aware of it. I marked that after I looked up the XAMPP log.

Just after XAMPP launched it has shown in the log that there is a conflict in mySQL and indicated the folder where my mySQL Server 5.7 is installed. I removed mySQL 5.7 manually from Program Files (x86) and ProgramData folder, restarted and XAMPP mySQL started normally then.

I've tried only stopping the mySQL service but for me it didn't work. Only manually deleting all mySQL 5.7 folders seemed to have helped.

Solving sslv3 alert handshake failure when trying to use a client certificate

The solution for me on a CentOS 8 system was checking the System Cryptography Policy by verifying the /etc/crypto-policies/config reads the default value of DEFAULT rather than any other value.

Once changing this value to DEFAULT, run the following command:

/usr/bin/update-crypto-policies --set DEFAULT

Rerun the curl command and it should work.

caching JavaScript files

The best (and only) method is to set correct HTTP headers, specifically these ones: "Expires", "Last-Modified", and "Cache-Control". How to do it depends on the server software you use.

In Improving performance… look for "Optimization on server side" for general considerations and relevant links and for "Client-side cache" for the Apache-specific advice.

If you are a fan of nginx (or nginx in plain English) like I am, you can easily configure it too:

location /images {
  ...
  expires 4h;
}

In the example above any file from /images/ will be cached on the client for 4 hours.

Now when you know right words to look for (HTTP headers "Expires", "Last-Modified", and "Cache-Control"), just peruse the documentation of the web server you use.

Calculate business days

Brute attempt to detect working time - Monday to Friday 8am-4pm:

if (date('N')<6 && date('G')>8 && date('G')<16) {
   // we have a working time (or check for holidays)
}

How to add manifest permission to an application?

I am late but i want to complete the answer.

An permission is added in manifest.xml like

<uses-permission android:name="android.permission.INTERNET"/>

This is enough for standard permissions where no permission is prompted to the user. However, it is not enough to add permission only to manifest if it is a dangerous permission. See android doc. Like Camera, Storage permissions.

<uses-permission android:name="android.permission.CAMERA"/>

You will need to ask permission from user. I use RxPermission library that is widely used library for asking permission. Because it is long code which we have to write to ask permission.

RxPermissions rxPermissions = new RxPermissions(this); // where this is an Activity instance // Must be done during an initialization phase like onCreate
rxPermissions
    .request(Manifest.permission.CAMERA)
    .subscribe(granted -> {
        if (granted) { // Always true pre-M
           // I can control the camera now
        } else {
           // Oups permission denied
        }
    });

Add this library to your app

allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}

dependencies {
    implementation 'com.github.tbruyelle:rxpermissions:0.10.1'
    implementation 'com.jakewharton.rxbinding2:rxbinding:2.1.1'
}

Securely storing passwords for use in python script

Know the master key yourself. Don't hard code it.

Use py-bcrypt (bcrypt), powerful hashing technique to generate a password yourself.

Basically you can do this (an idea...)

import bcrypt
from getpass import getpass
master_secret_key = getpass('tell me the master secret key you are going to use')
salt = bcrypt.gensalt()
combo_password = raw_password + salt + master_secret_key
hashed_password = bcrypt.hashpw(combo_password, salt)

save salt and hashed password somewhere so whenever you need to use the password, you are reading the encrypted password, and test against the raw password you are entering again.

This is basically how login should work these days.

Solutions for INSERT OR UPDATE on SQL Server

See my detailed answer to a very similar previous question

@Beau Crawford's is a good way in SQL 2005 and below, though if you're granting rep it should go to the first guy to SO it. The only problem is that for inserts it's still two IO operations.

MS Sql2008 introduces merge from the SQL:2003 standard:

merge tablename with(HOLDLOCK) as target
using (values ('new value', 'different value'))
    as source (field1, field2)
    on target.idfield = 7
when matched then
    update
    set field1 = source.field1,
        field2 = source.field2,
        ...
when not matched then
    insert ( idfield, field1, field2, ... )
    values ( 7,  source.field1, source.field2, ... )

Now it's really just one IO operation, but awful code :-(

jQuery function to open link in new window

Try this,

$('.popup').click(function(event) {
    event.preventDefault();
    window.open($(this).attr("href"), "popupWindow", "width=600,height=600,scrollbars=yes");
});

You have to include jQuery reference to work this, here is the working sampe http://jsfiddle.net/a7qJt/

Substring a string from the end of the string

s = s.Substring(0, Math.Max(0, s.Length - 2))

to include the case where the length is less than 2

How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'

An additional note. If you check uncompressed javascript file, you will find the condition:

if(window.Tether === undefined) {
     throw new Error('Bootstrap tooltips require Tether (http://github.hubspot.com/tether)')
}

So the error message contains the required information.

You can download the archive from that link.

Uncompressed version:

https://rawgit.com/HubSpot/tether/master/src/js/tether.js https://rawgit.com/HubSpot/tether/master/dist/css/tether.css

How to return multiple values?

You can do something like this:

public class Example
{
    public String name;
    public String location;

    public String[] getExample()
    {
        String ar[] = new String[2];
        ar[0]= name;
        ar[1] =  location;
        return ar; //returning two values at once
    }
}

How to capture multiple repeated groups?

Sorry, not Swift, just a proof of concept in the closest language at hand.

// JavaScript POC. Output:
// Matches:  ["GOODBYE","CRUEL","WORLD","IM","LEAVING","U","TODAY"]

let str = `GOODBYE,CRUEL,WORLD,IM,LEAVING,U,TODAY`
let matches = [];

function recurse(str, matches) {
    let regex = /^((,?([A-Z]+))+)$/gm
    let m
    while ((m = regex.exec(str)) !== null) {
        matches.unshift(m[3])
        return str.replace(m[2], '')
    }
    return "bzzt!"
}

while ((str = recurse(str, matches)) != "bzzt!") ;
console.log("Matches: ", JSON.stringify(matches))

Note: If you were really going to use this, you would use the position of the match as given by the regex match function, not a string replace.

Printing Python version in output

If you are using jupyter notebook Try:

!python --version

If you are using terminal Try:

 python --version

How do I pass options to the Selenium Chrome driver using Python?

Found the chrome Options class in the Selenium source code.

Usage to create a Chrome driver instance:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--disable-extensions")
driver = webdriver.Chrome(chrome_options=chrome_options)

How to group subarrays by a column value?

Recursive function grouping 2-dimensional array by keys from first to last

Input:

$arr = array(
    '0' => array(
        'key0' => 'value0',
        'key1' => 'value1',
        'key2' => 'value02',
    ),
    '2' => array(
        'key0' => 'value0',
        'key1' => 'value1',
        'key2' => 'value12',
    ),
    '3' => array(
        'key0' => 'value0',
        'key1' => 'value3',
        'key2' => 'value22',
    ),
);
$keys = array('key0', 'key1', 'key2');

Output:

$arr = array(
    'value0' => array(
        'value1 => array(
            'value02' => null,
            'value12' => null,
        ),
        'value3' => 'value22',
    ),
);

Code:

function array_group_by_keys(&$arr, $keys) {

    if (count($arr) < 2){
        $arr = array_shift($arr[0]);
        return;
    }

    foreach ($arr as $k => $item) {
        $fvalue = array_shift($item);
        $arr[$fvalue][] = $item;
        unset($arr[$k]);
    }

    array_shift($keys);
    foreach ($arr as &$sub_arr) {
        array_group_by_keys($sub_arr, $keys);
    }
}

Replace multiple characters in a C# string

You can use a replace regular expression.

s/[;,\t\r ]|[\n]{2}/\n/g
  • s/ at the beginning means a search
  • The characters between [ and ] are the characters to search for (in any order)
  • The second / delimits the search-for text and the replace text

In English, this reads:

"Search for ; or , or \t or \r or (space) or exactly two sequential \n and replace it with \n"

In C#, you could do the following: (after importing System.Text.RegularExpressions)

Regex pattern = new Regex("[;,\t\r ]|[\n]{2}");
pattern.Replace(myString, "\n");

Warning: session_start(): Cannot send session cookie - headers already sent by (output started at

Move the session_start(); to top of the page always.

<?php
@ob_start();
session_start();
?>

Clearing <input type='file' /> using jQuery

On my Firefox 40.0.3 only work with this

 $('input[type=file]').val('');
 $('input[type=file]').replaceWith($('input[type=file]').clone(true));

python tuple to dict

>>> dict([('hi','goodbye')])
{'hi': 'goodbye'}

Or:

>>> [ dict([i]) for i in (('CSCO', 21.14), ('CSCO', 21.14), ('CSCO', 21.14), ('CSCO', 21.14)) ]
[{'CSCO': 21.14}, {'CSCO': 21.14}, {'CSCO': 21.14}, {'CSCO': 21.14}]

In CSS how do you change font size of h1 and h2

What have you tried? This should work.

h1 { font-size: 20pt; }
h2 { font-size: 16pt; }

Setting and getting localStorage with jQuery

You said you are attempting to get the text from a div and store it on local storage.

Please Note: Text and Html are different. In the question you mentioned text. html() will return Html content like <a>example</a>. if you want to get Text content then you have to use text() instead of html() then the result will be example instead of <a>example<a>. Anyway, I am using your terminology let it be Text.

Step 1: get the text from div.

what you did is not get the text from div but set the text to a div.

$('#test').html("Test"); 

is actually setting text to div and the output will be a jQuery object. That is why it sets it as [object Object].

To get the text you have to write like this
$('#test').html();

This will return a string not an object so the result will be Test in your case.

Step 2: set it to local storage.

Your approach is correct and you can write it as

localStorage.key=value

But the preferred approach is

localStorage.setItem(key,value); to set

localStorage.getItem(key); to get.

key and value must be strings.

so in your context code will become

$('#test').html("Test");
localStorage.content = $('#test').html();
$('#test').html(localStorage.content);

But I don't find any meaning in your code. Because you want to get the text from div and store it on local storage. And again you are reading the same from local storage and set to div. just like a=10; b=a; a=b;

If you are facing any other problems please update your question accordingly.

How to create a drop-down list?

simple / elegant / how I do it:

Preview:

enter image description here

XML:

<Spinner
    android:id="@+id/spinner1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:drawable/btn_dropdown"
    android:spinnerMode="dropdown"/>

spinnerMode set to dropdown is androids way to make a dropdown. (https://developer.android.com/reference/android/widget/Spinner#attr_android:spinnerMode)

Java:

//get the spinner from the xml.
Spinner dropdown = findViewById(R.id.spinner1);
//create a list of items for the spinner.
String[] items = new String[]{"1", "2", "three"};
//create an adapter to describe how the items are displayed, adapters are used in several places in android.
//There are multiple variations of this, but this is the basic variant.
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, items);
//set the spinners adapter to the previously created one.
dropdown.setAdapter(adapter);

Documentation:

This is the basics but there is more to be self taught with experimentation. https://developer.android.com/guide/topics/ui/controls/spinner.html

  1. You can use a setOnItemSelectedListener with this. (https://developer.android.com/guide/topics/ui/controls/spinner.html#SelectListener)
  2. You can add a strings list from xml. (https://developer.android.com/guide/topics/ui/controls/spinner.html#Populate)
  3. There is an appCompat version of this view. (https://developer.android.com/reference/androidx/appcompat/widget/AppCompatSpinner)

Can I change the name of `nohup.out`?

Above methods will remove your output file data whenever you run above nohup command.

To Append output in user defined file you can use >> in nohup command.

nohup your_command >> filename.out &

This command will append all output in your file without removing old data.

Get Row Index on Asp.net Rowcommand event

I was able to use @rahularyansharma's answer above in my own project, with one minor modification. I needed to get the value of particular cells on the row on which the user clicks a LinkButton. The second line can be modified to get the value of as many cells as you wish.

Here is my solution:

GridViewRow gvr = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
string typecore = gvr.Cells[3].Text.ToString().Trim();

What's "this" in JavaScript onclick?

The value of event handler attributes such as onclick should just be JavaScript, without any "javascript:" prefix. The javascript: pseudo-protocol is used in a URL, for example:

<a href="javascript:func(this)">here</a>

You should use the onclick="func(this)" form in preference to this though. Also note that in my example above using the javascript: pseudo-protocol "this" will refer to the window object rather than the <a> element.

getting the ng-object selected with ng-change

This is the cleanest way to get a value from an angular select options list (other than The Id or Text). Assuming you have a Product Select like this on your page :

<select ng-model="data.ProductId"
        ng-options="product.Id as product.Name for product in productsList"
        ng-change="onSelectChange()">
</select>

Then in Your Controller set the callback function like so:

    $scope.onSelectChange = function () {
        var filteredData = $scope.productsList.filter(function (response) {
            return response.Id === $scope.data.ProductId;
        })
        console.log(filteredData[0].ProductColor);
    }

Simply Explained: Since the ng-change event does not recognize the option items in the select, we are using the ngModel to filter out the selected Item from the options list loaded in the controller.

Furthermore, since the event is fired before the ngModel is really updated, you might get undesirable results, So a better way would be to add a timeout :

        $scope.onSelectChange = function () {
            $timeout(function () {
            var filteredData = $scope.productsList.filter(function (response) {
                return response.Id === $scope.data.ProductId;
            })
            console.log(filteredData[0].ProductColor);
            }, 100);
        };

What is the equivalent of bigint in C#?

I was handling a bigint datatype to be shown in a DataGridView and made it like this

something = (int)(Int64)data_reader[0];

javascript: optional first argument in function

Call like this

my_function ("", options);

How do I convert two lists into a dictionary?

If you are working with more than 1 set of values and wish to have a list of dicts you can use this:

def as_dict_list(data: list, columns: list):
    return [dict((zip(columns, row))) for row in data]

Real-life example would be a list of tuples from a db query paired to a tuple of columns from the same query. Other answers only provided for 1 to 1.

Where will log4net create this log file?

If you want your log file to be place at a specified location which will be decided at run time may be your project output directory then you can configure your .config file entry in that way

<file type="log4net.Util.PatternString" value="%property{LogFileName}.txt" />

and then in the code before calling log4net configure, set the new path like below

 log4net.GlobalContext.Properties["LogFileName"] = @"E:\\file1"; //log file path
 log4net.Config.XmlConfigurator.Configure();

How simple is it? :)

Passing multiple variables to another page in url

Your first variable declartion must start with a ? while any additional must be concatenated with a &

Is it possible in Java to catch two exceptions in the same catch block?

Java 7 and later

Multiple-exception catches are supported, starting in Java 7.

The syntax is:

try {
     // stuff
} catch (Exception1 | Exception2 ex) {
     // Handle both exceptions
}

The static type of ex is the most specialized common supertype of the exceptions listed. There is a nice feature where if you rethrow ex in the catch, the compiler knows that only one of the listed exceptions can be thrown.


Java 6 and earlier

Prior to Java 7, there are ways to handle this problem, but they tend to be inelegant, and to have limitations.

Approach #1

try {
     // stuff
} catch (Exception1 ex) {
     handleException(ex);
} catch (Exception2 ex) {
     handleException(ex);
}

public void handleException(SuperException ex) {
     // handle exception here
}

This gets messy if the exception handler needs to access local variables declared before the try. And if the handler method needs to rethrow the exception (and it is checked) then you run into serious problems with the signature. Specifically, handleException has to be declared as throwing SuperException ... which potentially means you have to change the signature of the enclosing method, and so on.

Approach #2

try {
     // stuff
} catch (SuperException ex) {
     if (ex instanceof Exception1 || ex instanceof Exception2) {
         // handle exception
     } else {
         throw ex;
     }
}

Once again, we have a potential problem with signatures.

Approach #3

try {
     // stuff
} catch (SuperException ex) {
     if (ex instanceof Exception1 || ex instanceof Exception2) {
         // handle exception
     }
}

If you leave out the else part (e.g. because there are no other subtypes of SuperException at the moment) the code becomes more fragile. If the exception hierarchy is reorganized, this handler without an else may end up silently eating exceptions!

Hiding the R code in Rmarkdown/knit and just showing the results

Alternatively, you can also parse a standard markdown document (without code blocks per se) on the fly by the markdownreports package.

Convert utf8-characters to iso-88591 and back in PHP

Have a look at iconv() or mb_convert_encoding(). Just by the way: why don't utf8_encode() and utf8_decode() work for you?

utf8_decode — Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1

utf8_encode — Encodes an ISO-8859-1 string to UTF-8

So essentially

$utf8 = 'ÄÖÜ'; // file must be UTF-8 encoded
$iso88591_1 = utf8_decode($utf8);
$iso88591_2 = iconv('UTF-8', 'ISO-8859-1', $utf8);
$iso88591_2 = mb_convert_encoding($utf8, 'ISO-8859-1', 'UTF-8');

$iso88591 = 'ÄÖÜ'; // file must be ISO-8859-1 encoded
$utf8_1 = utf8_encode($iso88591);
$utf8_2 = iconv('ISO-8859-1', 'UTF-8', $iso88591);
$utf8_2 = mb_convert_encoding($iso88591, 'UTF-8', 'ISO-8859-1');

all should do the same - with utf8_en/decode() requiring no special extension, mb_convert_encoding() requiring ext/mbstring and iconv() requiring ext/iconv.

Order columns through Bootstrap4

You can do two different container one with mobile order and hide on desktop screen, another with desktop order and hide on mobile screen

Static extension methods

In short, no, you can't.

Long answer, extension methods are just syntactic sugar. IE:

If you have an extension method on string let's say:

public static string SomeStringExtension(this string s)
{
   //whatever..
}

When you then call it:

myString.SomeStringExtension();

The compiler just turns it into:

ExtensionClass.SomeStringExtension(myString);

So as you can see, there's no way to do that for static methods.

And another thing just dawned on me: what would really be the point of being able to add static methods on existing classes? You can just have your own helper class that does the same thing, so what's really the benefit in being able to do:

Bool.Parse(..)

vs.

Helper.ParseBool(..);

Doesn't really bring much to the table...

How do I connect C# with Postgres?

If you want an recent copy of npgsql, then go here

http://www.npgsql.org/

This can be installed via package manager console as

PM> Install-Package Npgsql

Getting Database connection in pure JPA setup

Where you want to get that connection is unclear. One possibility would be to get it from the underlying Hibernate Session used by the EntityManager. With JPA 1.0, you'll have to do something like this:

Session session = (Session)em.getDelegate();
Connection conn = session.connection();

Note that the getDelegate() is not portable, the result of this method is implementation specific: the above code works in JBoss, for GlassFish you'd have to adapt it - have a look at Be careful while using EntityManager.getDelegate().

In JPA 2.0, things are a bit better and you can do the following:

Connection conn = em.unwrap(Session.class).connection();

If you are running inside a container, you could also perform a lookup on the configured DataSource.

Find the greatest number in a list of numbers

What about max()

highest = max(1, 2, 3)  # or max([1, 2, 3]) for lists

How to POST JSON request using Apache HttpClient?

For Apache HttpClient 4.5 or newer version:

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost("http://targethost/login");
    String JSON_STRING="";
    HttpEntity stringEntity = new StringEntity(JSON_STRING,ContentType.APPLICATION_JSON);
    httpPost.setEntity(stringEntity);
    CloseableHttpResponse response2 = httpclient.execute(httpPost);

Note:

1 in order to make the code compile, both httpclient package and httpcore package should be imported.

2 try-catch block has been ommitted.

Reference: appache official guide

the Commons HttpClient project is now end of life, and is no longer being developed. It has been replaced by the Apache HttpComponents project in its HttpClient and HttpCore modules

Classpath including JAR within a JAR

I was about to advise to extract all the files at the same level, then to make a jar out of the result, since the package system should keep them neatly separated. That would be the manual way, I suppose the tools indicated by Steve will do that nicely.

How to launch Windows Scheduler by command-line?

Here is an example I just used:

at 8am /EVERY:M,T,W,Th,F,S,Su cmd /c c:\myapp.exe

The result was:

Added a new job with job ID = 1

Then, to check my work:

at

How to check if a word is an English word with Python?

For a semantic web approach, you could run a sparql query against WordNet in RDF format. Basically just use urllib module to issue GET request and return results in JSON format, parse using python 'json' module. If it's not English word you'll get no results.

As another idea, you could query Wiktionary's API.

Clear variable in python

  • If want to totally delete it use del:

    del your_variable
    
  • Or otherwise, to make the value None:

    your_variable = None
    
  • If it's a mutable iterable (lists, sets, dictionaries, etc, but not tuples because they're immutable), you can make it empty like:

    your_variable.clear()
    

Then your_variable will be empty

jQuery creating objects

You can always make it a function

function writeObject(color){
    $('body').append('<div style="color:'+color+';">Hello!</div>')
}

writeObject('blue') ? enter image description here

Raise warning in Python without interrupting program

import warnings
warnings.warn("Warning...........Message")

See the python documentation: here

How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9

The simplest solution might be to install Java 8 in parallel to Java 9 (if not still still existant) and specify the JVM to be used explicitly in eclipse.ini. You can find a description of this setting including a description how to find eclipse.ini on a Mac at Eclipsepedia

Best way to verify string is empty or null

Optional.ofNullable(label)
.map(String::trim)
.map(string -> !label.isEmpty)
.orElse(false)

OR

TextUtils.isNotBlank(label);

the last solution will check if not null and trimm the str at the same time

Javascript date regex DD/MM/YYYY

If you are in Javascript already, couldn't you just use Date.Parse() to validate a date instead of using regEx.

RegEx for date is actually unwieldy and hard to get right especially with leap years and all.

How do you uninstall all dependencies listed in package.json (NPM)?

Tip for Windows users: Run this PowerShell command from within node_modules parent directory:

ls .\node_modules | % {npm uninstall $_}

How to tell if a connection is dead in python

It depends on what you mean by "dropped". For TCP sockets, if the other end closes the connection either through close() or the process terminating, you'll find out by reading an end of file, or getting a read error, usually the errno being set to whatever 'connection reset by peer' is by your operating system. For python, you'll read a zero length string, or a socket.error will be thrown when you try to read or write from the socket.

Bootstrap 4 img-circle class not working

It's now called rounded-circle as explained here in the BS4 docs

<img src="img/gallery2.JPG" class="rounded-circle">

Demo

How can getContentResolver() be called in Android?

A solution would be to get the ContentResolver from the context

ContentResolver contentResolver = getContext().getContentResolver();

Link to the documentation : ContentResolver

Case-insensitive search in Rails model

Assuming that you use mysql, you could use fields that are not case sensitive: http://dev.mysql.com/doc/refman/5.0/en/case-sensitivity.html

What does collation mean?

Besides the "accented letters are sorted differently than unaccented ones" in some Western European languages, you must take into account the groups of letters, which sometimes are sorted differently, also.

Traditionally, in Spanish, "ch" was considered a letter in its own right, same with "ll" (both of which represent a single phoneme), so a list would get sorted like this:

  • caballo
  • cinco
  • coche
  • charco
  • chocolate
  • chueco
  • dado
  • (...)
  • lámpara
  • luego
  • llanta
  • lluvia
  • madera

Notice all the words starting with single c go together, except words starting with ch which go after them, same with ll-starting words which go after all the words starting with a single l. This is the ordering you'll see in old dictionaries and encyclopedias, sometimes even today by very conservative organizations.

The Royal Academy of the Language changed this to make it easier for Spanish to be accomodated in the computing world. Nevertheless, ñ is still considered a different letter than n and goes after it, and before o. So this is a correctly ordered list:

  • Namibia
  • número
  • ñandú
  • ñú
  • obra
  • ojo

By selecting the correct collation, you get all this done for you, automatically :-)

Create a user with all privileges in Oracle

There are 2 differences:

2 methods creating a user and granting some privileges to him

create user userName identified by password;
grant connect to userName;

and

grant connect to userName identified by password;

do exactly the same. It creates a user and grants him the connect role.

different outcome

resource is a role in oracle, which gives you the right to create objects (tables, procedures, some more but no views!). ALL PRIVILEGES grants a lot more of system privileges.

To grant a user all privileges run you first snippet or

grant all privileges to userName identified by password;

Using CSS :before and :after pseudo-elements with inline CSS?

No you cant target the pseudo-classes or pseudo-elements in inline-css as David Thomas said. For more details see this answer by BoltClock about Pseudo-classes

No. The style attribute only defines style properties for a given HTML element. Pseudo-classes are a member of the family of selectors, which don't occur in the attribute .....

We can also write use same for the pseudo-elements

No. The style attribute only defines style properties for a given HTML element. Pseudo-classes and pseudo-elements the are a member of the family of selectors, which don't occur in the attribute so you cant style them inline.