Programs & Examples On #Webinvoke

WebInvoke - Indicates a service operation is logically an invoke operation and that it can be called by the REST programming model

Cannot set content-type to 'application/json' in jQuery.ajax

I recognized those screens, I'm using CodeFluentEntities, and I've got solution that worked for me as well.

I'm using that construction:

$.ajax({
   url: path,
   type: "POST",
   contentType: "text/plain",
   data: {"some":"some"}
}

as you can see, if I use

contentType: "",

or

contentType: "text/plain", //chrome

Everything works fine.

I'm not 100% sure that it's all that you need, cause I've also changed headers.

No connection could be made because the target machine actively refused it 127.0.0.1:3446

For my case, I had an Angular SLA project template with ASP.NET Core.

I was trying to run the IIS Express from the Visual Studio WebUI solution, triggering the "Actively refused it" error.

enter image description here


The problem, in this case, wasn't connected with the Firewall blocking the connection.

It turned out that I had to run the Angular server independently of the Kestrel run because the Server was expecting the UI to run on a specific port but wasn't actually.


For more information, check the official Microsoft documentation.

Pandas dataframe fillna() only some columns in place

You can using dict , fillna with different value for different column

df.fillna({'a':0,'b':0})
Out[829]: 
     a    b    c
0  1.0  4.0  NaN
1  2.0  5.0  NaN
2  3.0  0.0  7.0
3  0.0  6.0  8.0

After assign it back

df=df.fillna({'a':0,'b':0})
df
Out[831]: 
     a    b    c
0  1.0  4.0  NaN
1  2.0  5.0  NaN
2  3.0  0.0  7.0
3  0.0  6.0  8.0

How to set xlim and ylim for a subplot in matplotlib

You should use the OO interface to matplotlib, rather than the state machine interface. Almost all of the plt.* function are thin wrappers that basically do gca().*.

plt.subplot returns an axes object. Once you have a reference to the axes object you can plot directly to it, change its limits, etc.

import matplotlib.pyplot as plt

ax1 = plt.subplot(131)
ax1.scatter([1, 2], [3, 4])
ax1.set_xlim([0, 5])
ax1.set_ylim([0, 5])


ax2 = plt.subplot(132)
ax2.scatter([1, 2],[3, 4])
ax2.set_xlim([0, 5])
ax2.set_ylim([0, 5])

and so on for as many axes as you want.

or better, wrap it all up in a loop:

import matplotlib.pyplot as plt

DATA_x = ([1, 2],
          [2, 3],
          [3, 4])

DATA_y = DATA_x[::-1]

XLIMS = [[0, 10]] * 3
YLIMS = [[0, 10]] * 3

for j, (x, y, xlim, ylim) in enumerate(zip(DATA_x, DATA_y, XLIMS, YLIMS)):
    ax = plt.subplot(1, 3, j + 1)
    ax.scatter(x, y)
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)

ImportError: No module named pandas

When I try to build docker image zeppelin-highcharts, I find that the base image openjdk:8 also does not have pandas installed. I solved it with this steps.

curl --silent --show-error --retry 5 https://bootstrap.pypa.io/get-pip.py | python
pip install pandas

I refered what-is-the-official-preferred-way-to-install-pip-and-virtualenv-systemwide

Performing a query on a result from another query?

You just wrap your query in another one:

SELECT COUNT(*), SUM(Age)
FROM (
    SELECT availables.bookdate AS Count, DATEDIFF(now(),availables.updated_at) as Age
    FROM availables
    INNER JOIN rooms
    ON availables.room_id=rooms.id
    WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094
    GROUP BY availables.bookdate
) AS tmp;

How to write log base(2) in c/c++

Improved version of what Ustaman Sangat did

static inline uint64_t
log2(uint64_t n)
{
    uint64_t val;
    for (val = 0; n > 1; val++, n >>= 1);

    return val;
}

Spark java.lang.OutOfMemoryError: Java heap space

The location to set the memory heap size (at least in spark-1.0.0) is in conf/spark-env. The relevant variables are SPARK_EXECUTOR_MEMORY & SPARK_DRIVER_MEMORY. More docs are in the deployment guide

Also, don't forget to copy the configuration file to all the slave nodes.

How to remove folders with a certain name

This also works - it will remove all the folders called "a" and their contents:

rm -rf `find -type d -name a`

Activity transition in Android

create res>anim>fadein.xml

<?xml version="1.0" encoding="utf-8"?>
    <alpha xmlns:android="http://schemas.android.com/apk/res/android"
       android:interpolator="@android:anim/accelerate_interpolator"
       android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="500" />

create res>anim>fadeout.xml

<?xml version="1.0" encoding="utf-8"?>
    <alpha xmlns:android="http://schemas.android.com/apk/res/android"
       android:interpolator="@android:anim/accelerate_interpolator"
       android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="500" />

In res>values>styles.xml

<style name="Fade">
        <item name="android:windowEnterAnimation">@anim/fadein</item>
        <item name="android:windowExitAnimation">@anim/fadeout</item>
    </style>

In activities onCreate()

getWindow().getAttributes().windowAnimations = R.style.Fade;

How to set image name in Dockerfile?

Here is another version if you have to reference a specific docker file:

version: "3"
services:
  nginx:
    container_name: nginx
    build:
      context: ../..
      dockerfile: ./docker/nginx/Dockerfile
    image: my_nginx:latest

Then you just run

docker-compose build

Checking if any elements in one list are in another

You could solve this many ways. One that is pretty simple to understand is to just use a loop.

def comp(list1, list2):
    for val in list1:
        if val in list2:
            return True
    return False

A more compact way you can do it is to use map and reduce:

reduce(lambda v1,v2: v1 or v2, map(lambda v: v in list2, list1))

Even better, the reduce can be replaced with any:

any(map(lambda v: v in list2, list1))

You could also use sets:

len(set(list1).intersection(list2)) > 0

How to change dot size in gnuplot

The pointsize command scales the size of points, but does not affect the size of dots.

In other words, plot ... with points ps 2 will generate points of twice the normal size, but for plot ... with dots ps 2 the "ps 2" part is ignored.

You could use circular points (pt 7), which look just like dots.

Illegal mix of collations MySQL Error

In general the best way is to Change the table collation. However I have an old application and are not really able to estimate the outcome whether this has side effects. Therefore I tried somehow to convert the string into some other format that solved the collation problem. What I found working is to do the string compare by converting the strings into a hexadecimal representation of it's characters. On the database this is done with HEX(column). For PHP you may use this function:

public static function strToHex($string)
{
    $hex = '';
    for ($i=0; $i<strlen($string); $i++){
        $ord = ord($string[$i]);
        $hexCode = dechex($ord);
        $hex .= substr('0'.$hexCode, -2);
    }
    return strToUpper($hex);
}

When doing the database query, your original UTF8 string must be converted first into an iso string (e.g. using utf8_decode() in PHP) before using it in the DB. Because of the collation type the database cannot have UTF8 characters inside so the comparism should work event though this changes the original string (converting UTF8 characters that are not existend in the ISO charset result in a ? or these are removed entirely). Just make sure that when you write data into the database, that you use the same UTF8 to ISO conversion.

ModelState.IsValid == false, why?

bool hasErrors =  ViewData.ModelState.Values.Any(x => x.Errors.Count > 1);

or iterate with

    foreach (ModelState state in ViewData.ModelState.Values.Where(x => x.Errors.Count > 0))
    {

    }

Can't import database through phpmyadmin file size too large

You have three options:

  • Use another way to get the file on the server, and use a mysql client on the server
  • Use another client to connect to the server and load the data
  • Change your PHP settings to allow such huge files. Don't forget to increment the execution time as well.

How to use Sublime over SSH

You can use rsub, which is inspired on TextMate's rmate. From the description:

Rsub is an implementation of TextMate 2's 'rmate' feature for Sublime Text 2, allowing files to be edited on a remote server using SSH port forwarding / tunnelling.

Here's a good tutorial on how to set it up properly.

"inappropriate ioctl for device"

Odd errors like "inappropriate ioctl for device" are usually a result of checking $! at some point other than just after a system call failed. If you'd show your code, I bet someone would rapidly point out your error.

Preloading CSS Images

how about loading that background image somewhere hidden. That way it will be loaded when the page is opened and wont take any time once the form is created using ajax:

body {
background: #ffffff url('img_tree.png') no-repeat -100px -100px;
}

When use ResponseEntity<T> and @RestController for Spring RESTful applications

ResponseEntity is meant to represent the entire HTTP response. You can control anything that goes into it: status code, headers, and body.

@ResponseBody is a marker for the HTTP response body and @ResponseStatus declares the status code of the HTTP response.

@ResponseStatus isn't very flexible. It marks the entire method so you have to be sure that your handler method will always behave the same way. And you still can't set the headers. You'd need the HttpServletResponse or a HttpHeaders parameter.

Basically, ResponseEntity lets you do more.

How to get the current location latitude and longitude in android

try this, hope it will help you to get the current location, every time the location changes.

public class MyClass implements LocationListener {
    double currentLatitude, currentLongitude;

    public void onLocationChanged(Location location) {
        currentLatitude = location.getLatitude();
        currentLongitude = location.getLongitude();
    }
}

jQuery equivalent to Prototype array.last()

with slice():

var a = [1,2,3,4];
var lastEl = a.slice(-1)[0]; // 4
// a is still [1,2,3,4]

with pop();

var a = [1,2,3,4];
var lastEl = a.pop(); // 4
// a is now [1,2,3]

see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array for more information

How to count the number of rows in excel with data?

  n = ThisWorkbook.Worksheets(1).Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count

Importing Maven project into Eclipse

I am not experienced with Eclipse or Maven so the other answers seemed a bit over complicated.

The following simpler set of steps worked for me:

Prerequisite: Make sure you have Maven plugin installed in your Eclipse IDE: How to add Maven plugin to Eclipse

  1. Open Eclipse
  2. Click File > Import
  3. Type Maven in the search box under Select an import source:
  4. Select Existing Maven Projects
  5. Click Next
  6. Click Browse and select the folder that is the root of the Maven project (probably contains the pom.xml file)
  7. Click Next
  8. Click Finish

Fixed width buttons with Bootstrap

Best way to the solution of your problem is to use button block btn-block with desired column width.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>_x000D_
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
_x000D_
    <div class="col-md-12">_x000D_
      <button class="btn btn-primary btn-block">Save</button>_x000D_
    </div>_x000D_
    <div class="col-md-12">_x000D_
        <button class="btn btn-success btn-block">Download</button>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

Python Requests and persistent sessions

The documentation says that get takes in an optional cookies argument allowing you to specify cookies to use:

from the docs:

>>> url = 'http://httpbin.org/cookies'
>>> cookies = dict(cookies_are='working')

>>> r = requests.get(url, cookies=cookies)
>>> r.text
'{"cookies": {"cookies_are": "working"}}'

http://docs.python-requests.org/en/latest/user/quickstart/#cookies

Python variables as keys to dict

A one-liner is:-

fruitdict = dict(zip(('apple','banana','carrot'), (1,'f', '3'))

What do "branch", "tag" and "trunk" mean in Subversion repositories?

Tag = a defined slice in time, usually used for releases

I think this is what one typically means by "tag". But in Subversion:

They don't really have any formal meaning. A folder is a folder to SVN.

which I find rather confusing: a revision control system that knows nothing about branches or tags. From an implementation point of view, I think the Subversion way of creating "copies" is very clever, but me having to know about it is what I'd call a leaky abstraction.

Or perhaps I've just been using CVS far too long.

The openssl extension is required for SSL/TLS protection

I just add this because it worked for me, i install composer with the developer option activate (just check the box in the installer)

https://getcomposer.org/Composer-Setup.exe

I think this problem may occurs when you add a new version of php to your wamp server. If you do this, you have to check if the extension_dir variable is configure to "env".

Then check if the php_openssl.dll exist in your phpx.x/ext folder. If there is not php_openssl.dll, you have to download it here : http://www.telecharger-dll.fr/dll-php_openssl.dll.html

If it still not working, check if your apache server use the good php.ini file by running the following cmd command :

php --ini

Configuration File (php.ini) Path: C:\Windows
Loaded Configuration File:         C:\wamp64\bin\php\php7.4.7x64\php.ini
Scan for additional .ini files in: (none)
Additional .ini files parsed:      (none)

If the loaded configuration file return (none), you have to check your appache/apache2.4.41/conf/httpd.conf file is configure with the proper phpIniDir and the correct module.

It must be something like this :

PHPIniDir "${APACHE_DIR}/bin"
LoadModule php7_module "${INSTALL_DIR}/bin/php/php7.4.7x64/php7apache2_4.dll"

Then restart apache and check the "apache/apache2.4.41/bin/php.ini" (wich is the one configure above by PHPIniDir) it must me like

enter image description here

How to download HTTP directory with all files and sub-directories as they appear on the online files/folders list?

you can use lftp, the swish army knife of downloading if you have bigger files you can add --use-pget-n=10 to command

lftp -c 'mirror --parallel=100 https://example.com/files/ ;exit'

Foreach loop, determine which is the last iteration of the loop

using Linq and the foreach:

foreach (Item result in Model.Results)   
{   
     if (Model.Results.IndexOf(result) == Model.Results.Count - 1) {
             // this is the last item
     }
}

https://code.i-harness.com/en/q/7213ce

How can I go back/route-back on vue-router?

Another solution is using vue-router-back-mixin

import BackMixin from `vue-router-back-mixin`

export default {
  ...
  mixins: [BackMixin],
  methods() {
    goBack() {
      this.backMixin_handleBack()
    }
  }
  ...
}

How to disable PHP Error reporting in CodeIgniter?

Here is the typical structure of new Codeigniter project:

- application/
- system/
- user_guide/
- index.php <- this is the file you need to change

I usually use this code in my CI index.php. Just change local_server_name to the name of your local webserver.

With this code you can deploy your site to your production server without changing index.php each time.

// Domain-based environment
if ($_SERVER['SERVER_NAME'] == 'local_server_name') {
    define('ENVIRONMENT', 'development');
} else {
    define('ENVIRONMENT', 'production');
}

/*
 *---------------------------------------------------------------
 * ERROR REPORTING
 *---------------------------------------------------------------
 *
 * Different environments will require different levels of error reporting.
 * By default development will show errors but testing and live will hide them.
 */

if (defined('ENVIRONMENT')) {
    switch (ENVIRONMENT) {
        case 'development':
            error_reporting(E_ALL);
            break;
        case 'testing':
        case 'production':
            error_reporting(0);
            ini_set('display_errors', 0);  
            break;
        default:
            exit('The application environment is not set correctly.');
    }
}

Adding to the classpath on OSX

If your shell is tcsh or csh, you can set it in /etc/profile. Open terminal, "vim /etc/profile" and add the following line:

setenv CLASSPATH (insert your classpath here)

What does the "at" (@) symbol do in Python?

Decorators were added in Python to make function and method wrapping (a function that receives a function and returns an enhanced one) easier to read and understand. The original use case was to be able to define the methods as class methods or static methods on the head of their definition. Without the decorator syntax, it would require a rather sparse and repetitive definition:

class WithoutDecorators:
def some_static_method():
    print("this is static method")
some_static_method = staticmethod(some_static_method)

def some_class_method(cls):
    print("this is class method")
some_class_method = classmethod(some_class_method)

If the decorator syntax is used for the same purpose, the code is shorter and easier to understand:

class WithDecorators:
    @staticmethod
    def some_static_method():
        print("this is static method")

    @classmethod
    def some_class_method(cls):
        print("this is class method")

General syntax and possible implementations

The decorator is generally a named object ( lambda expressions are not allowed) that accepts a single argument when called (it will be the decorated function) and returns another callable object. "Callable" is used here instead of "function" with premeditation. While decorators are often discussed in the scope of methods and functions, they are not limited to them. In fact, anything that is callable (any object that implements the _call__ method is considered callable), can be used as a decorator and often objects returned by them are not simple functions but more instances of more complex classes implementing their own __call_ method.

The decorator syntax is simply only a syntactic sugar. Consider the following decorator usage:

@some_decorator
def decorated_function():
    pass

This can always be replaced by an explicit decorator call and function reassignment:

def decorated_function():
    pass
decorated_function = some_decorator(decorated_function)

However, the latter is less readable and also very hard to understand if multiple decorators are used on a single function. Decorators can be used in multiple different ways as shown below:

As a function

There are many ways to write custom decorators, but the simplest way is to write a function that returns a subfunction that wraps the original function call.

The generic patterns is as follows:

def mydecorator(function):
    def wrapped(*args, **kwargs):
        # do some stuff before the original
        # function gets called
        result = function(*args, **kwargs)
        # do some stuff after function call and
        # return the result
        return result
    # return wrapper as a decorated function
    return wrapped

As a class

While decorators almost always can be implemented using functions, there are some situations when using user-defined classes is a better option. This is often true when the decorator needs complex parametrization or it depends on a specific state.

The generic pattern for a nonparametrized decorator as a class is as follows:

class DecoratorAsClass:
    def __init__(self, function):
        self.function = function

    def __call__(self, *args, **kwargs):
        # do some stuff before the original
        # function gets called
        result = self.function(*args, **kwargs)
        # do some stuff after function call and
        # return the result
        return result

Parametrizing decorators

In real code, there is often a need to use decorators that can be parametrized. When the function is used as a decorator, then the solution is simple—a second level of wrapping has to be used. Here is a simple example of the decorator that repeats the execution of a decorated function the specified number of times every time it is called:

def repeat(number=3):
"""Cause decorated function to be repeated a number of times.

Last value of original function call is returned as a result
:param number: number of repetitions, 3 if not specified
"""
def actual_decorator(function):
    def wrapper(*args, **kwargs):
        result = None
        for _ in range(number):
            result = function(*args, **kwargs)
        return result
    return wrapper
return actual_decorator

The decorator defined this way can accept parameters:

>>> @repeat(2)
... def foo():
...     print("foo")
...
>>> foo()
foo
foo

Note that even if the parametrized decorator has default values for its arguments, the parentheses after its name is required. The correct way to use the preceding decorator with default arguments is as follows:

>>> @repeat()
... def bar():
...     print("bar")
...
>>> bar()
bar
bar
bar

Finally lets see decorators with Properties.

Properties

The properties provide a built-in descriptor type that knows how to link an attribute to a set of methods. A property takes four optional arguments: fget , fset , fdel , and doc . The last one can be provided to define a docstring that is linked to the attribute as if it were a method. Here is an example of a Rectangle class that can be controlled either by direct access to attributes that store two corner points or by using the width , and height properties:

class Rectangle:
    def __init__(self, x1, y1, x2, y2):
        self.x1, self.y1 = x1, y1
        self.x2, self.y2 = x2, y2

    def _width_get(self):
        return self.x2 - self.x1

    def _width_set(self, value):
        self.x2 = self.x1 + value

    def _height_get(self):
        return self.y2 - self.y1

    def _height_set(self, value):
        self.y2 = self.y1 + value

    width = property(
        _width_get, _width_set,
        doc="rectangle width measured from left"
    )
    height = property(
        _height_get, _height_set,
        doc="rectangle height measured from top"
    )

    def __repr__(self):
        return "{}({}, {}, {}, {})".format(
            self.__class__.__name__,
            self.x1, self.y1, self.x2, self.y2
    )

The best syntax for creating properties is using property as a decorator. This will reduce the number of method signatures inside of the class and make code more readable and maintainable. With decorators the above class becomes:

class Rectangle:
    def __init__(self, x1, y1, x2, y2):
        self.x1, self.y1 = x1, y1
        self.x2, self.y2 = x2, y2

    @property
    def width(self):
        """rectangle height measured from top"""
        return self.x2 - self.x1

    @width.setter
    def width(self, value):
        self.x2 = self.x1 + value

    @property
    def height(self):
        """rectangle height measured from top"""
        return self.y2 - self.y1

    @height.setter
    def height(self, value):
        self.y2 = self.y1 + value

Create zip file and ignore directory structure

Retain the parent directory so unzip doesn't spew files everywhere

When zipping directories, keeping the parent directory in the archive will help to avoid littering your current directory when you later unzip the archive file

So to avoid retaining all paths, and since you can't use -j and -r together ( you'll get an error ), you can do this instead:

cd path/to/parent/dir/;
zip -r ../my.zip ../$(basename $PWD)
cd -;

The ../$(basename $PWD) is the magic that retains the parent directory.

So now unzip my.zip will give a folder containing all your files:

parent-directory
+-- file1
+-- file2
+-- dir1
¦   +-- file3
¦   +-- file4

Instead of littering the current directory with the unzipped files:

file1
file2
dir1
+-- file3
+-- file4

What does 'x packages are looking for funding' mean when running `npm install`?

When you run npm update in the command prompt, when it is done it will recommend you type a new command called npm fund.

When you run npm fund it will list all the modules and packages you have installed that were created by companies or organizations that need money for their IT projects. You will see a list of webpages where you can send them money. So "funds" means "Angular packages you installed that could use some money from you as an option to help support their businesses".

It's basically a list of the modules you have that need contributions or donations of money to their projects and which list websites where you can enter a credit card to help pay for them.

How To Execute SSH Commands Via PHP

I've had a hard time with ssh2 in php mostly because the output stream sometimes works and sometimes it doesn't. I'm just gonna paste my lib here which works for me very well. If there are small inconsistencies in code it's because I have it plugged in a framework but you should be fine porting it:

<?php

class Components_Ssh {

    private $host;

    private $user;

    private $pass;

    private $port;

    private $conn = false;

    private $error;

    private $stream;

    private $stream_timeout = 100;

    private $log;

    private $lastLog;

    public function __construct ( $host, $user, $pass, $port, $serverLog ) {
        $this->host = $host;
        $this->user = $user;
        $this->pass = $pass;
        $this->port = $port;
        $this->sLog = $serverLog;

        if ( $this->connect ()->authenticate () ) {
            return true;
        }
    }

    public function isConnected () {
        return ( boolean ) $this->conn;
    }

    public function __get ( $name ) {
        return $this->$name;
    }

    public function connect () {
        $this->logAction ( "Connecting to {$this->host}" );
        if ( $this->conn = ssh2_connect ( $this->host, $this->port ) ) {
            return $this;
        }
        $this->logAction ( "Connection to {$this->host} failed" );
        throw new Exception ( "Unable to connect to {$this->host}" );
    }

    public function authenticate () {
        $this->logAction ( "Authenticating to {$this->host}" );
        if ( ssh2_auth_password ( $this->conn, $this->user, $this->pass ) ) {
            return $this;
        }
        $this->logAction ( "Authentication to {$this->host} failed" );
        throw new Exception ( "Unable to authenticate to {$this->host}" );
    }

    public function sendFile ( $localFile, $remoteFile, $permision = 0644 ) {
        if ( ! is_file ( $localFile ) ) throw new Exception ( "Local file {$localFile} does not exist" );
        $this->logAction ( "Sending file $localFile as $remoteFile" );

        $sftp = ssh2_sftp ( $this->conn );
        $sftpStream = @fopen ( 'ssh2.sftp://' . $sftp . $remoteFile, 'w' );
        if ( ! $sftpStream ) {
            //  if 1 method failes try the other one
            if ( ! @ssh2_scp_send ( $this->conn, $localFile, $remoteFile, $permision ) ) {
                throw new Exception ( "Could not open remote file: $remoteFile" );
            }
            else {
                return true;
            }
        }

        $data_to_send = @file_get_contents ( $localFile );

        if ( @fwrite ( $sftpStream, $data_to_send ) === false ) {
            throw new Exception ( "Could not send data from file: $localFile." );
        }

        fclose ( $sftpStream );

        $this->logAction ( "Sending file $localFile as $remoteFile succeeded" );
        return true;
    }

    public function getFile ( $remoteFile, $localFile ) {
        $this->logAction ( "Receiving file $remoteFile as $localFile" );
        if ( ssh2_scp_recv ( $this->conn, $remoteFile, $localFile ) ) {
            return true;
        }
        $this->logAction ( "Receiving file $remoteFile as $localFile failed" );
        throw new Exception ( "Unable to get file to {$remoteFile}" );
    }

    public function cmd ( $cmd, $returnOutput = false ) {
        $this->logAction ( "Executing command $cmd" );
        $this->stream = ssh2_exec ( $this->conn, $cmd );

        if ( FALSE === $this->stream ) {
            $this->logAction ( "Unable to execute command $cmd" );
            throw new Exception ( "Unable to execute command '$cmd'" );
        }
        $this->logAction ( "$cmd was executed" );

        stream_set_blocking ( $this->stream, true );
        stream_set_timeout ( $this->stream, $this->stream_timeout );
        $this->lastLog = stream_get_contents ( $this->stream );

        $this->logAction ( "$cmd output: {$this->lastLog}" );
        fclose ( $this->stream );
        $this->log .= $this->lastLog . "\n";
        return ( $returnOutput ) ? $this->lastLog : $this;
    }

    public function shellCmd ( $cmds = array () ) {
        $this->logAction ( "Openning ssh2 shell" );
        $this->shellStream = ssh2_shell ( $this->conn );

        sleep ( 1 );
        $out = '';
        while ( $line = fgets ( $this->shellStream ) ) {
            $out .= $line;
        }

        $this->logAction ( "ssh2 shell output: $out" );

        foreach ( $cmds as $cmd ) {
            $out = '';
            $this->logAction ( "Writing ssh2 shell command: $cmd" );
            fwrite ( $this->shellStream, "$cmd" . PHP_EOL );
            sleep ( 1 );
            while ( $line = fgets ( $this->shellStream ) ) {
                $out .= $line;
                sleep ( 1 );
            }
            $this->logAction ( "ssh2 shell command $cmd output: $out" );
        }

        $this->logAction ( "Closing shell stream" );
        fclose ( $this->shellStream );
    }

    public function getLastOutput () {
        return $this->lastLog;
    }

    public function getOutput () {
        return $this->log;
    }

    public function disconnect () {
        $this->logAction ( "Disconnecting from {$this->host}" );
        // if disconnect function is available call it..
        if ( function_exists ( 'ssh2_disconnect' ) ) {
            ssh2_disconnect ( $this->conn );
        }
        else { // if no disconnect func is available, close conn, unset var
            @fclose ( $this->conn );
            $this->conn = false;
        }
        // return null always
        return NULL;
    }

    public function fileExists ( $path ) {
        $output = $this->cmd ( "[ -f $path ] && echo 1 || echo 0", true );
        return ( bool ) trim ( $output );
    }
}

java.lang.ClassNotFoundException: org.springframework.core.io.Resource

There is a version conflict between jar/dependency please check all version of spring is same. if you use maven remove version of dependency and use Spring.io dependency.it handle version conflict. Add this in your pom

 <dependency>
            <groupId>io.spring.platform</groupId>
            <artifactId>platform-bom</artifactId>
            <version>2.0.1.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
  </dependency>

How to make an AlertDialog in Flutter?

Here is a shorter, but complete code.

If you need a dialog with only one button:

await showDialog(
      context: context,
      builder: (context) => new AlertDialog(
        title: new Text('Message'),
        content: Text(
                'Your file is saved.'),
        actions: <Widget>[
          new FlatButton(
            onPressed: () {
              Navigator.of(context, rootNavigator: true)
                  .pop(); // dismisses only the dialog and returns nothing
            },
            child: new Text('OK'),
          ),
        ],
      ),
    );

If you need a dialog with Yes/No buttons:

onPressed: () async {
bool result = await showDialog(
  context: context,
  builder: (context) {
    return AlertDialog(
      title: Text('Confirmation'),
      content: Text('Do you want to save?'),
      actions: <Widget>[
        new FlatButton(
          onPressed: () {
            Navigator.of(context, rootNavigator: true)
                .pop(false); // dismisses only the dialog and returns false
          },
          child: Text('No'),
        ),
        FlatButton(
          onPressed: () {
            Navigator.of(context, rootNavigator: true)
                .pop(true); // dismisses only the dialog and returns true
          },
          child: Text('Yes'),
        ),
      ],
    );
  },
);

if (result) {
  if (missingvalue) {
    Scaffold.of(context).showSnackBar(new SnackBar(
      content: new Text('Missing Value'),
    ));
  } else {
    saveObject();
    Navigator.of(context).pop(_myObject); // dismisses the entire widget
  }
} else {
  Navigator.of(context).pop(_myObject); // dismisses the entire widget
}
}

Add context path to Spring Boot application

server.contextPath=/mainstay

works for me if i had one war file in JBOSS. Among multiple war files where each contain jboss-web.xml it didn't work. I had to put jboss-web.xml inside WEB-INF directory with content

<?xml version="1.0" encoding="UTF-8"?>
<jboss-web xmlns="http://www.jboss.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.jboss.com/xml/ns/javaee http://www.jboss.org/j2ee/schema/jboss-web_5_1.xsd">
    <context-root>mainstay</context-root>
</jboss-web>

Where does VBA Debug.Print log to?

Debug.Print outputs to the "Immediate" window.

Debug.Print outputs to the Immediate window

Also, you can simply type ? and then a statement directly into the immediate window (and then press Enter) and have the output appear right below, like this:

simply type ? and then a statement directly into the immediate window

This can be very handy to quickly output the property of an object...

? myWidget.name

...to set the property of an object...

myWidget.name = "thingy"

...or to even execute a function or line of code, while in debugging mode:

Sheet1.MyFunction()

Printing newlines with print() in R

You can do this:

cat("File not supplied.\nUsage: ./program F=filename\n")

Notice that cat has a return value of NULL.

libpng warning: iCCP: known incorrect sRGB profile

Here is a ridiculously brute force answer:

I modified the gradlew script. Here is my new exec command at the end of the file in the

exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" **| grep -v "libpng warning:"**

Casting interfaces for deserialization in JSON.NET

Two things you might try:

Implement a try/parse model:

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

  [JsonConverter(typeof(RichDudeConverter))]
  public IPerson Owner { get; set; }
}

public interface IPerson {
  string Name { get; set; }
}

public class Tycoon : IPerson {
  public string Name { get; set; }
}

public class Magnate : IPerson {
  public string Name { get; set; }
  public string IndustryName { get; set; }
}

public class Heir: IPerson {
  public string Name { get; set; }
  public IPerson Benefactor { get; set; }
}

public class RichDudeConverter : JsonConverter
{
  public override bool CanConvert(Type objectType)
  {
    return (objectType == typeof(IPerson));
  }

  public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  {
    // pseudo-code
    object richDude = serializer.Deserialize<Heir>(reader);

    if (richDude == null)
    {
        richDude = serializer.Deserialize<Magnate>(reader);
    }

    if (richDude == null)
    {
        richDude = serializer.Deserialize<Tycoon>(reader);
    }

    return richDude;
  }

  public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  {
    // Left as an exercise to the reader :)
    throw new NotImplementedException();
  }
}

Or, if you can do so in your object model, implement a concrete base class between IPerson and your leaf objects, and deserialize to it.

The first can potentially fail at runtime, the second requires changes to your object model and homogenizes the output to the lowest common denominator.

Modifying list while iterating

I've been bitten before by (someone else's) "clever" code that tries to modify a list while iterating over it. I resolved that I would never do it under any circumstance.

You can use the slice operator mylist[::3] to skip across to every third item in your list.

mylist = [i for i in range(100)]
for i in mylist[::3]:
    print(i)

Other points about my example relate to new syntax in python 3.0.

  • I use a list comprehension to define mylist because it works in Python 3.0 (see below)
  • print is a function in python 3.0

Python 3.0 range() now behaves like xrange() used to behave, except it works with values of arbitrary size. The latter no longer exists.

Disable submit button on form submit

Want to submit value of button as well and prevent double form submit?

If you are using button of type submit and want to submit value of button as well, which will not happen if the button is disabled, you can set a form data attribute and test afterwards.

// Add class disableonsubmit to your form
    $(document).ready(function () {
        $('form.disableonsubmit').submit(function(e) {
            if ($(this).data('submitted') === true) {
                // Form is already submitted
                console.log('Form is already submitted, waiting response.');
                // Stop form from submitting again
                e.preventDefault();
            } else {
                // Set the data-submitted attribute to true for record
                $(this).data('submitted', true);
            }
        });
    });

How to get current page URL in MVC 3

One thing that isn't mentioned in other answers is case sensitivity, if it is going to be referenced in multiple places (which it isn't in the original question but is worth taking into consideration as this question appears in a lot of similar searches). Based on other answers I found the following worked for me initially:

Request.Url.AbsoluteUri.ToString()

But in order to be more reliable this then became:

Request.Url.AbsoluteUri.ToString().ToLower()

And then for my requirements (checking what domain name the site is being accessed from and showing the relevant content):

Request.Url.AbsoluteUri.ToString().ToLower().Contains("xxxx")

use Lodash to sort array of object by value

This method orderBy does not change the input array, you have to assign the result to your array :

var chars = this.state.characters;

chars = _.orderBy(chars, ['name'],['asc']); // Use Lodash to sort array by 'name'

 this.setState({characters: chars})

LINQ: Select where object does not contain items from list

I have not tried this, so I am not guarantueeing anything, however

foreach Bar f in filterBars
{
     search(f)
}
Foo search(Bar b)
{
    fooSelect = (from f in fooBunch
                 where !(from b in f.BarList select b.BarId).Contains(b.ID)
                 select f).ToList();

    return fooSelect;
}

matplotlib does not show my drawings although I call pyplot.show()

What solved my problem was just using the below two lines in ipython notebook at the top

%matplotib inline
%pylab inline

And it worked. I'm using Ubuntu16.04 and ipython-5.1

How to get only time from date-time C#

This works for me. I discovered it when I had to work with DateTime.Date to get only the date part.

var wholeDate = DateTime.Parse("6/22/2009 10:00:00 AM");
var time = wholeDate - wholeDate.Date;

Accessing an SQLite Database in Swift

AppDelegate.swift

func createDatabase()
{
    var path:Array=NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
    let directory:String=path[0]
    let DBpath=(directory as NSString).appendingPathComponent("Food.sqlite")

    print(DBpath)

    if (FileManager.default.fileExists(atPath: DBpath))
    {
        print("Successfull database create")
    }
    else
    {
        let pathfrom:String=(Bundle.main.resourcePath! as NSString).appendingPathComponent("Food.sqlite")

        var success:Bool
        do {
            try FileManager.default.copyItem(atPath: pathfrom, toPath: DBpath)
            success = true
        } catch _ {
            success = false
        }

        if !success
        {
            print("database not create ")
        }
        else
        {
            print("Successfull database new create")
        }
    }
}

Database.swift

import UIKit

class database: NSObject
{
func databasePath() -> NSString
{
    var path:Array=NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
    let directory:String=path[0] 
    let DBpath=(directory as NSString).appendingPathComponent("Food.sqlite")

    if (FileManager.default.fileExists(atPath: DBpath))
    {
        return DBpath as NSString
    }
    return DBpath as NSString
}

func ExecuteQuery(_ str:String) -> Bool
{
    var result:Bool=false
    let DBpath:String=self.databasePath() as String

    var db: OpaquePointer? = nil
    var stmt:OpaquePointer? = nil

    let strExec=str.cString(using: String.Encoding.utf8)

    if (sqlite3_open(DBpath, &db)==SQLITE_OK)
    {
        if (sqlite3_prepare_v2(db, strExec! , -1, &stmt, nil) == SQLITE_OK)
        {
            if (sqlite3_step(stmt) == SQLITE_DONE)
            {
                result=true
            } 
        }
        sqlite3_finalize(stmt)
    }
    sqlite3_close(db)

    return result
}

func SelectQuery(_ str:String) -> Array<Dictionary<String,String>>
{
    var result:Array<Dictionary<String,String>>=[]
    let DBpath:String=self.databasePath() as String

    var db: OpaquePointer? = nil
    var stmt:OpaquePointer? = nil

    let strExec=str.cString(using: String.Encoding.utf8)

    if ( sqlite3_open(DBpath,&db) == SQLITE_OK)
    {
        if (sqlite3_prepare_v2(db, strExec! , -1, &stmt, nil) == SQLITE_OK)
        {
            while (sqlite3_step(stmt) == SQLITE_ROW)
            {
                var i:Int32=0
                let icount:Int32=sqlite3_column_count(stmt)

                var dict=Dictionary<String, String>()

                while i < icount
                {
                    let strF=sqlite3_column_name(stmt, i)
                    let strV = sqlite3_column_text(stmt, i)

                    let rFiled:String=String(cString: strF!)
                    let rValue:String=String(cString: strV!)
                    //let rValue=String(cString: UnsafePointer<Int8>(strV!))

                    dict[rFiled] = rValue

                    i += 1
                }
                result.insert(dict, at: result.count)
            }
        sqlite3_finalize(stmt)
        }

    sqlite3_close(db)
    }
    return result
}

func AllSelectQuery(_ str:String) -> Array<Model>
{
    var result:Array<Model>=[]
    let DBpath:String=self.databasePath() as String

    var db: OpaquePointer? = nil
    var stmt:OpaquePointer? = nil

    let strExec=str.cString(using: String.Encoding.utf8)

    if ( sqlite3_open(DBpath,&db) == SQLITE_OK)
    {
        if (sqlite3_prepare_v2(db, strExec! , -1, &stmt, nil) == SQLITE_OK)
        {
            while (sqlite3_step(stmt) == SQLITE_ROW)
            {
                let mod=Model()

                mod.id=String(cString: sqlite3_column_text(stmt, 0))
                mod.image=String(cString: sqlite3_column_text(stmt, 1))
                mod.name=String(cString: sqlite3_column_text(stmt, 2))
                mod.foodtype=String(cString: sqlite3_column_text(stmt, 3))
                mod.vegtype=String(cString: sqlite3_column_text(stmt, 4))
                mod.details=String(cString: sqlite3_column_text(stmt, 5))

                result.insert(mod, at: result.count)
            }
            sqlite3_finalize(stmt)
        }
        sqlite3_close(db)
    }
    return result
}

}

Model.swift

import UIKit


class Model: NSObject
{
var uid:Int = 0
var id:String = ""
var image:String = ""
var name:String = ""
var foodtype:String = ""
var vegtype:String = ""
var details:String = ""
var mealtype:String = ""
var date:String = ""
}

Access database :

let DB=database()
var mod=Model()

database Query fire :

var DailyResult:Array<Model> = DB.AllSelectQuery("select * from food where foodtype == 'Sea Food' ORDER BY name ASC")

How do you get the current text contents of a QComboBox?

You can convert the QString type to python string by just using the str function. Assuming you are not using any Unicode characters you can get a python string as below:

text = str(combobox1.currentText())

If you are using any unicode characters, you can do:

text = unicode(combobox1.currentText())

String parsing in Java with delimiter tab "\t" using split

Try this:

String[] columnDetail = column.split("\t", -1);

Read the Javadoc on String.split(java.lang.String, int) for an explanation about the limit parameter of split function:

split

public String[] split(String regex, int limit)
Splits this string around matches of the given regular expression.
The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

The string "boo:and:foo", for example, yields the following results with these parameters:

Regex   Limit   Result
:   2   { "boo", "and:foo" }
:   5   { "boo", "and", "foo" }
:   -2  { "boo", "and", "foo" }
o   5   { "b", "", ":and:f", "", "" }
o   -2  { "b", "", ":and:f", "", "" }
o   0   { "b", "", ":and:f" }

When the last few fields (I guest that's your situation) are missing, you will get the column like this:

field1\tfield2\tfield3\t\t

If no limit is set to split(), the limit is 0, which will lead to that "trailing empty strings will be discarded". So you can just get just 3 fields, {"field1", "field2", "field3"}.

When limit is set to -1, a non-positive value, trailing empty strings will not be discarded. So you can get 5 fields with the last two being empty string, {"field1", "field2", "field3", "", ""}.

Git: How configure KDiff3 as merge tool and diff tool

I needed to add the command line parameters or KDiff3 would only open without files and prompt me for base, local and remote. I used the version supplied with TortoiseHg.

Additionally, I needed to resort to the good old DOS 8.3 file names.

[merge]
    tool = kdiff3

[mergetool "kdiff3"]
    cmd = /c/Progra~1/TortoiseHg/lib/kdiff3.exe $BASE $LOCAL $REMOTE -o $MERGED

However, it works correctly now.

Nesting CSS classes

Not with pure CSS. The closest equivalent is this:

.class1, .class2 {
    some stuff
}

.class2 {
    some more stuff
}

How can I programmatically freeze the top row of an Excel worksheet in Excel 2007 VBA?

Rows("2:2").Select
ActiveWindow.FreezePanes = True

This is the easiest way to freeze the top row. The rule for FreezePanes is it will freeze the upper left corner from the cell you selected. For example, if you highlight C10, it will freeze between columns B and C, rows 9 and 10. So when you highlight Row 2, it actually freeze between Rows 1 and 2 which is the top row.

Also, the .SplitColumn or .SplitRow will split your window once you unfreeze it which is not the way I like.

What does __FILE__ mean in Ruby?

The value of __FILE__ is a relative path that is created and stored (but never updated) when your file is loaded. This means that if you have any calls to Dir.chdir anywhere else in your application, this path will expand incorrectly.

puts __FILE__
Dir.chdir '../../'
puts __FILE__

One workaround to this problem is to store the expanded value of __FILE__ outside of any application code. As long as your require statements are at the top of your definitions (or at least before any calls to Dir.chdir), this value will continue to be useful after changing directories.

$MY_FILE_PATH = File.expand_path(File.dirname(__FILE__))

# open class and do some stuff that changes directory

puts $MY_FILE_PATH

C# Switch-case string starting with

Short answer: No.

The switch statement takes an expression that is only evaluated once. Based on the result, another piece of code is executed.

So what? => String.StartsWith is a function. Together with a given parameter, it is an expression. However, for your case you need to pass a different parameter for each case, so it cannot be evaluated only once.

Long answer #1 has been given by others.

Long answer #2:

Depending on what you're trying to achieve, you might be interested in the Command Pattern/Chain-of-responsibility pattern. Applied to your case, each piece of code would be represented by an implementation of a Command. In addition to the execute method, the command can provide a boolean Accept method, which checks whether the given string starts with the respective parameter.

Advantage: Instead of your hardcoded switch statement, hardcoded StartsWith evaluations and hardcoded strings, you'd have lot more flexibility.

The example you gave in your question would then look like this:

var commandList = new List<Command>() { new MyABCCommand() };

foreach (Command c in commandList)
{
    if (c.Accept(mystring))
    {
        c.Execute(mystring);
        break;
    }
}

class MyABCCommand : Command
{
    override bool Accept(string mystring)
    {
        return mystring.StartsWith("abc");
    }
}    

Chrome net::ERR_INCOMPLETE_CHUNKED_ENCODING error

I'm pretty sure that this issue can have multiple causes — both on server and on client sides.

Recently I faced it with a website I'm hosting on VPS (Ubuntu 18.04, PHP 7.4 FPM, nginx + certbot, site is powered by WordPress) — admin pages were loaded without CSS/JS.

It took me few hours to try different solutions, none of which helped.

Finally, I discovered, that for some reason (probably it was changed by me earlier, but also I can't exclude possibility it was like this by default) in my /etc/nginx/nginx.conf a first line of this file was commented:

# user www-data

I uncommented it, restarted nginx with sudo service nginx restart, and the issue was gone.

If anyone can check on pristine Ubuntu 18.04 with nginx installed if this line is commented by default — please put it in comments.

Entity Framework code first unique column

In Entity Framework 6.1+ you can use this attribute on your model:

[Index(IsUnique=true)]

You can find it in this namespace:

using System.ComponentModel.DataAnnotations.Schema;

If your model field is a string, make sure it is not set to nvarchar(MAX) in SQL Server or you will see this error with Entity Framework Code First:

Column 'x' in table 'dbo.y' is of a type that is invalid for use as a key column in an index.

The reason is because of this:

SQL Server retains the 900-byte limit for the maximum total size of all index key columns."

(from: http://msdn.microsoft.com/en-us/library/ms191241.aspx )

You can solve this by setting a maximum string length on your model:

[StringLength(450)]

Your model will look like this now in EF CF 6.1+:

public class User
{
   public int UserId{get;set;}
   [StringLength(450)]
   [Index(IsUnique=true)]
   public string UserName{get;set;}
}

Update:

if you use Fluent:

  public class UserMap : EntityTypeConfiguration<User>
  {
    public UserMap()
    {
      // ....
      Property(x => x.Name).IsRequired().HasMaxLength(450).HasColumnAnnotation("Index", new IndexAnnotation(new[] { new IndexAttribute("Index") { IsUnique = true } }));
    }
  }

and use in your modelBuilder:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
  // ...
  modelBuilder.Configurations.Add(new UserMap());
  // ...
}

Update 2

for EntityFrameworkCore see also this topic: https://github.com/aspnet/EntityFrameworkCore/issues/1698

Update 3

for EF6.2 see: https://github.com/aspnet/EntityFramework6/issues/274

Update 4

ASP.NET Core Mvc 2.2 with EF Core:

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Unique { get; set; }

How to change the project in GCP using CLI commands

Make sure you are authenticated with the correct account:

gcloud auth list
* account 1
  account 2

Change to the project's account if not:

gcloud config set account `ACCOUNT`

Depending on the account, the project list will be different:

gcloud projects list

- project 1
- project 2...

Switch to intended project:

gcloud config set project `PROJECT ID`

Convert a JSON Object to Buffer and Buffer to JSON Object back

You need to stringify the json, not calling toString

var buf = Buffer.from(JSON.stringify(obj));

And for converting string to json obj :

var temp = JSON.parse(buf.toString());

Setting up foreign keys in phpMyAdmin?

InnoDB allows you to add a new foreign key constraint to a table by using ALTER TABLE:

ALTER TABLE tbl_name
    ADD [CONSTRAINT [symbol]] FOREIGN KEY
    [index_name] (index_col_name, ...)
    REFERENCES tbl_name (index_col_name,...)
    [ON DELETE reference_option]
    [ON UPDATE reference_option]

On the other hand, if MyISAM has advantages over InnoDB in your context, why would you want to create foreign key constraints at all. You can handle this on the model level of your application. Just make sure the columns which you want to use as foreign keys are indexed!

No content to map due to end-of-input jackson parser

I had a similar error today and the issue was the content-type header of the post request. Make sure the content type is what you expect. In my case a multipart/form-data content-type header was being sent to the API instead of application/json.

How to disable anchor "jump" when loading a page?

This will work with bootstrap v3

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  if ($('.nav-tabs').length) {_x000D_
    var hash = window.location.hash;_x000D_
    var hashEl = $('ul.nav a[href="' + hash + '"]');_x000D_
    hash && hashEl.tab('show');_x000D_
_x000D_
    $('.nav-tabs a').click(function(e) {_x000D_
      e.preventDefault();_x000D_
      $(this).tab('show');_x000D_
      window.location.hash = this.hash;_x000D_
    });_x000D_
_x000D_
    // Change tab on hashchange_x000D_
    window.addEventListener('hashchange', function() {_x000D_
      var changedHash = window.location.hash;_x000D_
      changedHash && $('ul.nav a[href="' + changedHash + '"]').tab('show');_x000D_
    }, false);_x000D_
  }_x000D_
});
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>_x000D_
<div class="container">_x000D_
<ul class="nav nav-tabs">_x000D_
  <li class="active"><a data-toggle="tab" href="#home">Home</a></li>_x000D_
  <li><a data-toggle="tab" href="#menu1">Menu 1</a></li>_x000D_
</ul>_x000D_
_x000D_
<div class="tab-content">_x000D_
  <div id="home" class="tab-pane fade in active">_x000D_
    <h3>HOME</h3>_x000D_
    <p>Some content.</p>_x000D_
  </div>_x000D_
  <div id="menu1" class="tab-pane fade">_x000D_
    <h3>Menu 1</h3>_x000D_
    <p>Some content in menu 1.</p>_x000D_
  </div>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

EditText, inputType values (xml)

You can use the properties tab in eclipse to set various values.

here are all the possible values

  • none
  • text
  • textCapCharacters
  • textCapWords
  • textCapSentences
  • textAutoCorrect
  • textAutoComplete
  • textMultiLine
  • textImeMultiLine
  • textNoSuggestions
  • textUri
  • textEmailAddress
  • textEmailSubject
  • textShortMessage
  • textLongMessage
  • textPersonName
  • textPostalAddress
  • textPassword
  • textVisiblePassword
  • textWebEditText
  • textFilter
  • textPhonetic
  • textWebEmailAddress
  • textWebPassword
  • number
  • numberSigned
  • numberDecimal
  • numberPassword
  • phone
  • datetime
  • date
  • time

Check here for explanations: http://developer.android.com/reference/android/widget/TextView.html#attr_android:inputType

What is the difference between H.264 video and MPEG-4 video?

They are names for the same standard from two different industries with different naming methods, the guys who make & sell movies and the guys who transfer the movies over the internet. Since 2003: "MPEG 4 Part 10" = "H.264" = "AVC". Before that the relationship was a little looser in that they are not equal but an "MPEG 4 Part 2" decoder can render a stream that's "H.263". The Next standard is "MPEG H Part 2" = "H.265" = "HEVC"

How to set Java SDK path in AndroidStudio?

This problem arises due to incompatible JDK version. Download and install latest JDK(currently its 8) from java official site in case you are using previous versions. Then in Android Studio go to File->Project Structure->SDK location -> JDK location and set it to 'C:\Program Files\Java\jdk1.8.0_121' (Default location of JDK). Gradle sync your project and you are all set...

Caesar Cipher Function in Python

Why not use the function reverse on the shift input, and and join the plain_text with the shift, and input it as the cipher text:

Plain = int(input("enter a number ")) 
Rev = plain[::-1]
Cipher = " ".join(for cipher_text in Rev) 

Determine Whether Two Date Ranges Overlap

Split the problem into cases then handle each case.

The situation 'two date ranges intersect' is covered by two cases - the first date range starts within the second, or the second date range starts within the first.

Common HTTPclient and proxy

Here is how to do that with the last version of HTTPClient (4.3.4)

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpHost target = new HttpHost("localhost", 443, "https");
        HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");

        RequestConfig config = RequestConfig.custom()
                .setProxy(proxy)
                .build();
        HttpGet request = new HttpGet("/");
        request.setConfig(config);

        System.out.println("Executing request " + request.getRequestLine() + " to " + target + " via " + proxy);

        CloseableHttpResponse response = httpclient.execute(target, request);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            EntityUtils.consume(response.getEntity());
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }

json.dump throwing "TypeError: {...} is not JSON serializable" on seemingly valid object?

I wrote a class to normalize the data in my dictionary. The 'element' in the NormalizeData class below, needs to be of dict type. And you need to replace in the __iterate() with either your custom class object or any other object type that you would like to normalize.

class NormalizeData:

    def __init__(self, element):
        self.element = element

    def execute(self):
        if isinstance(self.element, dict):
            self.__iterate()
        else:
            return

    def __iterate(self):
        for key in self.element:
            if isinstance(self.element[key], <ClassName>):
                self.element[key] = str(self.element[key])

            node = NormalizeData(self.element[key])
            node.execute()

How can I get file extensions with JavaScript?

i just wanted to share this.

fileName.slice(fileName.lastIndexOf('.'))

although this has a downfall that files with no extension will return last string. but if you do so this will fix every thing :

   function getExtention(fileName){
     var i = fileName.lastIndexOf('.');
     if(i === -1 ) return false;
     return fileName.slice(i)
   }

How do I resolve "Run-time error '429': ActiveX component can't create object"?

The file msrdo20.dll is missing from the installation.

According to the Support Statement for Visual Basic 6.0 on Windows Vista, Windows Server 2008 and Windows 7 this file should be distributed with the application.

I'm not sure why it isn't, but my solution is to place the file somewhere on the machine, and register it using regsvr32 in the command line, eg:

regsvr32 c:\windows\system32\msrdo20.dll

In an ideal world you would package this up with the redistributable.

SQL SELECT multi-columns INTO multi-variable

SELECT @variable1 = col1, @variable2 = col2
FROM table1

Detecting real time window size changes in Angular 4

This is an example of service which I use.

You can get the screen width by subscribing to screenWidth$, or via screenWidth$.value.

The same is for mediaBreakpoint$ ( or mediaBreakpoint$.value)

import {
  Injectable,
  OnDestroy,
} from '@angular/core';
import {
  Subject,
  BehaviorSubject,
  fromEvent,
} from 'rxjs';
import {
  takeUntil,
  debounceTime,
} from 'rxjs/operators';

@Injectable()
export class ResponsiveService implements OnDestroy {
  private _unsubscriber$: Subject<any> = new Subject();
  public screenWidth$: BehaviorSubject<number> = new BehaviorSubject(null);
  public mediaBreakpoint$: BehaviorSubject<string> = new BehaviorSubject(null);

  constructor() {
    this.init();
  }

  init() {
    this._setScreenWidth(window.innerWidth);
    this._setMediaBreakpoint(window.innerWidth);
    fromEvent(window, 'resize')
      .pipe(
        debounceTime(1000),
        takeUntil(this._unsubscriber$)
      ).subscribe((evt: any) => {
        this._setScreenWidth(evt.target.innerWidth);
        this._setMediaBreakpoint(evt.target.innerWidth);
      });
  }

  ngOnDestroy() {
    this._unsubscriber$.next();
    this._unsubscriber$.complete();
  }

  private _setScreenWidth(width: number): void {
    this.screenWidth$.next(width);
  }

  private _setMediaBreakpoint(width: number): void {
    if (width < 576) {
      this.mediaBreakpoint$.next('xs');
    } else if (width >= 576 && width < 768) {
      this.mediaBreakpoint$.next('sm');
    } else if (width >= 768 && width < 992) {
      this.mediaBreakpoint$.next('md');
    } else if (width >= 992 && width < 1200) {
      this.mediaBreakpoint$.next('lg');
    } else if (width >= 1200 && width < 1600) {
      this.mediaBreakpoint$.next('xl');
    } else {
      this.mediaBreakpoint$.next('xxl');
    }
  }

}

Hope this helps someone

Optimal way to Read an Excel file (.xls/.xlsx)

Try to use Aspose.cells library (not free, but trial is enough to read), it is quite good

Install-package Aspose.cells

There is sample code:

using Aspose.Cells;
using System;

namespace ExcelReader
{
    class Program
    {
        static void Main(string[] args)
        {
            // Replace path for your file
            readXLS(@"C:\MyExcelFile.xls"); // or "*.xlsx"
            Console.ReadKey();
        }

        public static void readXLS(string PathToMyExcel)
        {
            //Open your template file.
            Workbook wb = new Workbook(PathToMyExcel);

            //Get the first worksheet.
            Worksheet worksheet = wb.Worksheets[0];

            //Get cells
            Cells cells = worksheet.Cells;

            // Get row and column count
            int rowCount = cells.MaxDataRow;
            int columnCount = cells.MaxDataColumn;

            // Current cell value
            string strCell = "";

            Console.WriteLine(String.Format("rowCount={0}, columnCount={1}", rowCount, columnCount));

            for (int row = 0; row <= rowCount; row++) // Numeration starts from 0 to MaxDataRow
            {
                for (int column = 0; column <= columnCount; column++)  // Numeration starts from 0 to MaxDataColumn
                {
                    strCell = "";
                    strCell = Convert.ToString(cells[row, column].Value);
                    if (String.IsNullOrEmpty(strCell))
                    {
                        continue;
                    }
                    else
                    {
                        // Do your staff here
                        Console.WriteLine(strCell);
                    }
                }
            }
        }
    }
}

HTML display result in text (input) field?

With .value and INPUT tag

<HTML>
  <HEAD>
    <TITLE>Sum</TITLE>

    <script type="text/javascript">
      function sum()
      {

         var num1 = document.myform.number1.value;
         var num2 = document.myform.number2.value;
         var sum = parseInt(num1) + parseInt(num2);
         document.getElementById('add').value = sum;
      }
    </script>
  </HEAD>

  <BODY>
    <FORM NAME="myform">
      <INPUT TYPE="text" NAME="number1" VALUE=""/> + 
      <INPUT TYPE="text" NAME="number2" VALUE=""/>
      <INPUT TYPE="button" NAME="button" Value="=" onClick="sum()"/>
      <INPUT TYPE="text" ID="add" NAME="result" VALUE=""/>
    </FORM>

  </BODY>
</HTML>

with innerHTML and DIV

<HTML>
  <HEAD>
    <TITLE>Sum</TITLE>

    <script type="text/javascript">
      function sum()
      {

         var num1 = document.myform.number1.value;
         var num2 = document.myform.number2.value;
         var sum = parseInt(num1) + parseInt(num2);
         document.getElementById('add').innerHTML = sum;
      }
    </script>
  </HEAD>

  <BODY>
    <FORM NAME="myform">
      <INPUT TYPE="text" NAME="number1" VALUE=""/> + 
      <INPUT TYPE="text" NAME="number2" VALUE=""/>
      <INPUT TYPE="button" NAME="button" Value="=" onClick="sum()"/>
      <DIV  ID="add"></DIV>
    </FORM>

  </BODY>
</HTML>

Convert XML String to Object

Simply Run Your Visual Studio 2013 as Administration ... Copy the content of your Xml file.. Go to Visual Studio 2013 > Edit > Paste Special > Paste Xml as C# Classes It will create your c# classes according to your Xml file content.

How can I delete all cookies with JavaScript?

On the face of it, it looks okay - if you call eraseCookie() on each cookie that is read from document.cookie, then all of your cookies will be gone.

Try this:

var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++)
  eraseCookie(cookies[i].split("=")[0]);

All of this with the following caveat:

  • JavaScript cannot remove cookies that have the HttpOnly flag set.

bundle install fails with SSL certificate verification error

Simple copy paste instruction given here about .pem file

https://gist.github.com/luislavena/f064211759ee0f806c88

For certificate verification failed

If you've read the previous sections, you will know what this means (and shame > on you if you have not).

We need to download AddTrustExternalCARoot-2048.pem. Open a Command Prompt and type in:

C:>gem which rubygems C:/Ruby21/lib/ruby/2.1.0/rubygems.rb Now, let's locate that directory. From within the same window, enter the path part up to the file extension, but using backslashes instead:

C:>start C:\Ruby21\lib\ruby\2.1.0\rubygems This will open a Explorer window inside the directory we indicated.

Step 3: Copy new trust certificate

Now, locate ssl_certs directory and copy the .pem file we obtained from previous step inside.

It will be listed with other files like GeoTrustGlobalCA.pem.

Error: 0xC0202009 at Data Flow Task, OLE DB Destination [43]: SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x80040E21

In my case the underlying system account through which the package was running was locked out. Once we got the system account unlocked and reran the package, it executed successfully. The developer said that he got to know of this while debugging wherein he directly tried to connect to the server and check the status of the connection.

curl posting with header application/x-www-form-urlencoded

 $curl = curl_init();
 curl_setopt_array($curl, array(
            CURLOPT_URL => "http://example.com",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => "value1=111&value2=222",
            CURLOPT_HTTPHEADER => array(
                "cache-control: no-cache",
                "content-type: application/x-www-form-urlencoded"
            ),
        ));
 $response = curl_exec($curl);
 $err = curl_error($curl);

 curl_close($curl);

 if (!$err)
 {
      var_dump($response);
 }

How do I find which process is leaking memory?

if the program leaks over a long time, top might not be practical. I would write a simple shell scripts that appends the result of "ps aux" to a file every X seconds, depending on how long it takes to leak significant amounts of memory. Something like:

while true
do
echo "---------------------------------" >> /tmp/mem_usage
date >> /tmp/mem_usage
ps aux >> /tmp/mem_usage
sleep 60
done

How to run Gradle from the command line on Mac bash

Also, if you don't have the gradlew file in your current directory:

You can install gradle with homebrew with the following command:

$ brew install gradle

As mentioned in this answer. Then, you are not going to need to include it in your path (homebrew will take care of that) and you can just run (from any directory):

$ gradle test 

VB.Net: Dynamically Select Image from My.Resources

Dim resources As Object = My.Resources.ResourceManager
PictureBoxName.Image = resources.GetObject("Company_Logo")

Redirect on Ajax Jquery Call

For ExpressJs router:

router.post('/login', async(req, res) => {
    return res.send({redirect: '/yoururl'});
})

Client-side:

    success: function (response) {
        if (response.redirect) {
            window.location = response.redirect
        }
    },

SQL-Server: Is there a SQL script that I can use to determine the progress of a SQL Server backup or restore process?

Use STATS in the BACKUP command if it is just a script.

Inside code it is a bit more complicated. In ODBC for example, you set SQL_ATTR_ASYNC_ENABLE and then look for SQL_STILL_EXECUTING return code, and do some repeated calls of SQLExecDirect until you get a SQL_SUCCESS (or eqiv).

How to test if string exists in file with Bash?

Regarding the following solution:

grep -Fxq "$FILENAME" my_list.txt

In case you are wondering (as I did) what -Fxq means in plain English:

  • F: Affects how PATTERN is interpreted (fixed string instead of a regex)
  • x: Match whole line
  • q: Shhhhh... minimal printing

From the man file:

-F, --fixed-strings
    Interpret  PATTERN  as  a  list of fixed strings, separated by newlines, any of which is to be matched.
    (-F is specified by POSIX.)
-x, --line-regexp
    Select only those matches that exactly match the whole line.  (-x is specified by POSIX.)
-q, --quiet, --silent
    Quiet; do not write anything to standard output.  Exit immediately with zero status  if  any  match  is
          found,  even  if  an error was detected.  Also see the -s or --no-messages option.  (-q is specified by
          POSIX.)

Regex replace uppercase with lowercase letters

Before searching with regex like [A-Z], you should press the case sensitive button (or Alt+C) (as leemour nicely suggested to be edited in the accepted answer). Just to be clear, I'm leaving a few other examples:

  1. Capitalize words
    • Find: (\s)([a-z]) (\s also matches new lines, i.e. "venuS" => "VenuS")
    • Replace: $1\u$2
  2. Uncapitalize words
    • Find: (\s)([A-Z])
    • Replace: $1\l$2
  3. Remove camel case (e.g. cAmelCAse => camelcAse => camelcase)
    • Find: ([a-z])([A-Z])
    • Replace: $1\l$2
  4. Lowercase letters within words (e.g. LowerCASe => Lowercase)
    • Find: (\w)([A-Z]+)
    • Replace: $1\L$2
    • Alternate Replace: \L$0
  5. Uppercase letters within words (e.g. upperCASe => uPPERCASE)
    • Find: (\w)([A-Z]+)
    • Replace: $1\U$2
  6. Uppercase previous (e.g. upperCase => UPPERCase)
    • Find: (\w+)([A-Z])
    • Replace: \U$1$2
  7. Lowercase previous (e.g. LOWERCase => lowerCase)
    • Find: (\w+)([A-Z])
    • Replace: \L$1$2
  8. Uppercase the rest (e.g. upperCase => upperCASE)
    • Find: ([A-Z])(\w+)
    • Replace: $1\U$2
  9. Lowercase the rest (e.g. lOWERCASE => lOwercase)
    • Find: ([A-Z])(\w+)
    • Replace: $1\L$2
  10. Shift-right-uppercase (e.g. Case => cAse => caSe => casE)
    • Find: ([a-z\s])([A-Z])(\w)
    • Replace: $1\l$2\u$3
  11. Shift-left-uppercase (e.g. CasE => CaSe => CAse => Case)
    • Find: (\w)([A-Z])([a-z\s])
    • Replace: \u$1\l$2$3

Regarding the question (match words with at least one uppercase and one lowercase letter and make them lowercase), leemour's comment-answer is the right answer. Just to clarify, if there is only one group to replace, you can just use ?: in the inner groups (i.e. non capture groups) or avoid creating them at all:

  • Find: ((?:[a-z][A-Z]+)|(?:[A-Z]+[a-z])) OR ([a-z][A-Z]+|[A-Z]+[a-z])
  • Replace: \L$1

2016-06-23 Edit

Tyler suggested by editing this answer an alternate find expression for #4:

  • (\B)([A-Z]+)

According to the documentation, \B will look for a character that is not at the word's boundary (i.e. not at the beginning and not at the end). You can use the Replace All button and it does the exact same thing as if you had (\w)([A-Z]+) as the find expression.

However, the downside of \B is that it does not allow single replacements, perhaps due to the find's "not boundary" restriction (please do edit this if you know the exact reason).

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

Many people have given a fix, so I'll talk about the source of the problem.

According to the exception log:

Caused by: java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation
    at android.app.Activity.onCreate(Activity.java:1081)
    at android.support.v4.app.SupportActivity.onCreate(SupportActivity.java:66)
    at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:297)
    at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:84)
    at com.nut.blehunter.ui.DialogContainerActivity.onCreate(DialogContainerActivity.java:43)
    at android.app.Activity.performCreate(Activity.java:7372)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1218)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3147)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3302) 
    at android.app.ActivityThread.-wrap12(Unknown Source:0) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1891) 
    at android.os.Handler.dispatchMessage(Handler.java:108) 
    at android.os.Looper.loop(Looper.java:166)

The code that triggered the exception in Activity.java

    //Need to pay attention mActivityInfo.isFixedOrientation() and ActivityInfo.isTranslucentOrFloating(ta)
    if (getApplicationInfo().targetSdkVersion >= O_MR1 && mActivityInfo.isFixedOrientation()) {
        final TypedArray ta = obtainStyledAttributes(com.android.internal.R.styleable.Window);
        final boolean isTranslucentOrFloating = ActivityInfo.isTranslucentOrFloating(ta);
        ta.recycle();

        //Exception occurred
        if (isTranslucentOrFloating) {
            throw new IllegalStateException(
                    "Only fullscreen opaque activities can request orientation");
        }
    }

mActivityInfo.isFixedOrientation():

        /**
        * Returns true if the activity's orientation is fixed.
        * @hide
        */
        public boolean isFixedOrientation() {
            return isFixedOrientationLandscape() || isFixedOrientationPortrait()
                    || screenOrientation == SCREEN_ORIENTATION_LOCKED;
        }
        /**
        * Returns true if the activity's orientation is fixed to portrait.
        * @hide
        */
        boolean isFixedOrientationPortrait() {
            return isFixedOrientationPortrait(screenOrientation);
        }

        /**
        * Returns true if the activity's orientation is fixed to portrait.
        * @hide
        */
        public static boolean isFixedOrientationPortrait(@ScreenOrientation int orientation) {
            return orientation == SCREEN_ORIENTATION_PORTRAIT
                    || orientation == SCREEN_ORIENTATION_SENSOR_PORTRAIT
                    || orientation == SCREEN_ORIENTATION_REVERSE_PORTRAIT
                    || orientation == SCREEN_ORIENTATION_USER_PORTRAIT;
        }

        /**
        * Determines whether the {@link Activity} is considered translucent or floating.
        * @hide
        */
        public static boolean isTranslucentOrFloating(TypedArray attributes) {
            final boolean isTranslucent = attributes.getBoolean(com.android.internal.R.styleable.Window_windowIsTranslucent, false);
            final boolean isSwipeToDismiss = !attributes.hasValue(com.android.internal.R.styleable.Window_windowIsTranslucent)
                                            && attributes.getBoolean(com.android.internal.R.styleable.Window_windowSwipeToDismiss, false);
            final boolean isFloating = attributes.getBoolean(com.android.internal.R.styleable.Window_windowIsFloating, false);
            return isFloating || isTranslucent || isSwipeToDismiss;
        }

According to the above code analysis, when TargetSdkVersion>=27, when using SCREEN_ORIENTATION_LANDSCAPE, SCREEN_ORIENTATION_PORTRAIT, and other related attributes, the use of windowIsTranslucent, windowIsFloating, and windowSwipeToDismiss topic attributes will trigger an exception.

After the problem is found, you can change the TargetSdkVersion or remove the related attributes of the theme according to your needs.

Xml Parsing in C#

First add an Enrty and Category class:

public class Entry {     public string Id { get; set; }     public string Title { get; set; }     public string Updated { get; set; }     public string Summary { get; set; }     public string GPoint { get; set; }     public string GElev { get; set; }     public List<string> Categories { get; set; } }  public class Category {     public string Label { get; set; }     public string Term { get; set; } } 

Then use LINQ to XML

XDocument xDoc = XDocument.Load("path");          List<Entry> entries = (from x in xDoc.Descendants("entry")             select new Entry()             {                 Id = (string) x.Element("id"),                 Title = (string)x.Element("title"),                 Updated = (string)x.Element("updated"),                 Summary = (string)x.Element("summary"),                 GPoint = (string)x.Element("georss:point"),                 GElev = (string)x.Element("georss:elev"),                 Categories = (from c in x.Elements("category")                                   select new Category                                   {                                       Label = (string)c.Attribute("label"),                                       Term = (string)c.Attribute("term")                                   }).ToList();             }).ToList(); 

Java - Convert image to Base64

Late GraveDig ... Just constrain your byte array to the file size.

FileInputStream fis = new FileInputStream( file );
byte[] byteArray= new byte[(int) file.length()];

Echo a blank (empty) line to the console from a Windows batch file

Any of the below three options works for you:

echo[

echo(

echo. 

For example:

@echo off
echo There will be a blank line below
echo[
echo Above line is blank
echo( 
echo The above line is also blank.
echo. 
echo The above line is also blank.

How do I create an Excel chart that pulls data from multiple sheets?

2007 is more powerful with ribbon..:=) To add new series in chart do: Select Chart, then click Design in Chart Tools on the ribbon, On the Design ribbon, select "Select Data" in Data Group, Then you will see the button for Add to add new series.

Hope that will help.

How to select between brackets (or quotes or ...) in Vim?

Use arrows or hjkl to get to one of the bracketing expressions, then v to select visual (i.e. selecting) mode, then % to jump to the other bracket.

How do I determine k when using k-means clustering?

If you use MATLAB, any version since 2013b that is, you can make use of the function evalclusters to find out what should the optimal k be for a given dataset.

This function lets you choose from among 3 clustering algorithms - kmeans, linkage and gmdistribution.

It also lets you choose from among 4 clustering evaluation criteria - CalinskiHarabasz, DaviesBouldin, gap and silhouette.

Nesting await in Parallel.ForEach

An extension method for this which makes use of SemaphoreSlim and also allows to set maximum degree of parallelism

    /// <summary>
    /// Concurrently Executes async actions for each item of <see cref="IEnumerable<typeparamref name="T"/>
    /// </summary>
    /// <typeparam name="T">Type of IEnumerable</typeparam>
    /// <param name="enumerable">instance of <see cref="IEnumerable<typeparamref name="T"/>"/></param>
    /// <param name="action">an async <see cref="Action" /> to execute</param>
    /// <param name="maxDegreeOfParallelism">Optional, An integer that represents the maximum degree of parallelism,
    /// Must be grater than 0</param>
    /// <returns>A Task representing an async operation</returns>
    /// <exception cref="ArgumentOutOfRangeException">If the maxActionsToRunInParallel is less than 1</exception>
    public static async Task ForEachAsyncConcurrent<T>(
        this IEnumerable<T> enumerable,
        Func<T, Task> action,
        int? maxDegreeOfParallelism = null)
    {
        if (maxDegreeOfParallelism.HasValue)
        {
            using (var semaphoreSlim = new SemaphoreSlim(
                maxDegreeOfParallelism.Value, maxDegreeOfParallelism.Value))
            {
                var tasksWithThrottler = new List<Task>();

                foreach (var item in enumerable)
                {
                    // Increment the number of currently running tasks and wait if they are more than limit.
                    await semaphoreSlim.WaitAsync();

                    tasksWithThrottler.Add(Task.Run(async () =>
                    {
                        await action(item).ContinueWith(res =>
                        {
                            // action is completed, so decrement the number of currently running tasks
                            semaphoreSlim.Release();
                        });
                    }));
                }

                // Wait for all tasks to complete.
                await Task.WhenAll(tasksWithThrottler.ToArray());
            }
        }
        else
        {
            await Task.WhenAll(enumerable.Select(item => action(item)));
        }
    }

Sample Usage:

await enumerable.ForEachAsyncConcurrent(
    async item =>
    {
        await SomeAsyncMethod(item);
    },
    5);

How to get the entire document HTML as a string?

I am using outerHTML for elements (the main <html> container), and XMLSerializer for anything else including <!DOCTYPE>, random comments outside the <html> container, or whatever else might be there. It seems that whitespace isn't preserved outside the <html> element, so I'm adding newlines by default with sep="\n".

_x000D_
_x000D_
function get_document_html(sep="\n") {_x000D_
    let html = "";_x000D_
    let xml = new XMLSerializer();_x000D_
    for (let n of document.childNodes) {_x000D_
        if (n.nodeType == Node.ELEMENT_NODE)_x000D_
            html += n.outerHTML + sep;_x000D_
        else_x000D_
            html += xml.serializeToString(n) + sep;_x000D_
    }_x000D_
    return html;_x000D_
}_x000D_
_x000D_
console.log(get_document_html().slice(0, 200));
_x000D_
_x000D_
_x000D_

Finish all previous activities

for API >= 15 to API 23 simple solution.

 Intent nextScreen = new Intent(currentActivity.this, MainActivity.class);
 nextScreen.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
 startActivity(nextScreen);
 ActivityCompat.finishAffinity(currentActivity.this);

Default text which won't be shown in drop-down list

Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML. Adding a value of selected to the item we want to appear as a header forces it to show in the first place as a placeholder. Something like:

<option selected disabled>Choose here</option>

The complete markup should be along these lines:

<select>
    <option selected disabled>Choose here</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>

You can take a look at this fiddle, and here's the result:

enter image description here

If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden attribute like so:

<select>
    <option selected disabled hidden>Choose here</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>

Check the fiddle here and the screenshot below.

enter image description here


Here is the solution:

<select>
    <option style="display:none;" selected>Select language</option>
    <option>Option 1</option>
    <option>Option 2</option>
</select>

Convert Python program to C/C++ code?

Yes. Look at Cython. It does just that: Converts Python to C for speedups.

How can I start an Activity from a non-Activity class?

You can define a context for your application say ExampleContext which will hold the context of your application and then use it to instantiate an activity like this:

var intent = new Intent(Application.ApplicationContext, typeof(Activity2));
intent.AddFlags(ActivityFlags.NewTask);
Application.ApplicationContext.StartActivity(intent);

Please bear in mind that this code is written in C# as I use MonoDroid, but I believe it is very similar to Java. For how to create an ApplicationContext look at this thread

This is how I made my Application Class

    [Application]
    public class Application : Android.App.Application, IApplication
    {
        public Application(IntPtr handle, JniHandleOwnership transfer) : base(handle, transfer)
        {

        }
        public object MyObject { get; set; }
    }

How can I get a Unicode character's code?

Just convert it to int:

char registered = '®';
int code = (int) registered;

In fact there's an implicit conversion from char to int so you don't have to specify it explicitly as I've done above, but I would do so in this case to make it obvious what you're trying to do.

This will give the UTF-16 code unit - which is the same as the Unicode code point for any character defined in the Basic Multilingual Plane. (And only BMP characters can be represented as char values in Java.) As Andrzej Doyle's answer says, if you want the Unicode code point from an arbitrary string, use Character.codePointAt().

Once you've got the UTF-16 code unit or Unicode code points, but of which are integers, it's up to you what you do with them. If you want a string representation, you need to decide exactly what kind of representation you want. (For example, if you know the value will always be in the BMP, you might want a fixed 4-digit hex representation prefixed with U+, e.g. "U+0020" for space.) That's beyond the scope of this question though, as we don't know what the requirements are.

IndexOf function in T-SQL

CHARINDEX is what you are looking for

select CHARINDEX('@', '[email protected]')
-----------
8

(1 row(s) affected)

-or-

select CHARINDEX('c', 'abcde')
-----------
3

(1 row(s) affected)

Constant pointer vs Pointer to constant

const int* ptr;

is a pointer to constant (content). You are allowed to modify the pointer. e.g. ptr = NULL, ptr++, but modification of the content is not possible.

int * const ptr;

Is a constant pointer. The opposite is possible. You are not allowed to modify the pointer, but you are allowed to modify what it points to e.g. *ptr += 5.

Convert Unicode to ASCII without errors in Python

Looks like you are using python 2.x. Python 2.x defaults to ascii and it doesn’t know about Unicode. Hence the exception.

Just paste the below line after shebang, it will work

# -*- coding: utf-8 -*-

Renaming branches remotely in Git

You just have to create a new local branch with the desired name, push it to your remote, and then delete the old remote branch:

$ git branch new-branch-name origin/old-branch-name
$ git push origin --set-upstream new-branch-name
$ git push origin :old-branch-name

Then, to see the old branch name, each client of the repository would have to do:

$ git fetch origin
$ git remote prune origin

NOTE: If your old branch is your main branch, you should change your main branch settings. Otherwise, when you run $ git push origin :old-branch-name, you'll get the error "deletion of the current branch prohibited".

Swap x and y axis without manually swapping values

Using Excel 2010 x64. XY plot: I could not see no tabs (it is late and I am probably tired blind, 250 limit?). Here is what worked for me:

Swap the data columns, to end with X_data in column A and Y_data in column B.

My original data had Y_data in column A and X_data in column B, and the graph was rotated 90deg clockwise. I was suffering. Then it hit me: an Excel XY plot literally wants {x,y} pairs, i.e. X_data in first column and Y_data in second column. But it does not tell you this right away. For me an XY plot means Y=f(X) plotted.

Load JSON text into class object in c#

First create a class to represent your json data.

public class MyFlightDto
{
    public string err_code { get; set; }
    public string org { get; set; } 
    public string flight_date { get; set; }
    // Fill the missing properties for your data
}

Using Newtonsoft JSON serializer to Deserialize a json string to it's corresponding class object.

var jsonInput = "{ org:'myOrg',des:'hello'}"; 
MyFlightDto flight = Newtonsoft.Json.JsonConvert.DeserializeObject<MyFlightDto>(jsonInput);

Or Use JavaScriptSerializer to convert it to a class(not recommended as the newtonsoft json serializer seems to perform better).

string jsonInput="have your valid json input here"; //
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
Customer objCustomer  = jsonSerializer.Deserialize<Customer >(jsonInput)

Assuming you want to convert it to a Customer classe's instance. Your class should looks similar to the JSON structure (Properties)

What is the most efficient way to concatenate N arrays?

If you are in the middle of piping the result through map/filter/sort etc and you want to concat array of arrays, you can use reduce

let sorted_nums = ['1,3', '4,2']
  .map(item => item.split(','))   // [['1', '3'], ['4', '2']]
  .reduce((a, b) => a.concat(b))  // ['1', '3', '4', '2']
  .sort()                         // ['1', '2', '3', '4']

TypeError: $ is not a function when calling jQuery function

<script>
var jq=jQuery.noConflict();
(function ($) 
    {
    function nameoffunction()
    {
        // Set your code here!!
    }

    $(document).ready(readyFn); 
    })(jQuery);

now use jq in place of jQuery

jQuery load first 3 elements, click "load more" to display next 5 elements

The expression $(document).ready(function() deprecated in jQuery3.

See working fiddle with jQuery 3 here

Take into account I didn't include the showless button.

Here's the code:

JS

$(function () {
    x=3;
    $('#myList li').slice(0, 3).show();
    $('#loadMore').on('click', function (e) {
        e.preventDefault();
        x = x+5;
        $('#myList li').slice(0, x).slideDown();
    });
});

CSS

#myList li{display:none;
}
#loadMore {
    color:green;
    cursor:pointer;
}
#loadMore:hover {
    color:black;
}

Getting Django admin url for an object

There's another way for the later versions, for example in 1.10:

{% load admin_urls %}
<a href="{% url opts|admin_urlname:'add' %}">Add user</a>
<a href="{% url opts|admin_urlname:'delete' user.pk %}">Delete this user</a>

Where opts is something like mymodelinstance._meta or MyModelClass._meta

One gotcha is you can't access underscore attributes directly in Django templates (like {{ myinstance._meta }}) so you have to pass the opts object in from the view as template context.

Multiple conditions with CASE statements

Another way based on amadan:

    SELECT * FROM [Purchasing].[Vendor] WHERE  

      ( (@url IS null OR @url = '' OR @url = 'ALL') and   PurchasingWebServiceURL LIKE '%')
    or

       ( @url = 'blank' and  PurchasingWebServiceURL = '')
    or
        (@url = 'fail' and  PurchasingWebServiceURL NOT LIKE '%treyresearch%')
    or( (@url not in ('fail','blank','','ALL') and @url is not null and 
          PurchasingWebServiceUrl Like '%'+@ur+'%') 
END

Java: Integer equals vs. ==

As well for correctness of using == you can just unbox one of compared Integer values before doing == comparison, like:

if ( firstInteger.intValue() == secondInteger ) {..

The second will be auto unboxed (of course you have to check for nulls first).

Plotting multiple time series on the same plot using ggplot()

I know this is old but it is still relevant. You can take advantage of reshape2::melt to change the dataframe into a more friendly structure for ggplot2.

Advantages:

  • allows you plot any number of lines
  • each line with a different color
  • adds a legend for each line
  • with only one call to ggplot/geom_line

Disadvantage:

  • an extra package(reshape2) required
  • melting is not so intuitive at first

For example:

jobsAFAM1 <- data.frame(
  data_date = seq.Date(from = as.Date('2017-01-01'),by = 'day', length.out = 100),
  Percent.Change = runif(5,1,100)
)

jobsAFAM2 <- data.frame(
  data_date = seq.Date(from = as.Date('2017-01-01'),by = 'day', length.out = 100),
  Percent.Change = runif(5,1,100)
)

jobsAFAM <- merge(jobsAFAM1, jobsAFAM2, by="data_date")

jobsAFAMMelted <- reshape2::melt(jobsAFAM, id.var='data_date')

ggplot(jobsAFAMMelted, aes(x=data_date, y=value, col=variable)) + geom_line()

enter image description here

Characters allowed in a URL

The upcoming change is for chinese, arabic domain names not URIs. The internationalised URIs are called IRIs and are defined in RFC 3987. However, having said that I'd recommend not doing this yourself but relying on an existing, tested library since there are lots of choices of URI encoding/decoding and what are considered safe by specification, versus what are safe by actual use (browsers).

Spring Boot - Loading Initial Data

As suggestion try this:

@Bean
public CommandLineRunner loadData(CustomerRepository repository) {
    return (args) -> {
        // save a couple of customers
        repository.save(new Customer("Jack", "Bauer"));
        repository.save(new Customer("Chloe", "O'Brian"));
        repository.save(new Customer("Kim", "Bauer"));
        repository.save(new Customer("David", "Palmer"));
        repository.save(new Customer("Michelle", "Dessler"));

        // fetch all customers
        log.info("Customers found with findAll():");
        log.info("-------------------------------");
        for (Customer customer : repository.findAll()) {
            log.info(customer.toString());
        }
        log.info("");

        // fetch an individual customer by ID
        Customer customer = repository.findOne(1L);
        log.info("Customer found with findOne(1L):");
        log.info("--------------------------------");
        log.info(customer.toString());
        log.info("");

        // fetch customers by last name
        log.info("Customer found with findByLastNameStartsWithIgnoreCase('Bauer'):");
        log.info("--------------------------------------------");
        for (Customer bauer : repository
                .findByLastNameStartsWithIgnoreCase("Bauer")) {
            log.info(bauer.toString());
        }
        log.info("");
    }
}

Option 2: Initialize with schema and data scripts

Prerequisites: in application.properties you have to mention this:

spring.jpa.hibernate.ddl-auto=none (otherwise scripts will be ignored by hibernate, and it will scan project for @Entity and/or @Table annotated classes)

Then, in your MyApplication class paste this:

@Bean(name = "dataSource")
public DriverManagerDataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName("org.h2.Driver");
    dataSource.setUrl("jdbc:h2:~/myDB;MV_STORE=false");
    dataSource.setUsername("sa");
    dataSource.setPassword("");

    // schema init
    Resource initSchema = new ClassPathResource("scripts/schema-h2.sql");
    Resource initData = new ClassPathResource("scripts/data-h2.sql");
    DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema, initData);
    DatabasePopulatorUtils.execute(databasePopulator, dataSource);

    return dataSource;
}

Where scripts folder is located under resources folder (IntelliJ Idea)

Hope it helps someone

error C2065: 'cout' : undeclared identifier

If you started a project requiring the #include "stdafx.h" line, put it first.

Convert an ArrayList to an object array

TypeA[] array = (TypeA[]) a.toArray();

Is there a way to use PhantomJS in Python?

In case you are using Buildout, you can easily automate the installation processes that Pykler describes using the gp.recipe.node recipe.

[nodejs]
recipe = gp.recipe.node
version = 0.10.32
npms = phantomjs
scripts = phantomjs

That part installs node.js as binary (at least on my system) and then uses npm to install PhantomJS. Finally it creates an entry point bin/phantomjs, which you can call the PhantomJS webdriver with. (To install Selenium, you need to specify it in your egg requirements or in the Buildout configuration.)

driver = webdriver.PhantomJS('bin/phantomjs')

React "after render" code?

React has few lifecycle methods which help in these situations, the lists including but not limited to getInitialState, getDefaultProps, componentWillMount, componentDidMount etc.

In your case and the cases which needs to interact with the DOM elements, you need to wait till the dom is ready, so use componentDidMount as below:

/** @jsx React.DOM */
var List = require('../list');
var ActionBar = require('../action-bar');
var BalanceBar = require('../balance-bar');
var Sidebar = require('../sidebar');
var AppBase = React.createClass({
  componentDidMount: function() {
    ReactDOM.findDOMNode(this).height = /* whatever HEIGHT */;
  },
  render: function () {
    return (
      <div className="wrapper">
        <Sidebar />
        <div className="inner-wrapper">
          <ActionBar title="Title Here" />
          <BalanceBar balance={balance} />
          <div className="app-content">
            <List items={items} />
          </div>
        </div>
      </div>
    );
  }
});

module.exports = AppBase;

Also for more information about lifecycle in react you can have look the below link: https://facebook.github.io/react/docs/state-and-lifecycle.html

getInitialState, getDefaultProps, componentWillMount, componentDidMount

Hide axis values but keep axis tick labels in matplotlib

plt.gca().axes.yaxis.set_ticklabels([])

enter image description here

Format date as dd/MM/yyyy using pipes

If anyone looking with time and timezone, this is for you

 {{data.ct | date :'dd-MMM-yy h:mm:ss a '}}

add z for time zone at the end of date and time format

 {{data.ct | date :'dd-MMM-yy h:mm:ss a z'}}

How to use store and use session variables across pages?

Starting a Session:

Put below code at the top of file.

<?php session_start();?>

Storing a session variable:

<?php $_SESSION['id']=10; ?>

To Check if data stored in session variable:

<?php if(isset($_SESSION['id']) && !empty(isset($_SESSION['id'])))
echo “Session id “.$_SESSION['id'].” exist”;
else
echo “Session not set “;?>

?> detail here http://skillrow.com/sessions-in-php-4/

how to POST/Submit an Input Checkbox that is disabled?

Adding onclick="this.checked=true"Solve my problem:
Example:

<input type="checkbox" id="scales" name="feature[]" value="scales" checked="checked" onclick="this.checked=true" />

phpmyadmin #1045 Cannot log in to the MySQL server. after installing mysql command line client

Adding the following $cfg helps to narrow down the problem

$cfg['Error_Handler']['display'] = true;
$cfg['Error_Handler']['gather'] = true;

Don't forget to remove those $cfg after done debugging!

How to get height of <div> in px dimension

Use height():

var result = $("#myDiv").height();
alert(result);

This will give you the unit-less computed height in pixels. "px" will be stripped from the result. I.e. if the height is 400px, the result will be 400, but the result will be in pixels.

If you want to do it without jQuery, you can use plain JavaScript:

var result = document.getElementById("myDiv").offsetHeight;

How to format a java.sql Timestamp for displaying?

If you're using MySQL and want the database itself to perform the conversion, use this:

DATE_FORMAT(date,format)

If you prefer to format using Java, use this:

java.text.SimpleDateFormat

SimpleDateFormat dateFormat = new SimpleDateFormat("M/dd/yyyy");
dateFormat.format( new Date() );

Java - Convert integer to string

One that I use often:

 Integer.parseInt("1234");

Point is, there are plenty of ways to do this, all equally valid. As to which is most optimum/efficient, you'd have to ask someone else.

Android View shadow

This question may be old, but for anybody in future that wants a simple way to achieve complex shadow effects check out my library here https://github.com/BluRe-CN/ComplexView

Using the library, you can change shadow colors, tweak edges and so much more. Here's an example to achieve what you seek for.

<com.blure.complexview.ComplexView
        android:layout_width="400dp"
        android:layout_height="600dp"
        app:radius="10dp"
        app:shadow="true"
        app:shadowSpread="2">

        <com.blure.complexview.ComplexView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:color="#fdfcfc"
            app:radius="10dp" />
    </com.blure.complexview.ComplexView>

To change the shadow color, use app:shadowColor="your color code".

HTML table headers always visible at top of window when viewing a large table

If you're targeting modern css3 compliant browsers (Browser support: https://caniuse.com/#feat=css-sticky) you can use position:sticky, which doesn't require JS and won't break the table layout miss-aligning th and td of the same column. Nor does it require fixed column width to work properly.

Example for a single header row:

thead th
{
    position: sticky;
    top: 0px;
}

For theads with 1 or 2 rows, you can use something like this:

thead > :last-child th
{
    position: sticky;
    top: 30px; /* This is for all the the "th" elements in the second row, (in this casa is the last child element into the thead) */
}

thead > :first-child th
{
    position: sticky;
    top: 0px; /* This is for all the the "th" elements in the first child row */
}

You might need to play a bit with the top property of the last child changing the number of pixels to match the height of the first row (+ the margin + the border + the padding, if any), so the second row sticks just down bellow the first one.

Also both solutions work even if you have more than one table in the same page: the th element of each one starts to be sticky when its top position is the one indicated into the css definition and just disappear when all the table scrolls down. So if there are more tables all work beautifully the same way.

Why to use last-child before and first-child after in the css?

Because css rules are rendered by the browser in the same order as you write them into the css file and because of this if you have just 1 row into the thead element the first row is simultaneously the last row too and the first-child rule need to override the last-child one. If not you will have an offset of the row 30 px from the top margin which I suppose you don't want to.

A known problem of position: sticky is that it doesn't work on thead elements or table rows: you must target th elements. Hopping this issue will be solved on future browser versions.

How to compute the sum and average of elements in an array?

I would recommend D3 in this case. It is the most readable (and provides 2 different kinds of averages)

let d3 = require('d3');
let array = [1,2,3,4];
let sum = d3.sum(array); //10
let mean = d3.mean(array); //2.5
let median = d3.median(array); 

How to make google spreadsheet refresh itself every 1 minute?

If you are only looking for a refresh rate for the GOOGLEFINANCE function, keep in mind that data delays can be up to 20 minutes (per Google Finance Disclaimer).

Single-symbol refresh rate (using GoogleClock)

Here is a modified version of the refresh action, taking the data delay into consideration, to save on unproductive refresh cycles.

=GoogleClock(GOOGLEFINANCE(symbol,"datadelay"))

For example, with:

  • SYMBOL: GOOG
  • DATA DELAY: 15 (minutes)

then

=GoogleClock(GOOGLEFINANCE("GOOG","datadelay"))

Results in a dynamic data-based refresh rate of:

=GoogleClock(15)

Multi-symbol refresh rate (using GoogleClock)

If your sheet contains a number of rows of symbols, you could add a datadelay column for each symbol and use the lowest value, for example:

=GoogleClock(MIN(dataDelayValuesNamedRange))

Where dataDelayValuesNamedRange is the absolute reference or named reference of the range of cells that contain the data delay values for each symbol (assuming these values are different).

Without GoogleClock()

The GoogleClock() function was removed in 2014 and replaced with settings setup for refreshing sheets. At present, I have confirmed that replacement settings is only on available in Sheets from when accessed from a desktop browser, not the mobile app (I'm using Google's mobile Sheets app updated 2016-03-14).

(This part of the answer is based on, and portions copied from, Google Docs Help)

To change how often "some" Google Sheets functions update:

  1. Open a spreadsheet. Click File > Spreadsheet settings.
  2. In the RECALCULATION section, choose a setting from the drop-down menu.
  3. Setting options are:
    • On change
    • On change and every minute
    • On change and every hour
  4. Click SAVE SETTINGS.

NOTE External data functions recalculate at the following intervals:

  • ImportRange: 30 minutes
  • ImportHtml, ImportFeed, ImportData, ImportXml: 1 hour
  • GoogleFinance: 2 minutes

The references in earlier sections to the display and use of the datadelay attribute still apply, as well as the concepts for more efficient coding of sheets.

On a positive note, the new refresh option continues to be refreshed by Google servers regardless of whether you have the sheet loaded or not. That's a positive for shared sheets for sure; even more so for Google Apps Scripts (GAS), where GAS is used in workflow code or referenced data is used as a trigger for an event.

[*] in my understanding so far (I am currently testing this)

What does elementFormDefault do in XSD?

New, detailed answer and explanation to an old, frequently asked question...

Short answer: If you don't add elementFormDefault="qualified" to xsd:schema, then the default unqualified value means that locally declared elements are in no namespace.

There's a lot of confusion regarding what elementFormDefault does, but this can be quickly clarified with a short example...

Streamlined version of your XSD:

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
        xmlns:target="http://www.levijackson.net/web340/ns"
        targetNamespace="http://www.levijackson.net/web340/ns">
  <element name="assignments">
    <complexType>
      <sequence>
        <element name="assignment" type="target:assignmentInfo" 
                 minOccurs="1" maxOccurs="unbounded"/>
      </sequence>
    </complexType>
  </element>
  <complexType name="assignmentInfo">
    <sequence>
      <element name="name" type="string"/>
    </sequence>
    <attribute name="id" type="string" use="required"/>
  </complexType>
</schema>

Key points:

  • The assignment element is locally defined.
  • Elements locally defined in XSD are in no namespace by default.
    • This is because the default value for elementFormDefault is unqualified.
    • This arguably is a design mistake by the creators of XSD.
    • Standard practice is to always use elementFormDefault="qualified" so that assignment is in the target namespace as one would expect.
  • It is a rarely used form attribute on xs:element declarations for which elementFormDefault establishes default values.

Seemingly Valid XML

This XML looks like it should be valid according to the above XSD:

<assignments xmlns="http://www.levijackson.net/web340/ns"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.levijackson.net/web340/ns try.xsd">
  <assignment id="a1">
    <name>John</name>
  </assignment>
</assignments>

Notice:

  • The default namespace on assignments places assignments and all of its descendents in the default namespace (http://www.levijackson.net/web340/ns).

Perplexing Validation Error

Despite looking valid, the above XML yields the following confusing validation error:

[Error] try.xml:4:23: cvc-complex-type.2.4.a: Invalid content was found starting with element 'assignment'. One of '{assignment}' is expected.

Notes:

  • You would not be the first developer to curse this diagnostic that seems to say that the content is invalid because it expected to find an assignment element but it actually found an assignment element. (WTF)
  • What this really means: The { and } around assignment means that validation was expecting assignment in no namespace here. Unfortunately, when it says that it found an assignment element, it doesn't mention that it found it in a default namespace which differs from no namespace.

Solution

  • Vast majority of the time: Add elementFormDefault="qualified" to the xsd:schema element of the XSD. This means valid XML must place elements in the target namespace when locally declared in the XSD; otherwise, valid XML must place locally declared elements in no namespace.
  • Tiny minority of the time: Change the XML to comply with the XSD's requirement that assignment be in no namespace. This can be achieved, for example, by adding xmlns="" to the assignment element.

Credits: Thanks to Michael Kay for helpful feedback on this answer.

How to randomize Excel rows

Here's a macro that allows you to shuffle selected cells in a column:

Option Explicit

Sub ShuffleSelectedCells()
  'Do nothing if selecting only one cell
  If Selection.Cells.Count = 1 Then Exit Sub
  'Save selected cells to array
  Dim CellData() As Variant
  CellData = Selection.Value
  'Shuffle the array
  ShuffleArrayInPlace CellData
  'Output array to spreadsheet
  Selection.Value = CellData
End Sub

Sub ShuffleArrayInPlace(InArray() As Variant)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' ShuffleArrayInPlace
' This shuffles InArray to random order, randomized in place.
' Source: http://www.cpearson.com/excel/ShuffleArray.aspx
' Modified by Tom Doan to work with Selection.Value two-dimensional arrays.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
  Dim J As Long, _
    N As Long, _
    Temp As Variant
  'Randomize
  For N = LBound(InArray) To UBound(InArray)
    J = CLng(((UBound(InArray) - N) * Rnd) + N)
    If J <> N Then
      Temp = InArray(N, 1)
      InArray(N, 1) = InArray(J, 1)
      InArray(J, 1) = Temp
    End If
  Next N
End Sub

You can read the comments to see what the macro is doing. Here's how to install the macro:

  1. Open the VBA editor (Alt + F11).
  2. Right-click on "ThisWorkbook" under your currently open spreadsheet (listed in parentheses after "VBAProject") and select Insert / Module.
  3. Paste the code above and save the spreadsheet.

Now you can assign the "ShuffleSelectedCells" macro to an icon or hotkey to quickly randomize your selected rows (keep in mind that you can only select one column of rows).

Position a div container on the right side

if you don't want to use float

<div style="text-align:right; margin:0px auto 0px auto;">
<p> Hello </p>
</div>
  <div style="">
<p> Hello </p>
</div>

jquery, find next element by class

Given a first selector: SelectorA, you can find the next match of SelectorB as below:

Example with mouseover to change border-with:

$("SelectorA").on("mouseover", function() {
    var i = $(this).find("SelectorB")[0];
    $(i).css({"border" : "1px"});
    });
}

General use example to change border-with:

var i = $("SelectorA").find("SelectorB")[0];
$(i).css({"border" : "1px"});

SQLSTATE[HY000] [1045] Access denied for user 'username'@'localhost' using CakePHP

Check Following Things

  • Make Sure You Have MySQL Server Running
  • Check connection with default credentials i.e. username : 'root' & password : '' [Blank Password]
  • Try login phpmyadmin with same credentials
  • Try to put 127.0.0.1 instead localhost or your lan IP would do too.
  • Make sure you are running MySql on 3306 and if you have configured make sure to state it while making a connection

Best Way to View Generated Source of Webpage?

In Firefox, just ctrl-a (select everything on the screen) then right click "View Selection Source". This captures any changes made by JavaScript to the DOM.

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

There isn't a field initialization syntax like that for objects in JavaScript or TypeScript.

Option 1:

class bar {
    // Makes a public field called 'length'
    constructor(public length: number) { }
}

bars = [ new bar(1) ];

Option 2:

interface bar {
    length: number;
}

bars = [ {length: 1} ];

rejected master -> master (non-fast-forward)

use this command:

git pull --allow-unrelated-histories <nick name of repository> <branch name>

like:

git pull --allow-unrelated-histories origin master

this error occurs when projects don't have any common ancestor.

catching stdout in realtime from subprocess

for line in p.stdout:
  ...

always blocks until the next line-feed.

For "real-time" behaviour you have to do something like this:

while True:
  inchar = p.stdout.read(1)
  if inchar: #neither empty string nor None
    print(str(inchar), end='') #or end=None to flush immediately
  else:
    print('') #flush for implicit line-buffering
    break

The while-loop is left when the child process closes its stdout or exits. read()/read(-1) would block until the child process closed its stdout or exited.

Make Frequency Histogram for Factor Variables

If you'd like to do this in ggplot, an API change was made to geom_histogram() that leads to an error: https://github.com/hadley/ggplot2/issues/1465

To get around this, use geom_bar():

animals <- c("cat", "dog",  "dog", "dog", "dog", "dog", "dog", "dog", "cat", "cat", "bird")

library(ggplot2)
# counts
ggplot(data.frame(animals), aes(x=animals)) +
  geom_bar()

enter image description here

How can I get npm start at a different directory?

This one-liner should work:

npm start --prefix path/to/your/app

Corresponding doc

Start redis-server with config file

To start redis with a config file all you need to do is specifiy the config file as an argument:

redis-server /root/config/redis.rb

Instead of using and killing PID's I would suggest creating an init script for your service

I would suggest taking a look at the Installing Redis more properly section of http://redis.io/topics/quickstart. It will walk you through setting up an init script with redis so you can just do something like service redis_server start and service redis_server stop to control your server.

I am not sure exactly what distro you are using, that article describes instructions for a Debian based distro. If you are are using a RHEL/Fedora distro let me know, I can provide you with instructions for the last couple of steps, the config file and most of the other steps will be the same.

C - casting int to char and append char to char

int myInt = 65;

char myChar = (char)myInt;  // myChar should now be the letter A

char[20] myString = {0}; // make an empty string.

myString[0] = myChar;
myString[1] = myChar; // Now myString is "AA"

This should all be found in any intro to C book, or by some basic online searching.

How to make Java Set?

Like this:

import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);

Or adding from an Array/ or multiple literals; wrap to a list, first.

Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b));         // from an array variable
b.addAll( Arrays.asList( 8, 9, 10));  // from literals

To get the intersection:

// copies all from A;  then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print;   r.toString() implied.
System.out.println("A intersect B="+r);

Hope this answer helps. Vote for it!

How do I select a random value from an enumeration?

Here's an alternative version as an Extension Method using LINQ.

using System;
using System.Linq;

public static class EnumExtensions
{
    public static Enum GetRandomEnumValue(this Type t)
    {
        return Enum.GetValues(t)          // get values from Type provided
            .OfType<Enum>()               // casts to Enum
            .OrderBy(e => Guid.NewGuid()) // mess with order of results
            .FirstOrDefault();            // take first item in result
    }
}

public static class Program
{
    public enum SomeEnum
    {
        One = 1,
        Two = 2,
        Three = 3,
        Four = 4
    }

    public static void Main()
    {
        for(int i=0; i < 10; i++)
        {
            Console.WriteLine(typeof(SomeEnum).GetRandomEnumValue());
        }
    }           
}

Two
One
Four
Four
Four
Three
Two
Four
One
Three

iPhone SDK:How do you play video inside a view? Rather than fullscreen

Looking at your code, you need to set the frame of the movie player controller's view, and also add the movie player controller's view to your view. Also, don't forget to add MediaPlayer.framework to your target.

Here's some sample code:

#import <MediaPlayer/MediaPlayer.h>

@interface ViewController () {
    MPMoviePlayerController *moviePlayerController;
}

@property (weak, nonatomic) IBOutlet UIView *movieView; // this should point to a view where the movie will play

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    // Instantiate a movie player controller and add it to your view
    NSString *moviePath = [[NSBundle mainBundle] pathForResource:@"foo" ofType:@"mov"];
    NSURL *movieURL = [NSURL fileURLWithPath:moviePath];    
    moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
    [moviePlayerController.view setFrame:self.movieView.bounds];  // player's frame must match parent's
    [self.movieView addSubview:moviePlayerController.view];

    // Configure the movie player controller
    moviePlayerController.controlStyle = MPMovieControlStyleNone;        
    [moviePlayerController prepareToPlay];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    // Start the movie
    [moviePlayerController play];
}

@end

Output to the same line overwriting previous output?

Have a look at the curses module documentation and the curses module HOWTO.

Really basic example:

import time
import curses

stdscr = curses.initscr()

stdscr.addstr(0, 0, "Hello")
stdscr.refresh()

time.sleep(1)

stdscr.addstr(0, 0, "World! (with curses)")
stdscr.refresh()

ActiveX component can't create object

Check your browser settings.

For me, using IE, the fix was to go into Tools/Internet Options, Security tab, for the relevant zone, "custom level" and check the ActiveX settings. Setting "Initialize and script ActiveX controls not marked as safe for scripting" to "Enable" fixed this problem for me.

RegEx for valid international mobile phone number

Even if you write a regular expression that matches exactly the subset "valid phone numbers" out of strings, there is no way to guarantee (by way of a regular expression) that they are valid mobile phone numbers. In several countries, mobile phone numbers are indistinguishable from landline phone numbers without at least a number plan lookup, and in some cases, even that won't help. For example, in Sweden, lots of people have "ported" their regular, landline-like phone number to their mobile phone. It's still the same number as they had before, but now it goes to a mobile phone instead of a landline.

Since valid phone numbers consist only of digits, I doubt that rolling your own would risk missing some obscure case of phone number at least. If you want to have better certainty, write a generator that takes a list of all valid country codes, and requires one of them at the beginning of the phone number to be matched by the generated regular expression.

How to use an image for the background in tkinter?

One simple method is to use place to use an image as a background image. This is the type of thing that place is really good at doing.

For example:

background_image=tk.PhotoImage(...)
background_label = tk.Label(parent, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)

You can then grid or pack other widgets in the parent as normal. Just make sure you create the background label first so it has a lower stacking order.

Note: if you are doing this inside a function, make sure you keep a reference to the image, otherwise the image will be destroyed by the garbage collector when the function returns. A common technique is to add a reference as an attribute of the label object:

background_label.image = background_image

'System.OutOfMemoryException' was thrown when there is still plenty of memory free

Convert your solution to x64. If you still face an issue, grant max length to everything that throws an exception like below :

 var jsSerializer = new JavaScriptSerializer();
 jsSerializer.MaxJsonLength = Int32.MaxValue;

how to set length of an column in hibernate with maximum length

You need to alter your table. Increase the column width using a DDL statement.

please see here

http://dba-oracle.com/t_alter_table_modify_column_syntax_example.htm

error: pathspec 'test-branch' did not match any file(s) known to git

This error can also appear if your git branch is not correct even though case sensitive wise. In my case I was getting this error as actual branch name was "CORE-something" but I was taking pull like "core-something".

Extract parameter value from url using regular expressions

Not tested but this should work:

/\?v=([a-z0-9\-]+)\&?/i

Convert a String to a byte array and then back to the original String

I would suggest using the members of string, but with an explicit encoding:

byte[] bytes = text.getBytes("UTF-8");
String text = new String(bytes, "UTF-8");

By using an explicit encoding (and one which supports all of Unicode) you avoid the problems of just calling text.getBytes() etc:

  • You're explicitly using a specific encoding, so you know which encoding to use later, rather than relying on the platform default.
  • You know it will support all of Unicode (as opposed to, say, ISO-Latin-1).

EDIT: Even though UTF-8 is the default encoding on Android, I'd definitely be explicit about this. For example, this question only says "in Java or Android" - so it's entirely possible that the code will end up being used on other platforms.

Basically given that the normal Java platform can have different default encodings, I think it's best to be absolutely explicit. I've seen way too many people using the default encoding and losing data to take that risk.

EDIT: In my haste I forgot to mention that you don't have to use the encoding's name - you can use a Charset instead. Using Guava I'd really use:

byte[] bytes = text.getBytes(Charsets.UTF_8);
String text = new String(bytes, Charsets.UTF_8);

Where are Magento's log files located?

You can find them in /var/log within your root Magento installation

There will usually be two files by default, exception.log and system.log.

If the directories or files don't exist, create them and give them the correct permissions, then enable logging within Magento by going to System > Configuration > Developer > Log Settings > Enabled = Yes

How to pick just one item from a generator?

I believe the only way is to get a list from the iterator then get the element you want from that list.

l = list(myfunct())
l[4]

Oracle: SQL query to find all the triggers belonging to the tables?

The following will work independent of your database privileges:

select * from all_triggers
where table_name = 'YOUR_TABLE'

The following alternate options may or may not work depending on your assigned database privileges:

select * from DBA_TRIGGERS

or

select * from USER_TRIGGERS

How can I turn a string into a list in Python?

The list() function [docs] will convert a string into a list of single-character strings.

>>> list('hello')
['h', 'e', 'l', 'l', 'o']

Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:

>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'

You can also loop over the characters in the string as you can loop over the elements of a list:

>>> for c in 'hello':
...     print c + c,
... 
hh ee ll ll oo

How to clear an ImageView in Android?

For ListView item image you can set ImageView.setVisibility(View.INVISIBLE) or ImageView.setImageBitmap(null) in list adapter for "no image" case.

How to edit HTML input value colour?

Add a style = color:black !important; in your input type.

How to enable Auto Logon User Authentication for Google Chrome

If you add your site to "Local Intranet" in

Chrome > Options > Under the Hood > Change Proxy Settings > Security (tab) > Local Intranet/Sites > Advanced.

Add you site URL here and it will work.

Update for New Version of Chrome

Chrome > Settings > Advanced > System > Open Proxy Settings > Security (tab) > Local Intranet > Sites (button) > Advanced.

How to enable CORS in apache tomcat

CORS support in Tomcat is provided via a filter. You need to add this filter to your web.xml file and configure it to match your requirements. Full details on the configuration options available can be found in the Tomcat Documentation.

Difference between sh and bash

This question has frequently been nominated as a canonical for people who try to use sh and are surprised that it's not behaving the same as bash. Here's a quick rundown of common misunderstandings and pitfalls.

First off, you should understand what to expect.

  • If you run your script with sh scriptname, or run it with scriptname and have #!/bin/sh in the shebang line, you should expect POSIX sh behavior.
  • If you run your script with bash scriptname, or run it with scriptname and have #!/bin/bash (or the local equivalent) in the shebang line, you should expect Bash behavior.

Having a correct shebang and running the script by typing just the script name (possibly with a relative or full path) is generally the preferred solution. In addition to a correct shebang, this requires the script file to have execute permission (chmod a+x scriptname).

So, how do they actually differ?

The Bash Reference manual has a section which attempts to enumerate the differences but some common sources of confusion include

  • [[ is not available in sh (only [ which is more clunky and limited). See also Difference between single and double square brackets in Bash
  • sh does not have arrays.
  • Some Bash keywords like local, source, function, shopt, let, declare, and select are not portable to sh. (Some sh implementations support e.g. local.)
  • Bash has many C-style syntax extensions like the three-argument for((i=0;i<=3;i++)) loop, += increment assignment, etc. The $'string\nwith\tC\aescapes' feature is tentatively accepted for POSIX (meaning it works in Bash now, but will not yet be supported by sh on systems which only adhere to the current POSIX specification, and likely will not for some time to come).
  • Bash supports <<<'here strings'.
  • Bash has *.{png,jpg} and {0..12} brace expansion.
  • ~ refers to $HOME only in Bash (and more generally ~username to the home directory of username).This is in POSIX, but may be missing from some pre-POSIX /bin/sh implementations.
  • Bash has process substitution with <(cmd) and >(cmd).
  • Bash has Csh-style convenience redirection aliases like &| for 2>&1 | and &> for > ... 2>&1
  • Bash supports coprocesses with <> redirection.
  • Bash features a rich set of expanded non-standard parameter expansions such as ${substring:1:2}, ${variable/pattern/replacement}, case conversion, etc.
  • Bash has significantly extended facilities for shell arithmetic (though still no floating-point support). There is an obsolescent legacy $[expression] syntax which however should be replaced with POSIX arithmetic $((expression)) syntax. (Some legacy pre-POSIX sh implementations may not support that, though.)
  • Several built-in commands have options which are not portable, like type -a, printf -v, and the perennial echo -e.
  • Magic variables like $RANDOM, $SECONDS, $PIPESTATUS[@] and $FUNCNAME are Bash extensions.
  • Syntactic differences like export variable=value and [ "x" == "y" ] which are not portable (export variable should be separate from variable assignment, and portable string comparison in [ ... ] uses a single equals sign).
  • Many, many Bash-only extensions to enable or disable optional behavior and expose internal state of the shell.
  • Many, many convenience features for interactive use which however do not affect script behavior.

Remember, this is an abridged listing. Refer to the reference manual for the full scoop, and http://mywiki.wooledge.org/Bashism for many good workarounds; and/or try http://shellcheck.net/ which warns for many Bash-only features.

A common error is to have a #!/bin/bash shebang line, but then nevertheless using sh scriptname to actually run the script. This basically disables any Bash-only functionality, so you get syntax errors e.g. for trying to use arrays. (The shebang line is syntactically a comment, so it is simply ignored in this scenario.)

Unfortunately, Bash will not warn when you try to use these constructs when it is invoked as sh. It doesn't completely disable all Bash-only functionality, either, so running Bash by invoking it as sh is not a good way to check if your script is properly portable to ash/dash/POSIX sh or variants like Heirloom sh

Deprecated: mysql_connect()

<?php 
$link = mysqli_connect('localhost','root',''); 
if (!$link) { 
    die('Could not connect to MySQL: ' . mysqli_error()); 
} 
echo 'Connection OK'; mysqli_close($link); 
?>

This will solve your problem.

Determining if Swift dictionary contains key and obtaining any of its values

You don't need any special code to do this, because it is what a dictionary already does. When you fetch dict[key] you know whether the dictionary contains the key, because the Optional that you get back is not nil (and it contains the value).

So, if you just want to answer the question whether the dictionary contains the key, ask:

let keyExists = dict[key] != nil

If you want the value and you know the dictionary contains the key, say:

let val = dict[key]!

But if, as usually happens, you don't know it contains the key - you want to fetch it and use it, but only if it exists - then use something like if let:

if let val = dict[key] {
    // now val is not nil and the Optional has been unwrapped, so use it
}

How to configure encoding in Maven?

This would be in addition to previous, if someone meets a problem with scandic letters that isn't solved with the solution above.

If the java source files contain scandic letters they need to be interpreted correctly by the Java used for compiling. (e.g. scandic letters used in constants)

Even that the files are stored in UTF-8 and the Maven is configured to use UTF-8, the System Java used by the Maven will still use the system default (eg. in Windows: cp1252).

This will be visible only running the tests via maven (possibly printing the values of these constants in tests. The printed scandic letters would show as '< ?>') If not tested properly, this would corrupt the class files as compile result and be left unnoticed.

To prevent this, you have to set the Java used for compiling to use UTF-8 encoding. It is not enough to have the encoding settings in the maven pom.xml, you need to set the environment variable: JAVA_TOOL_OPTIONS = -Dfile.encoding=UTF8

Also, if using Eclipse in Windows, you may need to set the encoding used in addition to this (if you run individual test via eclipse).

for or while loop to do something n times

but on the other hand it creates a completely useless list of integers just to loop over them. Isn't it a waste of memory, especially as far as big numbers of iterations are concerned?

That is what xrange(n) is for. It avoids creating a list of numbers, and instead just provides an iterator object.

In Python 3, xrange() was renamed to range() - if you want a list, you have to specifically request it via list(range(n)).

How can I force division to be floating point? Division keeps rounding down to 0?

If you want to use "true" (floating point) division by default, there is a command line flag:

python -Q new foo.py

There are some drawbacks (from the PEP):

It has been argued that a command line option to change the default is evil. It can certainly be dangerous in the wrong hands: for example, it would be impossible to combine a 3rd party library package that requires -Qnew with another one that requires -Qold.

You can learn more about the other flags values that change / warn-about the behavior of division by looking at the python man page.

For full details on division changes read: PEP 238 -- Changing the Division Operator

Java, Check if integer is multiple of a number

Use the remainder operator (also known as the modulo operator) which returns the remainder of the division and check if it is zero:

if (j % 4 == 0) {
     // j is an exact multiple of 4
}

403 Access Denied on Tomcat 8 Manager App without prompting for user/password

<role rolename="tomcat"/>
  <role rolename="manager-gui"/>
  <role rolename="admin-gui"/>
  <role rolename="manager-script"/>
  <role rolename="manager-jmx"/>
  <user username="admin" password="admin" roles="tomcat,manager-gui,admin-gui,manager-script,manager-jmx"/>


Close all the session, once closed, ensure open the URL in incognito mode login again and it should start working

Unable to capture screenshot. Prevented by security policy. Galaxy S6. Android 6.0

You must have either disabled, froze or uninstalled FaceProvider in settings>applications>all
This will only happen if it's frozen, either uninstall it, or enable it.

How to increase MySQL connections(max_connections)?

From Increase MySQL connection limit:-

MySQL’s default configuration sets the maximum simultaneous connections to 100. If you need to increase it, you can do it fairly easily:

For MySQL 3.x:

# vi /etc/my.cnf
set-variable = max_connections = 250

For MySQL 4.x and 5.x:

# vi /etc/my.cnf
max_connections = 250

Restart MySQL once you’ve made the changes and verify with:

echo "show variables like 'max_connections';" | mysql

EDIT:-(From comments)

The maximum concurrent connection can be maximum range: 4,294,967,295. Check MYSQL docs

How can I enable auto complete support in Notepad++?

Open Notepad++ and Settings -> Preferences -> Auto-Completion -> Check the Auto-insert options you want. this link will help alot: http://docs.notepad-plus-plus.org/index.php/Auto_Completion

Parsing JSON in Excel VBA

Simpler way you can go array.myitem(0) in VB code

my full answer here parse and stringify (serialize)

Use the 'this' object in js

ScriptEngine.AddCode "Object.prototype.myitem=function( i ) { return this[i] } ; "

Then you can go array.myitem(0)

Private ScriptEngine As ScriptControl

Public Sub InitScriptEngine()
    Set ScriptEngine = New ScriptControl
    ScriptEngine.Language = "JScript"
    ScriptEngine.AddCode "Object.prototype.myitem=function( i ) { return this[i] } ; "
    Set foo = ScriptEngine.Eval("(" + "[ 1234, 2345 ]" + ")") ' JSON array
    Debug.Print foo.myitem(1) ' method case sensitive!
    Set foo = ScriptEngine.Eval("(" + "{ ""key1"":23 , ""key2"":2345 }" + ")") ' JSON key value
    Debug.Print foo.myitem("key1") ' WTF

End Sub

What’s the best way to reload / refresh an iframe?

<script type="text/javascript">
  top.frames['DetailFrame'].location = top.frames['DetailFrame'].location;
</script> 

How to find index position of an element in a list when contains returns true

int indexOf() can be used. It returns -1 if no matching finds

Cannot find libcrypto in Ubuntu

ld is trying to find libcrypto.sowhich is not present as seen in your locate output. You can make a copy of the libcrypto.so.0.9.8 and name it as libcrypto.so. Put this is your ld path. ( If you do not have root access then you can put it in a local path and specify the path manually )

matplotlib: plot multiple columns of pandas data frame on the bar chart

You can plot several columns at once by supplying a list of column names to the plot's y argument.

df.plot(x="X", y=["A", "B", "C"], kind="bar")

enter image description here

This will produce a graph where bars are sitting next to each other.

In order to have them overlapping, you would need to call plot several times, and supplying the axes to plot to as an argument ax to the plot.

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

y = np.random.rand(10,4)
y[:,0]= np.arange(10)
df = pd.DataFrame(y, columns=["X", "A", "B", "C"])

ax = df.plot(x="X", y="A", kind="bar")
df.plot(x="X", y="B", kind="bar", ax=ax, color="C2")
df.plot(x="X", y="C", kind="bar", ax=ax, color="C3")

plt.show()

enter image description here

How to get screen width without (minus) scrollbar?

I experienced a similar problem and doing width:100%; solved it for me. I came to this solution after trying an answer in this question and realizing that the very nature of an <iframe> will make these javascript measurement tools inaccurate without using some complex function. Doing 100% is a simple way to take care of it in an iframe. I don't know about your issue since I'm not sure of what HTML elements you are manipulating.

How the single threaded non blocking IO model works in Node.js

Node.js is built upon libuv, a cross-platform library that abstracts apis/syscalls for asynchronous (non-blocking) input/output provided by the supported OSes (Unix, OS X and Windows at least).

Asynchronous IO

In this programming model open/read/write operation on devices and resources (sockets, filesystem, etc.) managed by the file-system don't block the calling thread (as in the typical synchronous c-like model) and just mark the process (in kernel/OS level data structure) to be notified when new data or events are available. In case of a web-server-like app, the process is then responsible to figure out which request/context the notified event belongs to and proceed processing the request from there. Note that this will necessarily mean you'll be on a different stack frame from the one that originated the request to the OS as the latter had to yield to a process' dispatcher in order for a single threaded process to handle new events.

The problem with the model I described is that it's not familiar and hard to reason about for the programmer as it's non-sequential in nature. "You need to make request in function A and handle the result in a different function where your locals from A are usually not available."

Node's model (Continuation Passing Style and Event Loop)

Node tackles the problem leveraging javascript's language features to make this model a little more synchronous-looking by inducing the programmer to employ a certain programming style. Every function that requests IO has a signature like function (... parameters ..., callback) and needs to be given a callback that will be invoked when the requested operation is completed (keep in mind that most of the time is spent waiting for the OS to signal the completion - time that can be spent doing other work). Javascript's support for closures allows you to use variables you've defined in the outer (calling) function inside the body of the callback - this allows to keep state between different functions that will be invoked by the node runtime independently. See also Continuation Passing Style.

Moreover, after invoking a function spawning an IO operation the calling function will usually return control to node's event loop. This loop will invoke the next callback or function that was scheduled for execution (most likely because the corresponding event was notified by the OS) - this allows the concurrent processing of multiple requests.

You can think of node's event loop as somewhat similar to the kernel's dispatcher: the kernel would schedule for execution a blocked thread once its pending IO is completed while node will schedule a callback when the corresponding event has occured.

Highly concurrent, no parallelism

As a final remark, the phrase "everything runs in parallel except your code" does a decent job of capturing the point that node allows your code to handle requests from hundreds of thousands open socket with a single thread concurrently by multiplexing and sequencing all your js logic in a single stream of execution (even though saying "everything runs in parallel" is probably not correct here - see Concurrency vs Parallelism - What is the difference?). This works pretty well for webapp servers as most of the time is actually spent on waiting for network or disk (database / sockets) and the logic is not really CPU intensive - that is to say: this works well for IO-bound workloads.

Get today date in google appScript

The following can be used to get the date:

function date_date() {
var date = new Date();
var year = date.getYear();
var month = date.getMonth() + 1;  if(month.toString().length==1){var month = 
'0'+month;}
var day = date.getDate(); if(day.toString().length==1){var day = '0'+day;}
var hour = date.getHours(); if(hour.toString().length==1){var hour = '0'+hour;}
var minu = date.getMinutes(); if(minu.toString().length==1){var minu = '0'+minu;}
var seco = date.getSeconds(); if(seco.toString().length==1){var seco = '0'+seco;}
var date = year+'·'+month+'·'+day+'·'+hour+'·'+minu+'·'+seco;
Logger.log(date);
}

How to print out more than 20 items (documents) in MongoDB's shell?

In the mongo shell, if the returned cursor is not assigned to a variable using the var keyword, the cursor is automatically iterated to access up to the first 20 documents that match the query. You can set the DBQuery.shellBatchSize variable to change the number of automatically iterated documents.

Reference - https://docs.mongodb.com/v3.2/reference/method/db.collection.find/

equivalent of rm and mv in windows .cmd

move in windows is equivalent of mv command in Linux

del in windows is equivalent of rm command in Linux

Facebook Like-Button - hide count?

I know many solutions have been posted already, but mine is still somewhat different. It works for the HTML5 Version of the like button and only uses css to hide the count box. Don't forget to add the appId to test.

CSS:

<style type="text/css">
    .fb-like span {
        display: block;
        height: 22px;
        overflow: hidden;
        position: relative;
        width: 140px /* set this to fit your needs when support international sites */;
    }

    .fb-like iframe {
        height: 62px;
        overflow: hidden;
        position: absolute;
        top: -41px;
        width: 55px;
    }
</style>

FB Like Button:

<div id="fb-root"></div>
<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=xxxxxxxxxxxx";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

<div class="fb-like" data-send="true" data-layout="box_count" data-width="450" data-show-faces="false"></div>

How to reduce the image file size using PIL

A built-in parameter for saving JPEGs and PNGs is optimize.

 >>> from PIL import Image
 # My image is a 200x374 jpeg that is 102kb large
 >>> foo = Image.open("path\\to\\image.jpg")
 >>> foo.size
  (200,374)
 # I downsize the image with an ANTIALIAS filter (gives the highest quality)
 >>> foo = foo.resize((160,300),Image.ANTIALIAS)
 >>> foo.save("path\\to\\save\\image_scaled.jpg",quality=95)
 # The saved downsized image size is 24.8kb
 >>> foo.save("path\\to\\save\\image_scaled_opt.jpg",optimize=True,quality=95)
 # The saved downsized image size is 22.9kb

The optimize flag will do an extra pass on the image to find a way to reduce its size as much as possible. 1.9kb might not seem like much, but over hundreds/thousands of pictures, it can add up.

Now to try and get it down to 5kb to 10 kb, you can change the quality value in the save options. Using a quality of 85 instead of 95 in this case would yield: Unoptimized: 15.1kb Optimized : 14.3kb Using a quality of 75 (default if argument is left out) would yield: Unoptimized: 11.8kb Optimized : 11.2kb

I prefer quality 85 with optimize because the quality isn't affected much, and the file size is much smaller.

How to get the row number from a datatable?

You do know that DataRow is the row of a DataTable correct?

What you currently have already loop through each row. You just have to keep track of how many rows there are in order to get the current row.

int i = 0;
int index = 0;
foreach (DataRow row in dt.Rows) 
{
index = i;
// do stuff
i++;
} 

Logging levels - Logback - rule-of-thumb to assign log levels

My approach, i think coming more from an development than an operations point of view, is:

  • Error means that the execution of some task could not be completed; an email couldn't be sent, a page couldn't be rendered, some data couldn't be stored to a database, something like that. Something has definitively gone wrong.
  • Warning means that something unexpected happened, but that execution can continue, perhaps in a degraded mode; a configuration file was missing but defaults were used, a price was calculated as negative, so it was clamped to zero, etc. Something is not right, but it hasn't gone properly wrong yet - warnings are often a sign that there will be an error very soon.
  • Info means that something normal but significant happened; the system started, the system stopped, the daily inventory update job ran, etc. There shouldn't be a continual torrent of these, otherwise there's just too much to read.
  • Debug means that something normal and insignificant happened; a new user came to the site, a page was rendered, an order was taken, a price was updated. This is the stuff excluded from info because there would be too much of it.
  • Trace is something i have never actually used.

"You tried to execute a query that does not include the specified aggregate function"

GROUP BY can be selected from Total row in query design view in MS Access.
If Total row not shown in design view (as in my case). You can go to SQL View and add GROUP By fname etc. Then Total row will automatically show in design view.
You have to select as Expression in this row for calculated fields.

How to use BeginInvoke C#

Action is a Type of Delegate provided by the .NET framework. The Action points to a method with no parameters and does not return a value.

() => is lambda expression syntax. Lambda expressions are not of Type Delegate. Invoke requires Delegate so Action can be used to wrap the lambda expression and provide the expected Type to Invoke()

Invoke causes said Action to execute on the thread that created the Control's window handle. Changing threads is often necessary to avoid Exceptions. For example, if one tries to set the Rtf property on a RichTextBox when an Invoke is necessary, without first calling Invoke, then a Cross-thread operation not valid exception will be thrown. Check Control.InvokeRequired before calling Invoke.

BeginInvoke is the Asynchronous version of Invoke. Asynchronous means the thread will not block the caller as opposed to a synchronous call which is blocking.

How does `scp` differ from `rsync`?

There's a distinction to me that scp is always encrypted with ssh (secure shell), while rsync isn't necessarily encrypted. More specifically, rsync doesn't perform any encryption by itself; it's still capable of using other mechanisms (ssh for example) to perform encryption.

In addition to security, encryption also has a major impact on your transfer speed, as well as the CPU overhead. (My experience is that rsync can be significantly faster than scp.)

Check out this post for when rsync has encryption on.

How to add a footer in ListView?

I know this is a very old question, but I googled my way here and found the answer provided not 100% satisfying, because as gcl1 mentioned - this way the footer is not really a footer to the screen - it's just an "add-on" to the list.

Bottom line - for others who may google their way here - I found the following suggestion here: Fixed and always visible footer below ListFragment

Try doing as follows, where the emphasis is on the button (or any footer element) listed first in the XML - and then the list is added as "layout_above":

<RelativeLayout>

<Button android:id="@+id/footer" android:layout_alignParentBottom="true"/> 
<ListView android:id="@android:id/list" **android:layout_above**="@id/footer"> <!-- the list -->

</RelativeLayout>