Programs & Examples On #Quickdraw

QuickDraw is the 2D graphics library and associated Application Programming Interface (API) which is a core part of the classic Apple Macintosh operating system.

How to sort a List<Object> alphabetically using Object name field

@Victor's answer worked for me and reposting it here in Kotlin in case useful to someone else doing Android.

if (list!!.isNotEmpty()) {
   Collections.sort(
     list,
     Comparator { c1, c2 -> //You should ensure that list doesn't contain null values!
     c1.name!!.compareTo(c2.name!!)
   })
}

Questions every good Database/SQL developer should be able to answer

At our company, instead of asking a lot of SQL questions that anyone with a good memory can answer, we created a SQL Developers test. The test is designed to have the candidate put together a solid schema with normalization and RI considerations, check constraints etc. And then be able to create some queries to produce results sets we're looking for. They create all this against a brief design specification we give them. They are allowed to do this at home, and take as much time as they need (within reason).

Android: How to enable/disable option menu item on button click?

simplify @Vikas version

@Override
public boolean onPrepareOptionsMenu (Menu menu) {

    menu.findItem(R.id.example_foobar).setEnabled(isFinalized);
    return true;
}

How do you change the width and height of Twitter Bootstrap's tooltips?

You should overwrite the properties using your own css. like so:

div.tooltip-inner {
    text-align: center;
    -webkit-border-radius: 0px;
    -moz-border-radius: 0px;
    border-radius: 0px;
    margin-bottom: 6px;
    background-color: #505050;
    font-size: 14px;
}

the selector choose the div that the tooltip is held (tooltip is added in by javascript and it usually does not belong to any container.

How to output a multiline string in Bash?

Also with indented source code you can use <<- (with a trailing dash) to ignore leading tabs (but not leading spaces).

For example this:

if [ some test ]; then
    cat <<- xx
        line1
        line2
xx
fi

Outputs indented text without the leading whitespace:

line1
line2

How do I extend a class with c# extension methods?

I was looking for something similar - a list of constraints on classes that provide Extension Methods. Seems tough to find a concise list so here goes:

  1. You can't have any private or protected anything - fields, methods, etc.

  2. It must be a static class, as in public static class....

  3. Only methods can be in the class, and they must all be public static.

  4. You can't have conventional static methods - ones that don't include a this argument aren't allowed.

  5. All methods must begin:

    public static ReturnType MethodName(this ClassName _this, ...)

So the first argument is always the this reference.

There is an implicit problem this creates - if you add methods that require a lock of any sort, you can't really provide it at the class level. Typically you'd provide a private instance-level lock, but it's not possible to add any private fields, leaving you with some very awkward options, like providing it as a public static on some outside class, etc. Gets dicey. Signs the C# language had kind of a bad turn in the design for these.

The workaround is to use your Extension Method class as just a Facade to a regular class, and all the static methods in your Extension class just call the real class, probably using a Singleton.

If condition inside of map() React

This one I found simple solutions:

row = myArray.map((cell, i) => {

    if (i == myArray.length - 1) {
      return <div> Test Data 1</div>;
    }
    return <div> Test Data 2</div>;
  });

What is the purpose of nameof?

Most common usage will be in input validation, such as

//Currently
void Foo(string par) {
   if (par == null) throw new ArgumentNullException("par");
}

//C# 6 nameof
void Foo(string par) {
   if (par == null) throw new ArgumentNullException(nameof(par));
}

In first case, if you refactor the method changing par parameter's name, you'll probably forget to change that in the ArgumentNullException. With nameof you don't have to worry about that.

See also: nameof (C# and Visual Basic Reference)

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured

It's happening because the @valerio-vaudi said.

Your problem is the dependency of spring batch spring-boot-starter-batch that has a spring-boot-starter-jdbc transitive maven dependency.

But you can resolve it set the primary datasource with your configuration

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

 @Bean
 public JdbcTemplate jdbcTemplate(DataSource dataSource) {
      return new JdbcTemplate(dataSource);
 }

How do I download a tarball from GitHub using cURL?

All the other solutions require specifying a release/version number which obviously breaks automation.

This solution- currently tested and known to work with Github API v3- however can be used programmatically to grab the LATEST release without specifying any tag or release number and un-TARs the binary to an arbitrary name you specify in switch --one-top-level="pi-ap". Just swap-out user f1linux and repo pi-ap in below example with your own details and Bob's your uncle:

curl -L https://api.github.com/repos/f1linux/pi-ap/tarball | tar xzvf - --one-top-level="pi-ap" --strip-components 1

How to make an embedded Youtube video automatically start playing?

This works perfectly for me try this just put ?rel=0&autoplay=1 in the end of link

<iframe width="631" height="466" src="https://www.youtube.com/embed/UUdMixCYeTA?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>

FtpWebRequest Download File

Easiest way

The most trivial way to download a binary file from an FTP server using .NET framework is using WebClient.DownloadFile:

WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
client.DownloadFile(
    "ftp://ftp.example.com/remote/path/file.zip", @"C:\local\path\file.zip");

Advanced options

Use FtpWebRequest, only if you need a greater control, that WebClient does not offer (like TLS/SSL encryption, progress monitoring, ascii/text transfer mode, resuming transfers, etc). Easy way is to just copy an FTP response stream to FileStream using Stream.CopyTo:

FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;

using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(@"C:\local\path\file.zip"))
{
    ftpStream.CopyTo(fileStream);
}

Progress monitoring

If you need to monitor a download progress, you have to copy the contents by chunks yourself:

FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;

using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(@"C:\local\path\file.zip"))
{
    byte[] buffer = new byte[10240];
    int read;
    while ((read = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
    {
        fileStream.Write(buffer, 0, read);
        Console.WriteLine("Downloaded {0} bytes", fileStream.Position);
    }
}

For GUI progress (WinForms ProgressBar), see:
FtpWebRequest FTP download with ProgressBar


Downloading folder

If you want to download all files from a remote folder, see
C# Download all files and subdirectories through FTP.

Creating Threads in python

Did you override the run() method? If you overrided __init__, did you make sure to call the base threading.Thread.__init__()?

After starting the two threads, does the main thread continue to do work indefinitely/block/join on the child threads so that main thread execution does not end before the child threads complete their tasks?

And finally, are you getting any unhandled exceptions?

Get OS-level system information

One simple way which can be used to get the OS level information and I tested in my Mac which works well :

 OperatingSystemMXBean osBean =
        (OperatingSystemMXBean)ManagementFactory.getOperatingSystemMXBean();
    return osBean.getProcessCpuLoad();

You can find many relevant metrics of the operating system here

How to debug Google Apps Script (aka where does Logger.log log to?)

Just as a notice. I made a test function for my spreadsheet. I use the variable google throws in the onEdit(e) function (I called it e). Then I made a test function like this:

function test(){
var testRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GetItemInfoSheetName).getRange(2,7)
var testObject = {
    range:testRange,
    value:"someValue"
}
onEdit(testObject)
SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GetItemInfoSheetName).getRange(2,6).setValue(Logger.getLog())
}

Calling this test function makes all the code run as you had an event in the spreadsheet. I just put in the possision of the cell i edited whitch gave me an unexpected result, setting value as the value i put into the cell. OBS! for more variables googles gives to the function go here: https://developers.google.com/apps-script/guides/triggers/events#google_sheets_events

How to use jQuery Plugin with Angular 4?

Install jQuery using NPM Jquery NPM

npm install jquery

Install the jQuery declaration file

npm install -D @types/jquery

Import jQuery inside .ts

import * as $ from 'jquery';

call inside class

export class JqueryComponent implements OnInit {

constructor() {
}

ngOnInit() {
    $(window).click(function () {
        alert('ok');
        });
    }

}

Cannot change column used in a foreign key constraint

You can turn off foreign key checks:

SET FOREIGN_KEY_CHECKS = 0;

/* DO WHAT YOU NEED HERE */

SET FOREIGN_KEY_CHECKS = 1;

Please make sure to NOT use this on production and have a backup.

JavaScript before leaving the page

Just a bit more helpful, enable and disable

$(window).on('beforeunload.myPluginName', false); // or use function() instead of false
$(window).off('beforeunload.myPluginName');

jQuery .each() index?

From the jQuery.each() documentation:

.each( function(index, Element) )
    function(index, Element)A function to execute for each matched element.

So you'll want to use:

$('#list option').each(function(i,e){
    //do stuff
});

...where index will be the index and element will be the option element in list

better way to drop nan rows in pandas

bool_series=pd.notnull(dat["x"])
dat=dat[bool_series]

Retrieving Data from SQL Using pyodbc

Just do this:

import pandas as pd
import pyodbc

cnxn = pyodbc.connect("Driver={SQL Server}\
                    ;Server=SERVER_NAME\
                    ;Database=DATABASE_NAME\
                    ;Trusted_Connection=yes")

df = pd.read_sql("SELECT * FROM myTableName", cnxn) 
df.head()

Using Postman to access OAuth 2.0 Google APIs

  1. go to https://console.developers.google.com/apis/credentials
  2. create web application credentials.

Postman API Access

  1. use these settings with oauth2 in Postman:

SCOPE = https: //www.googleapis.com/auth/admin.directory.userschema

post https: //www.googleapis.com/admin/directory/v1/customer/customer-id/schemas

{
  "fields": [
    {
      "fieldName": "role",
      "fieldType": "STRING",
      "multiValued": true,
      "readAccessType": "ADMINS_AND_SELF"
    }
  ],
  "schemaName": "SAML"
}
  1. to patch user use:

SCOPE = https://www.googleapis.com/auth/admin.directory.user

PATCH https://www.googleapis.com/admin/directory/v1/users/[email protected]

 {
  "customSchemas": {
     "SAML": {
       "role": [
         {
          "value": "arn:aws:iam::123456789123:role/Admin,arn:aws:iam::123456789123:saml-provider/GoogleApps",
          "customType": "Admin"
         }
       ]
     }
   }
}

I can't access http://localhost/phpmyadmin/

I also faced the same issue. i worked on it and found out ,this is simply because i have mistakenly moved my "phpmyadmin" folder in to a some folder inside Xampp. Go through all the other folders which are inside the main "XAMPP" folder. Then if you find the "phpmyadmin" inside another folder other than "xampp" move it back to the main "XAmpp" folder and refresh the page. :)

CMake not able to find OpenSSL library

Just for fun ill post an alternative working answer for the OP's question:

cmake -DOPENSSL_ROOT_DIR=/usr/local/opt/openssl/ -DOPENSSL_CRYPTO_LIBRARY=/usr/local/opt/openssl/lib/

Bootstrap Collapse not Collapsing

Maybe your mobile view port is not set. Add following meta tag inside <head></head> to allow menu to work on mobiles.

<meta name=viewport content="width=device-width, initial-scale=1">

How to increment a number by 2 in a PHP For Loop

Simple solution

<?php
   $x = 1;
     for($x = 1; $x < 8; $x++) {
        $x = $x + 1;
       echo $x;
     };    
?>

Why am I getting ImportError: No module named pip ' right after installing pip?

I'v solved this error by setting the correct path variables

    C:\Users\name\AppData\Local\Programs\Python\Python37\Scripts
    C:\Users\name\AppData\Local\Programs\Python\Python37\Lib\site-packages

Microsoft Advertising SDK doesn't deliverer ads

I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.

Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled

Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is

  1. Remove the XAML for the ad
  2. Remove the xmlns declaration (usually at the top of the page, but sometimes will be declared in the ad itself)
  3. Remove the bad DLL (the one ending in .SDK )
  4. Do a Clean and then Build (clean out anything remaining from the DLL)
  5. Add the xmlns reference (actual reference is below)
  6. Add the ad to the page (example below)

Here is the xmlns reference:

xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI" 

Then the ad itself:

<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480"                    AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/> 

How do I find ' % ' with the LIKE operator in SQL Server?

You can use ESCAPE:

WHERE columnName LIKE '%\%%' ESCAPE '\'

Mocking HttpClient in unit tests

Since HttpClient use SendAsync method to perform all HTTP Requests, you can override SendAsync method and mock the HttpClient.

For that wrap creating HttpClient to a interface, something like below

public interface IServiceHelper
{
    HttpClient GetClient();
}

Then use above interface for dependency injection in your service, sample below

public class SampleService
{
    private readonly IServiceHelper serviceHelper;

    public SampleService(IServiceHelper serviceHelper)
    {
        this.serviceHelper = serviceHelper;
    }

    public async Task<HttpResponseMessage> Get(int dummyParam)
    {
        try
        {
            var dummyUrl = "http://www.dummyurl.com/api/controller/" + dummyParam;
            var client = serviceHelper.GetClient();
            HttpResponseMessage response = await client.GetAsync(dummyUrl);               

            return response;
        }
        catch (Exception)
        {
            // log.
            throw;
        }
    }
}

Now in unit test project create a helper class for mocking SendAsync. Here it is a FakeHttpResponseHandler class which is inheriting DelegatingHandler which will provide an option to override the SendAsync method. After overriding the SendAsync method need to setup a response for each HTTP Request which is calling SendAsync method, for that create a Dictionary with key as Uri and value as HttpResponseMessage so that whenever there is a HTTP Request and if the Uri matches SendAsync will return the configured HttpResponseMessage.

public class FakeHttpResponseHandler : DelegatingHandler
{
    private readonly IDictionary<Uri, HttpResponseMessage> fakeServiceResponse;
    private readonly JavaScriptSerializer javaScriptSerializer;
    public FakeHttpResponseHandler()
    {
        fakeServiceResponse =  new Dictionary<Uri, HttpResponseMessage>();
        javaScriptSerializer =  new JavaScriptSerializer();
    }

    /// <summary>
    /// Used for adding fake httpResponseMessage for the httpClient operation.
    /// </summary>
    /// <typeparam name="TQueryStringParameter"> query string parameter </typeparam>
    /// <param name="uri">Service end point URL.</param>
    /// <param name="httpResponseMessage"> Response expected when the service called.</param>
    public void AddFakeServiceResponse(Uri uri, HttpResponseMessage httpResponseMessage)
    {
        fakeServiceResponse.Remove(uri);
        fakeServiceResponse.Add(uri, httpResponseMessage);
    }

    /// <summary>
    /// Used for adding fake httpResponseMessage for the httpClient operation having query string parameter.
    /// </summary>
    /// <typeparam name="TQueryStringParameter"> query string parameter </typeparam>
    /// <param name="uri">Service end point URL.</param>
    /// <param name="httpResponseMessage"> Response expected when the service called.</param>
    /// <param name="requestParameter">Query string parameter.</param>
    public void AddFakeServiceResponse<TQueryStringParameter>(Uri uri, HttpResponseMessage httpResponseMessage, TQueryStringParameter requestParameter)
    {
        var serilizedQueryStringParameter = javaScriptSerializer.Serialize(requestParameter);
        var actualUri = new Uri(string.Concat(uri, serilizedQueryStringParameter));
        fakeServiceResponse.Remove(actualUri);
        fakeServiceResponse.Add(actualUri, httpResponseMessage);
    }

    // all method in HttpClient call use SendAsync method internally so we are overriding that method here.
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if(fakeServiceResponse.ContainsKey(request.RequestUri))
        {
            return Task.FromResult(fakeServiceResponse[request.RequestUri]);
        }

        return Task.FromResult(new HttpResponseMessage(HttpStatusCode.NotFound)
        {
            RequestMessage = request,
            Content = new StringContent("Not matching fake found")
        });
    }
}

Create a new implementation for IServiceHelper by mocking framework or like below. This FakeServiceHelper class we can use to inject the FakeHttpResponseHandler class so that whenever the HttpClient created by this class it will use FakeHttpResponseHandler class instead of the actual implementation.

public class FakeServiceHelper : IServiceHelper
{
    private readonly DelegatingHandler delegatingHandler;

    public FakeServiceHelper(DelegatingHandler delegatingHandler)
    {
        this.delegatingHandler = delegatingHandler;
    }

    public HttpClient GetClient()
    {
        return new HttpClient(delegatingHandler);
    }
}

And in test configure FakeHttpResponseHandler class by adding the Uri and expected HttpResponseMessage. The Uri should be the actual serviceendpoint Uri so that when the overridden SendAsync method is called from actual service implementation it will match the Uri in Dictionary and respond with the configured HttpResponseMessage. After configuring inject the FakeHttpResponseHandler object to the fake IServiceHelper implementation. Then inject the FakeServiceHelper class to the actual service which will make the actual service to use the override SendAsync method.

[TestClass]
public class SampleServiceTest
{
    private FakeHttpResponseHandler fakeHttpResponseHandler;

    [TestInitialize]
    public void Initialize()
    {
        fakeHttpResponseHandler = new FakeHttpResponseHandler();
    }

    [TestMethod]
    public async Task GetMethodShouldReturnFakeResponse()
    {
        Uri uri = new Uri("http://www.dummyurl.com/api/controller/");
        const int dummyParam = 123456;
        const string expectdBody = "Expected Response";

        var expectedHttpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new StringContent(expectdBody)
        };

        fakeHttpResponseHandler.AddFakeServiceResponse(uri, expectedHttpResponseMessage, dummyParam);

        var fakeServiceHelper = new FakeServiceHelper(fakeHttpResponseHandler);

        var sut = new SampleService(fakeServiceHelper);

        var response = await sut.Get(dummyParam);

        var responseBody = await response.Content.ReadAsStringAsync();

        Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
        Assert.AreEqual(expectdBody, responseBody);
    }
}

GitHub Link : which is having sample implementation

Create a folder if it doesn't already exist

To create a folder if it doesn't already exist

Considering the question's environment.

  • WordPress.
  • Webhosting Server.
  • Assuming its Linux not Windows running PHP.

And quoting from: http://php.net/manual/en/function.mkdir.php

bool mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive = FALSE [, resource $context ]]] )

Manual says that the only required parameter is the $pathname!

so, We can simply code:

<?php
error_reporting(0); 
if(!mkdir('wp-content/uploads')){
   // todo
}
?>

Explanation:

We don't have to pass any parameter or check if folder exists or even pass mode parameter unless needed; for the following reasons:

  • The command will create the folder with 0755 permission (Shared hosting folder's default permission) or 0777 the command's default.
  • mode is ignored on Windows Hosting running PHP.
  • Already the mkdir command has build in checker if folder exists; so we need to check the return only True|False ; and its not an error, its a warning only, and Warning is disabled in hosting servers by default.
  • As per speed, this is faster if warning disabled.

This is just another way to look into the question and not claiming a better or most optimal solution.

Tested on PHP7, Production Server, Linux

Word wrap for a label in Windows Forms

This helped me in my Form called InpitWindow: In Designer for Label:

AutoSize = true;
Achors = Top, Left, Right.

private void InputWindow_Shown(object sender, EventArgs e) {
    lbCaption.MaximumSize = new Size(this.ClientSize.Width - btOK.Width - btOK.Margin.Left - btOK.Margin.Right -
        lbCaption.Margin.Right - lbCaption.Margin.Left, 
        Screen.GetWorkingArea(this).Height / 2);
    this.Height = this.Height + (lbCaption.Height - btOK.Height - btCancel.Height);
    //Uncomment this line to prevent form height chage to values lower than initial height
    //this.MinimumSize = new Size(this.MinimumSize.Width, this.Height);
}
//Use this handler if you want your label change it size according to form clientsize.
private void InputWindow_ClientSizeChanged(object sender, EventArgs e) {
    lbCaption.MaximumSize = new Size(this.ClientSize.Width - btOK.Width - btOK.Margin.Left * 2 - btOK.Margin.Right * 2 -
        lbCaption.Margin.Right * 2 - lbCaption.Margin.Left * 2,
        Screen.GetWorkingArea(this).Height / 2);
}

Whole code of my form

How to check if a string starts with "_" in PHP?

To build on pinusnegra's answer, and in response to Gumbo's comment on that answer:

function has_leading_underscore($string) {

    return $string[0] === '_';

}

Running on PHP 5.3.0, the following works and returns the expected value, even without checking if the string is at least 1 character in length:

echo has_leading_underscore('_somestring').', ';
echo has_leading_underscore('somestring').', ';
echo has_leading_underscore('').', ';
echo has_leading_underscore(null).', ';
echo has_leading_underscore(false).', ';
echo has_leading_underscore(0).', ';
echo has_leading_underscore(array('_foo', 'bar'));

/*
 * output: true, false, false, false, false, false, false
 */

I don't know how other versions of PHP will react, but if they all work, then this method is probably more efficient than the substr route.

How to escape special characters of a string with single backslashes

re.escape doesn't double escape. It just looks like it does if you run in the repl. The second layer of escaping is caused by outputting to the screen.

When using the repl, try using print to see what is really in the string.

$ python
>>> import re
>>> re.escape("\^stack\.\*/overflo\\w\$arr=1")
'\\\\\\^stack\\\\\\.\\\\\\*\\/overflo\\\\w\\\\\\$arr\\=1'
>>> print re.escape("\^stack\.\*/overflo\\w\$arr=1")
\\\^stack\\\.\\\*\/overflo\\w\\\$arr\=1
>>>

Convert INT to DATETIME (SQL)

you need to convert to char first because converting to int adds those days to 1900-01-01

select CONVERT (datetime,convert(char(8),rnwl_efctv_dt ))

here are some examples

select CONVERT (datetime,5)

1900-01-06 00:00:00.000

select CONVERT (datetime,20100101)

blows up, because you can't add 20100101 days to 1900-01-01..you go above the limit

convert to char first

declare @i int
select @i = 20100101
select CONVERT (datetime,convert(char(8),@i))

How to discard local changes and pull latest from GitHub repository

Run the below commands

git log

From this you will get your last push commit hash key

git reset --hard <your commit hash key>

What is a serialVersionUID and why should I use it?

What is a serialVersionUID and why should I use it?

SerialVersionUID is a unique identifier for each class, JVM uses it to compare the versions of the class ensuring that the same class was used during Serialization is loaded during Deserialization.

Specifying one gives more control, though JVM does generate one if you don't specify. The value generated can differ between different compilers. Furthermore, sometimes you just want for some reason to forbid deserialization of old serialized objects [backward incompatibility], and in this case you just have to change the serialVersionUID.

The javadocs for Serializable say:

the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization.

Therefore, you must declare serialVersionUID because it give us more control.

This article has some good points on the topic.

How to convert unsigned long to string

char buffer [50];

unsigned long a = 5;

int n=sprintf (buffer, "%lu", a);

ImportError: No module named sqlalchemy

Okay,I have re-installed the package via pip even that didn't help. And then I rsync'ed the entire /usr/lib/python-2.7 directory from other working machine with similar configuration to the current machine.It started working. I don't have any idea ,what was wrong with my setup. I see some difference "print sys.path" output earlier and now. but now my issue is resolved by this work around.

EDIT:Found the real solution for my setup. upgrading "sqlalchemy only doesn't solve the issue" I also need to upgrade flask-sqlalchemy that resolved the issue.

Using %f with strftime() in Python to get microseconds

If you want an integer, try this code:

import datetime
print(datetime.datetime.now().strftime("%s%f")[:13])

Output:

1545474382803

Is there a Python caching library?

Try redis, it is one of the cleanest and easiest solutions for applications to share data in a atomic way or if you have got some web server platform. Its very easy to setup, you will need a python redis client http://pypi.python.org/pypi/redis

How to access SOAP services from iPhone

One word: Don't.

OK obviously that isn't a real answer. But still SOAP should be avoided at all costs. ;-) Is it possible to add a proxy server between the iPhone and the web service? Perhaps something that converts REST into SOAP for you?

You could try CSOAP, a SOAP library that depends on libxml2 (which is included in the iPhone SDK).

I've written my own SOAP framework for OSX. However it is not actively maintained and will require some time to port to the iPhone (you'll need to replace NSXML with TouchXML for a start)

Are there any free Xml Diff/Merge tools available?

Altova's DiffDog has free 30-day trial and should do what you're looking for:

http://www.altova.com/diffdog/diff-merge-tool.html

What's the maximum value for an int in PHP?

From the PHP manual:

The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5.

64-bit platforms usually have a maximum value of about 9E18, except on Windows prior to PHP 7, where it was always 32 bit.

raw_input function in Python

Another example method, to mix the prompt using print, if you need to make your code simpler.

Format:-

x = raw_input () -- This will return the user input as a string

x= int(raw_input()) -- Gets the input number as a string from raw_input() and then converts it to an integer using int().

print '\nWhat\'s your name ?', 
name = raw_input('--> ')
print '\nHow old are you, %s?' % name,
age = int(raw_input())
print '\nHow tall are you (in cms), %s?' % name,
height = int(raw_input())
print '\nHow much do you weigh (in kgs), %s?' % name,
weight = int(raw_input())

print '\nSo, %s is %d years old, %d cms tall and weighs %d kgs.\n' %(
name, age, height, weight)

git pull error "The requested URL returned error: 503 while accessing"

here you can see the latest updated status form their website

bitbucket site status

if Git via HTTPS status is Major Outage, you will not be able to pull/push, let this status to get green

HTTP Error 503 - Service unavailable

Case Insensitive String comp in C

I've found built-in such method named from which contains additional string functions to the standard header .

Here's the relevant signatures :

int  strcasecmp(const char *, const char *);
int  strncasecmp(const char *, const char *, size_t);

I also found it's synonym in xnu kernel (osfmk/device/subrs.c) and it's implemented in the following code, so you wouldn't expect to have any change of behavior in number compared to the original strcmp function.

tolower(unsigned char ch) {
    if (ch >= 'A' && ch <= 'Z')
        ch = 'a' + (ch - 'A');
    return ch;
 }

int strcasecmp(const char *s1, const char *s2) {
    const unsigned char *us1 = (const u_char *)s1,
                        *us2 = (const u_char *)s2;

    while (tolower(*us1) == tolower(*us2++))
        if (*us1++ == '\0')
            return (0);
    return (tolower(*us1) - tolower(*--us2));
}

Remove everything after a certain character

It can easly be done using JavaScript for reference see link JS String

EDIT it can easly done as. ;)

var url="/Controller/Action?id=11112&value=4444 ";
var parameter_Start_index=url.indexOf('?');
var action_URL = url.substring(0, parameter_Start_index);
alert('action_URL : '+action_URL);

How to set session variable in jquery?

Use localStorage to store the fact that you opened the page :

$(document).ready(function() {
    var yetVisited = localStorage['visited'];
    if (!yetVisited) {
        // open popup
        localStorage['visited'] = "yes";
    }
});

How to capitalize the first letter in a String in Ruby

You can use mb_chars. This respects umlaute:

class String

  # Only capitalize first letter of a string
  def capitalize_first
    self[0] = self[0].mb_chars.upcase
    self
  end

end

Example:

"ümlaute".capitalize_first
#=> "Ümlaute"

ADB - Android - Getting the name of the current activity

You can use this command,

adb shell dumpsys activity

You can find current activity name in activity stack.

Output :-

 Sticky broadcasts:
 * Sticky action android.intent.action.BATTERY_CHANGED:
   Intent: act=android.intent.action.BATTERY_CHANGED flg=0x60000000
     Bundle[{icon-small=17302169, present=true, scale=100, level=50, technology=Li-ion, status=2, voltage=0, plugged=1, health=2, temperature=0}]
 * Sticky action android.net.thrott.THROTTLE_ACTION:
   Intent: act=android.net.thrott.THROTTLE_ACTION
     Bundle[{level=-1}]
 * Sticky action android.intent.action.NETWORK_SET_TIMEZONE:
   Intent: act=android.intent.action.NETWORK_SET_TIMEZONE flg=0x20000000
     Bundle[mParcelledData.dataSize=68]
 * Sticky action android.provider.Telephony.SPN_STRINGS_UPDATED:
   Intent: act=android.provider.Telephony.SPN_STRINGS_UPDATED flg=0x20000000
     Bundle[mParcelledData.dataSize=156]
 * Sticky action android.net.thrott.POLL_ACTION:
   Intent: act=android.net.thrott.POLL_ACTION
     Bundle[{cycleRead=0, cycleStart=1349893800000, cycleEnd=1352572200000, cycleWrite=0}]
 * Sticky action android.intent.action.SIM_STATE_CHANGED:
   Intent: act=android.intent.action.SIM_STATE_CHANGED flg=0x20000000
     Bundle[mParcelledData.dataSize=116]
 * Sticky action android.intent.action.SIG_STR:
   Intent: act=android.intent.action.SIG_STR flg=0x20000000
     Bundle[{EvdoSnr=-1, CdmaDbm=-1, GsmBitErrorRate=-1, CdmaEcio=-1, EvdoDbm=-1, GsmSignalStrength=7, EvdoEcio=-1, isGsm=true}]
 * Sticky action android.intent.action.SERVICE_STATE:
   Intent: act=android.intent.action.SERVICE_STATE flg=0x20000000
     Bundle[{cdmaRoamingIndicator=0, operator-numeric=310260, networkId=0, state=0, emergencyOnly=false, operator-alpha-short=Android, radioTechnology=3, manual=false, cssIndicator=false, operator-alpha-long=Android, systemId=0, roaming=false, cdmaDefaultRoamingIndicator=0}]
 * Sticky action android.net.conn.CONNECTIVITY_CHANGE:
   Intent: act=android.net.conn.CONNECTIVITY_CHANGE flg=0x30000000
     Bundle[{networkInfo=NetworkInfo: type: mobile[UMTS], state: CONNECTED/CONNECTED, reason: simLoaded, extra: internet, roaming: false, failover: false, isAvailable: true, reason=simLoaded, extraInfo=internet}]
 * Sticky action android.intent.action.NETWORK_SET_TIME:
   Intent: act=android.intent.action.NETWORK_SET_TIME flg=0x20000000
     Bundle[mParcelledData.dataSize=36]
 * Sticky action android.media.RINGER_MODE_CHANGED:
   Intent: act=android.media.RINGER_MODE_CHANGED flg=0x70000000
     Bundle[{android.media.EXTRA_RINGER_MODE=2}]
 * Sticky action android.intent.action.ANY_DATA_STATE:
   Intent: act=android.intent.action.ANY_DATA_STATE flg=0x20000000
     Bundle[{state=CONNECTED, apnType=*, iface=/dev/omap_csmi_tty1, apn=internet, reason=simLoaded}]

 Activity stack:
 * TaskRecord{450adb90 #22 A org.chanakyastocktipps.com}
   clearOnBackground=false numActivities=2 rootWasReset=false
   affinity=org.chanakyastocktipps.com
   intent={act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=org.chanakyastocktipps.com/.ui.SplashScreen}
   realActivity=org.chanakyastocktipps.com/.ui.SplashScreen
   lastActiveTime=15107753 (inactive for 4879s)
   * Hist #2: HistoryRecord{450d7ab0 org.chanakyastocktipps.com/.ui.Profile}
       packageName=org.chanakyastocktipps.com processName=org.chanakyastocktipps.com
       launchedFromUid=10046 app=ProcessRecord{44fa3450 1065:org.chanakyastocktipps.com/10046}
       Intent { cmp=org.chanakyastocktipps.com/.ui.Profile }
       frontOfTask=false task=TaskRecord{450adb90 #22 A org.chanakyastocktipps.com}
       taskAffinity=org.chanakyastocktipps.com
       realActivity=org.chanakyastocktipps.com/.ui.Profile
       base=/data/app/org.chanakyastocktipps.com-1.apk/data/app/org.chanakyastocktipps.com-1.apk data=/data/data/org.chanakyastocktipps.com
       labelRes=0x7f09000b icon=0x7f020065 theme=0x1030007
       stateNotNeeded=false componentSpecified=true isHomeActivity=false
       configuration={ scale=1.0 imsi=310/260 loc=en_US touch=3 keys=2/1/2 nav=3/1 orien=1 layout=18 uiMode=17 seq=3}
       resultTo=HistoryRecord{44f523c0 org.chanakyastocktipps.com/.ui.MainScreen} resultWho=null resultCode=4
       launchFailed=false haveState=false icicle=null
       state=RESUMED stopped=false delayedResume=false finishing=false
       keysPaused=false inHistory=true persistent=false launchMode=0
       fullscreen=true visible=true frozenBeforeDestroy=false thumbnailNeeded=false idle=true
       waitingVisible=false nowVisible=true
   * Hist #1: HistoryRecord{44f523c0 org.chanakyastocktipps.com/.ui.MainScreen}
       packageName=org.chanakyastocktipps.com processName=org.chanakyastocktipps.com
       launchedFromUid=10046 app=ProcessRecord{44fa3450 1065:org.chanakyastocktipps.com/10046}
       Intent { cmp=org.chanakyastocktipps.com/.ui.MainScreen }
       frontOfTask=true task=TaskRecord{450adb90 #22 A org.chanakyastocktipps.com}
       taskAffinity=org.chanakyastocktipps.com
       realActivity=org.chanakyastocktipps.com/.ui.MainScreen
       base=/data/app/org.chanakyastocktipps.com-1.apk/data/app/org.chanakyastocktipps.com-1.apk data=/data/data/org.chanakyastocktipps.com
       labelRes=0x7f09000b icon=0x7f020065 theme=0x1030007
       stateNotNeeded=false componentSpecified=true isHomeActivity=false
       configuration={ scale=1.0 imsi=310/260 loc=en_US touch=3 keys=2/1/2 nav=3/1 orien=1 layout=18 uiMode=17 seq=3}
       launchFailed=false haveState=true icicle=Bundle[mParcelledData.dataSize=1344]
       state=STOPPED stopped=true delayedResume=false finishing=false
       keysPaused=false inHistory=true persistent=false launchMode=0
       fullscreen=true visible=false frozenBeforeDestroy=false thumbnailNeeded=false idle=true
 * TaskRecord{450615a0 #2 A com.android.launcher}
   clearOnBackground=true numActivities=1 rootWasReset=false
   affinity=com.android.launcher
   intent={act=android.intent.action.MAIN cat=[android.intent.category.HOME] flg=0x10000000 cmp=com.android.launcher/com.android.launcher2.Launcher}
   realActivity=com.android.launcher/com.android.launcher2.Launcher
   lastActiveTime=12263090 (inactive for 7724s)
   * Hist #0: HistoryRecord{4505d838 com.android.launcher/com.android.launcher2.Launcher}
       packageName=com.android.launcher processName=com.android.launcher
       launchedFromUid=0 app=ProcessRecord{45062558 129:com.android.launcher/10025}
       Intent { act=android.intent.action.MAIN cat=[android.intent.category.HOME] flg=0x10000000 cmp=com.android.launcher/com.android.launcher2.Launcher }
       frontOfTask=true task=TaskRecord{450615a0 #2 A com.android.launcher}
       taskAffinity=com.android.launcher
       realActivity=com.android.launcher/com.android.launcher2.Launcher
       base=/system/app/Launcher2.apk/system/app/Launcher2.apk data=/data/data/com.android.launcher
       labelRes=0x7f0c0002 icon=0x7f020044 theme=0x7f0d0000
       stateNotNeeded=true componentSpecified=false isHomeActivity=true
       configuration={ scale=1.0 imsi=310/260 loc=en_US touch=3 keys=2/1/2 nav=3/1 orien=1 layout=18 uiMode=17 seq=3}
       launchFailed=false haveState=true icicle=Bundle[mParcelledData.dataSize=3608]
       state=STOPPED stopped=true delayedResume=false finishing=false
       keysPaused=false inHistory=true persistent=false launchMode=2
       fullscreen=true visible=false frozenBeforeDestroy=false thumbnailNeeded=false idle=true

 Running activities (most recent first):
   TaskRecord{450adb90 #22 A org.chanakyastocktipps.com}
     Run #2: HistoryRecord{450d7ab0 org.chanakyastocktipps.com/.ui.Profile}
     Run #1: HistoryRecord{44f523c0 org.chanakyastocktipps.com/.ui.MainScreen}
   TaskRecord{450615a0 #2 A com.android.launcher}
     Run #0: HistoryRecord{4505d838 com.android.launcher/com.android.launcher2.Launcher}

 mPausingActivity: null
 mResumedActivity: HistoryRecord{450d7ab0 org.chanakyastocktipps.com/.ui.Profile}
 mFocusedActivity: HistoryRecord{450d7ab0 org.chanakyastocktipps.com/.ui.Profile}
 mLastPausedActivity: HistoryRecord{44f523c0 org.chanakyastocktipps.com/.ui.MainScreen}

 mCurTask: 22

 Running processes (most recent first):
   App  #13: adj=vis  /F 45052120 119:com.android.inputmethod.latin/10003 (service)
             com.android.inputmethod.latin.LatinIME<=ProcessRecord{44ec2698 59:system/1000}
   PERS #12: adj=sys  /F 44ec2698 59:system/1000 (fixed)
   App  #11: adj=fore /F 44fa3450 1065:org.chanakyastocktipps.com/10046 (top-activity)
   App  #10: adj=bak  /B 44e7c4c0 299:com.svox.pico/10028 (bg-empty)
   App  # 9: adj=bak+1/B 450f7ef0 288:com.dreamreminder.org:feather_system_receiver/10057 (bg-empty)
   App  # 8: adj=bak+2/B 4503cc38 201:com.android.defcontainer/10010 (bg-empty)
   App  # 7: adj=home /B 45062558 129:com.android.launcher/10025 (home)
   App  # 6: adj=bak+3/B 450244d8 276:android.process.media/10002 (bg-empty)
   App  # 5: adj=bak+4/B 44f2b9b8 263:com.android.quicksearchbox/10012 (bg-empty)
   App  # 4: adj=bak+5/B 450beec0 257:com.android.protips/10007 (bg-empty)
   App  # 3: adj=bak+6/B 44ff37b8 270:com.android.music/10022 (bg-empty)
   PERS # 2: adj=core /F 45056818 124:com.android.phone/1001 (fixed)
   App  # 1: adj=bak+7/B 45080c38 238:com.dreamreminder.org/10057 (bg-empty)
   App  # 0: adj=empty/B 4507d030 229:com.android.email/10030 (bg-empty)

 PID mappings:
   PID #59: ProcessRecord{44ec2698 59:system/1000}
   PID #119: ProcessRecord{45052120 119:com.android.inputmethod.latin/10003}
   PID #124: ProcessRecord{45056818 124:com.android.phone/1001}
   PID #129: ProcessRecord{45062558 129:com.android.launcher/10025}
   PID #201: ProcessRecord{4503cc38 201:com.android.defcontainer/10010}
   PID #229: ProcessRecord{4507d030 229:com.android.email/10030}
   PID #238: ProcessRecord{45080c38 238:com.dreamreminder.org/10057}
   PID #257: ProcessRecord{450beec0 257:com.android.protips/10007}
   PID #263: ProcessRecord{44f2b9b8 263:com.android.quicksearchbox/10012}
   PID #270: ProcessRecord{44ff37b8 270:com.android.music/10022}
   PID #276: ProcessRecord{450244d8 276:android.process.media/10002}
   PID #288: ProcessRecord{450f7ef0 288:com.dreamreminder.org:feather_system_receiver/10057}
   PID #299: ProcessRecord{44e7c4c0 299:com.svox.pico/10028}
   PID #1065: ProcessRecord{44fa3450 1065:org.chanakyastocktipps.com/10046}

 mHomeProcess: ProcessRecord{45062558 129:com.android.launcher/10025}
 mConfiguration: { scale=1.0 imsi=310/260 loc=en_US touch=3 keys=2/1/2 nav=3/1 orien=1 layout=18 uiMode=17 seq=3}
 mConfigWillChange: false
 mSleeping=false mShuttingDown=false

Interfaces — What's the point?

The Pizza example is bad because you should be using an abstract class that handles the ordering, and the pizzas should just override the pizza type, for example.

You use interfaces when you have a shared property, but your classes inherit from different places, or when you don't have any common code you could use. For instance, this is used things that can be disposed IDisposable, you know it will be disposed, you just don't know what will happen when it's disposed.

An interface is just a contract that tells you some things an object can do, what parameters and what return types to expect.

Making a Windows shortcut start relative to where the folder is?

After making the shortcut as you have, set the following in Properties:

Target: %comspec% /k "data\run.bat"

  • Drop the /k if you don't want the prompt to stay open after you've run it.

Start In: %cd%\data

PostgreSQL: ERROR: operator does not exist: integer = character varying

I think it is telling you exactly what is wrong. You cannot compare an integer with a varchar. PostgreSQL is strict and does not do any magic typecasting for you. I'm guessing SQLServer does typecasting automagically (which is a bad thing).

If you want to compare these two different beasts, you will have to cast one to the other using the casting syntax ::.

Something along these lines:

create view view1
as 
select table1.col1,table2.col1,table3.col3
from table1 
inner join
table2 
inner join 
table3
on 
table1.col4::varchar = table2.col5
/* Here col4 of table1 is of "integer" type and col5 of table2 is of type "varchar" */
/* ERROR: operator does not exist: integer = character varying */
....;

Notice the varchar typecasting on the table1.col4.

Also note that typecasting might possibly render your index on that column unusable and has a performance penalty, which is pretty bad. An even better solution would be to see if you can permanently change one of the two column types to match the other one. Literately change your database design.

Or you could create a index on the casted values by using a custom, immutable function which casts the values on the column. But this too may prove suboptimal (but better than live casting).

How to add subject alernative name to ssl certs?

When generating CSR is possible to specify -ext attribute again to have it inserted in the CSR

keytool -certreq -file test.csr -keystore test.jks -alias testAlias -ext SAN=dns:test.example.com

complete example here: How to create CSR with SANs using keytool

SQL TRUNCATE DATABASE ? How to TRUNCATE ALL TABLES

I use this script

EXEC sp_MSForEachTable ‘ALTER TABLE ? NOCHECK CONSTRAINT ALL’
EXEC sp_MSForEachTable ‘DELETE FROM ?’
EXEC sp_MSForEachTable ‘ALTER TABLE ? CHECK CONSTRAINT ALL’
GO

Regex date format validation on Java

I would go with a simple regex which will check that days doesn't have more than 31 days and months no more than 12. Something like:

(0?[1-9]|[12][0-9]|3[01])-(0?[1-9]|1[012])-((18|19|20|21)\\d\\d)

This is the format "dd-MM-yyyy". You can tweak it to your needs (for example take off the ? to make the leading 0 required - now its optional), and then use a custom logic to cut down to the specific rules like leap years February number of days case, and other months number of days cases. See the DateChecker code below.

I am choosing this approach since I tested that this is the best one when performance is taken into account. I checked this (1st) approach versus 2nd approach of validating a date against a regex that takes care of the other use cases, and 3rd approach of using the same simple regex above in combination with SimpleDateFormat.parse(date).
The 1st approach was 4 times faster than the 2nd approach, and 8 times faster than the 3rd approach. See the self contained date checker and performance tester main class at the bottom. One thing that I left unchecked is the joda time approach(s). (The more efficient date/time library).

Date checker code:

class DateChecker {

    private Matcher matcher;
    private Pattern pattern;

    public DateChecker(String regex) {
        pattern = Pattern.compile(regex);
    }

    /**
     * Checks if the date format is a valid.
     * Uses the regex pattern to match the date first. 
     * Than additionally checks are performed on the boundaries of the days taken the month into account (leap years are covered).
     * 
     * @param date the date that needs to be checked.
     * @return if the date is of an valid format or not.
     */
    public boolean check(final String date) {
        matcher = pattern.matcher(date);
        if (matcher.matches()) {
            matcher.reset();
            if (matcher.find()) {
                int day = Integer.parseInt(matcher.group(1));
                int month = Integer.parseInt(matcher.group(2));
                int year = Integer.parseInt(matcher.group(3));

                switch (month) {
                case 1:
                case 3:
                case 5:
                case 7:
                case 8:
                case 10:
                case 12: return day < 32;
                case 4:
                case 6:
                case 9:
                case 11: return day < 31;
                case 2: 
                    int modulo100 = year % 100;
                    //http://science.howstuffworks.com/science-vs-myth/everyday-myths/question50.htm
                    if ((modulo100 == 0 && year % 400 == 0) || (modulo100 != 0 && year % LEAP_STEP == 0)) {
                        //its a leap year
                        return day < 30;
                    } else {
                        return day < 29;
                    }
                default:
                    break;
                }
            }
        }
        return false;
    }

    public String getRegex() {
        return pattern.pattern();
    }
}

Date checking/testing and performance testing:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Tester {

    private static final String[] validDateStrings = new String[]{
        "1-1-2000", //leading 0s for day and month optional
        "01-1-2000", //leading 0 for month only optional
        "1-01-2000", //leading 0 for day only optional
        "01-01-1800", //first accepted date
        "31-12-2199", //last accepted date
        "31-01-2000", //January has 31 days
        "31-03-2000", //March has 31 days
        "31-05-2000", //May has 31 days
        "31-07-2000", //July has 31 days
        "31-08-2000", //August has 31 days
        "31-10-2000", //October has 31 days
        "31-12-2000", //December has 31 days
        "30-04-2000", //April has 30 days
        "30-06-2000", //June has 30 days
        "30-09-2000", //September has 30 days
        "30-11-2000", //November has 30 days
    };
    private static final String[] invalidDateStrings = new String[]{
        "00-01-2000", //there is no 0-th day
        "01-00-2000", //there is no 0-th month
        "31-12-1799", //out of lower boundary date
        "01-01-2200", //out of high boundary date
        "32-01-2000", //January doesn't have 32 days
        "32-03-2000", //March doesn't have 32 days
        "32-05-2000", //May doesn't have 32 days
        "32-07-2000", //July doesn't have 32 days
        "32-08-2000", //August doesn't have 32 days
        "32-10-2000", //October doesn't have 32 days
        "32-12-2000", //December doesn't have 32 days
        "31-04-2000", //April doesn't have 31 days
        "31-06-2000", //June doesn't have 31 days
        "31-09-2000", //September doesn't have 31 days
        "31-11-2000", //November doesn't have 31 days
        "001-02-2000", //SimpleDateFormat valid date (day with leading 0s) even with lenient set to false
        "1-0002-2000", //SimpleDateFormat valid date (month with leading 0s) even with lenient set to false
        "01-02-0003", //SimpleDateFormat valid date (year with leading 0s) even with lenient set to false
        "01.01-2000", //. invalid separator between day and month
        "01-01.2000", //. invalid separator between month and year
        "01/01-2000", /// invalid separator between day and month
        "01-01/2000", /// invalid separator between month and year
        "01_01-2000", //_ invalid separator between day and month
        "01-01_2000", //_ invalid separator between month and year
        "01-01-2000-12345", //only whole string should be matched
        "01-13-2000", //month bigger than 13
    };

    /**
     * These constants will be used to generate the valid and invalid boundary dates for the leap years. (For no leap year, Feb. 28 valid and Feb. 29 invalid; for a leap year Feb. 29 valid and Feb. 30 invalid)   
     */
    private static final int LEAP_STEP = 4;
    private static final int YEAR_START = 1800;
    private static final int YEAR_END = 2199;

    /**
     * This date regex will find matches for valid dates between 1800 and 2199 in the format of "dd-MM-yyyy".
     * The leading 0 is optional.
     */
    private static final String DATE_REGEX = "((0?[1-9]|[12][0-9]|3[01])-(0?[13578]|1[02])-(18|19|20|21)[0-9]{2})|((0?[1-9]|[12][0-9]|30)-(0?[469]|11)-(18|19|20|21)[0-9]{2})|((0?[1-9]|1[0-9]|2[0-8])-(0?2)-(18|19|20|21)[0-9]{2})|(29-(0?2)-(((18|19|20|21)(04|08|[2468][048]|[13579][26]))|2000))";

    /**
     * This date regex is similar to the first one, but with the difference of matching only the whole string. So "01-01-2000-12345" won't pass with a match.
     * Keep in mind that String.matches tries to match only the whole string.
     */
    private static final String DATE_REGEX_ONLY_WHOLE_STRING = "^" + DATE_REGEX + "$";

    /**
     * The simple regex (without checking for 31 day months and leap years):
     */
    private static final String DATE_REGEX_SIMPLE = "(0?[1-9]|[12][0-9]|3[01])-(0?[1-9]|1[012])-((18|19|20|21)\\d\\d)";

    /**
     * This date regex is similar to the first one, but with the difference of matching only the whole string. So "01-01-2000-12345" won't pass with a match.
     */
    private static final String DATE_REGEX_SIMPLE_ONLY_WHOLE_STRING = "^" + DATE_REGEX_SIMPLE + "$";

    private static final SimpleDateFormat SDF = new SimpleDateFormat("dd-MM-yyyy");
    static {
        SDF.setLenient(false);
    }

    private static final DateChecker dateValidatorSimple = new DateChecker(DATE_REGEX_SIMPLE);
    private static final DateChecker dateValidatorSimpleOnlyWholeString = new DateChecker(DATE_REGEX_SIMPLE_ONLY_WHOLE_STRING);

    /**
     * @param args
     */
    public static void main(String[] args) {
        DateTimeStatistics dateTimeStatistics = new DateTimeStatistics();
        boolean shouldMatch = true;
        for (int i = 0; i < validDateStrings.length; i++) {
            String validDate = validDateStrings[i];
            matchAssertAndPopulateTimes(
                    dateTimeStatistics,
                    shouldMatch, validDate);
        }

        shouldMatch = false;
        for (int i = 0; i < invalidDateStrings.length; i++) {
            String invalidDate = invalidDateStrings[i];

            matchAssertAndPopulateTimes(dateTimeStatistics,
                    shouldMatch, invalidDate);
        }

        for (int year = YEAR_START; year < (YEAR_END + 1); year++) {
            FebruaryBoundaryDates februaryBoundaryDates = createValidAndInvalidFebruaryBoundaryDateStringsFromYear(year);
            shouldMatch = true;
            matchAssertAndPopulateTimes(dateTimeStatistics,
                    shouldMatch, februaryBoundaryDates.getValidFebruaryBoundaryDateString());
            shouldMatch = false;
            matchAssertAndPopulateTimes(dateTimeStatistics,
                    shouldMatch, februaryBoundaryDates.getInvalidFebruaryBoundaryDateString());
        }

        dateTimeStatistics.calculateAvarageTimesAndPrint();
    }

    private static void matchAssertAndPopulateTimes(
            DateTimeStatistics dateTimeStatistics,
            boolean shouldMatch, String date) {
        dateTimeStatistics.addDate(date);
        matchAndPopulateTimeToMatch(date, DATE_REGEX, shouldMatch, dateTimeStatistics.getTimesTakenWithDateRegex());
        matchAndPopulateTimeToMatch(date, DATE_REGEX_ONLY_WHOLE_STRING, shouldMatch, dateTimeStatistics.getTimesTakenWithDateRegexOnlyWholeString());
        boolean matchesSimpleDateFormat = matchWithSimpleDateFormatAndPopulateTimeToMatchAndReturnMatches(date, dateTimeStatistics.getTimesTakenWithSimpleDateFormatParse());
        matchAndPopulateTimeToMatchAndReturnMatchesAndCheck(
                dateTimeStatistics.getTimesTakenWithDateRegexSimple(), shouldMatch,
                date, matchesSimpleDateFormat, DATE_REGEX_SIMPLE);
        matchAndPopulateTimeToMatchAndReturnMatchesAndCheck(
                dateTimeStatistics.getTimesTakenWithDateRegexSimpleOnlyWholeString(), shouldMatch,
                date, matchesSimpleDateFormat, DATE_REGEX_SIMPLE_ONLY_WHOLE_STRING);

        matchAndPopulateTimeToMatch(date, dateValidatorSimple, shouldMatch, dateTimeStatistics.getTimesTakenWithdateValidatorSimple());
        matchAndPopulateTimeToMatch(date, dateValidatorSimpleOnlyWholeString, shouldMatch, dateTimeStatistics.getTimesTakenWithdateValidatorSimpleOnlyWholeString());
    }

    private static void matchAndPopulateTimeToMatchAndReturnMatchesAndCheck(
            List<Long> times,
            boolean shouldMatch, String date, boolean matchesSimpleDateFormat, String regex) {
        boolean matchesFromRegex = matchAndPopulateTimeToMatchAndReturnMatches(date, regex, times);
        assert !((matchesSimpleDateFormat && matchesFromRegex) ^ shouldMatch) : "Parsing with SimpleDateFormat and date:" + date + "\nregex:" + regex + "\nshouldMatch:" + shouldMatch;
    }

    private static void matchAndPopulateTimeToMatch(String date, String regex, boolean shouldMatch, List<Long> times) {
        boolean matches = matchAndPopulateTimeToMatchAndReturnMatches(date, regex, times);
        assert !(matches ^ shouldMatch) : "date:" + date + "\nregex:" + regex + "\nshouldMatch:" + shouldMatch;
    }

    private static void matchAndPopulateTimeToMatch(String date, DateChecker dateValidator, boolean shouldMatch, List<Long> times) {
        long timestampStart;
        long timestampEnd;
        boolean matches;
        timestampStart = System.nanoTime();
        matches = dateValidator.check(date);
        timestampEnd = System.nanoTime();
        times.add(timestampEnd - timestampStart);
        assert !(matches ^ shouldMatch) : "date:" + date + "\ndateValidator with regex:" + dateValidator.getRegex() + "\nshouldMatch:" + shouldMatch;
    }

    private static boolean matchAndPopulateTimeToMatchAndReturnMatches(String date, String regex, List<Long> times) {
        long timestampStart;
        long timestampEnd;
        boolean matches;
        timestampStart = System.nanoTime();
        matches = date.matches(regex);
        timestampEnd = System.nanoTime();
        times.add(timestampEnd - timestampStart);
        return matches;
    }

    private static boolean matchWithSimpleDateFormatAndPopulateTimeToMatchAndReturnMatches(String date, List<Long> times) {
        long timestampStart;
        long timestampEnd;
        boolean matches = true;
        timestampStart = System.nanoTime();
        try {
            SDF.parse(date);
        } catch (ParseException e) {
            matches = false;
        } finally {
            timestampEnd = System.nanoTime();
            times.add(timestampEnd - timestampStart);
        }
        return matches;
    }

    private static FebruaryBoundaryDates createValidAndInvalidFebruaryBoundaryDateStringsFromYear(int year) {
        FebruaryBoundaryDates februaryBoundaryDates;
        int modulo100 = year % 100;
        //http://science.howstuffworks.com/science-vs-myth/everyday-myths/question50.htm
        if ((modulo100 == 0 && year % 400 == 0) || (modulo100 != 0 && year % LEAP_STEP == 0)) {
            februaryBoundaryDates = new FebruaryBoundaryDates(
                    createFebruaryDateFromDayAndYear(29, year), 
                    createFebruaryDateFromDayAndYear(30, year)
                    );
        } else {
            februaryBoundaryDates = new FebruaryBoundaryDates(
                    createFebruaryDateFromDayAndYear(28, year), 
                    createFebruaryDateFromDayAndYear(29, year)
                    );
        }
        return februaryBoundaryDates;
    }

    private static String createFebruaryDateFromDayAndYear(int day, int year) {
        return String.format("%d-02-%d", day, year);
    }

    static class FebruaryBoundaryDates {
        private String validFebruaryBoundaryDateString;
        String invalidFebruaryBoundaryDateString;
        public FebruaryBoundaryDates(String validFebruaryBoundaryDateString,
                String invalidFebruaryBoundaryDateString) {
            super();
            this.validFebruaryBoundaryDateString = validFebruaryBoundaryDateString;
            this.invalidFebruaryBoundaryDateString = invalidFebruaryBoundaryDateString;
        }
        public String getValidFebruaryBoundaryDateString() {
            return validFebruaryBoundaryDateString;
        }
        public void setValidFebruaryBoundaryDateString(
                String validFebruaryBoundaryDateString) {
            this.validFebruaryBoundaryDateString = validFebruaryBoundaryDateString;
        }
        public String getInvalidFebruaryBoundaryDateString() {
            return invalidFebruaryBoundaryDateString;
        }
        public void setInvalidFebruaryBoundaryDateString(
                String invalidFebruaryBoundaryDateString) {
            this.invalidFebruaryBoundaryDateString = invalidFebruaryBoundaryDateString;
        }
    }

    static class DateTimeStatistics {
        private List<String> dates = new ArrayList<String>();
        private List<Long> timesTakenWithDateRegex = new ArrayList<Long>();
        private List<Long> timesTakenWithDateRegexOnlyWholeString = new ArrayList<Long>();
        private List<Long> timesTakenWithDateRegexSimple = new ArrayList<Long>();
        private List<Long> timesTakenWithDateRegexSimpleOnlyWholeString = new ArrayList<Long>();
        private List<Long> timesTakenWithSimpleDateFormatParse = new ArrayList<Long>();
        private List<Long> timesTakenWithdateValidatorSimple = new ArrayList<Long>();
        private List<Long> timesTakenWithdateValidatorSimpleOnlyWholeString = new ArrayList<Long>();
        public List<String> getDates() {
            return dates;
        }
        public List<Long> getTimesTakenWithDateRegex() {
            return timesTakenWithDateRegex;
        }
        public List<Long> getTimesTakenWithDateRegexOnlyWholeString() {
            return timesTakenWithDateRegexOnlyWholeString;
        }
        public List<Long> getTimesTakenWithDateRegexSimple() {
            return timesTakenWithDateRegexSimple;
        }
        public List<Long> getTimesTakenWithDateRegexSimpleOnlyWholeString() {
            return timesTakenWithDateRegexSimpleOnlyWholeString;
        }
        public List<Long> getTimesTakenWithSimpleDateFormatParse() {
            return timesTakenWithSimpleDateFormatParse;
        }
        public List<Long> getTimesTakenWithdateValidatorSimple() {
            return timesTakenWithdateValidatorSimple;
        }
        public List<Long> getTimesTakenWithdateValidatorSimpleOnlyWholeString() {
            return timesTakenWithdateValidatorSimpleOnlyWholeString;
        }
        public void addDate(String date) {
            dates.add(date);
        }
        public void addTimesTakenWithDateRegex(long time) {
            timesTakenWithDateRegex.add(time);
        }
        public void addTimesTakenWithDateRegexOnlyWholeString(long time) {
            timesTakenWithDateRegexOnlyWholeString.add(time);
        }
        public void addTimesTakenWithDateRegexSimple(long time) {
            timesTakenWithDateRegexSimple.add(time);
        }
        public void addTimesTakenWithDateRegexSimpleOnlyWholeString(long time) {
            timesTakenWithDateRegexSimpleOnlyWholeString.add(time);
        }
        public void addTimesTakenWithSimpleDateFormatParse(long time) {
            timesTakenWithSimpleDateFormatParse.add(time);
        }
        public void addTimesTakenWithdateValidatorSimple(long time) {
            timesTakenWithdateValidatorSimple.add(time);
        }
        public void addTimesTakenWithdateValidatorSimpleOnlyWholeString(long time) {
            timesTakenWithdateValidatorSimpleOnlyWholeString.add(time);
        }

        private void calculateAvarageTimesAndPrint() {
            long[] sumOfTimes = new long[7];
            int timesSize = timesTakenWithDateRegex.size();
            for (int i = 0; i < timesSize; i++) {
                sumOfTimes[0] += timesTakenWithDateRegex.get(i);
                sumOfTimes[1] += timesTakenWithDateRegexOnlyWholeString.get(i);
                sumOfTimes[2] += timesTakenWithDateRegexSimple.get(i);
                sumOfTimes[3] += timesTakenWithDateRegexSimpleOnlyWholeString.get(i);
                sumOfTimes[4] += timesTakenWithSimpleDateFormatParse.get(i);
                sumOfTimes[5] += timesTakenWithdateValidatorSimple.get(i);
                sumOfTimes[6] += timesTakenWithdateValidatorSimpleOnlyWholeString.get(i);
            }
            System.out.println("AVG from timesTakenWithDateRegex (in nanoseconds):" + (double) sumOfTimes[0] / timesSize);
            System.out.println("AVG from timesTakenWithDateRegexOnlyWholeString (in nanoseconds):" + (double) sumOfTimes[1] / timesSize);
            System.out.println("AVG from timesTakenWithDateRegexSimple (in nanoseconds):" + (double) sumOfTimes[2] / timesSize);
            System.out.println("AVG from timesTakenWithDateRegexSimpleOnlyWholeString (in nanoseconds):" + (double) sumOfTimes[3] / timesSize);
            System.out.println("AVG from timesTakenWithSimpleDateFormatParse (in nanoseconds):" + (double) sumOfTimes[4] / timesSize);
            System.out.println("AVG from timesTakenWithDateRegexSimple + timesTakenWithSimpleDateFormatParse (in nanoseconds):" + (double) (sumOfTimes[2] + sumOfTimes[4]) / timesSize);
            System.out.println("AVG from timesTakenWithDateRegexSimpleOnlyWholeString + timesTakenWithSimpleDateFormatParse (in nanoseconds):" + (double) (sumOfTimes[3] + sumOfTimes[4]) / timesSize);
            System.out.println("AVG from timesTakenWithdateValidatorSimple (in nanoseconds):" + (double) sumOfTimes[5] / timesSize);
            System.out.println("AVG from timesTakenWithdateValidatorSimpleOnlyWholeString (in nanoseconds):" + (double) sumOfTimes[6] / timesSize);
        }
    }

    static class DateChecker {

        private Matcher matcher;
        private Pattern pattern;

        public DateChecker(String regex) {
            pattern = Pattern.compile(regex);
        }

        /**
         * Checks if the date format is a valid.
         * Uses the regex pattern to match the date first. 
         * Than additionally checks are performed on the boundaries of the days taken the month into account (leap years are covered).
         * 
         * @param date the date that needs to be checked.
         * @return if the date is of an valid format or not.
         */
        public boolean check(final String date) {
            matcher = pattern.matcher(date);
            if (matcher.matches()) {
                matcher.reset();
                if (matcher.find()) {
                    int day = Integer.parseInt(matcher.group(1));
                    int month = Integer.parseInt(matcher.group(2));
                    int year = Integer.parseInt(matcher.group(3));

                    switch (month) {
                    case 1:
                    case 3:
                    case 5:
                    case 7:
                    case 8:
                    case 10:
                    case 12: return day < 32;
                    case 4:
                    case 6:
                    case 9:
                    case 11: return day < 31;
                    case 2: 
                        int modulo100 = year % 100;
                        //http://science.howstuffworks.com/science-vs-myth/everyday-myths/question50.htm
                        if ((modulo100 == 0 && year % 400 == 0) || (modulo100 != 0 && year % LEAP_STEP == 0)) {
                            //its a leap year
                            return day < 30;
                        } else {
                            return day < 29;
                        }
                    default:
                        break;
                    }
                }
            }
            return false;
        }

        public String getRegex() {
            return pattern.pattern();
        }
    }
}

Some useful notes:
- to enable the assertions (assert checks) you need to use -ea argument when running the tester. (In eclipse this is done by editing the Run/Debug configuration -> Arguments tab -> VM Arguments -> insert "-ea"
- the regex above is bounded to years 1800 to 2199
- you don't need to use ^ at the beginning and $ at the end to match only the whole date string. The String.matches takes care of that.
- make sure u check the valid and invalid cases and change them according the rules that you have.
- the "only whole string" version of each regex gives the same speed as the "normal" version (the one without ^ and $). If you see performance differences this is because java "gets used" to processing the same instructions so the time lowers. If you switch the lines where the "normal" and the "only whole string" version execute, you will see this proven.

Hope this helps someone!
Cheers,
Despot

In Java, how to append a string more efficiently?

You can use StringBuffer or StringBuilder for this. Both are for dynamic string manipulation. StringBuffer is thread-safe where as StringBuilder is not.

Use StringBuffer in a multi-thread environment. But if it is single threaded StringBuilder is recommended and it is much faster than StringBuffer.

Reloading/refreshing Kendo Grid

Just write below code

$('.k-i-refresh').click();

How to add hours to current time in python

from datetime import datetime, timedelta

nine_hours_from_now = datetime.now() + timedelta(hours=9)
#datetime.datetime(2012, 12, 3, 23, 24, 31, 774118)

And then use string formatting to get the relevant pieces:

>>> '{:%H:%M:%S}'.format(nine_hours_from_now)
'23:24:31'

If you're only formatting the datetime then you can use:

>>> format(nine_hours_from_now, '%H:%M:%S')
'23:24:31'

Or, as @eumiro has pointed out in comments - strftime

Passing an array/list into a Python function

When you define your function using this syntax:

def someFunc(*args):
    for x in args
        print x

You're telling it that you expect a variable number of arguments. If you want to pass in a List (Array from other languages) you'd do something like this:

def someFunc(myList = [], *args):
    for x in myList:
        print x

Then you can call it with this:

items = [1,2,3,4,5]

someFunc(items)

You need to define named arguments before variable arguments, and variable arguments before keyword arguments. You can also have this:

def someFunc(arg1, arg2, arg3, *args, **kwargs):
    for x in args
        print x

Which requires at least three arguments, and supports variable numbers of other arguments and keyword arguments.

Closing Twitter Bootstrap Modal From Angular Controller

You can do it like this:

angular.element('#modal').modal('hide');

Change column type in pandas

You have four main options for converting types in pandas:

  1. to_numeric() - provides functionality to safely convert non-numeric types (e.g. strings) to a suitable numeric type. (See also to_datetime() and to_timedelta().)

  2. astype() - convert (almost) any type to (almost) any other type (even if it's not necessarily sensible to do so). Also allows you to convert to categorial types (very useful).

  3. infer_objects() - a utility method to convert object columns holding Python objects to a pandas type if possible.

  4. convert_dtypes() - convert DataFrame columns to the "best possible" dtype that supports pd.NA (pandas' object to indicate a missing value).

Read on for more detailed explanations and usage of each of these methods.


1. to_numeric()

The best way to convert one or more columns of a DataFrame to numeric values is to use pandas.to_numeric().

This function will try to change non-numeric objects (such as strings) into integers or floating point numbers as appropriate.

Basic usage

The input to to_numeric() is a Series or a single column of a DataFrame.

>>> s = pd.Series(["8", 6, "7.5", 3, "0.9"]) # mixed string and numeric values
>>> s
0      8
1      6
2    7.5
3      3
4    0.9
dtype: object

>>> pd.to_numeric(s) # convert everything to float values
0    8.0
1    6.0
2    7.5
3    3.0
4    0.9
dtype: float64

As you can see, a new Series is returned. Remember to assign this output to a variable or column name to continue using it:

# convert Series
my_series = pd.to_numeric(my_series)

# convert column "a" of a DataFrame
df["a"] = pd.to_numeric(df["a"])

You can also use it to convert multiple columns of a DataFrame via the apply() method:

# convert all columns of DataFrame
df = df.apply(pd.to_numeric) # convert all columns of DataFrame

# convert just columns "a" and "b"
df[["a", "b"]] = df[["a", "b"]].apply(pd.to_numeric)

As long as your values can all be converted, that's probably all you need.

Error handling

But what if some values can't be converted to a numeric type?

to_numeric() also takes an errors keyword argument that allows you to force non-numeric values to be NaN, or simply ignore columns containing these values.

Here's an example using a Series of strings s which has the object dtype:

>>> s = pd.Series(['1', '2', '4.7', 'pandas', '10'])
>>> s
0         1
1         2
2       4.7
3    pandas
4        10
dtype: object

The default behaviour is to raise if it can't convert a value. In this case, it can't cope with the string 'pandas':

>>> pd.to_numeric(s) # or pd.to_numeric(s, errors='raise')
ValueError: Unable to parse string

Rather than fail, we might want 'pandas' to be considered a missing/bad numeric value. We can coerce invalid values to NaN as follows using the errors keyword argument:

>>> pd.to_numeric(s, errors='coerce')
0     1.0
1     2.0
2     4.7
3     NaN
4    10.0
dtype: float64

The third option for errors is just to ignore the operation if an invalid value is encountered:

>>> pd.to_numeric(s, errors='ignore')
# the original Series is returned untouched

This last option is particularly useful when you want to convert your entire DataFrame, but don't not know which of our columns can be converted reliably to a numeric type. In that case just write:

df.apply(pd.to_numeric, errors='ignore')

The function will be applied to each column of the DataFrame. Columns that can be converted to a numeric type will be converted, while columns that cannot (e.g. they contain non-digit strings or dates) will be left alone.

Downcasting

By default, conversion with to_numeric() will give you either a int64 or float64 dtype (or whatever integer width is native to your platform).

That's usually what you want, but what if you wanted to save some memory and use a more compact dtype, like float32, or int8?

to_numeric() gives you the option to downcast to either 'integer', 'signed', 'unsigned', 'float'. Here's an example for a simple series s of integer type:

>>> s = pd.Series([1, 2, -7])
>>> s
0    1
1    2
2   -7
dtype: int64

Downcasting to 'integer' uses the smallest possible integer that can hold the values:

>>> pd.to_numeric(s, downcast='integer')
0    1
1    2
2   -7
dtype: int8

Downcasting to 'float' similarly picks a smaller than normal floating type:

>>> pd.to_numeric(s, downcast='float')
0    1.0
1    2.0
2   -7.0
dtype: float32

2. astype()

The astype() method enables you to be explicit about the dtype you want your DataFrame or Series to have. It's very versatile in that you can try and go from one type to the any other.

Basic usage

Just pick a type: you can use a NumPy dtype (e.g. np.int16), some Python types (e.g. bool), or pandas-specific types (like the categorical dtype).

Call the method on the object you want to convert and astype() will try and convert it for you:

# convert all DataFrame columns to the int64 dtype
df = df.astype(int)

# convert column "a" to int64 dtype and "b" to complex type
df = df.astype({"a": int, "b": complex})

# convert Series to float16 type
s = s.astype(np.float16)

# convert Series to Python strings
s = s.astype(str)

# convert Series to categorical type - see docs for more details
s = s.astype('category')

Notice I said "try" - if astype() does not know how to convert a value in the Series or DataFrame, it will raise an error. For example if you have a NaN or inf value you'll get an error trying to convert it to an integer.

As of pandas 0.20.0, this error can be suppressed by passing errors='ignore'. Your original object will be return untouched.

Be careful

astype() is powerful, but it will sometimes convert values "incorrectly". For example:

>>> s = pd.Series([1, 2, -7])
>>> s
0    1
1    2
2   -7
dtype: int64

These are small integers, so how about converting to an unsigned 8-bit type to save memory?

>>> s.astype(np.uint8)
0      1
1      2
2    249
dtype: uint8

The conversion worked, but the -7 was wrapped round to become 249 (i.e. 28 - 7)!

Trying to downcast using pd.to_numeric(s, downcast='unsigned') instead could help prevent this error.


3. infer_objects()

Version 0.21.0 of pandas introduced the method infer_objects() for converting columns of a DataFrame that have an object datatype to a more specific type (soft conversions).

For example, here's a DataFrame with two columns of object type. One holds actual integers and the other holds strings representing integers:

>>> df = pd.DataFrame({'a': [7, 1, 5], 'b': ['3','2','1']}, dtype='object')
>>> df.dtypes
a    object
b    object
dtype: object

Using infer_objects(), you can change the type of column 'a' to int64:

>>> df = df.infer_objects()
>>> df.dtypes
a     int64
b    object
dtype: object

Column 'b' has been left alone since its values were strings, not integers. If you wanted to try and force the conversion of both columns to an integer type, you could use df.astype(int) instead.


4. convert_dtypes()

Version 1.0 and above includes a method convert_dtypes() to convert Series and DataFrame columns to the best possible dtype that supports the pd.NA missing value.

Here "best possible" means the type most suited to hold the values. For example, this a pandas integer type if all of the values are integers (or missing values): an object column of Python integer objects is converted to Int64, a column of NumPy int32 values will become the pandas dtype Int32.

With our object DataFrame df, we get the following result:

>>> df.convert_dtypes().dtypes                                             
a     Int64
b    string
dtype: object

Since column 'a' held integer values, it was converted to the Int64 type (which is capable of holding missing values, unlike int64).

Column 'b' contained string objects, so was changed to pandas' string dtype.

By default, this method will infer the type from object values in each column. We can change this by passing infer_objects=False:

>>> df.convert_dtypes(infer_objects=False).dtypes                          
a    object
b    string
dtype: object

Now column 'a' remained an object column: pandas knows it can be described as an 'integer' column (internally it ran infer_dtype) but didn't infer exactly what dtype of integer it should have so did not convert it. Column 'b' was again converted to 'string' dtype as it was recognised as holding 'string' values.

C#: New line and tab characters in strings

sb.AppendLine();

or

sb.Append( "\n" );

And

sb.Append( "\t" );

How to Extract Year from DATE in POSTGRESQL

This line solved my same problem in postgresql:

SELECT DATE_PART('year', column_name::date) from tableName;

If you want month, then simply replacing year with month solves that as well and likewise.

Annotations from javax.validation.constraints not working

If you are using lombok then, you can use @NonNull annotation insted. or Just add the javax.validation dependency in pom.xml file.

Move a view up only when the keyboard covers an input field

Just use this extension to move any UIView when keyboard is presented.

extension UIView {
    func bindToKeyboard(){
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillChange(_:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }

    @objc func keyboardWillChange(_ notification: NSNotification){
        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
        let curve = notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! UInt
        let beginningFrame = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
        let endFrame = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue

        let deltaY = endFrame.origin.y - beginningFrame.origin.y

        UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIViewKeyframeAnimationOptions(rawValue: curve), animations: {
            self.frame.origin.y += deltaY
        }, completion: nil)
    }
}

Then in your viewdidload bind your view to the keyboard

UiView.bindToKeyboard()

Python if not == vs if !=

@jonrsharpe has an excellent explanation of what's going on. I thought I'd just show the difference in time when running each of the 3 options 10,000,000 times (enough for a slight difference to show).

Code used:

def a(x):
    if x != 'val':
        pass


def b(x):
    if not x == 'val':
        pass


def c(x):
    if x == 'val':
        pass
    else:
        pass


x = 1
for i in range(10000000):
    a(x)
    b(x)
    c(x)

And the cProfile profiler results:

enter image description here

So we can see that there is a very minute difference of ~0.7% between if not x == 'val': and if x != 'val':. Of these, if x != 'val': is the fastest.

However, most surprisingly, we can see that

if x == 'val':
        pass
    else:

is in fact the fastest, and beats if x != 'val': by ~0.3%. This isn't very readable, but I guess if you wanted a negligible performance improvement, one could go down this route.

MySQL/SQL: Group by date only on a Datetime column

Cast the datetime to a date, then GROUP BY using this syntax:

SELECT SUM(foo), DATE(mydate) FROM a_table GROUP BY DATE(a_table.mydate);

Or you can GROUP BY the alias as @orlandu63 suggested:

SELECT SUM(foo), DATE(mydate) DateOnly FROM a_table GROUP BY DateOnly;

Though I don't think it'll make any difference to performance, it is a little clearer.

Declaring an unsigned int in Java

Perhaps this is what you meant?

long getUnsigned(int signed) {
    return signed >= 0 ? signed : 2 * (long) Integer.MAX_VALUE + 2 + signed;
}
  • getUnsigned(0) ? 0
  • getUnsigned(1) ? 1
  • getUnsigned(Integer.MAX_VALUE) ? 2147483647
  • getUnsigned(Integer.MIN_VALUE) ? 2147483648
  • getUnsigned(Integer.MIN_VALUE + 1) ? 2147483649

Preserve Line Breaks From TextArea When Writing To MySQL

Got my own answer: Using this function from the data from the textarea solves the problem:

function mynl2br($text) { 
   return strtr($text, array("\r\n" => '<br />', "\r" => '<br />', "\n" => '<br />')); 
} 

More here: http://php.net/nl2br

Java generics - get class?

I'm not 100% sure if this works in all cases (needs at least Java 1.5):

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

public class Main 
{
    public class A
    {   
    }

    public class B extends A
    {       
    }


    public Map<A, B> map = new HashMap<Main.A, Main.B>();

    public static void main(String[] args) 
    {

        try
        {
            Field field = Main.class.getField("map");           
            System.out.println("Field " + field.getName() + " is of type " + field.getType().getSimpleName());

            Type genericType = field.getGenericType();

            if(genericType instanceof ParameterizedType)
            {
                ParameterizedType type = (ParameterizedType) genericType;               
                Type[] typeArguments = type.getActualTypeArguments();

                for(Type typeArgument : typeArguments) 
                {   
                    Class<?> classType = ((Class<?>)typeArgument);                  
                    System.out.println("Field " + field.getName() + " has a parameterized type of " + classType.getSimpleName());
                }
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }    
}

This will output:

Field map is of type Map
Field map has a parameterized type of A
Field map has a parameterized type of B

How to call another controller Action From a controller in Mvc

Let the resolver automatically do that.

Inside A controller:

public class AController : ApiController
{
    private readonly BController _bController;

    public AController(
    BController bController)
    {
        _bController = bController;
    }

    public httpMethod{
    var result =  _bController.OtherMethodBController(parameters);
    ....
    }

}

Shell script not running, command not found

Make sure you are not using "PATH" as a variable, which will override the existing PATH for environment variables.

Find files and tar them (with spaces)

Why not:

tar czvf backup.tar.gz *

Sure it's clever to use find and then xargs, but you're doing it the hard way.

Update: Porges has commented with a find-option that I think is a better answer than my answer, or the other one: find -print0 ... | xargs -0 ....

How to test an SQL Update statement before running it?

make a SELECT of it,

like if you got

UPDATE users SET id=0 WHERE name='jan'

convert it to

SELECT * FROM users WHERE name='jan'

nginx error "conflicting server name" ignored

You have another server_name ec2-xx-xx-xxx-xxx.us-west-1.compute.amazonaws.com somewhere in the config.

Control flow in T-SQL SP using IF..ELSE IF - are there other ways?

Nope IF is the way to go, what is the problem you have with using it?

BTW your example won't ever get to the third block of code as it and the second block are exactly alike.

Displaying standard DataTables in MVC

Here is the answer in Razor syntax

 <table border="1" cellpadding="5">
    <thead>
       <tr>
          @foreach (System.Data.DataColumn col in Model.Columns)
          {
             <th>@col.Caption</th>
          }
       </tr>
    </thead>
    <tbody>
    @foreach(System.Data.DataRow row in Model.Rows)
    {
       <tr>
          @foreach (var cell in row.ItemArray)
          {
             <td>@cell.ToString()</td>
          }
       </tr>
    }      
    </tbody>
</table>

Can I grep only the first n lines of a file?

You have a few options using programs along with grep. The simplest in my opinion is to use head:

head -n10 filename | grep ...

head will output the first 10 lines (using the -n option), and then you can pipe that output to grep.

jquery validate check at least one checkbox

 if ($('input:checkbox').filter(':checked').length < 1){
        alert("Check at least one!");
 return false;
 }

How do I read the first line of a file using cat?

There are many different ways:

sed -n 1p file
head -n 1 file
awk 'NR==1' file

Finding the position of bottom of a div with jquery

use this script to calculate end of div

$('#bottom').offset().top +$('#bottom').height()

Showing alert in angularjs when user leaves a page

Here is the directive I use. It automatically cleans itself up when the form is unloaded. If you want to prevent the prompt from firing (e.g. because you successfully saved the form), call $scope.FORMNAME.$setPristine(), where FORMNAME is the name of the form you want to prevent from prompting.

.directive('dirtyTracking', [function () {
    return {
        restrict: 'A',
        link: function ($scope, $element, $attrs) {
            function isDirty() {
                var formObj = $scope[$element.attr('name')];
                return formObj && formObj.$pristine === false;
            }

            function areYouSurePrompt() {
                if (isDirty()) {
                    return 'You have unsaved changes. Are you sure you want to leave this page?';
                }
            }

            window.addEventListener('beforeunload', areYouSurePrompt);

            $element.bind("$destroy", function () {
                window.removeEventListener('beforeunload', areYouSurePrompt);
            });

            $scope.$on('$locationChangeStart', function (event) {
                var prompt = areYouSurePrompt();
                if (!event.defaultPrevented && prompt && !confirm(prompt)) {
                    event.preventDefault();
                }
            });
        }
    };
}]);

How to include css files in Vue 2

As you can see, the import command did work but is showing errors because it tried to locate the resources in vendor.css and couldn't find them

You should also upload your project structure and ensure that there aren't any path issues. Also, you could include the css file in the index.html or the Component template and webpack loader would extract it when built

Removing header column from pandas dataframe

I had the same problem but solved it in this way:

df = pd.read_csv('your-array.csv', skiprows=[0])

Get last record of a table in Postgres

Easy way: ORDER BY in conjunction with LIMIT

SELECT timestamp, value, card
FROM my_table
ORDER BY timestamp DESC
LIMIT 1;

However, LIMIT is not standard and as stated by Wikipedia, The SQL standard's core functionality does not explicitly define a default sort order for Nulls.. Finally, only one row is returned when several records share the maximum timestamp.

Relational way:

The typical way of doing this is to check that no row has a higher timestamp than any row we retrieve.

SELECT timestamp, value, card
FROM my_table t1
WHERE NOT EXISTS (
  SELECT *
  FROM my_table t2
  WHERE t2.timestamp > t1.timestamp
);

It is my favorite solution, and the one I tend to use. The drawback is that our intent is not immediately clear when having a glimpse on this query.

Instructive way: MAX

To circumvent this, one can use MAX in the subquery instead of the correlation.

SELECT timestamp, value, card
FROM my_table
WHERE timestamp = (
  SELECT MAX(timestamp)
  FROM my_table
);

But without an index, two passes on the data will be necessary whereas the previous query can find the solution with only one scan. That said, we should not take performances into consideration when designing queries unless necessary, as we can expect optimizers to improve over time. However this particular kind of query is quite used.

Show off way: Windowing functions

I don't recommend doing this, but maybe you can make a good impression on your boss or something ;-)

SELECT DISTINCT
  first_value(timestamp) OVER w,
  first_value(value) OVER w,
  first_value(card) OVER w
FROM my_table
WINDOW w AS (ORDER BY timestamp DESC);

Actually this has the virtue of showing that a simple query can be expressed in a wide variety of ways (there are several others I can think of), and that picking one or the other form should be done according to several criteria such as:

  • portability (Relational/Instructive ways)
  • efficiency (Relational way)
  • expressiveness (Easy/Instructive way)

Converting map to struct

You can do it ... it may get a bit ugly and you'll be faced with some trial and error in terms of mapping types .. but heres the basic gist of it:

func FillStruct(data map[string]interface{}, result interface{}) {
    t := reflect.ValueOf(result).Elem()
    for k, v := range data {
        val := t.FieldByName(k)
        val.Set(reflect.ValueOf(v))
    }
}

Working sample: http://play.golang.org/p/PYHz63sbvL

How to enter a multi-line command

$scriptBlock = [Scriptblock]::Create(@'
  echo 'before'
  ipconfig /all
  echo 'after'
'@)

Invoke-Command -ComputerName AD01 -ScriptBlock $scriptBlock

source
don't use backquote

How to get the file name from a full path using JavaScript?

What platform does the path come from? Windows paths are different from POSIX paths are different from Mac OS 9 paths are different from RISC OS paths are different...

If it's a web app where the filename can come from different platforms there is no one solution. However a reasonable stab is to use both '\' (Windows) and '/' (Linux/Unix/Mac and also an alternative on Windows) as path separators. Here's a non-RegExp version for extra fun:

var leafname= pathname.split('\\').pop().split('/').pop();

"SetPropertiesRule" warning message when starting Tomcat from Eclipse

I am using Eclipse. I have resolved this problem by the following:

  1. Open servers tab.
  2. Double click on the server you are using.
  3. On the server configuration page go to server options page.
  4. Check Serve module without publishing.
  5. Then save the page and configurations.
  6. Restart the server by rebuild all the applications.

You will not get any this kind of error.

internet explorer 10 - how to apply grayscale filter?

Inline SVG can be used in IE 10 and 11 and Edge 12.

I've created a project called gray which includes a polyfill for these browsers. The polyfill switches out <img> tags with inline SVG: https://github.com/karlhorky/gray

To implement, the short version is to download the jQuery plugin at the GitHub link above and add after jQuery at the end of your body:

<script src="/js/jquery.gray.min.js"></script>

Then every image with the class grayscale will appear as gray.

<img src="/img/color.jpg" class="grayscale">

You can see a demo too if you like.

PHP passing $_GET in linux command prompt

php file_name.php var1 var2 varN

Then set your $_GET variables on your first line in PHP, although this is not the desired way of setting a $_GET variable and you may experience problems depending on what you do later with that variable.

if (isset($argv[1])) {
   $_GET['variable_name'] = $argv[1];
}

the variables you launch the script with will be accessible from the $argv array in your PHP app. the first entry will the name of the script they came from, so you may want to do an array_shift($argv) to drop that first entry if you want to process a bunch of variables. Or just load into a local variable.

Prevent any form of page refresh using jQuery/Javascript

#1 can be implemented via window.onbeforeunload.

For example:

<script type="text/javascript">
    window.onbeforeunload = function() {
        return "Dude, are you sure you want to leave? Think of the kittens!";
    }
</script>

The user will be prompted with the message, and given an option to stay on the page or continue on their way. This is becoming more common. Stack Overflow does this if you try to navigate away from a page while you are typing a post. You can't completely stop the user from reloading, but you can make it sound real scary if they do.

#2 is more or less impossible. Even if you tracked sessions and user logins, you still wouldn't be able to guarantee that you were detecting a second tab correctly. For example, maybe I have one window open, then close it. Now I open a new window. You would likely detect that as a second tab, even though I already closed the first one. Now your user can't access the first window because they closed it, and they can't access the second window because you're denying them.

In fact, my bank's online system tries real hard to do #2, and the situation described above happens all the time. I usually have to wait until the server-side session expires before I can use the banking system again.

WinForms DataGridView font size

'   Cell style
 With .DefaultCellStyle
     .BackColor = Color.Black
     .ForeColor = Color.White 
     .Font = New System.Drawing.Font("Microsoft Sans Serif", 11.0!,
   System.Drawing.FontStyle.Regular,
   System.Drawing.GraphicsUnit.Point, CType(0, Byte))
      .Alignment = DataGridViewContentAlignment.MiddleRight
 End With

How add class='active' to html menu with php

seperate your page from nav bar.

pageOne.php:

$page="one";
include("navigation.php");

navigation.php

if($page=="one"){$oneIsActive = 'class="active"';}else{ $oneIsActive=""; }
if($page=="two"){$twoIsActive = 'class="active"';}else{ $twoIsActive=""; }
if($page=="three"){$threeIsActive = 'class="active"';}else{ $threeIsActive=""; }

<ul class="nav">
  <li <?php echo $oneIsActive; ?>><a href="pageOne.php">One</a></li>
  <li <?php echo $twoIsActive; ?>><a href="pageTwo.php"><a href="#">Page 2</a></li>
  <li <?php echo $threeIsActive; ?>><a href="pageThree.php"><a href="#">Page 3</a></li>
</ul>

I found that I could also set the title of my pages with this method as well.

 $page="one";
 $title="This is page one."
 include("navigation.php");

and just grab the $title var and put it in between the "title" tags. Though I am sending it to my header page above my nav bar.

NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver

It may happen after your Linux kernel update, if you entered this error, you can rebuild your nvidia driver using the following command to fix:

  1. Firstly, you need to have dkms, which can automatically regenerate new modules after kernel version changes.
    sudo apt-get install dkms
  2. Secondly, rebuild your nvidia driver. Here my nvidia driver version is 440.82, if you have installed before, you could check your installed version on /usr/src.
    sudo dkms build -m nvidia -v 440.82
  3. Lastly, reinstall nvidia driver. And then reboot your computer.
    sudo dkms install -m nvidia -v 440.82

Now you can check to see if you can use it by sudo nvidia-smi.

when exactly are we supposed to use "public static final String"?

  1. Static means..You can use it without instantiate of the class or using any object.
  2. final..It is a keyword which is used for make the string constant. You can not change the value of that string. Look at the example below:

      public class StringTest { 
               static final String str = "Hello"; 
      public static void main(String args[]) { 
               // str = "world"; // gives error 
               System.out.println(str); // called without the help of an object                       
               System.out.println(StringTest.str);// called with class name  
                 } 
             } 
    

Thanks

MySQL foreach alternative for procedure

This can be done with MySQL, although it's highly unintuitive:

CREATE PROCEDURE p25 (OUT return_val INT)
BEGIN
  DECLARE a,b INT;
  DECLARE cur_1 CURSOR FOR SELECT s1 FROM t;
  DECLARE CONTINUE HANDLER FOR NOT FOUND
  SET b = 1;
  OPEN cur_1;
  REPEAT
    FETCH cur_1 INTO a;
    UNTIL b = 1
  END REPEAT;
  CLOSE cur_1;
  SET return_val = a;
END;//

Check out this guide: mysql-storedprocedures.pdf

Simple way to encode a string according to a password?

Python has no built-in encryption schemes, no. You also should take encrypted data storage serious; trivial encryption schemes that one developer understands to be insecure and a toy scheme may well be mistaken for a secure scheme by a less experienced developer. If you encrypt, encrypt properly.

You don’t need to do much work to implement a proper encryption scheme however. First of all, don’t re-invent the cryptography wheel, use a trusted cryptography library to handle this for you. For Python 3, that trusted library is cryptography.

I also recommend that encryption and decryption applies to bytes; encode text messages to bytes first; stringvalue.encode() encodes to UTF8, easily reverted again using bytesvalue.decode().

Last but not least, when encrypting and decrypting, we talk about keys, not passwords. A key should not be human memorable, it is something you store in a secret location but machine readable, whereas a password often can be human-readable and memorised. You can derive a key from a password, with a little care.

But for a web application or process running in a cluster without human attention to keep running it, you want to use a key. Passwords are for when only an end-user needs access to the specific information. Even then, you usually secure the application with a password, then exchange encrypted information using a key, perhaps one attached to the user account.

Symmetric key encryption

Fernet – AES CBC + HMAC, strongly recommended

The cryptography library includes the Fernet recipe, a best-practices recipe for using cryptography. Fernet is an open standard, with ready implementations in a wide range of programming languages and it packages AES CBC encryption for you with version information, a timestamp and an HMAC signature to prevent message tampering.

Fernet makes it very easy to encrypt and decrypt messages and keep you secure. It is the ideal method for encrypting data with a secret.

I recommend you use Fernet.generate_key() to generate a secure key. You can use a password too (next section), but a full 32-byte secret key (16 bytes to encrypt with, plus another 16 for the signature) is going to be more secure than most passwords you could think of.

The key that Fernet generates is a bytes object with URL and file safe base64 characters, so printable:

from cryptography.fernet import Fernet

key = Fernet.generate_key()  # store in a secure location
print("Key:", key.decode())

To encrypt or decrypt messages, create a Fernet() instance with the given key, and call the Fernet.encrypt() or Fernet.decrypt(), both the plaintext message to encrypt and the encrypted token are bytes objects.

encrypt() and decrypt() functions would look like:

from cryptography.fernet import Fernet

def encrypt(message: bytes, key: bytes) -> bytes:
    return Fernet(key).encrypt(message)

def decrypt(token: bytes, key: bytes) -> bytes:
    return Fernet(key).decrypt(token)

Demo:

>>> key = Fernet.generate_key()
>>> print(key.decode())
GZWKEhHGNopxRdOHS4H4IyKhLQ8lwnyU7vRLrM3sebY=
>>> message = 'John Doe'
>>> encrypt(message.encode(), key)
'gAAAAABciT3pFbbSihD_HZBZ8kqfAj94UhknamBuirZWKivWOukgKQ03qE2mcuvpuwCSuZ-X_Xkud0uWQLZ5e-aOwLC0Ccnepg=='
>>> token = _
>>> decrypt(token, key).decode()
'John Doe'

Fernet with password – key derived from password, weakens the security somewhat

You can use a password instead of a secret key, provided you use a strong key derivation method. You do then have to include the salt and the HMAC iteration count in the message, so the encrypted value is not Fernet-compatible anymore without first separating salt, count and Fernet token:

import secrets
from base64 import urlsafe_b64encode as b64e, urlsafe_b64decode as b64d

from cryptography.fernet import Fernet
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

backend = default_backend()
iterations = 100_000

def _derive_key(password: bytes, salt: bytes, iterations: int = iterations) -> bytes:
    """Derive a secret key from a given password and salt"""
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(), length=32, salt=salt,
        iterations=iterations, backend=backend)
    return b64e(kdf.derive(password))

def password_encrypt(message: bytes, password: str, iterations: int = iterations) -> bytes:
    salt = secrets.token_bytes(16)
    key = _derive_key(password.encode(), salt, iterations)
    return b64e(
        b'%b%b%b' % (
            salt,
            iterations.to_bytes(4, 'big'),
            b64d(Fernet(key).encrypt(message)),
        )
    )

def password_decrypt(token: bytes, password: str) -> bytes:
    decoded = b64d(token)
    salt, iter, token = decoded[:16], decoded[16:20], b64e(decoded[20:])
    iterations = int.from_bytes(iter, 'big')
    key = _derive_key(password.encode(), salt, iterations)
    return Fernet(key).decrypt(token)

Demo:

>>> message = 'John Doe'
>>> password = 'mypass'
>>> password_encrypt(message.encode(), password)
b'9Ljs-w8IRM3XT1NDBbSBuQABhqCAAAAAAFyJdhiCPXms2vQHO7o81xZJn5r8_PAtro8Qpw48kdKrq4vt-551BCUbcErb_GyYRz8SVsu8hxTXvvKOn9QdewRGDfwx'
>>> token = _
>>> password_decrypt(token, password).decode()
'John Doe'

Including the salt in the output makes it possible to use a random salt value, which in turn ensures the encrypted output is guaranteed to be fully random regardless of password reuse or message repetition. Including the iteration count ensures that you can adjust for CPU performance increases over time without losing the ability to decrypt older messages.

A password alone can be as safe as a Fernet 32-byte random key, provided you generate a properly random password from a similar size pool. 32 bytes gives you 256 ^ 32 number of keys, so if you use an alphabet of 74 characters (26 upper, 26 lower, 10 digits and 12 possible symbols), then your password should be at least math.ceil(math.log(256 ** 32, 74)) == 42 characters long. However, a well-selected larger number of HMAC iterations can mitigate the lack of entropy somewhat as this makes it much more expensive for an attacker to brute force their way in.

Just know that choosing a shorter but still reasonably secure password won’t cripple this scheme, it just reduces the number of possible values a brute-force attacker would have to search through; make sure to pick a strong enough password for your security requirements.

Alternatives

Obscuring

An alternative is not to encrypt. Don't be tempted to just use a low-security cipher, or a home-spun implementation of, say Vignere. There is no security in these approaches, but may give an inexperienced developer that is given the task to maintain your code in future the illusion of security, which is worse than no security at all.

If all you need is obscurity, just base64 the data; for URL-safe requirements, the base64.urlsafe_b64encode() function is fine. Don't use a password here, just encode and you are done. At most, add some compression (like zlib):

import zlib
from base64 import urlsafe_b64encode as b64e, urlsafe_b64decode as b64d

def obscure(data: bytes) -> bytes:
    return b64e(zlib.compress(data, 9))

def unobscure(obscured: bytes) -> bytes:
    return zlib.decompress(b64d(obscured))

This turns b'Hello world!' into b'eNrzSM3JyVcozy_KSVEEAB0JBF4='.

Integrity only

If all you need is a way to make sure that the data can be trusted to be unaltered after having been sent to an untrusted client and received back, then you want to sign the data, you can use the hmac library for this with SHA1 (still considered secure for HMAC signing) or better:

import hmac
import hashlib

def sign(data: bytes, key: bytes, algorithm=hashlib.sha256) -> bytes:
    assert len(key) >= algorithm().digest_size, (
        "Key must be at least as long as the digest size of the "
        "hashing algorithm"
    )
    return hmac.new(key, data, algorithm).digest()

def verify(signature: bytes, data: bytes, key: bytes, algorithm=hashlib.sha256) -> bytes:
    expected = sign(data, key, algorithm)
    return hmac.compare_digest(expected, signature)

Use this to sign data, then attach the signature with the data and send that to the client. When you receive the data back, split data and signature and verify. I've set the default algorithm to SHA256, so you'll need a 32-byte key:

key = secrets.token_bytes(32)

You may want to look at the itsdangerous library, which packages this all up with serialisation and de-serialisation in various formats.

Using AES-GCM encryption to provide encryption and integrity

Fernet builds on AEC-CBC with a HMAC signature to ensure integrity of the encrypted data; a malicious attacker can't feed your system nonsense data to keep your service busy running in circles with bad input, because the ciphertext is signed.

The Galois / Counter mode block cipher produces ciphertext and a tag to serve the same purpose, so can be used to serve the same purposes. The downside is that unlike Fernet there is no easy-to-use one-size-fits-all recipe to reuse on other platforms. AES-GCM also doesn't use padding, so this encryption ciphertext matches the length of the input message (whereas Fernet / AES-CBC encrypts messages to blocks of fixed length, obscuring the message length somewhat).

AES256-GCM takes the usual 32 byte secret as a key:

key = secrets.token_bytes(32)

then use

import binascii, time
from base64 import urlsafe_b64encode as b64e, urlsafe_b64decode as b64d

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
from cryptography.exceptions import InvalidTag

backend = default_backend()

def aes_gcm_encrypt(message: bytes, key: bytes) -> bytes:
    current_time = int(time.time()).to_bytes(8, 'big')
    algorithm = algorithms.AES(key)
    iv = secrets.token_bytes(algorithm.block_size // 8)
    cipher = Cipher(algorithm, modes.GCM(iv), backend=backend)
    encryptor = cipher.encryptor()
    encryptor.authenticate_additional_data(current_time)
    ciphertext = encryptor.update(message) + encryptor.finalize()        
    return b64e(current_time + iv + ciphertext + encryptor.tag)

def aes_gcm_decrypt(token: bytes, key: bytes, ttl=None) -> bytes:
    algorithm = algorithms.AES(key)
    try:
        data = b64d(token)
    except (TypeError, binascii.Error):
        raise InvalidToken
    timestamp, iv, tag = data[:8], data[8:algorithm.block_size // 8 + 8], data[-16:]
    if ttl is not None:
        current_time = int(time.time())
        time_encrypted, = int.from_bytes(data[:8], 'big')
        if time_encrypted + ttl < current_time or current_time + 60 < time_encrypted:
            # too old or created well before our current time + 1 h to account for clock skew
            raise InvalidToken
    cipher = Cipher(algorithm, modes.GCM(iv, tag), backend=backend)
    decryptor = cipher.decryptor()
    decryptor.authenticate_additional_data(timestamp)
    ciphertext = data[8 + len(iv):-16]
    return decryptor.update(ciphertext) + decryptor.finalize()

I've included a timestamp to support the same time-to-live use-cases that Fernet supports.

Other approaches on this page, in Python 3

AES CFB - like CBC but without the need to pad

This is the approach that All ?? V????y follows, albeit incorrectly. This is the cryptography version, but note that I include the IV in the ciphertext, it should not be stored as a global (reusing an IV weakens the security of the key, and storing it as a module global means it'll be re-generated the next Python invocation, rendering all ciphertext undecryptable):

import secrets
from base64 import urlsafe_b64encode as b64e, urlsafe_b64decode as b64d

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend

backend = default_backend()

def aes_cfb_encrypt(message, key):
    algorithm = algorithms.AES(key)
    iv = secrets.token_bytes(algorithm.block_size // 8)
    cipher = Cipher(algorithm, modes.CFB(iv), backend=backend)
    encryptor = cipher.encryptor()
    ciphertext = encryptor.update(message) + encryptor.finalize()
    return b64e(iv + ciphertext)

def aes_cfb_decrypt(ciphertext, key):
    iv_ciphertext = b64d(ciphertext)
    algorithm = algorithms.AES(key)
    size = algorithm.block_size // 8
    iv, encrypted = iv_ciphertext[:size], iv_ciphertext[size:]
    cipher = Cipher(algorithm, modes.CFB(iv), backend=backend)
    decryptor = cipher.decryptor()
    return decryptor.update(encrypted) + decryptor.finalize()

This lacks the added armoring of an HMAC signature and there is no timestamp; you’d have to add those yourself.

The above also illustrates how easy it is to combine basic cryptography building blocks incorrectly; All ?? V????y‘s incorrect handling of the IV value can lead to a data breach or all encrypted messages being unreadable because the IV is lost. Using Fernet instead protects you from such mistakes.

AES ECB – not secure

If you previously implemented AES ECB encryption and need to still support this in Python 3, you can do so still with cryptography too. The same caveats apply, ECB is not secure enough for real-life applications. Re-implementing that answer for Python 3, adding automatic handling of padding:

from base64 import urlsafe_b64encode as b64e, urlsafe_b64decode as b64d

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.backends import default_backend

backend = default_backend()

def aes_ecb_encrypt(message, key):
    cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=backend)
    encryptor = cipher.encryptor()
    padder = padding.PKCS7(cipher.algorithm.block_size).padder()
    padded = padder.update(msg_text.encode()) + padder.finalize()
    return b64e(encryptor.update(padded) + encryptor.finalize())

def aes_ecb_decrypt(ciphertext, key):
    cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=backend)
    decryptor = cipher.decryptor()
    unpadder = padding.PKCS7(cipher.algorithm.block_size).unpadder()
    padded = decryptor.update(b64d(ciphertext)) + decryptor.finalize()
    return unpadder.update(padded) + unpadder.finalize()

Again, this lacks the HMAC signature, and you shouldn’t use ECB anyway. The above is there merely to illustrate that cryptography can handle the common cryptographic building blocks, even the ones you shouldn’t actually use.

How to declare array of zeros in python (or an array of a certain size)

use numpy

import numpy
zarray = numpy.zeros(100)

And then use the Histogram library function

How do I clear my local working directory in Git?

Use:

git clean -df

It's not well advertised, but git clean is really handy. Git Ready has a nice introduction to git clean.

What does the star operator mean, in a function call?

I find this particularly useful for when you want to 'store' a function call.

For example, suppose I have some unit tests for a function 'add':

def add(a, b): return a + b
tests = { (1,4):5, (0, 0):0, (-1, 3):3 }
for test, result in tests.items():
    print 'test: adding', test, '==', result, '---', add(*test) == result

There is no other way to call add, other than manually doing something like add(test[0], test[1]), which is ugly. Also, if there are a variable number of variables, the code could get pretty ugly with all the if-statements you would need.

Another place this is useful is for defining Factory objects (objects that create objects for you). Suppose you have some class Factory, that makes Car objects and returns them. You could make it so that myFactory.make_car('red', 'bmw', '335ix') creates Car('red', 'bmw', '335ix'), then returns it.

def make_car(*args):
    return Car(*args)

This is also useful when you want to call a superclass' constructor.

JavaScript/regex: Remove text between parentheses

I found this version most suitable for all cases. It doesn't remove all whitespaces.

For example "a (test) b" -> "a b"

"Hello, this is Mike (example)".replace(/ *\([^)]*\) */g, " ").trim(); "Hello, this is (example) Mike ".replace(/ *\([^)]*\) */g, " ").trim();

XML Document to String

Assuming doc is your instance of org.w3c.dom.Document:

TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String output = writer.getBuffer().toString().replaceAll("\n|\r", "");

Combine a list of data frames into one data frame by row

bind-plot

Code:

library(microbenchmark)

dflist <- vector(length=10,mode="list")
for(i in 1:100)
{
  dflist[[i]] <- data.frame(a=runif(n=260),b=runif(n=260),
                            c=rep(LETTERS,10),d=rep(LETTERS,10))
}


mb <- microbenchmark(
plyr::rbind.fill(dflist),
dplyr::bind_rows(dflist),
data.table::rbindlist(dflist),
plyr::ldply(dflist,data.frame),
do.call("rbind",dflist),
times=1000)

ggplot2::autoplot(mb)

Session:

R version 3.3.0 (2016-05-03)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

> packageVersion("plyr")
[1] ‘1.8.4’
> packageVersion("dplyr")
[1] ‘0.5.0’
> packageVersion("data.table")
[1] ‘1.9.6’

UPDATE: Rerun 31-Jan-2018. Ran on the same computer. New versions of packages. Added seed for seed lovers.

enter image description here

set.seed(21)
library(microbenchmark)

dflist <- vector(length=10,mode="list")
for(i in 1:100)
{
  dflist[[i]] <- data.frame(a=runif(n=260),b=runif(n=260),
                            c=rep(LETTERS,10),d=rep(LETTERS,10))
}


mb <- microbenchmark(
  plyr::rbind.fill(dflist),
  dplyr::bind_rows(dflist),
  data.table::rbindlist(dflist),
  plyr::ldply(dflist,data.frame),
  do.call("rbind",dflist),
  times=1000)

ggplot2::autoplot(mb)+theme_bw()


R version 3.4.0 (2017-04-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

> packageVersion("plyr")
[1] ‘1.8.4’
> packageVersion("dplyr")
[1] ‘0.7.2’
> packageVersion("data.table")
[1] ‘1.10.4’

UPDATE: Rerun 06-Aug-2019.

enter image description here

set.seed(21)
library(microbenchmark)

dflist <- vector(length=10,mode="list")
for(i in 1:100)
{
  dflist[[i]] <- data.frame(a=runif(n=260),b=runif(n=260),
                            c=rep(LETTERS,10),d=rep(LETTERS,10))
}


mb <- microbenchmark(
  plyr::rbind.fill(dflist),
  dplyr::bind_rows(dflist),
  data.table::rbindlist(dflist),
  plyr::ldply(dflist,data.frame),
  do.call("rbind",dflist),
  purrr::map_df(dflist,dplyr::bind_rows),
  times=1000)

ggplot2::autoplot(mb)+theme_bw()

R version 3.6.0 (2019-04-26)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 18.04.2 LTS

Matrix products: default
BLAS:   /usr/lib/x86_64-linux-gnu/openblas/libblas.so.3
LAPACK: /usr/lib/x86_64-linux-gnu/libopenblasp-r0.2.20.so

packageVersion("plyr")
packageVersion("dplyr")
packageVersion("data.table")
packageVersion("purrr")

>> packageVersion("plyr")
[1] ‘1.8.4’
>> packageVersion("dplyr")
[1] ‘0.8.3’
>> packageVersion("data.table")
[1] ‘1.12.2’
>> packageVersion("purrr")
[1] ‘0.3.2’

Running python script inside ipython

In python there is no difference between modules and scripts; You can execute both scripts and modules. The file must be on the pythonpath AFAIK because python must be able to find the file in question. If python is executed from a directory, then the directory is automatically added to the pythonpath.

Refer to What is the best way to call a Python script from another Python script? for more information about modules vs scripts

There is also a builtin function execfile(filename) that will do what you want

How to remove any URL within a string in Python

I know this has already been answered and its stupid late but I think this should be here. This is a regex that matches any kind of url.

[^ ]+\.[^ ]+

It can be used like

re.sub('[^ ]+\.[^ ]+','',sentence)

git returns http error 407 from proxy after CONNECT

I experienced this error due to my corporate network using one proxy while on premise, and a second (completely different) proxy when VPN'd from the outside. I was originally configured for the on-premise proxy, received the error, and then had to update my config to use the alternate, off-prem, proxy when working elsewhere.

How can I convert this foreach code to Parallel.ForEach?

Foreach loop:

  • Iterations takes place sequentially, one by one
  • foreach loop is run from a single Thread.
  • foreach loop is defined in every framework of .NET
  • Execution of slow processes can be slower, as they're run serially
    • Process 2 can't start until 1 is done. Process 3 can't start until 2 & 1 are done...
  • Execution of quick processes can be faster, as there is no threading overhead

Parallel.ForEach:

  • Execution takes place in parallel way.
  • Parallel.ForEach uses multiple Threads.
  • Parallel.ForEach is defined in .Net 4.0 and above frameworks.
  • Execution of slow processes can be faster, as they can be run in parallel
    • Processes 1, 2, & 3 may run concurrently (see reused threads in example, below)
  • Execution of quick processes can be slower, because of additional threading overhead

The following example clearly demonstrates the difference between traditional foreach loop and

Parallel.ForEach() Example

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace ParallelForEachExample
{
    class Program
    {
        static void Main()
        {
            string[] colors = {
                                  "1. Red",
                                  "2. Green",
                                  "3. Blue",
                                  "4. Yellow",
                                  "5. White",
                                  "6. Black",
                                  "7. Violet",
                                  "8. Brown",
                                  "9. Orange",
                                  "10. Pink"
                              };
            Console.WriteLine("Traditional foreach loop\n");
            //start the stopwatch for "for" loop
            var sw = Stopwatch.StartNew();
            foreach (string color in colors)
            {
                Console.WriteLine("{0}, Thread Id= {1}", color, Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(10);
            }
            Console.WriteLine("foreach loop execution time = {0} seconds\n", sw.Elapsed.TotalSeconds);
            Console.WriteLine("Using Parallel.ForEach");
            //start the stopwatch for "Parallel.ForEach"
             sw = Stopwatch.StartNew();
            Parallel.ForEach(colors, color =>
            {
                Console.WriteLine("{0}, Thread Id= {1}", color, Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(10);
            }
            );
            Console.WriteLine("Parallel.ForEach() execution time = {0} seconds", sw.Elapsed.TotalSeconds);
            Console.Read();
        }
    }
}

Output

Traditional foreach loop
1. Red, Thread Id= 10
2. Green, Thread Id= 10
3. Blue, Thread Id= 10
4. Yellow, Thread Id= 10
5. White, Thread Id= 10
6. Black, Thread Id= 10
7. Violet, Thread Id= 10
8. Brown, Thread Id= 10
9. Orange, Thread Id= 10
10. Pink, Thread Id= 10
foreach loop execution time = 0.1054376 seconds

Using Parallel.ForEach example

1. Red, Thread Id= 10
3. Blue, Thread Id= 11
4. Yellow, Thread Id= 11
2. Green, Thread Id= 10
5. White, Thread Id= 12
7. Violet, Thread Id= 14
9. Orange, Thread Id= 13
6. Black, Thread Id= 11
8. Brown, Thread Id= 10
10. Pink, Thread Id= 12
Parallel.ForEach() execution time = 0.055976 seconds

C# nullable string error

For nullable, use ? with all of the C# primitives, except for string.

The following page gives a list of the C# primitives: http://msdn.microsoft.com/en-us/library/aa711900(v=vs.71).aspx

How to store phone numbers on MySQL databases?

I would definitely split them. It would be easy to sort the numbers by area code and contry code. But even if you're not going to split, just insert the numbers into the DB in one certain format. e.g. 1-555-555-1212 Your client side will be thankfull for not making it reformat your numbers.

How do I detect whether a Python variable is a function?

Since Python 2.1 you can import isfunction from the inspect module.

>>> from inspect import isfunction
>>> def f(): pass
>>> isfunction(f)
True
>>> isfunction(lambda x: x)
True

RegEx to extract all matches from string using RegExp.exec

Here is my answer:

var str = '[me nombre es] : My name is. [Yo puedo] is the right word'; 

var reg = /\[(.*?)\]/g;

var a = str.match(reg);

a = a.toString().replace(/[\[\]]/g, "").split(','));

Passing data to components in vue.js

-------------Following is applicable only to Vue 1 --------------

Passing data can be done in multiple ways. The method depends on the type of use.


If you want to pass data from your html while you add a new component. That is done using props.

<my-component prop-name="value"></my-component>

This prop value will be available to your component only if you add the prop name prop-name to your props attribute.


When data is passed from a component to another component because of some dynamic or static event. That is done by using event dispatchers and broadcasters. So for example if you have a component structure like this:

<my-parent>
    <my-child-A></my-child-A>
    <my-child-B></my-child-B>
</my-parent>

And you want to send data from <my-child-A> to <my-child-B> then in <my-child-A> you will have to dispatch an event:

this.$dispatch('event_name', data);

This event will travel all the way up the parent chain. And from whichever parent you have a branch toward <my-child-B> you broadcast the event along with the data. So in the parent:

events:{
    'event_name' : function(data){
        this.$broadcast('event_name', data);
    },

Now this broadcast will travel down the child chain. And at whichever child you want to grab the event, in our case <my-child-B> we will add another event:

events: {
    'event_name' : function(data){
        // Your code. 
    },
},

The third way to pass data is through parameters in v-links. This method is used when components chains are completely destroyed or in cases when the URI changes. And i can see you already understand them.


Decide what type of data communication you want, and choose appropriately.

How to read a file from jar in Java?

Ah, this is one of my favorite subjects. There are essentially two ways you can load a resource through the classpath:

Class.getResourceAsStream(resource)

and

ClassLoader.getResourceAsStream(resource)

(there are other ways which involve getting a URL for the resource in a similar fashion, then opening a connection to it, but these are the two direct ways).

The first method actually delegates to the second, after mangling the resource name. There are essentially two kinds of resource names: absolute (e.g. "/path/to/resource/resource") and relative (e.g. "resource"). Absolute paths start with "/".

Here's an example which should illustrate. Consider a class com.example.A. Consider two resources, one located at /com/example/nested, the other at /top, in the classpath. The following program shows nine possible ways to access the two resources:

package com.example;

public class A {

    public static void main(String args[]) {

        // Class.getResourceAsStream
        Object resource = A.class.getResourceAsStream("nested");
        System.out.println("1: A.class nested=" + resource);

        resource = A.class.getResourceAsStream("/com/example/nested");
        System.out.println("2: A.class /com/example/nested=" + resource);

        resource = A.class.getResourceAsStream("top");
        System.out.println("3: A.class top=" + resource);

        resource = A.class.getResourceAsStream("/top");
        System.out.println("4: A.class /top=" + resource);

        // ClassLoader.getResourceAsStream
        ClassLoader cl = A.class.getClassLoader();
        resource = cl.getResourceAsStream("nested");        
        System.out.println("5: cl nested=" + resource);

        resource = cl.getResourceAsStream("/com/example/nested");
        System.out.println("6: cl /com/example/nested=" + resource);
        resource = cl.getResourceAsStream("com/example/nested");
        System.out.println("7: cl com/example/nested=" + resource);

        resource = cl.getResourceAsStream("top");
        System.out.println("8: cl top=" + resource);

        resource = cl.getResourceAsStream("/top");
        System.out.println("9: cl /top=" + resource);
    }

}

The output from the program is:

1: A.class nested=java.io.BufferedInputStream@19821f
2: A.class /com/example/nested=java.io.BufferedInputStream@addbf1
3: A.class top=null
4: A.class /top=java.io.BufferedInputStream@42e816
5: cl nested=null
6: cl /com/example/nested=null
7: cl com/example/nested=java.io.BufferedInputStream@9304b1
8: cl top=java.io.BufferedInputStream@190d11
9: cl /top=null

Mostly things do what you'd expect. Case-3 fails because class relative resolving is with respect to the Class, so "top" means "/com/example/top", but "/top" means what it says.

Case-5 fails because classloader relative resolving is with respect to the classloader. But, unexpectedly Case-6 also fails: one might expect "/com/example/nested" to resolve properly. To access a nested resource through the classloader you need to use Case-7, i.e. the nested path is relative to the root of the classloader. Likewise Case-9 fails, but Case-8 passes.

Remember: for java.lang.Class, getResourceAsStream() does delegate to the classloader:

     public InputStream getResourceAsStream(String name) {
        name = resolveName(name);
        ClassLoader cl = getClassLoader0();
        if (cl==null) {
            // A system class.
            return ClassLoader.getSystemResourceAsStream(name);
        }
        return cl.getResourceAsStream(name);
    }

so it is the behavior of resolveName() that is important.

Finally, since it is the behavior of the classloader that loaded the class that essentially controls getResourceAsStream(), and the classloader is often a custom loader, then the resource-loading rules may be even more complex. e.g. for Web-Applications, load from WEB-INF/classes or WEB-INF/lib in the context of the web application, but not from other web-applications which are isolated. Also, well-behaved classloaders delegate to parents, so that duplicateed resources in the classpath may not be accessible using this mechanism.

Authentication issues with WWW-Authenticate: Negotiate

The web server is prompting you for a SPNEGO (Simple and Protected GSSAPI Negotiation Mechanism) token.

This is a Microsoft invention for negotiating a type of authentication to use for Web SSO (single-sign-on):

  • either NTLM
  • or Kerberos.

See:

Cropping images in the browser BEFORE the upload

Yes, it can be done.
It is based on the new html5 "download" attribute of anchor tags.
The flow should be something like this :

  1. load the image
  2. draw the image into a canvas with the crop boundaries specified
  3. get the image data from the canvas and make it a href attribute for an anchor tag in the dom
  4. add the download attribute (download="desired-file-name") to that a element That's it. all the user has to do is click your "download link" and the image will be downloaded to his pc.

I'll come back with a demo when I get the chance.

Update
Here's the live demo as I promised. It takes the jsfiddle logo and crops 5px of each margin.
The code looks like this :

var img = new Image();
img.onload = function(){
    var cropMarginWidth = 5,
        canvas = $('<canvas/>')
                    .attr({
                         width: img.width - 2 * cropMarginWidth,
                         height: img.height - 2 * cropMarginWidth
                     })
                    .hide()
                    .appendTo('body'),
        ctx = canvas.get(0).getContext('2d'),
        a = $('<a download="cropped-image" title="click to download the image" />'),
        cropCoords = {
            topLeft : {
                x : cropMarginWidth,
                y : cropMarginWidth 
            },
            bottomRight :{
                x : img.width - cropMarginWidth,
                y : img.height - cropMarginWidth
            }
        };

    ctx.drawImage(img, cropCoords.topLeft.x, cropCoords.topLeft.y, cropCoords.bottomRight.x, cropCoords.bottomRight.y, 0, 0, img.width, img.height);
    var base64ImageData = canvas.get(0).toDataURL();


    a
        .attr('href', base64ImageData)
        .text('cropped image')
        .appendTo('body');

    a
        .clone()
        .attr('href', img.src)
        .text('original image')
        .attr('download','original-image')
        .appendTo('body');

    canvas.remove();
}
img.src = 'some-image-src';

Update II
Forgot to mention : of course there is a downside :(.
Because of the same-origin policy that is applied to images too, if you want to access an image's data (through the canvas method toDataUrl).
So you would still need a server-side proxy that would serve your image as if it were hosted on your domain.

Update III Although I can't provide a live demo for this (for security reasons), here is a php sample code that solves the same-origin policy :

file proxy.php :

$imgData = getimagesize($_GET['img']);
header("Content-type: " . $imgData['mime']);
echo file_get_contents($_GET['img']);  

This way, instead of loading the external image direct from it's origin :

img.src = 'http://some-domain.com/imagefile.png';

You can load it through your proxy :

img.src = 'proxy.php?img=' + encodeURIComponent('http://some-domain.com/imagefile.png');  

And here's a sample php code for saving the image data (base64) into an actual image :

file save-image.php :

$data = preg_replace('/data:image\/(png|jpg|jpeg|gif|bmp);base64/','',$_POST['data']);
$data = base64_decode($data);
$img = imagecreatefromstring($data);

$path = 'path-to-saved-images/';
// generate random name
$name  = substr(md5(time()),10);
$ext = 'png';
$imageName = $path.$name.'.'.$ext;

// write the image to disk
imagepng($img,  $imageName);
imagedestroy($img);
// return the image path
echo $imageName;

All you have to do then is post the image data to this file and it will save the image to disc and return you the existing image filename.

Of course all this might feel a bit complicated, but I wanted to show you that what you're trying to achieve is possible.

Converting URL to String and back again

Swift 3 used with UIWebViewDelegate shouldStartLoadWith

  func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {

    let urlPath: String = (request.url?.absoluteString)!
    print(urlPath)
    if urlPath.characters.last == "#" {
        return false
    }else{
        return true
    }

}

Java: is there a map function?

There is no notion of a function in the JDK as of java 6.

Guava has a Function interface though and the
Collections2.transform(Collection<E>, Function<E,E2>)
method provides the functionality you require.

Example:

// example, converts a collection of integers to their
// hexadecimal string representations
final Collection<Integer> input = Arrays.asList(10, 20, 30, 40, 50);
final Collection<String> output =
    Collections2.transform(input, new Function<Integer, String>(){

        @Override
        public String apply(final Integer input){
            return Integer.toHexString(input.intValue());
        }
    });
System.out.println(output);

Output:

[a, 14, 1e, 28, 32]

These days, with Java 8, there is actually a map function, so I'd probably write the code in a more concise way:

Collection<String> hex = input.stream()
                              .map(Integer::toHexString)
                              .collect(Collectors::toList);

When using SASS how can I import a file from a different directory?

Look into using the includePaths parameter...

"The SASS compiler uses each path in loadPaths when resolving SASS @imports."

https://stackoverflow.com/a/33588202/384884

How to check SQL Server version

select charindex(  'Express',@@version)

if this value is 0 is not a express edition

Converting string from snake_case to CamelCase in Ruby

If you're using Rails, String#camelize is what you're looking for.

  "active_record".camelize                # => "ActiveRecord"
  "active_record".camelize(:lower)        # => "activeRecord"

If you want to get an actual class, you should use String#constantize on top of that.

"app_user".camelize.constantize

VSCode regex find & replace submatch math?

Another simple example:

Search: style="(.+?)"
Replace: css={css`$1`}

Useful for converting HTML to JSX with emotion/css!

Verifying that a string contains only letters in C#

For those of you who would rather not go with Regex and are on the .NET 2.0 Framework (AKA no LINQ):

Only Letters:

public static bool IsAllLetters(string s)
{
    foreach (char c in s)
    {
        if (!Char.IsLetter(c))
            return false;
    }
    return true;
}

Only Numbers:

    public static bool IsAllDigits(string s)
    {
        foreach (char c in s)
        {
            if (!Char.IsDigit(c))
                return false;
        }
        return true;
    }

Only Numbers Or Letters:

    public static bool IsAllLettersOrDigits(string s)
    {
        foreach (char c in s)
        {
            if (!Char.IsLetterOrDigit(c))
                return false;
        }
        return true;
    }

Only Numbers Or Letters Or Underscores:

    public static bool IsAllLettersOrDigitsOrUnderscores(string s)
    {
        foreach (char c in s)
        {
            if (!Char.IsLetterOrDigit(c) && c != '_')
                return false;
        }
        return true;
    }

How to get the fragment instance from the FragmentActivity?

To get the fragment instance in a class that extends FragmentActivity:

MyclassFragment instanceFragment=
    (MyclassFragment)getSupportFragmentManager().findFragmentById(R.id.idFragment);

To get the fragment instance in a class that extends Fragment:

MyclassFragment instanceFragment =  
    (MyclassFragment)getFragmentManager().findFragmentById(R.id.idFragment);

How can one create an overlay in css?

I would suggest using css attributes to do this. You can use position:absolute to position an element on top of another.

For example:

<div id="container">
   <div id="on-top">Top!</div>
   <div id="on-bottom">Bottom!</div>
</div>

and css

#container {position:relative;}
#on-top {position:absolute; z-index:5;}
#on-bottom {position:absolute; z-index:4;}

I would take a look at this for advice: http://www.w3schools.com/cssref/pr_class_position.asp

And finally here is a jsfiddle to show you my example

http://jsfiddle.net/Wgfw6/

Asp.net - Add blank item at top of dropdownlist

After your databind:

drpList.Items.Insert(0, new ListItem(String.Empty, String.Empty));
drpList.SelectedIndex = 0;

delete all record from table in mysql

It’s because you tried to update a table without a WHERE that uses a KEY column.

The quick fix is to add SET SQL_SAFE_UPDATES=0; before your query :

SET SQL_SAFE_UPDATES=0; 

Or

close the safe update mode. Edit -> Preferences -> SQL Editor -> SQL Editor remove Forbid UPDATE and DELETE statements without a WHERE clause (safe updates) .

BTW you can use TRUNCATE TABLE tablename; to delete all the records .

jQuery scrollTop not working in Chrome but working in Firefox

If your CSS html element has the following overflow markup, scrollTop will not function.

html {
    overflow-x: hidden;
    overflow-y: hidden;
}

To allow scrollTop to scroll, modify your markup remove overflow markup from the html element and append to a body element.

body { 
    overflow-x: hidden;
    overflow-y: hidden;
}

Unable to load AWS credentials from the /AwsCredentials.properties file on the classpath

If you're wanting to use Environment variables using apache/tomcat, I found that the only way they could be found was setting them in tomcat/bin/setenv.sh (where catalina_opts are set - might be catalina.sh in your setup)

export AWS_ACCESS_KEY_ID=*********;

export AWS_SECRET_ACCESS_KEY=**************;

If you're using ubuntu, try logging in as ubuntu $printenv then log in as root $printenv, the environmental variables won't necessarily be the same....

If you only want to use environmental variables you can use: com.amazonaws.auth.EnvironmentVariableCredentialsProvider

instead of:

com.amazonaws.auth.DefaultAWSCredentialsProviderChain

(which by default checks all 4 possible locations)

anyway after hours of trying to figure out why my environmental variables weren't being found...this worked for me.

Best way to remove duplicate entries from a data table

In order to distinct all datatable columns, you can easily retrieve the names of the columns in a string array

public static DataTable RemoveDuplicateRows(this DataTable dataTable)
{
    List<string> columnNames = new List<string>();
    foreach (DataColumn col in dataTable.Columns)
    {
        columnNames.Add(col.ColumnName);
    }
    return dataTable.DefaultView.ToTable(true, columnNames.Select(c => c.ToString()).ToArray());
}

As you can notice, I thought of using it as an extension to DataTable class

WSDL vs REST Pros and Cons

The previous answers contain a lot of information, but I think there is a philosophical difference that hasn't been pointed out. SOAP was the answer to "how to we create a modern, object-oriented, platform and protocol independent successor to RPC?". REST developed from the question, "how to we take the insights that made HTTP so successful for the web, and use them for distributed computing?"

SOAP is a about giving you tools to make distributed programming look like ... programming. REST tries to impose a style to simplify distributed interfaces, so that distributed resources can refer to each other like distributed html pages can refer to each other. One way it does that is attempt to (mostly) restrict operations to "CRUD" on resources (create, read, update, delete).

REST is still young -- although it is oriented towards "human readable" services, it doesn't rule out introspection services, etc. or automatic creation of proxies. However, these have not been standardized (as I write). SOAP gives you these things, but (IMHO) gives you "only" these things, whereas the style imposed by REST is already encouraging the spread of web services because of its simplicity. I would myself encourage newbie service providers to choose REST unless there are specific SOAP-provided features they need to use.

In my opinion, then, if you are implementing a "greenfield" API, and don't know that much about possible clients, I would choose REST as the style it encourages tends to help make interfaces comprehensible, and easy to develop to. If you know a lot about client and server, and there are specific SOAP tools that will make life easy for both, then I wouldn't be religious about REST, though.

How to shuffle an ArrayList

Use this method and pass your array in parameter

Collections.shuffle(arrayList);

This method return void so it will not give you a new list but as we know that array is passed as a reference type in Java so it will shuffle your array and save shuffled values in it. That's why you don't need any return type.

You can now use arraylist which is shuffled.

How can I get a resource "Folder" from inside my jar File?

The following code returns the wanted "folder" as Path regardless of if it is inside a jar or not.

  private Path getFolderPath() throws URISyntaxException, IOException {
    URI uri = getClass().getClassLoader().getResource("folder").toURI();
    if ("jar".equals(uri.getScheme())) {
      FileSystem fileSystem = FileSystems.newFileSystem(uri, Collections.emptyMap(), null);
      return fileSystem.getPath("path/to/folder/inside/jar");
    } else {
      return Paths.get(uri);
    }
  }

Requires java 7+.

Find file in directory from command line

When I was in the UNIX world (using tcsh (sigh...)), I used to have all sorts of "find" aliases/scripts setup for searching for files. I think the default "find" syntax is a little clunky, so I used to have aliases/scripts to pipe "find . -print" into grep, which allows you to use regular expressions for searching:

# finds all .java files starting in current directory
find . -print | grep '\.java'

#finds all .java files whose name contains "Message"
find . -print | grep '.*Message.*\.java'

Of course, the above examples can be done with plain-old find, but if you have a more specific search, grep can help quite a bit. This works pretty well, unless "find . -print" has too many directories to recurse through... then it gets pretty slow. (for example, you wouldn't want to do this starting in root "/")

How to add calendar events in Android?

if you have a given Date string with date and time .

for e.g String givenDateString = pojoModel.getDate()/* Format dd-MMM-yyyy hh:mm:ss */

use the following code to add an event with date and time to the calendar

Calendar cal = Calendar.getInstance();
cal.setTime(new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss").parse(givenDateString));
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", cal.getTimeInMillis());
intent.putExtra("allDay", false);
intent.putExtra("rrule", "FREQ=YEARLY");
intent.putExtra("endTime",cal.getTimeInMillis() + 60 * 60 * 1000);
intent.putExtra("title", " Test Title");
startActivity(intent);

Jquery find nearest matching element

Get the .column parent of the this element, get its previous sibling, then find any input there:

$(this).closest(".column").prev().find("input:first").val();

Demo: http://jsfiddle.net/aWhtP/

Remove an item from a dictionary when its key is unknown

Be aware that you're currently testing for object identity (is only returns True if both operands are represented by the same object in memory - this is not always the case with two object that compare equal with ==). If you are doing this on purpose, then you could rewrite your code as

some_dict = {key: value for key, value in some_dict.items() 
             if value is not value_to_remove}

But this may not do what you want:

>>> some_dict = {1: "Hello", 2: "Goodbye", 3: "You say yes", 4: "I say no"}
>>> value_to_remove = "You say yes"
>>> some_dict = {key: value for key, value in some_dict.items() if value is not value_to_remove}
>>> some_dict
{1: 'Hello', 2: 'Goodbye', 3: 'You say yes', 4: 'I say no'}
>>> some_dict = {key: value for key, value in some_dict.items() if value != value_to_remove}
>>> some_dict
{1: 'Hello', 2: 'Goodbye', 4: 'I say no'}

So you probably want != instead of is not.

error: RPC failed; curl transfer closed with outstanding read data remaining

As above mentioned, first of all run your git command from bash adding the enhanced log directives in the beginning: GIT_TRACE=1 GIT_CURL_VERBOSE=1 git ...

e.g. GIT_CURL_VERBOSE=1 GIT_TRACE=1 git -c diff.mnemonicprefix=false -c core.quotepath=false fetch origin This will show you detailed error information.

Why is __dirname not defined in node REPL?

In ES6 use:

import path from 'path';
const __dirname = path.resolve();

also available when node is called with --experimental-modules

How to get substring in C

If you just want to print the substrings ...

char s[] = "THESTRINGHASNOSPACES";
size_t i, slen = strlen(s);
for (i = 0; i < slen; i += 4) {
  printf("%.4s\n", s + i);
}

How can I force a hard reload in Chrome for Android

Don't forget to make sure that the "Reduce data usage" setting is turned OFF, as it seems to download cached data (from Google servers?) even though your local cache is flushed.

How to run Linux commands in Java?

You need not store the diff in a 3rd file and then read from in. Instead you make use of the Runtime.exec

Process p = Runtime.getRuntime().exec("diff fileA fileB");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((s = stdInput.readLine()) != null) {
        System.out.println(s);
}

Check If array is null or not in php

This checks if the array is empty

if (!empty($result) {
    // do stuf if array is not empty
} else {
    // do stuf if array is empty
}

This checks if the array is null or not

if (is_null($result) {
   // do stuf if array is null
} else {
   // do stuf if array is not null
}

Variable used in lambda expression should be final or effectively final

Java 8 has a new concept called “Effectively final” variable. It means that a non-final local variable whose value never changes after initialization is called “Effectively Final”.

This concept was introduced because prior to Java 8, we could not use a non-final local variable in an anonymous class. If you wanna have access to a local variable in anonymous class, you have to make it final.

When lambda was introduced, this restriction was eased. Hence to the need to make local variable final if it’s not changed once it is initialized as lambda in itself is nothing but an anonymous class.

Java 8 realized the pain of declaring local variable final every time a developer used lambda, introduced this concept, and made it unnecessary to make local variables final. So if you see the rule for anonymous classes has not changed, it’s just you don’t have to write the final keyword every time when using lambdas.

I found a good explanation here

XSLT equivalent for JSON

I am using Camel route umarshal(xmljson) -> to(xlst) -> marshal(xmljson). Efficient enough (though not 100% perfect), but simple, if you are already using Camel.

How to 'foreach' a column in a DataTable using C#?

Something like this:

 DataTable dt = new DataTable();

 // For each row, print the values of each column.
    foreach(DataRow row in dt .Rows)
    {
        foreach(DataColumn column in dt .Columns)
        {
            Console.WriteLine(row[column]);
        }
    }

http://msdn.microsoft.com/en-us/library/system.data.datatable.rows.aspx

Difference between dates in JavaScript

If you are looking for a difference expressed as a combination of years, months, and days, I would suggest this function:

_x000D_
_x000D_
function interval(date1, date2) {_x000D_
    if (date1 > date2) { // swap_x000D_
        var result = interval(date2, date1);_x000D_
        result.years  = -result.years;_x000D_
        result.months = -result.months;_x000D_
        result.days   = -result.days;_x000D_
        result.hours  = -result.hours;_x000D_
        return result;_x000D_
    }_x000D_
    result = {_x000D_
        years:  date2.getYear()  - date1.getYear(),_x000D_
        months: date2.getMonth() - date1.getMonth(),_x000D_
        days:   date2.getDate()  - date1.getDate(),_x000D_
        hours:  date2.getHours() - date1.getHours()_x000D_
    };_x000D_
    if (result.hours < 0) {_x000D_
        result.days--;_x000D_
        result.hours += 24;_x000D_
    }_x000D_
    if (result.days < 0) {_x000D_
        result.months--;_x000D_
        // days = days left in date1's month, _x000D_
        //   plus days that have passed in date2's month_x000D_
        var copy1 = new Date(date1.getTime());_x000D_
        copy1.setDate(32);_x000D_
        result.days = 32-date1.getDate()-copy1.getDate()+date2.getDate();_x000D_
    }_x000D_
    if (result.months < 0) {_x000D_
        result.years--;_x000D_
        result.months+=12;_x000D_
    }_x000D_
    return result;_x000D_
}_x000D_
_x000D_
// Be aware that the month argument is zero-based (January = 0)_x000D_
var date1 = new Date(2015, 4-1, 6);_x000D_
var date2 = new Date(2015, 5-1, 9);_x000D_
_x000D_
document.write(JSON.stringify(interval(date1, date2)));
_x000D_
_x000D_
_x000D_

This solution will treat leap years (29 February) and month length differences in a way we would naturally do (I think).

So for example, the interval between 28 February 2015 and 28 March 2015 will be considered exactly one month, not 28 days. If both those days are in 2016, the difference will still be exactly one month, not 29 days.

Dates with exactly the same month and day, but different year, will always have a difference of an exact number of years. So the difference between 2015-03-01 and 2016-03-01 will be exactly 1 year, not 1 year and 1 day (because of counting 365 days as 1 year).

Angular 4 - Select default value in dropdown [Reactive Forms]

As option, if you need just default text in dropdown without default value, try add <option disabled value="null">default text here</option> like this:

<select id="country" formControlName="country">
 <option disabled value="null">default text here</option>
 <option *ngFor="let c of countries" [value]="c" >{{ c }}</option>
</select>

In Chrome and Firefox works fine.

How to find sum of multiple columns in a table in SQL Server 2005?

SELECT Emp_cd, Val1, Val2, Val3, SUM(Val1 + Val2 + Val3) AS TOTAL 
FROM Emp
GROUP BY Emp_cd, Val1, Val2, Val3

How to navigate through textfields (Next / Done Buttons)

I've just created new Pod when dealing with this stuff GNTextFieldsCollectionManager. It automatically handles next/last textField problem and is very easy to use:

[[GNTextFieldsCollectionManager alloc] initWithView:self.view];

Grabs all textfields sorted by appearing in view hierarchy (or by tags), or you can specify your own array of textFields.

jQuery function to get all unique elements from an array?

As of jquery 3.0 you can use $.uniqueSort(ARRAY)

Example

array = ["1","2","1","2"]
$.uniqueSort(array)
=> ["1", "2"]

How to retrieve data from sqlite database in android and display it in TextView

First cast your Edit text like this:

TextView tekst = (TextView) findViewById(R.id.editText1);
tekst.setText(text);

And after that close the DB not befor this line...

 myDataBaseHelper.close(); 

Why do I get a "Null value was assigned to a property of primitive type setter of" error message when using HibernateCriteriaBuilder in Grails

According to this SO thread, the solution is to use the non-primitive wrapper types; e.g., Integer instead of int.

Validate email with a regex in jQuery

This regex can help you to check your email-address according to all the criteria which gmail.com used.

var re = /^\w+([-+.'][^\s]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;

var emailFormat = re.test($("#email").val()); // This return result in Boolean type

if (emailFormat) {}

Change the color of a checked menu item in a navigation drawer

Well you can achieve this using Color State Resource. If you notice inside your NavigationView you're using

app:itemIconTint="@color/black"
app:itemTextColor="@color/primary_text"

Here instead of using @color/black or @color/primary_test, use a Color State List Resource. For that, first create a new xml (e.g drawer_item.xml) inside color directory (which should be inside res directory.) If you don't have a directory named color already, create one.

Now inside drawer_item.xml do something like this

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="checked state color" android:state_checked="true" />
    <item android:color="your default color" />
</selector>

Final step would be to change your NavigationView

<android.support.design.widget.NavigationView
    android:id="@+id/activity_main_navigationview"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    app:headerLayout="@layout/drawer_header"
    app:itemIconTint="@color/drawer_item"  // notice here
    app:itemTextColor="@color/drawer_item" // and here
    app:itemBackground="@android:color/transparent"// and here for setting the background color to tranparent
    app:menu="@menu/menu_drawer">

Like this you can use separate Color State List Resources for IconTint, ItemTextColor, ItemBackground.

Now when you set an item as checked (either in xml or programmatically), the particular item will have different color than the unchecked ones.

Return the characters after Nth character in a string

Since there is the [vba] tag, split is also easy:

str1 = "001 baseball"
str2 = Split(str1)

Then use str2(1).

JavaFX - create custom button with image

There are a few different ways to accomplish this, I'll outline my favourites.

Use a ToggleButton and apply a custom style to it. I suggest this because your required control is "like a toggle button" but just looks different from the default toggle button styling.

My preferred method is to define a graphic for the button in css:

.toggle-button {
  -fx-graphic: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Pizza-icon.png');
}

.toggle-button:selected {
  -fx-graphic: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Piece-of-cake-icon.png');
}

OR use the attached css to define a background image.

// file imagetogglebutton.css deployed in the same package as ToggleButtonImage.class
.toggle-button {
  -fx-background-image: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Pizza-icon.png');
  -fx-background-repeat: no-repeat;
  -fx-background-position: center;
}

.toggle-button:selected {
  -fx-background-image: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Piece-of-cake-icon.png');
}

I prefer the -fx-graphic specification over the -fx-background-* specifications as the rules for styling background images are tricky and setting the background does not automatically size the button to the image, whereas setting the graphic does.

And some sample code:

import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.StackPaneBuilder;
import javafx.stage.Stage;

public class ToggleButtonImage extends Application {
  public static void main(String[] args) throws Exception { launch(args); }
  @Override public void start(final Stage stage) throws Exception {
    final ToggleButton toggle = new ToggleButton();
    toggle.getStylesheets().add(this.getClass().getResource(
      "imagetogglebutton.css"
    ).toExternalForm());
    toggle.setMinSize(148, 148); toggle.setMaxSize(148, 148);
    stage.setScene(new Scene(
      StackPaneBuilder.create()
        .children(toggle)
        .style("-fx-padding:10; -fx-background-color: cornsilk;")
        .build()
    ));
    stage.show();
  }
}

Some advantages of doing this are:

  1. You get the default toggle button behavior and don't have to re-implement it yourself by adding your own focus styling, mouse and key handlers etc.
  2. If your app gets ported to different platform such as a mobile device, it will work out of the box responding to touch events rather than mouse events, etc.
  3. Your styling is separated from your application logic so it is easier to restyle your application.

An alternate is to not use css and still use a ToggleButton, but set the image graphic in code:

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.scene.*;
import javafx.scene.control.ToggleButton;
import javafx.scene.image.*;
import javafx.scene.layout.StackPaneBuilder;
import javafx.stage.Stage;

public class ToggleButtonImageViaGraphic extends Application {
  public static void main(String[] args) throws Exception { launch(args); }
  @Override public void start(final Stage stage) throws Exception {
    final ToggleButton toggle      = new ToggleButton();
    final Image        unselected  = new Image(
      "http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Pizza-icon.png"
    );
    final Image        selected    = new Image(
      "http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Piece-of-cake-icon.png"
    );
    final ImageView    toggleImage = new ImageView();
    toggle.setGraphic(toggleImage);
    toggleImage.imageProperty().bind(Bindings
      .when(toggle.selectedProperty())
        .then(selected)
        .otherwise(unselected)
    );

    stage.setScene(new Scene(
      StackPaneBuilder.create()
        .children(toggle)
        .style("-fx-padding:10; -fx-background-color: cornsilk;")
        .build()
    ));
    stage.show();
  }
}

The code based approach has the advantage that you don't have to use css if you are unfamilar with it.

For best performance and ease of porting to unsigned applet and webstart sandboxes, bundle the images with your app and reference them by relative path urls rather than downloading them off the net.

Difference between web reference and service reference?

The service reference is the newer interface for adding references to all manner of WCF services (they may not be web services) whereas Web reference is specifically concerned with ASMX web references.

You can access web references via the advanced options in add service reference (if I recall correctly).

I'd use service reference because as I understand it, it's the newer mechanism of the two.

IIS_IUSRS and IUSR permissions in IIS8

When I added IIS_IUSRS permission to site folder - resources, like js and css, still were unaccessible (error 401, forbidden). However, when I added IUSR - it became ok. So for sure "you CANNOT remove the permissions for IUSR without worrying", dear @Travis G@

How do I declare and assign a variable on a single line in SQL

You've nearly got it:

DECLARE @myVariable nvarchar(max) = 'hello world';

See here for the docs

For the quotes, SQL Server uses apostrophes, not quotes:

DECLARE @myVariable nvarchar(max) = 'John said to Emily "Hey there Emily"';

Use double apostrophes if you need them in a string:

DECLARE @myVariable nvarchar(max) = 'John said to Emily ''Hey there Emily''';

Select random lines from a file

Use shuf with the -n option as shown below, to get N random lines:

shuf -n N input > output

jQuery: Check if special characters exists in string

You could also use the whitelist method -

var str = $('#Search').val();
var regex = /[^\w\s]/gi;

if(regex.test(str) == true) {
    alert('Your search string contains illegal characters.');
}

The regex in this example is digits, word characters, underscores (\w) and whitespace (\s). The caret (^) indicates that we are to look for everything that is not in our regex, so look for things that are not word characters, underscores, digits and whitespace.

Multidimensional Array [][] vs [,]

One is an array of arrays, and one is a 2d array. The former can be jagged, the latter is uniform.

That is, a double[][] can validly be:

double[][] x = new double[5][];

x[0] = new double[10];
x[1] = new double[5];
x[2] = new double[3];
x[3] = new double[100];
x[4] = new double[1];

Because each entry in the array is a reference to an array of double. With a jagged array, you can do an assignment to an array like you want in your second example:

x[0] = new double[13];

On the second item, because it is a uniform 2d array, you can't assign a 1d array to a row or column, because you must index both the row and column, which gets you down to a single double:

double[,] ServicePoint = new double[10,9];

ServicePoint[0]... // <-- meaningless, a 2d array can't use just one index.

UPDATE:

To clarify based on your question, the reason your #1 had a syntax error is because you had this:

double[][] ServicePoint = new double[10][9];

And you can't specify the second index at the time of construction. The key is that ServicePoint is not a 2d array, but an 1d array (of arrays) and thus since you are creating a 1d array (of arrays), you specify only one index:

double[][] ServicePoint = new double[10][];

Then, when you create each item in the array, each of those are also arrays, so then you can specify their dimensions (which can be different, hence the term jagged array):

ServicePoint[0] = new double[13];
ServicePoint[1] = new double[20];

Hope that helps!

Yii2 data provider default sorting

you can modify search model like this

$dataProvider = new ActiveDataProvider([
        'query' => $query,
        'sort' => [
            'defaultOrder' => ['user_id ASC, document_id ASC']
        ]
    ]);

Spark SQL: apply aggregate functions to a list of columns

Another example of the same concept - but say - you have 2 different columns - and you want to apply different agg functions to each of them i.e

f.groupBy("col1").agg(sum("col2").alias("col2"), avg("col3").alias("col3"), ...)

Here is the way to achieve it - though I do not yet know how to add the alias in this case

See the example below - Using Maps

val Claim1 = StructType(Seq(StructField("pid", StringType, true),StructField("diag1", StringType, true),StructField("diag2", StringType, true), StructField("allowed", IntegerType, true), StructField("allowed1", IntegerType, true)))
val claimsData1 = Seq(("PID1", "diag1", "diag2", 100, 200), ("PID1", "diag2", "diag3", 300, 600), ("PID1", "diag1", "diag5", 340, 680), ("PID2", "diag3", "diag4", 245, 490), ("PID2", "diag2", "diag1", 124, 248))

val claimRDD1 = sc.parallelize(claimsData1)
val claimRDDRow1 = claimRDD1.map(p => Row(p._1, p._2, p._3, p._4, p._5))
val claimRDD2DF1 = sqlContext.createDataFrame(claimRDDRow1, Claim1)

val l = List("allowed", "allowed1")
val exprs = l.map((_ -> "sum")).toMap
claimRDD2DF1.groupBy("pid").agg(exprs) show false
val exprs = Map("allowed" -> "sum", "allowed1" -> "avg")

claimRDD2DF1.groupBy("pid").agg(exprs) show false

how to set radio option checked onload with jQuery

 $("form input:[name=gender]").filter('[value=Male]').attr('checked', true);

Cordova - Error code 1 for command | Command failed for

I found answer myself; and if someone will face same issue, i hope my solution will work for them as well.

  • Downgrade NodeJs to 0.10.36
  • Upgrade Android SDK 22

How can I convert NSDictionary to NSData and vice versa?

In Swift 2 you can do it in this way:

var dictionary: NSDictionary = ...

/* NSDictionary to NSData */
let data = NSKeyedArchiver.archivedDataWithRootObject(dictionary)

/* NSData to NSDictionary */
let unarchivedDictionary = NSKeyedUnarchiver.unarchiveObjectWithData(data!) as! NSDictionary

In Swift 3:

/* NSDictionary to NSData */
let data = NSKeyedArchiver.archivedData(withRootObject: dictionary)

/* NSData to NSDictionary */
let unarchivedDictionary = NSKeyedUnarchiver.unarchiveObject(with: data)

Parsing Json rest api response in C#

1> Add this namspace. using Newtonsoft.Json.Linq;

2> use this source code.

JObject joResponse = JObject.Parse(response);                   
JObject ojObject = (JObject)joResponse["response"];
JArray array= (JArray)ojObject ["chats"];
int id = Convert.ToInt32(array[0].toString());

The HTTP request is unauthorized with client authentication scheme 'Ntlm'

It's a long time since the question was posted, but I experienced the same issue in a similar scenario. I have a console application and I was consuming a web service and our IIS server where the webservice was placed has windows authentication (NTLM) enabled.

I followed this link and that fixed my problem. Here's the sample code for App.config:

<system.serviceModel>
    <bindings>
        <basicHttpBinding>
            <binding name="Service1Soap">
                <security mode="TransportCredentialOnly">
                    <transport clientCredentialType="Ntlm" proxyCredentialType="None"
                        realm=""/>
                    <message clientCredentialType="UserName" algorithmSuite="Default"/>
                </security>
            </binding>
        </basicHttpBinding>
    </bindings>
    <client>
        <endpoint address="http://localhost/servicename/service1.asmx" 
            binding="basicHttpBinding" bindingConfiguration="ListsSoap"/>
    </client>
</system.serviceModel>

Logical operators for boolean indexing in Pandas

When you say

(a['x']==1) and (a['y']==10)

You are implicitly asking Python to convert (a['x']==1) and (a['y']==10) to boolean values.

NumPy arrays (of length greater than 1) and Pandas objects such as Series do not have a boolean value -- in other words, they raise

ValueError: The truth value of an array is ambiguous. Use a.empty, a.any() or a.all().

when used as a boolean value. That's because its unclear when it should be True or False. Some users might assume they are True if they have non-zero length, like a Python list. Others might desire for it to be True only if all its elements are True. Others might want it to be True if any of its elements are True.

Because there are so many conflicting expectations, the designers of NumPy and Pandas refuse to guess, and instead raise a ValueError.

Instead, you must be explicit, by calling the empty(), all() or any() method to indicate which behavior you desire.

In this case, however, it looks like you do not want boolean evaluation, you want element-wise logical-and. That is what the & binary operator performs:

(a['x']==1) & (a['y']==10)

returns a boolean array.


By the way, as alexpmil notes, the parentheses are mandatory since & has a higher operator precedence than ==. Without the parentheses, a['x']==1 & a['y']==10 would be evaluated as a['x'] == (1 & a['y']) == 10 which would in turn be equivalent to the chained comparison (a['x'] == (1 & a['y'])) and ((1 & a['y']) == 10). That is an expression of the form Series and Series. The use of and with two Series would again trigger the same ValueError as above. That's why the parentheses are mandatory.

Laravel Carbon subtract days from current date

From Laravel 5.6 you can use whereDate:

$users = Users::where('status_id', 'active')
       ->whereDate( 'created_at', '>', now()->subDays(30))
       ->get();

You also have whereMonth / whereDay / whereYear / whereTime

Select elements by attribute

JQuery will return the attribute as a string. Therefore you can check the length of that string to determine if is set:

if ($("input#A").attr("myattr").length == 0)
 return null;
else
 return $("input#A").attr("myattr");

Disable ONLY_FULL_GROUP_BY

Add or Remove modes to sql_mode

MySQL 5.7.9 or later

To add or remove a mode from sql_mode, you can use list_add and list_drop functions.

To remove a mode from the current SESSION.sql_mode, you can use one of the following:

SET SESSION sql_mode = sys.list_drop(@@SESSION.sql_mode, 'ONLY_FULL_GROUP_BY');
SET sql_mode = sys.list_drop(@@sql_mode, 'ONLY_FULL_GROUP_BY');
SET @@sql_mode = sys.list_drop(@@sql_mode, 'ONLY_FULL_GROUP_BY');

To remove a mode from the GLOBAL.sql_mode that persists for the current runtime operation, until the service is restarted.

SET GLOBAL sql_mode = sys.list_drop(@@GLOBAL.sql_mode, 'ONLY_FULL_GROUP_BY');

MySQL 5.7.8 or prior

Since the sql_mode value is a CSV string of modes, you would need to ensure that the string does not contain residual commas, which can be accomplished by using TRIM(BOTH ',' FROM ...).

To remove a mode from the sql_mode variable, you would want to use REPLACE() along with TRIM() to ensure any residual commas are removed.

SET SESSION sql_mode = TRIM(BOTH ',' FROM REPLACE(@@SESSION.sql_mode, 'ONLY_FULL_GROUP_BY', ''));
SET GLOBAL sql_mode = TRIM(BOTH ',' FROM REPLACE(@@GLOBAL.sql_mode, 'ONLY_FULL_GROUP_BY', ''));

To add a mode to the sql_mode variable, you would want to use CONCAT_WS(',', ...), to ensure a comma is appended with the current modes and TRIM() to ensure any residual commas are removed.

SET SESSION sql_mode = TRIM(BOTH ',' FROM CONCAT_WS(',', 'ONLY_FULL_GROUP_BY', @@SESSION.sql_mode));
SET GLOBAL sql_mode = TRIM(BOTH ',' FROM CONCAT_WS(',', 'ONLY_FULL_GROUP_BY', @@GLOBAL.sql_mode));

NOTE: Changing the GLOBAL variable does not propagate to the SESSION variable, until a new connection is established.

The GLOBAL variable will persist until the running service is restarted.

The SESSION variable will persist for the current connection, until the connection is closed and a new connection is established.


Revert to GLOBAL.sql_mode

Since SET sql_mode = 'ONLY_FULL_GROUP_BY'; was executed without the GLOBAL modifier, the change only affected the current SESSION state value, which also pertains to @@sql_mode. To remove it and revert to the global default on server restart value, you would want to use the value from @@GLOBAL.sql_mode. [sic]

The current SESSION value is only valid for the current connection. Reconnecting to the server will revert the value back to the GLOBAL value.

To revert the current session state value to the current global value, you can use one of the following:

SET SESSION sql_mode = @@GLOBAL.sql_mode;
SET @@sql_mode = @@GLOBAL.sql_mode;
SET sql_mode = @@GLOBAL.sql_mode;

Change SESSION.sql_mode value to ONLY_FULL_GROUP_BY

SET sql_mode = 'ONLY_FULL_GROUP_BY';
SELECT @@sql_mode, @@GLOBAL.sql_mode;
+--------------------+----------------------------------------------+
| @@sql_mode         | @@GLOBAL.sql_mode                            |
+--------------------+----------------------------------------------+
| ONLY_FULL_GROUP_BY | NO_AUTO_VALUE_ON_ZERO,NO_ENGINE_SUBSTITUTION |
+--------------------+----------------------------------------------+

Revert the SESSION.sql_mode value to the GLOBAL.sql_mode value

SET sql_mode = @@GLOBAL.sql_mode;
SELECT @@sql_mode, @@GLOBAL.sql_mode;
+----------------------------------------------+----------------------------------------------+
| @@sql_mode                                   | @@GLOBAL.sql_mode                            |
+----------------------------------------------+----------------------------------------------+
| NO_AUTO_VALUE_ON_ZERO,NO_ENGINE_SUBSTITUTION | NO_AUTO_VALUE_ON_ZERO,NO_ENGINE_SUBSTITUTION |
+----------------------------------------------+----------------------------------------------+

Server Restart Persistent sql_mode using the option file

To set the SQL mode at server startup, use the --sql-mode="modes" option on the command line, or sql-mode="modes" in an option file such as my.cnf (Unix operating systems) or my.ini (Windows). [sic]

Please see your version of MySQL to determine the supported and default modes.

MySQL >= 5.7.5, <= 5.7.6 default

[mysqld]
    
sql-mode="ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION"

Please see the Option File Syntax for more information.

The syntax for specifying options in an option file is similar to command-line syntax. However, in an option file, you omit the leading two dashes from the option name and you specify only one option per line. For example, --quick and --host=localhost on the command line should be specified as quick and host=localhost on separate lines in an option file. To specify an option of the form --loose-opt_name in an option file, write it as loose-opt_name.

The value optionally can be enclosed within single quotation marks or double quotation marks, which is useful if the value contains a # comment character.

Default sql_mode values

Since the MySQL documentation per-version values have been removed, I have added them here for your reference.

MySQL >= 8.0.11 8.0.5 - 8.0.10 Skipped

ONLY_FULL_GROUP_BY STRICT_TRANS_TABLES NO_ZERO_IN_DATE NO_ZERO_DATE ERROR_FOR_DIVISION_BY_ZERO NO_ENGINE_SUBSTITUTION

MySQL >= 5.7.8, <= 8.0.4

ONLY_FULL_GROUP_BY STRICT_TRANS_TABLES NO_ZERO_IN_DATE NO_ZERO_DATE ERROR_FOR_DIVISION_BY_ZERO NO_AUTO_CREATE_USER NO_ENGINE_SUBSTITUTION

MySQL 5.7.7

ONLY_FULL_GROUP_BY STRICT_TRANS_TABLES NO_AUTO_CREATE_USER NO_ENGINE_SUBSTITUTION

MySQL >= 5.7.5, <= 5.7.6

ONLY_FULL_GROUP_BY STRICT_TRANS_TABLES NO_ENGINE_SUBSTITUTION

MySQL >= 5.6.6, <= 5.7.4

NO_ENGINE_SUBSTITUTION

MySQL <= 5.6.5

''

Converting 24 hour time to 12 hour time w/ AM & PM using Javascript

UPDATE 2: without seconds option

UPDATE: AM after noon corrected, tested: http://jsfiddle.net/aorcsik/xbtjE/

I created this function to do this:

_x000D_
_x000D_
function formatDate(date) {_x000D_
  var d = new Date(date);_x000D_
  var hh = d.getHours();_x000D_
  var m = d.getMinutes();_x000D_
  var s = d.getSeconds();_x000D_
  var dd = "AM";_x000D_
  var h = hh;_x000D_
  if (h >= 12) {_x000D_
    h = hh - 12;_x000D_
    dd = "PM";_x000D_
  }_x000D_
  if (h == 0) {_x000D_
    h = 12;_x000D_
  }_x000D_
  m = m < 10 ? "0" + m : m;_x000D_
_x000D_
  s = s < 10 ? "0" + s : s;_x000D_
_x000D_
  /* if you want 2 digit hours:_x000D_
  h = h<10?"0"+h:h; */_x000D_
_x000D_
  var pattern = new RegExp("0?" + hh + ":" + m + ":" + s);_x000D_
_x000D_
  var replacement = h + ":" + m;_x000D_
  /* if you want to add seconds_x000D_
  replacement += ":"+s;  */_x000D_
  replacement += " " + dd;_x000D_
_x000D_
  return date.replace(pattern, replacement);_x000D_
}_x000D_
_x000D_
alert(formatDate("February 04, 2011 12:00:00"));
_x000D_
_x000D_
_x000D_

Show pop-ups the most elegant way

  • Create a 'popup' directive and apply it to the container of the popup content
  • In the directive, wrap the content in a absolute position div along with the mask div below it.
  • It is OK to move the 2 divs in the DOM tree as needed from within the directive. Any UI code is OK in the directives, including the code to position the popup in center of screen.
  • Create and bind a boolean flag to controller. This flag will control visibility.
  • Create scope variables that bond to OK / Cancel functions etc.

Editing to add a high level example (non functional)

<div id='popup1-content' popup='showPopup1'>
  ....
  ....
</div>


<div id='popup2-content' popup='showPopup2'>
  ....
  ....
</div>



.directive('popup', function() {
  var p = {
      link : function(scope, iElement, iAttrs){
           //code to wrap the div (iElement) with a abs pos div (parentDiv)
          // code to add a mask layer div behind 
          // if the parent is already there, then skip adding it again.
         //use jquery ui to make it dragable etc.
          scope.watch(showPopup, function(newVal, oldVal){
               if(newVal === true){
                   $(parentDiv).show();
                 } 
              else{
                 $(parentDiv).hide();
                }
          });
      }


   }
  return p;
});

javascript object max size limit

There is no such limit on the string length. To be certain, I just tested to create a string containing 60 megabyte.

The problem is likely that you are sending the data in a GET request, so it's sent in the URL. Different browsers have different limits for the URL, where IE has the lowest limist of about 2 kB. To be safe, you should never send more data than about a kilobyte in a GET request.

To send that much data, you have to send it in a POST request instead. The browser has no hard limit on the size of a post, but the server has a limit on how large a request can be. IIS for example has a default limit of 4 MB, but it's possible to adjust the limit if you would ever need to send more data than that.

Also, you shouldn't use += to concatenate long strings. For each iteration there is more and more data to move, so it gets slower and slower the more items you have. Put the strings in an array and concatenate all the items at once:

var items = $.map(keys, function(item, i) {
  var value = $("#value" + (i+1)).val().replace(/"/g, "\\\"");
  return
    '{"Key":' + '"' + Encoder.htmlEncode($(this).html()) + '"' + ",'+
    '" + '"Value"' + ':' + '"' + Encoder.htmlEncode(value) + '"}';
});
var jsonObj =
  '{"code":"' + code + '",'+
  '"defaultfile":"' + defaultfile + '",'+
  '"filename":"' + currentFile + '",'+
  '"lstResDef":[' + items.join(',') + ']}';

How do I install Eclipse Marketplace in Eclipse Classic?

  1. Help->Install New Software...
  2. Point to Eclipse Juno Site, If not available add the site "Juno - http://download.eclipse.org/releases/juno"

  3. Select and expand general purpose tools

  4. Select and install Marketplace client

C# static class constructor

Static constructor called only the first instance of the class created.

like this:

static class YourClass
{
    static YourClass()
    {
        //initialization
    }
}

show/hide a div on hover and hover out

May be there no need for JS. You can achieve this with css also. Write like this:

.flyout {
    position: absolute;
    width: 1000px;
    height: 450px;
    background: red;
    overflow: hidden;
    z-index: 10000;
    display: none;
}
#menu:hover + .flyout {
    display: block;
}

What characters are forbidden in Windows and Linux directory names?

For anyone looking for a regex:

const BLACKLIST = /[<>:"\/\\|?*]/g;

Select All distinct values in a column using LINQ

To have unique Categories:

var uniqueCategories =  repository.GetAllProducts()
                                  .Select(p=>p.Category)
                                  .Distinct();

Convert varchar2 to Date ('MM/DD/YYYY') in PL/SQL

First you convert VARCHAR to DATE and then back to CHAR. I do this almost every day and never found any better way.

select TO_CHAR(TO_DATE(DOJ,'MM/DD/YYYY'), 'MM/DD/YYYY') from EmpTable

How to get a reference to an iframe's window object inside iframe's onload handler created from parent window

You're declaring everything in the parent page. So the references to window and document are to the parent page's. If you want to do stuff to the iframe's, use iframe || iframe.contentWindow to access its window, and iframe.contentDocument || iframe.contentWindow.document to access its document.

There's a word for what's happening, possibly "lexical scope": What is lexical scope?

The only context of a scope is this. And in your example, the owner of the method is doc, which is the iframe's document. Other than that, anything that's accessed in this function that uses known objects are the parent's (if not declared in the function). It would be a different story if the function were declared in a different place, but it's declared in the parent page.

This is how I would write it:

(function () {
  var dom, win, doc, where, iframe;

  iframe = document.createElement('iframe');
  iframe.src = "javascript:false";

  where = document.getElementsByTagName('script')[0];
  where.parentNode.insertBefore(iframe, where);

  win = iframe.contentWindow || iframe;
  doc = iframe.contentDocument || iframe.contentWindow.document;

  doc.open();
  doc._l = (function (w, d) {
    return function () {
      w.vanishing_global = new Date().getTime();

      var js = d.createElement("script");
      js.src = 'test-vanishing-global.js?' + w.vanishing_global;

      w.name = "foobar";
      d.foobar = "foobar:" + Math.random();
      d.foobar = "barfoo:" + Math.random();
      d.body.appendChild(js);
    };
  })(win, doc);
  doc.write('<body onload="document._l();"></body>');
  doc.close();
})();

The aliasing of win and doc as w and d aren't necessary, it just might make it less confusing because of the misunderstanding of scopes. This way, they are parameters and you have to reference them to access the iframe's stuff. If you want to access the parent's, you still use window and document.

I'm not sure what the implications are of adding methods to a document (doc in this case), but it might make more sense to set the _l method on win. That way, things can be run without a prefix...such as <body onload="_l();"></body>

D3 Appending Text to a SVG Rectangle

Have you tried the SVG text element?

.append("text").text(function(d, i) { return d[whichevernode];})

rect element doesn't permit text element inside of it. It only allows descriptive elements (<desc>, <metadata>, <title>) and animation elements (<animate>, <animatecolor>, <animatemotion>, <animatetransform>, <mpath>, <set>)

Append the text element as a sibling and work on positioning.

UPDATE

Using g grouping, how about something like this? fiddle

You can certainly move the logic to a CSS class you can append to, remove from the group (this.parentNode)

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.

Use of var keyword in C#

It's a matter of taste. All this fussing about the type of a variable disappears when you get used to dynamically typed languages. That is, if you ever start to like them (I'm not sure if everybody can, but I do).

C#'s var is pretty cool in that it looks like dynamic typing, but actually is static typing - the compiler enforces correct usage.

The type of your variable is not really that important (this has been said before). It should be relatively clear from the context (its interactions with other variables and methods) and its name - don't expect customerList to contain an int...

I am still waiting to see what my boss thinks of this matter - I got a blanket "go ahead" to use any new constructs in 3.5, but what will we do about maintenance?

Read values into a shell variable from a pipe

I think you were trying to write a shell script which could take input from stdin. but while you are trying it to do it inline, you got lost trying to create that test= variable. I think it does not make much sense to do it inline, and that's why it does not work the way you expect.

I was trying to reduce

$( ... | head -n $X | tail -n 1 )

to get a specific line from various input. so I could type...

cat program_file.c | line 34

so I need a small shell program able to read from stdin. like you do.

22:14 ~ $ cat ~/bin/line 
#!/bin/sh

if [ $# -ne 1 ]; then echo enter a line number to display; exit; fi
cat | head -n $1 | tail -n 1
22:16 ~ $ 

there you go.

How to send a pdf file directly to the printer using JavaScript?

I think this Library of JavaScript might Help you:

It's called Print.js

First Include

<script src="print.js"></script>
<link rel="stylesheet" type="text/css" href="print.css">

It's basic usage is to call printJS() and just pass in a PDF document url: printJS('docs/PrintJS.pdf')

What I did was something like this, this will also show "Loading...." if PDF document is too large.

<button type="button" onclick="printJS({printable:'docs/xx_large_printjs.pdf', type:'pdf', showModal:true})">
    Print PDF with Message
</button>

However keep in mind that:

Firefox currently doesn't allow printing PDF documents using iframes. There is an open bug in Mozilla's website about this. When using Firefox, Print.js will open the PDF file into a new tab.

Using BufferedReader.readLine() in a while loop properly

Concept Solution:br.read() returns particular character's int value so loop continue's until we won't get -1 as int value and Hence up to there it prints br.readLine() which returns a line into String form.

    //Way 1:
    while(br.read()!=-1)
    {
      //continues loop until we won't get int value as a -1
      System.out.println(br.readLine());
    }

    //Way 2:
    while((line=br.readLine())!=null)
    {
      System.out.println(line);
    }

    //Way 3:
    for(String line=br.readLine();line!=null;line=br.readLine())
    {
      System.out.println(line);
    }

Way 4: It's an advance way to read file using collection and arrays concept How we iterate using for each loop. check it here http://www.java67.com/2016/01/how-to-use-foreach-method-in-java-8-examples.html

Google Maps v3 - limit viewable area and zoom level

To limit the zoom on v.3+. in your map setting add default zoom level and minZoom or maxZoom (or both if required) zoom levels are 0 to 19. You must declare deafult zoom level if limitation is required. all are case sensitive!

function initialize() {
   var mapOptions = {
      maxZoom:17,
      minZoom:15,
      zoom:15,
      ....

What's the best way to check if a String represents an integer in Java?

For kotlin, isDigitsOnly() (Also for Java's TextUtils.isDigitsOnly()) of String always returns false it has a negative sign in front though the rest of the character is digit only. For example -

/** For kotlin*/
var str = "-123" 
str.isDigitsOnly()  //Result will be false 

/** For Java */
String str = "-123"
TextUtils.isDigitsOnly(str) //Result will be also false 

So I made a quick fix by this -

 var isDigit=str.matches("-?\\d+(\\.\\d+)?".toRegex()) 
/** Result will be true for now*/

VB6 IDE cannot load MSCOMCTL.OCX after update KB 2687323

Same problem with VBA Macros using MSCOMCTL.OCX. Problem still unresolved with solutions like "reg/unreg mscomctl.ocx" Used the Info above of Rumi. Edited my *.dot file, search for #2.0#0, change it to #2.1#0 --> it worked