Programs & Examples On #Invitation

How to create a testflight invitation code?

after you add the user for testing. the user should get an email. open that email by your iOS device, then click "Start testing" it will bring you to testFlight to download the app directly. If you open that email via computer, and then click "Start testing" it will show you another page which have the instruction of how to install the app. and that invitation code is on the last line. those All upper case letters is the code.

POST request not allowed - 405 Not Allowed - nginx, even with headers included

I have tried the solution which redirects 405 to 200, and in production environment(in my case, it's Google Load Balancing with Nginx Docker container), this hack causes some 502 errors(Google Load Balancing error code: backend_early_response_with_non_error_status).

In the end, I have made this work properly by replacing Nginx with OpenResty which is completely compatible with Nginx and have more plugins.

With ngx_coolkit, Now Nginx(OpenResty) could serve static files with POST request properly, here is the config file in my case:

server {
  listen 80;

  location / {
    override_method GET;
    proxy_pass http://127.0.0.1:8080;
  }
}

server {
  listen 8080;
  location / {
    root /var/www/web-static;
    index index.html;
    add_header Cache-Control no-cache;
  }
}

In the above config, I use override_method offered by ngx_coolkit to override the HTTP Method to GET.

What is the difference between Sublime text and Github's Atom

I just got my beta invitation today and tried Atom right away. The GUI feels like Sublime, and yes, there some shortcuts adopted from Sublime.

Besides everything mentioned above, here are some differences I have noticed so far:

  1. Vim mode is not as good as the Vintage mode on Sublime (which is not a fully featured vim either) because the vim package is in an early stage of development. See https://atom.io/packages/vim-mode for detail.

  2. As James mention, Atom is written using web tools, so you have access to the stylesheet of the text editor (styles.less) to do whatever appearance changes you want using CSS. There is also an option to change the startup CoffeeScript.

  3. Again, because Atom is still in the beta stage, Sublime has much more native plugin packages. However, since Atom is written in Node.js, the Atom official site said you can "choose from over 50 thousand in Node's package repository." (Because I am not a Node.js pro, I haven't look into this feature though)

  4. Atom has better Github support out of the box, but Sublime has a several Git packages.

  5. Sublime is a paid application unlimited evaluation period. Atom is free at the beta stage but we don't know whether Github wants to charge it or not.

So the bottom line is Atom is a text editor built with web technology at beta stage. By contrast, Sublime has evolved through many different iterations. Atom is still missing a lot of packages that Sublime supports, so the question is will Atom catch up with Sublime or become some better? Github seems to be confident about the future of this text edit because of its popular underlying technologies, and Atom is probably going to be a good alternative to Sublime in the long run.

Validate email with a regex in jQuery

You probably want to use a regex like the one described here to check the format. When the form's submitted, run the following test on each field:

var userinput = $(this).val();
var pattern = /^\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i

if(!pattern.test(userinput))
{
  alert('not a valid e-mail address');
}?

Why does Google prepend while(1); to their JSON responses?

As this is a High traffic post i hope to provide here an answer slightly more undetermined to the original question and thus to provide further background on a JSON Hijacking attack and its consequences

JSON Hijacking as the name suggests is an attack similar to Cross-Site Request Forgery where an attacker can access cross-domain sensitive JSON data from applications that return sensitive data as array literals to GET requests. An example of a JSON call returning an array literal is shown below:

[{"id":"1001","ccnum":"4111111111111111","balance":"2345.15"}, 
{"id":"1002","ccnum":"5555555555554444","balance":"10345.00"}, 
{"id":"1003","ccnum":"5105105105105100","balance":"6250.50"}]

This attack can be achieved in 3 major steps:

Step 1: Get an authenticated user to visit a malicious page. Step 2: The malicious page will try and access sensitive data from the application that the user is logged into.This can be done by embedding a script tag in an HTML page since the same-origin policy does not apply to script tags.

<script src="http://<jsonsite>/json_server.php"></script>

The browser will make a GET request to json_server.php and any authentication cookies of the user will be sent along with the request. Step 3: At this point while the malicious site has executed the script it does not have access to any sensitive data. Getting access to the data can be achieved by using an object prototype setter. In the code below an object prototypes property is being bound to the defined function when an attempt is being made to set the "ccnum" property.

Object.prototype.__defineSetter__('ccnum',function(obj){

secrets =secrets.concat(" ", obj);

});

At this point the malicious site has successfully hijacked the sensitive financial data (ccnum) returned byjson_server.php JSON

It should be noted that not all browsers support this method; the proof of concept was done on Firefox 3.x.This method has now been deprecated and replaced by the useObject.defineProperty There is also a variation of this attack that should work on all browsers where full named JavaScript (e.g. pi=3.14159) is returned instead of a JSON array.

There are several ways in which JSON Hijacking can be prevented:

  • Since SCRIPT tags can only generate HTTP GET requests, only return JSON objects to POST requests.

  • Prevent the web browser from interpreting the JSON object as valid JavaScript code.

  • Implement Cross-Site Request Forgery protection by requiring that a predefined random value be required for all JSON requests.

so as you can see While(1) comes under the last option. In the most simple terms, while(1) is an infinite loop which will run till a break statement is issued explicitly. And thus what would be described as a lock for the key to be applied (google break statement). Therefore a JSON hijacking, in which the Hacker has no key will be consistently dismissed.Alas, If you read the JSON block with a parser, the while(1) loop is ignored.

So in conclusion, the while(1) loop can more easily visualised as a simple break statement cipher that google can use to control flow of data.

However the key word in that statement is the word 'simple'. The usage of authenticated infinite loops has been thankfully removed from basic practice in the years since 2010 due to its absolute decimation of CPU usage when isolated (and the fact the internet has moved away from forcing through crude 'quick-fixes'). Today instead the codebase has preventative measures embedded and the system is not crucial nor effective anymore. (part of this is the move away from JSON Hijacking to more fruitful datafarming techniques that i wont go into at present)

*

"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"

ON DUPLICATE KEY UPDATE is not really in the standard. It's about as standard as REPLACE is. See SQL MERGE.

Essentially both commands are alternative-syntax versions of standard commands.

jQuery Validate Plugin - Trigger validation of single field

$("#FormId").validate().element('#FieldId');

What is the PostgreSQL equivalent for ISNULL()

SELECT CASE WHEN field IS NULL THEN 'Empty' ELSE field END AS field_alias

Or more idiomatic:

SELECT coalesce(field, 'Empty') AS field_alias

How to capitalize the first character of each word in a string

WordUtils.capitalize(str) (from apache commons-text)

(Note: if you need "fOO BAr" to become "Foo Bar", then use capitalizeFully(..) instead)

Understanding `scale` in R

It provides nothing else but a standardization of the data. The values it creates are known under several different names, one of them being z-scores ("Z" because the normal distribution is also known as the "Z distribution").

More can be found here:

http://en.wikipedia.org/wiki/Standard_score

Correct way to use StringBuilder in SQL

When you already have all the "pieces" you wish to append, there is no point in using StringBuilder at all. Using StringBuilder and string concatenation in the same call as per your sample code is even worse.

This would be better:

return "select id1, " + " id2 " + " from " + " table";

In this case, the string concatenation is actually happening at compile-time anyway, so it's equivalent to the even-simpler:

return "select id1, id2 from table";

Using new StringBuilder().append("select id1, ").append(" id2 ")....toString() will actually hinder performance in this case, because it forces the concatenation to be performed at execution time, instead of at compile time. Oops.

If the real code is building a SQL query by including values in the query, then that's another separate issue, which is that you should be using parameterized queries, specifying the values in the parameters rather than in the SQL.

I have an article on String / StringBuffer which I wrote a while ago - before StringBuilder came along. The principles apply to StringBuilder in the same way though.

How can I make Bootstrap columns all the same height?

If you want to make this work in any browser, use javascript:

$( document ).ready(function() {
    var heights = $(".panel").map(function() {
        return $(this).height();
    }).get(),

    maxHeight = Math.max.apply(null, heights);

    $(".panel").height(maxHeight);
});

What is the easiest way to remove all packages installed by pip?

Pip has no way of knowing what packages were installed by it and what packages were installed by your system's package manager. For this you would need to do something like this

for rpm-based distros (replace python2.7 with your python version you installed pip with):

find /usr/lib/python2.7/ |while read f; do
  if ! rpm -qf "$f" &> /dev/null; then
    echo "$f"
  fi
done |xargs rm -fr

for a deb-based distribution:

find /usr/lib/python2.7/ |while read f; do
  if ! dpkg-query -S "$f" &> /dev/null; then
    echo "$f"
  fi
done |xargs rm -fr

then to clean up empty directories left over:

find /usr/lib/python2.7 -type d -empty |xargs rm -fr

I found the top answer very misleading since it will remove all (most?) python packages from your distribution and probably leave you with a broken system.

SQL query question: SELECT ... NOT IN

It's always dangerous to have NULL in the IN list - it often behaves as expected for the IN but not for the NOT IN:

IF 1 NOT IN (1, 2, 3, NULL) PRINT '1 NOT IN (1, 2, 3, NULL)'
IF 1 NOT IN (2, 3, NULL) PRINT '1 NOT IN (2, 3, NULL)'
IF 1 NOT IN (2, 3) PRINT '1 NOT IN (2, 3)' -- Prints
IF 1 IN (1, 2, 3, NULL) PRINT '1 IN (1, 2, 3, NULL)' -- Prints
IF 1 IN (2, 3, NULL) PRINT '1 IN (2, 3, NULL)'
IF 1 IN (2, 3) PRINT '1 IN (2, 3)'

How to use operator '-replace' in PowerShell to replace strings of texts with special characters and replace successfully

'-replace' does a regex search and you have special characters in that last one (like +) So you might use the non-regex replace version like this:

$c = $c.replace('AccountKey=eKkij32jGEIYIEqAR5RjkKgf4OTiMO6SAyF68HsR/Zd/KXoKvSdjlUiiWyVV2+OUFOrVsd7jrzhldJPmfBBpQA==','DdOegAhDmLdsou6Ms6nPtP37bdw6EcXucuT47lf9kfClA6PjGTe3CfN+WVBJNWzqcQpWtZf10tgFhKrnN48lXA==')

How can I control the speed that bootstrap carousel slides in items?

In your main.js file or bootstrap.js, change the value of autoplayTimeout

_x000D_
_x000D_
    $('.carousel').each(function () {
        $(this).owlCarousel({
            nav: $(this).data('nav'),
            dots: $(this).data('dots'),
            loop: $(this).data('loop'),
            margin: $(this).data('space'),
            center: $(this).data('center'),
            dotsSpeed: $(this).data('speed'),
            autoplay: $(this).data('autoplay'),
            transitionStyle: $(this).data('transition'),
            animateOut: $(this).data('animate-out'),
            animateIn: $(this).data('animate-in'),
            autoplayTimeout: 3000,
            responsive: {
                0: {
                    items: 1,
                },
                400: {
                    items: $(this).data('slide-sm'),
                },
                700: {
                    items: $(this).data('slide-md'),
                },
                1000: {
                    items: $(this).data('slide'),
                }
            }
        });
    });
_x000D_
_x000D_
_x000D_

Is String.Contains() faster than String.IndexOf()?

Just as an update to this I've been doing some testing and providing your input string is fairly large then parallel Regex is the fastest C# method I've found (providing you have more than one core I imagine)

Getting the total amount of matches for example -

needles.AsParallel ( ).Sum ( l => Regex.IsMatch ( haystack , Regex.Escape ( l ) ) ? 1 : 0 );

Hope this helps!

Get controller and action name from within controller?

This is what I have so far:

var actionName = filterContext.ActionDescriptor.ActionName;
var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;

Force download a pdf link using javascript/ajax/jquery

If htaccess is an option this will make all PDF links download instead of opening in browser

<FilesMatch "\.(?i:pdf)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</FilesMatch>

Struct with template variables in C++

The problem is you can't template a typedef, also there is no need to typedef structs in C++.

The following will do what you need

template <typename T> 
struct array { 
  size_t x; 
  T *ary; 
}; 

How can I list the scheduled jobs running in my database?

The DBA views are restricted. So you won't be able to query them unless you're connected as a DBA or similarly privileged user.

The ALL views show you the information you're allowed to see. Normally that would be jobs you've submitted, unless you have additional privileges.

The privileges you need are defined in the Admin Guide. Find out more.

So, either you need a DBA account or you need to chat with your DBA team about getting access to the information you need.

Adb install failure: INSTALL_CANCELED_BY_USER

Its a Xiaomi's issue If possible update MIUI to latest version then go to Settings > Additional Settings > Developer Options > Developer options: Check the Install via USB option.

This solved my issue hope it will also solve yours good luck!

How do I set an ASP.NET Label text from code behind on page load?

protected void Page_Load(object sender, EventArgs e)
{
    myLabel.Text = "My text";
}

this is the base of ASP.Net, thinking in controls, not html flow.

Consider following a course, or reading a beginner book... and first, forget what you did in php :)

How does numpy.newaxis work and when to use it?

What is np.newaxis?

The np.newaxis is just an alias for the Python constant None, which means that wherever you use np.newaxis you could also use None:

>>> np.newaxis is None
True

It's just more descriptive if you read code that uses np.newaxis instead of None.

How to use np.newaxis?

The np.newaxis is generally used with slicing. It indicates that you want to add an additional dimension to the array. The position of the np.newaxis represents where I want to add dimensions.

>>> import numpy as np
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a.shape
(10,)

In the first example I use all elements from the first dimension and add a second dimension:

>>> a[:, np.newaxis]
array([[0],
       [1],
       [2],
       [3],
       [4],
       [5],
       [6],
       [7],
       [8],
       [9]])
>>> a[:, np.newaxis].shape
(10, 1)

The second example adds a dimension as first dimension and then uses all elements from the first dimension of the original array as elements in the second dimension of the result array:

>>> a[np.newaxis, :]  # The output has 2 [] pairs!
array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
>>> a[np.newaxis, :].shape
(1, 10)

Similarly you can use multiple np.newaxis to add multiple dimensions:

>>> a[np.newaxis, :, np.newaxis]  # note the 3 [] pairs in the output
array([[[0],
        [1],
        [2],
        [3],
        [4],
        [5],
        [6],
        [7],
        [8],
        [9]]])
>>> a[np.newaxis, :, np.newaxis].shape
(1, 10, 1)

Are there alternatives to np.newaxis?

There is another very similar functionality in NumPy: np.expand_dims, which can also be used to insert one dimension:

>>> np.expand_dims(a, 1)  # like a[:, np.newaxis]
>>> np.expand_dims(a, 0)  # like a[np.newaxis, :]

But given that it just inserts 1s in the shape you could also reshape the array to add these dimensions:

>>> a.reshape(a.shape + (1,))  # like a[:, np.newaxis]
>>> a.reshape((1,) + a.shape)  # like a[np.newaxis, :]

Most of the times np.newaxis is the easiest way to add dimensions, but it's good to know the alternatives.

When to use np.newaxis?

In several contexts is adding dimensions useful:

  • If the data should have a specified number of dimensions. For example if you want to use matplotlib.pyplot.imshow to display a 1D array.

  • If you want NumPy to broadcast arrays. By adding a dimension you could for example get the difference between all elements of one array: a - a[:, np.newaxis]. This works because NumPy operations broadcast starting with the last dimension 1.

  • To add a necessary dimension so that NumPy can broadcast arrays. This works because each length-1 dimension is simply broadcast to the length of the corresponding1 dimension of the other array.


1 If you want to read more about the broadcasting rules the NumPy documentation on that subject is very good. It also includes an example with np.newaxis:

>>> a = np.array([0.0, 10.0, 20.0, 30.0])
>>> b = np.array([1.0, 2.0, 3.0])
>>> a[:, np.newaxis] + b
array([[  1.,   2.,   3.],
       [ 11.,  12.,  13.],
       [ 21.,  22.,  23.],
       [ 31.,  32.,  33.]])

Excel - Sum column if condition is met by checking other column in same table

SUMIF didn't worked for me, had to use SUMIFS.

=SUMIFS(TableAmount,TableMonth,"January")

TableAmount is the table to sum the values, TableMonth the table where we search the condition and January, of course, the condition to meet.

Hope this can help someone!

How to directly execute SQL query in C#?

Something like this should suffice, to do what your batch file was doing (dumping the result set as semi-colon delimited text to the console):

// sqlcmd.exe
// -S .\PDATA_SQLEXPRESS
// -U sa
// -P 2BeChanged!
// -d PDATA_SQLEXPRESS
// -s ; -W -w 100
// -Q "SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName, tPatDBirthday  FROM  [dbo].[TPatientRaw] WHERE tPatSName = '%name%' "

DataTable dt            = new DataTable() ;
int       rows_returned ;

const string credentials = @"Server=(localdb)\.\PDATA_SQLEXPRESS;Database=PDATA_SQLEXPRESS;User ID=sa;Password=2BeChanged!;" ;
const string sqlQuery = @"
  select tPatCulIntPatIDPk ,
         tPatSFirstname    ,
         tPatSName         ,
         tPatDBirthday
  from dbo.TPatientRaw
  where tPatSName = @patientSurname
  " ;

using ( SqlConnection connection = new SqlConnection(credentials) )
using ( SqlCommand    cmd        = connection.CreateCommand() )
using ( SqlDataAdapter sda       = new SqlDataAdapter( cmd ) )
{
  cmd.CommandText = sqlQuery ;
  cmd.CommandType = CommandType.Text ;
  connection.Open() ;
  rows_returned = sda.Fill(dt) ;
  connection.Close() ;
}

if ( dt.Rows.Count == 0 )
{
  // query returned no rows
}
else
{

  //write semicolon-delimited header
  string[] columnNames = dt.Columns
                           .Cast<DataColumn>()
                           .Select( c => c.ColumnName )
                           .ToArray()
                           ;
  string   header      = string.Join("," , columnNames) ;
  Console.WriteLine(header) ;

  // write each row
  foreach ( DataRow dr in dt.Rows )
  {

    // get each rows columns as a string (casting null into the nil (empty) string
    string[] values = new string[dt.Columns.Count];
    for ( int i = 0 ; i < dt.Columns.Count ; ++i )
    {
      values[i] = ((string) dr[i]) ?? "" ; // we'll treat nulls as the nil string for the nonce
    }

    // construct the string to be dumped, quoting each value and doubling any embedded quotes.
    string data = string.Join( ";" , values.Select( s => "\""+s.Replace("\"","\"\"")+"\"") ) ;
    Console.WriteLine(values);

  }

}

Hide Utility Class Constructor : Utility classes should not have a public or default constructor

If this class is only a utility class, you should make the class final and define a private constructor:

public final class FilePathHelper {

   private FilePathHelper() {
      //not called
   }
}

This prevents the default parameter-less constructor from being used elsewhere in your code. Additionally, you can make the class final, so that it can't be extended in subclasses, which is a best practice for utility classes. Since you declared only a private constructor, other classes wouldn't be able to extend it anyway, but it is still a best practice to mark the class as final.

Remove Android App Title Bar

In the graphical editor, make sure you have chosen your theme at the top.

Show ProgressDialog Android

While creating the object for the progressbar check the following.

This fails:

dialog = new ProgressDialog(getApplicationContext());

While adding the activities context works..

dialog = new ProgressDialog(MainActivity.this);

Element implicitly has an 'any' type because expression of type 'string' can't be used to index

This happens because you try to access plotOptions property using string name. TypeScript understands that name may have any value, not only property name from plotOptions. So TypeScript requires to add index signature to plotOptions, so it knows that you can use any property name in plotOptions. But I suggest to change type of name, so it can only be one of plotOptions properties.

interface trainInfo {
    name: keyof typeof plotOptions;
    x: Array<number>;
    y: Array<number>;
    type: string;
    mode: string;
}

Now you'll be able to use only property names that exist in plotOptions.

You also have to slightly change your code.

First assign array to some temp variable, so TS knows array type:

const plotDataTemp: Array<trainInfo> = [
    {
      name: "train_1",
      x: data.filtrationData.map((i: any) => i["1-CumVol"]),
      y: data.filtrationData.map((i: any) => i["1-PressureA"]),
      type: "scatter",
      mode: "lines"
    },
    // ...
}

Then filter:

const plotData = plotDataTemp.filter(({ name }) => plotOptions[name]);

If you're getting data from API and have no way to type check props at compile time the only way is to add index signature to your plotOptions:

type tplotOptions = {
    [key: string]: boolean
}

const plotOptions: tplotOptions = {
    train_1: true,
    train_2: true,
    train_3: true,
    train_4: true
}

Uninstall old versions of Ruby gems

# remove all old versions of the gem
gem cleanup rjb

# choose which ones you want to remove
gem uninstall rjb

# remove version 1.1.9 only
gem uninstall rjb --version 1.1.9

# remove all versions less than 1.3.4
gem uninstall rjb --version '<1.3.4'

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check

I believe this is the simplest example:

header := w.Header()
header.Add("Access-Control-Allow-Origin", "*")
header.Add("Access-Control-Allow-Methods", "DELETE, POST, GET, OPTIONS")
header.Add("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With")

You can also add a header for Access-Control-Max-Age and of course you can allow any headers and methods that you wish.

Finally you want to respond to the initial request:

if r.Method == "OPTIONS" {
    w.WriteHeader(http.StatusOK)
    return
}

Edit (June 2019): We now use gorilla for this. Their stuff is more actively maintained and they have been doing this for a really long time. Leaving the link to the old one, just in case.

Old Middleware Recommendation below: Of course it would probably be easier to just use middleware for this. I don't think I've used it, but this one seems to come highly recommended.

In Python, how do I read the exif data for an image?

For Python3.x and starting Pillow==6.0.0, Image objects now provide a getexif() method that returns a <class 'PIL.Image.Exif'> instance or None if the image has no EXIF data.

From Pillow 6.0.0 release notes:

getexif() has been added, which returns an Exif instance. Values can be retrieved and set like a dictionary. When saving JPEG, PNG or WEBP, the instance can be passed as an exif argument to include any changes in the output image.

As stated, you can iterate over the key-value pairs of the Exif instance like a regular dictionary. The keys are 16-bit integers that can be mapped to their string names using the ExifTags.TAGS module.

from PIL import Image, ExifTags

img = Image.open("sample.jpg")
img_exif = img.getexif()
print(type(img_exif))
# <class 'PIL.Image.Exif'>

if img_exif is None:
    print('Sorry, image has no exif data.')
else:
    for key, val in img_exif.items():
        if key in ExifTags.TAGS:
            print(f'{ExifTags.TAGS[key]}:{val}')
            # ExifVersion:b'0230'
            # ...
            # FocalLength:(2300, 100)
            # ColorSpace:1
            # ...
            # Model:'X-T2'
            # Make:'FUJIFILM'
            # LensSpecification:(18.0, 55.0, 2.8, 4.0)
            # ...
            # DateTime:'2019:12:01 21:30:07'
            # ...

Tested with Python 3.8.8 and Pillow==8.1.0.

How to change the Jupyter start-up folder

As of 2020, for Windows...

The configuration is for an installation from miniconda, but it'll be the same for anaconda. The shortcut can be modified by looking at its properties. The target of the link has this format:

  • C:\Users\A_User\miniconda3\python.exe C:\Users\A_User\miniconda3\cwp.py C:\Users\A_User\miniconda3 C:\Users\A_User\miniconda3\python.exe C:\Users\A_User\miniconda3\Scripts\jupyter-notebook-script.py "%USERPROFILE%\Documents\Jupyter"

There are three parts:

1: The first part launches a wrapper

C:\Users\A_User\miniconda3\python.exe C:\Users\A_User\miniconda3\cwp.py

This wrapper ensures the third part (which is the actual shortcut) can be executed with the proper configuration, depending on the environment chosen for execution. Code is here.

2: The path to the Script folder

Scripts are in a subfolder Scripts of the folder used for each environment. Give the path to the environment you want, the wrapper will do the rest. In my case I'm using the base environment:

C:\Users\A_User\miniconda3

This fragment is passed to the script which identifies it as variable prefix, the full path computed from the variable and then added at the beginning of environment variable PATH and also replaces the current content of CONDA_PREFIX.

3: The command to run

This is the command to be processed by the previous wrapper:

C:\Users\A_User\miniconda3\python.exe C:\Users\A_User\miniconda3\Scripts\jupyter-notebook-script.py "%USERPROFILE%\Documents\Jupyter"

It runs Python with the jupyter-notebook-script.py script to launch Jupyter notebook, and it adds the specific initial folder "%USERPROFILE%\Documents\Jupyter" which corresponds to the location I use to store notebook files. This path is the one you asked for.

The paths can be adjusted to your specific configuration and preferences for environment to use and storage.

ios Upload Image and Text using HTTP POST

here's the working swift code translated from the code provided by @xjones. Thanks alot for your help mate. Yours was the only way that worked for me. I used this method to send 1 image and a another parameter to a webservice made in asp.net


                    let params = NSMutableDictionary()

                    let boundaryConstant  = "----------V2y2HFg03eptjbaKO0j1"

                    let file1ParamConstant = "file1"
                    params.setObject(device_id!, forKey: "deviceID")

                    let requestUrl = NSURL(string: "\(siteurl):\(port)/FileUpload/Upload")

                    let request = NSMutableURLRequest()

                    request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
                    request.HTTPShouldHandleCookies=false
                    request.timeoutInterval = 30
                    request.HTTPMethod = "POST"

                    let contentType = "multipart/form-data; boundary=\(boundaryConstant)"

                    request.setValue(contentType, forHTTPHeaderField: "Content-Type")

                    let body = NSMutableData()

                    // parameters

                    for param in params {

                    body.appendData("--\(boundaryConstant)\r\n" .dataUsingEncoding(NSUTF8StringEncoding)! )
                    body.appendData("Content-Disposition: form-data; name=\"\(param)\"\r\n\r\n" .dataUsingEncoding(NSUTF8StringEncoding)!)
                    body.appendData("\(param.value)\r\n" .dataUsingEncoding(NSUTF8StringEncoding)!)

                    }
                    // images

                    // image begin
                    body.appendData("--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

                    body.appendData("Content-Disposition: form-data; name=\"\(file1ParamConstant)\"; filename=\"image.jpg\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
                    body.appendData("Content-Type: image/jpeg\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

                    body.appendData(passportImageData)
                    body.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

                    // image end



                    body.appendData("--\(boundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

                    request.HTTPBody  = body
                    let postLength = "\(body.length)"
                    request.setValue(postLength, forHTTPHeaderField: "Content-Length")
                    request.URL = requestUrl

                    var serverResponse = NSString()

                    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
                        data, response, error in

                        if error != nil
                        {
                            print("error=\(error)")
                            return
                        }


                        print("response = \(response)")


                        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
                        print("responseString = \(responseString!)")
                        serverResponse = responseString!


                        }

                            task.resume()

How to convert unix timestamp to calendar date moment.js

This function creates date from timestamp:

    function formatDateTime(dateString) {
        const parsed = moment(new Date(dateString))

        if (!parsed.isValid()) {
            return dateString
        }

        return parsed.format('MMM D, YYYY, HH:mmA')
    }

Setting action for back button in navigation controller

Easiest way

You can use the UINavigationController's delegate methods. The method willShowViewController is called when the back button of your VC is pressed.do whatever you want when back btn pressed

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated;

DLL References in Visual C++

You mention adding the additional include directory (C/C++|General) and additional lib dependency (Linker|Input), but have you also added the additional library directory (Linker|General)?

Including a sample error message might also help people answer the question since it's not even clear if the error is during compilation or linking.

Get current batchfile directory

Here's what I use at the top of all my batch files. I just copy/paste from my template folder.

@echo off
:: --HAS ENDING BACKSLASH
set batdir=%~dp0
:: --MISSING ENDING BACKSLASH
:: set batdir=%CD%
pushd "%batdir%"

Setting current batch file's path to %batdir% allows you to call it in subsequent stmts in current batch file, regardless of where this batch file changes to. Using PUSHD allows you to use POPD to quickly set this batch file's path to original %batdir%. Remember, if using %batdir%ExtraDir or %batdir%\ExtraDir (depending on which version used above, ending backslash or not) you will need to enclose the entire string in double quotes if path has spaces (i.e. "%batdir%ExtraDir"). You can always use PUSHD %~dp0. [https: // ss64.com/ nt/ syntax-args .html] has more on (%~) parameters.

Note that using (::) at beginning of a line makes it a comment line. More importantly, using :: allows you to include redirectors, pipes, special chars (i.e. < > | etc) in that comment.

:: ORIG STMT WAS: dir *.* | find /v "1917" > outfile.txt

Of course, Powershell does this and lots more.

Does return stop a loop?

This code will exit the loop after the first iteration in a for of loop:

const objc = [{ name: 1 }, { name: 2 }, { name: 3 }];
for (const iterator of objc) {
  if (iterator.name == 2) {
    return;
  }
  console.log(iterator.name);// 1
}

the below code will jump on the condition and continue on a for of loop:

const objc = [{ name: 1 }, { name: 2 }, { name: 3 }];

for (const iterator of objc) {
  if (iterator.name == 2) {
    continue;
  }
  console.log(iterator.name); // 1  , 3
}

How to instantiate, initialize and populate an array in TypeScript?

A simple solution could be:

interface bar {
    length: number;
}

let bars: bar[];
bars = [];

Typescript: How to extend two classes?

I would suggest using the new mixins approach described there: https://blogs.msdn.microsoft.com/typescript/2017/02/22/announcing-typescript-2-2/

This approach is better, than the "applyMixins" approach described by Fenton, because the autocompiler would help you and show all the methods / properties from the both base and 2nd inheritance classes.

This approach might be checked on the TS Playground site.

Here is the implementation:

class MainClass {
    testMainClass() {
        alert("testMainClass");
    }
}

const addSecondInheritance = (BaseClass: { new(...args) }) => {
    return class extends BaseClass {
        testSecondInheritance() {
            alert("testSecondInheritance");
        }
    }
}

// Prepare the new class, which "inherits" 2 classes (MainClass and the cass declared in the addSecondInheritance method)
const SecondInheritanceClass = addSecondInheritance(MainClass);
// Create object from the new prepared class
const secondInheritanceObj = new SecondInheritanceClass();
secondInheritanceObj.testMainClass();
secondInheritanceObj.testSecondInheritance();

#ifdef replacement in the Swift language

Yes you can do it.

In Swift you can still use the "#if/#else/#endif" preprocessor macros (although more constrained), as per Apple docs. Here's an example:

#if DEBUG
    let a = 2
#else
    let a = 3
#endif

Now, you must set the "DEBUG" symbol elsewhere, though. Set it in the "Swift Compiler - Custom Flags" section, "Other Swift Flags" line. You add the DEBUG symbol with the -D DEBUG entry.

As usual, you can set a different value when in Debug or when in Release.

I tested it in real code and it works; it doesn't seem to be recognized in a playground though.

You can read my original post here.


IMPORTANT NOTE: -DDEBUG=1 doesn't work. Only -D DEBUG works. Seems compiler is ignoring a flag with a specific value.

Get full query string in C# ASP.NET

This should work fine for you.

Write this code in the Page_Load event of the page.

string ID = Request.QueryString["id"].ToString();
Response.Redirect("http://www.example.com/rendernews.php?id=" + ID);

'const int' vs. 'int const' as function parameters in C++ and C

They are the same, but in C++ there's a good reason to always use const on the right. You'll be consistent everywhere because const member functions must be declared this way:

int getInt() const;

It changes the this pointer in the function from Foo * const to Foo const * const. See here.

gradlew command not found?

I use intellj idea and in windows in terminal type: gradlew.bat run it is working for me.

Compile error: package javax.servlet does not exist

JSP and Servlet are Server side Programming. As it comes as an built in package inside a Server like Tomcat. The path may be like wise

C:\Program Files\Apache Software Foundation\Tomcat 6.0\lib\jsp-api.jar
C:\Program Files\Apache Software Foundation\Tomcat 6.0\lib\servlet-api.jar

Just you want to Do is Add this in the following way

Right Click> My Computer>Advanced>Environment Variables>System variables

Do> New..> Variable name:CLASSPATH
           Variable value:CLASSPATH=.;C:\Program Files\Apache Software Foundation\Tomcat 6.0\lib\servlet-api.jar;

Is it possible to set a number to NaN or infinity?

Cast from string using float():

>>> float('NaN')
nan
>>> float('Inf')
inf
>>> -float('Inf')
-inf
>>> float('Inf') == float('Inf')
True
>>> float('Inf') == 1
False

How to get back Lost phpMyAdmin Password, XAMPP

The only solution worked for me:

(source: https://stackoverflow.com/a/22784404/2377343 )

You need to stop Mysql and change user password using Commands.

IOPub data rate exceeded in Jupyter notebook (when viewing image)

I ran into this using networkx and bokeh

This works for me in Windows 7 (taken from here):

  1. To create a jupyter_notebook_config.py file, with all the defaults commented out, you can use the following command line:

    $ jupyter notebook --generate-config

  2. Open the file and search for c.NotebookApp.iopub_data_rate_limit

  3. Comment out the line c.NotebookApp.iopub_data_rate_limit = 1000000 and change it to a higher default rate. l used c.NotebookApp.iopub_data_rate_limit = 10000000

This unforgiving default config is popping up in a lot of places. See git issues:

It looks like it might get resolved with the 5.1 release

Update:

Jupyter notebook is now on release 5.2.2. This problem should have been resolved. Upgrade using conda or pip.

File.Move Does Not Work - File Already Exists

1) With C# on .Net Core 3.0 and beyond, there is now a third boolean parameter:

see https://docs.microsoft.com/en-us/dotnet/api/system.io.file.move?view=netcore-3.1

In .NET Core 3.0 and later versions, you can call Move(String, String, Boolean) setting the parameter overwrite to true, which will replace the file if it exists.

2) For all other versions of .Net, https://stackoverflow.com/a/42224803/887092 is the best answer. Copy with Overwrite, then delete the source file. This is better because it makes it an atomic operation. (I have attempted to update the MS Docs with this)

SQL Server 2008: how do I grant privileges to a username?

If you want to give your user all read permissions, you could use:

EXEC sp_addrolemember N'db_datareader', N'your-user-name'

That adds the default db_datareader role (read permission on all tables) to that user.

There's also a db_datawriter role - which gives your user all WRITE permissions (INSERT, UPDATE, DELETE) on all tables:

EXEC sp_addrolemember N'db_datawriter', N'your-user-name'

If you need to be more granular, you can use the GRANT command:

GRANT SELECT, INSERT, UPDATE ON dbo.YourTable TO YourUserName
GRANT SELECT, INSERT ON dbo.YourTable2 TO YourUserName
GRANT SELECT, DELETE ON dbo.YourTable3 TO YourUserName

and so forth - you can granularly give SELECT, INSERT, UPDATE, DELETE permission on specific tables.

This is all very well documented in the MSDN Books Online for SQL Server.

And yes, you can also do it graphically - in SSMS, go to your database, then Security > Users, right-click on that user you want to give permissions to, then Properties adn at the bottom you see "Database role memberships" where you can add the user to db roles.

alt text

mysql after insert trigger which updates another table's column

With your requirements you don't need BEGIN END and IF with unnecessary SELECT in your trigger. So you can simplify it to this

CREATE TRIGGER occupy_trig AFTER INSERT ON occupiedroom 
FOR EACH ROW
  UPDATE BookingRequest
     SET status = 1
   WHERE idRequest = NEW.idRequest;

Get the number of rows in a HTML table

The following code assumes that your table has the ID 'MyTable'

<script language="JavaScript">
<!--
var oRows = document.getElementById('MyTable').getElementsByTagName('tr');
var iRowCount = oRows.length;

alert('Your table has ' + iRowCount + ' rows.');
//-->
</script>

Answer taken from : http://www.delphifaq.com/faq/f771.shtml, which is the first result on google for the query : "Get the number of rows in a HTML table" ;)

I get conflicting provisioning settings error when I try to archive to submit an iOS app

Using Xcode 10: None of the other solutions here worked for me.

This error appears to be something you can't fix in Xcode 10

I had to revert to Xcode 9 to resolve this issue, and then update back to Xcode 10 so I could run my application on iOS 12 on a non-emulator device.

Any other solutions found on Stack Overflow or elsewhere, used in Xcode 10, sent me into an endless cycle of provisioning conflicts or signing certificate issues. It seems like signing is broken in Xcode 10 whether you're using the automatic method or manually selecting provisioning profiles and certificates.

You can revert to Xcode 9 by first deleting Xcode 10 from your Applications folder. Then, install Xcode 9 using the .xip file listed on this Apple Developers page.

In Xcode 9, use the automatic build option. You may have to uncheck 'Automatically manage signing' and reselect it, and you also may be required to revoke an existing certificate at developer.apple.com.

After you get the app to successfully build in Xcode 9, you can update back to Xcode 10 using the App Store. After reopening the application in Xcode 10, everything still worked. You may not need to do this, but I needed to in order to build for iOS 12 which requires Xcode 10.

R cannot be resolved - Android error

For me it was due to using 'private' android drawables:

[2015-11-26 18:59:48 - MyAndroidApp] 
/Users/myname/git/MyAndroidApp/res/menu/drawer_view.xml:24: 
error: Error: Resource is not public. (at 'icon' with value 
'@android:drawable/ic_menu_home').

The interesting thing is that this errors didn't show up in the Console until I removed the reference to the file using the icons (ugh!).

android:entries="@menu/drawer_view"

Now the solution was quite obvious, copying the icons into my project (res/drawable-XXXX/) and switching to local references.

@drawable/ic_menu_home

Hope this helps.

Convert NSData to String?

A simple way to convert arbitrary NSData to NSString is to base64 encode it.

NSString *base64EncodedKey = [keydata base64EncodedStringWithOptions: NSDataBase64Encoding64CharacterLineLength];

You can then store it into your database for reuse later. Just decode it back to NSData.

What's the difference between xsd:include and xsd:import?

Use xsd:include to bring in an XSD from the same or no namespace.

Use xsd:import to bring in an XSD from a different namespace.

TypeScript getting error TS2304: cannot find name ' require'

  1. Did you specify what module to use to transpile the code?
    tsc --target es5 --module commonjs script.ts
    You must do that to let the transpiler know that you're compiling NodeJS code. Docs.

  2. You must install mongoose definitions as well
    tsd install mongoose --save

  3. Do not use var to declare variables (unless necessary, which is a very rare case), use let instead. Learn more about that

Enable PHP Apache2

If anyone gets

ERROR: Module phpX.X does not exist!

just install the module for your current php version:

apt-get install libapache2-mod-phpX.X

Javascript validation: Block special characters

A few of the options are deprecated as of today. So watch out for those.

If you try <input onkeypress="blockSpecialCharacters(event)" />, an IDE like WebStorm will slash out event and tell you:

Deprecated symbol used, consults docs for better alternative

Then when you get to the JavaScript, console.log(e.keyCode) will also give keyCode and say:

Deprecated symbol used, consults docs for better alternative

Anyways I did it using jQuery.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js"></script>

<input id="theInput" />

<script>
    function blockSpecialCharacters(e) {
            let key = e.key;
            let keyCharCode = key.charCodeAt(0);

            // 0-9
            if(keyCharCode >= 48 && keyCharCode <= 57) {
                return key;
            }
            // A-Z
            if(keyCharCode >= 65 && keyCharCode <= 90) {
                return key;
            }
            // a-z
            if(keyCharCode >= 97 && keyCharCode <= 122) {
                return key;
            }

            return false;
    }

    $('#theInput').keypress(function(e) {
        blockSpecialCharacters(e);
    });
</script>

How to add an object to an ArrayList in Java

Contacts.add(objt.Data(name, address, contact));

This is not a perfect way to call a constructor. The constructor is called at the time of object creation automatically. If there is no constructor java class creates its own constructor.

The correct way is:

// object creation. 
Data object1 = new Data(name, address, contact);      

// adding Data object to ArrayList object Contacts.
Contacts.add(object1);                              

Is there a way to reset IIS 7.5 to factory settings?

There are automatic backup under %systemdrive%\inetpub\history but it may not help much if you already made lots of changes.

http://blogs.iis.net/bills/archive/2008/03/24/how-to-backup-restore-iis7-configuration.aspx

You will have to regularly back up manually using appcmd.

If you try to reinstall IIS, please first uninstall IIS and WAS via Add/Remove Programs, and then delete all existing files under C:\inetpub and C:\Windows\system32\inetsrv directories. Then you can install again cleanly.

WARN: beginners on IIS are not recommended to execute the steps above without a full backup of the system. The steps should be executed with caution and good understanding of IIS. If you are not capable of or you have doubt, make sure you open a support case with Microsoft via http://support.microsoft.com and consult.

Pods stuck in Terminating status

The original question is "What could be the reason for this issue?" and the answer is discussed at https://github.com/kubernetes/kubernetes/issues/51835 & https://github.com/kubernetes/kubernetes/issues/65569 & see https://www.bountysource.com/issues/33241128-unable-to-remove-a-stopped-container-device-or-resource-busy

Its caused by docker mount leaking into some other namespace.

You can logon to pod host to investigate.

minikube ssh
docker container ps | grep <id>
docker container stop <id> 

Saving an image in OpenCV

I had similar problem with my Microsoft WebCam. I looked in the image aquisition toolbox in Matlab and found that the maximum supported resolution is 640*480.

I just changed the code in openCV and added

cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, 352); 
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, 288);

before cvQueryFrame function which was the next supported resolution and changed skipped some initial frames before saving the image and finally got it working.

I am sharing my working Code

#include "cv.h" 
#include "highgui.h" 
#include <stdio.h> 



using namespace cv;
using namespace std;

int main() 
{
CvCapture* capture = cvCaptureFromCAM( CV_CAP_ANY );
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, 352); 
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, 288)


 // Get one frame
IplImage* frame;

for (int i = 0; i < 25; i++) 
{
frame = cvQueryFrame( capture );
}


printf( "Image captured \n" );  
//IplImage* RGB_frame = frame;
//cvCvtColor(frame,RGB_frame,CV_YCrCb2BGR);
//cvWaitKey(1000);
cvSaveImage("test.jpg" ,frame);
//cvSaveImage("cam.jpg" ,RGB_frame);

printf( "Image Saved \n" );

//cvWaitKey(10);

// Release the capture device housekeeping
cvReleaseCapture( &capture );
//cvDestroyWindow( "mywindow" );
return 0;
}

My Suggestions:

  1. Dont grab frame with maximum resolution
  2. Skip some frames for correct camera initialisation

How do C++ class members get initialized if I don't do it explicitly?

You can also initialize data members at the point you declare them:

class another_example{
public:
    another_example();
    ~another_example();
private:
    int m_iInteger=10;
    double m_dDouble=10.765;
};

I use this form pretty much exclusively, although I have read some people consider it 'bad form', perhaps because it was only recently introduced - I think in C++11. To me it is more logical.

Another useful facet to the new rules is how to initialize data-members that are themselves classes. For instance suppose that CDynamicString is a class that encapsulates string handling. It has a constructor that allows you specify its initial value CDynamicString(wchat_t* pstrInitialString). You might very well use this class as a data member inside another class - say a class that encapsulates a windows registry value which in this case stores a postal address. To 'hard code' the registry key name to which this writes you use braces:

class Registry_Entry{
public:
    Registry_Entry();
    ~Registry_Entry();
    Commit();//Writes data to registry.
    Retrieve();//Reads data from registry;
private:
    CDynamicString m_cKeyName{L"Postal Address"};
    CDynamicString m_cAddress;
};

Note the second string class which holds the actual postal address does not have an initializer so its default constructor will be called on creation - perhaps automatically setting it to a blank string.

How to convert XML to java.util.Map and vice versa

One option would be to roll your own. It would be fairly simple to do:

Document doc = getDocument();
Element root = doc.createElement(rootName);
doc.appendChild(root);
for (Map.Entry<String,String> element : map.entrySet() ) {
    Element e = doc.createElement(element.getKey());
    e.setTextContent(element.getValue());
    root.appendChild(e);
}
save(doc, file);

and the load is an equally simply getChildNodes and a loop. Sure it has a bit of boiler plate that the XML Gods demand but it is at most 1 hours work.

Or you could look at Properties if you are not too fused about the format of the XML.

React-Router: No Not Found Route?

This answer is for react-router-4. You can wrap all the routes in Switch block, which functions just like the switch-case expression, and renders the component with the first matched route. eg)

<Switch>
      <Route path="/" component={home}/>
      <Route path="/home" component={home}/>
      <Route component={GenericNotFound}/> {/* The Default not found component */}
</Switch>

When to use exact

Without exact:

<Route path='/home'
       component = {Home} />

{/* This will also work for cases like https://<domain>/home/anyvalue. */}

With exact:

<Route exact path='/home'
       component = {Home} />

{/* 
     This will NOT work for cases like https://<domain>/home/anyvalue. 
     Only for https://<url>/home and https://<domain>/home/
*/}

Now if you are accepting routing parameters, and if it turns out incorrect, you can handle it in the target component itself. eg)

<Route exact path='/user/:email'
       render = { (props) => <ProfilePage {...props} user={this.state.user} />} />

Now in ProfilePage.js

if(this.props.match.params.email != desiredValue)
{
   <Redirect to="/notFound" component = {GenericNotFound}/>
   //Or you can show some other component here itself.
}

For more details you can go through this code:

App.js

ProfilePage.js

How to calculate the inverse of the normal cumulative distribution function in python?

NORMSINV (mentioned in a comment) is the inverse of the CDF of the standard normal distribution. Using scipy, you can compute this with the ppf method of the scipy.stats.norm object. The acronym ppf stands for percent point function, which is another name for the quantile function.

In [20]: from scipy.stats import norm

In [21]: norm.ppf(0.95)
Out[21]: 1.6448536269514722

Check that it is the inverse of the CDF:

In [34]: norm.cdf(norm.ppf(0.95))
Out[34]: 0.94999999999999996

By default, norm.ppf uses mean=0 and stddev=1, which is the "standard" normal distribution. You can use a different mean and standard deviation by specifying the loc and scale arguments, respectively.

In [35]: norm.ppf(0.95, loc=10, scale=2)
Out[35]: 13.289707253902945

If you look at the source code for scipy.stats.norm, you'll find that the ppf method ultimately calls scipy.special.ndtri. So to compute the inverse of the CDF of the standard normal distribution, you could use that function directly:

In [43]: from scipy.special import ndtri

In [44]: ndtri(0.95)
Out[44]: 1.6448536269514722

Func delegate with no return type

... takes no arguments and has a void return type?

If you are writing for System.Windows.Forms, You can also use:

public delegate void MethodInvoker()

SQL DELETE with INNER JOIN

Add .* to s in your first line.

Try:

DELETE s.* FROM spawnlist s
INNER JOIN npc n ON s.npc_templateid = n.idTemplate
WHERE (n.type = "monster");

PHP Change Array Keys

No, there is not, for starters, it is impossible to have an array with elements sharing the same key

$x =array(); 
$x['foo'] = 'bar' ; 
$x['foo'] = 'baz' ; #replaces 'bar'

Secondarily, if you wish to merely prefix the numbers so that

$x[0] --> $x['foo_0']  

That is computationally implausible to do without looping. No php functions presently exist for the task of "key-prefixing", and the closest thing is "extract" which will prefix numeric keys prior to making them variables.

The very simplest way is this:

function rekey( $input , $prefix ) { 
    $out = array(); 
    foreach( $input as $i => $v ) { 
        if ( is_numeric( $i ) ) { 
            $out[$prefix . $i] = $v; 
            continue; 
        }
        $out[$i] = $v;
    }
    return $out;
}

Additionally, upon reading XMLWriter usage, I believe you would be writing XML in a bad way.

<section> 
    <foo_0></foo_0>
   <foo_1></foo_1>
   <bar></bar>
   <foo_2></foo_2>
</section>

Is not good XML.

<section> 
   <foo></foo>
   <foo></foo>
   <bar></bar>
   <foo></foo>
</section>

Is better XML, because when intrepreted, the names being duplicate don't matter because they're all offset numerically like so:

section => { 
    0 => [ foo , {} ]
    1 => [ foo , {} ]
    2 => [ bar , {} ]
    3 => [ foo , {} ] 
}

How to convert comma-delimited string to list in Python?

Consider the following in order to handle the case of an empty string:

>>> my_string = 'A,B,C,D,E'
>>> my_string.split(",") if my_string else []
['A', 'B', 'C', 'D', 'E']
>>> my_string = ""
>>> my_string.split(",") if my_string else []
[]

ASP.Net MVC How to pass data from view to controller

You can do it with ViewModels like how you passed data from your controller to view.

Assume you have a viewmodel like this

public class ReportViewModel
{
   public string Name { set;get;}
}

and in your GET Action,

public ActionResult Report()
{
  return View(new ReportViewModel());
}

and your view must be strongly typed to ReportViewModel

@model ReportViewModel
@using(Html.BeginForm())
{
  Report NAme : @Html.TextBoxFor(s=>s.Name)
  <input type="submit" value="Generate report" />
}

and in your HttpPost action method in your controller

[HttpPost]
public ActionResult Report(ReportViewModel model)
{
  //check for model.Name property value now
  //to do : Return something
}

OR Simply, you can do this without the POCO classes (Viewmodels)

@using(Html.BeginForm())
{
   <input type="text" name="reportName" />
   <input type="submit" />
}

and in your HttpPost action, use a parameter with same name as the textbox name.

[HttpPost]
public ActionResult Report(string reportName)
{
  //check for reportName parameter value now
  //to do : Return something
}

EDIT : As per the comment

If you want to post to another controller, you may use this overload of the BeginForm method.

@using(Html.BeginForm("Report","SomeOtherControllerName"))
{
   <input type="text" name="reportName" />
   <input type="submit" />
}

Passing data from action method to view ?

You can use the same view model, simply set the property values in your GET action method

public ActionResult Report()
{
  var vm = new ReportViewModel();
  vm.Name="SuperManReport";
  return View(vm);
}

and in your view

@model ReportViewModel
<h2>@Model.Name</h2>
<p>Can have input field with value set in action method</p>
@using(Html.BeginForm())
{
  @Html.TextBoxFor(s=>s.Name)
  <input type="submit" />
}

Read file-contents into a string in C++

The most efficient is to create a buffer of the correct size and then read the file into the buffer.

#include <fstream>
#include <vector>

int main()
{
    std::ifstream       file("Plop");
    if (file)
    {
        /*
         * Get the size of the file
         */
        file.seekg(0,std::ios::end);
        std::streampos          length = file.tellg();
        file.seekg(0,std::ios::beg);

        /*
         * Use a vector as the buffer.
         * It is exception safe and will be tidied up correctly.
         * This constructor creates a buffer of the correct length.
         * Because char is a POD data type it is not initialized.
         *
         * Then read the whole file into the buffer.
         */
        std::vector<char>       buffer(length);
        file.read(&buffer[0],length);
    }
}

Get all child views inside LinearLayout at once

It is easier with Kotlin using for-in loop:

for (childView in ll.children) {
     //childView is a child of ll         
}

Here ll is id of LinearLayout defined in layout XML.

How do I make a matrix from a list of vectors in R?

Not straightforward, but it works:

> t(sapply(a, unlist))
      [,1] [,2] [,3] [,4] [,5] [,6]
 [1,]    1    1    2    3    4    5
 [2,]    2    1    2    3    4    5
 [3,]    3    1    2    3    4    5
 [4,]    4    1    2    3    4    5
 [5,]    5    1    2    3    4    5
 [6,]    6    1    2    3    4    5
 [7,]    7    1    2    3    4    5
 [8,]    8    1    2    3    4    5
 [9,]    9    1    2    3    4    5
[10,]   10    1    2    3    4    5

Making TextView scrollable on Android

This is how I did it purely in XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <ScrollView
        android:id="@+id/SCROLLER_ID"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical"
        android:fillViewport="true">

        <TextView
            android:id="@+id/TEXT_STATUS_ID"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1.0"/>
    </ScrollView>
</LinearLayout>

NOTES:

  1. android:fillViewport="true" combined with android:layout_weight="1.0" will make the textview take up all available space.

  2. When defining the Scrollview, DO NOT specify android:layout_height="fill_parent" otherwise the scrollview doesn't work! (this has caused me to waste an hour just now! FFS).

PRO TIP:

To programmatically scroll to the bottom after appending text, use this:

mTextStatus = (TextView) findViewById(R.id.TEXT_STATUS_ID);
mScrollView = (ScrollView) findViewById(R.id.SCROLLER_ID);

private void scrollToBottom()
{
    mScrollView.post(new Runnable()
    {
        public void run()
        {
            mScrollView.smoothScrollTo(0, mTextStatus.getBottom());
        }
    });
}

Unknown Column In Where Clause

I had the same problem, I found this useful.

mysql_query("SELECT * FROM `users` WHERE `user_name`='$user'");

remember to put $user in ' ' single quotes.

How do I create a SQL table under a different schema?

The default schema for the user could be changed with the following query and avoids changing the property every time a table is to be created.

USE [DBName] 
GO 
ALTER USER [YourUserName] WITH DEFAULT_SCHEMA = [YourSchema] 
GO

How do I pass multiple parameters into a function in PowerShell?

The correct answer has already been provided, but this issue seems prevalent enough to warrant some additional details for those wanting to understand the subtleties.

I would have added this just as a comment, but I wanted to include an illustration--I tore this off my quick reference chart on PowerShell functions. This assumes function f's signature is f($a, $b, $c):

Syntax pitfalls of a function call

Thus, one can call a function with space-separated positional parameters or order-independent named parameters. The other pitfalls reveal that you need to be cognizant of commas, parentheses, and white space.

For further reading, see my article Down the Rabbit Hole: A Study in PowerShell Pipelines, Functions, and Parameters. The article contains a link to the quick reference/wall chart as well.

Determine number of pages in a PDF file

One Line:

int pdfPageCount = System.IO.File.ReadAllText("example.pdf").Split(new string[] { "/Type /Page" }, StringSplitOptions.None).Count()-2;

Recommended: ITEXTSHARP

Remote branch is not showing up in "git branch -r"

The remote section also specifies fetch rules. You could add something like this into it to fetch all branches from the remote:

fetch = +refs/heads/*:refs/remotes/origin/*

(Or replace origin with bitbucket.)

Please read about it here: 10.5 Git Internals - The Refspec

More Pythonic Way to Run a Process X Times

There is not a really pythonic way of repeating something. However, it is a better way:

map(lambda index:do_something(), xrange(10))

If you need to pass the index then:

map(lambda index:do_something(index), xrange(10))

Consider that it returns the results as a collection. So, if you need to collect the results it can help.

How can I send a file document to the printer and have it print?

The following code snippet is an adaptation of Kendall Bennett's code for printing pdf files using the PdfiumViewer library. The main difference is that a Stream is used rather than a file.

public bool PrintPDF(
    string printer,
    string paperName,
    int copies, Stream stream)
        {
            try
            {
                // Create the printer settings for our printer
                var printerSettings = new PrinterSettings
                {
                    PrinterName = printer,
                    Copies = (short)copies,
                };

            // Create our page settings for the paper size selected
            var pageSettings = new PageSettings(printerSettings)
            {
                Margins = new Margins(0, 0, 0, 0),
            };
            foreach (PaperSize paperSize in printerSettings.PaperSizes)
            {
                if (paperSize.PaperName == paperName)
                {
                    pageSettings.PaperSize = paperSize;
                    break;
                }
            }

            // Now print the PDF document
            using (var document = PdfiumViewer.PdfDocument.Load(stream))
            {
                using (var printDocument = document.CreatePrintDocument())
                {
                    printDocument.PrinterSettings = printerSettings;
                    printDocument.DefaultPageSettings = pageSettings;
                    printDocument.PrintController = new StandardPrintController();
                    printDocument.Print();
                }
            }
            return true;
        }
        catch (System.Exception e)
        {
            return false;
        }
    }

In my case I am generating the PDF file using a library called PdfSharp and then saving the document to a Stream like so:

        PdfDocument pdf = PdfGenerator.GeneratePdf(printRequest.html, PageSize.A4);
        pdf.AddPage();

        MemoryStream stream = new MemoryStream();
        pdf.Save(stream);
        MemoryStream stream2 = new MemoryStream(stream.ToArray());

One thing that I want to point out that might be helpful to other developers is that I had to install the 32 bit version of the pdfuim native dll in order for the printing to work even though I am running Windows 10 64 bit. I installed the following two NuGet packages using the NuGet package manager in Visual Studio:

  • PdfiumViewer
  • PdfiumViewer.Native.x86.v8-xfa

Difference between Width:100% and width:100vw?

Havengard's answer doesn't seem to be strictly true. I've found that vw fills the viewport width, but doesn't account for the scrollbars. So, if your content is taller than the viewport (so that your site has a vertical scrollbar), then using vw results in a small horizontal scrollbar. I had to switch out width: 100vw for width: 100% to get rid of the horizontal scrollbar.

What does java.lang.Thread.interrupt() do?

Thread interruption is based on flag interrupt status. For every thread default value of interrupt status is set to false. Whenever interrupt() method is called on thread, interrupt status is set to true.

  1. If interrupt status = true (interrupt() already called on thread), that particular thread cannot go to sleep. If sleep is called on that thread interrupted exception is thrown. After throwing exception again flag is set to false.
  2. If thread is already sleeping and interrupt() is called, thread will come out of sleeping state and throw interrupted Exception.

How can I upload fresh code at github?

You can create GitHub repositories via the command line using their Repositories API (http://develop.github.com/p/repo.html)

Check Creating github repositories with command line | Do it yourself Android for example usage.

Install numpy on python3.3 - Install pip for python3

My issue was the failure to import numpy into my python files. I was receiving the "ModuleNotFoundError: No module named 'numpy'". I ran into the same issue and I was not referencing python3 on the installation of numpy. I inputted the following into my terminal for OSX and my problems were solved:

python3 -m pip install numpy

Finding element in XDocument?

My experience when working with large & complicated XML files is that sometimes neither Elements nor Descendants seem to work in retrieving a specific Element (and I still do not know why).

In such cases, I found that a much safer option is to manually search for the Element, as described by the following MSDN post:

https://social.msdn.microsoft.com/Forums/vstudio/en-US/3d457c3b-292c-49e1-9fd4-9b6a950f9010/how-to-get-tag-name-of-xml-by-using-xdocument?forum=csharpgeneral

In short, you can create a GetElement function:

private XElement GetElement(XDocument doc,string elementName)
{
    foreach (XNode node in doc.DescendantNodes())
    {
        if (node is XElement)
        {
            XElement element = (XElement)node;
            if (element.Name.LocalName.Equals(elementName))
                return element;
        }
    }
    return null;
}

Which you can then call like this:

XElement element = GetElement(doc,"Band");

Note that this will return null if no matching element is found.

Session only cookies with Javascript

For creating session only cookie with java script, you can use the following. This works for me.

document.cookie = "cookiename=value; expires=0; path=/";

then get cookie value as following

 //get cookie 
var cookiename = getCookie("cookiename");
if (cookiename == "value") {
    //write your script
}

//function getCookie        
function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
    }
    return "";
}

Okay to support IE we can leave "expires" completely and can use this

document.cookie = "mtracker=somevalue; path=/";

How to install Jdk in centos

Here is something that might help. Use the root privileges. if you have .bin then simply add the execution permission to the bin file.

chmod a+x jdk*.bin

next step is to run the .bin file which is simply

./jdk*.bin in the location you want to install.

you are done.

Adding elements to a C# array

You can use this snippet:

static void Main(string[] args)
{



        Console.WriteLine("Enter number:");
        int fnum = 0;
        bool chek = Int32.TryParse(Console.ReadLine(),out fnum);            


        Console.WriteLine("Enter number:");
        int snum = 0;
        chek = Int32.TryParse(Console.ReadLine(),out snum);


        Console.WriteLine("Enter number:");
        int thnum = 0;
        chek = Int32.TryParse(Console.ReadLine(),out thnum);


        int[] arr = AddToArr(fnum,snum,thnum);

        IOrderedEnumerable<int> oarr = arr.OrderBy(delegate(int s)
        {  
            return s;
        });


        Console.WriteLine("Here your result:");


        oarr.ToList().FindAll(delegate(int num) {

            Console.WriteLine(num);

            return num > 0;

        });



}



public static int[] AddToArr(params int[] arr) {

    return arr;
}

I hope this will help to you, just change the type

jQuery scrollTop() doesn't seem to work in Safari or Chrome (Windows)

The browser support status is this:

IE8, Firefox, Opera: $("html")

Chrome, Safari: $("body")

So this works:

bodyelem = $.browser.safari ? $("body") : $("html") ;
bodyelem.animate( {scrollTop: 0}, 500 );

Exception is never thrown in body of corresponding try statement

As pointed out in the comments, you cannot catch an exception that's not thrown by the code within your try block. Try changing your code to:

try{
    Integer.parseInt(args[i-1]); // this only throws a NumberFormatException
}
catch(NumberFormatException e){
    throw new MojException("Bledne dane");
}

Always check the documentation to see what exceptions are thrown by each method. You may also wish to read up on the subject of checked vs unchecked exceptions before that causes you any confusion in the future.

Getting Google+ profile picture url with user_id

Approach 1: (no longer works)

https://plus.google.com/s2/photos/profile/<user_id>?sz=<your_desired_size>

Approach 2: (each request counts in your api rate limits which is 10k requests per day for free)

https://www.googleapis.com/plus/v1/people/<user_id>?fields=image&key={YOUR_API_KEY}

with the following response format:

{ "image": { "url": "lh5.googleusercontent.com/-keLR5zGxWOg/.../photo.jpg?sz=50"; } }

Approach 3: (donot require api key)

http://picasaweb.google.com/data/entry/api/user/<user_id>?alt=json

in the json response you get a property named "gphoto$thumbnail", which contains the profile picture url like the following:

http://lh6.ggpht.com/-btLsReiDeF0/AAAAAAAAAAI/AAAAAAAAAAA/GXBpycNk984/s64-c/filename.jpg

You may notice in the url the portion "s64-c" which means the image size to be 64, I've tried using other values like "s100-c" and they worked. Also if you remove the "s64-c" part and append the "?sz=100" parameter, that will also work as of now. Though this is not very good way of getting the profile picture of a gplus user, but the advantage is it do not require any api key.

What does the function then() mean in JavaScript?

Here is a thing I made for myself to clear out how things work. I guess others too can find this concrete example useful:

_x000D_
_x000D_
doit().then(function() { log('Now finally done!') });_x000D_
log('---- But notice where this ends up!');_x000D_
_x000D_
// For pedagogical reasons I originally wrote the following doit()-function so that _x000D_
// it was clear that it is a promise. That way wasn't really a normal way to do _x000D_
// it though, and therefore Slikts edited my answer. I therefore now want to remind _x000D_
// you here that the return value of the following function is a promise, because _x000D_
// it is an async function (every async function returns a promise). _x000D_
async function doit() {_x000D_
  log('Calling someTimeConsumingThing');_x000D_
  await someTimeConsumingThing();_x000D_
  log('Ready with someTimeConsumingThing');_x000D_
}_x000D_
_x000D_
function someTimeConsumingThing() {_x000D_
  return new Promise(function(resolve,reject) {_x000D_
    setTimeout(resolve, 2000);_x000D_
  })_x000D_
}_x000D_
_x000D_
function log(txt) {_x000D_
  document.getElementById('msg').innerHTML += txt + '<br>'_x000D_
}
_x000D_
<div id='msg'></div>
_x000D_
_x000D_
_x000D_

Express.js - app.listen vs server.listen

Express is basically a wrapper of http module that is created for the ease of the developers in such a way that..

  1. They can set up middlewares to respond to HTTP Requests (easily) using express.
  2. They can dynamically render HTML Pages based on passing arguments to templates using express.
  3. They can also define routing easily using express.

How can I check if a JSON is empty in NodeJS?

You can use this:

var isEmpty = function(obj) {
  return Object.keys(obj).length === 0;
}

or this:

function isEmpty(obj) {
  return !Object.keys(obj).length > 0;
}

You can also use this:

function isEmpty(obj) {
  for(var prop in obj) {
    if(obj.hasOwnProperty(prop))
      return false;
  }

  return true;
}

If using underscore or jQuery, you can use their isEmpty or isEmptyObject calls.

How do I extract text that lies between parentheses (round brackets)?

string input = "User name (sales)";

string output = input.Substring(input.IndexOf('(') + 1, input.IndexOf(')') - input.IndexOf('(') - 1);

Is the buildSessionFactory() Configuration method deprecated in Hibernate

In hibernate 5.3.1, you can try this:

ServiceRegistry standardRegistry = 
                new StandardServiceRegistryBuilder().configure().build();

Metadata sources = new MetadataSources(standardRegistry).addAnnotatedClass(MyEntity.class).getMetadataBuilder().build();

SessionFactory sf = sources.buildSessionFactory();

How to create a file in Android?

I used the following code to create a temporary file for writing bytes. And its working fine.

File file = new File(Environment.getExternalStorageDirectory() + "/" + File.separator + "test.txt");
file.createNewFile();
byte[] data1={1,1,0,0};
//write the bytes in file
if(file.exists())
{
     OutputStream fo = new FileOutputStream(file);              
     fo.write(data1);
     fo.close();
     System.out.println("file created: "+file);
}               

//deleting the file             
file.delete();
System.out.println("file deleted");

Detect when an HTML5 video finishes

You can simply add onended="myFunction()" to your video tag.

<video onended="myFunction()">
  ...
  Your browser does not support the video tag.
</video>

<script type='text/javascript'>
  function myFunction(){
    console.log("The End.")
  }
</script>

How unique is UUID?

Very safe:

the annual risk of a given person being hit by a meteorite is estimated to be one chance in 17 billion, which means the probability is about 0.00000000006 (6 × 10-11), equivalent to the odds of creating a few tens of trillions of UUIDs in a year and having one duplicate. In other words, only after generating 1 billion UUIDs every second for the next 100 years, the probability of creating just one duplicate would be about 50%.

Caveat:

However, these probabilities only hold when the UUIDs are generated using sufficient entropy. Otherwise, the probability of duplicates could be significantly higher, since the statistical dispersion might be lower. Where unique identifiers are required for distributed applications, so that UUIDs do not clash even when data from many devices is merged, the randomness of the seeds and generators used on every device must be reliable for the life of the application. Where this is not feasible, RFC4122 recommends using a namespace variant instead.

Source: The Random UUID probability of duplicates section of the Wikipedia article on Universally unique identifiers (link leads to a revision from December 2016 before editing reworked the section).

Also see the current section on the same subject on the same Universally unique identifier article, Collisions.

How to embed fonts in CSS?

One of the best source of information on this topic is Paul Irish's Bulletproof @font-face syntax article.

Read it and you will end with something like:

/* definition */
@font-face {
  font-family: EntezareZohoor2;
  src: url('fonts/EntezareZohoor2.eot');
  src: url('fonts/EntezareZohoor2.eot?') format('?'),
       url('fonts/EntezareZohoor2.woff') format('woff'),
       url('fonts/EntezareZohoor2.ttf') format('truetype');
  font-weight: normal;
  font-style: normal;
}

/* use */
body {
    font-family: EntezareZohoor2, Tahoma, serif;
}

How to remove "index.php" in codeigniter's path

All above methods failed for me and then I found that I was not changing AllowOverride None to AllowOverride All in my virtual host file at /etc/apache2/sites-available/default

<VirtualHost *:80>
    ServerAdmin webmaster@localhost

    DocumentRoot /var/www
    <Directory />
            Options FollowSymLinks
            AllowOverride All    <---- replace None with All
    </Directory>
    <Directory /var/www >
            Options Indexes FollowSymLinks MultiViews
            AllowOverride All   <---  replace None with All
            Order allow,deny
            allow from all
    </Directory>

     ...

How can I get the last 7 characters of a PHP string?

Safer results for working with multibyte character codes, allways use mb_substr instead substr. Example for utf-8:

$str = 'Ne zaman seni düsünsem';
echo substr( $str, -7 ) . ' <strong>is not equal to</strong> ' .
  mb_substr( $str, -7, null, 'UTF-8') ;

Output of git branch in tree like fashion

It's not quite what you asked for, but

git log --graph --simplify-by-decoration --pretty=format:'%d' --all

does a pretty good job. It shows tags and remote branches as well. This may not be desirable for everyone, but I find it useful. --simplifiy-by-decoration is the big trick here for limiting the refs shown.

I use a similar command to view my log. I've been able to completely replace my gitk usage with it:

git log --graph --oneline --decorate --all

I use it by including these aliases in my ~/.gitconfig file:

[alias]
    l = log --graph --oneline --decorate
    ll = log --graph --oneline --decorate --branches --tags
    lll = log --graph --oneline --decorate --all

Edit: Updated suggested log command/aliases to use simpler option flags.

Preferred way of getting the selected item of a JComboBox

If you have only put (non-null) String references in the JComboBox, then either way is fine.

However, the first solution would also allow for future modifications in which you insert Integers, Doubless, LinkedLists etc. as items in the combo box.

To be robust against null values (still without casting) you may consider a third option:

String x = String.valueOf(JComboBox.getSelectedItem());

How to change XAMPP apache server port?

If the XAMPP server is running for the moment, stop XAMPP server.

Follow these steps to change the port number.

Open the file in following location.

[XAMPP Installation Folder]/apache/conf/httpd.conf

Open the httpd.conf file and search for the String:

Listen 80

This is the port number used by XAMMP.

Then search for the string ServerName and update the Port Number which you entered earlier for Listen

Now save and re-start XAMPP server.

Check if a string has a certain piece of text

Here you go: ES5

var test = 'Hello World';
if( test.indexOf('World') >= 0){
  // Found world
}

With ES6 best way would be to use includes function to test if the string contains the looking work.

const test = 'Hello World';
if (test.includes('World')) { 
  // Found world
}

How do I tell Spring Boot which main class to use for the executable jar?

For those using Gradle (instead of Maven), referencing here:

The main class can also be configured explicitly using the task’s mainClassName property:

bootJar {
    mainClassName = 'com.example.ExampleApplication'
}

Alternatively, the main class name can be configured project-wide using the mainClassName property of the Spring Boot DSL:

springBoot {
    mainClassName = 'com.example.ExampleApplication'
}

AttributeError: 'numpy.ndarray' object has no attribute 'append'

Use numpy.concatenate(list1 , list2) or numpy.append() Look into the thread at Append a NumPy array to a NumPy array.

How to run Conda?

I also was facing the same issue ,this might be the simplest possible solution

source anaconda/bin/activate

for anaconda2 use

source anaconda2/bin/activate

depending on the name of the directory , then execute your command i.e. conda --create

How to store NULL values in datetime fields in MySQL?

MySQL does allow NULL values for datetime fields. I just tested it:

mysql> create table datetimetest (testcolumn datetime null default null);
Query OK, 0 rows affected (0.10 sec)

mysql> insert into datetimetest (testcolumn) values (null);
Query OK, 1 row affected (0.00 sec)

mysql> select * from datetimetest;
+------------+
| testcolumn |
+------------+
| NULL       | 
+------------+
1 row in set (0.00 sec)

I'm using this version:

mysql> select version();
+-----------+
| version() |
+-----------+
| 5.0.45    | 
+-----------+
1 row in set (0.03 sec)

EDIT #1: I see in your edit that the error message you are getting in PHP indicates that you are passing an empty string (i.e. ''), not null. An empty string is different than null and is not a valid datetime value which is why you are getting that error message. You must pass the special sql keyword null if that's what you mean. Also, don't put any quotes around the word null. See my insert statement above for an example of how to insert null.

EDIT #2: Are you using PDO? If so, when you bind your null param, make sure to use the [PDO::PARAM_NULL][1] type when binding a null. See the answer to this stackoverflow question on how to properly insert null using PDO.

Saving a select count(*) value to an integer (SQL Server)

select @myInt = COUNT(*) from myTable

Faking an RS232 Serial Port

There's always the hardware route. Purchase two USB to serial converters, and connect them via a NULL modem.

Pro tips: 1) Windows may assign new COM ports to the adapters after every device sleep or reboot. 2) The market leaders in chips for USB to serial are Prolific and FTDI. Both companies are battling knockoffs, and may be blocked in future official Windows drivers. The Linux drivers however work fine with the clones.

How to add new contacts in android

It's not that above answers are incorrect, but I find this code extremely easy to understand and therefore I am sharing it here with everyone. And there is also the check for WRITE_CONTACTS permission.

Here is the complete code for how to add phone number, email, website etc to an existing contact.

public static void addNumberToContact(Context context, Long contactRawId, String number) throws RemoteException, OperationApplicationException {
    addInfoToAddressBookContact(
            context,
            contactRawId,
            ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
            ContactsContract.CommonDataKinds.Phone.NUMBER,
            ContactsContract.CommonDataKinds.Phone.TYPE,
            ContactsContract.CommonDataKinds.Phone.TYPE_OTHER,
            number
    );
}

public static void addEmailToContact(Context context, Long contactRawId, String email) throws RemoteException, OperationApplicationException {
    addInfoToAddressBookContact(
            context,
            contactRawId,
            ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE,
            ContactsContract.CommonDataKinds.Email.ADDRESS,
            ContactsContract.CommonDataKinds.Email.TYPE,
            ContactsContract.CommonDataKinds.Email.TYPE_OTHER,
            email
    );
}

public static void addURLToContact(Context context, Long contactRawId, String url) throws RemoteException, OperationApplicationException {
    addInfoToAddressBookContact(
            context,
            contactRawId,
            ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE,
            ContactsContract.CommonDataKinds.Website.URL,
            ContactsContract.CommonDataKinds.Website.TYPE,
            ContactsContract.CommonDataKinds.Website.TYPE_OTHER,
            url
    );
}

private static void addInfoToAddressBookContact(Context context, Long contactRawId, String mimeType, String whatToAdd, String typeKey, int type, String data) throws RemoteException, OperationApplicationException {
    if(ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_CONTACTS) == PackageManager.PERMISSION_DENIED) {
        return;
    }
    ArrayList<ContentProviderOperation> ops = new ArrayList<>();
    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
            .withValue(ContactsContract.Data.RAW_CONTACT_ID, contactRawId)
            .withValue(ContactsContract.Data.MIMETYPE, mimeType)
            .withValue(whatToAdd, data)
            .withValue(typeKey, type)
            .build());
    getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
}

How to paste yanked text into the Vim command line

For pasting something from the system clipboard into the Vim command line ("command mode"), use Ctrl+R followed by +. For me, at least on Ubuntu, Shift+Ins is not working.

PS: I am not sure why Ctrl+R followed by *, which is theoretically the same as Ctrl+R followed by + doesn't seem to work always. I searched and discovered the + version and it seems to work always, at least on my box.

Location of sqlite database on the device

public class MySQLiteOpenHelper extends SQLiteOpenHelper { MySQLiteOpenHelper(Context context) { super(context, "/mnt/sdcard/database_name.db", null, 0); } }

Do not hardcode "/sdcard/"; use Environment.getExternalStorageDirectory().getPath() instead

Get querystring from URL using jQuery

We do it this way...

String.prototype.getValueByKey = function (k) {
    var p = new RegExp('\\b' + k + '\\b', 'gi');
    return this.search(p) != -1 ? decodeURIComponent(this.substr(this.search(p) + k.length + 1).substr(0, this.substr(this.search(p) + k.length + 1).search(/(&|;|$)/))) : "";
};

Are there any standard exit status codes in Linux?

'1' >>> Catchall for general errors

'2' >>> Misuse of shell builtins (according to Bash documentation)

'126'>>> Command invoked cannot execute

'127'>>>"command not found"

'128'>>> Invalid argument to exit

'128+n'>>>Fatal error signal "n"

'130'>>> Script terminated by Control-C

'255'>>>Exit status out of range

This is for bash. However, for other applications, there are different exit codes.

Convert array to string in NodeJS

toString is a method, so you should add parenthesis () to make the function call.

> a = [1,2,3]
[ 1, 2, 3 ]
> a.toString()
'1,2,3'

Besides, if you want to use strings as keys, then you should consider using a Object instead of Array, and use JSON.stringify to return a string.

> var aa = {}
> aa['a'] = 'aaa'
> JSON.stringify(aa)
'{"a":"aaa","b":"bbb"}'

Detecting a redirect in ajax request?

While the other folks who answered this question are (sadly) correct that this information is hidden from us by the browser, I thought I'd post a workaround I came up with:

I configured my server app to set a custom response header (X-Response-Url) containing the url that was requested. Whenever my ajax code receives a response, it checks if xhr.getResponseHeader("x-response-url") is defined, in which case it compares it to the url that it originally requested via $.ajax(). If the strings differ, I know there was a redirect, and additionally, what url we actually arrived at.

This does have the drawback of requiring some server-side help, and also may break down if the url gets munged (due to quoting/encoding issues etc) during the round trip... but for 99% of cases, this seems to get the job done.


On the server side, my specific case was a python application using the Pyramid web framework, and I used the following snippet:

import pyramid.events

@pyramid.events.subscriber(pyramid.events.NewResponse)
def set_response_header(event):
    request = event.request
    if request.is_xhr:
        event.response.headers['X-Response-URL'] = request.url

Rename Oracle Table or View

In order to rename a table in a different schema, try:

ALTER TABLE owner.mytable RENAME TO othertable;

The rename command (as in "rename mytable to othertable") only supports renaming a table in the same schema.

Plotting dates on the x-axis with Python's matplotlib

I have too low reputation to add comment to @bernie response, with response to @user1506145. I have run in to same issue.

1

The answer to it is a interval parameter which fixes things up

2

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
import datetime as dt

np.random.seed(1)

N = 100
y = np.random.rand(N)

now = dt.datetime.now()
then = now + dt.timedelta(days=100)
days = mdates.drange(now,then,dt.timedelta(days=1))

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=5))
plt.plot(days,y)
plt.gcf().autofmt_xdate()
plt.show()

How can I determine the status of a job?

we can query the msdb in many ways to get the details.

few are

select job.Name, job.job_ID, job.Originating_Server,activity.run_requested_Date,
datediff(minute, activity.run_requested_Date, getdate()) as Elapsed 
from msdb.dbo.sysjobs_view job 
inner join msdb.dbo.sysjobactivity activity on (job.job_id = activity.job_id) 
where run_Requested_date is not null 
and stop_execution_date is null 
and job.name like 'Your Job Prefix%'

How to ignore deprecation warnings in Python

Not to beat you up about it but you are being warned that what you are doing will likely stop working when you next upgrade python. Convert to int and be done with it.

BTW. You can also write your own warnings handler. Just assign a function that does nothing. How to redirect python warnings to a custom stream?

Do I need to pass the full path of a file in another directory to open()?

Yes, you need the full path.

log = open(os.path.join(root, f), 'r')

Is the quick fix. As the comment pointed out, os.walk decends into subdirs so you do need to use the current directory root rather than indir as the base for the path join.

Operation Not Permitted when on root - El Capitan (rootless disabled)

If after calling "csrutil disabled" still your command does not work, try with "sudo" in terminal, for example:

sudo mv geckodriver /usr/local/bin

And it should work.

Getting number of elements in an iterator in Python

One simple way is using set() built-in function:

iter = zip([1,2,3],['a','b','c'])
print(len(set(iter)) # set(iter) = {(1, 'a'), (2, 'b'), (3, 'c')}
Out[45]: 3

or

iter = range(1,10)
print(len(set(iter)) # set(iter) = {1, 2, 3, 4, 5, 6, 7, 8, 9}
Out[47]: 9

Filtering JSON array using jQuery grep()

_x000D_
_x000D_
var data = {_x000D_
  "items": [{_x000D_
    "id": 1,_x000D_
    "category": "cat1"_x000D_
  }, {_x000D_
    "id": 2,_x000D_
    "category": "cat2"_x000D_
  }, {_x000D_
    "id": 3,_x000D_
    "category": "cat1"_x000D_
  }, {_x000D_
    "id": 4,_x000D_
    "category": "cat2"_x000D_
  }, {_x000D_
    "id": 5,_x000D_
    "category": "cat1"_x000D_
  }]_x000D_
};_x000D_
//Filters an array of numbers to include only numbers bigger then zero._x000D_
//Exact Data you want..._x000D_
var returnedData = $.grep(data.items, function(element) {_x000D_
  return element.category === "cat1" && element.id === 3;_x000D_
}, false);_x000D_
console.log(returnedData);_x000D_
$('#id').text('Id is:-' + returnedData[0].id)_x000D_
$('#category').text('Category is:-' + returnedData[0].category)_x000D_
//Filter an array of numbers to include numbers that are not bigger than zero._x000D_
//Exact Data you don't want..._x000D_
var returnedOppositeData = $.grep(data.items, function(element) {_x000D_
  return element.category === "cat1";_x000D_
}, true);_x000D_
console.log(returnedOppositeData);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<p id='id'></p>_x000D_
<p id='category'></p>
_x000D_
_x000D_
_x000D_

The $.grep() method eliminates items from an array as necessary so that only remaining items carry a given search. The test is a function that is passed an array item and the index of the item within the array. Only if the test returns true will the item be in the result array.

How to select date without time in SQL

If you want to return a date type as just a date use

CONVERT(date, SYSDATETIME())

or

SELECT CONVERT(date,SYSDATETIME()) 

or

DECLARE @DateOnly Datetime
SET @DateOnly=CONVERT(date,SYSDATETIME())

PHP session handling errors

please make sure the session.save_path is set correctly in the php.ini. php needs read/write access to the directory to which this variable is set.

more information: http://www.php.net/manual/en/session.configuration.php#ini.session.save-path

Are arrays passed by value or passed by reference in Java?

The definitive discussion of arrays is at http://docs.oracle.com/javase/specs/jls/se5.0/html/arrays.html#27803 . This makes clear that Java arrays are objects. The class of these objects is defined in 10.8.

Section 8.4.1 of the language spec, http://docs.oracle.com/javase/specs/jls/se5.0/html/classes.html#40420 , describe how arguments are passed to methods. Since Java syntax is derived from C and C++, the behavior is similar. Primitive types are passed by value, as with C. When an object is passed, an object reference (pointer) is passed by value, mirroring the C syntax of passing a pointer by value. See 4.3.1, http://docs.oracle.com/javase/specs/jls/se5.0/html/typesValues.html#4.3 ,

In practical terms, this means that modifying the contents of an array within a method is reflected in the array object in the calling scope, but reassigning a new value to the reference within the method has no effect on the reference in the calling scope, which is exactly the behavior you would expect of a pointer to a struct in C or an object in C++.

At least part of the confusion in terminology stems from the history of high level languages prior to the common use of C. In prior, popular, high level languages, directly referencing memory by address was something to be avoided to the extent possible, and it was considered the job of the language to provide a layer of abstraction. This made it necessary for the language to explicitly support a mechanism for returning values from subroutines (not necessarily functions). This mechanism is what is formally meant when referring to 'pass by reference'.

When C was introduced, it came with a stripped down notion of procedure calling, where all arguments are input-only, and the only value returned to the caller is a function result. However, the purpose of passing references could be achieved through the explicit and broad use of pointers. Since it serves the same purpose, the practice of passing a pointer as a reference to a value is often colloquially referred to a passing by reference. If the semantics of a routine call for a parameter to be passed by reference, the syntax of C requires the programmer to explicitly pass a pointer. Passing a pointer by value is the design pattern for implementing pass by reference semantics in C.

Since it can often seem like the sole purpose of raw pointers in C is to create crashing bugs, subsequent developments, especially Java, have sought to return to safer means to pass parameters. However, the dominance of C made it incumbent on the developers to mimic the familiar style of C coding. The result is references that are passed similarly to pointers, but are implemented with more protections to make them safer. An alternative would have been the rich syntax of a language like Ada, but this would have presented the appearance of an unwelcome learning curve, and lessened the likely adoption of Java.

In short, the design of parameter passing for objects, including arrays, in Java,is esentially to serve the semantic intent of pass by reference, but is imlemented with the syntax of passing a reference by value.

SQL Server stored procedure parameters

Why would you pass a parameter to a stored procedure that doesn't use it?

It sounds to me like you might be better of building dynamic SQL statements and then executing them. What you are trying to do with the SP won't work, and even if you could change what you are doing in such a way to accommodate varying numbers of parameters, you would then essentially be using dynamically generated SQL you are defeating the purpose of having/using a SP in the first place. SP's have a role, but there are not the solution in all cases.

Switch statement equivalent in Windows batch file

I ended up using label names containing the values for the case expressions as suggested by AjV Jsy. Anyway, I use CALL instead of GOTO to jump into the correct case block and GOTO :EOF to jump back. The following sample code is a complete batch script illustrating the idea.

@ECHO OFF

SET /P COLOR="Choose a background color (type red, blue or black): "

2>NUL CALL :CASE_%COLOR% # jump to :CASE_red, :CASE_blue, etc.
IF ERRORLEVEL 1 CALL :DEFAULT_CASE # If label doesn't exist

ECHO Done.
EXIT /B

:CASE_red
  COLOR CF
  GOTO END_CASE
:CASE_blue
  COLOR 9F
  GOTO END_CASE
:CASE_black
  COLOR 0F
  GOTO END_CASE
:DEFAULT_CASE
  ECHO Unknown color "%COLOR%"
  GOTO END_CASE
:END_CASE
  VER > NUL # reset ERRORLEVEL
  GOTO :EOF # return from CALL

Android Studio Rendering Problems : The following classes could not be found

I faced this error when I created second activity in my project in the newly updated Android Studio,I solved it simply by copy pasting the whole xml code from first layout to the second and then I just removed the code that's unnecessary.

How to submit a form when the return key is pressed?

Since display: none buttons and inputs won't work in Safari and IE, I found that the easiest way, requiring no extra javascript hacks, is to simply add an absolutely positioned <button /> to the form and place it far off screen.

<form action="" method="get">
  <input type="text" name="name" />
  <input type="password" name="password" />
  <div class="yourCustomDiv"/>
  <button style="position:absolute;left:-10000px;right:9990px"/>
</form>

This works in the current version of all major browsers as of September 2016.

Obviously its reccomended (and more semantically correct) to just style the <button/> as desired.

"Find next" in Vim

If you press Ctrl + Enter after you press something like "/wordforsearch", then you can find the word "wordforsearch" in the current line. Then press n for the next match; press N for previous match.

Building and running app via Gradle and Android Studio is slower than via Eclipse

Following the steps will make it 10 times faster and reduce build time 90%

First create a file named gradle.properties in the following directory:

/home/<username>/.gradle/ (Linux)
/Users/<username>/.gradle/ (Mac)
C:\Users\<username>\.gradle (Windows)

Add this line to the file:

org.gradle.daemon=true
org.gradle.parallel=true

And check this options in Android Studio

enter image description here

JSON Structure for List of Objects

The first one is invalid syntax. You cannot have object properties inside a plain array. The second one is right although it is not strict JSON. It's a relaxed form of JSON wherein quotes in string keys are omitted.

This tutorial by Patrick Hunlock, may help to learn about JSON and this site may help to validate JSON.

Regex to get NUMBER only from String

The answers above are great. If you are in need of parsing all numbers out of a string that are nonconsecutive then the following may be of some help:

string input = "1-205-330-2342";
string result = Regex.Replace(input, @"[^\d]", "");
Console.WriteLine(result); // >> 12053302342

How to use apply a custom drawable to RadioButton?

if you want to change the only icon of radio button then you can only add android:button="@drawable/ic_launcher" to your radio button and for making sensitive on click then you have to use the selector

 <?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@drawable/image_what_you_want_on_select_state" android:state_checked="true"/>
<item android:drawable="@drawable/image_what_you_want_on_un_select_state"    android:state_checked="false"/>


 </selector>

and set to your radio android:background="@drawable/name_of_selector"

How to find the last field using 'cut'

There are multiple ways. You may use this too.

echo "Your string here"| tr ' ' '\n' | tail -n1
> here

Obviously, the blank space input for tr command should be replaced with the delimiter you need.

How to install both Python 2.x and Python 3.x in Windows

I did this in three steps by following the instructions here: This is all taken directly from here: http://ipython.readthedocs.io/en/stable/install/kernel_install.html. I'm currently running Python 2.x on Windows 8 and have Anaconda 4.2.13 installed.

1) First install the latest version of python:

conda create -n python3 python=3 ipykernel

2) Next activate python3

activate python3

3) Install the kernel:

python -m ipykernel install --user

If you have Python 3 installed and want to install 2, switch the 2 and the 3 above. When you open a new notebook, you can now choose between Python 2 or 3.

Algorithm to compare two images

If you're running Linux I would suggest two tools:

align_image_stack from package hugin-tools - is a commandline program that can automatically correct rotation, scaling, and other distortions (it's mostly intended for compositing HDR photography, but works for video frames and other documents too). More information: http://hugin.sourceforge.net/docs/manual/Align_image_stack.html

compare from package imagemagick - a program that can find and count the amount of different pixels in two images. Here's a neat tutorial: http://www.imagemagick.org/Usage/compare/ uising the -fuzz N% you can increase the error tolerance. The higher the N the higher the error tolerance to still count two pixels as the same.

align_image_stack should correct any offset so the compare command will actually have a chance of detecting same pixels.

How to view UTF-8 Characters in VIM or Gvim

I couldn't get any other fonts I installed to show up in my Windows GVim editor, so I just switched to Lucida Console which has at least somewhat better UTF-8 support. Add this to the end of your _vimrc:

" For making everything utf-8
set enc=utf-8
set guifont=Lucida_Console:h9:cANSI
set guifontwide=Lucida_Console:h12

Now I see at least some UTF-8 characters.

Find the max of two or more columns with pandas

You can get the maximum like this:

>>> import pandas as pd
>>> df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
>>> df
   A  B
0  1 -2
1  2  8
2  3  1
>>> df[["A", "B"]]
   A  B
0  1 -2
1  2  8
2  3  1
>>> df[["A", "B"]].max(axis=1)
0    1
1    8
2    3

and so:

>>> df["C"] = df[["A", "B"]].max(axis=1)
>>> df
   A  B  C
0  1 -2  1
1  2  8  8
2  3  1  3

If you know that "A" and "B" are the only columns, you could even get away with

>>> df["C"] = df.max(axis=1)

And you could use .apply(max, axis=1) too, I guess.

How to set image to UIImage

You can't alloc UIImage, this is impossible. Proper code with UIImageView allocate:

UIImageView *_image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"something.png"]] ;

Draw image:

CGContextDrawImage(context, rect, _image.image.CGImage);

Java converting Image to BufferedImage

If you are getting back a sun.awt.image.ToolkitImage, you can cast the Image to that, and then use getBufferedImage() to get the BufferedImage.

So instead of your last line of code where you are casting you would just do:

BufferedImage buffered = ((ToolkitImage) image).getBufferedImage();

Why doesn't JavaScript support multithreading?

Do you mean why doesn't the language support multithreading or why don't JavaScript engines in browsers support multithreading?

The answer to the first question is that JavaScript in the browser is meant to be run in a sandbox and in a machine/OS-independent way, to add multithreading support would complicate the language and tie the language too closely to the OS.

Get list of Excel files in a folder using VBA

Regarding the upvoted answer, I liked it except that if the resulting "listfiles" array is used in an array formula {CSE}, the list values come out all in a horizontal row. To make them come out in a vertical column, I simply made the array two dimensional as follows:

ReDim vaArray(1 To oFiles.Count, 0)
i = 1
For Each oFile In oFiles
    vaArray(i, 0) = oFile.Name
    i = i + 1
Next

What does AngularJS do better than jQuery?

Data-Binding

You go around making your webpage, and keep on putting {{data bindings}} whenever you feel you would have dynamic data. Angular will then provide you a $scope handler, which you can populate (statically or through calls to the web server).

This is a good understanding of data-binding. I think you've got that down.

DOM Manipulation

For simple DOM manipulation, which doesnot involve data manipulation (eg: color changes on mousehover, hiding/showing elements on click), jQuery or old-school js is sufficient and cleaner. This assumes that the model in angular's mvc is anything that reflects data on the page, and hence, css properties like color, display/hide, etc changes dont affect the model.

I can see your point here about "simple" DOM manipulation being cleaner, but only rarely and it would have to be really "simple". I think DOM manipulation is one the areas, just like data-binding, where Angular really shines. Understanding this will also help you see how Angular considers its views.

I'll start by comparing the Angular way with a vanilla js approach to DOM manipulation. Traditionally, we think of HTML as not "doing" anything and write it as such. So, inline js, like "onclick", etc are bad practice because they put the "doing" in the context of HTML, which doesn't "do". Angular flips that concept on its head. As you're writing your view, you think of HTML as being able to "do" lots of things. This capability is abstracted away in angular directives, but if they already exist or you have written them, you don't have to consider "how" it is done, you just use the power made available to you in this "augmented" HTML that angular allows you to use. This also means that ALL of your view logic is truly contained in the view, not in your javascript files. Again, the reasoning is that the directives written in your javascript files could be considered to be increasing the capability of HTML, so you let the DOM worry about manipulating itself (so to speak). I'll demonstrate with a simple example.

This is the markup we want to use. I gave it an intuitive name.

<div rotate-on-click="45"></div>

First, I'd just like to comment that if we've given our HTML this functionality via a custom Angular Directive, we're already done. That's a breath of fresh air. More on that in a moment.

Implementation with jQuery

live demo here (click).

function rotate(deg, elem) {
  $(elem).css({
    webkitTransform: 'rotate('+deg+'deg)', 
    mozTransform: 'rotate('+deg+'deg)', 
    msTransform: 'rotate('+deg+'deg)', 
    oTransform: 'rotate('+deg+'deg)', 
    transform: 'rotate('+deg+'deg)'    
  });
}

function addRotateOnClick($elems) {
  $elems.each(function(i, elem) {
    var deg = 0;
    $(elem).click(function() {
      deg+= parseInt($(this).attr('rotate-on-click'), 10);
      rotate(deg, this);
    });
  });
}

addRotateOnClick($('[rotate-on-click]'));

Implementation with Angular

live demo here (click).

app.directive('rotateOnClick', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var deg = 0;
      element.bind('click', function() {
        deg+= parseInt(attrs.rotateOnClick, 10);
        element.css({
          webkitTransform: 'rotate('+deg+'deg)', 
          mozTransform: 'rotate('+deg+'deg)', 
          msTransform: 'rotate('+deg+'deg)', 
          oTransform: 'rotate('+deg+'deg)', 
          transform: 'rotate('+deg+'deg)'    
        });
      });
    }
  };
});

Pretty light, VERY clean and that's just a simple manipulation! In my opinion, the angular approach wins in all regards, especially how the functionality is abstracted away and the dom manipulation is declared in the DOM. The functionality is hooked onto the element via an html attribute, so there is no need to query the DOM via a selector, and we've got two nice closures - one closure for the directive factory where variables are shared across all usages of the directive, and one closure for each usage of the directive in the link function (or compile function).

Two-way data binding and directives for DOM manipulation are only the start of what makes Angular awesome. Angular promotes all code being modular, reusable, and easily testable and also includes a single-page app routing system. It is important to note that jQuery is a library of commonly needed convenience/cross-browser methods, but Angular is a full featured framework for creating single page apps. The angular script actually includes its own "lite" version of jQuery so that some of the most essential methods are available. Therefore, you could argue that using Angular IS using jQuery (lightly), but Angular provides much more "magic" to help you in the process of creating apps.

This is a great post for more related information: How do I “think in AngularJS” if I have a jQuery background?

General differences.

The above points are aimed at the OP's specific concerns. I'll also give an overview of the other important differences. I suggest doing additional reading about each topic as well.

Angular and jQuery can't reasonably be compared.

Angular is a framework, jQuery is a library. Frameworks have their place and libraries have their place. However, there is no question that a good framework has more power in writing an application than a library. That's exactly the point of a framework. You're welcome to write your code in plain JS, or you can add in a library of common functions, or you can add a framework to drastically reduce the code you need to accomplish most things. Therefore, a more appropriate question is:

Why use a framework?

Good frameworks can help architect your code so that it is modular (therefore reusable), DRY, readable, performant and secure. jQuery is not a framework, so it doesn't help in these regards. We've all seen the typical walls of jQuery spaghetti code. This isn't jQuery's fault - it's the fault of developers that don't know how to architect code. However, if the devs did know how to architect code, they would end up writing some kind of minimal "framework" to provide the foundation (achitecture, etc) I discussed a moment ago, or they would add something in. For example, you might add RequireJS to act as part of your framework for writing good code.

Here are some things that modern frameworks are providing:

  • Templating
  • Data-binding
  • routing (single page app)
  • clean, modular, reusable architecture
  • security
  • additional functions/features for convenience

Before I further discuss Angular, I'd like to point out that Angular isn't the only one of its kind. Durandal, for example, is a framework built on top of jQuery, Knockout, and RequireJS. Again, jQuery cannot, by itself, provide what Knockout, RequireJS, and the whole framework built on top them can. It's just not comparable.

If you need to destroy a planet and you have a Death Star, use the Death star.

Angular (revisited).

Building on my previous points about what frameworks provide, I'd like to commend the way that Angular provides them and try to clarify why this is matter of factually superior to jQuery alone.

DOM reference.

In my above example, it is just absolutely unavoidable that jQuery has to hook onto the DOM in order to provide functionality. That means that the view (html) is concerned about functionality (because it is labeled with some kind of identifier - like "image slider") and JavaScript is concerned about providing that functionality. Angular eliminates that concept via abstraction. Properly written code with Angular means that the view is able to declare its own behavior. If I want to display a clock:

<clock></clock>

Done.

Yes, we need to go to JavaScript to make that mean something, but we're doing this in the opposite way of the jQuery approach. Our Angular directive (which is in it's own little world) has "augumented" the html and the html hooks the functionality into itself.

MVW Architecure / Modules / Dependency Injection

Angular gives you a straightforward way to structure your code. View things belong in the view (html), augmented view functionality belongs in directives, other logic (like ajax calls) and functions belong in services, and the connection of services and logic to the view belongs in controllers. There are some other angular components as well that help deal with configuration and modification of services, etc. Any functionality you create is automatically available anywhere you need it via the Injector subsystem which takes care of Dependency Injection throughout the application. When writing an application (module), I break it up into other reusable modules, each with their own reusable components, and then include them in the bigger project. Once you solve a problem with Angular, you've automatically solved it in a way that is useful and structured for reuse in the future and easily included in the next project. A HUGE bonus to all of this is that your code will be much easier to test.

It isn't easy to make things "work" in Angular.

THANK GOODNESS. The aforementioned jQuery spaghetti code resulted from a dev that made something "work" and then moved on. You can write bad Angular code, but it's much more difficult to do so, because Angular will fight you about it. This means that you have to take advantage (at least somewhat) to the clean architecture it provides. In other words, it's harder to write bad code with Angular, but more convenient to write clean code.

Angular is far from perfect. The web development world is always growing and changing and there are new and better ways being put forth to solve problems. Facebook's React and Flux, for example, have some great advantages over Angular, but come with their own drawbacks. Nothing's perfect, but Angular has been and is still awesome for now. Just as jQuery once helped the web world move forward, so has Angular, and so will many to come.

How can I parse a string with a comma thousand separator to a number?

On modern browsers you can use the built in Intl.NumberFormat to detect the browser's number formatting and normalize the input to match.

_x000D_
_x000D_
function parseNumber(value, locales = navigator.languages) {
  const example = Intl.NumberFormat(locales).format('1.1');
  const cleanPattern = new RegExp(`[^-+0-9${ example.charAt( 1 ) }]`, 'g');
  const cleaned = value.replace(cleanPattern, '');
  const normalized = cleaned.replace(example.charAt(1), '.');

  return parseFloat(normalized);
}

const corpus = {
  '1.123': {
    expected: 1.123,
    locale: 'en-US'
  },
  '1,123': {
    expected: 1123,
    locale: 'en-US'
  },
  '2.123': {
    expected: 2123,
    locale: 'fr-FR'
  },
  '2,123': {
    expected: 2.123,
    locale: 'fr-FR'
  },
}


for (const candidate in corpus) {
  const {
    locale,
    expected
  } = corpus[candidate];
  const parsed = parseNumber(candidate, locale);

  console.log(`${ candidate } in ${ corpus[ candidate ].locale } == ${ expected }? ${ parsed === expected }`);
}
_x000D_
_x000D_
_x000D_

Their's obviously room for some optimization and caching but this works reliably in all languages.

how to count the spaces in a java string?

Another way using regular expressions

int length = text.replaceAll("[^ ]", "").length();

relative path in require_once doesn't work

In my case it doesn't work, even with __DIR__ or getcwd() it keeps picking the wrong path, I solved by defining a costant in every file I need with the absolute base path of the project:

if(!defined('THISBASEPATH')){ define('THISBASEPATH', '/mypath/'); }
require_once THISBASEPATH.'cache/crud.php';
/*every other require_once you need*/

I have MAMP with php 5.4.10 and my folder hierarchy is basilar:

q.php 
w.php 
e.php 
r.php 
cache/a.php 
cache/b.php 
setting/a.php 
setting/b.php

....

How do I replace a double-quote with an escape-char double-quote in a string using JavaScript?

The other answers will work for most strings, but you can end up unescaping an already escaped double quote, which is probably not what you want.

To work correctly, you are going to need to escape all backslashes and then escape all double quotes, like this:

var test_str = '"first \\" middle \\" last "';
var result = test_str.replace(/\\/g, '\\\\').replace(/\"/g, '\\"');

depending on how you need to use the string, and the other escaped charaters involved, this may still have some issues, but I think it will probably work in most cases.

Oracle SQL escape character (for a '&')

select 'one'||'&'||'two' from dual

How to set combobox default value?

Suppose you bound your combobox to a List<Person>

List<Person> pp = new List<Person>();
pp.Add(new Person() {id = 1, name="Steve"});
pp.Add(new Person() {id = 2, name="Mark"});
pp.Add(new Person() {id = 3, name="Charles"});

cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;

At this point you cannot set the Text property as you like, but instead you need to add an item to your list before setting the datasource

pp.Insert(0, new Person() {id=-1, name="--SELECT--"});
cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;
cbo1.SelectedIndex = 0;

Of course this means that you need to add a checking code when you try to use the info from the combobox

if(cbo1.SelectedValue != null && Convert.ToInt32(cbo1.SelectedValue) == -1)
    MessageBox.Show("Please select a person name");
else
    ...... 

The code is the same if you use a DataTable instead of a list. You need to add a fake row at the first position of the Rows collection of the datatable and set the initial index of the combobox to make things clear. The only thing you need to look at are the name of the datatable columns and which columns should contain a non null value before adding the row to the collection

In a table with three columns like ID, FirstName, LastName with ID,FirstName and LastName required you need to

DataRow row = datatable.NewRow();
row["ID"] = -1;
row["FirstName"] = "--Select--";    
row["LastName"] = "FakeAddress";
dataTable.Rows.InsertAt(row, 0);

How do I force detach Screen from another SSH session?

Short answer

  1. Reattach without ejecting others: screen -x
  2. Get list of displays: ^A *, select the one to disconnect, press d


Explained answer

Background: When I was looking for the solution with same problem description, I have always landed on this answer. I would like to provide more sensible solution. (For example: the other attached screen has a different size and a I cannot force resize it in my terminal.)

Note: PREFIX is usually ^A = ctrl+a

Note: the display may also be called:

  • "user front-end" (in at command manual in screen)
  • "client" (tmux vocabulary where this functionality is detach-client)
  • "terminal" (as we call the window in our user interface) /depending on

1. Reattach a session: screen -x

-x attach to a not detached screen session without detaching it

2. List displays of this session: PREFIX *

It is the default key binding for: PREFIX :displays. Performing it within the screen, identify the other display we want to disconnect (e.g. smaller size). (Your current display is displayed in brighter color/bold when not selected).

term-type   size         user interface           window       Perms
---------- ------- ---------- ----------------- ----------     -----
 screen     240x60         you@/dev/pts/2      nb  0(zsh)        rwx
 screen      78x40         you@/dev/pts/0      nb  0(zsh)        rwx

Using arrows ? ?, select the targeted display, press d If nothing happens, you tried to detach your own display and screen will not detach it. If it was another one, within a second or two, the entry will disappear.

Press ENTER to quit the listing.

Optionally: in order to make the content fit your screen, reflow: PREFIX F (uppercase F)

Excerpt from man page of screen:

displays

Shows a tabular listing of all currently connected user front-ends (displays). This is most useful for multiuser sessions. The following keys can be used in displays list:

  • mouseclick Move to the selected line. Available when "mousetrack" is set to on.
  • space Refresh the list
  • d Detach that display
  • D Power detach that display
  • C-g, enter, or escape Exit the list

Smart cast to 'Type' is impossible, because 'variable' is a mutable property that could have been changed by this time

Your most elegant solution must be:

var left: Node? = null

fun show() {
    left?.also {
        queue.add( it )
    }
}

Then you don't have to define a new and unnecessary local variable, and you don't have any new assertions or casts (which are not DRY). Other scope functions could also work so choose your favourite.

Print all key/value pairs in a Java ConcurrentHashMap

Work 100% sure try this code for the get all hashmap key and value

static HashMap<String, String> map = new HashMap<>();

map.put("one"  " a " );
map.put("two"  " b " );
map.put("three"  " c " );
map.put("four"  " d " );

just call this method whenever you want to show the HashMap value

 private void ShowHashMapValue() {

        /**
         * get the Set Of keys from HashMap
         */
        Set setOfKeys = map.keySet();

/**
 * get the Iterator instance from Set
 */
        Iterator iterator = setOfKeys.iterator();

/**
 * Loop the iterator until we reach the last element of the HashMap
 */
        while (iterator.hasNext()) {
/**
 * next() method returns the next key from Iterator instance.
 * return type of next() method is Object so we need to do DownCasting to String
 */
            String key = (String) iterator.next();

/**
 * once we know the 'key', we can get the value from the HashMap
 * by calling get() method
 */
            String value = map.get(key);

            System.out.println("Key: " + key + ", Value: " + value);
        }
    } 

How to add a Browse To File dialog to a VB.NET application

You should use the OpenFileDialog class like this

Dim fd As OpenFileDialog = New OpenFileDialog() 
Dim strFileName As String

fd.Title = "Open File Dialog"
fd.InitialDirectory = "C:\"
fd.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
fd.FilterIndex = 2
fd.RestoreDirectory = True

If fd.ShowDialog() = DialogResult.OK Then
   strFileName = fd.FileName
End If

Then you can use the File class.

How to make child divs always fit inside parent div?

I think I have the solution to your question, assuming you can use flexbox in your project. What you want to do is make #one a flexbox using display: flex and use flex-direction: column to make it a column alignment.

_x000D_
_x000D_
html,_x000D_
body {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
.border {_x000D_
  border: 1px solid black;_x000D_
}_x000D_
_x000D_
.margin {_x000D_
  margin: 5px;_x000D_
}_x000D_
_x000D_
#one {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
_x000D_
#two {_x000D_
  height: 50px;_x000D_
}_x000D_
_x000D_
#three {_x000D_
  width: 100px;_x000D_
  height: 100%;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div id="one" class="border">_x000D_
    <div id="two" class="border margin"></div>_x000D_
    <div id="three" class="border margin"></div>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Custom circle button

here is how you can perform simply, make a drawable resource file in drawable.xml. Say round_button.xml and then paste the following code.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
       <shape
           android:shape="oval">

           <solid
               android:color="@color/button_start_gradient_color"/>
       </shape>
    </item>
    <item
        android:drawable="@drawable/microphone"/>
</layer-list>

Note:- use your own color and drawable resource as i have used @drawable/microphone

Following is the result [1]: https://i.stack.imgur.com/QyhdJ.png

How to disable mouse right click on a web page?

You can use the oncontextmenu event for doing this.

But if the user turns off javascript then you won't be able to handle this.

window.oncontextmenu = function () {
   return false;
}

will disable right click menu.

Create a text file for download on-the-fly

No need to store it anywhere. Just output the content with the appropriate content type.

<?php
    header('Content-type: text/plain');
?>Hello, world.

Add content-disposition if you wish to trigger a download prompt.

header('Content-Disposition: attachment; filename="default-filename.txt"');

What are the differences between ArrayList and Vector?

ArrayList and Vector both implements List interface and maintains insertion order.But there are many differences between ArrayList and Vector classes...

ArrayList -

  1. ArrayList is not synchronized.
  2. ArrayList increments 50% of current array size if number of element exceeds from its capacity.
  3. ArrayList is not a legacy class, it is introduced in JDK 1.2.
  4. ArrayList is fast because it is non-synchronized.
  5. ArrayList uses Iterator interface to traverse the elements.

Vector -

  1. Vector is synchronized.
  2. Vector increments 100% means doubles the array size if total number of element exceeds than its capacity.
  3. Vector is a legacy class.

  4. Vector is slow because it is synchronized i.e. in multithreading environment, it will hold the other threads in runnable or non-runnable state until current thread releases the lock of object.

  5. Vector uses Enumeration interface to traverse the elements. But it can use Iterator also.

See Also : https://www.javatpoint.com/difference-between-arraylist-and-vector

WPF checkbox binding

if you have the property "MyProperty" on your data-class, then you bind the IsChecked like this.... (the converter is optional, but sometimes you need that)

<Window.Resources>
<local:MyBoolConverter x:Key="MyBoolConverterKey"/>
</Window.Resources>
<checkbox IsChecked="{Binding Path=MyProperty, Converter={StaticResource MyBoolConverterKey}}"/>

How to measure time taken between lines of code in python?

I was looking for a way how to output a formatted time with minimal code, so here is my solution. Many people use Pandas anyway, so in some cases this can save from additional library imports.

import pandas as pd
start = pd.Timestamp.now()
# code
print(pd.Timestamp.now()-start)

Output:

0 days 00:05:32.541600

I would recommend using this if time precision is not the most important, otherwise use time library:

%timeit pd.Timestamp.now() outputs 3.29 µs ± 214 ns per loop

%timeit time.time() outputs 154 ns ± 13.3 ns per loop

Auto code completion on Eclipse

Pressing Ctrl+Space opens up the auto-completion dialog in Eclipse. In the Java Perspective it opens automatically after you typed a . (normally with a short delay).

Java synchronized block vs. Collections.synchronizedMap

Yes, you are synchronizing correctly. I will explain this in more detail. You must synchronize two or more method calls on the synchronizedMap object only in a case you have to rely on results of previous method call(s) in the subsequent method call in the sequence of method calls on the synchronizedMap object. Let’s take a look at this code:

synchronized (synchronizedMap) {
    if (synchronizedMap.containsKey(key)) {
        synchronizedMap.get(key).add(value);
    }
    else {
        List<String> valuesList = new ArrayList<String>();
        valuesList.add(value);
        synchronizedMap.put(key, valuesList);
    }
}

In this code

synchronizedMap.get(key).add(value);

and

synchronizedMap.put(key, valuesList);

method calls are relied on the result of the previous

synchronizedMap.containsKey(key)

method call.

If the sequence of method calls were not synchronized the result might be wrong. For example thread 1 is executing the method addToMap() and thread 2 is executing the method doWork() The sequence of method calls on the synchronizedMap object might be as follows: Thread 1 has executed the method

synchronizedMap.containsKey(key)

and the result is "true". After that operating system has switched execution control to thread 2 and it has executed

synchronizedMap.remove(key)

After that execution control has been switched back to the thread 1 and it has executed for example

synchronizedMap.get(key).add(value);

believing the synchronizedMap object contains the key and NullPointerException will be thrown because synchronizedMap.get(key) will return null. If the sequence of method calls on the synchronizedMap object is not dependent on the results of each other then you don't need to synchronize the sequence. For example you don't need to synchronize this sequence:

synchronizedMap.put(key1, valuesList1);
synchronizedMap.put(key2, valuesList2);

Here

synchronizedMap.put(key2, valuesList2);

method call does not rely on the results of the previous

synchronizedMap.put(key1, valuesList1);

method call (it does not care if some thread has interfered in between the two method calls and for example has removed the key1).

How to format date string in java?

If you are looking for a solution to your particular case, it would be:

Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse("2012-05-20T09:00:00.000Z");
String formattedDate = new SimpleDateFormat("dd/MM/yyyy, Ka").format(date);

Pointtype command for gnuplot

You first have to tell Gnuplot to use a style that uses points, e.g. with points or with linespoints. Try for example:

plot sin(x) with points

Output:

Now try:

plot sin(x) with points pointtype 5

Output:

You may also want to look at the output from the test command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:

Java: Clear the console

Since there are several answers here showing non-working code for Windows, here is a clarification:

Runtime.getRuntime().exec("cls");

This command does not work, for two reasons:

  1. There is no executable named cls.exe or cls.com in a standard Windows installation that could be invoked via Runtime.exec, as the well-known command cls is builtin to Windows’ command line interpreter.

  2. When launching a new process via Runtime.exec, the standard output gets redirected to a pipe which the initiating Java process can read. But when the output of the cls command gets redirected, it doesn’t clear the console.

To solve this problem, we have to invoke the command line interpreter (cmd) and tell it to execute a command (/c cls) which allows invoking builtin commands. Further we have to directly connect its output channel to the Java process’ output channel, which works starting with Java 7, using inheritIO():

import java.io.IOException;

public class CLS {
    public static void main(String... arg) throws IOException, InterruptedException {
        new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
    }
}

Now when the Java process is connected to a console, i.e. has been started from a command line without output redirection, it will clear the console.

How to pipe list of files returned by find command to cat to view all the files

This will print the name and contents of files-only recursively..

find . -type f -printf '\n\n%p:\n' -exec cat {} \;

Edit (Improved version): This will print the name and contents of text (ascii) files-only recursively..

find . -type f -exec grep -Iq . {} \; -print | xargs awk 'FNR==1{print FILENAME ":" $0; }'

One more attempt

find . -type f -exec grep -Iq . {} \; -printf "\n%p:" -exec cat {} \;

COPY with docker but with exclusion

For those who can't use a .dockerignore file (e.g. if you need the file in one COPY but not another):

Yes, but you need multiple COPY instructions. Specifically, you need a COPY for each letter in the filename you wish to exclude.

COPY [^n]*    # All files that don't start with 'n'
COPY n[^o]*   # All files that start with 'n', but not 'no'
COPY no[^d]*  # All files that start with 'no', but not 'nod'

Continuing until you have the full file name, or just the prefix you're reasonably sure won't have any other files.

Java substring: 'string index out of range'

You really need to check if the string's length is greater to or equal to 38.

'list' object has no attribute 'shape'

If you have list, you can print its shape as if it is converted to array

import numpy as np
print(np.asarray(X).shape)

How do I convert from a money datatype in SQL server?

You can try like this:

SELECT PARSENAME('$'+ Convert(varchar,Convert(money,@MoneyValue),1),2)

Avoid dropdown menu close on click inside

This might help:

$("dropdownmenuname").click(function(e){
   e.stopPropagation();
})

Wrapping a react-router Link in an html button

Update for React Router version 6:

The various answers here are like a timeline of react-router's evolution

Using the latest hooks from react-router v6, this can now be done easily with the useNavigate hook.

import { useNavigate } from 'react-router-dom'      

function MyLinkButton() {
  const navigate = useNavigate()
  return (
      <button onClick={() => navigate("/home")}>
        Go Home
      </button>
  );
}

How do I determine whether an array contains a particular value in Java?

Arrays.asList(yourArray).contains(yourValue)

Warning: this doesn't work for arrays of primitives (see the comments).


Since you can now use Streams.

String[] values = {"AB","BC","CD","AE"};
boolean contains = Arrays.stream(values).anyMatch("s"::equals);

To check whether an array of int, double or long contains a value use IntStream, DoubleStream or LongStream respectively.

Example

int[] a = {1,2,3,4};
boolean contains = IntStream.of(a).anyMatch(x -> x == 4);

Passing an array by reference in C?

In plain C you can use a pointer/size combination in your API.

void doSomething(MyStruct* mystruct, size_t numElements)
{
    for (size_t i = 0; i < numElements; ++i)
    {
        MyStruct current = mystruct[i];
        handleElement(current);
    }
}

Using pointers is the closest to call-by-reference available in C.

Java 8 List<V> into Map<K, V>

It's possible to use streams to do this. To remove the need to explicitly use Collectors, it's possible to import toMap statically (as recommended by Effective Java, third edition).

import static java.util.stream.Collectors.toMap;

private static Map<String, Choice> nameMap(List<Choice> choices) {
    return choices.stream().collect(toMap(Choice::getName, it -> it));
}

How to Deep clone in javascript

Here is an ES6 function that will also work for objects with cyclic references:

_x000D_
_x000D_
function deepClone(obj, hash = new WeakMap()) {_x000D_
    if (Object(obj) !== obj) return obj; // primitives_x000D_
    if (hash.has(obj)) return hash.get(obj); // cyclic reference_x000D_
    const result = obj instanceof Set ? new Set(obj) // See note about this!_x000D_
                 : obj instanceof Map ? new Map(Array.from(obj, ([key, val]) => _x000D_
                                        [key, deepClone(val, hash)])) _x000D_
                 : obj instanceof Date ? new Date(obj)_x000D_
                 : obj instanceof RegExp ? new RegExp(obj.source, obj.flags)_x000D_
                 // ... add here any specific treatment for other classes ..._x000D_
                 // and finally a catch-all:_x000D_
                 : obj.constructor ? new obj.constructor() _x000D_
                 : Object.create(null);_x000D_
    hash.set(obj, result);_x000D_
    return Object.assign(result, ...Object.keys(obj).map(_x000D_
        key => ({ [key]: deepClone(obj[key], hash) }) ));_x000D_
}_x000D_
_x000D_
// Sample data_x000D_
var p = {_x000D_
  data: 1,_x000D_
  children: [{_x000D_
    data: 2,_x000D_
    parent: null_x000D_
  }]_x000D_
};_x000D_
p.children[0].parent = p;_x000D_
_x000D_
var q = deepClone(p);_x000D_
_x000D_
console.log(q.children[0].parent.data); // 1
_x000D_
_x000D_
_x000D_

A note about Sets and Maps

How to deal with the keys of Sets and Maps is debatable: those keys are often primitives (in which case there is no debate), but they can also be objects. In that case the question becomes: should those keys be cloned?

One could argue that this should be done, so that if those objects are mutated in the copy, the objects in the original are not affected, and vice versa.

On the other hand one would want that if a Set/Map has a key, this should be true in both the original and the copy -- at least before any change is made to either of them. It would be strange if the copy would be a Set/Map that has keys that never occurred before (as they were created during the cloning process): surely that is not very useful for any code that needs to know whether a given object is a key in that Set/Map or not.

As you notice, I am more of the second opinion: the keys of Sets and Maps are values (maybe references) that should remain the same.

Such choices will often also surface with other (maybe custom) objects. There is no general solution, as much depends on how the cloned object is expected to behave in your specific case.

Why do we always prefer using parameters in SQL statements?

Other answers cover why parameters are important, but there is a downside! In .net, there are several methods for creating parameters (Add, AddWithValue), but they all require you to worry, needlessly, about the parameter name, and they all reduce the readability of the SQL in the code. Right when you're trying to meditate on the SQL, you need to hunt around above or below to see what value has been used in the parameter.

I humbly claim my little SqlBuilder class is the most elegant way to write parameterized queries. Your code will look like this...

C#

var bldr = new SqlBuilder( myCommand );
bldr.Append("SELECT * FROM CUSTOMERS WHERE ID = ").Value(myId);
//or
bldr.Append("SELECT * FROM CUSTOMERS WHERE NAME LIKE ").FuzzyValue(myName);
myCommand.CommandText = bldr.ToString();

Your code will be shorter and much more readable. You don't even need extra lines, and, when you're reading back, you don't need to hunt around for the value of parameters. The class you need is here...

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;

public class SqlBuilder
{
private StringBuilder _rq;
private SqlCommand _cmd;
private int _seq;
public SqlBuilder(SqlCommand cmd)
{
    _rq = new StringBuilder();
    _cmd = cmd;
    _seq = 0;
}
public SqlBuilder Append(String str)
{
    _rq.Append(str);
    return this;
}
public SqlBuilder Value(Object value)
{
    string paramName = "@SqlBuilderParam" + _seq++;
    _rq.Append(paramName);
    _cmd.Parameters.AddWithValue(paramName, value);
    return this;
}
public SqlBuilder FuzzyValue(Object value)
{
    string paramName = "@SqlBuilderParam" + _seq++;
    _rq.Append("'%' + " + paramName + " + '%'");
    _cmd.Parameters.AddWithValue(paramName, value);
    return this;
}
public override string ToString()
{
    return _rq.ToString();
}
}

Java parsing XML document gives "Content not allowed in prolog." error

The document looks fine to me but I suspect that it contains invisible characters. Open it in a hex editor to check that there really isn't anything before the very first "<". Make sure the spaces in the XML header are spaces. Maybe delete the space before "?>". Check which line breaks are used.

Make sure the document is proper UTF-8. Some windows editors save the document as UTF-16 (i.e. every second byte is 0).

Convert python datetime to timestamp in milliseconds

For Python2.7

You can format it into seconds and then multiply by 1000 to convert to millisecond.

from datetime import datetime

d = datetime.strptime("20.12.2016 09:38:42,76", "%d.%m.%Y %H:%M:%S,%f").strftime('%s')
d_in_ms = int(d)*1000
print(d_in_ms)

print(datetime.fromtimestamp(float(d)))

Output:

1482206922000
2016-12-20 09:38:42

How to call two methods on button's onclick method in HTML or JavaScript?

As stated by Harry Joy, you can do it on the onclick attr like so:

<input type="button" onclick="func1();func2();" value="Call2Functions" />

Or, in your JS like so:

document.getElementById( 'Call2Functions' ).onclick = function()
{
    func1();
    func2();
};

Or, if you are assigning an onclick programmatically, and aren't sure if a previous onclick existed (and don't want to overwrite it):

var Call2FunctionsEle = document.getElementById( 'Call2Functions' ),
    func1 = Call2FunctionsEle.onclick;

Call2FunctionsEle.onclick = function()
{
    if( typeof func1 === 'function' )
    {
        func1();
    }
    func2();
};

If you need the functions run in scope of the element which was clicked, a simple use of apply could be made:

document.getElementById( 'Call2Functions' ).onclick = function()
{
    func1.apply( this, arguments );
    func2.apply( this, arguments );
};

Mobile Safari: Javascript focus() method on inputfield only works with click?

I have a search form with an icon that clears the text when clicked. However, the problem (on mobile & tablets) was that the keyboard would collapse/hide, as the click event removed focus was removed from the input.

text search input with close icon

Goal: after clearing the search form (clicking/tapping on x-icon) keep the keyboard visible!

To accomplish this, apply stopPropagation() on the event like so:

function clear ($event) {
    $event.preventDefault();
    $event.stopPropagation();
    self.query = '';
    $timeout(function () {
        document.getElementById('sidebar-search').focus();
    }, 1);
}

And the HTML form:

<form ng-controller="SearchController as search"
    ng-submit="search.submit($event)">
        <input type="search" id="sidebar-search" 
            ng-model="search.query">
                <span class="glyphicon glyphicon-remove-circle"
                    ng-click="search.clear($event)">
                </span>
</form>

How to check the differences between local and github before the pull

If you're not interested in the details that git diff outputs you can just run git cherry which will output a list of commits your remote tracking branch has ahead of your local branch.

For example:

git fetch origin
git cherry master origin/master

Will output something like :

+ 2642039b1a4c4d4345a0d02f79ccc3690e19d9b1
+ a4870f9fbde61d2d657e97b72b61f46d1fd265a9

Indicates that there are two commits in my remote tracking branch that haven't been merged into my local branch.

This also works the other way :

    git cherry origin/master master

Will show you a list of local commits that you haven't pushed to your remote repository yet.

How do I copy a folder from remote to local using scp?

Better to first compress catalog on remote server:

tar czfP backup.tar.gz /path/to/catalog

Secondly, download from remote:

scp [email protected]:/path/to/backup.tar.gz .

At the end, extract the files:

tar -xzvf backup.tar.gz

How to get current html page title with javascript

try like this

$('title').text();

List of installed gems?

This lists all the gems I have installed.

gem query --local

http://guides.rubygems.org/command-reference/#gem-list

See 2.7 Listing all installed gems

How do I convert from stringstream to string in C++?

Use the .str()-method:

Manages the contents of the underlying string object.

1) Returns a copy of the underlying string as if by calling rdbuf()->str().

2) Replaces the contents of the underlying string as if by calling rdbuf()->str(new_str)...

Notes

The copy of the underlying string returned by str is a temporary object that will be destructed at the end of the expression, so directly calling c_str() on the result of str() (for example in auto *ptr = out.str().c_str();) results in a dangling pointer...

How to convert Varchar to Double in sql?

This might be more desirable, that is use float instead

SELECT fullName, CAST(totalBal as float) totalBal FROM client_info ORDER BY totalBal DESC

CUSTOM_ELEMENTS_SCHEMA added to NgModule.schemas still showing Error

That didn't work for me (using 2.0.0). What worked for me was importing RouterTestingModule instead.

I resolved this by importing RouterTestingModule in spec file.

import {
    RouterTestingModule
} from '@angular/router/testing';

  beforeEach(() => {

        TestBed.configureTestingModule({
            providers: [
                App,
                AppState,
                Renderer,
                {provide: Router,  useClass: MockRouter }
            ],
            imports: [ RouterTestingModule ]
        });

    });

Regular Expression for any number greater than 0?

Very simple answer to this use this: \d*

CodeIgniter: Unable to connect to your database server using the provided settings Error Message

If that is all you have changed, you may not have the mysqli driver installed or enabled within your PHP configuration.

Check for its presence using phpinfo(), or in your php.ini file (extension=php_mysqli....).

Regular expressions in C: examples?

man regex.h reports there is no manual entry for regex.h, but man 3 regex gives you a page explaining the POSIX functions for pattern matching.
The same functions are described in The GNU C Library: Regular Expression Matching, which explains that the GNU C Library supports both the POSIX.2 interface and the interface the GNU C Library has had for many years.

For example, for an hypothetical program that prints which of the strings passed as argument match the pattern passed as first argument, you could use code similar to the following one.

#include <errno.h>
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void print_regerror (int errcode, size_t length, regex_t *compiled);

int
main (int argc, char *argv[])
{
  regex_t regex;
  int result;

  if (argc < 3)
    {
      // The number of passed arguments is lower than the number of
      // expected arguments.
      fputs ("Missing command line arguments\n", stderr);
      return EXIT_FAILURE;
    }

  result = regcomp (&regex, argv[1], REG_EXTENDED);
  if (result)
    {
      // Any value different from 0 means it was not possible to 
      // compile the regular expression, either for memory problems
      // or problems with the regular expression syntax.
      if (result == REG_ESPACE)
        fprintf (stderr, "%s\n", strerror(ENOMEM));
      else
        fputs ("Syntax error in the regular expression passed as first argument\n", stderr);
      return EXIT_FAILURE;               
    }
  for (int i = 2; i < argc; i++)
    {
      result = regexec (&regex, argv[i], 0, NULL, 0);
      if (!result)
        {
          printf ("'%s' matches the regular expression\n", argv[i]);
        }
      else if (result == REG_NOMATCH)
        {
          printf ("'%s' doesn't the regular expression\n", argv[i]);
        }
      else
        {
          // The function returned an error; print the string 
          // describing it.
          // Get the size of the buffer required for the error message.
          size_t length = regerror (result, &regex, NULL, 0);
          print_regerror (result, length, &regex);       
          return EXIT_FAILURE;
        }
    }

  /* Free the memory allocated from regcomp(). */
  regfree (&regex);
  return EXIT_SUCCESS;
}

void
print_regerror (int errcode, size_t length, regex_t *compiled)
{
  char buffer[length];
  (void) regerror (errcode, compiled, buffer, length);
  fprintf(stderr, "Regex match failed: %s\n", buffer);
}

The last argument of regcomp() needs to be at least REG_EXTENDED, or the functions will use basic regular expressions, which means that (for example) you would need to use a\{3\} instead of a{3} used from extended regular expressions, which is probably what you expect to use.

POSIX.2 has also another function for wildcard matching: fnmatch(). It doesn't allow to compile the regular expression, or get the substrings matching a sub-expression, but it is very specific for checking when a filename match a wildcard (e.g. it uses the FNM_PATHNAME flag).

pip: no module named _internal

you can remove it first, and install again ,it will be ok. for centos:

yum remove python-pip
yum install python-pip

Centering controls within a form in .NET (Winforms)?

myControl.Left = (this.ClientSize.Width - myControl.Width) / 2 ;
myControl.Top = (this.ClientSize.Height - myControl.Height) / 2;

How to display a confirmation dialog when clicking an <a> link?

Inline event handler

In the most simple way, you can use the confirm() function in an inline onclick handler.

<a href="delete.php?id=22" onclick="return confirm('Are you sure?')">Link</a>

Advanced event handling

But normally you would like to separate your HTML and Javascript, so I suggest you don't use inline event handlers, but put a class on your link and add an event listener to it.

<a href="delete.php?id=22" class="confirmation">Link</a>
...
<script type="text/javascript">
    var elems = document.getElementsByClassName('confirmation');
    var confirmIt = function (e) {
        if (!confirm('Are you sure?')) e.preventDefault();
    };
    for (var i = 0, l = elems.length; i < l; i++) {
        elems[i].addEventListener('click', confirmIt, false);
    }
</script>

This example will only work in modern browsers (for older IEs you can use attachEvent(), returnValue and provide an implementation for getElementsByClassName() or use a library like jQuery that will help with cross-browser issues). You can read more about this advanced event handling method on MDN.

jQuery

I'd like to stay far away from being considered a jQuery fanboy, but DOM manipulation and event handling are two areas where it helps the most with browser differences. Just for fun, here is how this would look with jQuery:

<a href="delete.php?id=22" class="confirmation">Link</a>
...
<!-- Include jQuery - see http://jquery.com -->
<script type="text/javascript">
    $('.confirmation').on('click', function () {
        return confirm('Are you sure?');
    });
</script>

How can I update window.location.hash without jumping the document?

This solution worked for me.

The problem with setting location.hash is that the page will jump to that id if it's found on the page.

The problem with window.history.pushState is that it adds an entry to the history for each tab the user clicks. Then when the user clicks the back button, they go to the previous tab. (this may or may not be what you want. it was not what I wanted).

For me, replaceState was the better option in that it only replaces the current history, so when the user clicks the back button, they go to the previous page.

$('#tab-selector').tabs({
  activate: function(e, ui) {
    window.history.replaceState(null, null, ui.newPanel.selector);
  }
});

Check out the History API docs on MDN.