Programs & Examples On #Spawning

How to spawn a process and capture its STDOUT in .NET?

I needed to capture both stdout and stderr and have it timeout if the process didn't exit when expected. I came up with this:

Process process = new Process();
StringBuilder outputStringBuilder = new StringBuilder();

try
{
process.StartInfo.FileName = exeFileName;
process.StartInfo.WorkingDirectory = args.ExeDirectory;
process.StartInfo.Arguments = args;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.EnableRaisingEvents = false;
process.OutputDataReceived += (sender, eventArgs) => outputStringBuilder.AppendLine(eventArgs.Data);
process.ErrorDataReceived += (sender, eventArgs) => outputStringBuilder.AppendLine(eventArgs.Data);
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
var processExited = process.WaitForExit(PROCESS_TIMEOUT);

if (processExited == false) // we timed out...
{
    process.Kill();
    throw new Exception("ERROR: Process took too long to finish");
}
else if (process.ExitCode != 0)
{
    var output = outputStringBuilder.ToString();
    var prefixMessage = "";

    throw new Exception("Process exited with non-zero exit code of: " + process.ExitCode + Environment.NewLine + 
    "Output from process: " + outputStringBuilder.ToString());
}
}
finally
{                
process.Close();
}

I am piping the stdout and stderr into the same string, but you could keep it separate if needed. It uses events, so it should handle them as they come (I believe). I have run this successfully, and will be volume testing it soon.

Extracting just Month and Year separately from Pandas Datetime column

df['year_month']=df.datetime_column.apply(lambda x: str(x)[:7])

This worked fine for me, didn't think pandas would interpret the resultant string date as date, but when i did the plot, it knew very well my agenda and the string year_month where ordered properly... gotta love pandas!

Save PHP array to MySQL?

check out the implode function, since the values are in an array, you want to put the values of the array into a mysql query that inserts the values into a table.

$query = "INSERT INto hardware (specifications) VALUES (".implode(",",$specifications).")";

If the values in the array are text values, you will need to add quotes

$query = "INSERT INto hardware (specifications) VALUES ("'.implode("','",$specifications)."')";

mysql_query($query);

Also, if you don't want duplicate values, switch the "INto" to "IGNORE" and only unique values will be inserted into the table.

Fetch first element which matches criteria

When you write a lambda expression, the argument list to the left of -> can be either a parenthesized argument list (possibly empty), or a single identifier without any parentheses. But in the second form, the identifier cannot be declared with a type name. Thus:

this.stops.stream().filter(Stop s-> s.getStation().getName().equals(name));

is incorrect syntax; but

this.stops.stream().filter((Stop s)-> s.getStation().getName().equals(name));

is correct. Or:

this.stops.stream().filter(s -> s.getStation().getName().equals(name));

is also correct if the compiler has enough information to figure out the types.

Check if xdebug is working

you can run this small php code

<?php
phpinfo();
?>

Copy the whole output page, paste it in this link. Then analyze. It will show if Xdebug is installed or not. And it will give instructions to complete the installation.

Generate random int value from 3 to 6

SELECT ROUND((6 - 3 * RAND()), 0)

object==null or null==object?

That is for people who prefer to have the constant on the left side. In most cases having the constant on the left side will prevent NullPointerException to be thrown (or having another nullcheck). For example the String method equals does also a null check. Having the constant on the left, will keep you from writing the additional check. Which, in another way is also performed later. Having the null value on the left is just being consistent.

like:

 String b = null;
 "constant".equals(b);  // result to false
 b.equals("constant");  // NullPointerException
 b != null && b.equals("constant");  // result to false

Getting error: Peer authentication failed for user "postgres", when trying to get pgsql working with rails

Use host=localhost in connection.

PGconn *conn = PQconnectdb(
    "host=localhost user=postgres dbname=postgres password=123"
);

Bootstrap 4 Dropdown Menu not working?

I used NuGet to install BootStrap 4. I was also having issues with it not displaying the Dropdown on click. It kept throwing an error in jquery base on what the Chrome console was telling me.

I originally had the following

<%-- CSS --%>
<link type="text/css" rel="stylesheet" href="/Content/bootstrap.css" />

 <%-- JS --%>
<script type="text/javascript" src="/Scripts/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="/Scripts/bootstrap.min.js"></script>

But I changed it to use the bundled version instead and it started to work

<%-- CSS --%>
<link type="text/css" rel="stylesheet" href="/Content/bootstrap.css" />

<%-- JS --%>
<script type="text/javascript" src="/Scripts/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="/Scripts/bootstrap.bundle.min.js"></script>

Can someone provide an example of a $destroy event for scopes in AngularJS?

Demo: http://jsfiddle.net/sunnycpp/u4vjR/2/

Here I have created handle-destroy directive.

ctrl.directive('handleDestroy', function() {
    return function(scope, tElement, attributes) {        
        scope.$on('$destroy', function() {
            alert("In destroy of:" + scope.todo.text);
        });
    };
});

SyntaxError: Unexpected Identifier in Chrome's Javascript console

The comma got eaten by the quotes!

This part:

("username," visitorName);

Should be this:

("username", visitorName);

Aside: For pasting code into the console, you can paste them in one line at a time to help you pinpoint where things went wrong ;-)

Count all occurrences of a string in lots of files with grep

Instead of using -c, just pipe it to wc -l.

grep string * | wc -l

This will list each occurrence on a single line and then count the number of lines.

This will miss instances where the string occurs 2+ times on one line, though.

ProgressDialog is deprecated.What is the alternate one to use?

You can use SpotDialog by using the library wasabeef you can find the complete tutorial from the following link:

SpotsDialog Example in Android

JDK was not found on the computer for NetBeans 6.5

You have to either provide JAVA_HOME environment variable which points to the JDK location or as it says, you can run the installer from the command line passing JDK address through its -javahome argument like this:

C:> <NetBeans_Installer_Name> -javahome <JDK-PATH>

You must also make sure that your installed JDK is the Windows 64-bit version of the program. This is the download link for JDK6U37: http://download.oracle.com/otn-pub/java/jdk/6u37-b06/jdk-6u37-windows-x64.exe

Violation Long running JavaScript task took xx ms

Look in the Chrome console under the Network tab and find the scripts which take the longest to load.

In my case there were a set of Angular add on scripts that I had included but not yet used in the app :

<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-utils/0.1.1/angular-ui-utils.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular-animate.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular-aria.min.js"></script>

These were the only JavaScript files that took longer to load than the time that the "Long Running Task" error specified.

All of these files run on my other websites with no errors generated but I was getting this "Long Running Task" error on a new web app that barely had any functionality. The error stopped immediately upon removing.

My best guess is that these Angular add ons were looking recursively into increasingly deep sections of the DOM for their start tags - finding none, they had to traverse the entire DOM before exiting, which took longer than Chrome expects - thus the warning.

Function not defined javascript

important: in this kind of error you should look for simple mistakes in most cases

besides syntax error, I should say once I had same problem and it was because of bad name I have chosen for function. I have never searched for the reason but I remember that I copied another function and change it to use. I add "1" after the name to changed the function name and I got this error.

What values can I pass to the event attribute of the f:ajax tag?

I just input some value that I knew was invalid and here is the output:

'whatToInput' is not a supported event for HtmlPanelGrid. Please specify one of these supported event names: click, dblclick, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, mouseup.

So values you can pass to event are

  • click
  • dblclick
  • keydown
  • mousedown
  • mousemove
  • mouseover
  • mouseup

How to update json file with python

The issue here is that you've opened a file and read its contents so the cursor is at the end of the file. By writing to the same file handle, you're essentially appending to the file.

The easiest solution would be to close the file after you've read it in, then reopen it for writing.

with open("replayScript.json", "r") as jsonFile:
    data = json.load(jsonFile)

data["location"] = "NewPath"

with open("replayScript.json", "w") as jsonFile:
    json.dump(data, jsonFile)

Alternatively, you can use seek() to move the cursor back to the beginning of the file then start writing, followed by a truncate() to deal with the case where the new data is smaller than the previous.

with open("replayScript.json", "r+") as jsonFile:
    data = json.load(jsonFile)

    data["location"] = "NewPath"

    jsonFile.seek(0)  # rewind
    json.dump(data, jsonFile)
    jsonFile.truncate()

How to search a specific value in all tables (PostgreSQL)?

How about dumping the contents of the database, then using grep?

$ pg_dump --data-only --inserts -U postgres your-db-name > a.tmp
$ grep United a.tmp
INSERT INTO countries VALUES ('US', 'United States');
INSERT INTO countries VALUES ('GB', 'United Kingdom');

The same utility, pg_dump, can include column names in the output. Just change --inserts to --column-inserts. That way you can search for specific column names, too. But if I were looking for column names, I'd probably dump the schema instead of the data.

$ pg_dump --data-only --column-inserts -U postgres your-db-name > a.tmp
$ grep country_code a.tmp
INSERT INTO countries (iso_country_code, iso_country_name) VALUES ('US', 'United  States');
INSERT INTO countries (iso_country_code, iso_country_name) VALUES ('GB', 'United Kingdom');

Is it possible to interactively delete matching search pattern in Vim?

http://vim.wikia.com/wiki/Search_and_replace

Try this search and replace:

:%s/foo/bar/gc

Change each 'foo' to 'bar', but ask for confirmation first.

Press y or n to change or keep your text.

Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive

Just had this issue deploying a new app to an old IIS box. The investigation led to the v4.5.1 run-time being installed but the app requiring v4.5.2

Nothing apart from installing the correct version of ASP .Net run-time was required.

Directing print output to a .txt file

Another Variation can be... Be sure to close the file afterwards

import sys
file = open('output.txt', 'a')
sys.stdout = file

print("Hello stackoverflow!") 
print("I have a question.")

file.close()

shuffling/permutating a DataFrame in pandas

Here is a work around I found if you want to only shuffle a subset of the DataFrame:

shuffle_to_index = 20
df = pd.concat([df.iloc[np.random.permutation(range(shuffle_to_index))], df.iloc[shuffle_to_index:]])

Adding css class through aspx code behind

If you want to add attributes, including the class, you need to set runat="server" on the tag.

    <div id="classMe" runat="server"></div>

Then in the code-behind:

classMe.Attributes.Add("class", "some-class")

Getting android.content.res.Resources$NotFoundException: exception even when the resource is present in android

Check to make sure that your imports are correct. I had a similar problem where R was pointing to the Android system R file, not my local one.

htmlentities() vs. htmlspecialchars()

You should use htmlspecialchars($strText, ENT_QUOTES) when you just want your string to be XML and HTML safe:

For example, encode

  • & to &amp;
  • " to &quot;
  • < to &lt;
  • > to &gt;
  • ' to &#039;

However, if you also have additional characters that are Unicode or uncommon symbols in your text then you should use htmlentities() to ensure they show up properly in your HTML page.

Notes:

  • ' will only be encoded by htmlspecialchars() to &#039; if the ENT_QUOTES option is passed in. &#039; is safer to use then &apos; since older versions of Internet Explorer do not support the &apos; entity.
  • Technically, > does not need to be encoded as per the XML specification, but it is usually encoded too for consistency with the requirement of < being encoded.

css 'pointer-events' property alternative for IE

It's worth mentioning that specifically for IE, disabled=disabled works for anchor tags:

<a href="contact.html" onclick="unleashTheDragon();" disabled="disabled">Contact</a>

IE treats this as an disabled element and does not trigger click event. However, disabled is not a valid attribute on an anchor tag. Hence this won't work in other browsers. For them pointer-events:none is required in the styling.

UPDATE 1: So adding following rule feels like a cross-browser solution to me

UPDATE 2: For further compatibility, because IE will not form styles for anchor tags with disabled='disabled', so they will still look active. Thus, a:hover{} rule and styling is a good idea:

a[disabled="disabled"] {
        pointer-events: none; /* this is enough for non-IE browsers */
        color: darkgrey;      /* IE */
    }
        /* IE - disable hover effects */   
        a[disabled="disabled"]:hover {
            cursor:default;
            color: darkgrey;
            text-decoration:none;
        }

Working on Chrome, IE11, and IE8.
Of course, above CSS assumes anchor tags are rendered with disabled="disabled"

how to toggle attr() in jquery

$(".list-toggle").click(function() {
    $(this).hasAttr('colspan') ? 
        $(this).removeAttr('colspan') : $(this).attr('colspan', 6);
});

How to add comments into a Xaml file in WPF?

For anyone learning this stuff, comments are more important, so drawing on Xak Tacit's idea
(from User500099's link) for Single Property comments, add this to the top of the XAML code block:

<!--Comments Allowed With Markup Compatibility (mc) In XAML!
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:ØignoreØ="http://www.galasoft.ch/ignore"
    mc:Ignorable="ØignoreØ"
    Usage in property:
ØignoreØ:AttributeToIgnore="Text Of AttributeToIgnore"-->

Then in the code block

<Application FooApp:Class="Foo.App"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ØignoreØ="http://www.galasoft.ch/ignore"
mc:Ignorable="ØignoreØ"
...

AttributeNotToIgnore="TextNotToIgnore"
...

...
ØignoreØ:IgnoreThisAttribute="IgnoreThatText"
...   
>
</Application>

How can I render repeating React elements?

You can put expressions inside braces. Notice in the compiled JavaScript why a for loop would never be possible inside JSX syntax; JSX amounts to function calls and sugared function arguments. Only expressions are allowed.

(Also: Remember to add key attributes to components rendered inside loops.)

JSX + ES2015:

render() {
  return (
    <table className="MyClassName">
      <thead>
        <tr>
          {this.props.titles.map(title =>
            <th key={title}>{title}</th>
          )}
        </tr>
      </thead>
      <tbody>
        {this.props.rows.map((row, i) =>
          <tr key={i}>
            {row.map((col, j) =>
              <td key={j}>{col}</td>
            )}
          </tr>
        )}
      </tbody>
    </table>
  );
} 

JavaScript:

render: function() {
  return (
    React.DOM.table({className: "MyClassName"}, 
      React.DOM.thead(null, 
        React.DOM.tr(null, 
          this.props.titles.map(function(title) {
            return React.DOM.th({key: title}, title);
          })
        )
      ), 
      React.DOM.tbody(null, 
        this.props.rows.map(function(row, i) {
          return (
            React.DOM.tr({key: i}, 
              row.map(function(col, j) {
                return React.DOM.td({key: j}, col);
              })
            )
          );
        })
      )
    )
  );
} 

NoSql vs Relational database

Not all data is relational. For those situations, NoSQL can be helpful.

With that said, NoSQL stands for "Not Only SQL". It's not intended to knock SQL or supplant it.

SQL has several very big advantages:

  1. Strong mathematical basis.
  2. Declarative syntax.
  3. A well-known language in Structured Query Language (SQL).

Those haven't gone away.

It's a mistake to think about this as an either/or argument. NoSQL is an alternative that people need to consider when it fits, that's all.

Documents can be stored in non-relational databases, like CouchDB.

Maybe reading this will help.

Where can I get Google developer key

I explored the google docs and found that developer key and api is same thing.

SQL Server Case Statement when IS NULL

  case isnull(B.[stat],0)
  when 0 then dateadd(dd,10,(c.[Eventdate]))
  end

you can add in else statement if you want to add 30 days to the same .

Push commits to another branch

Certainly, though it will only work if it's a fast forward of BRANCH2 or if you force it. The correct syntax to do such a thing is

git push <remote> <source branch>:<dest branch> 

See the description of a "refspec" on the git push man page for more detail on how it works. Also note that both a force push and a reset are operations that "rewrite history", and shouldn't be attempted by the faint of heart unless you're absolutely sure you know what you're doing with respect to any remote repositories and other people who have forks/clones of the same project.

How to enable external request in IIS Express?

There's a blog post up on the IIS team site now explaining how to enable remote connections on IIS Express. Here is the pertinent part of that post summarized:

On Vista and Win7, run the following command from an administrative prompt:

netsh http add urlacl url=http://vaidesg:8080/ user=everyone

For XP, first install Windows XP Service Pack 2 Support Tools. Then run the following command from an administrative prompt:

httpcfg set urlacl /u http://vaidesg1:8080/ /a D:(A;;GX;;;WD)

How do you normalize a file path in Bash?

Talkative, and a bit late answer. I need to write one since I'm stuck on older RHEL4/5. I handles absolute and relative links, and simplifies //, /./ and somedir/../ entries.

test -x /usr/bin/readlink || readlink () {
        echo $(/bin/ls -l $1 | /bin/cut -d'>' -f 2)
    }


test -x /usr/bin/realpath || realpath () {
    local PATH=/bin:/usr/bin
    local inputpath=$1
    local changemade=1
    while [ $changemade -ne 0 ]
    do
        changemade=0
        local realpath=""
        local token=
        for token in ${inputpath//\// }
        do 
            case $token in
            ""|".") # noop
                ;;
            "..") # up one directory
                changemade=1
                realpath=$(dirname $realpath)
                ;;
            *)
                if [ -h $realpath/$token ] 
                then
                    changemade=1
                    target=`readlink $realpath/$token`
                    if [ "${target:0:1}" = '/' ]
                    then
                        realpath=$target
                    else
                        realpath="$realpath/$target"
                    fi
                else
                    realpath="$realpath/$token"
                fi
                ;;
            esac
        done
        inputpath=$realpath
    done
    echo $realpath
}

mkdir -p /tmp/bar
(cd /tmp ; ln -s /tmp/bar foo; ln -s ../.././usr /tmp/bar/link2usr)
echo `realpath /tmp/foo`

Looping each row in datagridview

Best aproach for me was:

  private void grid_receptie_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        int X = 1;
        foreach(DataGridViewRow row in grid_receptie.Rows)
        {
            row.Cells["NR_CRT"].Value = X;
            X++;
        }
    }

How to manually reload Google Map with JavaScript

map.setZoom(map.getZoom());

For some reasons, resize trigger did not work for me, and this one worked.

How to set an environment variable in a running docker container

To:

  1. set up many env. vars in one step,
  2. prevent exposing them in 'sh' history, like with '-e' option (passing credentials/api tokens!),

you can use

--env-file key_value_file.txt

option:

docker run --env-file key_value_file.txt $INSTANCE_ID

Check if all values of array are equal

const allEqual = arr => arr.every( v => v === arr[0] )
allEqual( [1,1,1,1] )  // true

Or one-liner:

[1,1,1,1].every( (val, i, arr) => val === arr[0] )   // true

Array.prototype.every (from MDN) : The every() method tests whether all elements in the array pass the test implemented by the provided function.

How to upload files on server folder using jsp

Below code is working on my live server as well as in my own Lapy.

Note:

Please Create data folder in WebContent and put in any single image or any file(jsp or html file).

Add jar files

commons-collections-3.1.jar
commons-fileupload-1.2.2.jar
commons-io-2.1.jar
commons-logging-1.0.4.jar

upload.jsp

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
       pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload</title>
</head>
<body>
<form method="post" action="UploadServlet" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="dataFile" id="fileChooser"/><br/><br/>
<input type="submit" value="Upload" />
</form>
</body>
</html>

UploadServlet.java

package com.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class UploadServlet
 */
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private static final String DATA_DIRECTORY = "data";
    private static final int MAX_MEMORY_SIZE = 1024 * 1024 * 2;
    private static final int MAX_REQUEST_SIZE = 1024 * 1024;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // Check that we have a file upload request
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        if (!isMultipart) {
            return;
        }

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // Sets the size threshold beyond which files are written directly to
        // disk.
        factory.setSizeThreshold(MAX_MEMORY_SIZE);

        // Sets the directory used to temporarily store files that are larger
        // than the configured size threshold. We use temporary directory for
        // java
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        // constructs the folder where uploaded file will be stored
        String uploadFolder = getServletContext().getRealPath("")
                + File.separator + DATA_DIRECTORY;

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Set overall request size constraint
        upload.setSizeMax(MAX_REQUEST_SIZE);

        try {
            // Parse the request
            List items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String filePath = uploadFolder + File.separator + fileName;
                    File uploadedFile = new File(filePath);
                    System.out.println(filePath);
                    // saves the file to upload directory
                    item.write(uploadedFile);
                }
            }

            // displays done.jsp page after upload finished
            getServletContext().getRequestDispatcher("/done.jsp").forward(
                    request, response);

        } catch (FileUploadException ex) {
            throw new ServletException(ex);
        } catch (Exception ex) {
            throw new ServletException(ex);
        }

    }

}

web.xml

  <servlet>
    <description></description>
    <display-name>UploadServlet</display-name>
    <servlet-name>UploadServlet</servlet-name>
    <servlet-class>com.servlet.UploadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>UploadServlet</servlet-name>
    <url-pattern>/UploadServlet</url-pattern>
  </servlet-mapping>

done.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload Done</title>
</head>
<body>
<h3>Your file has been uploaded!</h3>
</body>
</html>

How do you fadeIn and animate at the same time?

For people still looking a couple of years later, things have changed a bit. You can now use the queue for .fadeIn() as well so that it will work like this:

$('.tooltip').fadeIn({queue: false, duration: 'slow'});
$('.tooltip').animate({ top: "-10px" }, 'slow');

This has the benefit of working on display: none elements so you don't need the extra two lines of code.

Can't subtract offset-naive and offset-aware datetimes

The correct solution is to add the timezone info e.g., to get the current time as an aware datetime object in Python 3:

from datetime import datetime, timezone

now = datetime.now(timezone.utc)

On older Python versions, you could define the utc tzinfo object yourself (example from datetime docs):

from datetime import tzinfo, timedelta, datetime

ZERO = timedelta(0)

class UTC(tzinfo):
  def utcoffset(self, dt):
    return ZERO
  def tzname(self, dt):
    return "UTC"
  def dst(self, dt):
    return ZERO

utc = UTC()

then:

now = datetime.now(utc)

What is a file with extension .a?

.a files are created with the ar utility, and they are libraries. To use it with gcc, collect all .a files in a lib/ folder and then link with -L lib/ and -l<name of specific library>.

Collection of all .a files into lib/ is optional. Doing so makes for better looking directories with nice separation of code and libraries, IMHO.

"make clean" results in "No rule to make target `clean'"

It seems your makefile's name is not 'Makefile' or 'makefile'. In case it is different say 'abc' try running 'make -f abc clean'

Add Text on Image using PIL

First, you have to download a font type...for example: https://www.wfonts.com/font/microsoft-sans-serif.

After that, use this code to draw the text:

from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw 
img = Image.open("filename.jpg")
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(r'filepath\..\sans-serif.ttf', 16)
draw.text((0, 0),"Draw This Text",(0,0,0),font=font) # this will draw text with Blackcolor and 16 size

img.save('sample-out.jpg')

Put quotes around a variable string in JavaScript

var text = "\"http://example.com\""; 

Whatever your text, to wrap it with ", you need to put them and escape inner ones with \. Above will result in:

"http://example.com"

Clear android application user data

The command pm clear com.android.browser requires root permission.
So, run su first.

Here is the sample code:

private static final String CHARSET_NAME = "UTF-8";
String cmd = "pm clear com.android.browser";

ProcessBuilder pb = new ProcessBuilder().redirectErrorStream(true).command("su");
Process p = pb.start();

// We must handle the result stream in another Thread first
StreamReader stdoutReader = new StreamReader(p.getInputStream(), CHARSET_NAME);
stdoutReader.start();

out = p.getOutputStream();
out.write((cmd + "\n").getBytes(CHARSET_NAME));
out.write(("exit" + "\n").getBytes(CHARSET_NAME));
out.flush();

p.waitFor();
String result = stdoutReader.getResult();

The class StreamReader:

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.CountDownLatch;

class StreamReader extends Thread {
    private InputStream is;
    private StringBuffer mBuffer;
    private String mCharset;
    private CountDownLatch mCountDownLatch;

    StreamReader(InputStream is, String charset) {
        this.is = is;
        mCharset = charset;
        mBuffer = new StringBuffer("");
        mCountDownLatch = new CountDownLatch(1);
    }

    String getResult() {
        try {
            mCountDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return mBuffer.toString();
    }

    @Override
    public void run() {
        InputStreamReader isr = null;
        try {
            isr = new InputStreamReader(is, mCharset);
            int c = -1;
            while ((c = isr.read()) != -1) {
                mBuffer.append((char) c);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (isr != null)
                    isr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            mCountDownLatch.countDown();
        }
    }
}

Line break in HTML with '\n'

This is to show new line and return carriage in html, then you don't need to do it explicitly. You can do it in css by setting the white-space attribute pre-line value.

<span style="white-space: pre-line">@Model.CommentText</span>

Outlets cannot be connected to repeating content iOS

Or you don't have to use IBOutlet to refer to the object in the view. You can give the Label in the tableViewCell a Tag value, for example set the Tag to 123 (this can be done by the attributes inspector). Then you can access the label by

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "someID", for: indexPath)

    let label = cell.viewWithTag(123) as! UILabel //refer the label by Tag

    switch indexPath.row {
    case 0:
        label.text = "Hello World!"
    default:
        label.text = "Default"
    }
    return cell 
}

How to change the Eclipse default workspace?

In Eclipse, go to File -> Switch Workspace, choose or create a new workspace.

Convert UTF-8 with BOM to UTF-8 with no BOM in Python

In Python 3 it's quite easy: read the file and rewrite it with utf-8 encoding:

s = open(bom_file, mode='r', encoding='utf-8-sig').read()
open(bom_file, mode='w', encoding='utf-8').write(s)

How to set default font family in React Native?

Set in package.json

"rnpm": {
  "assets": [
     "./assets/fonts/"
  ]
}

And link react-native link

Is there a way for non-root processes to bind to "privileged" ports on Linux?

Port redirect made the most sense for us, but we ran into an issue where our application would resolve a url locally that also needed to be re-routed; (that means you shindig).

This will also allow you to be redirected when accessing the url on the local machine.

iptables -A PREROUTING -t nat -p tcp --dport 80 -j REDIRECT --to-port 8080
iptables -A OUTPUT -t nat -p tcp --dport 80 -j REDIRECT --to-port 8080

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)

For those using Telerik as mentioned by Ovar, make sure you wrap your javascript in

 <telerik:RadScriptBlock ID="radSript1" runat="server">
   <script type="text/javascript">
        //Your javascript
   </script>
</telerik>

Since Telerik doesn't recognize <%# %> when looking for an element and <%= %> will give you an error if your javascript code isn't wrapped.

ggplot with 2 y axes on each side and different scales

I acknowledge and agree with hadley (and others), that separate y-scales are "fundamentally flawed". Having said that – I often wish ggplot2 had the feature – particularly, when the data is in wide-format and I quickly want to visualise or check the data (i.e. for personal use only).

While the tidyverse library makes it fairly easy to convert the data to long-format (such that facet_grid() will work), the process is still not trivial, as seen below:

library(tidyverse)
df.wide %>%
    # Select only the columns you need for the plot.
    select(date, column1, column2, column3) %>%
    # Create an id column – needed in the `gather()` function.
    mutate(id = n()) %>%
    # The `gather()` function converts to long-format. 
    # In which the `type` column will contain three factors (column1, column2, column3),
    # and the `value` column will contain the respective values.
    # All the while we retain the `id` and `date` columns.
    gather(type, value, -id, -date) %>%
    # Create the plot according to your specifications
    ggplot(aes(x = date, y = value)) +
        geom_line() +
        # Create a panel for each `type` (ie. column1, column2, column3).
        # If the types have different scales, you can use the `scales="free"` option.
        facet_grid(type~., scales = "free")

App.Config Transformation for projects which are not Web Projects in Visual Studio?

proposed solution will not work when a class library with config file is referenced from another project (in my case it was Azure worker project library). It will not copy correct transformed file from obj folder into bin\##configuration-name## folder. To make it work with minimal changes, you need to change AfterCompile target to BeforeCompile:

<Target Name="BeforeCompile" Condition="exists('app.$(Configuration).config')">

WSDL/SOAP Test With soapui

A likely possibility is that your browser reaches your web service through a proxy, and SoapUI is not configured to use that proxy. For example, I work in a corporate environment and while my IE and FireFox can access external websites, my SoapUI can only access internal web services.

The easy solution is to just open the WSDL in a browser, save it to a .xml file, and base your SoapUI project on that. This won't work if your WSDL relies on external XSDs that it can't get to, however.

How to make flexbox items the same size?

You need to add width: 0 to make columns equal if contents of the items make it grow bigger.

.item {
  flex: 1 1 0;
  width: 0;
}

What is the "proper" way to cast Hibernate Query.list() to List<Type>?

Short answer @SuppressWarnings is the right way to go.

Long answer, Hibernate returns a raw List from the Query.list method, see here. This is not a bug with Hibernate or something the can be solved, the type returned by the query is not known at compile time.

Therefore when you write

final List<MyObject> list = query.list();

You are doing an unsafe cast from List to List<MyObject> - this cannot be avoided.

There is no way you can safely carry out the cast as the List could contain anything.

The only way to make the error go away is the even more ugly

final List<MyObject> list = new LinkedList<>();
for(final Object o : query.list()) {
    list.add((MyObject)o);
}

How to change Status Bar text color in iOS

This does seem to be an issue with the current build of Xcode and iOS 7.

Some related content on Apple's Developer Forums is in a search for UIStatusBarStyleLightContent in "iOS 7 Beta Livability" on the Apple Developer Forums* (currently 32 posts).

I came across it trying to set it to the light version.

(This is just a follow up on Aaron's answer.)

What is a Subclass

Subclass is to Class as Java is to Programming Language.

REST API - Bulk Create or Update in single request

You probably will need to use POST or PATCH, because it is unlikely that a single request that updates and creates multiple resources will be idempotent.

Doing PATCH /docs is definitely a valid option. You might find using the standard patch formats tricky for your particular scenario. Not sure about this.

You could use 200. You could also use 207 - Multi Status

This can be done in a RESTful way. The key, in my opinion, is to have some resource that is designed to accept a set of documents to update/create.

If you use the PATCH method I would think your operation should be atomic. i.e. I wouldn't use the 207 status code and then report successes and failures in the response body. If you use the POST operation then the 207 approach is viable. You will have to design your own response body for communicating which operations succeeded and which failed. I'm not aware of a standardized one.

Android. Fragment getActivity() sometimes returns null

The best to get rid of this is to keep activity reference when onAttach is called and use the activity reference wherever needed, for e.g.

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    mContext = context;
}

@Override
public void onDetach() {
    super.onDetach();
    mContext = null;
}

Edited, since onAttach(Activity) is depreciated & now onAttach(Context) is being used

How to remove all callbacks from a Handler?

Please note that one should define a Handler and a Runnable in class scope, so that it is created once.removeCallbacks(Runnable) works correctly unless one defines them multiple times. Please look at following examples for better understanding:

Incorrect way :

    public class FooActivity extends Activity {
           private void handleSomething(){
                Handler handler = new Handler();
                Runnable runnable = new Runnable() {
                   @Override
                   public void run() {
                      doIt();
                  }
               };
              if(shouldIDoIt){
                  //doIt() works after 3 seconds.
                  handler.postDelayed(runnable, 3000);
              } else {
                  handler.removeCallbacks(runnable);
              }
           }

          public void onClick(View v){
              handleSomething();
          }
    } 

If you call onClick(..) method, you never stop doIt() method calling before it call. Because each time creates new Handler and new Runnable instances. In this way, you lost necessary references which belong to handler and runnable instances.

Correct way :

 public class FooActivity extends Activity {
        Handler handler = new Handler();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                doIt();
            }
        };
        private void handleSomething(){
            if(shouldIDoIt){
                //doIt() works after 3 seconds.
                handler.postDelayed(runnable, 3000);
            } else {
                handler.removeCallbacks(runnable);
            }
       }

       public void onClick(View v){
           handleSomething();
       }
 } 

In this way, you don't lost actual references and removeCallbacks(runnable) works successfully.

Key sentence is that 'define them as global in your Activity or Fragment what you use'.

How do I render a Word document (.doc, .docx) in the browser using JavaScript?

The answers by Brandon and fatbotdesigns are both correct, but having implemented the Google docs preview, we found multiple .docx files that couldn't be handled by Google. Switched to the MS Office Online preview and works likes a charm.

My recommendation would be to use the MS Office Preview URL over Google's.

https://view.officeapps.live.com/op/embed.aspx?src=http://remote.url.tld/path/to/document.doc' 

Bash if statement with multiple conditions throws an error

You can use either [[ or (( keyword. When you use [[ keyword, you have to use string operators such as -eq, -lt. I think, (( is most preferred for arithmetic, because you can directly use operators such as ==, < and >.

Using [[ operator

a=$1
b=$2
if [[ a -eq 1 || b -eq 2 ]] || [[ a -eq 3 && b -eq 4 ]]
then
     echo "Error"
else
     echo "No Error"
fi

Using (( operator

a=$1
b=$2
if (( a == 1 || b == 2 )) || (( a == 3 && b == 4 ))
then
     echo "Error"
else
     echo "No Error"
fi

Do not use -a or -o operators Since it is not Portable.

How do I set adaptive multiline UILabel text?

I kind of got things working by adding auto layout constraints:

auto layout contraints

But I am not happy with this. Took a lot of trial and error and couldn't understand why this worked.

Also I had to add to use titleLabel.numberOfLines = 0 in my ViewController

printf formatting (%d versus %u)

%u prints unsigned integer

%d prints signed integer

to get a pointer address use %p

Other List of Formatting Escapes:

Here are the full list of formatting escapes. I am just giving a screen shot from this page

enter image description here

How to fix Error: listen EADDRINUSE while using nodejs?

NOOB ERROR FIX: I'm new to Node.js and setup a webserver listening to port 8080. I ran into the EADDRINUSE error. I tried all the various 'kill -9 node' iterations and kept getting, 'node: no process found'

The problem was, I was calling http.listen(8080); TWICE in the same blob of code. So the first time it was actually working fine, and the second time it threw an error.

If you're getting a 'no process found' response when trying to kill the port, try checking to make sure you're only opening the port once.

Perl: function to trim string leading and trailing whitespace

Here's one approach using a regular expression:

$string =~ s/^\s+|\s+$//g ;     # remove both leading and trailing whitespace

Perl 6 will include a trim function:

$string .= trim;

Source: Wikipedia

Can I set the cookies to be used by a WKWebView?

You can also use WKWebsiteDataStore to get similar behaviour to HTTPCookieStorage from UIWebView.

let dataStore = WKWebsiteDataStore.default()
let cookies = HTTPCookieStorage.shared.cookies ?? [HTTPCookie]()
cookies.forEach({
    dataStore.httpCookieStore.setCookie($0, completionHandler: nil)
})

How do I convert a factor into date format?

You can try lubridate package which makes life much easier

library(lubridate)

mdy_hms(mydate)

The above will change the date format to POSIXct

A sample working example:

> data <- "1/15/2006 01:15:00"
> library(lubridate)
> mydate <- mdy_hms(data)
> mydate
[1] "2006-01-15 01:15:00 UTC"
> class(mydate)
[1] "POSIXct" "POSIXt" 

For case with factor use as.character

data <- factor("1/15/2006 01:15:00")
library(lubridate)
mydate <- mdy_hms(as.character(data))

XPath to select multiple tags

Not sure if this helps, but with XSL, I'd do something like:

<xsl:for-each select="a/b">
    <xsl:value-of select="c"/>
    <xsl:value-of select="d"/>
    <xsl:value-of select="e"/>
</xsl:for-each>

and won't this XPath select all children of B nodes:

a/b/*

What does Python's socket.recv() return for non-blocking sockets if no data is received until a timeout occurs?

Just to complete the existing answers, I'd suggest using select instead of nonblocking sockets. The point is that nonblocking sockets complicate stuff (except perhaps sending), so I'd say there is no reason to use them at all. If you regularly have the problem that your app is blocked waiting for IO, I would also consider doing the IO in a separate thread in the background.

Why is visible="false" not working for a plain html table?

The reason that visible="false" does not work is because HTML is defined as a standard by a consortium group. The standard for the Table element does not have a visibility property defined.

You can see all the valid properties for a table by going to the standards web page for tables.

That page can be a bit hard to read, so here is a link to another page that makes it easier to read.

How can I add to a List's first position?

Of course, Insert or AddFirst will do the trick, but you could always do:

myList.Reverse();
myList.Add(item);
myList.Reverse();

Update multiple rows in same query using PostgreSQL

Came across similar scenario and the CASE expression was useful to me.

UPDATE reports SET is_default = 
case 
 when report_id = 123 then true
 when report_id != 123 then false
end
WHERE account_id = 321;

Reports - is a table here, account_id is same for the report_ids mentioned above. The above query will set 1 record (the one which matches the condition) to true and all the non-matching ones to false.

How can I determine the URL that a local Git repository was originally cloned from?

To supplement the other answers: If the remote has for some reason been changed and so doesn't reflect the original origin, the very first entry in the reflog (i.e. the last entry displayed by the command git reflog) should indicate where the repo was originally cloned from.

e.g.

$ git reflog | tail -n 1
f34be46 HEAD@{0}: clone: from https://github.com/git/git
$

(Bear in mind that the reflog may be purged, so this isn't guaranteed to work.)

Iterate over model instance field names and values in template

You can use the values() method of a queryset, which returns a dictionary. Further, this method accepts a list of fields to subset on. The values() method will not work with get(), so you must use filter() (refer to the QuerySet API).

In view...

def show(request, object_id):
   object = Foo.objects.filter(id=object_id).values()[0]
   return render_to_response('detail.html', {'object': object})

In detail.html...

<ul>
   {% for key, value in object.items %}
        <li><b>{{ key }}:</b> {{ value }}</li>
   {% endfor %}
</ul>

For a collection of instances returned by filter:

   object = Foo.objects.filter(id=object_id).values() # no [0]

In detail.html...

{% for instance in object %}
<h1>{{ instance.id }}</h1>
<ul>
    {% for key, value in instance.items %}
        <li><b>{{ key }}:</b>  {{ value }}</li>
    {% endfor %}
</ul>
{% endfor %}

Get lengths of a list in a jinja2 template

<span>You have {{products|length}} products</span>

You can also use this syntax in expressions like

{% if products|length > 1 %}

jinja2's builtin filters are documented here; and specifically, as you've already found, length (and its synonym count) is documented to:

Return the number of items of a sequence or mapping.

So, again as you've found, {{products|count}} (or equivalently {{products|length}}) in your template will give the "number of products" ("length of list")

Generator expressions vs. list comprehensions

Use list comprehensions when the result needs to be iterated over multiple times, or where speed is paramount. Use generator expressions where the range is large or infinite.

See Generator expressions and list comprehensions for more info.

How to find all tables that have foreign keys that reference particular table.column and have values for those foreign keys?

You can find all schema related information in the wisely named information_schema table.

You might want to check the table REFERENTIAL_CONSTRAINTS and KEY_COLUMN_USAGE. The former tells you which tables are referenced by others; the latter will tell you how their fields are related.

Python3 integer division

Try this:

a = 1
b = 2
int_div  = a // b

How do I delete specific characters from a particular String in Java?

You can use replaceAll() method :

String.replaceAll(",", "");
String.replaceAll("\\.", "");
String.replaceAll("\\(", "");

etc..

Display progress bar while doing some work in C#?

For me the easiest way is definitely to use a BackgroundWorker, which is specifically designed for this kind of task. The ProgressChanged event is perfectly fitted to update a progress bar, without worrying about cross-thread calls

How to set the initial zoom/width for a webview

I figured out why the portrait view wasn't totally filling the viewport. At least in my case, it was because the scrollbar was always showing. In addition to the viewport code above, try adding this:

    browser.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    browser.setScrollbarFadingEnabled(false);

This causes the scrollbar to not take up layout space, and allows the webpage to fill the viewport.

Hope this helps

App can't be opened because it is from an unidentified developer

It is prohibiting the opening of Eclipse app because it was not registered with Apple by an identified developer. This is a security feature, however, you can override the security setting and open the app by doing the following:

  1. Locate the Eclipse.app (eclipse/Eclipse.app) in Finder. (Make sure you use Finder so that you can perform the subsequent steps.)
  2. Press the Control key and then click the Eclipse.app icon.
  3. Choose Open from the shortcut menu.
  4. Click the Open button when the alert window appears.

The last step will add an exception for Eclipse to your security settings and now you will be able to open it without any warnings.

Note, these steps work for other *.app apps that may encounter the same issue.

Getting attributes of Enum's value

Adding my solution for Net Framework and NetCore.

I used this for my Net Framework implementation:

public static class EnumerationExtension
{
    public static string Description( this Enum value )
    {
        // get attributes  
        var field = value.GetType().GetField( value.ToString() );
        var attributes = field.GetCustomAttributes( typeof( DescriptionAttribute ), false );

        // return description
        return attributes.Any() ? ( (DescriptionAttribute)attributes.ElementAt( 0 ) ).Description : "Description Not Found";
    }
}

This doesn't work for NetCore so I modified it to do this:

public static class EnumerationExtension
{
    public static string Description( this Enum value )
    {
        // get attributes  
        var field = value.GetType().GetField( value.ToString() );
        var attributes = field.GetCustomAttributes( false );

        // Description is in a hidden Attribute class called DisplayAttribute
        // Not to be confused with DisplayNameAttribute
        dynamic displayAttribute = null;

        if (attributes.Any())
        {
            displayAttribute = attributes.ElementAt( 0 );
        }

        // return description
        return displayAttribute?.Description ?? "Description Not Found";
    }
}

Enumeration Example:

public enum ExportTypes
{
    [Display( Name = "csv", Description = "text/csv" )]
    CSV = 0
}

Sample Usage for either static added:

var myDescription = myEnum.Description();

C# Change A Button's Background Color

Code for set background color, for SolidColor:

button.Background = new SolidColorBrush(Color.FromArgb(Avalue, rValue, gValue, bValue));

What would be the best method to code heading/title for <ul> or <ol>, Like we have <caption> in <table>?

how about making the heading a list-element with different styles like so

<ul>
 <li class="heading">heading</li>
 <li>list item</li>
 <li>list item</li>
 <li>list item</li>
 <li>list item</li>
</ul>

and the CSS

ul .heading {font-weight: normal; list-style: none;}

additionally, use a reset CSS to set margins and paddings right on the ul and li. here's a good reset CSS. once you've reset the margins and paddings, you can apply some margin on the list-elements other than the one's with the heading class, to indent them.

How to determine if a decimal/double is an integer?

I faced a similar situation, but where the value is a string. The user types in a value that's supposed to be a dollar amount, so I want to validate that it's numeric and has at most two decimal places.

Here's my code to return true if the string "s" represents a numeric with at most two decimal places, and false otherwise. It avoids any problems that would result from the imprecision of floating-point values.

try
{
    // must be numeric value
    double d = double.Parse(s);
    // max of two decimal places
    if (s.IndexOf(".") >= 0)
    {
        if (s.Length > s.IndexOf(".") + 3)
            return false;
    }
    return true;
catch
{
    return false;
}

I discuss this in more detail at http://progblog10.blogspot.com/2011/04/determining-whether-numeric-value-has.html.

How do I rename a Git repository?

Rename PRJ0.git to PROJ1.git, then edit the URL variable located in the .git/config file of your project.

Download the Android SDK components for offline install

Here is how I figured it out. I am behind corporate firewall too.

Go to Chrome or your Internet Settings by clicking the wrench in Chrome --> Settings --> Under the Hood --> Network --> Change Proxy Settings

Click on LAN Settings and then Advanced. Copy the proxy server address and port.

Mostly the connection refused link occurs when trying to download SDK packages through Eclipse.

Navigate to the SDK Manager.exe and double click on it. Once it starts click on Tools --> Options and then enter the proxy server address and the Port #

Check the checkbox force https:// to http:// That's it your SDK Manager will now be able to download packages from google remote site without any issue even from behind a firewall.

I am on Windows by the way. Tried everything and this works great.

Trying to embed newline in a variable in bash

There are three levels at which a newline could be inserted in a variable.
Well ..., technically four, but the first two are just two ways to write the newline in code.

1.1. At creation.

The most basic is to create the variable with the newlines already.
We write the variable value in code with the newlines already inserted.

$ var="a
> b
> c"
$ echo "$var"
a
b
c

Or, inside an script code:

var="a
b
c"

Yes, that means writing Enter where needed in the code.

1.2. Create using shell quoting.

The sequence $' is an special shell expansion in bash and zsh.

var=$'a\nb\nc'

The line is parsed by the shell and expanded to « var="anewlinebnewlinec" », which is exactly what we want the variable var to be.
That will not work on older shells.

2. Using shell expansions.

It is basically a command expansion with several commands:

  1. echo -e

    var="$( echo -e "a\nb\nc" )"
    
  2. The bash and zsh printf '%b'

    var="$( printf '%b' "a\nb\nc" )"
    
  3. The bash printf -v

    printf -v var '%b' "a\nb\nc"
    
  4. Plain simple printf (works on most shells):

    var="$( printf 'a\nb\nc' )"
    

3. Using shell execution.

All the commands listed in the second option could be used to expand the value of a var, if that var contains special characters.
So, all we need to do is get those values inside the var and execute some command to show:

var="a\nb\nc"                 # var will contain the characters \n not a newline.

echo -e "$var"                # use echo.
printf "%b" "$var"            # use bash %b in printf.
printf "$var"                 # use plain printf.

Note that printf is somewhat unsafe if var value is controlled by an attacker.

jquery stop child triggering parent event

The answers here took the OP's question too literally. How can these answers be expanded into a scenario where there are MANY child elements, not just a single <a> tag? Here's one way.

Let's say you have a photo gallery with a blacked out background and the photos centered in the browser. When you click the black background (but not anything inside of it) you want the overlay to close.

Here's some possible HTML:

<div class="gallery" style="background: black">
    <div class="contents"> <!-- Let's say this div is 50% wide and centered -->
        <h1>Awesome Photos</h1>
        <img src="img1.jpg"><br>
        <img src="img2.jpg"><br>
        <img src="img3.jpg"><br>
        <img src="img4.jpg"><br>
        <img src="img5.jpg">
    </div>
</div>

And here's how the JavaScript would work:

$('.gallery').click(
    function()
    {
        $(this).hide();
    }
);

$('.gallery > .contents').click(
    function(e) {
        e.stopPropagation();
    }
);

This will stop the click events from elements inside .contents from every research .gallery so the gallery will close only when you click in the faded black background area, but not when you click in the content area. This can be applied to many different scenarios.

When to use Common Table Expression (CTE)

Perhaps its more meaningful to think of a CTE as a substitute for a view used for a single query. But doesn't require the overhead, metadata, or persistence of a formal view. Very useful when you need to:

  • Create a recursive query.
  • Use the CTE's resultset more than once in your query.
  • Promote clarity in your query by reducing large chunks of identical subqueries.
  • Enable grouping by a column derived in the CTE's resultset

Here's a cut-and-paste example to play with:

WITH [cte_example] AS (
SELECT 1 AS [myNum], 'a num' as [label]
UNION ALL
SELECT [myNum]+1,[label]
FROM [cte_example]
WHERE [myNum] <=  10
)
SELECT * FROM [cte_example]
UNION
SELECT SUM([myNum]), 'sum_all' FROM [cte_example]
UNION
SELECT SUM([myNum]), 'sum_odd' FROM [cte_example] WHERE [myNum] % 2 = 1
UNION
SELECT SUM([myNum]), 'sum_even' FROM [cte_example] WHERE [myNum] % 2 = 0;

Enjoy

T-SQL: Deleting all duplicate rows but keeping one

Here's my twist on it, with a runnable example. Note this will only work in the situation where Id is unique, and you have duplicate values in other columns.

DECLARE @SampleData AS TABLE (Id int, Duplicate varchar(20))

INSERT INTO @SampleData
SELECT 1, 'ABC' UNION ALL
SELECT 2, 'ABC' UNION ALL
SELECT 3, 'LMN' UNION ALL
SELECT 4, 'XYZ' UNION ALL
SELECT 5, 'XYZ'

DELETE FROM @SampleData WHERE Id IN (
    SELECT Id FROM (
        SELECT 
            Id
            ,ROW_NUMBER() OVER (PARTITION BY [Duplicate] ORDER BY Id) AS [ItemNumber]
            -- Change the partition columns to include the ones that make the row distinct
        FROM 
            @SampleData
    ) a WHERE ItemNumber > 1 -- Keep only the first unique item
)

SELECT * FROM @SampleData

And the results:

Id          Duplicate
----------- ---------
1           ABC
3           LMN
4           XYZ

Not sure why that's what I thought of first... definitely not the simplest way to go but it works.

How to get the first element of the List or Set?

and further

Set<String> set = new TreeSet<>();
    set.add("2");
    set.add("1");
    set.add("3");
    String first = set.stream().findFirst().get();

This will help you retrieve the first element of the list or set. Given that the set or list is not empty (get() on empty optional will throw java.util.NoSuchElementException)

orElse() can be used as: (this is just a work around - not recommended)

String first = set.stream().findFirst().orElse("");
set.removeIf(String::isEmpty);

Below is the appropriate approach :

Optional<String> firstString = set.stream().findFirst();
if(firstString.isPresent()){
    String first = firstString.get();
}

Similarly first element of the list can be retrieved.

Hope this helps.

The static keyword and its various uses in C++

Static variables are shared between every instance of a class, instead of each class having their own variable.

class MyClass
{
    public:
    int myVar; 
    static int myStaticVar;
};

//Static member variables must be initialized. Unless you're using C++11, or it's an integer type,
//they have to be defined and initialized outside of the class like this:
MyClass::myStaticVar = 0;

MyClass classA;
MyClass classB;

Each instance of 'MyClass' has their own 'myVar', but share the same 'myStaticVar'. In fact, you don't even need an instance of MyClass to access 'myStaticVar', and you can access it outside of the class like this:

MyClass::myStaticVar //Assuming it's publicly accessible.

When used inside a function as a local variable (and not as a class member-variable) the static keyword does something different. It allows you to create a persistent variable, without giving global scope.

int myFunc()
{
   int myVar = 0; //Each time the code reaches here, a new variable called 'myVar' is initialized.
   myVar++;

   //Given the above code, this will *always* print '1'.
   std::cout << myVar << std::endl;

   //The first time the code reaches here, 'myStaticVar' is initialized. But ONLY the first time.
   static int myStaticVar = 0;

   //Each time the code reaches here, myStaticVar is incremented.
   myStaticVar++;

   //This will print a continuously incrementing number,
   //each time the function is called. '1', '2', '3', etc...
   std::cout << myStaticVar << std::endl;
}

It's a global variable in terms of persistence... but without being global in scope/accessibility.

You can also have static member functions. Static functions are basically non-member functions, but inside the class name's namespace, and with private access to the class's members.

class MyClass
{
    public:
    int Func()
    {
        //...do something...
    }

    static int StaticFunc()
    {
        //...do something...
    }
};

int main()
{
   MyClass myClassA;
   myClassA.Func(); //Calls 'Func'.
   myClassA.StaticFunc(); //Calls 'StaticFunc'.

   MyClass::StaticFunc(); //Calls 'StaticFunc'.
   MyClass::Func(); //Error: You can't call a non-static member-function without a class instance!

   return 0;
}

When you call a member-function, there's a hidden parameter called 'this', that is a pointer to the instance of the class calling the function. Static member functions don't have that hidden parameter... they are callable without a class instance, but also cannot access non-static member variables of a class, because they don't have a 'this' pointer to work with. They aren't being called on any specific class instance.

Span inside anchor or anchor inside span or doesn't matter?

It can matter if for instance you are using some sort icon font. I had this just now with:

<span class="fa fa-print fa-3x"><a href="some_link"></a></span>

Normally I would put the span inside the A but the styling wasn't taking effect until swapped it round.

Duplicate line in Visual Studio Code

Mac:

Duplicate Line Down :shift + option + ?

Duplicate Line Up:shift + option + ?

Predict() - Maybe I'm not understanding it

To avoid error, an important point about the new dataset is the name of independent variable. It must be the same as reported in the model. Another way is to nest the two function without creating a new dataset

model <- lm(Coupon ~ Total, data=df)
predict(model, data.frame(Total=c(79037022, 83100656, 104299800)))

Pay attention on the model. The next two commands are similar, but for predict function, the first work the second don't work.

model <- lm(Coupon ~ Total, data=df) #Ok
model <- lm(df$Coupon ~ df$Total) #Ko

Calculating width from percent to pixel then minus by pixel in LESS CSS

You can escape the calc arguments in order to prevent them from being evaluated on compilation.

Using your example, you would simply surround the arguments, like this:

calc(~'100% - 10px')

Demo : http://jsfiddle.net/c5aq20b6/


I find that I use this in one of the following three ways:

Basic Escaping

Everything inside the calc arguments is defined as a string, and is totally static until it's evaluated by the client:

LESS Input

div {
    > span {
        width: calc(~'100% - 10px');
    }
}

CSS Output

div > span {
  width: calc(100% - 10px);
}

Interpolation of Variables

You can insert a LESS variable into the string:

LESS Input

div {
    > span {
        @pad: 10px;
        width: calc(~'100% - @{pad}');
    }
}

CSS Output

div > span {
  width: calc(100% - 10px);
}

Mixing Escaped and Compiled Values

You may want to escape a percentage value, but go ahead and evaluate something on compilation:

LESS Input

@btnWidth: 40px;
div {
    > span {
        @pad: 10px;
        width: calc(~'(100% - @{pad})' - (@btnWidth * 2));
    }
}

CSS Output

div > span {
  width: calc((100% - 10px) - 80px);
}

Source: http://lesscss.org/functions/#string-functions-escape.

Is there any standard for JSON API response format?

The point of JSON is that it is completely dynamic and flexible. Bend it to whatever whim you would like, because it's just a set of serialized JavaScript objects and arrays, rooted in a single node.

What the type of the rootnode is is up to you, what it contains is up to you, whether you send metadata along with the response is up to you, whether you set the mime-type to application/json or leave it as text/plain is up to you (as long as you know how to handle the edge cases).

Build a lightweight schema that you like.
Personally, I've found that analytics-tracking and mp3/ogg serving and image-gallery serving and text-messaging and network-packets for online gaming, and blog-posts and blog-comments all have very different requirements in terms of what is sent and what is received and how they should be consumed.

So the last thing I'd want, when doing all of that, is to try to make each one conform to the same boilerplate standard, which is based on XML2.0 or somesuch.

That said, there's a lot to be said for using schemas which make sense to you and are well thought out.
Just read some API responses, note what you like, criticize what you don't, write those criticisms down and understand why they rub you the wrong way, and then think about how to apply what you learned to what you need.

MySQL CURRENT_TIMESTAMP on create and on update

Guess this is a old post but actually i guess mysql supports 2 TIMESTAMP in its recent editions mysql 5.6.25 thats what im using as of now.

Minimum and maximum value of z-index?

Z-Index only works for elements that have position: relative; or position: absolute; applied to them. If that's not the problem we'll need to see an example page to be more helpful.

EDIT: The good doctor has already put the fullest explanation but the quick version is that the minimum is 0 because it can't be a negative number and the maximum - well, you'll never really need to go above 10 for most designs.

how to read System environment variable in Spring applicationContext

In your bean definition, make sure to include "searchSystemEnvironment" and set it to "true". And if you're using it to build a path to a file, specify it as a file:/// url.

So for example, if you have a config file located in

/testapp/config/my.app.config.properties

then set an environment variable like so:

MY_ENV_VAR_PATH=/testapp/config

and your app can load the file using a bean definition like this:

e.g.

<bean class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer">
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
    <property name="searchSystemEnvironment" value="true" />
    <property name="searchContextAttributes" value="true" />
    <property name="contextOverride" value="true" />
    <property name="ignoreResourceNotFound" value="true" />
    <property name="locations">
        <list>
            <value>file:///${MY_ENV_VAR_PATH}/my.app.config.properties</value>
        </list>
    </property>
</bean>

See full command of running/stopped container in Docker

TL-DR

docker ps --no-trunc and docker inspect CONTAINER provide the entrypoint executed to start the container, along the command passed to, but that may miss some parts such as ${ANY_VAR} because container environment variables are not printed as resolved.

To overcome that, docker inspect CONTAINER has an advantage because it also allow to retrieve separately env variables and their values defined in the container from the Config.Env property.

docker ps and docker inspect provide information about the executed entrypoint and its command. Often, that is a wrapper entrypoint script (.sh) and not the "real" program started by the container. To get information on that, requesting process information with ps or /proc/1/cmdline help.


1) docker ps --no-trunc

It prints the entrypoint and the command executed for all running containers. While it prints the command passed to the entrypoint (if we pass that), it doesn't show value of docker env variables (such as $FOO or ${FOO}).
If our containers use env variables, it may be not enough.

For example, run an alpine container :

docker run --name alpine-example -e MY_VAR=/var alpine:latest sh -c 'ls $MY_VAR'

When use docker -ps such as :

docker ps -a --filter name=alpine-example --no-trunc

It prints :

CONTAINER ID           IMAGE               COMMAND                CREATED             STATUS                     PORTS               NAMES
5b064a6de6d8417...   alpine:latest       "sh -c 'ls $MY_VAR'"   2 minutes ago       Exited (0) 2 minutes ago                       alpine-example

We see the command passed to the entrypoint : sh -c 'ls $MY_VAR' but $MY_VAR is indeed not resolved.

2) docker inspect CONTAINER

When we inspect the alpine-example container :

docker inspect alpine-example | grep -4 Cmd

The command is also there but we don't still see the env variable value :

        "Cmd": [
            "sh",
            "-c",
            "ls $MY_VAR"
        ],

In fact, we could not see interpolated variables with these docker commands.
While as a trade-off, we could display separately both command and env variables for a container with docker inspect :

docker inspect  alpine-example  | grep -4 -E "Cmd|Env"

That prints :

        "Env": [
            "MY_VAR=/var",
            "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
        ],
        "Cmd": [
            "sh",
            "-c",
            "ls $MY_VAR"
        ]

A more docker way would be to use the --format flag of docker inspect that allows to specify JSON attributes to render :

docker inspect --format '{{.Name}} {{.Config.Cmd}}  {{ (.Config.Env) }}'  alpine-example

That outputs :

/alpine-example [sh -c ls $MY_VAR]  [MY_VAR=/var PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin]

3) Retrieve the started process from the container itself for running containers

The entrypoint and command executed by docker may be helpful but in some cases, it is not enough because that is "only" a wrapper entrypoint script (.sh) that is responsible to start the real/core process.
For example when I run a Nexus container, the command executed and shown to run the container is "sh -c ${SONATYPE_DIR}/start-nexus-repository-manager.sh".
For PostgreSQL that is "docker-entrypoint.sh postgres".

To get more information, we could execute on a running container docker exec CONTAINER ps aux.
It may print other processes that may not interest us.
To narrow to the initial process launched by the entrypoint, we could do :

docker exec CONTAINER ps -1

I specify 1 because the process executed by the entrypoint is generally the one with the 1 id.

Without ps, we could still find the information in /proc/1/cmdline (in most of Linux distros but not all). For example :

docker exec CONTAINER cat /proc/1/cmdline | sed -e "s/\x00/ /g"; echo    

If we have access to the docker host that started the container, another alternative to get the full command of the process executed by the entrypoint is : : execute ps -PID where PID is the local process created by the Docker daemon to run the container such as :

ps -$(docker container inspect --format '{{.State.Pid}}'  CONTAINER)

User-friendly formatting with docker ps

docker ps --no-trunc is not always easy to read.
Specifying columns to print and in a tabular format may make it better :

docker ps   --no-trunc  --format "table{{.Names}}\t{{.CreatedAt}}\t{{.Command}}"

Create an alias may help :

alias dps='docker ps   --no-trunc  --format "table{{.Names}}\t{{.CreatedAt}}\t{{.Command}}"'

How to set environment variable or system property in spring tests?

The right way to do this, starting with Spring 4.1, is to use a @TestPropertySource annotation.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:whereever/context.xml")
@TestPropertySource(properties = {"myproperty = foo"})
public class TestWarSpringContext {
    ...    
}

See @TestPropertySource in the Spring docs and Javadocs.

High Quality Image Scaling Library

When you draw the image using GDI+ it scales quite well in my opinion. You can use this to create a scaled image.

If you want to scale your image with GDI+ you can do something like this:

Bitmap original = ...
Bitmap scaled = new Bitmap(new Size(original.Width * 4, original.Height * 4));
using (Graphics graphics = Graphics.FromImage(scaled)) {
  graphics.DrawImage(original, new Rectangle(0, 0, scaled.Width, scaled.Height));
}

Java ArrayList for integers

you are not creating an arraylist for integers, but you are trying to create an arraylist for arrays of integers.

so if you want your code to work just put.

List<Integer> list = new ArrayList<>();
int x = 5;
list.add(x);

Align image to left of text on same line - Twitter Bootstrap3

Starting with Bootstrap v3.3.0 you can use .media-left and .media-body

<div class="media">
    <span class="media-left">
        <img src="../site/img/success32.png" alt="...">
    </span>
    <div class="media-body">
        <h3 class="media-heading">Experience</h3>
        ...
    </div>
</div>

Documentation: https://getbootstrap.com/docs/3.3/components/#media

Open popup and refresh parent page on close popup

I use this:

<script language='javascript'>
var t;
function doLoad() {
t = setTimeout("window.close()",1000);
}

</script>
<script type="text/javascript">
function refreshAndClose() {
    window.opener.location.reload(true);
    window.close();
}
</script>
<body onbeforeunload="refreshAndClose();" onLoad='doLoad()''>

when the window closes it then refreshes the parent window.

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

In my case, I have solved this way:

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

and input type date is ok

Loading local JSON file

$.ajax({
       url: "Scripts/testingJSON.json",
           //force to handle it as text
       dataType: "text",
            success: function (dataTest) {

                //data downloaded so we call parseJSON function 
                //and pass downloaded data
                var json = $.parseJSON(dataTest);
                //now json variable contains data in json format
                //let's display a few items
                $.each(json, function (i, jsonObjectList) {
                for (var index = 0; index < jsonObjectList.listValue_.length;index++) {
                      alert(jsonObjectList.listKey_[index][0] + " -- " + jsonObjectList.listValue_[index].description_);
                      }
                 });


             }
  });

How to convert an enum type variable to a string?

I'm a bit late but here's my solution using g++ and only standard libraries. I've tried to minimise namespace pollution and remove any need to re-typing enum names.

The header file "my_enum.hpp" is:

#include <cstring>

namespace ENUM_HELPERS{
    int replace_commas_and_spaces_with_null(char* string){
        int i, N;
        N = strlen(string);
        for(i=0; i<N; ++i){
            if( isspace(string[i]) || string[i] == ','){
                string[i]='\0';
            }
        }
        return(N);
    }

    int count_words_null_delim(char* string, int tot_N){
        int i;
        int j=0;
        char last = '\0';
        for(i=0;i<tot_N;++i){
            if((last == '\0') && (string[i]!='\0')){
                ++j;
            }
            last = string[i];
        }
        return(j);
    }

    int get_null_word_offsets(char* string, int tot_N, int current_w){
        int i;
        int j=0;
        char last = '\0';
        for(i=0; i<tot_N; ++i){
            if((last=='\0') && (string[i]!='\0')){
                if(j == current_w){
                    return(i);
                }
                ++j;
            }
            last = string[i];
        }
        return(tot_N); //null value for offset
    }

    int find_offsets(int* offsets, char* string, int tot_N, int N_words){
        int i;
        for(i=0; i<N_words; ++i){
            offsets[i] = get_null_word_offsets(string, tot_N, i);
        }
        return(0);
    }
}


#define MAKE_ENUM(NAME, ...)                                            \
namespace NAME{                                                         \
    enum ENUM {__VA_ARGS__};                                            \
    char name_holder[] = #__VA_ARGS__;                                  \
    int name_holder_N =                                                 \
        ENUM_HELPERS::replace_commas_and_spaces_with_null(name_holder); \
    int N =                                                             \
        ENUM_HELPERS::count_words_null_delim(                           \
            name_holder, name_holder_N);                                \
    int offsets[] = {__VA_ARGS__};                                      \
    int ZERO =                                                          \
        ENUM_HELPERS::find_offsets(                                     \
            offsets, name_holder, name_holder_N, N);                    \
    char* tostring(int i){                                              \
       return(&name_holder[offsets[i]]);                                \
    }                                                                   \
}

Example of use:

#include <cstdio>
#include "my_enum.hpp"

MAKE_ENUM(Planets, MERCURY, VENUS, EARTH, MARS)

int main(int argc, char** argv){    
    Planets::ENUM a_planet = Planets::EARTH;
    printf("%s\n", Planets::tostring(Planets::MERCURY));
    printf("%s\n", Planets::tostring(a_planet));
}

This will output:

MERCURY
EARTH

You only have to define everything once, your namespace shouldn't be polluted, and all of the computation is only done once (the rest is just lookups). However, you don't get the type-safety of enum classes (they are still just short integers), you cannot assign values to the enums, you have to define enums somewhere you can define namespaces (e.g. globally).

I'm not sure how good the performance on this is, or if it's a good idea (I learnt C before C++ so my brain still works that way). If anyone knows why this is a bad idea feel free to point it out.

Difference between JSON.stringify and JSON.parse

JSON.stringify turns a JavaScript object into JSON text and stores that JSON text in a string, eg:

var my_object = { key_1: "some text", key_2: true, key_3: 5 };

var object_as_string = JSON.stringify(my_object);  
// "{"key_1":"some text","key_2":true,"key_3":5}"  

typeof(object_as_string);  
// "string"  

JSON.parse turns a string of JSON text into a JavaScript object, eg:

var object_as_string_as_object = JSON.parse(object_as_string);  
// {key_1: "some text", key_2: true, key_3: 5} 

typeof(object_as_string_as_object);  
// "object" 

The executable gets signed with invalid entitlements in Xcode

I grappled with this issue for an hour, and finally found a fix. Turned out the Development Team was different in ProjectTarget and ProjectTests.

HttpListener Access Denied

Thanks all, it was of great help. Just to add more [from MS page]:

Warning

Top-level wildcard bindings (http://*:8080/ and http://+:8080) should not be used. Top-level wildcard bindings can open up your app to security vulnerabilities. This applies to both strong and weak wildcards. Use explicit host names rather than wildcards. Subdomain wildcard binding (for example, *.mysub.com) doesn't have this security risk if you control the entire parent domain (as opposed to *.com, which is vulnerable). See rfc7230 section-5.4 for more information.

What is an API key?

Very generally speaking:

An API key simply identifies you.

If there is a public/private distinction, then the public key is one that you can distribute to others, to allow them to get some subset of information about you from the api. The private key is for your use only, and provides access to all of your data.

OAuth: how to test with local URLs?

You can edit the hosts file on windows or linux Windows : C:\Windows\System32\Drivers\etc\hosts Linux : /etc/hosts

localhost name resolution is handled within DNS itself.

127.0.0.1 mywebsite.com

after you finish your tests you just comment the line you add to disable it

127.0.0.1 mywebsite.com

How to see what privileges are granted to schema of another user

You can use these queries:

select * from all_tab_privs;
select * from dba_sys_privs;
select * from dba_role_privs;

Each of these tables have a grantee column, you can filter on that in the where criteria:

where grantee = 'A'

To query privileges on objects (e.g. tables) in other schema I propose first of all all_tab_privs, it also has a table_schema column.

If you are logged in with the same user whose privileges you want to query, you can use user_tab_privs, user_sys_privs, user_role_privs. They can be queried by a normal non-dba user.

How to find cube root using Python?

def cube(x):
    if 0<=x: return x**(1./3.)
    return -(-x)**(1./3.)
print (cube(8))
print (cube(-8))

Here is the full answer for both negative and positive numbers.

>>> 
2.0
-2.0
>>> 

Or here is a one-liner;

root_cube = lambda x: x**(1./3.) if 0<=x else -(-x)**(1./3.)

HTML5 textarea placeholder not appearing

use <textarea></textarea> instead of leaving a space between the opening and closing tags as <textarea> </textarea>

Android: android.content.res.Resources$NotFoundException: String resource ID #0x5

You are assigning a numeric value to a text field. You have to convert the numeric value to a string with:

String.valueOf(variable)

How do I get a substring of a string in Python?

I would like to add two points to the discussion:

  1. You can use None instead on an empty space to specify "from the start" or "to the end":

    'abcde'[2:None] == 'abcde'[2:] == 'cde'
    

    This is particularly helpful in functions, where you can't provide an empty space as an argument:

    def substring(s, start, end):
        """Remove `start` characters from the beginning and `end` 
        characters from the end of string `s`.
    
        Examples
        --------
        >>> substring('abcde', 0, 3)
        'abc'
        >>> substring('abcde', 1, None)
        'bcde'
        """
        return s[start:end]
    
  2. Python has slice objects:

    idx = slice(2, None)
    'abcde'[idx] == 'abcde'[2:] == 'cde'
    

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled

I solved it by myself.

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.0.7.Final</version>
</dependency>

Injecting Mockito mocks into a Spring bean

I would suggest to migrate your project to Spring Boot 1.4. After that you can use new annotation @MockBean to fake your com.package.Dao

MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

If the ALTER USER ... command line doesn't work for you AND if you are using Windows 10 then try to follow those steps:

1) Type MySQL in the windows search bar

2) Open the MySQL Windows Installer - Community

3) Look for "MySQL server" and click on Reconfigure step 3

4) Click on "Next" until you reach the "Authentification Method" phase

5) On the "Authentification Method" phase check the second option "Use Legacy Authentication Method" step 5

6) Then follow the steps given by the Windows installer until the end

7) When it's done, go into "Services" from the Windows search bar, click on "start" MySql81".

Now, try again, the connection between MySQL and Node.js should work!

How to pass IEnumerable list to controller in MVC including checkbox state?

Use a list instead and replace your foreach loop with a for loop:

@model IList<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()

    @for (var i = 0; i < Model.Count; i++) 
    {
        <tr>
            <td>
                @Html.HiddenFor(x => x[i].IP)           
                @Html.CheckBoxFor(x => x[i].Checked)
            </td>
            <td>
                @Html.DisplayFor(x => x[i].IP)
            </td>
        </tr>
    }
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

Alternatively you could use an editor template:

@model IEnumerable<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()
    @Html.EditorForModel()   
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

and then define the template ~/Views/Shared/EditorTemplates/BlockedIPViewModel.cshtml which will automatically be rendered for each element of the collection:

@model BlockedIPViewModel
<tr>
    <td>
        @Html.HiddenFor(x => x.IP)
        @Html.CheckBoxFor(x => x.Checked)
    </td>
    <td>
        @Html.DisplayFor(x => x.IP)
    </td>
</tr>

The reason you were getting null in your controller is because you didn't respect the naming convention for your input fields that the default model binder expects to successfully bind to a list. I invite you to read the following article.

Once you have read it, look at the generated HTML (and more specifically the names of the input fields) with my example and yours. Then compare and you will understand why yours doesn't work.

Twitter bootstrap scrollable table

Put the table in a div and give that div the class pre-scrollable.

How do I add a bullet symbol in TextView?

Copy paste: •. I've done it with other weird characters, such as ? and ?.

Edit: here's an example. The two Buttons at the bottom have android:text="?" and "?".

What is the best way to determine a session variable is null or empty in C#?

To follow on from what others have said. I tend to have two layers:

The core layer. This is within a DLL that is added to nearly all web app projects. In this I have a SessionVars class which does the grunt work for Session state getters/setters. It contains code like the following:

public class SessionVar
{
    static HttpSessionState Session
    {
        get
        {
            if (HttpContext.Current == null)
                throw new ApplicationException("No Http Context, No Session to Get!");

            return HttpContext.Current.Session;
        }
    }

    public static T Get<T>(string key)
    {
        if (Session[key] == null)
            return default(T);
        else
            return (T)Session[key];
    }

    public static void Set<T>(string key, T value)
    {
        Session[key] = value;
    }
}

Note the generics for getting any type.

I then also add Getters/Setters for specific types, especially string since I often prefer to work with string.Empty rather than null for variables presented to Users.

e.g:

public static string GetString(string key)
{
    string s = Get<string>(key);
    return s == null ? string.Empty : s;
}

public static void SetString(string key, string value)
{
    Set<string>(key, value);
}

And so on...

I then create wrappers to abstract that away and bring it up to the application model. For example, if we have customer details:

public class CustomerInfo
{
    public string Name
    {
        get
        {
            return SessionVar.GetString("CustomerInfo_Name");
        }
        set
        {
            SessionVar.SetString("CustomerInfo_Name", value);
        }
    }
}

You get the idea right? :)

NOTE: Just had a thought when adding a comment to the accepted answer. Always ensure objects are serializable when storing them in Session when using a state server. It can be all too easy to try and save an object using the generics when on web farm and it go boom. I deploy on a web farm at work so added checks to my code in the core layer to see if the object is serializable, another benefit of encapsulating the Session Getters and Setters :)

Passing an array as parameter in JavaScript

It is possible to pass arrays to functions, and there are no special requirements for dealing with them. Are you sure that the array you are passing to to your function actually has an element at [0]?

Div vertical scrollbar show

What browser are you testing in?

What DOCType have you set?

How exactly are you declaring your CSS?

Are you sure you haven't missed a ; before/after the overflow-y: scroll?

I've just tested the following in IE7 and Firefox and it works fine

_x000D_
_x000D_
<!-- Scroll bar present but disabled when less content -->_x000D_
<div style="width: 200px; height: 100px; overflow-y: scroll;">_x000D_
  test_x000D_
</div>_x000D_
_x000D_
<!-- Scroll bar present and enabled when more contents -->        _x000D_
<div style="width: 200px; height: 100px; overflow-y: scroll;">_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
</div>
_x000D_
_x000D_
_x000D_

How is the java memory pool divided?

The new keyword allocates memory on the Java heap. The heap is the main pool of memory, accessible to the whole of the application. If there is not enough memory available to allocate for that object, the JVM attempts to reclaim some memory from the heap with a garbage collection. If it still cannot obtain enough memory, an OutOfMemoryError is thrown, and the JVM exits.

The heap is split into several different sections, called generations. As objects survive more garbage collections, they are promoted into different generations. The older generations are not garbage collected as often. Because these objects have already proven to be longer lived, they are less likely to be garbage collected.

When objects are first constructed, they are allocated in the Eden Space. If they survive a garbage collection, they are promoted to Survivor Space, and should they live long enough there, they are allocated to the Tenured Generation. This generation is garbage collected much less frequently.

There is also a fourth generation, called the Permanent Generation, or PermGen. The objects that reside here are not eligible to be garbage collected, and usually contain an immutable state necessary for the JVM to run, such as class definitions and the String constant pool. Note that the PermGen space is planned to be removed from Java 8, and will be replaced with a new space called Metaspace, which will be held in native memory. reference:http://www.programcreek.com/2013/04/jvm-run-time-data-areas/

Diagram of Java memory for several threads Diagram of Java memory distribution

Remove an item from an IEnumerable<T> collection

There is now an extension method to convert the IEnumerable<> to a Dictionary<,> which then has a Remove method.

public readonly IEnumerable<User> Users = new User[]; // or however this would be initialized

// To take an item out of the collection
Users.ToDictionary(u => u.Id).Remove(1123);

// To take add an item to the collection
Users.ToList().Add(newuser);

Determine distance from the top of a div to top of window with javascript

Vanilla:

window.addEventListener('scroll', function(ev) {

   var someDiv = document.getElementById('someDiv');
   var distanceToTop = someDiv.getBoundingClientRect().top;

   console.log(distanceToTop);
});

Open your browser console and scroll your page to see the distance.

Create a hidden field in JavaScript

You can use this method to create hidden text field with/without form. If you need form just pass form with object status = true.

You can also add multiple hidden fields. Use this way:

CustomizePPT.setHiddenFields( 
    { 
        "hidden" : 
        {
            'fieldinFORM' : 'thisdata201' , 
            'fieldinFORM2' : 'this3' //multiple hidden fields
            .
            .
            .
            .
            .
            'nNoOfFields' : 'nthData'
        },
    "form" : 
    {
        "status" : "true",
        "formID" : "form3"
    } 
} );

_x000D_
_x000D_
var CustomizePPT = new Object();_x000D_
CustomizePPT.setHiddenFields = function(){ _x000D_
    var request = [];_x000D_
 var container = '';_x000D_
 console.log(arguments);_x000D_
 request = arguments[0].hidden;_x000D_
    console.log(arguments[0].hasOwnProperty('form'));_x000D_
 if(arguments[0].hasOwnProperty('form') == true)_x000D_
 {_x000D_
  if(arguments[0].form.status == 'true'){_x000D_
   var parent = document.getElementById("container");_x000D_
   container = document.createElement('form');_x000D_
   parent.appendChild(container);_x000D_
   Object.assign(container, {'id':arguments[0].form.formID});_x000D_
  }_x000D_
 }_x000D_
 else{_x000D_
   container = document.getElementById("container");_x000D_
 }_x000D_
 _x000D_
 //var container = document.getElementById("container");_x000D_
 Object.keys(request).forEach(function(elem)_x000D_
 {_x000D_
  if($('#'+elem).length <= 0){_x000D_
   console.log("Hidden Field created");_x000D_
   var input = document.createElement('input');_x000D_
   Object.assign(input, {"type" : "text", "id" : elem, "value" : request[elem]});_x000D_
   container.appendChild(input);_x000D_
  }else{_x000D_
   console.log("Hidden Field Exists and value is below" );_x000D_
   $('#'+elem).val(request[elem]);_x000D_
  }_x000D_
 });_x000D_
};_x000D_
_x000D_
CustomizePPT.setHiddenFields( { "hidden" : {'fieldinFORM' : 'thisdata201' , 'fieldinFORM2' : 'this3'}, "form" : {"status" : "true","formID" : "form3"} } );_x000D_
CustomizePPT.setHiddenFields( { "hidden" : {'withoutFORM' : 'thisdata201','withoutFORM2' : 'this2'}});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id='container'>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Sort objects in an array alphabetically on one property of the array

To support unicode:

objArray.sort(function(a, b) {
   return a.DepartmentName.localeCompare(b.DepartmentName);
});

How to bind 'touchstart' and 'click' events but not respond to both?

Just for documentation purposes, here's what I've done for the fastest/most responsive click on desktop/tap on mobile solution that I could think of:

I replaced jQuery's on function with a modified one that, whenever the browser supports touch events, replaced all my click events with touchstart.

$.fn.extend({ _on: (function(){ return $.fn.on; })() });
$.fn.extend({
    on: (function(){
        var isTouchSupported = 'ontouchstart' in window || window.DocumentTouch && document instanceof DocumentTouch;
        return function( types, selector, data, fn, one ) {
            if (typeof types == 'string' && isTouchSupported && !(types.match(/touch/gi))) types = types.replace(/click/gi, 'touchstart');
            return this._on( types, selector, data, fn);
        };
    }()),
});

Usage than would be the exact same as before, like:

$('#my-button').on('click', function(){ /* ... */ });

But it would use touchstart when available, click when not. No delays of any kind needed :D

Compare DATETIME and DATE ignoring time portion

For Compare two date like MM/DD/YYYY to MM/DD/YYYY . Remember First thing column type of Field must be dateTime. Example : columnName : payment_date dataType : DateTime .

after that you can easily compare it. Query is :

select  *  from demo_date where date >= '3/1/2015' and date <=  '3/31/2015'.

It very simple ...... It tested it.....

JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory

I was getting this error even when all the relevant dependencies were in place because I hadn't created the schema in MySQL.

I thought it would be created automatically but it wasn't. Although the table itself will be created, you have to create the schema.

Aligning a button to the center

For me it worked using flexbox, which is in my opinion the cleanest solution.

Add a css class around the parent div / element with :

.parent {
display: flex;
}

and for the button use:

.button {
justify-content: center;
}

You should use a parent div, otherwise the button doesn't 'know' what the middle of the page / element is.

If this is not working, try :

#wrapper {
    display:flex;
    justify-content: center;
}

Use of Greater Than Symbol in XML

CDATA is a better general solution.

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

Why :not just use two :not:

input:not([type="radio"]):not([type="checkbox"])

Yes, it is intentional

Wait Until File Is Completely Written

I would like to add an answer here, because this worked for me. I used time delays, while loops, everything I could think of.

I had the Windows Explorer window of the output folder open. I closed it, and everything worked like a charm.

I hope this helps someone.

Is it possible to import modules from all files in a directory, using a wildcard?

This is not exactly what you asked for but, with this method I can Iterate throught componentsList in my other files and use function such as componentsList.map(...) which I find pretty usefull !

import StepOne from './StepOne';
import StepTwo from './StepTwo';
import StepThree from './StepThree';
import StepFour from './StepFour';
import StepFive from './StepFive';
import StepSix from './StepSix';
import StepSeven from './StepSeven';
import StepEight from './StepEight';

const componentsList= () => [
  { component: StepOne(), key: 'step1' },
  { component: StepTwo(), key: 'step2' },
  { component: StepThree(), key: 'step3' },
  { component: StepFour(), key: 'step4' },
  { component: StepFive(), key: 'step5' },
  { component: StepSix(), key: 'step6' },
  { component: StepSeven(), key: 'step7' },
  { component: StepEight(), key: 'step8' }
];

export default componentsList;

Resizing image in Java

If you have an java.awt.Image, rezising it doesn't require any additional libraries. Just do:

Image newImage = yourImage.getScaledInstance(newWidth, newHeight, Image.SCALE_DEFAULT);

Ovbiously, replace newWidth and newHeight with the dimensions of the specified image.
Notice the last parameter: it tells to the runtime the algorithm you want to use for resizing.

There are algorithms that produce a very precise result, however these take a large time to complete.
You can use any of the following algorithms:

See the Javadoc for more info.

Shift elements in a numpy array

Not numpy but scipy provides exactly the shift functionality you want,

import numpy as np
from scipy.ndimage.interpolation import shift

xs = np.array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.])

shift(xs, 3, cval=np.NaN)

where default is to bring in a constant value from outside the array with value cval, set here to nan. This gives the desired output,

array([ nan, nan, nan, 0., 1., 2., 3., 4., 5., 6.])

and the negative shift works similarly,

shift(xs, -3, cval=np.NaN)

Provides output

array([  3.,   4.,   5.,   6.,   7.,   8.,   9.,  nan,  nan,  nan])

Using gdb to single-step assembly code outside specified executable causes error "cannot find bounds of current function"

You can use stepi or nexti (which can be abbreviated to si or ni) to step through your machine code.

Loop through a comma-separated shell variable

Try this one.

#/bin/bash   
testpid="abc,def,ghij" 
count=`echo $testpid | grep -o ',' | wc -l` # this is not a good way
count=`expr $count + 1` 
while [ $count -gt 0 ]  ; do
     echo $testpid | cut -d ',' -f $i
     count=`expr $count - 1 `
done

How to replace (null) values with 0 output in PIVOT

You cannot place the IsNull() until after the data is selected so you will place the IsNull() around the final value in the SELECT:

SELECT CLASS,
  IsNull([AZ], 0) as [AZ],
  IsNull([CA], 0) as [CA],
  IsNull([TX], 0) as [TX]
FROM #TEMP
PIVOT 
(
  SUM(DATA)
  FOR STATE IN ([AZ], [CA], [TX])
) AS PVT
ORDER BY CLASS

Slack URL to open a channel from browser

The URI to open a specific channel in Slack app is:

slack://channel?id=<CHANNEL-ID>&team=<TEAM-ID>

You will probably need these resources of the Slack API to get IDs of your team and channel:

Here's the full documentation from Slack

Onclick javascript to make browser go back to previous page?

Works for me everytime

<a href="javascript:history.go(-1)">
    <button type="button">
        Back
    </button>
</a>

Python threading.timer - repeat function every 'n' seconds

I have changed some code in swapnil-jariwala code to make a little console clock.

from threading import Timer, Thread, Event
from datetime import datetime

class PT():

    def __init__(self, t, hFunction):
        self.t = t
        self.hFunction = hFunction
        self.thread = Timer(self.t, self.handle_function)

    def handle_function(self):
        self.hFunction()
        self.thread = Timer(self.t, self.handle_function)
        self.thread.start()

    def start(self):
        self.thread.start()

def printer():
    tempo = datetime.today()
    h,m,s = tempo.hour, tempo.minute, tempo.second
    print(f"{h}:{m}:{s}")


t = PT(1, printer)
t.start()

OUTPUT

>>> 11:39:11
11:39:12
11:39:13
11:39:14
11:39:15
11:39:16
...

Timer with a tkinter Graphic interface

This code puts the clock timer in a little window with tkinter

from threading import Timer, Thread, Event
from datetime import datetime
import tkinter as tk

app = tk.Tk()
lab = tk.Label(app, text="Timer will start in a sec")
lab.pack()


class perpetualTimer():

    def __init__(self, t, hFunction):
        self.t = t
        self.hFunction = hFunction
        self.thread = Timer(self.t, self.handle_function)

    def handle_function(self):
        self.hFunction()
        self.thread = Timer(self.t, self.handle_function)
        self.thread.start()

    def start(self):
        self.thread.start()

    def cancel(self):
        self.thread.cancel()


def printer():
    tempo = datetime.today()
    clock = "{}:{}:{}".format(tempo.hour, tempo.minute, tempo.second)
    try:
        lab['text'] = clock
    except RuntimeError:
        exit()


t = perpetualTimer(1, printer)
t.start()
app.mainloop()

An example of flashcards game (sort of)

from threading import Timer, Thread, Event
from datetime import datetime


class perpetualTimer():

    def __init__(self, t, hFunction):
        self.t = t
        self.hFunction = hFunction
        self.thread = Timer(self.t, self.handle_function)

    def handle_function(self):
        self.hFunction()
        self.thread = Timer(self.t, self.handle_function)
        self.thread.start()

    def start(self):
        self.thread.start()

    def cancel(self):
        self.thread.cancel()


x = datetime.today()
start = x.second


def printer():
    global questions, counter, start
    x = datetime.today()
    tempo = x.second
    if tempo - 3 > start:
        show_ans()
    #print("\n{}:{}:{}".format(tempo.hour, tempo.minute, tempo.second), end="")
    print()
    print("-" + questions[counter])
    counter += 1
    if counter == len(answers):
        counter = 0


def show_ans():
    global answers, c2
    print("It is {}".format(answers[c2]))
    c2 += 1
    if c2 == len(answers):
        c2 = 0


questions = ["What is the capital of Italy?",
             "What is the capital of France?",
             "What is the capital of England?",
             "What is the capital of Spain?"]

answers = "Rome", "Paris", "London", "Madrid"

counter = 0
c2 = 0
print("Get ready to answer")
t = perpetualTimer(3, printer)
t.start()

output:

Get ready to answer
>>> 
-What is the capital of Italy?
It is Rome

-What is the capital of France?
It is Paris

-What is the capital of England?
...

What is the difference between Document style and RPC style communication?

Document
Document style messages can be validated against predefined schema. In document style, SOAP message is sent as a single document. Example of schema:

  <types>  
   <xsd:schema> <xsd:import namespace="http://example.com/" 
    schemaLocation="http://localhost:8080/ws/hello?xsd=1"/>  
   </xsd:schema>  
  </types>

Example of document style soap body message

  <message name="getHelloWorldAsString">   
     <part name="parameters" element="tns:getHelloWorldAsString"/>   
  </message> 
  <message name="getHelloWorldAsStringResponse">  
     <part name="parameters"> element="tns:getHelloWorldAsStringResponse"/>   
  </message>

Document style message is loosely coupled.

RPC RPC style messages use method name and parameters to generate XML structure. messages are difficult to be validated against schema. In RPC style, SOAP message is sent as many elements.

  <message name="getHelloWorldAsString">
    <part name="arg0"> type="xsd:string"/>   
   </message> 
  <message name="getHelloWorldAsStringResponse">   
    <part name="return"
   > type="xsd:string"/>   
  </message>

Here each parameters are discretely specified, RPC style message is tightly coupled, is typically static, requiring changes to the client when the method signature changes The rpc style is limited to very simple XSD types such as String and Integer, and the resulting WSDL will not even have a types section to define and constrain the parameters

Literal By default style. Data is serialized according to a schema, data type not specified in messages but a reference to schema(namespace) is used to build soap messages.

   <soap:body>
     <myMethod>
        <x>5</x>
        <y>5.0</y>
     </myMethod>
   </soap:body>

Encoded Datatype specified in each parameter

   <soap:body>
     <myMethod>
         <x xsi:type="xsd:int">5</x>
         <y xsi:type="xsd:float">5.0</y>
     </myMethod>
   </soap:body>

Schema free

C# Interfaces. Implicit implementation versus Explicit implementation

An implicit interface implementation is where you have a method with the same signature of the interface.

An explicit interface implementation is where you explicitly declare which interface the method belongs to.

interface I1
{
    void implicitExample();
}

interface I2
{
    void explicitExample();
}


class C : I1, I2
{
    void implicitExample()
    {
        Console.WriteLine("I1.implicitExample()");
    }


    void I2.explicitExample()
    {
        Console.WriteLine("I2.explicitExample()");
    }
}

MSDN: implicit and explicit interface implementations

SSRS custom number format

Have you tried with the custom format "#,##0.##" ?

Check if instance is of a type

A little more compact than the other answers if you want to use c as a TForm:

if(c is TForm form){
    form.DoStuff();
}

iPhone get SSID without private library

UPDATE FOR iOS 10 and up

CNCopySupportedInterfaces is no longer deprecated in iOS 10. (API Reference)

You need to import SystemConfiguration/CaptiveNetwork.h and add SystemConfiguration.framework to your target's Linked Libraries (under build phases).

Here is a code snippet in swift (RikiRiocma's Answer):

import Foundation
import SystemConfiguration.CaptiveNetwork

public class SSID {
    class func fetchSSIDInfo() -> String {
        var currentSSID = ""
        if let interfaces = CNCopySupportedInterfaces() {
            for i in 0..<CFArrayGetCount(interfaces) {
                let interfaceName: UnsafePointer<Void> = CFArrayGetValueAtIndex(interfaces, i)
                let rec = unsafeBitCast(interfaceName, AnyObject.self)
                let unsafeInterfaceData = CNCopyCurrentNetworkInfo("\(rec)")
                if unsafeInterfaceData != nil {
                    let interfaceData = unsafeInterfaceData! as Dictionary!
                    currentSSID = interfaceData["SSID"] as! String
                }
            }
        }
        return currentSSID
    }
}

(Important: CNCopySupportedInterfaces returns nil on simulator.)

For Objective-c, see Esad's answer here and below

+ (NSString *)GetCurrentWifiHotSpotName {    
    NSString *wifiName = nil;
    NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
    for (NSString *ifnam in ifs) {
        NSDictionary *info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
        if (info[@"SSID"]) {
            wifiName = info[@"SSID"];
        }
    }
    return wifiName;
}

UPDATE FOR iOS 9

As of iOS 9 Captive Network is deprecated*. (source)

*No longer deprecated in iOS 10, see above.

It's recommended you use NEHotspotHelper (source)

You will need to email apple at [email protected] and request entitlements. (source)

Sample Code (Not my code. See Pablo A's answer):

for(NEHotspotNetwork *hotspotNetwork in [NEHotspotHelper supportedNetworkInterfaces]) {
    NSString *ssid = hotspotNetwork.SSID;
    NSString *bssid = hotspotNetwork.BSSID;
    BOOL secure = hotspotNetwork.secure;
    BOOL autoJoined = hotspotNetwork.autoJoined;
    double signalStrength = hotspotNetwork.signalStrength;
}

Side note: Yup, they deprecated CNCopySupportedInterfaces in iOS 9 and reversed their position in iOS 10. I spoke with an Apple networking engineer and the reversal came after so many people filed Radars and spoke out about the issue on the Apple Developer forums.

How to add buttons like refresh and search in ToolBar in Android?

Add this line at the top:

"xmlns:app="http://schemas.android.com/apk/res-auto"

and then use:

app:showasaction="ifroom"

Is JavaScript's "new" keyword considered harmful?

I agree with pez and some here.

It seems obvious to me that "new" is self descriptive object creation, where the YUI pattern Greg Dean describes is completely obscured.

The possibility someone could write var bar = foo; or var bar = baz(); where baz isn't an object creating method seems far more dangerous.

How to use Git Revert

I reverted back a few commits by running 'git revert commit id' such as:

git revert b2cb7c248d416409f8eb42b561cbff91b0601712

Then i was prompted to commit the revert (just as you would when running 'git commit'). My default terminal program is Vim so i ran:

:wq 

Finally i pushed the change to the repository with:

git push

Trim to remove white space

Why not try this?

html:

<p>
  a b c
</p>

js:

$("p").text().trim();

Echoing the last command run in Bash?

I was able to achieve this by using set -x in the main script (which makes the script print out every command that is executed) and writing a wrapper script which just shows the last line of output generated by set -x.

This is the main script:

#!/bin/bash
set -x
echo some command here
echo last command

And this is the wrapper script:

#!/bin/sh
./test.sh 2>&1 | grep '^\+' | tail -n 1 | sed -e 's/^\+ //'

Running the wrapper script produces this as output:

echo last command

How do I wrap text in a pre tag?

The following helped me:

pre {
    white-space: normal;
    word-wrap: break-word;
}

Thanks

Concatenate multiple node values in xpath

<xsl:template match="element3">
        <xsl:value-of select="element4,element5" separator="."/>
    </xsl:template>

Finding the number of non-blank columns in an Excel sheet using VBA

Result is shown in the following code as column number (8,9 etc.):

Dim lastColumn As Long
lastColumn = Sheet1.Cells(1, Columns.Count).End(xlToLeft).Column
MsgBox lastColumn

Result is shown in the following code as letter (H,I etc.):

Dim lastColumn As Long
lastColumn = Sheet1.Cells(1, Columns.Count).End(xlToLeft).Column
MsgBox Split(Sheet1.Cells(1, lastColumn).Address, "$")(1)

Removing elements by class name?

In pure vanilla Javascript, without jQuery or ES6, you could do:

const elements = document.getElementsByClassName("my-class");

while (elements.length > 0) elements[0].remove();

AngularJS : Initialize service with asynchronous data

So I found a solution. I created an angularJS service, we'll call it MyDataRepository and I created a module for it. I then serve up this javascript file from my server-side controller:

HTML:

<script src="path/myData.js"></script>

Server-side:

@RequestMapping(value="path/myData.js", method=RequestMethod.GET)
public ResponseEntity<String> getMyDataRepositoryJS()
{
    // Populate data that I need into a Map
    Map<String, String> myData = new HashMap<String,String>();
    ...
    // Use Jackson to convert it to JSON
    ObjectMapper mapper = new ObjectMapper();
    String myDataStr = mapper.writeValueAsString(myData);

    // Then create a String that is my javascript file
    String myJS = "'use strict';" +
    "(function() {" +
    "var myDataModule = angular.module('myApp.myData', []);" +
    "myDataModule.service('MyDataRepository', function() {" +
        "var myData = "+myDataStr+";" +
        "return {" +
            "getData: function () {" +
                "return myData;" +
            "}" +
        "}" +
    "});" +
    "})();"

    // Now send it to the client:
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.add("Content-Type", "text/javascript");
    return new ResponseEntity<String>(myJS , responseHeaders, HttpStatus.OK);
}

I can then inject MyDataRepository where ever I need it:

someOtherModule.service('MyOtherService', function(MyDataRepository) {
    var myData = MyDataRepository.getData();
    // Do what you have to do...
}

This worked great for me, but I am open to any feedback if anyone has any. }

sed edit file in place

Versions of sed that support the -i option for editing a file in place write to a temporary file and then rename the file.

Alternatively, you can just use ed. For example, to change all occurrences of foo to bar in the file file.txt, you can do:

echo ',s/foo/bar/g; w' | tr \; '\012' | ed -s file.txt

Syntax is similar to sed, but certainly not exactly the same.

Even if you don't have a -i supporting sed, you can easily write a script to do the work for you. Instead of sed -i 's/foo/bar/g' file, you could do inline file sed 's/foo/bar/g'. Such a script is trivial to write. For example:

#!/bin/sh
IN=$1
shift
trap 'rm -f "$tmp"' 0
tmp=$( mktemp )
<"$IN" "$@" >"$tmp" && cat "$tmp" > "$IN"  # preserve hard links

should be adequate for most uses.

Set Culture in an ASP.Net MVC app

I would do it in the Initialize event of the controller like this...

    protected override void Initialize(System.Web.Routing.RequestContext requestContext)
    {
        base.Initialize(requestContext);

        const string culture = "en-US";
        CultureInfo ci = CultureInfo.GetCultureInfo(culture);

        Thread.CurrentThread.CurrentCulture = ci;
        Thread.CurrentThread.CurrentUICulture = ci;
    }

Convert a PHP object to an associative array

Here I've made an objectToArray() method, which also works with recursive objects, like when $objectA contains $objectB which points again to $objectA.

Additionally I've restricted the output to public properties using ReflectionClass. Get rid of it, if you don't need it.

    /**
     * Converts given object to array, recursively.
     * Just outputs public properties.
     *
     * @param object|array $object
     * @return array|string
     */
    protected function objectToArray($object) {
        if (in_array($object, $this->usedObjects, TRUE)) {
            return '**recursive**';
        }
        if (is_array($object) || is_object($object)) {
            if (is_object($object)) {
                $this->usedObjects[] = $object;
            }
            $result = array();
            $reflectorClass = new \ReflectionClass(get_class($this));
            foreach ($object as $key => $value) {
                if ($reflectorClass->hasProperty($key) && $reflectorClass->getProperty($key)->isPublic()) {
                    $result[$key] = $this->objectToArray($value);
                }
            }
            return $result;
        }
        return $object;
    }

To identify already used objects, I am using a protected property in this (abstract) class, named $this->usedObjects. If a recursive nested object is found, it will be replaced by the string **recursive**. Otherwise it would fail in because of infinite loop.

Get spinner selected items text?

TextView textView = (TextView)mySpinner.getSelectedView();
String result = textView.getText().toString();

How to make a custom LinkedIn share button

The API is updated now and the previous API will be deprecated on 1st March, 2019.

To create a custom Share button for LinkedIn, you need to make POST calls now. You can read the updated documentation here for doing so.

Get JSON data from external URL and display it in a div as plain text

Since the desired page will be called from a different domain you need to return jsonp instead of a json.

$.get("http://theSource", {callback : "?" }, "jsonp",  function(data) {
    $('#summary').text(data.result);
});

Force browser to download image files on click

Leeroy & Richard Parnaby-King:

UPDATE: As of spring 2018 this is no longer possible for cross-origin hrefs. So if you want to create on a domain other than imgur.com it will not work as intended. Chrome deprecations and removals announcement

function forceDownload(url, fileName){
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.responseType = "blob";
    xhr.onload = function(){
        var urlCreator = window.URL || window.webkitURL;
        var imageUrl = urlCreator.createObjectURL(this.response);
        var tag = document.createElement('a');
        tag.href = imageUrl;
        tag.download = fileName;
        document.body.appendChild(tag);
        tag.click();
        document.body.removeChild(tag);
    }
    xhr.send();
}

AngularJS - Trigger when radio button is selected

i prefer to use ng-value with ng-if, [ng-value] will handle trigger changes

<input type="radio"  name="isStudent" ng-model="isStudent" ng-value="true" />

//to show and hide input by removing it from the DOM, that's make me secure from malicious data

<input type="text" ng-if="isStudent"  name="textForStudent" ng-model="job">

Mocking a function to raise an Exception to test an except block

Your mock is raising the exception just fine, but the error.resp.status value is missing. Rather than use return_value, just tell Mock that status is an attribute:

barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')

Additional keyword arguments to Mock() are set as attributes on the resulting object.

I put your foo and bar definitions in a my_tests module, added in the HttpError class so I could use it too, and your test then can be ran to success:

>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
...     barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
...     result = my_test.foo()
... 
404 - 
>>> result is None
True

You can even see the print '404 - %s' % error.message line run, but I think you wanted to use error.content there instead; that's the attribute HttpError() sets from the second argument, at any rate.

"Operation must use an updateable query" error in MS Access

You have to remove the IMEX=1 if you want to update. ;)

"IMEX=1; tells the driver to always read "intermixed" (numbers, dates, strings etc) data columns as text. Note that this option might affect excel sheet write access negative." https://www.connectionstrings.com/excel/

cannot call member function without object

You are right - you declared a new use defined type (Name_pairs) and you need variable of that type to use it.

The code should go like this:

Name_pairs np;
np.read_names()

How to get the list of all printers in computer

If you need more information than just the name of the printer you can use the System.Management API to query them:

var printerQuery = new ManagementObjectSearcher("SELECT * from Win32_Printer");
foreach (var printer in printerQuery.Get())
{
    var name = printer.GetPropertyValue("Name");
    var status = printer.GetPropertyValue("Status");
    var isDefault = printer.GetPropertyValue("Default");
    var isNetworkPrinter = printer.GetPropertyValue("Network");

    Console.WriteLine("{0} (Status: {1}, Default: {2}, Network: {3}", 
                name, status, isDefault, isNetworkPrinter);
}

Vertical divider CSS

<div class="headerdivider"></div>

and

.headerdivider {
    border-left: 1px solid #38546d;
    background: #16222c;
    width: 1px;
    height: 80px;
    position: absolute;
    right: 250px;
    top: 10px;
}

How to switch to new window in Selenium for Python?

On top of the answers already given, to open a new tab the javascript command window.open() can be used.

For example:

# Opens a new tab
self.driver.execute_script("window.open()")

# Switch to the newly opened tab
self.driver.switch_to.window(self.driver.window_handles[1])

# Navigate to new URL in new tab
self.driver.get("https://google.com")
# Run other commands in the new tab here

You're then able to close the original tab as follows

# Switch to original tab
self.driver.switch_to.window(self.driver.window_handles[0])

# Close original tab
self.driver.close()

# Switch back to newly opened tab, which is now in position 0
self.driver.switch_to.window(self.driver.window_handles[0])

Or close the newly opened tab

# Close current tab
self.driver.close()

# Switch back to original tab
self.driver.switch_to.window(self.driver.window_handles[0])

Hope this helps.

Detect the Internet connection is offline?

I had to make a web app (ajax based) for a customer who works a lot with schools, these schools have often a bad internet connection I use this simple function to detect if there is a connection, works very well!

I use CodeIgniter and Jquery:

function checkOnline() {
    setTimeout("doOnlineCheck()", 20000);
}

function doOnlineCheck() {
    //if the server can be reached it returns 1, other wise it times out
    var submitURL = $("#base_path").val() + "index.php/menu/online";

    $.ajax({
        url : submitURL,
        type : "post",
        dataType : "msg",
        timeout : 5000,
        success : function(msg) {
            if(msg==1) {
                $("#online").addClass("online");
                $("#online").removeClass("offline");
            } else {
                $("#online").addClass("offline");
                $("#online").removeClass("online");
            }
            checkOnline();
        },
        error : function() {
            $("#online").addClass("offline");
            $("#online").removeClass("online");
            checkOnline();
        }
    });
}

Get first key in a (possibly) associative array?

Today I had to search for the first key of my array returned by a POST request. (And note the number for a form id etc)

Well, I've found this: Return first key of associative array in PHP

http://php.net/key

I've done this, and it work.

    $data = $request->request->all();
    dump($data);
    while ($test = current($data)) {
        dump($test);
        echo key($data).'<br />';die();
        break;
    }

Maybe it will eco 15min of an other guy. CYA.

Self-reference for cell, column and row in worksheet functions

Just for row, but try referencing a cell just below the selected cell and subtracting one from row.

=ROW(A2)-1

Yields the Row of cell A1 (This formula would go in cell A1.

This avoids all the indirect() and index() use but still works.

What's the CMake syntax to set and use variables?

When writing CMake scripts there is a lot you need to know about the syntax and how to use variables in CMake.

The Syntax

Strings using set():

  • set(MyString "Some Text")
  • set(MyStringWithVar "Some other Text: ${MyString}")
  • set(MyStringWithQuot "Some quote: \"${MyStringWithVar}\"")

Or with string():

  • string(APPEND MyStringWithContent " ${MyString}")

Lists using set():

  • set(MyList "a" "b" "c")
  • set(MyList ${MyList} "d")

Or better with list():

  • list(APPEND MyList "a" "b" "c")
  • list(APPEND MyList "d")

Lists of File Names:

  • set(MySourcesList "File.name" "File with Space.name")
  • list(APPEND MySourcesList "File.name" "File with Space.name")
  • add_excutable(MyExeTarget ${MySourcesList})

The Documentation

The Scope or "What value does my variable have?"

First there are the "Normal Variables" and things you need to know about their scope:

  • Normal variables are visible to the CMakeLists.txt they are set in and everything called from there (add_subdirectory(), include(), macro() and function()).
  • The add_subdirectory() and function() commands are special, because they open-up their own scope.
    • Meaning variables set(...) there are only visible there and they make a copy of all normal variables of the scope level they are called from (called parent scope).
    • So if you are in a sub-directory or a function you can modify an already existing variable in the parent scope with set(... PARENT_SCOPE)
    • You can make use of this e.g. in functions by passing the variable name as a function parameter. An example would be function(xyz _resultVar) is setting set(${_resultVar} 1 PARENT_SCOPE)
  • On the other hand everything you set in include() or macro() scripts will modify variables directly in the scope of where they are called from.

Second there is the "Global Variables Cache". Things you need to know about the Cache:

  • If no normal variable with the given name is defined in the current scope, CMake will look for a matching Cache entry.
  • Cache values are stored in the CMakeCache.txt file in your binary output directory.
  • The values in the Cache can be modified in CMake's GUI application before they are generated. Therefore they - in comparison to normal variables - have a type and a docstring. I normally don't use the GUI so I use set(... CACHE INTERNAL "") to set my global and persistant values.

    Please note that the INTERNAL cache variable type does imply FORCE

  • In a CMake script you can only change existing Cache entries if you use the set(... CACHE ... FORCE) syntax. This behavior is made use of e.g. by CMake itself, because it normally does not force Cache entries itself and therefore you can pre-define it with another value.

  • You can use the command line to set entries in the Cache with the syntax cmake -D var:type=value, just cmake -D var=value or with cmake -C CMakeInitialCache.cmake.
  • You can unset entries in the Cache with unset(... CACHE).

The Cache is global and you can set them virtually anywhere in your CMake scripts. But I would recommend you think twice about where to use Cache variables (they are global and they are persistant). I normally prefer the set_property(GLOBAL PROPERTY ...) and set_property(GLOBAL APPEND PROPERTY ...) syntax to define my own non-persistant global variables.

Variable Pitfalls and "How to debug variable changes?"

To avoid pitfalls you should know the following about variables:

  • Local variables do hide cached variables if both have the same name
  • The find_... commands - if successful - do write their results as cached variables "so that no call will search again"
  • Lists in CMake are just strings with semicolons delimiters and therefore the quotation-marks are important
    • set(MyVar a b c) is "a;b;c" and set(MyVar "a b c") is "a b c"
    • The recommendation is that you always use quotation marks with the one exception when you want to give a list as list
    • Generally prefer the list() command for handling lists
  • The whole scope issue described above. Especially it's recommended to use functions() instead of macros() because you don't want your local variables to show up in the parent scope.
  • A lot of variables used by CMake are set with the project() and enable_language() calls. So it could get important to set some variables before those commands are used.
  • Environment variables may differ from where CMake generated the make environment and when the the make files are put to use.
    • A change in an environment variable does not re-trigger the generation process.
    • Especially a generated IDE environment may differ from your command line, so it's recommended to transfer your environment variables into something that is cached.

Sometimes only debugging variables helps. The following may help you:

  • Simply use old printf debugging style by using the message() command. There also some ready to use modules shipped with CMake itself: CMakePrintHelpers.cmake, CMakePrintSystemInformation.cmake
  • Look into CMakeCache.txt file in your binary output directory. This file is even generated if the actual generation of your make environment fails.
  • Use variable_watch() to see where your variables are read/written/removed.
  • Look into the directory properties CACHE_VARIABLES and VARIABLES
  • Call cmake --trace ... to see the CMake's complete parsing process. That's sort of the last reserve, because it generates a lot of output.

Special Syntax

  • Environment Variables
    • You can can read $ENV{...} and write set(ENV{...} ...) environment variables
  • Generator Expressions
    • Generator expressions $<...> are only evaluated when CMake's generator writes the make environment (it comparison to normal variables that are replaced "in-place" by the parser)
    • Very handy e.g. in compiler/linker command lines and in multi-configuration environments
  • References
    • With ${${...}} you can give variable names in a variable and reference its content.
    • Often used when giving a variable name as function/macro parameter.
  • Constant Values (see if() command)
    • With if(MyVariable) you can directly check a variable for true/false (no need here for the enclosing ${...})
    • True if the constant is 1, ON, YES, TRUE, Y, or a non-zero number.
    • False if the constant is 0, OFF, NO, FALSE, N, IGNORE, NOTFOUND, the empty string, or ends in the suffix -NOTFOUND.
    • This syntax is often use for something like if(MSVC), but it can be confusing for someone who does not know this syntax shortcut.
  • Recursive substitutions
    • You can construct variable names using variables. After CMake has substituted the variables, it will check again if the result is a variable itself. This is very powerful feature used in CMake itself e.g. as sort of a template set(CMAKE_${lang}_COMPILER ...)
    • But be aware this can give you a headache in if() commands. Here is an example where CMAKE_CXX_COMPILER_ID is "MSVC" and MSVC is "1":
      • if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") is true, because it evaluates to if("1" STREQUAL "1")
      • if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") is false, because it evaluates to if("MSVC" STREQUAL "1")
      • So the best solution here would be - see above - to directly check for if(MSVC)
    • The good news is that this was fixed in CMake 3.1 with the introduction of policy CMP0054. I would recommend to always set cmake_policy(SET CMP0054 NEW) to "only interpret if() arguments as variables or keywords when unquoted."
  • The option() command
    • Mainly just cached strings that only can be ON or OFF and they allow some special handling like e.g. dependencies
    • But be aware, don't mistake the option with the set command. The value given to option is really only the "initial value" (transferred once to the cache during the first configuration step) and is afterwards meant to be changed by the user through CMake's GUI.

References

What is the difference between buffer and cache memory in Linux?

It's not 'quite' as simple as this, but it might help understand:

Buffer is for storing file metadata (permissions, location, etc). Every memory page is kept track of here.

Cache is for storing actual file contents.

Can I install Python 3.x and 2.x on the same Windows computer?

You should make sure that the PATH environment variable doesn't contain both python.exe files ( add the one you're currently using to run scripts on a day to day basis ) , or do as Kniht suggested with the batch files . Aside from that , I don't see why not .

P.S : I have 2.6 installed as my "primary" python and 3.0 as my "play" python . The 2.6 is included in the PATH . Everything works fine .

How can I detect if a selector returns null?

My preference, and I have no idea why this isn't already in jQuery:

$.fn.orElse = function(elseFunction) {
  if (!this.length) {
    elseFunction();
  }
};

Used like this:

$('#notAnElement').each(function () {
  alert("Wrong, it is an element")
}).orElse(function() {
  alert("Yup, it's not an element")
});

Or, as it looks in CoffeeScript:

$('#notAnElement').each ->
  alert "Wrong, it is an element"; return
.orElse ->
  alert "Yup, it's not an element"

Copying formula to the next row when inserting a new row

If you have a worksheet with many rows that all contain the formula, by far the easiest method is to copy a row that is without data (but it does contain formulas), and then "insert copied cells" below/above the row where you want to add. The formulas remain. In a pinch, it is OK to use a row with data. Just clear it or overwrite it after pasting.

Handling 'Sequence has no elements' Exception

The value is null, you have to check why... (in addition to the implementation of the solutions proposed here)

Check the hardware Connections.

How to remove CocoaPods from a project?

pod deintegrate and pod clean are two designated commands to remove CocoaPod from your project/repo.

Here is the complete set of commands:

$ sudo gem install cocoapods-deintegrate cocoapods-clean
$ pod deintegrate
$ pod cache clean --all
$ rm Podfile

The original solution was found here: https://medium.com/@icanhazedit/remove-uninstall-deintegrate-cocoapods-from-your-xcode-ios-project-c4621cee5e42#.wd00fj2e5

CocoaPod documentation on pod deintegrate: https://guides.cocoapods.org/terminal/commands.html#pod_deintegrate

SQL: IF clause within WHERE clause

CASE Statement is better option than IF always.

  WHERE  vfl.CreatedDate >= CASE WHEN @FromDate IS NULL THEN vfl.CreatedDate ELSE  @FromDate END
    AND vfl.CreatedDate<=CASE WHEN @ToDate IS NULL THEN vfl.CreatedDate ELSE @ToDate END 

Failed to decode downloaded font

I had to add type="text/css" to my link-tag. I changed it from:

<link href="https://fonts.googleapis.com/css?family=Roboto+Condensed:300,400,700" rel="stylesheet">

to:

<link href="https://fonts.googleapis.com/css?family=Roboto+Condensed:300,400,700" rel="stylesheet" type="text/css">

After I changed it the error disappeared.

Python 2.7 getting user input and manipulating as string without quotations

We can use the raw_input() function in Python 2 and the input() function in Python 3. By default the input function takes an input in string format. For other data type you have to cast the user input.

In Python 2 we use the raw_input() function. It waits for the user to type some input and press return and we need to store the value in a variable by casting as our desire data type. Be careful when using type casting

x = raw_input("Enter a number: ") #String input

x = int(raw_input("Enter a number: ")) #integer input

x = float(raw_input("Enter a float number: ")) #float input

x = eval(raw_input("Enter a float number: ")) #eval input

In Python 3 we use the input() function which returns a user input value.

x = input("Enter a number: ") #String input

If you enter a string, int, float, eval it will take as string input

x = int(input("Enter a number: ")) #integer input

If you enter a string for int cast ValueError: invalid literal for int() with base 10:

x = float(input("Enter a float number: ")) #float input

If you enter a string for float cast ValueError: could not convert string to float

x = eval(input("Enter a float number: ")) #eval input

If you enter a string for eval cast NameError: name ' ' is not defined Those error also applicable for Python 2.