Programs & Examples On #Spooler

Using Powershell to stop a service remotely without WMI or remoting

Based on the built-in Powershell examples, this is what Microsoft suggests. Tested and verified:

To stop:

(Get-WmiObject Win32_Service -filter "name='IPEventWatcher'" -ComputerName Server01).StopService()

To start:

(Get-WmiObject Win32_Service -filter "name='IPEventWatcher'" -ComputerName Server01).StartService()

How best to include other scripts?

An alternative to:

scriptPath=$(dirname $0)

is:

scriptPath=${0%/*}

.. the advantage being not having the dependence on dirname, which is not a built-in command (and not always available in emulators)

How to disable margin-collapsing?

I had similar problem with margin collapse because of parent having position set to relative. Here are list of commands you can use to disable margin collapsing.

HERE IS PLAYGROUND TO TEST

Just try to assign any parent-fix* class to div.container element, or any class children-fix* to div.margin. Pick the one that fits your needs best.

When

  • margin collapsing is disabled, div.absolute with red background will be positioned at the very top of the page.
  • margin is collapsing div.absolute will be positioned at the same Y coordinate as div.margin

_x000D_
_x000D_
html, body { margin: 0; padding: 0; }_x000D_
_x000D_
.container {_x000D_
  width: 100%;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.absolute {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 50px;_x000D_
  right: 50px;_x000D_
  height: 100px;_x000D_
  border: 5px solid #F00;_x000D_
  background-color: rgba(255, 0, 0, 0.5);_x000D_
}_x000D_
_x000D_
.margin {_x000D_
  width: 100%;_x000D_
  height: 20px;_x000D_
  background-color: #444;_x000D_
  margin-top: 50px;_x000D_
  color: #FFF;_x000D_
}_x000D_
_x000D_
/* Here are some examples on how to disable margin _x000D_
   collapsing from within parent (.container) */_x000D_
.parent-fix1 { padding-top: 1px; }_x000D_
.parent-fix2 { border: 1px solid rgba(0,0,0, 0);}_x000D_
.parent-fix3 { overflow: auto;}_x000D_
.parent-fix4 { float: left;}_x000D_
.parent-fix5 { display: inline-block; }_x000D_
.parent-fix6 { position: absolute; }_x000D_
.parent-fix7 { display: flex; }_x000D_
.parent-fix8 { -webkit-margin-collapse: separate; }_x000D_
.parent-fix9:before {  content: ' '; display: table; }_x000D_
_x000D_
/* Here are some examples on how to disable margin _x000D_
   collapsing from within children (.margin) */_x000D_
.children-fix1 { float: left; }_x000D_
.children-fix2 { display: inline-block; }
_x000D_
<div class="container parent-fix1">_x000D_
  <div class="margin children-fix">margin</div>_x000D_
  <div class="absolute"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Here is jsFiddle with example you can edit

"An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page..."

I wasn't using Azure, but I got the same error locally. Using <customErrors mode="Off" /> seemed to have no effect, but checking the Application logs in Event Viewer revealed a warning from ASP.NET which contained all the detail I needed to resolve the issue.

How to break out or exit a method in Java?

Use the return keyword to exit from a method.

public void someMethod() {
    //... a bunch of code ...
    if (someCondition()) {
        return;
    }
    //... otherwise do the following...
}

From the Java Tutorial that I linked to above:

Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so. In such a case, a return statement can be used to branch out of a control flow block and exit the method and is simply used like this:

return;

How to send a model in jQuery $.ajax() post request to MVC controller method

This can be done by building a javascript object to match your mvc model. The names of the javascript properties have to match exactly to the mvc model or else the autobind won't happen on the post. Once you have your model on the server side you can then manipulate it and store the data to the database.

I am achieving this either by a double click event on a grid row or click event on a button of some sort.

@model TestProject.Models.TestModel

<script>

function testButton_Click(){
  var javaModel ={
  ModelId: '@Model.TestId',
  CreatedDate: '@Model.CreatedDate.ToShortDateString()',
  TestDescription: '@Model.TestDescription',
  //Here I am using a Kendo editor and I want to bind the text value to my javascript
  //object. This may be different for you depending on what controls you use.
  TestStatus: ($('#StatusTextBox'))[0].value, 
  TestType: '@Model.TestType'
  }

  //Now I did for some reason have some trouble passing the ENUM id of a Kendo ComboBox 
    //selected value. This puzzled me due to the conversion to Json object in the Ajax call. 
  //By parsing the Type to an int this worked.

  javaModel.TestType = parseInt(javaModel.TestType);

  $.ajax({
      //This is where you want to post to.
      url:'@Url.Action("TestModelUpdate","TestController")', 
      async:true,
      type:"POST",
      contentType: 'application/json',
      dataType:"json",
      data: JSON.stringify(javaModel)
  });
}
</script>


//This is your controller action on the server, and it will autobind your values 
//to the newTestModel on post.

[HttpPost]
public ActionResult TestModelUpdate(TestModel newTestModel)
{
 TestModel.UpdateTestModel(newTestModel);
 return //do some return action;
}

Eclipse - Failed to load class "org.slf4j.impl.StaticLoggerBinder"

After placing the jar file in desired location, you need to add the jar file by right click on

Project --> properties --> Java Build Path --> Libraries --> Add Jar.

How to use SQL Select statement with IF EXISTS sub query?

SELECT Id, 'TRUE' AS NewFiled FROM TABEL1
INTERSECT
SELECT Id, 'TRUE' AS NewFiled FROM TABEL2
UNION
SELECT Id, 'FALSE' AS NewFiled FROM TABEL1
EXCEPT
SELECT Id, 'FALSE' AS NewFiled FROM TABEL2;

Read a zipped file as a pandas DataFrame

For "zip" files, you can use import zipfile and your code will be working simply with these lines:

import zipfile
import pandas as pd
with zipfile.ZipFile("Crime_Incidents_in_2013.zip") as z:
   with z.open("Crime_Incidents_in_2013.csv") as f:
      train = pd.read_csv(f, header=0, delimiter="\t")
      print(train.head())    # print the first 5 rows

And the result will be:

X,Y,CCN,REPORT_DAT,SHIFT,METHOD,OFFENSE,BLOCK,XBLOCK,YBLOCK,WARD,ANC,DISTRICT,PSA,NEIGHBORHOOD_CLUSTER,BLOCK_GROUP,CENSUS_TRACT,VOTING_PRECINCT,XCOORD,YCOORD,LATITUDE,LONGITUDE,BID,START_DATE,END_DATE,OBJECTID
0  -77.054968548763071,38.899775938598317,0925135...                                                                                                                                                               
1  -76.967309569035052,38.872119553647011,1003352...                                                                                                                                                               
2  -76.996184958456539,38.927921847721443,1101010...                                                                                                                                                               
3  -76.943077541353617,38.883686046653935,1104551...                                                                                                                                                               
4  -76.939209158039446,38.892278093281632,1125028...

how to parse a "dd/mm/yyyy" or "dd-mm-yyyy" or "dd-mmm-yyyy" formatted date string using JavaScript or jQuery

See this http://blog.stevenlevithan.com/archives/date-time-format

you can do anything with date.

file : http://stevenlevithan.com/assets/misc/date.format.js

add this to your html code using script tag and to use you can use it as :

var now = new Date();

now.format("m/dd/yy");
// Returns, e.g., 6/09/07

Inserting values into a SQL Server database using ado.net via C#

As I said in comments - you should always use parameters in your query - NEVER EVER concatenate together your SQL statements yourself.

Also: I would recommend to separate the click event handler from the actual code to insert the data.

So I would rewrite your code to be something like

In your web page's code-behind file (yourpage.aspx.cs)

private void button1_Click(object sender, EventArgs e)
{
      string connectionString = "Data Source=DELL-PC;initial catalog=AdventureWorks2008R2 ; User ID=sa;Password=sqlpass;Integrated Security=SSPI;";

      InsertData(connectionString,
                 textBox1.Text.Trim(),  -- first name
                 textBox2.Text.Trim(),  -- last name
                 textBox3.Text.Trim(),  -- user name
                 textBox4.Text.Trim(),  -- password
                 Convert.ToInt32(comboBox1.Text),  -- age
                 comboBox2.Text.Trim(), -- gender
                 textBox7.Text.Trim() );  -- contact
}

In some other code (e.g. a databaselayer.cs):

private void InsertData(string connectionString, string firstName, string lastname, string username, string password
                        int Age, string gender, string contact)
{
    // define INSERT query with parameters
    string query = "INSERT INTO dbo.regist (FirstName, Lastname, Username, Password, Age, Gender,Contact) " + 
                   "VALUES (@FirstName, @Lastname, @Username, @Password, @Age, @Gender, @Contact) ";

    // create connection and command
    using(SqlConnection cn = new SqlConnection(connectionString))
    using(SqlCommand cmd = new SqlCommand(query, cn))
    {
        // define parameters and their values
        cmd.Parameters.Add("@FirstName", SqlDbType.VarChar, 50).Value = firstName;
        cmd.Parameters.Add("@Lastname", SqlDbType.VarChar, 50).Value = lastName;
        cmd.Parameters.Add("@Username", SqlDbType.VarChar, 50).Value = userName;
        cmd.Parameters.Add("@Password", SqlDbType.VarChar, 50).Value = password;
        cmd.Parameters.Add("@Age", SqlDbType.Int).Value = age;
        cmd.Parameters.Add("@Gender", SqlDbType.VarChar, 50).Value = gender;
        cmd.Parameters.Add("@Contact", SqlDbType.VarChar, 50).Value = contact;

        // open connection, execute INSERT, close connection
        cn.Open();
        cmd.ExecuteNonQuery();
        cn.Close();
    }
}

Code like this:

  • is not vulnerable to SQL injection attacks
  • performs much better on SQL Server (since the query is parsed once into an execution plan, then cached and reused later on)
  • separates the event handler (code-behind file) from your actual database code (putting things where they belong - helping to avoid "overweight" code-behinds with tons of spaghetti code, doing everything from handling UI events to database access - NOT a good design!)

C# Passing Function as Argument

There are a couple generic types in .Net (v2 and later) that make passing functions around as delegates very easy.

For functions with return types, there is Func<> and for functions without return types there is Action<>.

Both Func and Action can be declared to take from 0 to 4 parameters. For example, Func < double, int > takes one double as a parameter and returns an int. Action < double, double, double > takes three doubles as parameters and returns nothing (void).

So you can declare your Diff function to take a Func:

public double Diff(double x, Func<double, double> f) {
    double h = 0.0000001;

    return (f(x + h) - f(x)) / h;
}

And then you call it as so, simply giving it the name of the function that fits the signature of your Func or Action:

double result = Diff(myValue, Function);

You can even write the function in-line with lambda syntax:

double result = Diff(myValue, d => Math.Sqrt(d * 3.14));

Why ModelState.IsValid always return false in mvc

Please post your Model Class.

To check the errors in your ModelState use the following code:

var errors = ModelState
    .Where(x => x.Value.Errors.Count > 0)
    .Select(x => new { x.Key, x.Value.Errors })
    .ToArray();

OR: You can also use

var errors = ModelState.Values.SelectMany(v => v.Errors);

Place a break point at the above line and see what are the errors in your ModelState.

How to check if a file exists in a shell script

Here is an alternative method using ls:

(ls x.txt && echo yes) || echo no

If you want to hide any output from ls so you only see yes or no, redirect stdout and stderr to /dev/null:

(ls x.txt >> /dev/null 2>&1 && echo yes) || echo no

How do I get the path of a process in Unix / Linux

I use:

ps -ef | grep 786

Replace 786 with your PID or process name.

Expansion of variables inside single quotes in a command in Bash

The repo command can't care what kind of quotes it gets. If you need parameter expansion, use double quotes. If that means you wind up having to backslash a lot of stuff, use single quotes for most of it, and then break out of them and go into doubles for the part where you need the expansion to happen.

repo forall -c 'literal stuff goes here; '"stuff with $parameters here"' more literal stuff'

Explanation follows, if you're interested.

When you run a command from the shell, what that command receives as arguments is an array of null-terminated strings. Those strings may contain absolutely any non-null character.

But when the shell is building that array of strings from a command line, it interprets some characters specially; this is designed to make commands easier (indeed, possible) to type. For instance, spaces normally indicate the boundary between strings in the array; for that reason, the individual arguments are sometimes called "words". But an argument may nonetheless have spaces in it; you just need some way to tell the shell that's what you want.

You can use a backslash in front of any character (including space, or another backslash) to tell the shell to treat that character literally. But while you can do something like this:

echo \”That\'ll\ be\ \$4.96,\ please,\"\ said\ the\ cashier

...it can get tiresome. So the shell offers an alternative: quotation marks. These come in two main varieties.

Double-quotation marks are called "grouping quotes". They prevent wildcards and aliases from being expanded, but mostly they're for including spaces in a word. Other things like parameter and command expansion (the sorts of thing signaled by a $) still happen. And of course if you want a literal double-quote inside double-quotes, you have to backslash it:

echo "\"That'll be \$4.96, please,\" said the cashier"

Single-quotation marks are more draconian. Everything between them is taken completely literally, including backslashes. There is absolutely no way to get a literal single quote inside single quotes.

Fortunately, quotation marks in the shell are not word delimiters; by themselves, they don't terminate a word. You can go in and out of quotes, including between different types of quotes, within the same word to get the desired result:

echo '"That'\''ll be $4.96, please," said the cashier'

So that's easier - a lot fewer backslashes, although the close-single-quote, backslashed-literal-single-quote, open-single-quote sequence takes some getting used to.

Modern shells have added another quoting style not specified by the POSIX standard, in which the leading single quotation mark is prefixed with a dollar sign. Strings so quoted follow similar conventions to string literals in the ANSI standard version of the C programming language, and are therefore sometimes called "ANSI strings" and the $'...' pair "ANSI quotes". Within such strings, the above advice about backslashes being taken literally no longer applies. Instead, they become special again - not only can you include a literal single quotation mark or backslash by prepending a backslash to it, but the shell also expands the ANSI C character escapes (like \n for a newline, \t for tab, and \xHH for the character with hexadecimal code HH). Otherwise, however, they behave as single-quoted strings: no parameter or command substitution takes place:

echo $'"That\'ll be $4.96, please," said the cashier'

The important thing to note is that the single string received as the argument to the echo command is exactly the same in all of these examples. After the shell is done parsing a command line, there is no way for the command being run to tell what was quoted how. Even if it wanted to.

How do I sort a list of dictionaries by a value of the dictionary?

If you do not need the original list of dictionaries, you could modify it in-place with sort() method using a custom key function.

Key function:

def get_name(d):
    """ Return the value of a key in a dictionary. """

    return d["name"]

The list to be sorted:

data_one = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]

Sorting it in-place:

data_one.sort(key=get_name)

If you need the original list, call the sorted() function passing it the list and the key function, then assign the returned sorted list to a new variable:

data_two = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
new_data = sorted(data_two, key=get_name)

Printing data_one and new_data.

>>> print(data_one)
[{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]
>>> print(new_data)
[{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]

Ubuntu says "bash: ./program Permission denied"

Try this:

sudo chmod +x program_name
./program_name 

sqlalchemy: how to join several tables by one query?

Try this

q = Session.query(
         User, Document, DocumentPermissions,
    ).filter(
         User.email == Document.author,
    ).filter(
         Document.name == DocumentPermissions.document,
    ).filter(
        User.email == 'someemail',
    ).all()

How to install and use "make" in Windows?

make is a GNU command so the only way you can get it on Windows is installing a Windows version like the one provided by GNUWin32. Anyway, there are several options for getting that:

  1. Using MinGW, be sure you have C:\MinGW\bin\mingw32-make.exe. Otherwise you're missing the mingw32-make additional utilities. Look for the link at MinGW's HowTo page to get it installed. Once you've got it, you have two choices:
  • 1.1 Copy the MinGW make executable to make.exe:

    copy c:\MinGW\bin\mingw32-make.exe c:\MinGW\bin\make.exe
    
  • 1.2 Create a link to the actual executable, in your PATH. In this case, if you update MinGW, the link is not deleted:

    mklink c:\bin\make.exe C:\MinGW\bin\mingw32-make.exe
    
  1. Other option is using Chocolatey. First you need to install this package manager. Once installed you simlpy need to install make:

    choco install make
    
  2. Last option is installing a Windows Subsystem for Linux (WSL), so you'll have a Linux distribution of your choice embedded in Windows 10 where you'll be able to install make, gccand all the tools you need to build C programs.

Compute elapsed time

Hope this will help:

<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
    <head>
        <title>compute elapsed time in JavaScript</title>

        <script type="text/javascript">

            function display_c (start) {
                window.start = parseFloat(start);
                var end = 0 // change this to stop the counter at a higher value
                var refresh = 1000; // Refresh rate in milli seconds
                if( window.start >= end ) {
                    mytime = setTimeout( 'display_ct()',refresh )
                } else {
                    alert("Time Over ");
                }
            }

            function display_ct () {
                // Calculate the number of days left
                var days = Math.floor(window.start / 86400);
                // After deducting the days calculate the number of hours left
                var hours = Math.floor((window.start - (days * 86400 ))/3600)
                // After days and hours , how many minutes are left
                var minutes = Math.floor((window.start - (days * 86400 ) - (hours *3600 ))/60)
                // Finally how many seconds left after removing days, hours and minutes.
                var secs = Math.floor((window.start - (days * 86400 ) - (hours *3600 ) - (minutes*60)))

                var x = window.start + "(" + days + " Days " + hours + " Hours " + minutes + " Minutes and " + secs + " Secondes " + ")";

                document.getElementById('ct').innerHTML = x;
                window.start = window.start - 1;

                tt = display_c(window.start);
            }

            function stop() {
                clearTimeout(mytime);
            }

        </script>

    </head>

    <body>

        <input type="button" value="Start Timer" onclick="display_c(86501);"/> | <input type="button" value="End Timer" onclick="stop();"/>
        <span id='ct' style="background-color: #FFFF00"></span>

    </body>
</html>

MongoDb query condition on comparing 2 fields

You can use $expr ( 3.6 mongo version operator ) to use aggregation functions in regular query.

Compare query operators vs aggregation comparison operators.

Regular Query:

db.T.find({$expr:{$gt:["$Grade1", "$Grade2"]}})

Aggregation Query:

db.T.aggregate({$match:{$expr:{$gt:["$Grade1", "$Grade2"]}}})

Declaring variables inside loops, good practice or bad practice?

Chapter 4.8 Block Structure in K&R's The C Programming Language 2.Ed.:

An automatic variable declared and initialized in a block is initialized each time the block is entered.

I might have missed seeing the relevant description in the book like:

An automatic variable declared and initialized in a block is allocated only one time before the block is entered.

But a simple test can prove the assumption held:

 #include <stdio.h>                                                                                                    

 int main(int argc, char *argv[]) {                                                                                    
     for (int i = 0; i < 2; i++) {                                                                                     
         for (int j = 0; j < 2; j++) {                                                                                 
             int k;                                                                                                    
             printf("%p\n", &k);                                                                                       
         }                                                                                                             
     }                                                                                                                 
     return 0;                                                                                                         
 }                                                                                                                     

MS Access DB Engine (32-bit) with Office 64-bit

Install the 2007 version, it seems that if you install the version opposite to the version of Office you are using you can make it work.

http://www.microsoft.com/en-us/download/details.aspx?id=23734

AES vs Blowfish for file encryption

AES.

(I also am assuming you mean twofish not the much older and weaker blowfish)

Both (AES & twofish) are good algorithms. However even if they were equal or twofish was slightly ahead on technical merit I would STILL chose AES.

Why? Publicity. AES is THE standard for government encryption and thus millions of other entities also use it. A talented cryptanalyst simply gets more "bang for the buck" finding a flaw in AES then it does for the much less know and used twofish.

Obscurity provides no protection in encryption. More bodies looking, studying, probing, attacking an algorithm is always better. You want the most "vetted" algorithm possible and right now that is AES. If an algorithm isn't subject to intense and continual scrutiny you should place a lower confidence of it's strength. Sure twofish hasn't been compromised. Is that because of the strength of the cipher or simply because not enough people have taken a close look ..... YET

How to set null value to int in c#?

int does not allow null, use-

int? value = 0  

or use

Nullable<int> value

RecyclerView - How to smooth scroll to top of item on a certain position?

This is an extension function I wrote in Kotlin to use with the RecyclerView (based on @Paul Woitaschek answer):

fun RecyclerView.smoothSnapToPosition(position: Int, snapMode: Int = LinearSmoothScroller.SNAP_TO_START) {
  val smoothScroller = object : LinearSmoothScroller(this.context) {
    override fun getVerticalSnapPreference(): Int = snapMode
    override fun getHorizontalSnapPreference(): Int = snapMode
  }
  smoothScroller.targetPosition = position
  layoutManager?.startSmoothScroll(smoothScroller)
}

Use it like this:

myRecyclerView.smoothSnapToPosition(itemPosition)

How do I detect if software keyboard is visible on Android Device or not?

I wrote sample.

This repository can help to detect keyboard status without assumption that "keyboard should be more than X part of screen"

How to search file text for a pattern and replace it with a given value

Disclaimer: This approach is a naive illustration of Ruby's capabilities, and not a production-grade solution for replacing strings in files. It's prone to various failure scenarios, such as data loss in case of a crash, interrupt, or disk being full. This code is not fit for anything beyond a quick one-off script where all the data is backed up. For that reason, do NOT copy this code into your programs.

Here's a quick short way to do it.

file_names = ['foo.txt', 'bar.txt']

file_names.each do |file_name|
  text = File.read(file_name)
  new_contents = text.gsub(/search_regexp/, "replacement string")

  # To merely print the contents of the file, use:
  puts new_contents

  # To write changes to the file, use:
  File.open(file_name, "w") {|file| file.puts new_contents }
end

Query grants for a table in postgres

\z mytable from psql gives you all the grants from a table, but you'd then have to split it up by individual user.

How do I check if a given string is a legal/valid file name under Windows?

This class cleans filenames and paths; use it like

var myCleanPath = PathSanitizer.SanitizeFilename(myBadPath, ' ');

Here's the code;

/// <summary>
/// Cleans paths of invalid characters.
/// </summary>
public static class PathSanitizer
{
    /// <summary>
    /// The set of invalid filename characters, kept sorted for fast binary search
    /// </summary>
    private readonly static char[] invalidFilenameChars;
    /// <summary>
    /// The set of invalid path characters, kept sorted for fast binary search
    /// </summary>
    private readonly static char[] invalidPathChars;

    static PathSanitizer()
    {
        // set up the two arrays -- sorted once for speed.
        invalidFilenameChars = System.IO.Path.GetInvalidFileNameChars();
        invalidPathChars = System.IO.Path.GetInvalidPathChars();
        Array.Sort(invalidFilenameChars);
        Array.Sort(invalidPathChars);

    }

    /// <summary>
    /// Cleans a filename of invalid characters
    /// </summary>
    /// <param name="input">the string to clean</param>
    /// <param name="errorChar">the character which replaces bad characters</param>
    /// <returns></returns>
    public static string SanitizeFilename(string input, char errorChar)
    {
        return Sanitize(input, invalidFilenameChars, errorChar);
    }

    /// <summary>
    /// Cleans a path of invalid characters
    /// </summary>
    /// <param name="input">the string to clean</param>
    /// <param name="errorChar">the character which replaces bad characters</param>
    /// <returns></returns>
    public static string SanitizePath(string input, char errorChar)
    {
        return Sanitize(input, invalidPathChars, errorChar);
    }

    /// <summary>
    /// Cleans a string of invalid characters.
    /// </summary>
    /// <param name="input"></param>
    /// <param name="invalidChars"></param>
    /// <param name="errorChar"></param>
    /// <returns></returns>
    private static string Sanitize(string input, char[] invalidChars, char errorChar)
    {
        // null always sanitizes to null
        if (input == null) { return null; }
        StringBuilder result = new StringBuilder();
        foreach (var characterToTest in input)
        {
            // we binary search for the character in the invalid set. This should be lightning fast.
            if (Array.BinarySearch(invalidChars, characterToTest) >= 0)
            {
                // we found the character in the array of 
                result.Append(errorChar);
            }
            else
            {
                // the character was not found in invalid, so it is valid.
                result.Append(characterToTest);
            }
        }

        // we're done.
        return result.ToString();
    }

}

I do not understand how execlp() works in Linux

this prototype:

  int execlp(const char *file, const char *arg, ...);

Says that execlp ìs a variable argument function. It takes 2 const char *. The rest of the arguments, if any, are the additional arguments to hand over to program we want to run - also char * - all these are C strings (and the last argument must be a NULL pointer)

So, the file argument is the path name of an executable file to be executed. arg is the string we want to appear as argv[0] in the executable. By convention, argv[0] is just the file name of the executable, normally it's set to the same as file.

The ... are now the additional arguments to give to the executable.

Say you run this from a commandline/shell:

$ ls

That'd be execlp("ls", "ls", (char *)NULL); Or if you run

$ ls -l /

That'd be execlp("ls", "ls", "-l", "/", (char *)NULL);

So on to execlp("/bin/sh", ..., "ls -l /bin/??", ...);

Here you are going to the shell, /bin/sh , and you're giving the shell a command to execute. That command is "ls -l /bin/??". You can run that manually from a commandline/shell:

 $ ls -l /bin/??

Now, how do you run a shell and tell it to execute a command ? You open up the documentation/man page for your shell and read it.

What you want to run is:

$ /bin/sh -c "ls -l /bin/??"

This becomes

  execlp("/bin/sh","/bin/sh", "-c", "ls -l /bin/??", (char *)NULL);

Side note: The /bin/?? is doing pattern matching, this pattern matching is done by the shell, and it expands to all files under /bin/ with 2 characters. If you simply did

  execlp("ls","ls", "-l", "/bin/??", (char *)NULL);

Probably nothing would happen (unless there's a file actually named /bin/??) as there's no shell that interprets and expands /bin/??

Formatting "yesterday's" date in python

Use datetime.timedelta()

>>> from datetime import date, timedelta
>>> yesterday = date.today() - timedelta(days=1)
>>> yesterday.strftime('%m%d%y')
'110909'

Ring Buffer in Java

If you need

  • O(1) insertion and removal
  • O(1) indexing to interior elements
  • access from a single thread only
  • generic element type

then you can use this CircularArrayList for Java in this way (for example):

CircularArrayList<String> buf = new CircularArrayList<String>(4);

buf.add("A");
buf.add("B");
buf.add("C");
buf.add("D"); // ABCD

String pop = buf.remove(0); // A <- BCD
buf.add("E"); // BCDE

String interiorElement = buf.get(i);

All these methods run in O(1).

Calculate date from week number

using Fluent DateTime http://fluentdatetime.codeplex.com/

        var year = 2009;
        var firstDayOfYear = new DateTime(year, 1, 1);
        var firstMonday = firstDayOfYear.Next(DayOfWeek.Monday);
        var weeksDateTime = 12.Weeks().Since(firstMonday);

error LNK2001: unresolved external symbol (C++)

That means that the definition of your function is not present in your program. You forgot to add that one.cpp to your program.

What "to add" means in this case depends on your build environment and its terminology. In MSVC (since you are apparently use MSVC) you'd have to add one.cpp to the project.

In more practical terms, applicable to all typical build methodologies, when you link you program, the object file created form one.cpp is missing.

Datatable vs Dataset

There are some optimizations you can use when filling a DataTable, such as calling BeginLoadData(), inserting the data, then calling EndLoadData(). This turns off some internal behavior within the DataTable, such as index maintenance, etc. See this article for further details.

Filter element based on .data() key/value

We can make a plugin pretty easily:

$.fn.filterData = function(key, value) {
    return this.filter(function() {
        return $(this).data(key) == value;
    });
};

Usage (checking a radio button):

$('input[name=location_id]').filterData('my-data','data-val').prop('checked',true);

Confusion: @NotNull vs. @Column(nullable = false) with JPA and Hibernate

The most recent versions of hibernate JPA provider applies the bean validation constraints (JSR 303) like @NotNull to DDL by default (thanks to hibernate.validator.apply_to_ddl property defaults to true). But there is no guarantee that other JPA providers do or even have the ability to do that.

You should use bean validation annotations like @NotNull to ensure, that bean properties are set to a none-null value, when validating java beans in the JVM (this has nothing to do with database constraints, but in most situations should correspond to them).

You should additionally use the JPA annotation like @Column(nullable = false) to give the jpa provider hints to generate the right DDL for creating table columns with the database constraints you want. If you can or want to rely on a JPA provider like Hibernate, which applies the bean validation constraints to DDL by default, then you can omit them.

How can I get the current array index in a foreach loop?

You can get the index value with this

foreach ($arr as $key => $val)
{
    $key = (int) $key;
    //With the variable $key you can get access to the current array index
    //You can use $val[$key] to

}

Validate phone number with JavaScript

I would suggest using something clearer (especially thinking to who will have to maintain the code)... what about:

var formats = "(999)999-9999|999-999-9999|9999999999";
var r = RegExp("^(" +
               formats
                 .replace(/([\(\)])/g, "\\$1")
                 .replace(/9/g,"\\d") +
               ")$");

where the regexp is built from a clear template ? Adding a new one would then be a no-brainer and may be even the customer itself could be able to do that in a "options" page.

How can I make a horizontal ListView in Android?

Have you looked into the ViewFlipper component? Maybe it can help you.

http://developer.android.com/reference/android/widget/ViewFlipper.html

With this component, you can attach two or more view childs. If you add some translate animation and capture Gesture detection, you can have a nicely horizontal scroll.

how to make password textbox value visible when hover an icon

As these guys said, just change input type.
But do not forget to change type back as well.

See my simple jquery demo: http://jsfiddle.net/kPJbU/1/

HTML:

<input name="password" class="password" type="password" />
<div class="icon">icon</div>

jQuery:

$('.icon').hover(function () {
    $('.password').attr('type', 'text');
}, function () {
    $('.password').attr('type', 'password');
});

Convert string to Python class object?

This could work:

import sys

def str_to_class(classname):
    return getattr(sys.modules[__name__], classname)

How to unapply a migration in ASP.NET Core with EF Core

You can do it with:

dotnet ef migrations remove

Warning

Take care not to remove any migrations which are already applied to production databases. Not doing so will prevent you from being able to revert it, and may break the assumptions made by subsequent migrations.

How to implement the Softmax function in Python

(Well... much confusion here, both in the question and in the answers...)

To start with, the two solutions (i.e. yours and the suggested one) are not equivalent; they happen to be equivalent only for the special case of 1-D score arrays. You would have discovered it if you had tried also the 2-D score array in the Udacity quiz provided example.

Results-wise, the only actual difference between the two solutions is the axis=0 argument. To see that this is the case, let's try your solution (your_softmax) and one where the only difference is the axis argument:

import numpy as np

# your solution:
def your_softmax(x):
    """Compute softmax values for each sets of scores in x."""
    e_x = np.exp(x - np.max(x))
    return e_x / e_x.sum()

# correct solution:
def softmax(x):
    """Compute softmax values for each sets of scores in x."""
    e_x = np.exp(x - np.max(x))
    return e_x / e_x.sum(axis=0) # only difference

As I said, for a 1-D score array, the results are indeed identical:

scores = [3.0, 1.0, 0.2]
print(your_softmax(scores))
# [ 0.8360188   0.11314284  0.05083836]
print(softmax(scores))
# [ 0.8360188   0.11314284  0.05083836]
your_softmax(scores) == softmax(scores)
# array([ True,  True,  True], dtype=bool)

Nevertheless, here are the results for the 2-D score array given in the Udacity quiz as a test example:

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

print(your_softmax(scores2D))
# [[  4.89907947e-04   1.33170787e-03   3.61995731e-03   7.27087861e-02]
#  [  1.33170787e-03   9.84006416e-03   2.67480676e-02   7.27087861e-02]
#  [  3.61995731e-03   5.37249300e-01   1.97642972e-01   7.27087861e-02]]

print(softmax(scores2D))
# [[ 0.09003057  0.00242826  0.01587624  0.33333333]
#  [ 0.24472847  0.01794253  0.11731043  0.33333333]
#  [ 0.66524096  0.97962921  0.86681333  0.33333333]]

The results are different - the second one is indeed identical with the one expected in the Udacity quiz, where all columns indeed sum to 1, which is not the case with the first (wrong) result.

So, all the fuss was actually for an implementation detail - the axis argument. According to the numpy.sum documentation:

The default, axis=None, will sum all of the elements of the input array

while here we want to sum row-wise, hence axis=0. For a 1-D array, the sum of the (only) row and the sum of all the elements happen to be identical, hence your identical results in that case...

The axis issue aside, your implementation (i.e. your choice to subtract the max first) is actually better than the suggested solution! In fact, it is the recommended way of implementing the softmax function - see here for the justification (numeric stability, also pointed out by some other answers here).

TypeError: got multiple values for argument

This also happens if you forget selfdeclaration inside class methods.

Example:

class Example():
    def is_overlapping(x1, x2, y1, y2):
        # Thanks to https://stackoverflow.com/a/12888920/940592
        return max(x1, y1) <= min(x2, y2)

Fails calling it like self.is_overlapping(x1=2, x2=4, y1=3, y2=5) with:

{TypeError} is_overlapping() got multiple values for argument 'x1'

WORKS:

class Example():
    def is_overlapping(self, x1, x2, y1, y2):
        # Thanks to https://stackoverflow.com/a/12888920/940592
        return max(x1, y1) <= min(x2, y2)

Android: checkbox listener

Translation of the accepted answer by Chris into Kotlin:

val checkBox: CheckBox = findViewById(R.id.chk)
checkBox.setOnCheckedChangeListener { buttonView, isChecked ->
    // Code here 
}

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

With Nodejs, if you are using routers, make sure to add cors before the routers. Otherwise, you'll still get the cors error. Like below:

const cors = require('cors');

const userRouter = require('./routers/user');

expressApp = express();
expressApp.use(cors());
expressApp.use(express.json());
expressApp.use(userRouter);

Apache 2.4.3 (with XAMPP 1.8.1) not starting in windows 8

This problem may occur due to apache not getting required port (default is 80).

The port may be being used by other services.

For example: Skype also has default port 80.

Installing Skype and Apache both on same machine will cause conflict and hence Apache will not start.

Either, you change Skype port or change Apache port as described in following steps:

Change the ports of Apache and it will work for you. Go to httpd.conf

How to change port for Apache:

Search for:

ServerName localhost:80

Change it to:

ServerName localhost:81

Also Search For:

Listen 80

Change it to:

Listen 81

If you have created any virtual hosts, change the ports there also. Then restart your apache.

How to refer to relative paths of resources when working with a code repository

I spent a long time figuring out the answer to this, but I finally got it (and it's actually really simple):

import sys
import os
sys.path.append(os.getcwd() + '/your/subfolder/of/choice')

# now import whatever other modules you want, both the standard ones,
# as the ones supplied in your subfolders

This will append the relative path of your subfolder to the directories for python to look in It's pretty quick and dirty, but it works like a charm :)

Print raw string from variable? (not getting the answers)

Get rid of the escape characters before storing or manipulating the raw string:

You could change any backslashes of the path '\' to forward slashes '/' before storing them in a variable. The forward slashes don't need to be escaped:

>>> mypath = os.getcwd().replace('\\','/')  
>>> os.path.exists(mypath)  
True  
>>>   

function to return a string in java

In Java, a String is a reference to heap-allocated storage. Returning "ans" only returns the reference so there is no need for stack-allocated storage. In fact, there is no way in Java to allocate objects in stack storage.

I would change to this, though. You don't need "ans" at all.

return String.format("%d:%d", mins, secs);

Could not load file or assembly CrystalDecisions.ReportAppServer.ClientDoc

Regarding the 64-bit system wanting 32-bit support. I don't find it so bizarre:

Although deployed to a 64-bit system, this doesn't mean all the referenced assemblies are necessarily 64-bit Crystal Reports assemblies. Further to that, the Crystal Reports assemblies are largely just wrappers to a collection of legacy DLLs upon which they are based. Many 32-bit DLLs are required by the primarily referenced assembly. The error message "can not load the assembly" involves these DLLs as well. To see visually what those are, go to www.dependencywalker.com and run 'Depends' on the assembly in question, directly on that IIS server.

How to detect shake event with android?

Since SensorListener is deprecated so use the following code:

/* put this into your activity class */
private SensorManager mSensorManager;
private float mAccel; // acceleration apart from gravity
private float mAccelCurrent; // current acceleration including gravity
private float mAccelLast; // last acceleration including gravity

private final SensorEventListener mSensorListener = new SensorEventListener() {

  public void onSensorChanged(SensorEvent se) {
    float x = se.values[0];
    float y = se.values[1];
    float z = se.values[2];
    mAccelLast = mAccelCurrent;
    mAccelCurrent = (float) Math.sqrt((double) (x*x + y*y + z*z));
    float delta = mAccelCurrent - mAccelLast;
    mAccel = mAccel * 0.9f + delta; // perform low-cut filter
  }

  public void onAccuracyChanged(Sensor sensor, int accuracy) {
  }
};

@Override
protected void onResume() {
  super.onResume();
  mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}

@Override
protected void onPause() {
  mSensorManager.unregisterListener(mSensorListener);
  super.onPause();
}

Then:

/* do this in onCreate */
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
mAccel = 0.00f;
mAccelCurrent = SensorManager.GRAVITY_EARTH;
mAccelLast = SensorManager.GRAVITY_EARTH;

The question with full details could be found here:

Android: I want to shake it

int to unsigned int conversion

You can convert an int to an unsigned int. The conversion is valid and well-defined.

Since the value is negative, UINT_MAX + 1 is added to it so that the value is a valid unsigned quantity. (Technically, 2N is added to it, where N is the number of bits used to represent the unsigned type.)

In this case, since int on your platform has a width of 32 bits, 62 is subtracted from 232, yielding 4,294,967,234.

Spaces in URLs?

They are indeed fools. If you look at RFC 3986 Appendix A, you will see that "space" is simply not mentioned anywhere in the grammar for defining a URL. Since it's not mentioned anywhere in the grammar, the only way to encode a space is with percent-encoding (%20).

In fact, the RFC even states that spaces are delimiters and should be ignored:

In some cases, extra whitespace (spaces, line-breaks, tabs, etc.) may have to be added to break a long URI across lines. The whitespace should be ignored when the URI is extracted.

and

For robustness, software that accepts user-typed URI should attempt to recognize and strip both delimiters and embedded whitespace.

Curiously, the use of + as an encoding for space isn't mentioned in the RFC, although it is reserved as a sub-delimeter. I suspect that its use is either just convention or covered by a different RFC (possibly HTTP).

How to break out of nested loops?

Use this wise advice from LLVM team:

"Turn Predicate Loops into Predicate Functions"

See:

http://llvm.org/docs/CodingStandards.html#turn-predicate-loops-into-predicate-functions

Telling Python to save a .txt file to a certain directory on Windows and Mac

If you want to save a file to a particular DIRECTORY and FILENAME here is some simple example. It also checks to see if the directory has or has not been created.

import os.path
directory = './html/'
filename = "file.html"
file_path = os.path.join(directory, filename)
if not os.path.isdir(directory):
    os.mkdir(directory)
file = open(file_path, "w")
file.write(html)
file.close()

Hope this helps you!

A Simple AJAX with JSP example

loadXMLDoc JS function should return false, otherwise it will result in postback.

How to trigger button click in MVC 4

ASP.NET MVC doesn't work on events like ASP classic; there's no "button click event". Your controller methods correspond to requests sent to the server.

Instead, you need to wrap that form in code something like this:

@using (Html.BeginForm("SignUp", "Account", FormMethod.Post))
{
    <!-- form goes here -->

    <input type="submit" value="Sign Up" />
}

This will set up a form, and then your submit input will trigger a POST, which will hit your SignUp() method, assuming your routes are properly set up (the defaults should work).

How to parse a JSON and turn its values into an Array?

You can prefer quick-json parser to meet your requirement...

quick-json parser is very straight forward, flexible, very fast and customizable. Try this out

[quick-json parser] (https://code.google.com/p/quick-json/) - quick-json features -

  • Compliant with JSON specification (RFC4627)

  • High-Performance JSON parser

  • Supports Flexible/Configurable parsing approach

  • Configurable validation of key/value pairs of any JSON Heirarchy

  • Easy to use # Very Less foot print

  • Raises developer friendly and easy to trace exceptions

  • Pluggable Custom Validation support - Keys/Values can be validated by configuring custom validators as and when encountered

  • Validating and Non-Validating parser support

  • Support for two types of configuration (JSON/XML) for using quick-json validating parser

  • Require JDK 1.5 # No dependency on external libraries

  • Support for Json Generation through object serialization

  • Support for collection type selection during parsing process

For e.g.

JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonMap=parser.parseJson(jsonString);

Get the new record primary key ID from MySQL insert query?

You will receive these parameters on your query result:

    "fieldCount": 0,
    "affectedRows": 1,
    "insertId": 66,
    "serverStatus": 2,
    "warningCount": 1,
    "message": "",
    "protocol41": true,
    "changedRows": 0

The insertId is exactly what you need.

(NodeJS-mySql)

Combine Multiple child rows into one row MYSQL

If you know you're going to have a limited number of max options then I would try this (example for max of 4 options per order):

Select OI.ID, OI.Item_Name, OO1.Value, OO2.Value, OO3.Value, OO4.Value

FROM Ordered_Items OI
    LEFT JOIN Ordered_Options OO1 ON OO1.Ordered_Item_ID = OI.ID
    LEFT JOIN Ordered_Options OO2 ON OO2.Ordered_Item_ID = OI.ID AND OO2.ID != OO1.ID
    LEFT JOIN Ordered_Options OO3 ON OO3.Ordered_Item_ID = OI.ID AND OO3.ID != OO1.ID AND OO3.ID != OO2.ID
    LEFT JOIN Ordered_Options OO4 ON OO4.Ordered_Item_ID = OI.ID AND OO4.ID != OO1.ID AND OO4.ID != OO2.ID AND OO4.ID != OO3.ID

GROUP BY OI.ID, OI.Item_Name

The group by condition gets rid of all of the duplicates that you would otherwise get. I've just implemented something similar on a site I'm working on where I knew I'd always have 1 or 2 matched in my child table, and I wanted to make sure I only had 1 row for each parent item.

apache redirect from non www to www

Do not always use Redirect permanent (or why it may cause issues in future)

If there is a chance that you will add subdomains later, do not use redirect permanent.

Because if a client has used a subdomain that wasn't registred as VirtualHost he may also never reach this subdomain even when it is registred later.

redirect permanent sends an HTTP 301 Moved Permanently to the client (browser) and a lot of them cache this response for ever (until cache is cleared [manually]). So using that subdomain will always autoredirect to www.*** without requesting the server again.

see How long do browsers cache HTTP 301s?

So just use Redirect

<VirtualHost *:80>
  ServerName example.com

  Redirect / http://www.example.com/
</VirtualHost>

Apache.org - When not to use mod_rewrite

Apache.org - Canonical Hostnames

GetElementByID - Multiple IDs

document.getElementById() only supports one name at a time and only returns a single node not an array of nodes. You have several different options:

  1. You could implement your own function that takes multiple ids and returns multiple elements.
  2. You could use document.querySelectorAll() that allows you to specify multiple ids in a CSS selector string .
  3. You could put a common class names on all those nodes and use document.getElementsByClassName() with a single class name.

Examples of each option:

doStuff(document.querySelectorAll("#myCircle1, #myCircle2, #myCircle3, #myCircle4"));

or:

// put a common class on each object
doStuff(document.getElementsByClassName("circles"));

or:

function getElementsById(ids) {
    var idList = ids.split(" ");
    var results = [], item;
    for (var i = 0; i < idList.length; i++) {
        item = document.getElementById(idList[i]);
        if (item) {
            results.push(item);
        }
    }
    return(results);
}

doStuff(getElementsById("myCircle1 myCircle2 myCircle3 myCircle4"));

Unsigned keyword in C++

From the link above:

Several of these types can be modified using the keywords signed, unsigned, short, and long. When one of these type modifiers is used by itself, a data type of int is assumed

This means that you can assume the author is using ints.

onActivityResult is not being called in Fragment

Kotlin version for those who use Android Navigation Component inspired in Mohit Mehta's answer

 override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    supportFragmentManager.primaryNavigationFragment?.childFragmentManager?.fragments?.forEach { fragment ->
        fragment.onActivityResult(requestCode, resultCode, data)
    }
}

Eclipse: Error ".. overlaps the location of another project.." when trying to create new project

Go to the actual FILE menu and create a new general project.

If the project type isn't recognized, preventing one of these import methods from working, then try this. Once you add the generic project, you can then add support for whatever language you require.

Cassandra cqlsh - connection refused

Try to change the rpc_address to point to the node's IP instead of 0.0.0.0 and specify the IP while connecting to the cqlsh, as if the IP is 10.0.1.34 and the rpc_port left to the default value 9160 then the following should work:

cqlsh 10.0.1.34 9160 

Or:

cqlsh 10.0.1.34 

Also make sure that start_rpc is set to true in /etc/cassandra/cassandra.yaml configuration file.

How to access the php.ini from my CPanel?

You cant do it on shared hosting , Add ticket to support of hosting for same ( otherwise you can look for dedicated server where you can manage anything )

"string could not resolved" error in Eclipse for C++ (Eclipse can't resolve standard library)

I had the same problem. Change the CurrentBuilder in Properties/C/C++ Build/ToolChainEditor to another value and apply it. Then again change it the original value. It works.

How do you create an asynchronous method in C#?

If you didn't want to use async/await inside your method, but still "decorate" it so as to be able to use the await keyword from outside, TaskCompletionSource.cs:

public static Task<T> RunAsync<T>(Func<T> function)
{ 
    if (function == null) throw new ArgumentNullException(“function”); 
    var tcs = new TaskCompletionSource<T>(); 
    ThreadPool.QueueUserWorkItem(_ =>          
    { 
        try 
        {  
           T result = function(); 
           tcs.SetResult(result);  
        } 
        catch(Exception exc) { tcs.SetException(exc); } 
   }); 
   return tcs.Task; 
}

From here and here

To support such a paradigm with Tasks, we need a way to retain the Task façade and the ability to refer to an arbitrary asynchronous operation as a Task, but to control the lifetime of that Task according to the rules of the underlying infrastructure that’s providing the asynchrony, and to do so in a manner that doesn’t cost significantly. This is the purpose of TaskCompletionSource.

I saw it's also used in the .NET source, e.g. WebClient.cs:

    [HostProtection(ExternalThreading = true)]
    [ComVisible(false)]
    public Task<string> UploadStringTaskAsync(Uri address, string method, string data)
    {
        // Create the task to be returned
        var tcs = new TaskCompletionSource<string>(address);

        // Setup the callback event handler
        UploadStringCompletedEventHandler handler = null;
        handler = (sender, e) => HandleCompletion(tcs, e, (args) => args.Result, handler, (webClient, completion) => webClient.UploadStringCompleted -= completion);
        this.UploadStringCompleted += handler;

        // Start the async operation.
        try { this.UploadStringAsync(address, method, data, tcs); }
        catch
        {
            this.UploadStringCompleted -= handler;
            throw;
        }

        // Return the task that represents the async operation
        return tcs.Task;
    }

Finally, I also found the following useful:

I get asked this question all the time. The implication is that there must be some thread somewhere that’s blocking on the I/O call to the external resource. So, asynchronous code frees up the request thread, but only at the expense of another thread elsewhere in the system, right? No, not at all.

To understand why asynchronous requests scale, I’ll trace a (simplified) example of an asynchronous I/O call. Let’s say a request needs to write to a file. The request thread calls the asynchronous write method. WriteAsync is implemented by the Base Class Library (BCL), and uses completion ports for its asynchronous I/O. So, the WriteAsync call is passed down to the OS as an asynchronous file write. The OS then communicates with the driver stack, passing along the data to write in an I/O request packet (IRP).

This is where things get interesting: If a device driver can’t handle an IRP immediately, it must handle it asynchronously. So, the driver tells the disk to start writing and returns a “pending” response to the OS. The OS passes that “pending” response to the BCL, and the BCL returns an incomplete task to the request-handling code. The request-handling code awaits the task, which returns an incomplete task from that method and so on. Finally, the request-handling code ends up returning an incomplete task to ASP.NET, and the request thread is freed to return to the thread pool.

Introduction to Async/Await on ASP.NET

If the target is to improve scalability (rather than responsiveness), it all relies on the existence of an external I/O that provides the opportunity to do that.

How to display items side-by-side without using tables?

What about display:inline?

<html>
      <img src='#' style='display:inline;'/>
      <p style='display:inline;'> Some text </p>
</html>

How to change the Text color of Menu item in Android?

Simply just go to Values - styles and inside styles and type your color

Alert after page load

$(window).on('load', function () {
 alert('Alert after page load');
        }
    });

No connection could be made because the target machine actively refused it (PHP / WAMP)

following steps worked for me.

  1. Go to wamp\apps\phpmyadmin
  2. search config.inc.php
  3. search 127.0.0.1 and replace with "localhost".

Why do access tokens expire?

This is very much implementation specific, but the general idea is to allow providers to issue short term access tokens with long term refresh tokens. Why?

  • Many providers support bearer tokens which are very weak security-wise. By making them short-lived and requiring refresh, they limit the time an attacker can abuse a stolen token.
  • Large scale deployment don't want to perform a database lookup every API call, so instead they issue self-encoded access token which can be verified by decryption. However, this also means there is no way to revoke these tokens so they are issued for a short time and must be refreshed.
  • The refresh token requires client authentication which makes it stronger. Unlike the above access tokens, it is usually implemented with a database lookup.

How to change the blue highlight color of a UITableViewCell?

1- Add a view to the content view of your cell.
2- Right click your cell.
3- Make the added view as "selectedBackgroundView" enter image description here

Is it possible to declare two variables of different types in a for loop?

You can't declare multiple types in the initialization, but you can assign to multiple types E.G.

{
   int i;
   char x;
   for(i = 0, x = 'p'; ...){
      ...
   }
}

Just declare them in their own scope.

How to convert a Datetime string to a current culture datetime string

This works for me:

string myTime = DateTime.Parse("12/1/2011")
                        .ToString(CultureInfo.GetCultureInfo("en-GB").DateTimeFormat.ShortDatePattern);

About "*.d.ts" in TypeScript

d stands for Declaration Files:

When a TypeScript script gets compiled there is an option to generate a declaration file (with the extension .d.ts) that functions as an interface to the components in the compiled JavaScript. In the process the compiler strips away all function and method bodies and preserves only the signatures of the types that are exported. The resulting declaration file can then be used to describe the exported virtual TypeScript types of a JavaScript library or module when a third-party developer consumes it from TypeScript.

The concept of declaration files is analogous to the concept of header file found in C/C++.

declare module arithmetics {
    add(left: number, right: number): number;
    subtract(left: number, right: number): number;
    multiply(left: number, right: number): number;
    divide(left: number, right: number): number;
}

Type declaration files can be written by hand for existing JavaScript libraries, as has been done for jQuery and Node.js.

Large collections of declaration files for popular JavaScript libraries are hosted on GitHub in DefinitelyTyped and the Typings Registry. A command-line utility called typings is provided to help search and install declaration files from the repositories.

Align an element to bottom with flexbox

When setting your display to flex, you could simply use the flex property to mark which content can grow and which content cannot.

Flex property

_x000D_
_x000D_
div.content {_x000D_
 height: 300px;_x000D_
 display: flex;_x000D_
 flex-direction: column;_x000D_
}_x000D_
_x000D_
div.up {_x000D_
  flex: 1;_x000D_
}_x000D_
_x000D_
div.down {_x000D_
  flex: none;_x000D_
}
_x000D_
<div class="content">_x000D_
  <div class="up">_x000D_
    <h1>heading 1</h1>_x000D_
    <h2>heading 2</h2>_x000D_
    <p>Some more or less text</p>_x000D_
  </div>_x000D_
_x000D_
  <div class="down">_x000D_
    <a href="/" class="button">Click me</a>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Superscript in markdown (Github flavored)?

Comments about previous answers

The universal solution is using the HTML tag <sup>, as suggested in the main answer.
However, the idea behind Markdown is precisely to avoid the use of such tags:
The document should look nice as plain text, not only when rendered.

Another answer proposes using Unicode characters, which makes the document look nice as a plain text document but could reduce compatibility.

Finally, I would like to remember the simplest solution for some documents: the character ^.
Some Markdown implementation (e.g. MacDown in macOS) interprets the caret as an instruction for superscript.

Ex.
Sin^2 + Cos^2 = 1
Clearly, Stack Overflow does not interpret the caret as a superscript instruction. However, the text is comprehensible, and this is what really matters when using Markdown.

How to make primary key as autoincrement for Room Persistence lib

You can add @PrimaryKey(autoGenerate = true) like this:

@Entity
data class Food(
        var foodName: String, 
        var foodDesc: String, 
        var protein: Double, 
        var carbs: Double, 
        var fat: Double
){
    @PrimaryKey(autoGenerate = true)
    var foodId: Int = 0 // or foodId: Int? = null
    var calories: Double = 0.toDouble()
}

What's the difference between session.persist() and session.save() in Hibernate?

This question has some good answers about different persistence methods in Hibernate. To answer your question directly, with save() the insert statement is executed immediately regardless of transaction state. It returns the inserted key so you can do something like this:

long newKey = session.save(myObj);

So use save() if you need an identifier assigned to the persistent instance immediately.

With persist(), the insert statement is executed in a transaction, not necessarily immediately. This is preferable in most cases.

Use persist() if you don't need the insert to happen out-of-sequence with the transaction and you don't need the inserted key returned.

How can I stream webcam video with C#?

If you want a "capture/streamer in a box" component, there are several out there as others have mentioned.

If you want to get down to the low-level control over it all, you'll need to use DirectShow as thealliedhacker points out. The best way to use DirectShow in C# is through the DirectShow.Net library - it wraps all of the DirectShow COM APIs and includes many useful shortcut functions for you.

In addition to capturing and streaming, you can also do recording, audio and video format conversions, audio and video live filters, and a whole lot of stuff.

Microsoft claims DirectShow is going away, but they have yet to release a new library or API that does everything that DirectShow provides. I suspect many of the latest things they have released are still DirectShow under the hood. Because of its status at Microsoft, there aren't a whole lot of books or references on it other than MSDN and what you can find on forums. Last year when we started a project using it, the best book on the subject - Programming Microsoft DirectShow - was out of print and going for around $350 for a used copy!

Return None if Dictionary key is not available

A one line solution would be:

item['key'] if 'key' in item else None

This is useful when trying to add dictionary values to a new list and want to provide a default:

eg.

row = [item['key'] if 'key' in item else 'default_value']

How to compare two vectors for equality element by element in C++?

Your code (vector1 == vector2) is correct C++ syntax. There is an == operator for vectors.

If you want to compare short vector with a portion of a longer vector, you can use theequal() operator for vectors. (documentation here)

Here's an example:

using namespace std;

if( equal(vector1.begin(), vector1.end(), vector2.begin()) )
    DoSomething();

How to import cv2 in python3?

Make a virtual enviroment using python3

virtualenv env_name --python="python3"

and run the following command

pip3 install opencv-python

What does 'foo' really mean?

See: RFC 3092: Etymology of "Foo", D. Eastlake 3rd et al.

Quoting only the relevant definitions from that RFC for brevity:

  1. Used very generally as a sample name for absolutely anything, esp. programs and files (esp. scratch files).

  2. First on the standard list of metasyntactic variables used in syntax examples (bar, baz, qux, quux, corge, grault, garply, waldo, fred, plugh, xyzzy, thud). [JARGON]

How can I make a jQuery UI 'draggable()' div draggable for touchscreen?

Caution: This answer was written in 2010 and technology moves fast. For a more recent solution, see @ctrl-alt-dileep's answer below.


Depending on your needs, you may wish to try the jQuery touch plugin; you can try an example here. It works fine to drag on my iPhone, whereas jQuery UI Draggable doesn't.

Alternatively, you can try this plugin, though that might require you to actually write your own draggable function.

As a sidenote: Believe it or not, we're hearing increasing buzz about how touch devices such as the iPad and iPhone is causing problems both for websites using :hover/onmouseover functions and draggable content.

If you're interested in the underlying solution for this, it's to use three new JavaScript events; ontouchstart, ontouchmove and ontouchend. Apple actually has written an article about their use, which you can find here. A simplified example can be found here. These events are used in both of the plugins I linked to.

How to read file contents into a variable in a batch file?

You can read multiple variables from file like this:

for /f "delims== tokens=1,2" %%G in (param.txt) do set %%G=%%H

where param.txt:

PARAM1=value1
PARAM2=value2
...

What does the ELIFECYCLE Node.js error mean?

When running Webpack build I was getting similar error because node doesn't understand async await keywords on older versions. I added webpack babel-plugin-transform-async-to-generator and it was solved. This replaces them with promises.

Reading a text file using OpenFileDialog in windows forms

for this approach, you will need to add system.IO to your references by adding the next line of code below the other references near the top of the c# file(where the other using ****.** stand).

using System.IO;

this next code contains 2 methods of reading the text, the first will read single lines and stores them in a string variable, the second one reads the whole text and saves it in a string variable(including "\n" (enters))

both should be quite easy to understand and use.


    string pathToFile = "";//to save the location of the selected object
    private void openToolStripMenuItem_Click(object sender, EventArgs e)
    {
        OpenFileDialog theDialog = new OpenFileDialog();
        theDialog.Title = "Open Text File";
        theDialog.Filter = "TXT files|*.txt";
        theDialog.InitialDirectory = @"C:\";
        if (theDialog.ShowDialog() == DialogResult.OK)
        {
            MessageBox.Show(theDialog.FileName.ToString());
            pathToFile = theDialog.FileName;//doesn't need .tostring because .filename returns a string// saves the location of the selected object

        }

        if (File.Exists(pathToFile))// only executes if the file at pathtofile exists//you need to add the using System.IO reference at the top of te code to use this
        {
            //method1
            string firstLine = File.ReadAllLines(pathToFile).Skip(0).Take(1).First();//selects first line of the file
            string secondLine = File.ReadAllLines(pathToFile).Skip(1).Take(1).First();

            //method2
            string text = "";
            using(StreamReader sr =new StreamReader(pathToFile))
            {
                text = sr.ReadToEnd();//all text wil be saved in text enters are also saved
            }
        }
    }

To split the text you can use .Split(" ") and use a loop to put the name back into one string. if you don't want to use .Split() then you could also use foreach and ad an if statement to split it where needed.


to add the data to your class you can use the constructor to add the data like:

  public Employee(int EMPLOYEENUM, string NAME, string ADRESS, double WAGE, double HOURS)
        {
            EmployeeNum = EMPLOYEENUM;
            Name = NAME;
            Address = ADRESS;
            Wage = WAGE;
            Hours = HOURS;
        }

or you can add it using the set by typing .variablename after the name of the instance(if they are public and have a set this will work). to read the data you can use the get by typing .variablename after the name of the instance(if they are public and have a get this will work).

How to start nginx via different port(other than 80)

You have to go to the /etc/nginx/sites-enabled/ and if this is the default configuration, then there should be a file by name: default.

Edit that file by defining your desired port; in the snippet below, we are serving the Nginx instance on port 81.

server {
    listen 81;
}

To start the server, run the command line below;

sudo service nginx start

You may now access your application on port 81 (for localhost, http://localhost:81).

Groovy executing shell commands

I find this more idiomatic:

def proc = "ls foo.txt doesnotexist.txt".execute()
assert proc.in.text == "foo.txt\n"
assert proc.err.text == "ls: doesnotexist.txt: No such file or directory\n"

As another post mentions, these are blocking calls, but since we want to work with the output, this may be necessary.

Most efficient T-SQL way to pad a varchar on the left to a certain length?

I know this was originally asked back in 2008, but there are some new functions that were introduced with SQL Server 2012. The FORMAT function simplifies padding left with zeros nicely. It will also perform the conversion for you:

declare @n as int = 2
select FORMAT(@n, 'd10') as padWithZeros

Update:

I wanted to test the actual efficiency of the FORMAT function myself. I was quite surprised to find the efficiency was not very good compared to the original answer from AlexCuse. Although I find the FORMAT function cleaner, it is not very efficient in terms of execution time. The Tally table I used has 64,000 records. Kudos to Martin Smith for pointing out execution time efficiency.

SET STATISTICS TIME ON
select FORMAT(N, 'd10') as padWithZeros from Tally
SET STATISTICS TIME OFF

SQL Server Execution Times: CPU time = 2157 ms, elapsed time = 2696 ms.

SET STATISTICS TIME ON
select right('0000000000'+ rtrim(cast(N as varchar(5))), 10) from Tally
SET STATISTICS TIME OFF

SQL Server Execution Times:

CPU time = 31 ms, elapsed time = 235 ms.

What does "exited with code 9009" mean during this build?

If the script actually does what it needs to do and it's just Visual Studio bugging you about the error you could just add:

exit 0

to the end of you script.

Dart: mapping a list (list.map)

Yes, You can do it this way too

 List<String> listTab = new List();
 map.forEach((key, val) {
  listTab.add(val);
 });

 //your widget//
 bottom: new TabBar(
  controller: _controller,
  isScrollable: true,
  tabs: listTab
  ,
),

Trying to Validate URL Using JavaScript

Someone mentioned the Jquery Validation plugin, seems overkill if you just want to validate the url, here is the line of regex from the plugin:

return this.optional(element) || /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);

Here is where they got it from: http://projects.scottsplayground.com/iri/

Pointed out by @nhahtdh This has been updated to:

        // Copyright (c) 2010-2013 Diego Perini, MIT licensed
        // https://gist.github.com/dperini/729294
        // see also https://mathiasbynens.be/demo/url-regex
        // modified to allow protocol-relative URLs
        return this.optional( element ) || /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[/?#]\S*)?$/i.test( value );

source: https://github.com/jzaefferer/jquery-validation/blob/c1db10a34c0847c28a5bd30e3ee1117e137ca834/src/core.js#L1349

Difference between a script and a program?

According to my perspective, the main difference between script and program:

Scripts can be used with the other technologies. Example: PHP scripts, Javascripts, etc. can be used within HTML.

Programs are stand-alone chunks of code that can never be embedded into the other technologies.

If I am wrong at any place please correct me.I will admire your correction.

What is the format specifier for unsigned short int?

Here is a good table for printf specifiers. So it should be %hu for unsigned short int.

And link to Wikipedia "C data types" too.

How to get Url Hash (#) from server side

Probably the only choice is to read it on the client side and transfer it manually to the server (GET/POST/AJAX). Regards Artur

You may see also how to play with back button and browser history at Malcan

how to set radio button checked in edit mode in MVC razor view

Here is the code for get value of checked radio button and set radio button checked according to it's value in edit form:

Controller:

[HttpPost]
public ActionResult Create(FormCollection collection)
{
    try
    {
        CommonServiceReference.tbl_user user = new CommonServiceReference.tbl_user();
        user.user_gender = collection["rdbtnGender"];
        return RedirectToAction("Index");
    }
    catch(Exception e)
    {
        throw e;
    }
}

public ActionResult Edit(int id)
{
    CommonServiceReference.ViewUserGroup user = clientObj.getUserById(id);
    ViewBag.UserObj = user;
    return View();
}

VIEW:

Create:

<input type="radio" id="rdbtnGender1" name="rdbtnGender" value="Male" required>
<label for="rdbtnGender1">MALE</label>
<input type="radio" id="rdbtnGender2" name="rdbtnGender" value="Female" required>
<label  for="rdbtnGender2">FEMALE</label>

Edit:

<input type="radio" id="rdbtnGender1" name="rdbtnGender" value="Male" @(ViewBag.UserObj.user_gender == "Male" ? "checked='true'" : "") required>
<label for="rdbtnGender1">MALE</label>

<input type="radio" id="rdbtnGender2" name="rdbtnGender" value="Female" @(ViewBag.UserObj.user_gender == "Female" ? "checked='true'" : "") required>
<label for="rdbtnGender2">FEMALE</label>

How to know what the 'errno' means?

Here is the documentation. That should tell you what it means and what to do with them. You should avoid using the numeric value and use the constants listed there as well, as the number may change between different systems.

How to match "any character" in regular expression?

There are lots of sophisticated regex testing and development tools, but if you just want a simple test harness in Java, here's one for you to play with:

    String[] tests = {
        "AAA123",
        "ABCDEFGH123",
        "XXXX123",
        "XYZ123ABC",
        "123123",
        "X123",
        "123",
    };
    for (String test : tests) {
        System.out.println(test + " " +test.matches(".+123"));
    }

Now you can easily add new testcases and try new patterns. Have fun exploring regex.

See also

Using Node.JS, how do I read a JSON file into (server) memory?

Asynchronous is there for a reason! Throws stone at @mihai

Otherwise, here is the code he used with the asynchronous version:

// Declare variables
var fs = require('fs'),
    obj

// Read the file and send to the callback
fs.readFile('path/to/file', handleFile)

// Write the callback function
function handleFile(err, data) {
    if (err) throw err
    obj = JSON.parse(data)
    // You can now play with your datas
}

Why is exception.printStackTrace() considered bad practice?

printStackTrace() prints to a console. In production settings, nobody is ever watching at that. Suraj is correct, should pass this information to a logger.

Make a negative number positive

Use the abs function:

int sum=0;
for(Integer i : container)
  sum+=Math.abs(i);

Command to get time in milliseconds

Perl can be used for this, even on exotic platforms like AIX. Example:

#!/usr/bin/perl -w

use strict;
use Time::HiRes qw(gettimeofday);

my ($t_sec, $usec) = gettimeofday ();
my $msec= int ($usec/1000);

my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
    localtime ($t_sec);

printf "%04d-%02d-%02d %02d:%02d:%02d %03d\n",
    1900+$year, 1+$mon, $mday, $hour, $min, $sec, $msec;

MongoDb shuts down with Code 100

In MacOS:-

If you forgot to give the path of the previously created database while running the mongo server, the above error will appear.

sudo ./mongod --dbpath ../../mongo-data/

Reference

Note :- ./mongod && ../../mongo-data is relative path. So you can avoid it by configuration in environment variable

Reference

IIS7 Cache-Control

That's not true Jeff.

You simply have to select a folder within your IIS 7 Manager UI (e.g. Images or event the Default Web Application folder) and then click on "HTTP Response Headers". Then you have to click on "Set Common Header.." in the right pane and select the "Expire Web content". There you can easily configure a max-age of 24 hours by choosing "After:", entering "24" in the Textbox and choose "Hours" in the combobox.

Your first paragraph regarding the web.config entry is right. I'd add the cacheControlCustom-attribute to set the cache control header to "public" or whatever is needed in that case.

You can, of course, achieve the same by providing web.config entries (or files) as needed.

Edit: removed a confusing sentence :)

Dropdownlist width in IE

check this out.. it's not perfect but it works and it's for IE only and doesn't affect FF. I used the regular javascript for onmousedown to establish IE only fix.. but the msie from jquery could be used as well in the onmousedown.. the main idea is the "onchange" and on blur to have the select box return to normal... decide you're own width for those. I needed 35%.

onmousedown="javascript:if(navigator.appName=='Microsoft Internet Explorer'){this.style.width='auto'}" 
onchange="this.style.width='35%'"
onblur="this.style.width='35%'"

How can I loop through a List<T> and grab each item?

The low level iterator manipulate code:

List<Money> myMoney = new List<Money>
{
    new Money{amount = 10, type = "US"},
    new Money{amount = 20, type = "US"}
};
using (var enumerator = myMoney.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        var element = enumerator.Current;
        Console.WriteLine(element.amount);
    }
}

Laravel: How do I parse this json data in view blade?

It's pretty easy. First of all send to the view decoded variable (see Laravel Views):

view('your-view')->with('leads', json_decode($leads, true));

Then just use common blade constructions (see Laravel Templating):

@foreach($leads['member'] as $member)
    Member ID: {{ $member['id'] }}
    Firstname: {{ $member['firstName'] }}
    Lastname: {{ $member['lastName'] }}
    Phone: {{ $member['phoneNumber'] }}

    Owner ID: {{ $member['owner']['id'] }}
    Firstname: {{ $member['owner']['firstName'] }} 
    Lastname: {{ $member['owner']['lastName'] }}
@endforeach

How to save a spark DataFrame as csv on disk?

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

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

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

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

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

My code:

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

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

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

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

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

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

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

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

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

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

    headerRdd union rowsRdd
  }

}

php.ini: which one?

It really depends on the situation, for me its in fpm as I'm using PHP5-FPM. A solution to your problem could be a universal php.ini and then using a symbolic link created like:

ln -s /etc/php5/php.ini php.ini

Then any modifications you make will be in one general .ini file. This is probably not really the best solution though, you might want to look into modifying some configuration so that you literally use one file, on one location. Not multiple locations hacked together.

Change Background color (css property) using Jquery

Try below jQuery snippet, you can change color :

<script type="text/javascript">
    $(document).ready(function(){
        $("#co").click(function() {
            $("body").css("background-color", "yellow");
        });
    });
</script>

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    $("#co").click(function() {_x000D_
        $("body").css("background-color", "yellow");_x000D_
    });_x000D_
});
_x000D_
body {_x000D_
    background-color:red;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="co" click="change()">hello</div>
_x000D_
_x000D_
_x000D_

PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

In my case I was committing transaction when persist method was used. On changing persist to save method , it got resolved.

Anaconda-Navigator - Ubuntu16.04

add anaconda installation path to .bashrc

export PATH="$PATH:/home/username/anaconda3/bin"

load in terminal

$ source ~/.bashrc

run from terminal

$ anaconda-navigator

Float vs Decimal in ActiveRecord

I remember my CompSci professor saying never to use floats for currency.

The reason for that is how the IEEE specification defines floats in binary format. Basically, it stores sign, fraction and exponent to represent a Float. It's like a scientific notation for binary (something like +1.43*10^2). Because of that, it is impossible to store fractions and decimals in Float exactly.

That's why there is a Decimal format. If you do this:

irb:001:0> "%.47f" % (1.0/10)
=> "0.10000000000000000555111512312578270211815834045" # not "0.1"!

whereas if you just do

irb:002:0> (1.0/10).to_s
=> "0.1" # the interprer rounds the number for you

So if you are dealing with small fractions, like compounding interests, or maybe even geolocation, I would highly recommend Decimal format, since in decimal format 1.0/10 is exactly 0.1.

However, it should be noted that despite being less accurate, floats are processed faster. Here's a benchmark:

require "benchmark" 
require "bigdecimal" 

d = BigDecimal.new(3) 
f = Float(3)

time_decimal = Benchmark.measure{ (1..10000000).each { |i| d * d } } 
time_float = Benchmark.measure{ (1..10000000).each { |i| f * f } }

puts time_decimal 
#=> 6.770960 seconds 
puts time_float 
#=> 0.988070 seconds

Answer

Use float when you don't care about precision too much. For example, some scientific simulations and calculations only need up to 3 or 4 significant digits. This is useful in trading off accuracy for speed. Since they don't need precision as much as speed, they would use float.

Use decimal if you are dealing with numbers that need to be precise and sum up to correct number (like compounding interests and money-related things). Remember: if you need precision, then you should always use decimal.

Circle-Rectangle collision detection (intersection)

There are only two cases when the circle intersects with the rectangle:

  • Either the circle's centre lies inside the rectangle, or
  • One of the edges of the rectangle has a point in the circle.

Note that this does not require the rectangle to be axis-parallel.

Some different ways a circle and rectangle may intersect

(One way to see this: if none of the edges has a point in the circle (if all the edges are completely "outside" the circle), then the only way the circle can still intersect the polygon is if it lies completely inside the polygon.)

With that insight, something like the following will work, where the circle has centre P and radius R, and the rectangle has vertices A, B, C, D in that order (not complete code):

def intersect(Circle(P, R), Rectangle(A, B, C, D)):
    S = Circle(P, R)
    return (pointInRectangle(P, Rectangle(A, B, C, D)) or
            intersectCircle(S, (A, B)) or
            intersectCircle(S, (B, C)) or
            intersectCircle(S, (C, D)) or
            intersectCircle(S, (D, A)))

If you're writing any geometry you probably have the above functions in your library already. Otherwise, pointInRectangle() can be implemented in several ways; any of the general point in polygon methods will work, but for a rectangle you can just check whether this works:

0 = AP·AB = AB·AB and 0 = AP·AD = AD·AD

And intersectCircle() is easy to implement too: one way would be to check if the foot of the perpendicular from P to the line is close enough and between the endpoints, and check the endpoints otherwise.

The cool thing is that the same idea works not just for rectangles but for the intersection of a circle with any simple polygon — doesn't even have to be convex!

add an element to int [] array in java

import java.util.Arrays;

public class NumberArray {     

    public static void main(String []args){
        int[] series = {4,2};
        int[] newSeries = putNumberInSeries(1,series);
        System.out.println(series==newSeries);//return false. you won't get the same int[] object. But functionality achieved.
    }
    private static int[] putNumberInSeries(int i, int[] series) {
        int[] localSeries = Arrays.copyOf(series, series.length+1);
        localSeries[series.length] = i;
        System.out.println(localSeries);
        return localSeries;
    }
}

How to convert a time string to seconds?

import time
from datetime import datetime

t1 = datetime.now().replace(microsecond=0)
time.sleep(3)
now = datetime.now().replace(microsecond=0)
print((now - t1).total_seconds())

result: 3.0

Android: adb pull file on desktop

Use a fully-qualified path to the desktop (e.g., /home/mmurphy/Desktop).

Example: adb pull sdcard/log.txt /home/mmurphy/Desktop

Convert a Unicode string to a string in Python (containing extra symbols)

>>> text=u'abcd'
>>> str(text)
'abcd'

If the string only contains ascii characters.

How do I round to the nearest 0.5?

This answer is taken from Rosdi Kasim's comment in the answer that John Rasch provided.

John's answer works but does have an overflow possibility.

Here is my version of Rosdi's code:

I also put it in an extension to make it easy to use. The extension is not necessary and could be used as a function without issue.

<Extension>
Public Function ToHalf(value As Decimal) As Decimal
    Dim integerPart = Decimal.Truncate(value)
    Dim fractionPart = value - Decimal.Truncate(integerPart)
    Dim roundedFractionPart = Math.Round(fractionPart * 2, MidpointRounding.AwayFromZero) / 2
    Dim newValue = integerPart + roundedFractionPart
    Return newValue
End Function

The usage would then be:

Dim newValue = CDec(1.26).ToHalf

This would return 1.5

Return value of x = os.system(..)

os.system() returns the (encoded) process exit value. 0 means success:

On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent.

The output you see is written to stdout, so your console or terminal, and not returned to the Python caller.

If you wanted to capture stdout, use subprocess.check_output() instead:

x = subprocess.check_output(['whoami'])

ListBox vs. ListView - how to choose for data binding

A ListView is a specialized ListBox (that is, it inherits from ListBox). It allows you to specify different views rather than a straight list. You can either roll your own view, or use GridView (think explorer-like "details view"). It's basically the multi-column listbox, the cousin of windows form's listview.

If you don't need the additional capabilities of ListView, you can certainly use ListBox if you're simply showing a list of items (Even if the template is complex).

JavaScript require() on client side

Simply use Browserify, what is something like a compiler that process your files before it go into production and packs the file in bundles.

Think you have a main.js file that require the files of your project, when you run browserify in it, it simply process all and creates a bundle with all your files, allowing the use of the require calls synchronously in the browser without HTTP requests and with very little overhead for the performance and for the size of the bundle, for example.

See the link for more info: http://browserify.org/

How do I implement JQuery.noConflict() ?

jQuery.noConflict will reset the $ variable so it's no longer an alias of jQuery. Aside from just calling it once, there's not much else you really need to do. Though, you can create your own alias with the return value, if you'd like:

var jq = jQuery.noConflict();

And, generally, you want to do this right after including jQuery and any plugins:

<script type="text/javascript" src="/path/to/jquery.js"></script>
<script type="text/javascript" src="/path/to/jquery-plugin.js"></script>
<script type="text/javascript">
  jQuery.noConflict();
  // Code that uses other library's $ can follow here.
</script>
<script type="text/javascript" src="/path/to/prototype.js"></script>

You can also go one step further and free up jQuery with noConflict(true). Though, if you take this route, you'll definitely want an alias as neither $ nor jQuery will probably be what you want:

var jq = jQuery.noConflict(true);

I think this last option is mostly used for mixing versions of jQuery, particularly for out-dated plugins when you want to update jQuery itself:

<script type="text/javascript" src="jquery-1.4.4.js"></script>
<script type="text/javascript" src="jquery-older-plugin.js"></script>
<script type="text/javascript">
    var jq144 = jQuery.noConflict(true);
</script>
<script type="text/javascript" src="jquery-1.6.4.js"></script>
<script type="text/javascript" src="jquery-newer-plugin.js"></script>

Is there a method to generate a UUID with go language

u[8] = (u[8] | 0x80) & 0xBF // what's the purpose ?
u[6] = (u[6] | 0x40) & 0x4F // what's the purpose ?

These lines clamp the values of byte 6 and 8 to a specific range. rand.Read returns random bytes in the range 0-255, which are not all valid values for a UUID. As far as I can tell, this should be done for all the values in the slice though.

If you are on linux, you can alternatively call /usr/bin/uuidgen.

package main

import (
    "fmt"
    "log"
    "os/exec"
)

func main() {
    out, err := exec.Command("uuidgen").Output()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%s", out)
}

Which yields:

$ go run uuid.go 
dc9076e9-2fda-4019-bd2c-900a8284b9c4

CSS force image resize and keep aspect ratio

I've struggled with this problem quite hard, and eventually arrived at this simple solution:

object-fit: cover;
width: 100%;
height: 250px;

You can adjust the width and height to fit your needs, and the object-fit property will do the cropping for you.

More information about the possible values for the object-fit property and a compatibility table are available here: https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

Cheers.

Fastest way to reset every value of std::vector<int> to 0

I had the same question but about rather short vector<bool> (afaik the standard allows to implement it internally differently than just a continuous array of boolean elements). Hence I repeated the slightly modified tests by Fabio Fracassi. The results are as follows (times, in seconds):

            -O0       -O3
         --------  --------
memset     0.666     1.045
fill      19.357     1.066
iterator  67.368     1.043
assign    17.975     0.530
for i     22.610     1.004

So apparently for these sizes, vector<bool>::assign() is faster. The code used for tests:

#include <vector>
#include <cstring>
#include <cstdlib>

#define TEST_METHOD 5
const size_t TEST_ITERATIONS = 34359738;
const size_t TEST_ARRAY_SIZE = 200;

using namespace std;

int main(int argc, char** argv) {

    std::vector<int> v(TEST_ARRAY_SIZE, 0);

    for(size_t i = 0; i < TEST_ITERATIONS; ++i) {
#if TEST_METHOD == 1
        memset(&v[0], false, v.size() * sizeof v[0]);
#elif TEST_METHOD == 2
        std::fill(v.begin(), v.end(), false);
   #elif TEST_METHOD == 3
        for (std::vector<int>::iterator it=v.begin(), end=v.end(); it!=end; ++it) {
            *it = 0;
        }
   #elif TEST_METHOD == 4
      v.assign(v.size(),false);
   #elif TEST_METHOD == 5
      for (size_t i = 0; i < TEST_ARRAY_SIZE; i++) {
          v[i] = false;
      }
#endif
    }

    return EXIT_SUCCESS;
}

I used GCC 7.2.0 compiler on Ubuntu 17.10. The command line for compiling:

g++ -std=c++11 -O0 main.cpp
g++ -std=c++11 -O3 main.cpp

How to escape a JSON string to have it in a URL?

Answer given by Delan is perfect. Just adding to it - incase someone wants to name the parameters or pass multiple JSON strings separately - the below code could help!

JQuery

var valuesToPass = new Array(encodeURIComponent(VALUE_1), encodeURIComponent(VALUE_2), encodeURIComponent(VALUE_3), encodeURIComponent(VALUE_4));

data = {elements:JSON.stringify(valuesToPass)}

PHP

json_decode(urldecode($_POST('elements')));

Hope this helps!

data.frame rows to a list

Seems a current version of the purrr (0.2.2) package is the fastest solution:

by_row(x, function(v) list(v)[[1L]], .collate = "list")$.out

Let's compare the most interesting solutions:

data("Batting", package = "Lahman")
x <- Batting[1:10000, 1:10]
library(benchr)
library(purrr)
benchmark(
    split = split(x, seq_len(.row_names_info(x, 2L))),
    mapply = .mapply(function(...) structure(list(...), class = "data.frame", row.names = 1L), x, NULL),
    purrr = by_row(x, function(v) list(v)[[1L]], .collate = "list")$.out
)

Rsults:

Benchmark summary:
Time units : milliseconds 
  expr n.eval   min  lw.qu median   mean  up.qu  max  total relative
 split    100 983.0 1060.0 1130.0 1130.0 1180.0 1450 113000     34.3
mapply    100 826.0  894.0  963.0  972.0 1030.0 1320  97200     29.3
 purrr    100  24.1   28.6   32.9   44.9   40.5  183   4490      1.0

Also we can get the same result with Rcpp:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
List df2list(const DataFrame& x) {
    std::size_t nrows = x.rows();
    std::size_t ncols = x.cols();
    CharacterVector nms = x.names();
    List res(no_init(nrows));
    for (std::size_t i = 0; i < nrows; ++i) {
        List tmp(no_init(ncols));
        for (std::size_t j = 0; j < ncols; ++j) {
            switch(TYPEOF(x[j])) {
                case INTSXP: {
                    if (Rf_isFactor(x[j])) {
                        IntegerVector t = as<IntegerVector>(x[j]);
                        RObject t2 = wrap(t[i]);
                        t2.attr("class") = "factor";
                        t2.attr("levels") = t.attr("levels");
                        tmp[j] = t2;
                    } else {
                        tmp[j] = as<IntegerVector>(x[j])[i];
                    }
                    break;
                }
                case LGLSXP: {
                    tmp[j] = as<LogicalVector>(x[j])[i];
                    break;
                }
                case CPLXSXP: {
                    tmp[j] = as<ComplexVector>(x[j])[i];
                    break;
                }
                case REALSXP: {
                    tmp[j] = as<NumericVector>(x[j])[i];
                    break;
                }
                case STRSXP: {
                    tmp[j] = as<std::string>(as<CharacterVector>(x[j])[i]);
                    break;
                }
                default: stop("Unsupported type '%s'.", type2name(x));
            }
        }
        tmp.attr("class") = "data.frame";
        tmp.attr("row.names") = 1;
        tmp.attr("names") = nms;
        res[i] = tmp;
    }
    res.attr("names") = x.attr("row.names");
    return res;
}

Now caompare with purrr:

benchmark(
    purrr = by_row(x, function(v) list(v)[[1L]], .collate = "list")$.out,
    rcpp = df2list(x)
)

Results:

Benchmark summary:
Time units : milliseconds 
 expr n.eval  min lw.qu median mean up.qu   max total relative
purrr    100 25.2  29.8   37.5 43.4  44.2 159.0  4340      1.1
 rcpp    100 19.0  27.9   34.3 35.8  37.2  93.8  3580      1.0

Which version of CodeIgniter am I currently using?

For CodeIgniter 4, use the following:

<?php    
    echo \CodeIgniter\CodeIgniter::CI_VERSION;
?>

Can I run HTML files directly from GitHub, instead of just viewing their source?

You might want to use raw.githack.com. It supports GitHub, Bitbucket, Gitlab and GitHub gists.

GitHub

Before:

https://raw.githubusercontent.com/[user]/[repository]/[branch]/[filename.ext]

In your case .html extension

After:

Development (throttled)

https://raw.githack.com/[user]/[repository]/[branch]/[filename.ext]

Production (CDN)

https://rawcdn.githack.com/[user]/[repository]/[branch]/[filename.ext]

In your case .html extension


raw.githack.com also supports other services:

Bitbucket

Before:

https://bitbucket.org/[user]/[repository]/raw/[branch]/[filename.ext]

After:

Development (throttled)

https://bb.githack.com/[user]/[repository]/raw/[branch]/[filename.ext]

Production (CDN)

https://bbcdn.githack.com/[user]/[repository]/raw/[branch]/[filename.ext]

GitLab

Before:

https://gitlab.com/[user]/[repository]/raw/[branch]/[filename.ext]

After:

Development (throttled)

https://gl.githack.com/[user]/[repository]/raw/[branch]/[filename.ext]

Production (CDN)

https://glcdn.githack.com/[user]/[repository]/raw/[branch]/[filename.ext]

GitHub gists

Before:

https://gist.githubusercontent.com/[user]/[gist]/raw/[revision]/[filename.ext]

After:

Development (throttled)

https://gist.githack.com/[user]/[gist]/raw/[revision]/[filename.ext]

Production (CDN)

https://gistcdn.githack.com/[user]/[gist]/raw/[revision]/[filename.ext]


Update: rawgit was discontinued

Passing command line arguments in Visual Studio 2010?

Under Project->Properties->Debug, you should see a box for Command line arguments (This is in C# 2010, but it should basically be the same place)

Uninstall old versions of Ruby gems

You might need to set GEM_HOME for the cleanup to work. You can check what paths exist for gemfiles by running:

gem env

Take note of the GEM PATHS section.

In my case, for example, with gems installed in my user home:

export GEM_HOME="~/.gem/ruby/2.4.0"
gem cleanup

How do I get the scroll position of a document?

Here's how to get the scrollHeight of an element obtained using a jQuery selector:

$(selector)[0].scrollHeight

If selector is the id of the element (e.g. elemId), it is guaranteed that the 0-indexed item of the array will be the element you wish to select, and scrollHeight will be correct.

byte[] to hex string

There is a built in method for this:

byte[] data = { 1, 2, 4, 8, 16, 32 };

string hex = BitConverter.ToString(data);

Result: 01-02-04-08-10-20

If you want it without the dashes, just remove them:

string hex = BitConverter.ToString(data).Replace("-", string.Empty);

Result: 010204081020

If you want a more compact representation, you can use Base64:

string base64 = Convert.ToBase64String(data);

Result: AQIECBAg

Getting absolute URLs using ASP.NET Core

For ASP.NET Core 1.0 Onwards

/// <summary>
/// <see cref="IUrlHelper"/> extension methods.
/// </summary>
public static class UrlHelperExtensions
{
    /// <summary>
    /// Generates a fully qualified URL to an action method by using the specified action name, controller name and
    /// route values.
    /// </summary>
    /// <param name="url">The URL helper.</param>
    /// <param name="actionName">The name of the action method.</param>
    /// <param name="controllerName">The name of the controller.</param>
    /// <param name="routeValues">The route values.</param>
    /// <returns>The absolute URL.</returns>
    public static string AbsoluteAction(
        this IUrlHelper url,
        string actionName,
        string controllerName,
        object routeValues = null)
    {
        return url.Action(actionName, controllerName, routeValues, url.ActionContext.HttpContext.Request.Scheme);
    }

    /// <summary>
    /// Generates a fully qualified URL to the specified content by using the specified content path. Converts a
    /// virtual (relative) path to an application absolute path.
    /// </summary>
    /// <param name="url">The URL helper.</param>
    /// <param name="contentPath">The content path.</param>
    /// <returns>The absolute URL.</returns>
    public static string AbsoluteContent(
        this IUrlHelper url,
        string contentPath)
    {
        HttpRequest request = url.ActionContext.HttpContext.Request;
        return new Uri(new Uri(request.Scheme + "://" + request.Host.Value), url.Content(contentPath)).ToString();
    }

    /// <summary>
    /// Generates a fully qualified URL to the specified route by using the route name and route values.
    /// </summary>
    /// <param name="url">The URL helper.</param>
    /// <param name="routeName">Name of the route.</param>
    /// <param name="routeValues">The route values.</param>
    /// <returns>The absolute URL.</returns>
    public static string AbsoluteRouteUrl(
        this IUrlHelper url,
        string routeName,
        object routeValues = null)
    {
        return url.RouteUrl(routeName, routeValues, url.ActionContext.HttpContext.Request.Scheme);
    }
}

Bonus Tip

You can't directly register an IUrlHelper in the DI container. Resolving an instance of IUrlHelper requires you to use the IUrlHelperFactory and IActionContextAccessor. However, you can do the following as a shortcut:

services
    .AddSingleton<IActionContextAccessor, ActionContextAccessor>()
    .AddScoped<IUrlHelper>(x => x
        .GetRequiredService<IUrlHelperFactory>()
        .GetUrlHelper(x.GetRequiredService<IActionContextAccessor>().ActionContext));

ASP.NET Core Backlog

UPDATE: This won't make ASP.NET Core 5

There are indications that you will be able to use LinkGenerator to create absolute URL's without the need to provide a HttpContext (This was the biggest downside of LinkGenerator and why IUrlHelper although more complex to setup using the solution below was easier to use) See "Make it easy to configure a host/scheme for absolute URLs with LinkGenerator".

FB OpenGraph og:image not pulling images (possibly https?)

tl;dr – be patient

I ended up here because I was seeing blank images served from a https site. The problem was quite a different one though:

When content is shared for the first time, the Facebook crawler will scrape and cache the metadata from the URL shared. The crawler has to see an image at least once before it can be rendered. This means that the first person who shares a piece of content won't see a rendered image

[https://developers.facebook.com/docs/sharing/best-practices/#precaching]

While testing, it took facebook around 10 minutes to finally show the rendered image. So while I was scratching my head and throwing random og tags at facebook (and suspecting the https problem mentioned here), all I had to do was wait.

As this might really stop people from sharing your links for the first time, FB suggests two ways to circumvent this behavior: a) running the OG Debugger on all your links: the image will be cached and ready for sharing after ~10 minutes or b) specifying og:image:width and og:image:height. (Read more in the above link)

Still wondering though what takes them so long ...

Get Current date & time with [NSDate date]

NSLocale* currentLocale = [NSLocale currentLocale];
[[NSDate date] descriptionWithLocale:currentLocale];  

or use

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// or @"yyyy-MM-dd hh:mm:ss a" if you prefer the time with AM/PM 
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);

NUnit Unit tests not showing in Test Explorer with Test Adapter installed

I experienced the problem mentioned by op

My case was that I was handed an old project and the tests were actually part of the system under test. I assume they were using the external test runner.

this task chain resolved the issue for me

  • created a test project,
  • moved the test files there
  • added references so the test project would compile
  • added the Nunit and Nunit adapter NuGet packages to the test project
  • recompiled

i was able to successfully run the Nunit tests.

How to replace spaces in file names using a bash script

Recursive version of Naidim's Answers.

find . -name "* *" | awk '{ print length, $0 }' | sort -nr -s | cut -d" " -f2- | while read f; do base=$(basename "$f"); newbase="${base// /_}"; mv "$(dirname "$f")/$(basename "$f")" "$(dirname "$f")/$newbase"; done

Cannot find or open the PDB file in Visual Studio C++ 2010

Answer by Paul is right, I am just putting the visual to easily get there.

Go to Tools->Options->Debugging->Symbols

Set the checkbox marked in red and it will download the pdb files from microsoft. When you set the checkbox, it will also set a default path for the pdb files in the edit box under, you don't need to change that.

enter image description here

Get index of a key/value pair in a C# dictionary based on the value

no , there is nothing similar IndexOf for Dictionary although you can make use of ContainsKey method to get whether a key belongs to dictionary or not

How to align 3 divs (left/center/right) inside another div?

There are several tricks available for aligning the elements.

01. Using Table Trick

_x000D_
_x000D_
.container{_x000D_
  display:table;_x000D_
 }_x000D_
_x000D_
.left{_x000D_
  background:green;_x000D_
  display:table-cell;_x000D_
  width:33.33vw;_x000D_
}_x000D_
_x000D_
.center{_x000D_
  background:gold;_x000D_
  display:table-cell;_x000D_
  width:33.33vw;_x000D_
}_x000D_
_x000D_
.right{_x000D_
  background:gray;_x000D_
  display:table-cell;_x000D_
  width:33.33vw;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="left">_x000D_
    Left_x000D_
  </div>_x000D_
  <div class="center">_x000D_
    Center_x000D_
  </div>_x000D_
  <div class="right">_x000D_
    Right_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

02. Using Flex Trick

_x000D_
_x000D_
.container{_x000D_
  display:flex;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
   }_x000D_
_x000D_
.left{_x000D_
  background:green;_x000D_
  width:33.33vw;_x000D_
}_x000D_
_x000D_
.center{_x000D_
  background:gold;_x000D_
   width:33.33vw;_x000D_
}_x000D_
_x000D_
.right{_x000D_
  background:gray;_x000D_
   width:33.33vw;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="left">_x000D_
    Left_x000D_
  </div>_x000D_
  <div class="center">_x000D_
    Center_x000D_
  </div>_x000D_
  <div class="right">_x000D_
    Right_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

03. Using Float Trick

_x000D_
_x000D_
.left{_x000D_
  background:green;_x000D_
  width:100px;_x000D_
  float:left;_x000D_
}_x000D_
_x000D_
.center{_x000D_
   background:gold;_x000D_
   width:100px;_x000D_
   float:left;_x000D_
}_x000D_
_x000D_
.right{_x000D_
   background:gray;_x000D_
   width:100px;_x000D_
   float:left;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="left">_x000D_
    Left_x000D_
  </div>_x000D_
  <div class="center">_x000D_
    Center_x000D_
  </div>_x000D_
  <div class="right">_x000D_
    Right_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Facebook Graph API : get larger pictures in one request

You can use full_picture instead of picture key to get full size image.

Merging a lot of data.frames

Put them into a list and use merge with Reduce

Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
#    id v1 v2 v3
# 1   1  1 NA NA
# 2  10  4 NA NA
# 3   2  3  4 NA
# 4  43  5 NA NA
# 5  73  2 NA NA
# 6  23 NA  2  1
# 7  57 NA  3 NA
# 8  62 NA  5  2
# 9   7 NA  1 NA
# 10 96 NA  6 NA

You can also use this more concise version:

Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))

Is there a command to undo git init?

Git keeps all of its files in the .git directory. Just remove that one and init again.

This post well show you how to find the hide .git file on Windows, Mac OSX, Ubuntu

Forward declaration of a typedef in C++

As Bill Kotsias noted, the only reasonable way to keep the typedef details of your point private, and forward declare them is with inheritance. You can do it a bit nicer with C++11 though. Consider this:

// LibraryPublicHeader.h

class Implementation;

class Library
{
...
private:
    Implementation* impl;
};
// LibraryPrivateImplementation.cpp

// This annoyingly does not work:
//
//     typedef std::shared_ptr<Foo> Implementation;

// However this does, and is almost as good.
class Implementation : public std::shared_ptr<Foo>
{
public:
    // C++11 allows us to easily copy all the constructors.
    using shared_ptr::shared_ptr;
};

What's the difference between a null pointer and a void pointer?

I don't think AnT's answer is correct.

  1. NULL is just a pointer constant, otherwise how could we have ptr = NULL.
  2. As NULL is a pointer, what's its type. I think the type is just (void *), otherwise how could we have both int * ptr = NULL and (user-defined type)* ptr = NULL. void type is actually a universal type.
  3. Quoted in "C11(ISO/IEC 9899:201x) §6.3.2.3 Pointers Section 3":

    An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant

So simply put: NULL pointer is a void pointer constant.

Iterating over arrays in Python 3

While iterating over a list or array with this method:

ar = [10, 11, 12]
for i in ar:
    theSum = theSum + ar[i]

You are actually getting the values of list or array sequentially in i variable. If you print the variable i inside the for loop. You will get following output:

10
11
12

However, in your code you are confusing i variable with index value of array. Therefore, while doing ar[i] will mean ar[10] for the first iteration. Which is of course index out of range throwing IndexError

Edit You can read this for better understanding of different methods of iterating over array or list in Python

JavaScript to get rows count of a HTML table

This is another option, using jQuery and getting only tbody rows (with the data) and desconsidering thead/tfoot.

$("#tableId > tbody > tr").length

_x000D_
_x000D_
console.log($("#myTableId > tbody > tr").length);
_x000D_
.demo {
   width:100%;
   height:100%;
   border:1px solid #C0C0C0;
   border-collapse:collapse;
   border-spacing:2px;
   padding:5px;
}

.demo caption {
   caption-side:top;
   text-align:center;
}

.demo th {
   border:1px solid #C0C0C0;
   padding:5px;
   background:#F0F0F0;
}

.demo td {
   border:1px solid #C0C0C0;
   text-align:left;
   padding:5px;
   background:#FFFFFF;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTableId" class="demo">
   <caption>Table 1</caption>
   <thead>
      <tr>
         <th>Header 1</th>
         <th>Header 2</th>
         <th>Header 3</th>
         <th>Header 4</th>
      </tr>
   </thead>
   <tbody>
      <tr>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
      </tr>
      <tr>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
      </tr>
      <tr>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
      </tr>
      <tr>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
         <td>&nbsp;</td>
      </tr>
   </tbody>
   <tfoot>
      <tr>
         <td colspan=4 style="background:#F0F0F0">&nbsp; </td>
      </tr>
   </tfoot>
</table>
_x000D_
_x000D_
_x000D_

Spring Boot: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean

Try this

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
    public static void main(String[] args) {
       SpringApplication.run(ScheduledTasks.class, args);
    }
}

Regex - Should hyphens be escaped?

Typically you would always put the hyphen first in the [] match section. EG, to match any alphanumeric character including hyphens (written the long way), you would use [-a-zA-Z0-9]

How can I list all foreign keys referencing a given table in SQL Server?

The following solution work for me:

--Eliminar las llaves foraneas
declare @query varchar(8000)
declare cursorRecorrerTabla cursor for

SELECT  'ALTER TABLE [PoaComFinH].['+sch.name+'].['+referencingTable.Name+'] DROP CONSTRAINT ['+foreignKey.name+']' 'query'
FROM PoaComFinH.sys.foreign_key_columns fk
JOIN PoaComFinH.sys.tables referencingTable ON fk.parent_object_id = referencingTable.object_id
JOIN PoaComFinH.sys.schemas sch ON referencingTable.schema_id = sch.schema_id
JOIN PoaComFinH.sys.objects foreignKey ON foreignKey.object_id = fk.constraint_object_id
JOIN PoaComFinH.sys.tables referencedTable ON fk.referenced_object_id = referencedTable.object_id


--3ro. abrir el cursor.
open cursorRecorrerTabla
fetch next from cursorRecorrerTabla
into @query
while @@fetch_status = 0
begin
--inicio cuerpo del cursor
    print @query
    exec(@query)
--fin cuerpo del cursor
fetch next from cursorRecorrerTabla
into @query
end
--cerrar cursor
close cursorRecorrerTabla
deallocate cursorRecorrerTabla

How do I configure the proxy settings so that Eclipse can download new plugins?

finally work for me !

In Eclipse, Window > Preferences > General > Network Connections,
set Active Provider to Native
add to eclipse.ini :

-Djava.net.useSystemProxies=true
-Dhttp.proxyPort=8080
-Dhttp.proxyHost=myproxy
-Dhttp.proxyUser=mydomain\myusername
-Dhttp.proxyPassword=mypassword
-Dhttp.nonProxyHosts=localhost|127.0.0.1|192.168.*|10.*
-Dorg.eclipse.ecf.provider.filetransfer.excludeContributors=org.eclipse.ecf.provider.filetransfer.httpclient4

update listview dynamically with adapter

SimpleListAdapter's are primarily used for static data! If you want to handle dynamic data, you're better off working with an ArrayAdapter, ListAdapter or with a CursorAdapter if your data is coming in from the database.

Here's a useful tutorial in understanding binding data in a ListAdapter

As referenced in this SO question

Using "&times" word in html changes to ×

You need to escape:

<div class="test">&amp;times</div>

And then read the value using text() to get the unescaped value:

alert($(".test").text()); // outputs: &times

How to download a file over HTTP?

One more, using urlretrieve:

import urllib
urllib.urlretrieve ("http://www.example.com/songs/mp3.mp3", "mp3.mp3")

(for Python 3+ use import urllib.request and urllib.request.urlretrieve)

Yet another one, with a "progressbar"

import urllib2

url = "http://download.thinkbroadband.com/10MB.zip"

file_name = url.split('/')[-1]
u = urllib2.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s Bytes: %s" % (file_name, file_size)

file_size_dl = 0
block_sz = 8192
while True:
    buffer = u.read(block_sz)
    if not buffer:
        break

    file_size_dl += len(buffer)
    f.write(buffer)
    status = r"%10d  [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
    status = status + chr(8)*(len(status)+1)
    print status,

f.close()

Template not provided using create-react-app

npx create-react-app@latest your-project-name

work for me after trying all the answers hope that can help someone in the future.

Pick images of root folder from sub-folder

../ takes you one folder up the directory tree. Then, select the appropriate folder and its contents.

../images/logo.png

Regex to split a CSV

If you know that you won't have an empty field (,,) then this expression works well:

("[^"]*"|[^,]+)

As in the following example...

Set rx = new RegExp
rx.Pattern = "(""[^""]*""|[^,]+)"
rx.Global = True
Set col = rx.Execute(sText)
For n = 0 to col.Count - 1
    if n > 0 Then s = s & vbCrLf
    s = s & col(n)
Next

However, if you anticipate an empty field and your text is relatively small than you might consider replacing the empty fields with a space prior to parsing to ensure that they are captured. For example...

...
Set col = rx.Execute(Replace(sText, ",,", ", ,"))
...

And if you need to maintain the integrity of the fields, you can restore the commas and test for empty spaces inside the loop. This may not be the most efficient method but it gets the job done.

Python: Split a list into sub-lists based on index ranges

list1=['x','y','z','a','b','c','d','e','f','g']
find=raw_input("Enter string to be found")
l=list1.index(find)
list1a=[:l]
list1b=[l:]

Error: unable to verify the first certificate in nodejs

This actually solved it for me, from https://www.npmjs.com/package/ssl-root-cas

// INCORRECT (but might still work)
var server = https.createServer({
  key: fs.readFileSync('privkey.pem', 'ascii'),
  cert: fs.readFileSync('cert.pem', 'ascii') // a PEM containing ONLY the SERVER certificate
});

// CORRECT (should always work)
var server = https.createServer({
  key: fs.readFileSync('privkey.pem', 'ascii'),
  cert: fs.readFileSync('fullchain.pem', 'ascii') // a PEM containing the SERVER and ALL INTERMEDIATES
});

How to Serialize a list in java?

As pointed out already, most standard implementations of List are serializable. However you have to ensure that the objects referenced/contained within the list are also serializable.

How open PowerShell as administrator from the run window

The easiest way to open an admin Powershell window in Windows 10 (and Windows 8) is to add a "Windows Powershell (Admin)" option to the "Power User Menu". Once this is done, you can open an admin powershell window via Win+X,A or by right-clicking on the start button and selecting "Windows Powershell (Admin)":

[Windows 10/Windows 8 Power User menu with "Windows Powershell (Admin)

Here's where you replace the "Command Prompt" option with a "Windows Powershell" option:

[Taskbar and Start Menu Properties: "Replace Command Prompt With Windows Powershell"

Handling Dialogs in WPF with MVVM

I've written a fairly comprehensive article about this very topic and also developed a pop-in library for MVVM Dialogs. Strict adherence to MVVM is not only possible but very clean when implemented properly, and it can be easily extended to third-party libraries that don't adhere to it themselves:

https://www.codeproject.com/Articles/820324/Implementing-Dialog-Boxes-in-MVVM

Keras input explanation: input_shape, units, batch_size, dim, etc

Input Dimension Clarified:

Not a direct answer, but I just realized the word Input Dimension could be confusing enough, so be wary:

It (the word dimension alone) can refer to:

a) The dimension of Input Data (or stream) such as # N of sensor axes to beam the time series signal, or RGB color channel (3): suggested word=> "InputStream Dimension"

b) The total number /length of Input Features (or Input layer) (28 x 28 = 784 for the MINST color image) or 3000 in the FFT transformed Spectrum Values, or

"Input Layer / Input Feature Dimension"

c) The dimensionality (# of dimension) of the input (typically 3D as expected in Keras LSTM) or (#RowofSamples, #of Senors, #of Values..) 3 is the answer.

"N Dimensionality of Input"

d) The SPECIFIC Input Shape (eg. (30,50,50,3) in this unwrapped input image data, or (30, 250, 3) if unwrapped Keras:

Keras has its input_dim refers to the Dimension of Input Layer / Number of Input Feature

model = Sequential()
model.add(Dense(32, input_dim=784))  #or 3 in the current posted example above
model.add(Activation('relu'))

In Keras LSTM, it refers to the total Time Steps

The term has been very confusing, is correct and we live in a very confusing world!!

I find one of the challenge in Machine Learning is to deal with different languages or dialects and terminologies (like if you have 5-8 highly different versions of English, then you need to very high proficiency to converse with different speakers). Probably this is the same in programming languages too.

php exec command (or similar) to not wait for result

"exec nohup setsid your_command"

the nohup allows your_command to continue even though the process that launched may terminate first. If it does, the the SIGNUP signal will be sent to your_command causing it to terminate (unless it catches that signal and ignores it).

How to set Grid row and column positions programmatically

for (int i = 0; i < 6; i++)
{
    test.ColumnDefinitions.Add(new ColumnDefinition());

    Label t1 = new Label();
    t1.Content = "Test" + i;

    Grid.SetColumn(t1, i);
    Grid.SetRow(t1, 0);
    test.Children.Add(t1);
}

Git: Permission denied (publickey) fatal - Could not read from remote repository. while cloning Git repository

If all fails, as was the case with me, Uninstall GIT, reinstall. For some reason this fixes.

P.S.

  1. I tried generating new Keys and Updating at SSH public keys
  2. Also tried deleting all keys and tried to create a fresh key.
  3. And NO, nothing wrong with my .gitconfig

Getting query parameters from react-router hash fragment

The above answers won't work in react-router v4. Here's what I did to solve the problem -

First Install query-string which will be required for parsing.

npm install -save query-string

Now in the routed component you can access the un-parsed query string like this

this.props.location.search

You can cross check it by logging in the console.

Finally parse to access the query parameters

const queryString = require('query-string');
var parsed = queryString.parse(this.props.location.search);
console.log(parsed.param); // replace param with your own 

So if query is like ?hello=world

console.log(parsed.hello) will log world

Set up Python simpleHTTPserver on Windows

From Stack Overflow question What is the Python 3 equivalent of "python -m SimpleHTTPServer":

The following works for me:

python -m http.server [<portNo>]

Because I am using Python 3 the module SimpleHTTPServer has been replaced by http.server, at least in Windows.

Get remote registry value

another option ... needs remoting ...

(invoke-command -ComputerName mymachine -ScriptBlock {Get-ItemProperty HKLM:\SOFTWARE\VanDyke\VShell\License -Name Version }).version

How to call controller from the button click in asp.net MVC 4

Try this:

@Html.ActionLink("DisplayText", "Action", "Controller", route, attribute)

in your code should be,

@Html.ActionLink("Search", "List", "Search", new{@class="btn btn-info", @id="addressSearch"})

How to flush route table in windows?

In Microsoft Windows, you can go through by route -f command to delete your current Gateway, check route / ? for more advance option, like add / delete etc and also can write a batch to add route on specific time as well but if you need to delete IP cache, then you have the option to use arp command.

How to declare a global variable in a .js file

Yes you can access them. You should declare them in 'public space' (outside any functions) as:

var globalvar1 = 'value';

You can access them later on, also in other files.

Reset push notification settings for app

The Apple Tech Note also described you can restore the device to reset the Push Notification dialog.

It does not say that you can also use the option "General -> Reset -> Erase All Content And Settings" on the device itself (iOS 5.x).

How to use enums in C++

Enums in C++ are like integers masked by the names you give them, when you declare your enum-values (this is not a definition only a hint how it works).

But there are two errors in your code:

  1. Spell enum all lower case
  2. You don't need the Days. before Saturday.
  3. If this enum is declared in a class, then use if (day == YourClass::Saturday){}

How do you cast a List of supertypes to a List of subtypes?

This is possible due to type erasure. You will find that

List<TestA> x = new ArrayList<TestA>();
List<TestB> y = new ArrayList<TestB>();
x.getClass().equals(y.getClass()); // true

Internally both lists are of type List<Object>. For that reason you can't cast one to the other - there is nothing to cast.

How can I represent an infinite number in Python?

Also if you use SymPy you can use sympy.oo

>>> from sympy import oo
>>> oo + 1
oo
>>> oo - oo
nan

etc.

Prevent browser caching of AJAX call result

Personally I feel that the query string method is more reliable than trying to set headers on the server - there's no guarantee that a proxy or browser won't just cache it anyway (some browsers are worse than others - naming no names).

I usually use Math.random() but I don't see anything wrong with using the date (you shouldn't be doing AJAX requests fast enough to get the same value twice).

Using Chrome's Element Inspector in Print Preview Mode?

With shortcuts available, the quickest way is to

  1. Open the Developer Tools

    • Windows: F12 or Ctrl+Shift+I
    • Mac: Cmd+Opt+I
  2. Open the Command Menu

    • Windows: Ctrl+Shift+P
    • Mac: Cmd+Shift+P
  3. Type print and select Emulate CSS print media type from the context menu

    Change Media Type Emulation Via Command Menu

Looking at the excellent and currently most-upvoted answer by lmeurs, I think this solution might also remain stable over time.

Enable CORS in fetch api

Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors at your server side.

You can fetch request using mode: 'cors'. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.

So in both condition you need to configure cors in your server or you need to use custom proxy server.

How to convert seconds to HH:mm:ss in moment.js

From this post I would try this to avoid leap issues

moment("2015-01-01").startOf('day')
    .seconds(s)
    .format('H:mm:ss');

I did not run jsPerf, but I would think this is faster than creating new date objects a million times

function pad(num) {
    return ("0"+num).slice(-2);
}
function hhmmss(secs) {
  var minutes = Math.floor(secs / 60);
  secs = secs%60;
  var hours = Math.floor(minutes/60)
  minutes = minutes%60;
  return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;
  // return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers
}

_x000D_
_x000D_
function pad(num) {_x000D_
    return ("0"+num).slice(-2);_x000D_
}_x000D_
function hhmmss(secs) {_x000D_
  var minutes = Math.floor(secs / 60);_x000D_
  secs = secs%60;_x000D_
  var hours = Math.floor(minutes/60)_x000D_
  minutes = minutes%60;_x000D_
  return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;_x000D_
  // return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers_x000D_
}_x000D_
_x000D_
for (var i=60;i<=60*60*5;i++) {_x000D_
 document.write(hhmmss(i)+'<br/>');_x000D_
}_x000D_
_x000D_
_x000D_
/* _x000D_
function show(s) {_x000D_
  var d = new Date();_x000D_
  var d1 = new Date(d.getTime()+s*1000);_x000D_
  var  hms = hhmmss(s);_x000D_
  return (s+"s = "+ hms + " - "+ Math.floor((d1-d)/1000)+"\n"+d.toString().split("GMT")[0]+"\n"+d1.toString().split("GMT")[0]);_x000D_
}    _x000D_
*/
_x000D_
_x000D_
_x000D_

How can I test that a variable is more than eight characters in PowerShell?

You can also use -match against a Regular expression. Ex:

if ($dbUserName -match ".{8}" )
{
    Write-Output " Please enter more than 8 characters "
    $dbUserName=read-host " Re-enter database user name"
}

Also if you're like me and like your curly braces to be in the same horizontal position for your code blocks, you can put that on a new line, since it's expecting a code block it will look on next line. In some commands where the first curly brace has to be in-line with your command, you can use a grave accent marker (`) to tell powershell to treat the next line as a continuation.

My prerelease app has been "processing" for over a week in iTunes Connect, what gives?

So I experienced this yesterday (22 feb '17), I tried uploading the build via Xcode (8.2) multiple times, it showed (Processing). Then I tried it with the application loader, still the same. I just had to wait for ~12 hours to have it spam me with processing done emails.

So yeah, it's not you, it's them.

How to integrate SAP Crystal Reports in Visual Studio 2017

Crystal Reports SP 19 does not support Visual Studio 2017. According to SAP they are targeting Visual Studio 2017 compatibility in SP 20 which is tentatively scheduled for June 2017.

Adb over wireless without usb cable at all for not rooted phones

The question is about a non rooted device but if it is rooted the simplest way would be to:

From the terminal on your phone, do this:

su
setprop service.adb.tcp.port 5555
stop adbd
start adbd

See this answer for full details.

How do I create a unique ID in Java?

String name,password;

public int idGen() {

    int id = this.name.hashCode() + this.password.hashCode();
    int length = String.valueOf(id).length();
    int Max_Length = 5;
    if(String.valueOf(id).length()>Max_Length) 
    {
        id = (int) (id /Math.pow(10.0,length - Max_Length ));
    }
    return  id;
}

Regular Expression to reformat a US phone number in Javascript

var numbers = "(123) 456-7890".replace(/[^\d]/g, ""); //This strips all characters that aren't digits
if (numbers.length != 10) //wrong format
    //handle error
var phone = "(" + numbers.substr(0, 3) + ") " + numbers.substr(3, 3) + "-" + numbers.substr(6); //Create format with substrings