Programs & Examples On #Tomcat6

Version 6.x (December 2006) of the Apache Tomcat servlet container. Use only if your question is specifically related to features of this version.

HTTP Status 500 - org.apache.jasper.JasperException: java.lang.NullPointerException

NullPointerException with JSP can also happen if:

A getter returns a non-public inner class.

This code will fail if you remove Getters's access modifier or make it private or protected.

JAVA:

package com.myPackage;
public class MyClass{ 
    //: Must be public or you will get:
    //: org.apache.jasper.JasperException: 
    //: java.lang.NullPointerException
    public class Getters{
        public String 
        myProperty(){ return(my_property); }
    };;

    //: JSP EL can only access functions:
    private Getters _get;
    public  Getters  get(){ return _get; }

    private String 
    my_property;

    public MyClass(String my_property){
        super();
        this.my_property    = my_property;
        _get = new Getters();
    };;
};;

JSP

<%@ taglib uri   ="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page import="com.myPackage.MyClass" %>
<%
    MyClass inst = new MyClass("[PROP_VALUE]");
    pageContext.setAttribute("my_inst", inst ); 
%><html lang="en"><body>
    ${ my_inst.get().myProperty() }
</body></html>

How to set level logging to DEBUG in Tomcat?

JULI logging levels for Tomcat

SEVERE - Serious failures

WARNING - Potential problems

INFO - Informational messages

CONFIG - Static configuration messages

FINE - Trace messages

FINER - Detailed trace messages

FINEST - Highly detailed trace messages

You can find here more https://documentation.progress.com/output/ua/OpenEdge_latest/index.html#page/pasoe-admin/tomcat-logging.html

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

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

replace

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

with

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

There are No resources that can be added or removed from the server

The issue is incompatible web application version with the targeted server. So project facets needs to be changed. In most of the cases the "Dynamic Web Module" property. This should be the value of the servlet-api version supported by the server.

In my case,

I tried changing the web_app value in web.xml. It did not worked.

I tried changing the project facet by right clicking on project properties(as mentioned above), did not work.

What worked is: Changing "version" value as in jst.web to right version from

org.eclipse.wst.common.project.facet.core.xml file. This file is present in the .setting folder under your project root directory.

You may also look at this

How to change the ROOT application?

You can do this in a slightly hack-y way by:

  1. Stop Tomcat
  2. Move ROOT.war aside and rm -rf webapps/ROOT
  3. Copy the webapp you want to webapps/ROOT.war
  4. Start Tomcat

Increase permgen space

For tomcat you can increase the permGem space by using

 -XX:MaxPermSize=128m

For this you need to create (if not already exists) a file named setenv.sh in tomcat/bin folder and include following line in it

   export JAVA_OPTS="-XX:MaxPermSize=128m"

Reference : http://wiki.razuna.com/display/ecp/Adjusting+Memory+Settings+for+Tomcat

JAX-WS and BASIC authentication, when user names and passwords are in a database

I was face-off a similar situation, I need to provide to my WS: Username, Password and WSS Password Type.

I was initially using the "Http Basic Auth" (as @ahoge), I tried to use the @Philipp-Dev 's ref. too. I didn't get a success solution.

After a little deep search at google, I found this post:

https://stackoverflow.com/a/3117841/1223901

And there was my problem solution

I hope this can help to anyone else, like helps to me.

Rgds, iVieL

How to solve could not create the virtual machine error of Java Virtual Machine Launcher?

I was also facing this issue when we upgraded from java 8 to java 10. I solved by removing -Djava.endorsed.dirs="C:\Program Files\Apache Software Foundation\Tomcat 8.5\endorsed" from the argument.

Proxy Error 502 : The proxy server received an invalid response from an upstream server

Add this into your httpd.conf file

Timeout 2400
ProxyTimeout 2400
ProxyBadHeader Ignore 

How to change the port of Tomcat from 8080 to 80?

Running the command below worked with. Tried changing server.xml and the conf file but both didn't work.

/sbin/iptables -A INPUT -i eth0 -p tcp --dport 80 -j ACCEPT

/sbin/iptables -A INPUT -i eth0 -p tcp --dport 8080 -j ACCEPT

/sbin/iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080

The network adapter could not establish the connection - Oracle 11g

I had the similar issue. its resolved for me with a simple command.

lsnrctl start

The Network Adapter exception is caused because:

  1. The database host name or port number is wrong (OR)
  2. The database TNSListener has not been started. The TNSListener may be started with the lsnrctl utility.

Try to start the listener using the command prompt:

  1. Click Start, type cmd in the search field, and when cmd shows up in the list of options, right click it and select ‘Run as Administrator’.
  2. At the Command Prompt window, type lsnrctl start without the quotes and press Enter.
  3. Type Exit and press Enter.

Hope it helps.

Error With Port 8080 already in use

It has been long time, but I faced the same Issue, and solved it as follow: 1. tried shutting down the application server using the shutdown.bat/.bash which might be in your application Server / bin/shutdown..

  1. My Issue, was that more than 1 instance of java was running, I was changing ports, and not looking back, so it kept running other java processes, with that specific port. for windows users, : ALT+Shift+Esc, and end java processes that you are not using and now you should be able to re-use your port 8080

Best way to increase heap size in catalina.bat file

increase heap size of tomcat for window add this file in apache-tomcat-7.0.42\bin

enter image description here

heap size can be changed based on Requirements.

  set JAVA_OPTS=-Dfile.encoding=UTF-8 -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256m

How do I show the changes which have been staged?

For Staging Area vs Repository(last commit) comparison use

 $git diff --staged

The command compares your staged($ git add fileName) changes to your last commit. If you want to see what you’ve staged that will go into your next commit, you can use git diff --staged. This command compares your staged changes to your last commit.

For Working vs Staging comparison use

$ git diff 

The command compares what is in your working directory with what is in your staging area. It’s important to note that git diff by itself doesn’t show all changes made since your last commit — only changes that are still unstaged. If you’ve staged all of your changes($ git add fileName), git diff will give you no output.

Also, if you stage a file($ git add fileName) and then edit it, you can use git diff to see the changes in the file that are staged and the changes that are unstaged.

How to search for a file in the CentOS command line

CentOS is Linux, so as in just about all other Unix/Linux systems, you have the find command. To search for files within the current directory:

find -name "filename"

You can also have wildcards inside the quotes, and not just a strict filename. You can also explicitly specify a directory to start searching from as the first argument to find:

find / -name "filename"

will look for "filename" or all the files that match the regex expression in between the quotes, starting from the root directory. You can also use single quotes instead of double quotes, but in most cases you don't need either one, so the above commands will work without any quotes as well. Also, for example, if you're searching for java files and you know they are somewhere in your /home/username, do:

find /home/username -name *.java

There are many more options to the find command and you should do a:

man find

to learn more about it.

One more thing: if you start searching from / and are not root or are not sudo running the command, you might get warnings that you don't have permission to read certain directories. To ignore/remove those, do:

find / -name 'filename' 2>/dev/null

That just redirects the stderr to /dev/null.

Word wrap for a label in Windows Forms

The simple answer for this problem is to change the DOCK property of the Label. It is "NONE" by default.

Trying to SSH into an Amazon Ec2 instance - permission error

In addition to the other answers, here is what I did in order for this to work:

  • Copy the key to .ssh folder if you still hadn't:

cp key.pem ~/.ssh/key.pem

  • Give the proper permissions to the key

chmod 400 ~/.ssh/key.pem

eval `ssh-agent -s` ssh-add

  • Then, add the key

ssh-add ~/.ssh/key.pem

Now you should be able to ssh EC2 (:

What does -> mean in C++?

The -> operator, which is applied exclusively to pointers, is needed to obtain the specified field or method of the object referenced by the pointer. (this applies also to structs just for their fields)

If you have a variable ptr declared as a pointer you can think of it as (*ptr).field.

A side node that I add just to make pedantic people happy: AS ALMOST EVERY OPERATOR you can define a different semantic of the operator by overloading it for your classes.

Converting JSON to XML in Java

Use the (excellent) JSON-Java library from json.org then

JSONObject json = new JSONObject(str);
String xml = XML.toString(json);

toString can take a second argument to provide the name of the XML root node.

This library is also able to convert XML to JSON using XML.toJSONObject(java.lang.String string)

Check the Javadoc

Link to the the github repository

POM

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20160212</version>
</dependency>

original post updated with new links

How do I find a particular value in an array and return its index?

#include <vector>
#include <algorithm>

int main()
{
     int arr[5] = {4, 1, 3, 2, 6};
     int x = -1;
     std::vector<int> testVector(arr, arr + sizeof(arr) / sizeof(int) );

     std::vector<int>::iterator it = std::find(testVector.begin(), testVector.end(), 3);
     if (it != testVector.end())
     {
          x = it - testVector.begin();
     }
     return 0;
}

Or you can just build a vector in a normal way, without creating it from an array of ints and then use the same solution as shown in my example.

Where and why do I have to put the "template" and "typename" keywords?

typedef typename Tail::inUnion<U> dummy;

However, I'm not sure you're implementation of inUnion is correct. If I understand correctly, this class is not supposed to be instantiated, therefore the "fail" tab will never avtually fails. Maybe it would be better to indicates whether the type is in the union or not with a simple boolean value.

template <typename T, typename TypeList> struct Contains;

template <typename T, typename Head, typename Tail>
struct Contains<T, UnionNode<Head, Tail> >
{
    enum { result = Contains<T, Tail>::result };
};

template <typename T, typename Tail>
struct Contains<T, UnionNode<T, Tail> >
{
    enum { result = true };
};

template <typename T>
struct Contains<T, void>
{
    enum { result = false };
};

PS: Have a look at Boost::Variant

PS2: Have a look at typelists, notably in Andrei Alexandrescu's book: Modern C++ Design

Adding attribute in jQuery

$('#someid').attr('disabled', 'true');

How can I convert an image into Base64 string using JavaScript?

You could use FileAPI, but it's pretty much unsupported.

How do I set the classpath in NetBeans?

Maven

The Answer by Bhesh Gurung is correct… unless your NetBeans project is Maven based.

Dependency

Under Maven, you add a "dependency". A dependency is a description of a library (its name & version number) you want to use from your code.

Or a dependency could be a description of a library which another library needs ("depends on"). Maven automatically handles this chain, libraries that need other libraries that then need other libraries and so on. For the mathematical-minded, perhaps the phrase "Maven resolves the transitive dependencies" makes sense.

Repository

Maven gets this related-ness information, and the libraries themselves from a Maven repository. A repository is basically an online database and collection of download files (the dependency library).

Easy to Use

Adding a dependency to a Maven-based project is really quite easy. That is the whole point to Maven, to make managing dependent libraries easy and to make building them into your project easy. To get started with adding a dependency, see this Question, Adding dependencies in Maven Netbeans and my Answer with screenshot.

enter image description here

Replace whitespace with a comma in a text file in Linux

without looking at your input file, only a guess

awk '{$1=$1}1' OFS=","

redirect to another file and rename as needed

Summing elements in a list

You can use sum to sum the elements of a list, however if your list is coming from raw_input, you probably want to convert the items to int or float first:

l = raw_input().split(' ')
sum(map(int, l))

Jquery how to find an Object by attribute in an Array

Javascript has a function just for that: Array.prototype.find. As example

function isBigEnough(element) {
  return element >= 15;
}

[12, 5, 8, 130, 44].find(isBigEnough); // 130

It not difficult to extends the callback to a function. However this is not compatible with IE (and partially with Edge). For a full list look at the Browser Compatibility

Difference between return and exit in Bash functions

Remember, functions are internal to a script and normally return from whence they were called by using the return statement. Calling an external script is another matter entirely, and scripts usually terminate with an exit statement.

The difference "between the return and exit statement in Bash functions with respect to exit codes" is very small. Both return a status, not values per se. A status of zero indicates success, while any other status (1 to 255) indicates a failure. The return statement will return to the script from where it was called, while the exit statement will end the entire script from wherever it is encountered.

return 0  # Returns to where the function was called.  $? contains 0 (success).

return 1  # Returns to where the function was called.  $? contains 1 (failure).

exit 0  # Exits the script completely.  $? contains 0 (success).

exit 1  # Exits the script completely.  $? contains 1 (failure).

If your function simply ends without a return statement, the status of the last command executed is returned as the status code (and will be placed in $?).

Remember, return and exit give back a status code from 0 to 255, available in $?. You cannot stuff anything else into a status code (e.g., return "cat"); it will not work. But, a script can pass back 255 different reasons for failure by using status codes.

You can set variables contained in the calling script, or echo results in the function and use command substitution in the calling script; but the purpose of return and exit are to pass status codes, not values or computation results as one might expect in a programming language like C.

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

Very sort cut and effective solution is below:-

Add the below rule in your tsconfig.json file:-

"noImplicitAny": false

Then restart your project.

javascript onclick increment number

For those who do NOT want an input box, here's a ready-to-compile example you can check out, which just counts the button clicks, updates them in the text and toggles the font. You could take the value and use it anywhere you see fit.

<!DOCTYPE html>
<html>


<body>
<p id="demo">JavaScript can change the style of an HTML element.</p>

<script>
   function incrementValue()
        {
            var demo_id = document.getElementById('demo')
            var value = parseInt(demo_id.value, 10);
            // if NaN, set to 0, else, keep the current value
            value = isNaN(value) ? 0 : value;
            value++;
            demo_id.value = value;

            if ((value%2)==0){
                demo_id.innerHTML = value;
                demo_id.style.fontSize = "25px"; 
                demo_id.style.color = "red";
                demo_id.style.backgroundColor = "yellow";   
            } 
            else {
                demo_id.innerHTML = value.toString() ;
                demo_id.style.fontSize = "15px"; 
                demo_id.style.color = "black";
                demo_id.style.backgroundColor = "white";
            }
        }
</script>

<form>
    <input type="button" onclick="incrementValue()" value="Increment Value" />
</form>
</body>


</html>

SVN check out linux

You can use checkout or co

$ svn co http://example.com/svn/app-name directory-name

Some short codes:-

  1. checkout (co)
  2. commit (ci)
  3. copy (cp)
  4. delete (del, remove,rm)
  5. diff (di)

Java ResultSet how to check if there are any results

Best to use ResultSet.next() along with the do {...} while() syntax for this.

The "check for any results" call ResultSet.next() moves the cursor to the first row, so use the do {...} while() syntax to process that row while continuing to process remaining rows returned by the loop.

This way you get to check for any results, while at the same time also processing any results returned.

if(resultSet.next()) { // Checks for any results and moves cursor to first row,
    do { // Use 'do...while' to process the first row, while continuing to process remaining rows

    } while (resultSet.next());
}

One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll?

Make sure that your project is targeting the .NET framework 4.0. Visual Studio 2010 supports .NET 3.5 framework target also, but .NET 3.5 does not support the dynamic keyword.

You can adjust the framework version in the project properties. See http://msdn.microsoft.com/en-us/library/bb398202.aspx for more info.

Generating a unique machine id

With our licensing tool we consider the following components

  • MAC Address
  • CPU (Not the serial number, but the actual CPU profile like stepping and model)
  • System Drive Serial Number (Not Volume Label)
  • Memory
  • CD-ROM model & vendor
  • Video Card model & vendor
  • IDE Controller
  • SCSI Controller

However, rather than just hashing the components and creating a pass/fail system, we create a comparable fingerprint that can be used to determine how different two machine profiles are. If the difference rating is above a specified tolerance then ask the user to activate again.

We've found over the last 8 years in use with hundreds of thousands of end-user installs that this combination works well to provide a reliably unique machine id - even for virtual machines and cloned OS installs.

Form inline inside a form horizontal in twitter bootstrap?

Don't nest <form> tags, that will not work. Just use Bootstrap classes.

Bootstrap 3

<form class="form-horizontal" role="form">
    <div class="form-group">
      <label for="inputType" class="col-md-2 control-label">Type</label>
      <div class="col-md-3">
          <input type="text" class="form-control" id="inputType" placeholder="Type">
      </div>
    </div>
    <div class="form-group">
        <span class="col-md-2 control-label">Metadata</span>
        <div class="col-md-6">
            <div class="form-group row">
                <label for="inputKey" class="col-md-1 control-label">Key</label>
                <div class="col-md-2">
                    <input type="text" class="form-control" id="inputKey" placeholder="Key">
                </div>
                <label for="inputValue" class="col-md-1 control-label">Value</label>
                <div class="col-md-2">
                    <input type="text" class="form-control" id="inputValue" placeholder="Value">
                </div>
            </div>
        </div>
    </div>
</form>

You can achieve that behaviour in many ways, that's just an example. Test it on this bootply

Bootstrap 2

<form class="form-horizontal">
    <div class="control-group">
        <label class="control-label" for="inputType">Type</label>
        <div class="controls">
            <input type="text" id="inputType" placeholder="Type">
        </div>
    </div>
    <div class="control-group">
        <span class="control-label">Metadata</span>
        <div class="controls form-inline">
            <label for="inputKey">Key</label>
            <input type="text" class="input-small" placeholder="Key" id="inputKey">
            <label for="inputValue">Value</label>
            <input type="password" class="input-small" placeholder="Value" id="inputValue">
        </div>
    </div>
</form>

Note that I'm using .form-inline to get the propper styling inside a .controls.
You can test it on this jsfiddle

java.lang.ClassNotFoundException: org.eclipse.core.runtime.adaptor.EclipseStarter

You might be launching your application from a Product file which is not linked to the plugin file. Reset your workspace and launch using the MANIFEST.MF > Overview > Testing > Launch.

Change File Extension Using C#

try this.

filename = Path.ChangeExtension(".blah") 

in you Case:

myfile= c:/my documents/my images/cars/a.jpg;
string extension = Path.GetExtension(myffile);
filename = Path.ChangeExtension(myfile,".blah") 

You should look this post too:

http://msdn.microsoft.com/en-us/library/system.io.path.changeextension.aspx

Pycharm does not show plot

Change import to:

import matplotlib.pyplot as plt

or use this line:

plt.pyplot.show()

Display Last Saved Date on worksheet

This might be an alternative solution. Paste the following code into the new module:

Public Function ModDate()
ModDate = 
Format(FileDateTime(ThisWorkbook.FullName), "m/d/yy h:n ampm") 
End Function

Before saving your module, make sure to save your Excel file as Excel Macro-Enabled Workbook.

Paste the following code into the cell where you want to display the last modification time:

=ModDate()

I'd also like to recommend an alternative to Excel allowing you to add creation and last modification time easily. Feel free to check on RowShare and this article I wrote: https://www.rowshare.com/blog/en/2018/01/10/Displaying-Last-Modification-Time-in-Excel

How can I turn a List of Lists into a List in Java 8?

Just as @Saravana mentioned:

flatmap is better but there are other ways to achieve the same

 listStream.reduce(new ArrayList<>(), (l1, l2) -> {
        l1.addAll(l2);
        return l1;
 });

To sum up, there are several ways to achieve the same as follows:

private <T> List<T> mergeOne(Stream<List<T>> listStream) {
    return listStream.flatMap(List::stream).collect(toList());
}

private <T> List<T> mergeTwo(Stream<List<T>> listStream) {
    List<T> result = new ArrayList<>();
    listStream.forEach(result::addAll);
    return result;
}

private <T> List<T> mergeThree(Stream<List<T>> listStream) {
    return listStream.reduce(new ArrayList<>(), (l1, l2) -> {
        l1.addAll(l2);
        return l1;
    });
}

private <T> List<T> mergeFour(Stream<List<T>> listStream) {
    return listStream.reduce((l1, l2) -> {
        List<T> l = new ArrayList<>(l1);
        l.addAll(l2);
        return l;
    }).orElse(new ArrayList<>());
}

private <T> List<T> mergeFive(Stream<List<T>> listStream) {
    return listStream.collect(ArrayList::new, List::addAll, List::addAll);
}

com.jcraft.jsch.JSchException: UnknownHostKey

Supply the public rsa key of the host :-

String knownHostPublicKey = "mywebsite.com ssh-rsa AAAAB3NzaC1.....XL4Jpmp/";

session.setKnownHosts(new ByteArrayInputStream(knownHostPublicKey.getBytes()));

async/await - when to return a Task vs void?

I have come across this very useful article about async and void written by Jérôme Laban: https://jaylee.org/archive/2012/07/08/c-sharp-async-tips-and-tricks-part-2-async-void.html

The bottom line is that an async+void can crash the system and usually should be used only on the UI side event handlers.

The reason behind this is the Synchronization Context used by the AsyncVoidMethodBuilder, being none in this example. When there is no ambient Synchronization Context, any exception that is unhandled by the body of an async void method is rethrown on the ThreadPool. While there is seemingly no other logical place where that kind of unhandled exception could be thrown, the unfortunate effect is that the process is being terminated, because unhandled exceptions on the ThreadPool effectively terminate the process since .NET 2.0. You may intercept all unhandled exception using the AppDomain.UnhandledException event, but there is no way to recover the process from this event.

When writing UI event handlers, async void methods are somehow painless because exceptions are treated the same way found in non-async methods; they are thrown on the Dispatcher. There is a possibility to recover from such exceptions, with is more than correct for most cases. Outside of UI event handlers however, async void methods are somehow dangerous to use and may not that easy to find.

How to remove all CSS classes using jQuery/JavaScript?

I like using native js do this, belive it or not!

1.

// remove all items all class  
const items = document.querySelectorAll('item');
for (let i = 0; i < items.length; i++) {
    items[i].className = '';
}

2.

// only remove all class of first item
const item1 = document.querySelector('item');
item1.className = '';

jQuery ways

  1. $("#item").removeClass();

  2. $("#item").removeClass("class1 ... classn");

When is it acceptable to call GC.Collect?

I was doing some performance testing on array and list:

private static int count = 100000000;
private static List<int> GetSomeNumbers_List_int()
{
    var lstNumbers = new List<int>();
    for(var i = 1; i <= count; i++)
    {
        lstNumbers.Add(i);
    }
    return lstNumbers;
}
private static int[] GetSomeNumbers_Array()
{
    var lstNumbers = new int[count];
    for (var i = 1; i <= count; i++)
    {
        lstNumbers[i-1] = i + 1;
    }
    return lstNumbers;
}
private static int[] GetSomeNumbers_Enumerable_Range()
{
    return  Enumerable.Range(1, count).ToArray();
}

static void performance_100_Million()
{
    var sw = new Stopwatch();

    sw.Start();
    var numbers1 = GetSomeNumbers_List_int();
    sw.Stop();
    //numbers1 = null;
    //GC.Collect();
    Console.WriteLine(String.Format("\"List<int>\" took {0} milliseconds", sw.ElapsedMilliseconds));

    sw.Reset();
    sw.Start();
    var numbers2 = GetSomeNumbers_Array();
    sw.Stop();
    //numbers2 = null;
    //GC.Collect();
    Console.WriteLine(String.Format("\"int[]\" took {0} milliseconds", sw.ElapsedMilliseconds));

    sw.Reset();
    sw.Start();
//getting System.OutOfMemoryException in GetSomeNumbers_Enumerable_Range method
    var numbers3 = GetSomeNumbers_Enumerable_Range();
    sw.Stop();
    //numbers3 = null;
    //GC.Collect();

    Console.WriteLine(String.Format("\"int[]\" Enumerable.Range took {0} milliseconds", sw.ElapsedMilliseconds));
}

and I got OutOfMemoryException in GetSomeNumbers_Enumerable_Range method the only workaround is to deallocate the memory by:

numbers = null;
GC.Collect();

How to use [DllImport("")] in C#?

You can't declare an extern local method inside of a method, or any other method with an attribute. Move your DLL import into the class:

using System.Runtime.InteropServices;


public class WindowHandling
{
    [DllImport("User32.dll")]
    public static extern int SetForegroundWindow(IntPtr point);

    public void ActivateTargetApplication(string processName, List<string> barcodesList)
    {
        Process p = Process.Start("notepad++.exe");
        p.WaitForInputIdle();
        IntPtr h = p.MainWindowHandle;
        SetForegroundWindow(h);
        SendKeys.SendWait("k");
        IntPtr processFoundWindow = p.MainWindowHandle;
    }
}

Saving response from Requests to file

I believe all the existing answers contain the relevant information, but I would like to summarize.

The response object that is returned by requests get and post operations contains two useful attributes:

Response attributes

  • response.text - Contains str with the response text.
  • response.content - Contains bytes with the raw response content.

You should choose one or other of these attributes depending on the type of response you expect.

  • For text-based responses (html, json, yaml, etc) you would use response.text
  • For binary-based responses (jpg, png, zip, xls, etc) you would use response.content.

Writing response to file

When writing responses to file you need to use the open function with the appropriate file write mode.

  • For text responses you need to use "w" - plain write mode.
  • For binary responses you need to use "wb" - binary write mode.

Examples

Text request and save

# Request the HTML for this web page:
response = requests.get("https://stackoverflow.com/questions/31126596/saving-response-from-requests-to-file")
with open("response.txt", "w") as f:
    f.write(response.text)

Binary request and save

# Request the profile picture of the OP:
response = requests.get("https://i.stack.imgur.com/iysmF.jpg?s=32&g=1")
with open("response.jpg", "wb") as f:
    f.write(response.content)

Answering the original question

The original code should work by using wb and response.content:

import requests

files = {'f': ('1.pdf', open('1.pdf', 'rb'))}
response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)
response.raise_for_status() # ensure we notice bad responses
file = open("out.xls", "wb")
file.write(response.content)
file.close()

But I would go further and use the with context manager for open.

import requests

with open('1.pdf', 'rb') as file:
    files = {'f': ('1.pdf', file)}
    response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)

response.raise_for_status() # ensure we notice bad responses

with open("out.xls", "wb") as file:
    file.write(response.content)

Android Studio drawable folders

Its little tricky in android studio there is no default folder for all screen size you need to create but with little trick.

  • when you paste your image into drawable folder a popup will appear to ask about directory
  • Add subfolder name after drawable like drawable-xxhdpi
  • I will suggest you to paste image with highest resolution it will auto detect for other size.. thats it next time when you will paste it will ask to you about directory

i cant post image here so if still having any problem. here is tutorial..

Drawable folder in android studio

Get a JSON object from a HTTP response

Do this to get the JSON

String json = EntityUtils.toString(response.getEntity());

More details here : get json from HttpResponse

Java: Find .txt files in specified folder

It's really useful, I used it with a slight change:

filename=directory.list(new FilenameFilter() { 
    public boolean accept(File dir, String filename) { 
        return filename.startsWith(ipro); 
    }
});

How to split a string into an array in Bash?

We can use tr command to split string into the array object. It works both MacOS and Linux

  #!/usr/bin/env bash
  currentVersion="1.0.0.140"
  arrayData=($(echo $currentVersion | tr "." "\n"))
  len=${#arrayData[@]}
  for (( i=0; i<=$((len-1)); i++ )); do 
       echo "index $i - value ${arrayData[$i]}"
  done

Another option use IFS command

IFS='.' read -ra arrayData <<< "$currentVersion"
#It is the same as tr
arrayData=($(echo $currentVersion | tr "." "\n"))

#Print the split string
for i in "${arrayData[@]}"
do
    echo $i
done

ClientScript.RegisterClientScriptBlock?

See if the below helps you:

I was using the following earlier:

ClientScript.RegisterClientScriptBlock(Page.GetType(), "AlertMsg", "<script language='javascript'>alert('The Web Policy need to be accepted to submit the new assessor information.');</script>");

After implementing AJAX in this page, it stopped working. After reading your blog, I changed the above to:

ScriptManager.RegisterClientScriptBlock(imgBtnSubmit, this.GetType(), "AlertMsg", "<script language='javascript'>alert('The Web Policy need to be accepted to submit the new assessor information.');</script>", false);

This is working perfectly fine.

(It’s .NET 2.0 Framework, I am using)

Send password when using scp to copy files from one server to another

Here is how I resolved it.

It is not the most secure way however it solved my problem as security was not an issue on internal servers.

Create a new file say password.txt and store the password for the server where the file will be pasted. Save this to a location on the host server.

scp -W location/password.txt copy_file_location paste_file_location

Cheers!

Get input type="file" value when it has multiple files selected

You use input.files property. It's a collection of File objects and each file has a name property:

onmouseout="for (var i = 0; i < this.files.length; i++) alert(this.files[i].name);"

How to break out of a loop in Bash?

while true ; do
    ...
    if [ something ]; then
        break
    fi
done

Deep copy in ES6 using the spread syntax

I myself landed on these answers last day, trying to find a way to deep copy complex structures, which may include recursive links. As I wasn't satisfied with anything being suggested before, I implemented this wheel myself. And it works quite well. Hope it helps someone.

Example usage:

OriginalStruct.deep_copy = deep_copy; // attach the function as a method

TheClone = OriginalStruct.deep_copy();

Please look at https://github.com/latitov/JS_DeepCopy for live examples how to use it, and also deep_print() is there.

If you need it quick, right here's the source of deep_copy() function:

function deep_copy() {
    'use strict';   // required for undef test of 'this' below

    // Copyright (c) 2019, Leonid Titov, Mentions Highly Appreciated.

    var id_cnt = 1;
    var all_old_objects = {};
    var all_new_objects = {};
    var root_obj = this;

    if (root_obj === undefined) {
        console.log(`deep_copy() error: wrong call context`);
        return;
    }

    var new_obj = copy_obj(root_obj);

    for (var id in all_old_objects) {
        delete all_old_objects[id].__temp_id;
    }

    return new_obj;
    //

    function copy_obj(o) {
        var new_obj = {};
        if (o.__temp_id === undefined) {
            o.__temp_id = id_cnt;
            all_old_objects[id_cnt] = o;
            all_new_objects[id_cnt] = new_obj;
            id_cnt ++;

            for (var prop in o) {
                if (o[prop] instanceof Array) {
                    new_obj[prop] = copy_array(o[prop]);
                }
                else if (o[prop] instanceof Object) {
                    new_obj[prop] = copy_obj(o[prop]);
                }
                else if (prop === '__temp_id') {
                    continue;
                }
                else {
                    new_obj[prop] = o[prop];
                }
            }
        }
        else {
            new_obj = all_new_objects[o.__temp_id];
        }
        return new_obj;
    }
    function copy_array(a) {
        var new_array = [];
        if (a.__temp_id === undefined) {
            a.__temp_id = id_cnt;
            all_old_objects[id_cnt] = a;
            all_new_objects[id_cnt] = new_array;
            id_cnt ++;

            a.forEach((v,i) => {
                if (v instanceof Array) {
                    new_array[i] = copy_array(v);
                }
                else if (v instanceof Object) {
                    new_array[i] = copy_object(v);
                }
                else {
                    new_array[i] = v;
                }
            });
        }
        else {
            new_array = all_new_objects[a.__temp_id];
        }
        return new_array;
    }
}

Cheers@!

Install shows error in console: INSTALL FAILED CONFLICTING PROVIDER

This can also happen when you have an older version of your app installed and made changes to the (support) library or the manifest file. Deleting the old applications from your device (Settings --> Application --> <your application> --> Uninstall) will solve the issue then.

How do I perform a GROUP BY on an aliased column in MS-SQL Server?

In the old FoxPro (I haven't used it since version 2.5), you could write something like this:

SELECT       LastName + ', ' + FirstName AS 'FullName', Birthday, Title
FROM         customers
GROUP BY     1,3,2

I really liked that syntax. Why isn't it implemented anywhere else? It's a nice shortcut, but I assume it causes other problems?

2D arrays in Python

In Python one would usually use lists for this purpose. Lists can be nested arbitrarily, thus allowing the creation of a 2D array. Not every sublist needs to be the same size, so that solves your other problem. Have a look at the examples I linked to.

What is the copy-and-swap idiom?

There are some good answers already. I'll focus mainly on what I think they lack - an explanation of the "cons" with the copy-and-swap idiom....

What is the copy-and-swap idiom?

A way of implementing the assignment operator in terms of a swap function:

X& operator=(X rhs)
{
    swap(rhs);
    return *this;
}

The fundamental idea is that:

  • the most error-prone part of assigning to an object is ensuring any resources the new state needs are acquired (e.g. memory, descriptors)

  • that acquisition can be attempted before modifying the current state of the object (i.e. *this) if a copy of the new value is made, which is why rhs is accepted by value (i.e. copied) rather than by reference

  • swapping the state of the local copy rhs and *this is usually relatively easy to do without potential failure/exceptions, given the local copy doesn't need any particular state afterwards (just needs state fit for the destructor to run, much as for an object being moved from in >= C++11)

When should it be used? (Which problems does it solve [/create]?)

  • When you want the assigned-to objected unaffected by an assignment that throws an exception, assuming you have or can write a swap with strong exception guarantee, and ideally one that can't fail/throw..†

  • When you want a clean, easy to understand, robust way to define the assignment operator in terms of (simpler) copy constructor, swap and destructor functions.

    • Self-assignment done as a copy-and-swap avoids oft-overlooked edge cases.‡

  • When any performance penalty or momentarily higher resource usage created by having an extra temporary object during the assignment is not important to your application. ?

swap throwing: it's generally possible to reliably swap data members that the objects track by pointer, but non-pointer data members that don't have a throw-free swap, or for which swapping has to be implemented as X tmp = lhs; lhs = rhs; rhs = tmp; and copy-construction or assignment may throw, still have the potential to fail leaving some data members swapped and others not. This potential applies even to C++03 std::string's as James comments on another answer:

@wilhelmtell: In C++03, there is no mention of exceptions potentially thrown by std::string::swap (which is called by std::swap). In C++0x, std::string::swap is noexcept and must not throw exceptions. – James McNellis Dec 22 '10 at 15:24


‡ assignment operator implementation that seems sane when assigning from a distinct object can easily fail for self-assignment. While it might seem unimaginable that client code would even attempt self-assignment, it can happen relatively easily during algo operations on containers, with x = f(x); code where f is (perhaps only for some #ifdef branches) a macro ala #define f(x) x or a function returning a reference to x, or even (likely inefficient but concise) code like x = c1 ? x * 2 : c2 ? x / 2 : x;). For example:

struct X
{
    T* p_;
    size_t size_;
    X& operator=(const X& rhs)
    {
        delete[] p_;  // OUCH!
        p_ = new T[size_ = rhs.size_];
        std::copy(p_, rhs.p_, rhs.p_ + rhs.size_);
    }
    ...
};

On self-assignment, the above code delete's x.p_;, points p_ at a newly allocated heap region, then attempts to read the uninitialised data therein (Undefined Behaviour), if that doesn't do anything too weird, copy attempts a self-assignment to every just-destructed 'T'!


? The copy-and-swap idiom can introduce inefficiencies or limitations due to the use of an extra temporary (when the operator's parameter is copy-constructed):

struct Client
{
    IP_Address ip_address_;
    int socket_;
    X(const X& rhs)
      : ip_address_(rhs.ip_address_), socket_(connect(rhs.ip_address_))
    { }
};

Here, a hand-written Client::operator= might check if *this is already connected to the same server as rhs (perhaps sending a "reset" code if useful), whereas the copy-and-swap approach would invoke the copy-constructor which would likely be written to open a distinct socket connection then close the original one. Not only could that mean a remote network interaction instead of a simple in-process variable copy, it could run afoul of client or server limits on socket resources or connections. (Of course this class has a pretty horrid interface, but that's another matter ;-P).

regex match any single character (one character only)

Match any single character

  • Use the dot . character as a wildcard to match any single character.

Example regex: a.c

abc   // match
a c   // match
azc   // match
ac    // no match
abbc  // no match

Match any specific character in a set

  • Use square brackets [] to match any characters in a set.
  • Use \w to match any single alphanumeric character: 0-9, a-z, A-Z, and _ (underscore).
  • Use \d to match any single digit.
  • Use \s to match any single whitespace character.

Example 1 regex: a[bcd]c

abc   // match
acc   // match
adc   // match
ac    // no match
abbc  // no match

Example 2 regex: a[0-7]c

a0c   // match
a3c   // match
a7c   // match
a8c   // no match
ac    // no match
a55c  // no match

Match any character except ...

Use the hat in square brackets [^] to match any single character except for any of the characters that come after the hat ^.

Example regex: a[^abc]c

aac   // no match
abc   // no match
acc   // no match
a c   // match
azc   // match
ac    // no match
azzc  // no match

(Don't confuse the ^ here in [^] with its other usage as the start of line character: ^ = line start, $ = line end.)

Match any character optionally

Use the optional character ? after any character to specify zero or one occurrence of that character. Thus, you would use .? to match any single character optionally.

Example regex: a.?c

abc   // match
a c   // match
azc   // match
ac    // match
abbc  // no match

See also

Equivalent of LIMIT and OFFSET for SQL Server?

The equivalent of LIMIT is SET ROWCOUNT, but if you want generic pagination it's better to write a query like this:

;WITH Results_CTE AS
(
    SELECT
        Col1, Col2, ...,
        ROW_NUMBER() OVER (ORDER BY SortCol1, SortCol2, ...) AS RowNum
    FROM Table
    WHERE <whatever>
)
SELECT *
FROM Results_CTE
WHERE RowNum >= @Offset
AND RowNum < @Offset + @Limit

The advantage here is the parameterization of the offset and limit in case you decide to change your paging options (or allow the user to do so).

Note: the @Offset parameter should use one-based indexing for this rather than the normal zero-based indexing.

How to pass integer from one Activity to another?

In Activity A

private void startSwitcher() {
    int yourInt = 200;
    Intent myIntent = new Intent(A.this, B.class);
    intent.putExtra("yourIntName", yourInt);
    startActivity(myIntent);
}

in Activity B

int score = getIntent().getIntExtra("yourIntName", 0);

@Directive vs @Component in Angular

In Angular 2 and above, “everything is a component.” Components are the main way we build and specify elements and logic on the page, through both custom elements and attributes that add functionality to our existing components.

http://learnangular2.com/components/

But what directives do then in Angular2+ ?

Attribute directives attach behaviour to elements.

There are three kinds of directives in Angular:

  1. Components—directives with a template.
  2. Structural directives—change the DOM layout by adding and removing DOM elements.
  3. Attribute directives—change the appearance or behaviour of an element, component, or another directive.

https://angular.io/docs/ts/latest/guide/attribute-directives.html

So what's happening in Angular2 and above is Directives are attributes which add functionalities to elements and components.

Look at the sample below from Angular.io:

import { Directive, ElementRef, Input } from '@angular/core';

@Directive({ selector: '[myHighlight]' })
export class HighlightDirective {
    constructor(el: ElementRef) {
       el.nativeElement.style.backgroundColor = 'yellow';
    }
}

So what it does, it will extends you components and HTML elements with adding yellow background and you can use it as below:

<p myHighlight>Highlight me!</p>

But components will create full elements with all functionalities like below:

import { Component } from '@angular/core';

@Component({
  selector: 'my-component',
  template: `
    <div>Hello my name is {{name}}. 
      <button (click)="sayMyName()">Say my name</button>
    </div>
   `
})
export class MyComponent {
  name: string;
  constructor() {
    this.name = 'Alireza'
  }
  sayMyName() {
    console.log('My name is', this.name)
  }
}

and you can use it as below:

<my-component></my-component>

When we use the tag in the HTML, this component will be created and the constructor get called and rendered.

Pandas convert string to int

You need add parameter errors='coerce' to function to_numeric:

ID = pd.to_numeric(ID, errors='coerce')

If ID is column:

df.ID = pd.to_numeric(df.ID, errors='coerce')

but non numeric are converted to NaN, so all values are float.

For int need convert NaN to some value e.g. 0 and then cast to int:

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)

Sample:

df = pd.DataFrame({'ID':['4806105017087','4806105017087','CN414149']})
print (df)
              ID
0  4806105017087
1  4806105017087
2       CN414149

print (pd.to_numeric(df.ID, errors='coerce'))
0    4.806105e+12
1    4.806105e+12
2             NaN
Name: ID, dtype: float64

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)
print (df)
              ID
0  4806105017087
1  4806105017087
2              0

EDIT: If use pandas 0.25+ then is possible use integer_na:

df.ID = pd.to_numeric(df.ID, errors='coerce').astype('Int64')
print (df)
              ID
0  4806105017087
1  4806105017087
2            NaN

Escaping quotes and double quotes

Escaping parameters like that is usually source of frustration and feels a lot like a time wasted. I see you're on v2 so I would suggest using a technique that Joel "Jaykul" Bennet blogged about a while ago.

Long story short: you just wrap your string with @' ... '@ :

Start-Process \\server\toto.exe @'
-batch=B -param="sort1;parmtxt='Security ID=1234'"
'@

(Mind that I assumed which quotes are needed, and which things you were attempting to escape.) If you want to work with the output, you may want to add the -NoNewWindow switch.

BTW: this was so important issue that since v3 you can use --% to stop the PowerShell parser from doing anything with your parameters:

\\server\toto.exe --% -batch=b -param="sort1;paramtxt='Security ID=1234'"

... should work fine there (with the same assumption).

How to edit one specific row in Microsoft SQL Server Management Studio 2008?

Use the "Edit top 200" option, then click on "Show SQL panel", modify your query with your WHERE clause, and execute the query. You'll be able to edit the results.

HTML Upload MAX_FILE_SIZE does not appear to work

There IS A POINT in introducing MAX_FILE_SIZE client side hidden form field.

php.ini can limit uploaded file size. So, while your script honors the limit imposed by php.ini, different HTML forms can further limit an uploaded file size. So, when uploading video, form may limit* maximum size to 10MB, and while uploading photos, forms may put a limit of just 1mb. And at the same time, the maximum limit can be set in php.ini to suppose 10mb to allow all this.

Although this is not a fool proof way of telling the server what to do, yet it can be helpful.

  • HTML does'nt limit anything. It just forwards the server all form variable including MAX_FILE_SIZE and its value.

Hope it helped someone.

Incorrect string value: '\xF0\x9F\x8E\xB6\xF0\x9F...' MySQL

Change database charset and collation

ALTER DATABASE
    database_name
    CHARACTER SET = utf8mb4
    COLLATE = utf8mb4_unicode_ci;

change specific table's charset and collation

ALTER TABLE
    table_name
    CONVERT TO CHARACTER SET utf8mb4
    COLLATE utf8mb4_unicode_ci;

change connection charset in mysql driver

before

charset=utf8&parseTime=True&loc=Local

after

charset=utf8mb4&collation=utf8mb4_unicode_ci&parseTime=True&loc=Local

From this article https://hackernoon.com/today-i-learned-storing-emoji-to-mysql-with-golang-204a093454b7

Check the current number of connections to MongoDb

In OS X, too see the connections directly on the network interface, just do:

$ lsof -n -i4TCP:27017

mongod     2191 inanc    7u  IPv4 0xab6d9f844e21142f  0t0  TCP 127.0.0.1:27017 (LISTEN)
mongod     2191 inanc   33u  IPv4 0xab6d9f84604cd757  0t0  TCP 127.0.0.1:27017->127.0.0.1:56078 (ESTABLISHED)
stores.te 18704 inanc    6u  IPv4 0xab6d9f84604d404f  0t0  TCP 127.0.0.1:56078->127.0.0.1:27017 (ESTABLISHED)
  • No need to use grep etc, just use the lsof's arguments.

  • Too see the connections on MongoDb's CLI, see @milan's answer (which I just edited).

How to do the equivalent of pass by reference for primitives in Java

Java is not call by reference it is call by value only

But all variables of object type are actually pointers.

So if you use a Mutable Object you will see the behavior you want

public class XYZ {

    public static void main(String[] arg) {
        StringBuilder toyNumber = new StringBuilder("5");
        play(toyNumber);
        System.out.println("Toy number in main " + toyNumber);
    }

    private static void play(StringBuilder toyNumber) {
        System.out.println("Toy number in play " + toyNumber);
        toyNumber.append(" + 1");
        System.out.println("Toy number in play after increement " + toyNumber);
    }
}

Output of this code:

run:
Toy number in play 5
Toy number in play after increement 5 + 1
Toy number in main 5 + 1
BUILD SUCCESSFUL (total time: 0 seconds)

You can see this behavior in Standard libraries too. For example Collections.sort(); Collections.shuffle(); These methods does not return a new list but modifies it's argument object.

    List<Integer> mutableList = new ArrayList<Integer>();

    mutableList.add(1);
    mutableList.add(2);
    mutableList.add(3);
    mutableList.add(4);
    mutableList.add(5);

    System.out.println(mutableList);

    Collections.shuffle(mutableList);

    System.out.println(mutableList);

    Collections.sort(mutableList);

    System.out.println(mutableList);

Output of this code:

run:
[1, 2, 3, 4, 5]
[3, 4, 1, 5, 2]
[1, 2, 3, 4, 5]
BUILD SUCCESSFUL (total time: 0 seconds)

How do I generate random integers within a specific range in Java?

ThreadLocalRandom equivalent of class java.util.Random for multithreaded environment. Generating a random number is carried out locally in each of the threads. So we have a better performance by reducing the conflicts.

int rand = ThreadLocalRandom.current().nextInt(x,y);

x,y - intervals e.g. (1,10)

Set height of chart in Chart.js

You can also set the dimensions to the canvas

<canvas id="myChart" width="400" height="400"></canvas>

And then set the responsive options to false to always maintain the chart at the size specified.

options: {
    responsive: false,
}

Does Eclipse have line-wrap

Update 2016

As mentioned by ralfstx's answer, Eclipse 4.6 M4 Neon (or more) has a word-wrap feature!
(Nov 2015, for release mid 2016). In any editor view, type:

Alt+Shift+Y

https://www.eclipse.org/eclipse/news/4.6/M4/images/word-wrap.png

(Sadik confirms in the comments it works with Eclipse 2019-09)

By default, text editors are opened with word wrap disabled.
This can be changed with the Enable word wrap when opening an editor option on the General > Editors > Text Editors preference page.

Manually toggle word wrap by clicking in the editor window and pressing (Shift+Alt+Y).
On Mac OS X, press (Cmd-Opt-Y). [Updated May 2017]

The famous bug 35779 is finally closed by r/#/c/61972/ last November.

There are however a few new bugs:

As long as we are unable to provide acceptable editor performance for big files after toggling editor word wrap state on, we should make sure users can't set WW preference 1 always on by default and wonder why the editors are slow during resizing/zooming.

(2020) MarcGuay adds in the comments:

If you want the wrapping to be persistent/automatic, the cdhq plugin seems to still work with the 2019-03 version of Eclipse.
After installing you can turn it on via Window->Preferences->Word Wrap.


Update 2014

The de.cdhq.eclipse.wordwrap Word-Wrap Eclipse plug-in just got updated, and does provide good wrapping, as illustrated in the project page:

http://dev.cdhq.de/eclipse/word-wrap/img/01_wrappingOff.gifhttp://dev.cdhq.de/eclipse/word-wrap/img/02_wrappingOn_full.gif


Original answer May 2010

Try the Eclipse Word-Wrap Plug-In here.

Just for the record, while Eclipse Colorer might bring wrapping for xml files, Eclipse has not in general a soft wrapping feature for Text editor.

Soft and hard. Soft will just warp the text at the right window border without adding new line numbers (so there are gaps in the list of numbers when you enable them).

This is one of the most upvoted bugs in Eclipse history: bug 35779 (9 years and counting, 200+ votes)

Update February 2013:

That bug references an old Word wrap plugin, but Oak mentions in his answer (upvoted) a new plugin for recent (Juno+) versions of Eclipse (so 3.8.x, 4.x, may have been seen working with 3.7)
That plugin is from Florian Weßling, who just updated it (March 2013)

Right click in an opened file and select "Toggle Word Wrap" (shortcut ctrl+alt+e)

before
words wrapped

In nodeJs is there a way to loop through an array without using array size?

In ES5 there is no efficient way to iterate over a sparse array without using the length property. In ES6 you can use for...of. Take this examples:

_x000D_
_x000D_
'use strict';_x000D_
_x000D_
var arr = ['one', 'two', undefined, 3, 4],_x000D_
    output;_x000D_
_x000D_
arr[6] = 'five';_x000D_
_x000D_
output = '';_x000D_
arr.forEach(function (val) {_x000D_
    output += val + ' ';_x000D_
});_x000D_
console.log(output);_x000D_
_x000D_
output = '';_x000D_
for (var i = 0; i < arr.length; i++) {_x000D_
    output += arr[i] + ' ';_x000D_
}_x000D_
console.log(output);_x000D_
_x000D_
output = '';_x000D_
for (var val of arr) {_x000D_
    output += val + ' ';_x000D_
};_x000D_
console.log(output);
_x000D_
<!-- results pane console output; see http://meta.stackexchange.com/a/242491 -->_x000D_
<script src="//gh-canon.github.io/stack-snippet-console/console.min.js"></script>
_x000D_
_x000D_
_x000D_

All array methods which you can use to iterate safely over dense arrays use the length property of an object created by calling ToObject internaly. See for instance the algorithm used in the forEach method: http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18 However in es6, you can use for...of safely for iterating over sparse arrays.

See also Are Javascript arrays sparse?.

Oracle SQL convert date format from DD-Mon-YY to YYYYMM

As offer_date is an number, and is of lower accuracy than your real dates, this may work...
- Convert your real date to a string of format YYYYMM
- Conver that value to an INT
- Compare the result you your offer_date

SELECT
  *
FROM
  offers
WHERE
    offer_date = (SELECT CAST(to_char(create_date, 'YYYYMM') AS INT) FROM customers where id = '12345678')
AND offer_rate > 0 

Also, by doing all the manipulation on the create_date you only do the processing on one value.

Additionally, had you manipulated the offer_date you would not be able to utilise any index on that field, and so force SCANs instead of SEEKs.

What is the easiest way to initialize a std::vector with hardcoded elements?

If you can, use the modern C++[11,14,17,...] way:

std::vector<int> vec = {10,20,30};

The old way of looping over a variable-length array or using sizeof() is truly terrible on the eyes and completely unnecessary in terms of mental overhead. Yuck.

How to clear the canvas for redrawing

This worked for my pieChart in chart.js

<div class="pie_nut" id="pieChartContainer">
    <canvas id="pieChart" height="5" width="6"></canvas> 
</div>

$('#pieChartContainer').html(''); //remove canvas from container
$('#pieChartContainer').html('<canvas id="pieChart" height="5" width="6"></canvas>'); //add it back to the container

How to get a jqGrid cell value when editing

I think that Aidan's answer is by far the best.

$('#yourgrid').jqGrid("editCell", 0, 0, false);

This commits any current edits, giving you access to the real value. I prefer it because:

  • You don't have to hard-code any cell references in.
    • It is particularly well suited to using getRowData() to get the entire grid, as it doesn't care which cell you've just been editing.
    • You're not trying to parse some markup generated by jqGrid which may change in future.
    • If the user is saving, then ending the edit session is likely the behaviour they would want anyway.

How to delete multiple files at once in Bash on Linux?

Bash supports all sorts of wildcards and expansions.

Your exact case would be handled by brace expansion, like so:

$ rm -rf abc.log.2012-03-{14,27,28}

The above would expand to a single command with all three arguments, and be equivalent to typing:

$ rm -rf abc.log.2012-03-14 abc.log.2012-03-27 abc.log.2012-03-28

It's important to note that this expansion is done by the shell, before rm is even loaded.

Using switch statement with a range of value in each case?

Try this if you must use switch.

public static int range(int num){ 
    if ( 10 < num && num < 20)
        return 1;
    if ( 20 <= num && num < 30)
        return 2;
    return 3;
}

public static final int TEN_TWENTY = 1;
public static final int TWENTY_THIRTY = 2;

public static void main(String[]args){
    int a = 110;
    switch (range(a)){
        case TEN_TWENTY: 
            System.out.println("10-20"); 
            break;
        case TWENTY_THIRTY: 
            System.out.println("20-30"); 
            break;
        default: break;
    }
}

How do I resolve ClassNotFoundException?

Basic Generic Question - Simplest Generic Answer ;)

Given the information I will make the assumption that you might be trying a basic approach to coding, building/compiling and running a simple console app like "Hello World", using some simple text editor and some Command Shell.

This error occurs in the fallowing scenario:

..\SomePath>javac HelloWorld.java
..\SomePath>java HelloWorld.class

In other words, use:

..\SomePath>java HelloWorld

P.S. The adding the file extension .class produces the same mistake. Also be sure to have the Java's (JDK/JRE) bin folder in the operating system's Environment Variables's PATH.(Lookup for more details other posts on this) P.P.S Was I correct in my assumption/s?

Stash only one file out of multiple files that have changed with Git?

Disclaimer: the following answer is for git before git 2.13. For git 2.13 and over, check out another answer further down.


Warning

As noted in the comments, this puts everything into the stash, both staged and unstaged. The --keep-index just leaves the index alone after the stash is done. This can cause merge conflicts when you later pop the stash.


This will stash everything that you haven't previously added. Just git add the things you want to keep, then run it.

git stash --keep-index

For example, if you want to split an old commit into more than one changeset, you can use this procedure:

  1. git rebase -i <last good commit>
  2. Mark some changes as edit.
  3. git reset HEAD^
  4. git add <files you want to keep in this change>
  5. git stash --keep-index
  6. Fix things up as necessary. Don't forget to git add any changes.
  7. git commit
  8. git stash pop
  9. Repeat, from #5, as necessary.
  10. git rebase --continue

How can I build a recursive function in python?

Recursion in Python works just as recursion in an other language, with the recursive construct defined in terms of itself:

For example a recursive class could be a binary tree (or any tree):

class tree():
    def __init__(self):
        '''Initialise the tree'''
        self.Data = None
        self.Count = 0
        self.LeftSubtree = None
        self.RightSubtree = None

    def Insert(self, data):
        '''Add an item of data to the tree'''
        if self.Data == None:
            self.Data = data
            self.Count += 1
        elif data < self.Data:
            if self.LeftSubtree == None:
                # tree is a recurive class definition
                self.LeftSubtree = tree()
            # Insert is a recursive function
            self.LeftSubtree.Insert(data)
        elif data == self.Data:
            self.Count += 1
        elif data > self.Data:
            if self.RightSubtree == None:
                self.RightSubtree = tree()
            self.RightSubtree.Insert(data)

if __name__ == '__main__':
    T = tree()
    # The root node
    T.Insert('b')
    # Will be put into the left subtree
    T.Insert('a')
    # Will be put into the right subtree
    T.Insert('c')

As already mentioned a recursive structure must have a termination condition. In this class, it is not so obvious because it only recurses if new elements are added, and only does it a single time extra.

Also worth noting, python by default has a limit to the depth of recursion available, to avoid absorbing all of the computer's memory. On my computer this is 1000. I don't know if this changes depending on hardware, etc. To see yours :

import sys
sys.getrecursionlimit()

and to set it :

import sys #(if you haven't already)
sys.setrecursionlimit()

edit: I can't guarentee that my binary tree is the most efficient design ever. If anyone can improve it, I'd be happy to hear how

How do I make a JSON object with multiple arrays?

Enclosed in {} represents an object; enclosed in [] represents an array, there can be multiple objects in the array
example object :

{
    "brand": "bwm", 
    "price": 30000
}


{
    "brand": "benz", 
    "price": 50000
}

example array:

[
    {
        "brand": "bwm", 
        "price": 30000
    }, 
    {
        "brand": "benz", 
        "price": 50000
    }
]

In order to use JSON more beautifully, you can go here JSON Viewer do format

Passing command line arguments from Maven as properties in pom.xml

I used the properties plugin to solve this.

Properties are defined in the pom, and written out to a my.properties file, where they can then be accessed from your Java code.

In my case it is test code that needs to access this properties file, so in the pom the properties file is written to maven's testOutputDirectory:

<configuration>
    <outputFile>${project.build.testOutputDirectory}/my.properties</outputFile>
</configuration>

Use outputDirectory if you want properties to be accessible by your app code:

<configuration>
    <outputFile>${project.build.outputDirectory}/my.properties</outputFile>
</configuration>

For those looking for a fuller example (it took me a bit of fiddling to get this working as I didn't understand how naming of properties tags affects ability to retrieve them elsewhere in the pom file), my pom looks as follows:

<dependencies>
     <dependency>
      ...
     </dependency>
</dependencies>

<properties>
    <app.env>${app.env}</app.env>
    <app.port>${app.port}</app.port>
    <app.domain>${app.domain}</app.domain>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.20</version>
        </plugin>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>properties-maven-plugin</artifactId>
            <version>1.0.0</version>
            <executions>
                <execution>
                    <phase>generate-resources</phase>
                    <goals>
                        <goal>write-project-properties</goal>
                    </goals>
                    <configuration>
                        <outputFile>${project.build.testOutputDirectory}/my.properties</outputFile>
                    </configuration>
                </execution>
            </executions>
        </plugin>

    </plugins>
</build>

And on the command line:

mvn clean test -Dapp.env=LOCAL -Dapp.domain=localhost -Dapp.port=9901

So these properties can be accessed from the Java code:

 java.io.InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("my.properties");
 java.util.Properties properties = new Properties();
 properties.load(inputStream);
 appPort = properties.getProperty("app.port");
 appDomain = properties.getProperty("app.domain");

Execute Python script via crontab

As you have mentioned it doesn't change anything.

First, you should redirect both standard input and standard error from the crontab execution like below:

*/2 * * * * /usr/bin/python /home/souza/Documets/Listener/listener.py > /tmp/listener.log 2>&1

Then you can view the file /tmp/listener.log to see if the script executed as you expected.

Second, I guess what you mean by change anything is by watching the files created by your program:

f = file('counter', 'r+w')
json_file = file('json_file_create_server.json', 'r+w')

The crontab job above won't create these file in directory /home/souza/Documets/Listener, as the cron job is not executed in this directory, and you use relative path in the program. So to create this file in directory /home/souza/Documets/Listener, the following cron job will do the trick:

*/2 * * * * cd /home/souza/Documets/Listener && /usr/bin/python listener.py > /tmp/listener.log 2>&1

Change to the working directory and execute the script from there, and then you can view the files created in place.

"ssl module in Python is not available" when installing package with pip3

If you are on Windows and use Anaconda you can try running "pip install ..." command in Anaconda Prompt instead of cmd.exe, as user willliu1995 suggests here. This was the fastest solution for me, that does not require installation of additional components.

How to get the bluetooth devices as a list?

You should change your code as below:

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

List<String> s = new ArrayList<String>();
for(BluetoothDevice bt : pairedDevices)
   s.add(bt.getName());

setListAdapter(new ArrayAdapter<String>(this, R.layout.list, s));

css transition opacity fade background

Wrap your image with a span element with a black background.

_x000D_
_x000D_
.img-wrapper {
  display: inline-block;
  background: #000;
}

.item-fade {
  vertical-align: top;
  transition: opacity 0.3s;
  -webkit-transition: opacity 0.3s;
  opacity: 1;
}

.item-fade:hover {
  opacity: 0.2;
}
_x000D_
<span class="img-wrapper">
   <img class="item-fade" src="http://placehold.it/100x100/cf5" />
</span>
_x000D_
_x000D_
_x000D_

How to iterate through a String

How about this

for (int i = 0; i < str.length(); i++) { 
    System.out.println(str.substring(i, i + 1)); 
} 

How to get the last five characters of a string using Substring() in C#?

In C# 8.0 and later you can use [^5..] to get the last five characters combined with a ? operator to avoid a potential ArgumentOutOfRangeException.

string input1 = "0123456789";
string input2 = "0123";
Console.WriteLine(input1.Length >= 5 ? input1[^5..] : input1); //returns 56789
Console.WriteLine(input2.Length >= 5 ? input2[^5..] : input2); //returns 0123

index-from-end-operator and range-operator

Add line break to ::after or ::before pseudo-element content

For people who will going to look for 'How to change dynamically content on pseudo element adding new line sign" here's answer

Html chars like &#13;&#10; will not work appending them to html using JavaScript because those characters are changed on document render

Instead you need to find unicode representation of this characters which are U+000D and U+000A so we can do something like

_x000D_
_x000D_
var el = document.querySelector('div');_x000D_
var string = el.getAttribute('text').replace(/, /, '\u000D\u000A');_x000D_
el.setAttribute('text', string);
_x000D_
div:before{_x000D_
   content: attr(text);_x000D_
   white-space: pre;_x000D_
}
_x000D_
<div text='I want to break it in javascript, after comma sign'></div> 
_x000D_
_x000D_
_x000D_

Hope this save someones time, good luck :)

How do I copy the contents of one stream to another?

From .NET 4.5 on, there is the Stream.CopyToAsync method

input.CopyToAsync(output);

This will return a Task that can be continued on when completed, like so:

await input.CopyToAsync(output)

// Code from here on will be run in a continuation.

Note that depending on where the call to CopyToAsync is made, the code that follows may or may not continue on the same thread that called it.

The SynchronizationContext that was captured when calling await will determine what thread the continuation will be executed on.

Additionally, this call (and this is an implementation detail subject to change) still sequences reads and writes (it just doesn't waste a threads blocking on I/O completion).

From .NET 4.0 on, there's is the Stream.CopyTo method

input.CopyTo(output);

For .NET 3.5 and before

There isn't anything baked into the framework to assist with this; you have to copy the content manually, like so:

public static void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[32768];
    int read;
    while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        output.Write (buffer, 0, read);
    }
}

Note 1: This method will allow you to report on progress (x bytes read so far ...)
Note 2: Why use a fixed buffer size and not input.Length? Because that Length may not be available! From the docs:

If a class derived from Stream does not support seeking, calls to Length, SetLength, Position, and Seek throw a NotSupportedException.

matplotlib has no attribute 'pyplot'

pyplot is a sub-module of matplotlib which doesn't get imported with a simple import matplotlib.

>>> import matplotlib
>>> print matplotlib.pyplot
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'
>>> import matplotlib.pyplot
>>> 

It seems customary to do: import matplotlib.pyplot as plt at which time you can use the various functions and classes it contains:

p = plt.plot(...)

Java collections convert a string to a list of characters

You will have to either use a loop, or create a collection wrapper like Arrays.asList which works on primitive char arrays (or directly on strings).

List<Character> list = new ArrayList<Character>();
Set<Character> unique = new HashSet<Character>();
for(char c : "abc".toCharArray()) {
    list.add(c);
    unique.add(c);
}

Here is an Arrays.asList like wrapper for strings:

public List<Character> asList(final String string) {
    return new AbstractList<Character>() {
       public int size() { return string.length(); }
       public Character get(int index) { return string.charAt(index); }
    };
}

This one is an immutable list, though. If you want a mutable list, use this with a char[]:

public List<Character> asList(final char[] string) {
    return new AbstractList<Character>() {
       public int size() { return string.length; }
       public Character get(int index) { return string[index]; }
       public Character set(int index, Character newVal) {
          char old = string[index];
          string[index] = newVal;
          return old;
       }
    };
}

Analogous to this you can implement this for the other primitive types. Note that using this normally is not recommended, since for every access you would do a boxing and unboxing operation.

The Guava library contains similar List wrapper methods for several primitive array classes, like Chars.asList, and a wrapper for String in Lists.charactersOf(String).

LINUX: Link all files from one to another directory

The posted solutions will not link any hidden files. To include them, try this:

cd /usr/lib
find /mnt/usr/lib -maxdepth 1 -print "%P\n" | while read file; do ln -s "/mnt/usr/lib/$file" "$file"; done

If you should happen to want to recursively create the directories and only link files (so that if you create a file within a directory, it really is in /usr/lib not /mnt/usr/lib), you could do this:

cd /usr/lib
find /mnt/usr/lib -mindepth 1 -depth -type d -printf "%P\n" | while read dir; do mkdir -p "$dir"; done
find /mnt/usr/lib -type f -printf "%P\n" | while read file; do ln -s "/mnt/usr/lib/$file" "$file"; done

Is there a minlength validation attribute in HTML5?

minlength attribute is now widely supported in most of the browsers.

<input type="text" minlength="2" required>

But, as with other HTML5 features, IE11 is missing from this panorama. So, if you have a wide IE11 user base, consider using the pattern HTML5 attribute that is supported almost across the board in most browsers (including IE11).

To have a nice and uniform implementation and maybe extensible or dynamic (based on the framework that generate your HTML), I would vote for the pattern attribute:

<input type="text" pattern=".{2,}" required>

There is still a small usability catch when using pattern. The user will see a non-intuitive (very generic) error/warning message when using pattern. See this jsfiddle or below:

_x000D_
_x000D_
<h3>In each form type 1 character and press submit</h3>_x000D_
</h2>_x000D_
<form action="#">_x000D_
  Input with minlength: <input type="text" minlength="2" required name="i1">_x000D_
  <input type="submit" value="Submit">_x000D_
</form>_x000D_
<br>_x000D_
<form action="#">_x000D_
  Input with patern: <input type="text" pattern=".{2,}" required name="i1">_x000D_
  <input type="submit" value="Submit">_x000D_
</form>
_x000D_
_x000D_
_x000D_

For example, in Chrome (but similar in most browsers), you will get the following error messages:

Please lengthen this text to 2 characters or more (you are currently using 1 character)

by using minlength and

Please match the format requested

by using pattern.

How do I vertically align text in a div?

Using flex, be careful with differences in browsers' rendering.

This works well both for Chrome and Internet Explorer:

_x000D_
_x000D_
.outer {_x000D_
    display: flex;_x000D_
    width: 200px;_x000D_
    height: 200px;_x000D_
    background-color: #ffc;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
    display: flex;_x000D_
    width: 50%;_x000D_
    height: 50%;_x000D_
    margin: auto;_x000D_
    text-align: center;_x000D_
    justify-content: center;_x000D_
    align-items: center;_x000D_
    background-color: #fcc;_x000D_
}
_x000D_
<div class="outer"><div class="inner">Active Tasks</div></div>
_x000D_
_x000D_
_x000D_

Compare with this one that works only with Chrome:

_x000D_
_x000D_
.outer {_x000D_
    display: flex;_x000D_
    width: 200px;_x000D_
    height: 200px;_x000D_
    background-color: #ffc;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
    display: flex;_x000D_
    width: 50%;_x000D_
    height: 50%;_x000D_
    margin: auto;_x000D_
    background-color: #fcc;_x000D_
}
_x000D_
<div class="outer">_x000D_
<div class="inner"><span style=" margin: auto;">Active Tasks</span></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Restore the mysql database from .frm files

Copy all file and replace to /var/lib/mysql , after that you must change owner of files to mysql this is so important if mariadb.service restart has been faild

chown -R mysql:mysql /var/lib/mysql/*

and

chmod -R 700 /var/lib/mysql/*

Getting "method not valid without suitable object" error when trying to make a HTTP request in VBA?

You probably haven't added a reference to Microsoft XML (any version) for Dim objHTTP As New MSXML2.XMLHTTP in the VBA window's Tools/References... dialog.

Also, it's a good idea to avoid using late binding (CreateObject...); better to use early binding (Dim objHTTP As New MSXML2.XMLHTTP), as early binding allows you to use Intellisense to list the members and do all sorts of design-time validation.

How to generate and auto increment Id with Entity Framework

You have a bad table design. You can't autoincrement a string, that doesn't make any sense. You have basically two options:

1.) change type of ID to int instead of string
2.) not recommended!!! - handle autoincrement by yourself. You first need to get the latest value from the database, parse it to the integer, increment it and attach it to the entity as a string again. VERY BAD idea

First option requires to change every table that has a reference to this table, BUT it's worth it.

Converting dict to OrderedDict

Use dict.items(); it can be as simple as following:

ship = collections.OrderedDict(ship.items())

In Java, how do I convert a byte array to a string of hex digits while keeping leading zeros?

You can use the one below. I tested this with leading zero bytes and with initial negative bytes as well

public static String toHex(byte[] bytes) {
    BigInteger bi = new BigInteger(1, bytes);
    return String.format("%0" + (bytes.length << 1) + "X", bi);
}

If you want lowercase hex digits, use "x" in the format String.

Rotating a point about another point (2D)

I struggled while working MS OCR Read API which returns back angle of rotation in range (-180, 180]. So I have to do an extra step of converting negative angles to positive. I hope someone struggling with point rotation with negative or positive angles can use the following.

def rotate(origin, point, angle):
    """
    Rotate a point counter-clockwise by a given angle around a given origin.
    """
    # Convert negative angles to positive
    angle = normalise_angle(angle)

    # Convert to radians
    angle = math.radians(angle)

    # Convert to radians
    ox, oy = origin
    px, py = point
    
    # Move point 'p' to origin (0,0)
    _px = px - ox
    _py = py - oy
    
    # Rotate the point 'p' 
    qx = (math.cos(angle) * _px) - (math.sin(angle) * _py)
    qy = (math.sin(angle) * _px) + (math.cos(angle) * _py)
    
    # Move point 'p' back to origin (ox, oy)
    qx = ox + qx
    qy = oy + qy
    
    return [qx, qy]


def normalise_angle(angle):
    """ If angle is negative then convert it to positive. """
    if (angle != 0) & (abs(angle) == (angle * -1)):
        angle = 360 + angle
    return angle

How to set width of mat-table column in angular?

Just need to update the width of the th tag.

th {
  width: 100px;
}

Run batch file from Java code

Rather than Runtime.exec(String command), you need to use the exec(String command, String[] envp, File dir) method signature:

Process p =  Runtime.getRuntime().exec("cmd /c upsert.bat", null, new File("C:\\Program Files\\salesforce.com\\Data Loader\\cliq_process\\upsert"));

But personally, I'd use ProcessBuilder instead, which is a little more verbose but much easier to use and debug than Runtime.exec().

ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "upsert.bat");
File dir = new File("C:/Program Files/salesforce.com/Data Loader/cliq_process/upsert");
pb.directory(dir);
Process p = pb.start();

Set bootstrap modal body height by percentage

This worked for me

.modal-dialog,
.modal-content {
    /* 80% of window height */
    height: 80%;
}

.modal-body {
    /* 100% = dialog height, 120px = header + footer */
    max-height: calc(100% - 120px);
    overflow-y: scroll;
}

Fiddle: http://jsfiddle.net/mehmetatas/18dpgqpb/2/

VB.NET - How to move to next item a For Each Loop?

I want to be clear that the following code is not good practice. You can use GOTO Label:

For Each I As Item In Items

    If I = x Then
       'Move to next item
        GOTO Label1
    End If

    ' Do something
    Label1:
Next

String's Maximum length in Java - calling length() method

The Return type of the length() method of the String class is int.

public int length()

Refer http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#length()

So the maximum value of int is 2147483647.

String is considered as char array internally,So indexing is done within the maximum range. This means we cannot index the 2147483648th member.So the maximum length of String in java is 2147483647.

Primitive data type int is 4 bytes(32 bits) in java.As 1 bit (MSB) is used as a sign bit,The range is constrained within -2^31 to 2^31-1 (-2147483648 to 2147483647). We cannot use negative values for indexing.So obviously the range we can use is from 0 to 2147483647.

Convert string to date then format the date

Tested this code

java.text.DateFormat formatter = new java.text.SimpleDateFormat("MM-dd-yyyy");
java.util.Date newDate = new java.util.Date();
System.out.println(formatter.format(newDate ));

http://download.oracle.com/javase/1,5.0/docs/api/java/text/SimpleDateFormat.html

Select rows with same id but different value in another column

$sql="SELECT * FROM TABLE_NAME WHERE item_id=".$item_id;

$query=mysql_query($sql);

while($myrow=mysql_fetch_array($query)) {

echo   print_r($myrow,1);


}

XPath: How to select elements based on their value?

The condition below:

//Element[@attribute1="abc" and @attribute2="xyz" and Data]

checks for the existence of the element Data within Element and not for element value Data.

Instead you can use

//Element[@attribute1="abc" and @attribute2="xyz" and text()="Data"]

Escape double quote in grep

The problem is that you aren't correctly escaping the input string, try:

echo "\"member\":\"time\"" | grep -e "member\""

Alternatively, you can use unescaped double quotes within single quotes:

echo '"member":"time"' | grep -e 'member"'

It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd').

Retrofit 2: Get JSON from Response body

use this to get String

String res = response.body().string();

instead of

String res = response.body().toString();

and always keep a check for null before converting responsebody to string

if(response.body() != null){
     //do your stuff   
}

Rails: How do I create a default value for attributes in Rails activerecord's model?

Just strengthening Jim's answer

Using presence one can do

class Task < ActiveRecord::Base
  before_save :default_values
  def default_values
    self.status = status.presence || 'P'
  end
end

How do I use the Tensorboard callback of Keras?

You should check out Losswise (https://losswise.com), it has a plugin for Keras that's easier to use than Tensorboard and has some nice extra features. With Losswise you'd just use from losswise.libs import LosswiseKerasCallback and then callback = LosswiseKerasCallback(tag='my fancy convnet 1') and you're good to go (see https://docs.losswise.com/#keras-plugin).

How to make borders collapse (on a div)?

Example of using border-collapse: separate; as

  • container displayed as table:

    ol[type="I"]>li{
      display: table;
      border-collapse: separate;
      border-spacing: 1rem;
    }
    
  • Bootstrap 3 modal vertical position center

    All what I did in my case is to set the Top in my css knowing the height of the modal

    <div id="myModal" class="modal fade"> ... </div>

    in my css i set

    #myModal{
        height: 400px;
        top: calc(50% - 200px) !important;
    }
    

    Error: Could not find or load main class in intelliJ IDE

    Explicitly creating an out folder and then setting the output path to C:\Users\USERNAME\IdeaProjects\PROJECTNAME\out

    LIKE THIS

    seemed to work for me when just out, and expecting IntelliJ to make the folder wouldn't.


    Also try having IntelliJ make you a new run configuration:

    Find the previous one by clicking

    ![Edit Configurations

    then remove it

    enter image description here

    and hit okay.

    Now, (IMPORTANT STEP) open the class containing your main method. This is probably easiest done by clicking on the class name in the left-hand side Project Pane.

    Give 'er a Alt + Shift + F10 and you should get a

    THIS

    Now hit Enter!!

    Tadah?? (Did it work?)

    Delimiter must not be alphanumeric or backslash and preg_match

    Maybe not related to original code example, but I received the error "Delimiter must not be alphanumeric or backslash" and Googled here. Reason: I mixed order of parameters for preg_match. Pattern was the second parameter and string to match was first. Be careful :)

    new Date() is working in Chrome but not Firefox

    Simple Solution, This works with All Browsers,

    var StringDate = "24-11-2017"   
    var DateVar = StringDate.split("-");
    var DateVal = new Date(DateVar[1] + "/" + DateVar[0] + "/" + DateVar[2]);
    alert(DateVal);
    

    How can I reference a commit in an issue comment on GitHub?

    If you are trying to reference a commit in another repo than the issue is in, you can prefix the commit short hash with reponame@.

    Suppose your commit is in the repo named dev, and the GitLab issue is in the repo named test. You can leave a comment on the issue and reference the commit by dev@e9c11f0a (where e9c11f0a is the first 8 letters of the sha hash of the commit you want to link to) if that makes sense.

    Temporarily change current working directory in bash to run a command

    Something like this should work:

    sh -c 'cd /tmp && exec pwd'
    

    Run MySQLDump without Locking Tables

    If you use the Percona XtraDB Cluster - I found that adding --skip-add-locks
    to the mysqldump command Allows the Percona XtraDB Cluster to run the dump file without an issue about LOCK TABLES commands in the dump file.

    How to Display Multiple Google Maps per page with API V3

    Here's another example if you have the long and lat, in my case using Umbraco Google Map Datatype package and outputting a list of divs with class "map" eg.

    <div class="map" id="UK">52.21454000000001,0.14044490000003407,13</div>
    

    my JavaScript using Google Maps API v3 based on Cultiv Razor examples

    $('.map').each(function (index, Element) {
        var coords = $(Element).text().split(",");
        if (coords.length != 3) {
            $(this).display = "none";
            return;
        }
        var latlng = new google.maps.LatLng(parseFloat(coords[0]), parseFloat(coords[1]));
        var myOptions = {
            zoom: parseFloat(coords[2]),
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            disableDefaultUI: false,
            mapTypeControl: true,
            zoomControl: true,
            zoomControlOptions: {
                style: google.maps.ZoomControlStyle.SMALL
            }
        };
        var map = new google.maps.Map(Element, myOptions);
    
        var marker = new google.maps.Marker({
            position: latlng,
            map: map
        });
    });
    

    How do I 'foreach' through a two-dimensional array?

    Remember that a multi-dimensional array is like a table. You don't have an x element and a y element for each entry; you have a string at (for instance) table[1,2].

    So, each entry is still only one string (in your example), it's just an entry at a specific x/y value. So, to get both entries at table[1, x], you'd do a nested for loop. Something like the following (not tested, but should be close)

    for (int x = 0; x < table.Length; x++)
    {
        for (int y = 0; y < table.Length; y += 2)
        {
            Console.WriteLine("{0} {1}", table[x, y], table[x, y + 1]);
        }
    }
    

    How to install plugin for Eclipse from .zip

    Seen here. You can unzip and

    enter image description here enter image description here

    Clicking Local will prefix your location fith file:/C:/etc/folder

    You can Click archive instead and select your zip, as suggested in the second popular question. It will prefix with jar://path.zip but it is not accepted by Eclipse itself. So, I used the plain folder solution.

    git: 'credential-cache' is not a git command

    We had the same issue with our Azure DevOps repositories after our domain changed, i.e. from @xy.com to @xyz.com. To fix this issue, we generated a fresh personal access token with the following permissions:

    Code: read & write Packaging: read

    Then we opened the Windows Credential Manager, added a new generic windows credential with the following details:

    Internet or network address: "git:{projectname}@dev.azure.com/{projectname}" - alternatively you should use your git repository name here.
    User name: "Personal Access Token"
    Password: {The generated Personal Access Token}

    Afterwards all our git operations were working again. Hope this helps someone else!

    Android Closing Activity Programmatically

    What about the Activity.finish() method (quoting) :

    Call this when your activity is done and should be closed.

    What is the basic difference between the Factory and Abstract Factory Design Patterns?

    The major difference in those factories is when what you want to do with the factories and when you want to use it.

    Sometimes, when you are doing IOC (inversion of control e.g. constructor injection), you know that you can create solid objects. As mentioned in the example above of fruits, if you are ready to create objects of fruits, you can use simple factory pattern.

    But many times, you do not want to create solid objects, they will come later in the program flow. But the configuration tells you the what kind of factory you want to use at start, instead of creating objects, you can pass on factories which are derived from a common factory class to the constructor in IOC.

    So, I think its also about the object lifetime and creation.

    How to include an HTML page into another HTML page without frame/iframe?

    If you're willing to use jquery, there is a handy jquery plugin called "inc".

    I use it often for website prototyping, where I just want to present the client with static HTML with no backend layer that can be quickly created/edited/improved/re-presented

    http://johannburkard.de/blog/programming/javascript/inc-a-super-tiny-client-side-include-javascript-jquery-plugin.html

    For example, things like the menu and footer need to be shown on every page, but you dont want to end up with a copy-and-paste-athon

    You can include a page fragment as follows

    <p class="inc:footer.htm"></p>
    

    How to view files in binary from bash?

    As a fallback there's always od -xc filename

    Add items to comboBox in WPF

    Use this

    string[] str = new string[] {"Foo", "Bar"};
    
    myComboBox.ItemsSource = str;
    myComboBox.SelectedIndex = 0;
    

    OR

    foreach (string s in str)
        myComboBox.Items.Add(s);
    
    myComboBox.SelectedIndex = 0;      
    

    Truncate Decimal number not Round Off

    double d = 2.22977777;
    d = ( (double) ( (int) (d * 1000.0) ) ) / 1000.0 ;
    

    Of course, this won't work if you're trying to truncate rounding error, but it should work fine with the values you give in your examples. See the first two answers to this question for details on why it won't work sometimes.

    Get first n characters of a string

    If there is no hard requirement on the length of the truncated string, one can use this to truncate and prevent cutting the last word as well:

    $text = "Knowledge is a natural right of every human being of which no one
    has the right to deprive him or her under any pretext, except in a case where a
    person does something which deprives him or her of that right. It is mere
    stupidity to leave its benefits to certain individuals and teams who monopolize
    these while the masses provide the facilities and pay the expenses for the
    establishment of public sports.";
    
    // we don't want new lines in our preview
    $text_only_spaces = preg_replace('/\s+/', ' ', $text);
    
    // truncates the text
    $text_truncated = mb_substr($text_only_spaces, 0, mb_strpos($text_only_spaces, " ", 50));
    
    // prevents last word truncation
    $preview = trim(mb_substr($text_truncated, 0, mb_strrpos($text_truncated, " ")));
    

    In this case, $preview will be "Knowledge is a natural right of every human being".

    Live code example: http://sandbox.onlinephpfunctions.com/code/25484a8b687d1f5ad93f62082b6379662a6b4713

    error LNK2038: mismatch detected for '_MSC_VER': value '1600' doesn't match value '1700' in CppFile1.obj

    You are trying to link objects compiled by different versions of the compiler. That's not supported in modern versions of VS, at least not if you are using the C++ standard library. Different versions of the standard library are binary incompatible and so you need all the inputs to the linker to be compiled with the same version. Make sure you re-compile all the objects that are to be linked.

    The compiler error names the objects involved so the information the the question already has the answer you are looking for. Specifically it seems that the static library that you are linking needs to be re-compiled.

    So the solution is to recompile Projectname1.lib with VS2012.

    Declaring a python function with an array parameters and passing an array argument to the function call?

    Maybe you want unpack elements of array, I don't know if I got it, but below a example:

    def my_func(*args):
        for a in args:
            print a
    
    my_func(*[1,2,3,4])
    my_list = ['a','b','c']
    my_func(*my_list)
    

    Best way to parse command-line parameters?

    I like the clean look of this code... gleaned from a discussion here: http://www.scala-lang.org/old/node/4380

    object ArgParser {
      val usage = """
    Usage: parser [-v] [-f file] [-s sopt] ...
    Where: -v   Run verbosely
           -f F Set input file to F
           -s S Set Show option to S
    """
    
      var filename: String = ""
      var showme: String = ""
      var debug: Boolean = false
      val unknown = "(^-[^\\s])".r
    
      val pf: PartialFunction[List[String], List[String]] = {
        case "-v" :: tail => debug = true; tail
        case "-f" :: (arg: String) :: tail => filename = arg; tail
        case "-s" :: (arg: String) :: tail => showme = arg; tail
        case unknown(bad) :: tail => die("unknown argument " + bad + "\n" + usage)
      }
    
      def main(args: Array[String]) {
        // if there are required args:
        if (args.length == 0) die()
        val arglist = args.toList
        val remainingopts = parseArgs(arglist,pf)
    
        println("debug=" + debug)
        println("showme=" + showme)
        println("filename=" + filename)
        println("remainingopts=" + remainingopts)
      }
    
      def parseArgs(args: List[String], pf: PartialFunction[List[String], List[String]]): List[String] = args match {
        case Nil => Nil
        case _ => if (pf isDefinedAt args) parseArgs(pf(args),pf) else args.head :: parseArgs(args.tail,pf)
      }
    
      def die(msg: String = usage) = {
        println(msg)
        sys.exit(1)
      }
    
    }
    

    How to get the innerHTML of selectable jquery element?

    The parameter ui has a property called selected which is a reference to the selected dom element, you can call innerHTML on that element.

    Your code $('.ui-selected').innerHTML tries to return the innerHTML property of a jQuery wrapper element for a dom element with class ui-selected

    $(function () {
        $("#select-image").selectable({
            selected: function (event, ui) {
                var $variable = ui.selected.innerHTML; // or $(ui.selected).html()
                console.log($variable);
            }
        });
    });
    

    Demo: Fiddle

    Illegal access: this web application instance has been stopped already

    Restarting Your Server Can Resolve this problem.

    I was getting the same error while Using Dynamic Jasper Reporting , When i deploy my Application for first use to Create Reports, the Report creation works fine, But Once I Do Hot Deployment of some code changes To the Server, I was getting This Error.

    Detect key input in Python

    Key input is a predefined event. You can catch events by attaching event_sequence(s) to event_handle(s) by using one or multiple of the existing binding methods(bind, bind_class, tag_bind, bind_all). In order to do that:

    1. define an event_handle method
    2. pick an event(event_sequence) that fits your case from an events list

    When an event happens, all of those binding methods implicitly calls the event_handle method while passing an Event object, which includes information about specifics of the event that happened, as the argument.

    In order to detect the key input, one could first catch all the '<KeyPress>' or '<KeyRelease>' events and then find out the particular key used by making use of event.keysym attribute.

    Below is an example using bind to catch both '<KeyPress>' and '<KeyRelease>' events on a particular widget(root):

    try:                        # In order to be able to import tkinter for
        import tkinter as tk    # either in python 2 or in python 3
    except ImportError:
        import Tkinter as tk
    
    
    def event_handle(event):
        # Replace the window's title with event.type: input key
        root.title("{}: {}".format(str(event.type), event.keysym))
    
    
    if __name__ == '__main__':
        root = tk.Tk()
        event_sequence = '<KeyPress>'
        root.bind(event_sequence, event_handle)
        root.bind('<KeyRelease>', event_handle)
        root.mainloop()
    

    What is the right way to POST multipart/form-data using curl?

    This is what worked for me

    curl --form file='@filename' URL
    

    It seems when I gave this answer (4+ years ago), I didn't really understand the question, or how form fields worked. I was just answering based on what I had tried in a difference scenario, and it worked for me.

    So firstly, the only mistake the OP made was in not using the @ symbol before the file name. Secondly, my answer which uses file=... only worked for me because the form field I was trying to do the upload for was called file. If your form field is called something else, use that name instead.

    Explanation

    From the curl manpages; under the description for the option --form it says:

    This enables uploading of binary files etc. To force the 'content' part to be a file, prefix the file name with an @ sign. To just get the content part from a file, prefix the file name with the symbol <. The difference between @ and < is then that @ makes a file get attached in the post as a file upload, while the < makes a text field and just get the contents for that text field from a file.

    Chances are that if you are trying to do a form upload, you will most likely want to use the @ prefix to upload the file rather than < which uploads the contents of the file.

    Addendum

    Now I must also add that one must be careful with using the < symbol because in most unix shells, < is the input redirection symbol [which coincidentally will also supply the contents of the given file to the command standard input of the program before <]. This means that if you do not properly escape that symbol or wrap it in quotes, you may find that your curl command does not behave the way you expect.

    On that same note, I will also recommend quoting the @ symbol.


    You may also be interested in this other question titled: application/x-www-form-urlencoded or multipart/form-data?

    I say this because curl offers other ways of uploading a file, but they differ in the content-type set in the header. For example the --data option offers a similar mechanism for uploading files as data, but uses a different content-type for the upload.

    Anyways that's all I wanted to say about this answer since it started to get more upvotes. I hope this helps erase any confusions such as the difference between this answer and the accepted answer. There is really none, except for this explanation.

    How do I print uint32_t and uint16_t variables value?

    The macros defined in <inttypes.h> are the most correct way to print values of types uint32_t, uint16_t, and so forth -- but they're not the only way.

    Personally, I find those macros difficult to remember and awkward to use. (Given the syntax of a printf format string, that's probably unavoidable; I'm not claiming I could have come up with a better system.)

    An alternative is to cast the values to a predefined type and use the format for that type.

    Types int and unsigned int are guaranteed by the language to be at least 16 bits wide, and therefore to be able to hold any converted value of type int16_t or uint16_t, respectively. Similarly, long and unsigned long are at least 32 bits wide, and long long and unsigned long long are at least 64 bits wide.

    For example, I might write your program like this (with a few additional tweaks):

    #include <stdio.h>
    #include <stdint.h>
    #include <netinet/in.h>  
    
    int main(void)
    {
        uint32_t a=12, a1;
        uint16_t b=1, b1;
        a1 = htonl(a);
        printf("%lu---------%lu\n", (unsigned long)a, (unsigned long)a1);
        b1 = htons(b);
        printf("%u-----%u\n", (unsigned)b, (unsigned)b1);
        return 0;
    }
    

    One advantage of this approach is that it can work even with pre-C99 implementations that don't support <inttypes.h>. Such an implementation most likely wouldn't have <stdint.h> either, but the technique is useful for other integer types.

    Set the text in a span

    You need to fix your selector. Although CSS syntax requires multiple classes to be space separated, selector syntax would require them to be directly concatenated, and dot prefixed:

    $(".ui-icon.ui-icon-circle-triangle-w").text(...);
    

    or better:

    $(".ui-datepicker-prev > span").text(...);
    

    Space between two rows in a table?

    tr { 
        display: block;
        margin-bottom: 5px;
    }
    

    List<object>.RemoveAll - How to create an appropriate Predicate

    Little bit off topic but say i want to remove all 2s from a list. Here's a very elegant way to do that.

    void RemoveAll<T>(T item,List<T> list)
    {
        while(list.Contains(item)) list.Remove(item);
    }
    

    With predicate:

    void RemoveAll<T>(Func<T,bool> predicate,List<T> list)
    {
        while(list.Any(predicate)) list.Remove(list.First(predicate));
    }
    

    +1 only to encourage you to leave your answer here for learning purposes. You're also right about it being off-topic, but I won't ding you for that because of there is significant value in leaving your examples here, again, strictly for learning purposes. I'm posting this response as an edit because posting it as a series of comments would be unruly.

    Though your examples are short & compact, neither is elegant in terms of efficiency; the first is bad at O(n2), the second, absolutely abysmal at O(n3). Algorithmic efficiency of O(n2) is bad and should be avoided whenever possible, especially in general-purpose code; efficiency of O(n3) is horrible and should be avoided in all cases except when you know n will always be very small. Some might fling out their "premature optimization is the root of all evil" battle axes, but they do so naïvely because they do not truly understand the consequences of quadratic growth since they've never coded algorithms that have to process large datasets. As a result, their small-dataset-handling algorithms just run generally slower than they could, and they have no idea that they could run faster. The difference between an efficient algorithm and an inefficient algorithm is often subtle, but the performance difference can be dramatic. The key to understanding the performance of your algorithm is to understand the performance characteristics of the primitives you choose to use.

    In your first example, list.Contains() and Remove() are both O(n), so a while() loop with one in the predicate & the other in the body is O(n2); well, technically O(m*n), but it approaches O(n2) as the number of elements being removed (m) approaches the length of the list (n).

    Your second example is even worse: O(n3), because for every time you call Remove(), you also call First(predicate), which is also O(n). Think about it: Any(predicate) loops over the list looking for any element for which predicate() returns true. Once it finds the first such element, it returns true. In the body of the while() loop, you then call list.First(predicate) which loops over the list a second time looking for the same element that had already been found by list.Any(predicate). Once First() has found it, it returns that element which is passed to list.Remove(), which loops over the list a third time to yet once again find that same element that was previously found by Any() and First(), in order to finally remove it. Once removed, the whole process starts over at the beginning with a slightly shorter list, doing all the looping over and over and over again starting at the beginning every time until finally no more elements matching the predicate remain. So the performance of your second example is O(m*m*n), or O(n3) as m approaches n.

    Your best bet for removing all items from a list that match some predicate is to use the generic list's own List<T>.RemoveAll(predicate) method, which is O(n) as long as your predicate is O(1). A for() loop technique that passes over the list only once, calling list.RemoveAt() for each element to be removed, may seem to be O(n) since it appears to pass over the loop only once. Such a solution is more efficient than your first example, but only by a constant factor, which in terms of algorithmic efficiency is negligible. Even a for() loop implementation is O(m*n) since each call to Remove() is O(n). Since the for() loop itself is O(n), and it calls Remove() m times, the for() loop's growth is O(n2) as m approaches n.

    -didSelectRowAtIndexPath: not being called

    I have read all the answers and strongly agree with them. But it is entirely different in my case. I had new segue for my detailViewController linked directly to my tableCell in StoryBoard which caused this. So I had to remove that segue from my cell and linked it with the UITableViewController itself. Now by writing the following code it works,

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            tableView.deselectRow(at: indexPath, animated: true)
            // Do any operation
            performSegue(withIdentifier: "DetailSegue", sender: self)
        }
    

    Hope this solution will help someone out there!

    Numpy Resize/Rescale Image

    One-line numpy solution for downsampling (by 2):

    smaller_img = bigger_img[::2, ::2]
    

    And upsampling (by 2):

    bigger_img = smaller_img.repeat(2, axis=0).repeat(2, axis=1)
    

    (this asssumes HxWxC shaped image. h/t to L. Kärkkäinen in the comments above. note this method only allows whole integer resizing (e.g., 2x but not 1.5x))

    What does 'corrupted double-linked list' mean

    Heap overflow should be blame (but not always) for corrupted double-linked list, malloc(): memory corruption, double free or corruption (!prev)-like glibc warnings.

    It should be reproduced by the following code:

    #include <vector>
    
    using std::vector;
    
    
    int main(int argc, const char *argv[])
    {
        int *p = new int[3];
        vector<int> vec;
        vec.resize(100);
        p[6] = 1024;
        delete[] p;
        return 0;
    }
    

    if compiled using g++ (4.5.4):

    $ ./heapoverflow
    *** glibc detected *** ./heapoverflow: double free or corruption (!prev): 0x0000000001263030 ***
    ======= Backtrace: =========
    /lib64/libc.so.6(+0x7af26)[0x7f853f5d3f26]
    ./heapoverflow[0x40138e]
    ./heapoverflow[0x400d9c]
    ./heapoverflow[0x400bd9]
    ./heapoverflow[0x400aa6]
    ./heapoverflow[0x400a26]
    /lib64/libc.so.6(__libc_start_main+0xfd)[0x7f853f57b4bd]
    ./heapoverflow[0x4008f9]
    ======= Memory map: ========
    00400000-00403000 r-xp 00000000 08:02 2150398851                         /data1/home/mckelvin/heapoverflow
    00602000-00603000 r--p 00002000 08:02 2150398851                         /data1/home/mckelvin/heapoverflow
    00603000-00604000 rw-p 00003000 08:02 2150398851                         /data1/home/mckelvin/heapoverflow
    01263000-01284000 rw-p 00000000 00:00 0                                  [heap]
    7f853f559000-7f853f6fa000 r-xp 00000000 09:01 201329536                  /lib64/libc-2.15.so
    7f853f6fa000-7f853f8fa000 ---p 001a1000 09:01 201329536                  /lib64/libc-2.15.so
    7f853f8fa000-7f853f8fe000 r--p 001a1000 09:01 201329536                  /lib64/libc-2.15.so
    7f853f8fe000-7f853f900000 rw-p 001a5000 09:01 201329536                  /lib64/libc-2.15.so
    7f853f900000-7f853f904000 rw-p 00000000 00:00 0
    7f853f904000-7f853f919000 r-xp 00000000 09:01 74726670                   /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libgcc_s.so.1
    7f853f919000-7f853fb19000 ---p 00015000 09:01 74726670                   /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libgcc_s.so.1
    7f853fb19000-7f853fb1a000 r--p 00015000 09:01 74726670                   /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libgcc_s.so.1
    7f853fb1a000-7f853fb1b000 rw-p 00016000 09:01 74726670                   /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libgcc_s.so.1
    7f853fb1b000-7f853fc11000 r-xp 00000000 09:01 201329538                  /lib64/libm-2.15.so
    7f853fc11000-7f853fe10000 ---p 000f6000 09:01 201329538                  /lib64/libm-2.15.so
    7f853fe10000-7f853fe11000 r--p 000f5000 09:01 201329538                  /lib64/libm-2.15.so
    7f853fe11000-7f853fe12000 rw-p 000f6000 09:01 201329538                  /lib64/libm-2.15.so
    7f853fe12000-7f853fefc000 r-xp 00000000 09:01 74726678                   /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libstdc++.so.6.0.18
    7f853fefc000-7f85400fb000 ---p 000ea000 09:01 74726678                   /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libstdc++.so.6.0.18
    7f85400fb000-7f8540103000 r--p 000e9000 09:01 74726678                   /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libstdc++.so.6.0.18
    7f8540103000-7f8540105000 rw-p 000f1000 09:01 74726678                   /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libstdc++.so.6.0.18
    7f8540105000-7f854011a000 rw-p 00000000 00:00 0
    7f854011a000-7f854013c000 r-xp 00000000 09:01 201328977                  /lib64/ld-2.15.so
    7f854031c000-7f8540321000 rw-p 00000000 00:00 0
    7f8540339000-7f854033b000 rw-p 00000000 00:00 0
    7f854033b000-7f854033c000 r--p 00021000 09:01 201328977                  /lib64/ld-2.15.so
    7f854033c000-7f854033d000 rw-p 00022000 09:01 201328977                  /lib64/ld-2.15.so
    7f854033d000-7f854033e000 rw-p 00000000 00:00 0
    7fff92922000-7fff92943000 rw-p 00000000 00:00 0                          [stack]
    7fff929ff000-7fff92a00000 r-xp 00000000 00:00 0                          [vdso]
    ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]
    [1]    18379 abort      ./heapoverflow
    

    and if compiled using clang++(6.0 (clang-600.0.56)):

    $  ./heapoverflow
    [1]    96277 segmentation fault  ./heapoverflow
    

    If you thought you might have written a bug like that, here is some hints to trace it out.

    First, compile the code with debug flag(-g):

    g++ -g foo.cpp
    

    And then, run it using valgrind:

    $ valgrind ./a.out
    ==12693== Memcheck, a memory error detector
    ==12693== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
    ==12693== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
    ==12693== Command: ./a.out
    ==12693==
    ==12693== Invalid write of size 4
    ==12693==    at 0x400A25: main (foo.cpp:11)
    ==12693==  Address 0x5a1c058 is 12 bytes after a block of size 12 alloc'd
    ==12693==    at 0x4C2B800: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
    ==12693==    by 0x4009F6: main (foo.cpp:8)
    ==12693==
    ==12693==
    ==12693== HEAP SUMMARY:
    ==12693==     in use at exit: 0 bytes in 0 blocks
    ==12693==   total heap usage: 2 allocs, 2 frees, 412 bytes allocated
    ==12693==
    ==12693== All heap blocks were freed -- no leaks are possible
    ==12693==
    ==12693== For counts of detected and suppressed errors, rerun with: -v
    ==12693== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
    

    The bug is located in ==12693== at 0x400A25: main (foo.cpp:11)

    How can I account for period (AM/PM) using strftime?

    >>> from datetime import datetime
    >>> print(datetime.today().strftime("%H:%M %p"))
    15:31 AM
    

    Try replacing %I with %H.

    Elevating process privilege programmatically?

    You can indicate the new process should be started with elevated permissions by setting the Verb property of your startInfo object to 'runas', as follows:

    startInfo.Verb = "runas";
    

    This will cause Windows to behave as if the process has been started from Explorer with the "Run as Administrator" menu command.

    This does mean the UAC prompt will come up and will need to be acknowledged by the user: if this is undesirable (for example because it would happen in the middle of a lengthy process), you'll need to run your entire host process with elevated permissions by Create and Embed an Application Manifest (UAC) to require the 'highestAvailable' execution level: this will cause the UAC prompt to appear as soon as your app is started, and cause all child processes to run with elevated permissions without additional prompting.

    Edit: I see you just edited your question to state that "runas" didn't work for you. That's really strange, as it should (and does for me in several production apps). Requiring the parent process to run with elevated rights by embedding the manifest should definitely work, though.

    CSS Grid Layout not working in IE11 even with prefixes

    Michael has given a very comprehensive answer, but I'd like to point out a few things which you can still do to be able to use grids in IE in a nearly painless way.

    The repeat functionality is supported

    You can still use the repeat functionality, it's just hiding behind a different syntax. Instead of writing repeat(4, 1fr), you have to write (1fr)[4]. That's it. See this series of articles for the current state of affairs: https://css-tricks.com/css-grid-in-ie-debunking-common-ie-grid-misconceptions/

    Supporting grid-gap

    Grid gaps are supported in all browsers except IE. So you can use the @supports at-rule to set the grid-gaps conditionally for all new browsers:

    Example:

    .grid {
      display: grid;
    }
    .item {
      margin-right: 1rem;
      margin-bottom: 1rem;
    }
    @supports (grid-gap: 1rem) {
      .grid {
        grid-gap: 1rem;
      }
      .item {
        margin-right: 0;
        margin-bottom: 0;
      }
    }
    

    It's a little verbose, but on the plus side, you don't have to give up grids altogether just to support IE.

    Use Autoprefixer

    I can't stress this enough - half the pain of grids is solved just be using autoprefixer in your build step. Write your CSS in a standards-complaint way, and just let autoprefixer do it's job transforming all older spec properties automatically. When you decide you don't want to support IE, just change one line in the browserlist config and you'll have removed all IE-specific code from your built files.

    Find indices of elements equal to zero in a NumPy array

    numpy.where() is my favorite.

    >>> x = numpy.array([1,0,2,0,3,0,4,5,6,7,8])
    >>> numpy.where(x == 0)[0]
    array([1, 3, 5])
    

    Groovy method with optional parameters

    You can use arguments with default values.

    def someMethod(def mandatory,def optional=null){}
    

    if argument "optional" not exist, it turns to "null".

    Using ADB to capture the screen

    To save to a file on Windows, OSX and Linux

    adb exec-out screencap -p > screen.png
    

    To copy to clipboard on Linux use

    adb exec-out screencap -p | xclip -t image/png
    

    getResourceAsStream returns null

    You might want to try this to get the stream i.e first get the url and then open it as stream.

    URL url = getClass().getResource("/initialization/Lifepaths.txt"); 
    InputStream strm = url.openStream(); 
    

    I once had a similar question: Reading txt file from jar fails but reading image works

    How do I increase memory on Tomcat 7 when running as a Windows Service?

    Assuming that you've downloaded and installed Tomcat as Windows Service Installer exe file from the Tomcat homepage, then check the Apache feather icon in the systray (or when absent, run Monitor Tomcat from the start menu). Doubleclick the feather icon and go to the Java tab. There you can configure the memory.

    enter image description here

    Restart the service to let the changes take effect.

    Mockito - difference between doReturn() and when()

    Both approaches behave differently if you use a spied object (annotated with @Spy) instead of a mock (annotated with @Mock):

    • when(...) thenReturn(...) makes a real method call just before the specified value will be returned. So if the called method throws an Exception you have to deal with it / mock it etc. Of course you still get your result (what you define in thenReturn(...))

    • doReturn(...) when(...) does not call the method at all.

    Example:

    public class MyClass {
         protected String methodToBeTested() {
               return anotherMethodInClass();
         }
    
         protected String anotherMethodInClass() {
              throw new NullPointerException();
         }
    }
    

    Test:

    @Spy
    private MyClass myClass;
    
    // ...
    
    // would work fine
    doReturn("test").when(myClass).anotherMethodInClass();
    
    // would throw a NullPointerException
    when(myClass.anotherMethodInClass()).thenReturn("test");
    

    How do I load an org.w3c.dom.Document from XML in a string?

    Just had a similar problem, except i needed a NodeList and not a Document, here's what I came up with. It's mostly the same solution as before, augmented to get the root element down as a NodeList and using erickson's suggestion of using an InputSource instead for character encoding issues.

    private String DOC_ROOT="root";
    String xml=getXmlString();
    Document xmlDoc=loadXMLFrom(xml);
    Element template=xmlDoc.getDocumentElement();
    NodeList nodes=xmlDoc.getElementsByTagName(DOC_ROOT);
    
    public static Document loadXMLFrom(String xml) throws Exception {
            InputSource is= new InputSource(new StringReader(xml));
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder builder = null;
            builder = factory.newDocumentBuilder();
            Document doc = builder.parse(is);
            return doc;
        }
    

    Django URL Redirect

    In Django 1.8, this is how I did mine.

    from django.views.generic.base import RedirectView
    
    url(r'^$', views.comingSoon, name='homepage'),
    # whatever urls you might have in here
    # make sure the 'catch-all' url is placed last
    url(r'^.*$', RedirectView.as_view(pattern_name='homepage', permanent=False))
    

    Instead of using url, you can use the pattern_name, which is a bit un-DRY, and will ensure you change your url, you don't have to change the redirect too.

    How to access the last value in a vector?

    I just benchmarked these two approaches on data frame with 663,552 rows using the following code:

    system.time(
      resultsByLevel$subject <- sapply(resultsByLevel$variable, function(x) {
        s <- strsplit(x, ".", fixed=TRUE)[[1]]
        s[length(s)]
      })
      )
    
     user  system elapsed 
      3.722   0.000   3.594 
    

    and

    system.time(
      resultsByLevel$subject <- sapply(resultsByLevel$variable, function(x) {
        s <- strsplit(x, ".", fixed=TRUE)[[1]]
        tail(s, n=1)
      })
      )
    
       user  system elapsed 
     28.174   0.000  27.662 
    

    So, assuming you're working with vectors, accessing the length position is significantly faster.

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

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

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

    The following code will give us all useful paths:

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

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


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

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

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


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

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

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


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

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

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

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

    Two versions of python on linux. how to make 2.7 the default

    I guess you have installed the 2.7 version manually, while 2.6 comes from a package?

    The simple answer is: uninstall python package.

    The more complex one is: do not install manually in /usr/local. Build a package with 2.7 version and then upgrade.

    Package handling depends on what distribution you use.

    Can't choose class as main class in IntelliJ

    The documentation you linked actually has the answer in the link associated with the "Java class located out of the source root." Configure your source and test roots and it should work.

    https://www.jetbrains.com/idea/webhelp/configuring-content-roots.html

    Since you stated that these are tests you should probably go with them marked as Test Source Root instead of Source Root.

    Selecting between two dates within a DateTime field - SQL Server

    SELECT * 
    FROM tbl 
    WHERE myDate BETWEEN #date one# AND #date two#;
    

    How are VST Plugins made?

    I realize this is a very old post, but I have had success using the JUCE library, which builds projects for the major IDE's like Xcode, VS, and Codeblocks and automatically builds VST/3, AU/v3, RTAS, and AAX.

    https://www.juce.com/

    Plot mean and standard deviation

    plt.errorbar can be used to plot x, y, error data (as opposed to the usual plt.plot)

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = np.array([1, 2, 3, 4, 5])
    y = np.power(x, 2) # Effectively y = x**2
    e = np.array([1.5, 2.6, 3.7, 4.6, 5.5])
    
    plt.errorbar(x, y, e, linestyle='None', marker='^')
    
    plt.show()
    

    plt.errorbar accepts the same arguments as plt.plot with additional yerr and xerr which default to None (i.e. if you leave them blank it will act as plt.plot).

    Example plot

    How to prevent Google Colab from disconnecting?

    Using python selenium

    from selenium.webdriver.common.keys import Keys
    from selenium import webdriver
    import time   
    
    driver = webdriver.Chrome('/usr/lib/chromium-browser/chromedriver')
    
    notebook_url = ''
    driver.get(notebook_url)
    
    # run all cells
    driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.F9)
    time.sleep(5)
    
    # click to stay connected
    start_time = time.time()
    current_time = time.time()
    max_time = 11*59*60 #12hours
    
    while (current_time - start_time) < max_time:
        webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform()
        driver.find_element_by_xpath('//*[@id="top-toolbar"]/colab-connect-button').click()
        time.sleep(30)
        current_time = time.time()
    

    "Prevent saving changes that require the table to be re-created" negative effects

    Tools --> Options --> Designers node --> Uncheck " Prevent saving changes that require table recreation ".

    Java String split removed empty values

    From String.split() API Doc:

    Splits this string around matches of the given regular expression. This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

    Overloaded String.split(regex, int) is more appropriate for your case.

    How do I compute derivative using Numpy?

    Depending on the level of precision you require you can work it out yourself, using the simple proof of differentiation:

    >>> (((5 + 0.1) ** 2 + 1) - ((5) ** 2 + 1)) / 0.1
    10.09999999999998
    >>> (((5 + 0.01) ** 2 + 1) - ((5) ** 2 + 1)) / 0.01
    10.009999999999764
    >>> (((5 + 0.0000000001) ** 2 + 1) - ((5) ** 2 + 1)) / 0.0000000001
    10.00000082740371
    

    we can't actually take the limit of the gradient, but its kinda fun. You gotta watch out though because

    >>> (((5+0.0000000000000001)**2+1)-((5)**2+1))/0.0000000000000001
    0.0
    

    Python: list of lists

    The list variable (which I would recommend to rename to something more sensible) is a reference to a list object, which can be changed.

    On the line

    listoflists.append((list, list[0]))
    

    You actually are only adding a reference to the object reference by the list variable. You've got multiple possibilities to create a copy of the list, so listoflists contains the values as you seem to expect:

    Use the copy library

    import copy
    listoflists.append((copy.copy(list), list[0]))
    

    use the slice notation

    listoflists.append((list[:], list[0]))
    

    Spring Boot @Value Properties

    Your problem is that you need a static PropertySourcesPlaceholderConfigurer Bean definition in your configuration. I say static with emphasis, because I had a non-static one and it didn't work.

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
    

    Disable building workspace process in Eclipse

    You can switch to manual build so can control when this is done. Just make sure that Project > Build Automatically from the main menu is unchecked.

    What is the difference between json.dumps and json.load?

    dumps takes an object and produces a string:

    >>> a = {'foo': 3}
    >>> json.dumps(a)
    '{"foo": 3}'
    

    load would take a file-like object, read the data from that object, and use that string to create an object:

    with open('file.json') as fh:
        a = json.load(fh)
    

    Note that dump and load convert between files and objects, while dumps and loads convert between strings and objects. You can think of the s-less functions as wrappers around the s functions:

    def dump(obj, fh):
        fh.write(dumps(obj))
    
    def load(fh):
        return loads(fh.read())
    

    Sorting arrays in javascript by object key value

    This worked for me

    var files=data.Contents;
              files = files.sort(function(a,b){
            return a.LastModified - b. LastModified;
          });
    

    OR use Lodash to sort the array

    files = _.orderBy(files,'LastModified','asc');
    

    Hiding and Showing TabPages in tabControl

    It looks easier for me to clear all TabPages add add those wished:

    PropertyTabControl.TabPages.Clear();
            PropertyTabControl.TabPages.Add(AspectTabPage);
            PropertyTabControl.TabPages.Add(WerkstattTabPage);
    

    or

    PropertyTabControl.TabPages.Clear();
            PropertyTabControl.TabPages.Add(TerminTabPage);
    

    Why does 'git commit' not save my changes?

    You didn't add the changes. Either specifically add them via

    git add filename1 filename2
    

    or add all changes (from root path of the project)

    git add .
    

    or use the shorthand -a while commiting:

    git commit -a -m "message".
    

    Unzip a file with php

    Simple PHP function to unzip. Please make sure you have zip extension installed on your server.

    /**
     * Unzip
     * @param string $zip_file_path Eg - /tmp/my.zip
     * @param string $extract_path Eg - /tmp/new_dir_name
     * @return boolean
     */
    function unzip(string $zip_file_path, string $extract_dir_path) {
        $zip = new \ZipArchive;
        $res = $zip->open($zip_file_path);
        if ($res === TRUE) {
            $zip->extractTo($extract_dir_path);
            $zip->close();
            return TRUE;
        } else {
            return FALSE;
        }
    }
    

    How to check 'undefined' value in jQuery

    You can use shorthand technique to check whether it is undefined or null

     function A(val)
     {
       if(val || "") 
       //do this
     else
     //do this
     }
    

    hope this will help you

    <input type="file"> limit selectable files by extensions

    Easy way of doing it would be:

    <input type="file" accept=".gif,.jpg,.jpeg,.png,.doc,.docx">
    

    Works with all browsers, except IE9. I haven't tested it in IE10+.

    jQuery and AJAX response header

    The underlying XMLHttpRequest object used by jQuery will always silently follow redirects rather than return a 302 status code. Therefore, you can't use jQuery's AJAX request functionality to get the returned URL. Instead, you need to put all the data into a form and submit the form with the target attribute set to the value of the name attribute of the iframe:

    $('#myIframe').attr('name', 'myIframe');
    
    var form = $('<form method="POST" action="url.do"></form>').attr('target', 'myIframe');
    $('<input type="hidden" />').attr({name: 'search', value: 'test'}).appendTo(form);
    
    form.appendTo(document.body);
    form.submit();
    

    The server's url.do page will be loaded in the iframe, but when its 302 status arrives, the iframe will be redirected to the final destination.

    How to update RecyclerView Adapter Data?

    I found out that a really simple way to reload the RecyclerView is to just call

    recyclerView.removeAllViews();
    

    This will first remove all content of the RecyclerView and then add it again with the updated values.

    Check if a Python list item contains a string inside another string

    If you want to get list of data for multiple substrings

    you can change it this way

    some_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
    # select element where "abc" or "ghi" is included
    find_1 = "abc"
    find_2 = "ghi"
    result = [element for element in some_list if find_1 in element or find_2 in element] 
    # Output ['abc-123', 'ghi-789', 'abc-456']
    

    python how to pad numpy array with zeros

    Tensorflow also implemented functions for resizing/padding images tf.image.pad tf.pad.

    padded_image = tf.image.pad_to_bounding_box(image, top_padding, left_padding, target_height, target_width)
    
    padded_image = tf.pad(image, paddings, "CONSTANT")
    

    These functions work just like other input-pipeline features of tensorflow and will work much better for machine learning applications.

    How to prevent downloading images and video files from my website?

    You can't stop image/video theft but you can make harder for normal users but you can't make it harder for the programmers like us (I mean thieves that know little web programming).

    There are some tricks you can try:

    1.) Using flash as YouTube and many others sites like http://www.funnenjoy.com does.

    2.) Div overlaping or background pic setting (but users with little sense can easily save all resources by opening inspect element or other developer option).

    3.) You can disable right click and specific keys like CTRL + S and others possibles with JavaScript but main drawback is that if user disable JavaScript our all tricks fail down.

    4.) Save image in none online directories (if you have full access to web server) and read that files with server side languages like PHP every time when image / video is required and change image id time to time or create script that can automatically change ID after every access.

    5.) Use .htaccess in apache to prevent linking of your images by others sites. you can use this site to automatically generate .htacess http://www.htaccesstools.com/hotlink-protection/

    What is a monad?

    If I've understood correctly, IEnumerable is derived from monads. I wonder if that might be an interesting angle of approach for those of us from the C# world?

    For what it's worth, here are some links to tutorials that helped me (and no, I still haven't understood what monads are).

    How do you use $sce.trustAsHtml(string) to replicate ng-bind-html-unsafe in Angular 1.2+

    For Rails (at least in my case) if you are using the angularjs-rails gem, please remember to add the sanitize module

    //= require angular
    //= require angular-sanitize
    

    And then load it up in your app...

    var myDummyApp = angular.module('myDummyApp', ['ngSanitize']);
    

    Then you can do the following:

    On the template:

    %span{"ng-bind-html"=>"phone_with_break(x)"}
    

    And eventually:

    $scope.phone_with_break = function (x) {
      if (x.phone != "") {
       return x.phone + "<br>";
      }
      return '';
    }
    

    What are the differences between Deferred, Promise and Future in JavaScript?

    • A promise represents a value that is not yet known
    • A deferred represents work that is not yet finished

    A promise is a placeholder for a result which is initially unknown while a deferred represents the computation that results in the value.

    Reference

    How to use foreach with a hash reference?

    foreach my $key (keys %$ad_grp_ref) {
        ...
    }
    

    Perl::Critic and daxim recommend the style

    foreach my $key (keys %{ $ad_grp_ref }) {
        ...
    }
    

    out of concerns for readability and maintenance (so that you don't need to think hard about what to change when you need to use %{ $ad_grp_obj[3]->get_ref() } instead of %{ $ad_grp_ref })

    How do I print out the value of this boolean? (Java)

    System.out.println(isLeapYear);
    

    should work just fine.

    Incidentally, in

    else if ((year % 4 == 0) && (year % 100 == 0))
        isLeapYear = false;
    
    else if ((year % 4 == 0) && (year % 100 == 0) && (year % 400 == 0))
        isLeapYear = true;
    

    the year % 400 part will never be reached because if (year % 4 == 0) && (year % 100 == 0) && (year % 400 == 0) is true, then (year % 4 == 0) && (year % 100 == 0) must have succeeded.

    Maybe swap those two conditions or refactor them:

    else if ((year % 4 == 0) && (year % 100 == 0))
        isLeapYear = (year % 400 == 0);
    

    What happens when a duplicate key is put into a HashMap?

    BTW, if you want some semantics such as only put if this key is not exist. you can use concurrentHashMap with putIfAbsent() function. Check this out:

    https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html#put(K,%20V)

    concurrentHashMap is thread safe with high performance since it uses "lock striping" mechanism to improve the throughput.

    implements Closeable or implements AutoCloseable

    It seems to me that you are not very familiar with interfaces. In the code you have posted, you don't need to implement AutoCloseable.

    You only have to (or should) implement Closeable or AutoCloseable if you are about to implement your own PrintWriter, which handles files or any other resources which needs to be closed.

    In your implementation, it is enough to call pw.close(). You should do this in a finally block:

    PrintWriter pw = null;
    try {
       File file = new File("C:\\test.txt");
       pw = new PrintWriter(file);
    } catch (IOException e) {
       System.out.println("bad things happen");
    } finally {
       if (pw != null) {
          try {
             pw.close();
          } catch (IOException e) {
          }
       }
    }
    

    The code above is Java 6 related. In Java 7 this can be done more elegantly (see this answer).

    Scrolling an iframe with JavaScript?

    Use the scrollTop property of the frame's content to set the content's vertical scroll-offset to a specific number of pixels (like 100):

    <iframe src="foo.html" onload="this.contentWindow.document.documentElement.scrollTop=100"></iframe>
    

    How to generate a random alpha-numeric string

    I don't really like any of these answers regarding a "simple" solution :S

    I would go for a simple ;), pure Java, one liner (entropy is based on random string length and the given character set):

    public String randomString(int length, String characterSet) {
        return IntStream.range(0, length).map(i -> new SecureRandom().nextInt(characterSet.length())).mapToObj(randomInt -> characterSet.substring(randomInt, randomInt + 1)).collect(Collectors.joining());
    }
    
    @Test
    public void buildFiveRandomStrings() {
        for (int q = 0; q < 5; q++) {
            System.out.println(randomString(10, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")); // The character set can basically be anything
        }
    }
    

    Or (a bit more readable old way)

    public String randomString(int length, String characterSet) {
        StringBuilder sb = new StringBuilder(); // Consider using StringBuffer if needed
        for (int i = 0; i < length; i++) {
            int randomInt = new SecureRandom().nextInt(characterSet.length());
            sb.append(characterSet.substring(randomInt, randomInt + 1));
        }
        return sb.toString();
    }
    
    @Test
    public void buildFiveRandomStrings() {
        for (int q = 0; q < 5; q++) {
            System.out.println(randomString(10, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")); // The character set can basically be anything
        }
    }
    

    But on the other hand you could also go with UUID which has a pretty good entropy:

    UUID.randomUUID().toString().replace("-", "")
    

    How to calculate the number of occurrence of a given character in each row of a column of strings?

    If you don't want to leave base R, here's a fairly succinct and expressive possibility:

    x <- q.data$string
    lengths(regmatches(x, gregexpr("a", x)))
    # [1] 2 1 0
    

    TypeError: Cannot read property 'then' of undefined

    You need to return your promise to the calling function.

    islogged:function(){
        var cUid=sessionService.get('uid');
        alert("in loginServce, cuid is "+cUid);
        var $checkSessionServer=$http.post('data/check_session.php?cUid='+cUid);
        $checkSessionServer.then(function(){
            alert("session check returned!");
            console.log("checkSessionServer is "+$checkSessionServer);
        });
        return $checkSessionServer; // <-- return your promise to the calling function
    }
    

    How to execute INSERT statement using JdbcTemplate class from Spring Framework

    Use jdbcTemplate.update(String sql, Object... args) method:

    jdbcTemplate.update(
        "INSERT INTO schema.tableName (column1, column2) VALUES (?, ?)",
        var1, var2
    );
    

    or jdbcTemplate.update(String sql, Object[] args, int[] argTypes), if you need to map arguments to SQL types manually:

    jdbcTemplate.update(
        "INSERT INTO schema.tableName (column1, column2) VALUES (?, ?)",
        new Object[]{var1, var2}, new Object[]{Types.TYPE_OF_VAR1, Types.TYPE_OF_VAR2}
    );
    

    "Actual or formal argument lists differs in length"

    Say you have defined your class like this:

        @Data
        @AllArgsConstructor(staticName = "of")
        private class Pair<P,Q> {
    
            public P first;
            public Q second;
        }
    

    So when you will need to create a new instance, it will need to take the parameters and you will provide it like this as defined in the annotation.

    Pair<Integer, String> pair = Pair.of(menuItemId, category);
    

    If you define it like this, you will get the error asked for.

    Pair<Integer, String> pair = new Pair(menuItemId, category);
    

    C++ equivalent of java's instanceof

    Try using:

    if(NewType* v = dynamic_cast<NewType*>(old)) {
       // old was safely casted to NewType
       v->doSomething();
    }
    

    This requires your compiler to have rtti support enabled.

    EDIT: I've had some good comments on this answer!

    Every time you need to use a dynamic_cast (or instanceof) you'd better ask yourself whether it's a necessary thing. It's generally a sign of poor design.

    Typical workarounds is putting the special behaviour for the class you are checking for into a virtual function on the base class or perhaps introducing something like a visitor where you can introduce specific behaviour for subclasses without changing the interface (except for adding the visitor acceptance interface of course).

    As pointed out dynamic_cast doesn't come for free. A simple and consistently performing hack that handles most (but not all cases) is basically adding an enum representing all the possible types your class can have and check whether you got the right one.

    if(old->getType() == BOX) {
       Box* box = static_cast<Box*>(old);
       // Do something box specific
    }
    

    This is not good oo design, but it can be a workaround and its cost is more or less only a virtual function call. It also works regardless of RTTI is enabled or not.

    Note that this approach doesn't support multiple levels of inheritance so if you're not careful you might end with code looking like this:

    // Here we have a SpecialBox class that inherits Box, since it has its own type
    // we must check for both BOX or SPECIAL_BOX
    if(old->getType() == BOX || old->getType() == SPECIAL_BOX) {
       Box* box = static_cast<Box*>(old);
       // Do something box specific
    }
    

    Change the mouse pointer using JavaScript

    document.body.style.cursor = 'cursorurl';
    

    How to auto adjust the <div> height according to content in it?

    height:59.55%;//First specify your height then make overflow auto overflow:auto;

    Hashmap with Streams in Java 8 Streams to collect value of Map

    For your Q2, there are already answers to your question. For your Q1, and more generally when you know that the key's filtering should give a unique value, there's no need to use Streams at all.

    Just use get or getOrDefault, i.e:

    List<String> list1 = id1.getOrDefault(1, Collections.emptyList());
    

    How do I raise an exception in Rails so it behaves like other Rails exceptions?

    If you need an easier way to do it, and don't want much fuss, a simple execution could be:

    raise Exception.new('something bad happened!')
    

    This will raise an exception, say e with e.message = something bad happened!

    and then you can rescue it as you are rescuing all other exceptions in general.

    Error in Eclipse: "The project cannot be built until build path errors are resolved"

    1. Go to Project > Properties > Java Compiler > Building
    2. Look under Build Path Problems
    3. Un-check "Abort build when build path error occurs"
      It won't solve all your errors but at least it will let you run your program :)

    Convert Java string to Time, NOT Date

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:MM");
    simpleDateFormat.format(fajr_prayertime);
    

    HTML display result in text (input) field?

    With .value and INPUT tag

    <HTML>
      <HEAD>
        <TITLE>Sum</TITLE>
    
        <script type="text/javascript">
          function sum()
          {
    
             var num1 = document.myform.number1.value;
             var num2 = document.myform.number2.value;
             var sum = parseInt(num1) + parseInt(num2);
             document.getElementById('add').value = sum;
          }
        </script>
      </HEAD>
    
      <BODY>
        <FORM NAME="myform">
          <INPUT TYPE="text" NAME="number1" VALUE=""/> + 
          <INPUT TYPE="text" NAME="number2" VALUE=""/>
          <INPUT TYPE="button" NAME="button" Value="=" onClick="sum()"/>
          <INPUT TYPE="text" ID="add" NAME="result" VALUE=""/>
        </FORM>
    
      </BODY>
    </HTML>
    

    with innerHTML and DIV

    <HTML>
      <HEAD>
        <TITLE>Sum</TITLE>
    
        <script type="text/javascript">
          function sum()
          {
    
             var num1 = document.myform.number1.value;
             var num2 = document.myform.number2.value;
             var sum = parseInt(num1) + parseInt(num2);
             document.getElementById('add').innerHTML = sum;
          }
        </script>
      </HEAD>
    
      <BODY>
        <FORM NAME="myform">
          <INPUT TYPE="text" NAME="number1" VALUE=""/> + 
          <INPUT TYPE="text" NAME="number2" VALUE=""/>
          <INPUT TYPE="button" NAME="button" Value="=" onClick="sum()"/>
          <DIV  ID="add"></DIV>
        </FORM>
    
      </BODY>
    </HTML>
    

    What is the difference between . (dot) and $ (dollar sign)?

    ... or you could avoid the . and $ constructions by using pipelining:

    third xs = xs |> tail |> tail |> head
    

    That's after you've added in the helper function:

    (|>) x y = y x
    

    MongoDB SELECT COUNT GROUP BY

    Mongo shell command that worked for me:

    db.getCollection(<collection_name>).aggregate([{"$match": {'<key>': '<value to match>'}}, {"$group": {'_id': {'<group_by_attribute>': "$group_by_attribute"}}}])