Programs & Examples On #Squirrel sql

SQuirreL SQL Client is a graphical Java program that will allow you to view the structure of a JDBC compliant database, browse the data in tables, issue SQL commands etc.

jQuery AJAX cross domain

There are few examples for using JSONP which include error handling.

However, please note that the error-event is not triggered when using JSONP! See: http://api.jquery.com/jQuery.ajax/ or jQuery ajax request using jsonp error

How to find the default JMX port number?

Now I need to connect that application from my local computer, but I don't know the JMX port number of the remote computer. Where can I find it? Or, must I restart that application with some VM parameters to specify the port number?

By default JMX does not publish on a port unless you specify the arguments from this page: How to activate JMX...

-Dcom.sun.management.jmxremote # no longer required for JDK6
-Dcom.sun.management.jmxremote.port=9010
-Dcom.sun.management.jmxremote.local.only=false # careful with security implications
-Dcom.sun.management.jmxremote.authenticate=false # careful with security implications

If you are running you should be able to access any of those system properties to see if they have been set:

if (System.getProperty("com.sun.management.jmxremote") == null) {
    System.out.println("JMX remote is disabled");
} else [
    String portString = System.getProperty("com.sun.management.jmxremote.port");
    if (portString != null) {
        System.out.println("JMX running on port "
            + Integer.parseInt(portString));
    }
}

Depending on how the server is connected, you might also have to specify the following parameter. As part of the initial JMX connection, jconsole connects up to the RMI port to determine which port the JMX server is running on. When you initially start up a JMX enabled application, it looks its own hostname to determine what address to return in that initial RMI transaction. If your hostname is not in /etc/hosts or if it is set to an incorrect interface address then you can override it with the following:

-Djava.rmi.server.hostname=<IP address>

As an aside, my SimpleJMX package allows you to define both the JMX server and the RMI port or set them both to the same port. The above port defined with com.sun.management.jmxremote.port is actually the RMI port. This tells the client what port the JMX server is running on.

Shortcut to Apply a Formula to an Entire Column in Excel

Try double-clicking on the bottom right hand corner of the cell (ie on the box that you would otherwise drag).

Get Folder Size from Windows Command Line

I got du.exe with my git distribution. Another place might be aforementioned Microsoft or Unxutils.

Once you got du.exe in your path. Here's your fileSizes.bat :-)

@echo ___________
@echo DIRECTORIES
@for /D %%i in (*) do @CALL du.exe -hs "%%i"
@echo _____
@echo FILES
@for %%i in (*) do @CALL du.exe -hs "%%i"
@echo _____
@echo TOTAL
@du.exe -sh "%CD%"

?

___________
DIRECTORIES
37M     Alps-images
12M     testfolder
_____
FILES
765K    Dobbiaco.jpg
1.0K    testfile.txt
_____
TOTAL
58M    D:\pictures\sample

How can I remove a key and its value from an associative array?

Consider this array:

$arr = array("key1" => "value1", "key2" => "value2", "key3" => "value3", "key4" => "value4");
  • To remove an element using the array key:

    // To unset an element from array using Key:
    unset($arr["key2"]);
    var_dump($arr);
    // output: array(3) { ["key1"]=> string(6) "value1" ["key3"]=> string(6) "value3" ["key4"]=> string(6) "value4" }
    
  • To remove element by value:

    // remove an element by value:
    $arr = array_diff($arr, ["value1"]);
    var_dump($arr);
    // output: array(2) { ["key3"]=> string(6) "value3" ["key4"]=> string(6) "value4" } 
    

read more about array_diff: http://php.net/manual/en/function.array-diff.php

  • To remove an element by using index:

    array_splice($arr, 1, 1);
    var_dump($arr);
    // array(1) { ["key3"]=> string(6) "value3" } 
    

read more about array_splice: http://php.net/manual/en/function.array-splice.php

Daemon Threads Explanation

Let's say you're making some kind of dashboard widget. As part of this, you want it to display the unread message count in your email box. So you make a little thread that will:

  1. Connect to the mail server and ask how many unread messages you have.
  2. Signal the GUI with the updated count.
  3. Sleep for a little while.

When your widget starts up, it would create this thread, designate it a daemon, and start it. Because it's a daemon, you don't have to think about it; when your widget exits, the thread will stop automatically.

Get Android shared preferences value in activity/normal class

This is the procedure that seems simplest to me:

SharedPreferences sp = getSharedPreferences("MySharedPrefs", MODE_PRIVATE);
SharedPreferences.Editor e = sp.edit();

    if (sp.getString("sharedString", null).equals("true")
            || sp.getString("sharedString", null) == null) {
        e.putString("sharedString", "false").commit();
        // Do something
    } else {
        // Do something else
    }

JQuery - Set Attribute value

$("#chk0") is refering to an element with the id chk0. You might try adding id's to the elements. Ids are unique even though the names are the same so that in jQuery you can access a single element by it's id.

What does the "map" method do in Ruby?

It "maps" a function to each item in an Enumerable - in this case, a range. So it would call the block passed once for every integer from 0 to param_count (exclusive - you're right about the dots) and return an array containing each return value.

Here's the documentation for Enumerable#map. It also has an alias, collect.

Why did I get the compile error "Use of unassigned local variable"?

A very dummy mistake, but you can get this with a class too if you didn't instantiate it.

BankAccount account;
account.addMoney(5);

The above will produce the same error whereas:

class BankAccount
{
    int balance = 0;
    public void addMoney(int amount)
    {
        balance += amount;
    }
}

Do the following to eliminate the error:

BankAccount account = new BankAccount();
account.addMoney(5);

Add Class to Object on Page Load

This should work:

window.onload = function() {
  document.getElementById('about').className = 'expand';
};

Or if you're using jQuery:

$(function() {
  $('#about').addClass('expand');
});

target input by type and name (selector)

input[type='checkbox', name='ProductCode']

That's the CSS way and I'm almost sure it will work in jQuery.

Asynchronous vs synchronous execution, what does it really mean?

Simple Explanation via analogy

Synchronous Execution

My boss is a busy man. He tells me to write the code. I tell him: Fine. I get started and he's watching me like a vulture, standing behind me, off my shoulder. I'm like "Dude, WTF: why don't you go and do something while I finish this?"

he's like: "No, I'm waiting right here until you finish." This is synchronous.

Asynchronous Execution

The boss tells me to do it, and rather than waiting right there for my work, the boss goes off and does other tasks. When I finish my job I simply report to my boss and say: "I'm DONE!" This is Asynchronous Execution.

(Take my advice: NEVER work with the boss behind you.)

Installing MySQL in Docker fails with error message "Can't connect to local MySQL server through socket"

Assuming you're using docker-compose, where your docker-compose.yml file looks like:

version: '3.7'
services:
  mysql_db_container:
    image: mysql:latest
    command: --default-authentication-plugin=mysql_native_password
    environment:
      MYSQL_ROOT_PASSWORD: rootpassword
    ports:
      - 3307:3306
    volumes:
      - mysql_db_data_container:/var/lib/mysql


  web:
    image: ${DOCKER_IMAGE_NAME-eis}:latest
    build:
      context: .
    links:
      - mysql_db_container
    ports:
      - 4000:3000
    command: ["./scripts/wait-for-it.sh", "mysql_db_container:3306", "--", "./scripts/start_web_server.sh"]
    volumes:
      - .:/opt/eis:cached
    env_file:
      - .env

volumes:
  mysql_db_data_container:

Notice the ports definition for mysql_db_container

    ports:
      - 3307:3306

<= That indicates that mysql will be accessible via port 3307 to the localhost workstation and via port 3306 within the docker net

Run the following to see your container names:

$ dc config --services
mysql_db_container
web

In this case, we have two containers.

Errors

If you connect to mysql_db_container from your localhost workstation and try to access the mysql console there, you'll get that error:

docker-compose run mysql_db_container bash
root@8880ffe47962:/# mysql -u root -p
Enter password: 
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
root@8880ffe47962:/# exit

Also, if you try to connect from your local workstation, you'll also get that error:

$ mysql -u root -p -P 3307
Enter password: 
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

Solutions

Connecting from local workstation

Just add the --protocol=tcp parameter (otherwise mysql assumes you want to connect via the mysql socket):

$ mysql --protocol=tcp -u root -p -P 3307
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 11
Server version: 8.0.21 MySQL Community Server - GPL

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

Connecting from web container

Reference the docker hostname -h mysql_db_container. Note that when you're running within the context of Docker that the TCP protocol is assumed.

$ dc run web bash
Starting eligibility-service_mysql_db_container_1_d625308b5a77 ... done
root@e7852ff02683:/opt/eis# mysql -h mysql_db_container -u root -p
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MySQL connection id is 18
Server version: 8.0.21 MySQL Community Server - GPL

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MySQL [(none)]> 

Connecting from mysql container

Assuming your mysql container name is eis_mysql_db_container_1_d625308b5a77 (that you can see when running docker ps), the following should work:

$ docker exec -it eis_mysql_db_container_1_d625308b5a77 bash
root@3738cf6eb3e9:/# mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 19
Server version: 8.0.21 MySQL Community Server - GPL

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 

auto create database in Entity Framework Core

For EF Core 2.0+ I had to take a different approach because they changed the API. As of March 2019 Microsoft recommends you put your database migration code in your application entry class but outside of the WebHost build code.

public class Program
{
    public static void Main(string[] args)
    {
        var host = CreateWebHostBuilder(args).Build();
        using (var serviceScope = host.Services.CreateScope())
        {
            var context = serviceScope.ServiceProvider.GetRequiredService<PersonContext>();
            context.Database.Migrate();
        }
        host.Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

How to include libraries in Visual Studio 2012?

In code level also, you could add your lib to the project using the compiler directives #pragma.

example:

#pragma comment( lib, "yourLibrary.lib" )

Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2:java (default-cli)

To solve this problem in IntelliJ...
1) Put your .fxml files into resources directory
2) In the Start method define the path to .fxml file in the following way:
Parent root = FXMLLoader.load(getClass().getResource("/sample.fxml"));
The / seemed to solve this problem for me :)

Typescript: difference between String and string

In JavaScript strings can be either string primitive type or string objects. The following code shows the distinction:

var a: string = 'test'; // string literal
var b: String = new String('another test'); // string wrapper object

console.log(typeof a); // string
console.log(typeof b); // object

Your error:

Type 'String' is not assignable to type 'string'. 'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible.

Is thrown by the TS compiler because you tried to assign the type string to a string object type (created via new keyword). The compiler is telling you that you should use the type string only for strings primitive types and you can't use this type to describe string object types.

Get file size before uploading

You can use PHP filesize function. During upload using ajax, please check the filesize first by making a request an ajax request to php script that checks the filesize and return the value.

PHP foreach change original array values

Use foreach($fields as &$field){ - so you will work with the original array.

Here is more about passing by reference.

Why is pydot unable to find GraphViz's executables in Windows 8?

The solution is easy, you just need to download and install the Graphviz, from here.

Then set the path variable to the bin directory, in my case it was C:\Program Files (x86)\Graphviz2.38\bin. Last, do the conda install python-graphviz and it should work fine.

Filter Extensions in HTML form upload

The accept attribute expects MIME types, not file masks. For example, to accept PNG images, you'd need accept="image/png". You may need to find out what MIME type the browser considers your file type to be, and use that accordingly. However, since a 'drp' file does not appear standard, you might have to accept a generic MIME type.

Additionally, it appears that most browsers may not honor this attribute.

The better way to filter file uploads is going to be on the server-side. This is inconvenient since the occasional user might waste time uploading a file only to learn they chose the wrong one, but at least you'll have some form of data integrity.

Alternatively you may choose to do a quick check with JavaScript before the form is submitted. Just check the extension of the file field's value to see if it is ".drp". This is probably going to be much more supported than the accept attribute.

What is the difference between java and core java?

Core java is a sun term.It mentions the USE,it means it contains only basics of java and some principles and also contain some packages details.

How to make google spreadsheet refresh itself every 1 minute?

GOOGLEFINANCE can have a 20 minutes delay, so refreshing every minute would not really help.

Instead of GOOGLEFINANCE you can use different source. I'm using this RealTime stock prices(I tried a couple but this is the easiest by-far to implement. They have API that retuen JSON { Name: CurrentPrice }

Here's a little script you can use in Google Sheets(Tools->Script Editor)

function GetStocksPrice() {      
   var url = 'https://financialmodelingprep.com/api/v3/stock/real-time- 
   price/AVP,BAC,CHK,CY,GE,GPRO,HIMX,IMGN,MFG,NIO,NMR,SSSS,UCTT,UMC,ZNGA';
   var response = UrlFetchApp.fetch(url);

   // convert json string to json object
   var jsonSignal = JSON.parse(response);    

  // define an array of all the object keys
  var headerRow = Object.keys(jsonSignal);
  // define an array of all the object values
  var values = headerRow.map(function(key){ return jsonSignal[key]});   
  var data = values[0];

  // get sheet by ID -  
  // you can get the sheet unqiue ID from the your current sheet url
  var jsonSheet = SpreadsheetApp.openById("Your Sheet UniqueID");  
  //var name = jsonSheet.getName();

  var sheet = jsonSheet.getSheetByName('Sheet1'); 

  // the column to put the data in -> Y
  var letter = "F";

  // start from line 
  var index = 4;
  data.forEach(function( row, index2 ) { 

     var keys = Object.keys(row);
     var value2 = row[keys[1]];            

     // set value loction
     var cellXY = letter +  index;      
     sheet.getRange(cellXY).setValue(value2);  
  
     index = index + 1;    
 });  
}

Now you need to add a trigger that will execute every minute.

  1. Go to Project Triggers -> click on the Watch icon next to the Save icon
  2. Add Trigger
  3. In -> Choose which function to run -> GetStocksPrice
  4. In -> Select event source -> Time-driven
  5. In -> Select type of time based trigger -> Minutes timer
  6. In -> Select minute interval -> Every minute

And your set :)

How to set a default value for an existing column

Try following command;

ALTER TABLE Person11
ADD CONSTRAINT col_1_def
DEFAULT 'This is not NULL' FOR Address

I want to add a JSONObject to a JSONArray and that JSONArray included in other JSONObject

JSONArray successObject=new JSONArray();
JSONObject dataObject=new JSONObject();
successObject.put(dataObject.toString());

This works for me.

Get value of a string after last slash in JavaScript

When I know the string is going to be reasonably short then I use the following one liner... (remember to escape backslashes)

// if str is C:\windows\file system\path\picture name.jpg
alert( str.split('\\').pop() );

alert pops up with picture name.jpg

Doctrine and LIKE query

you can also do it like that :

$ver = $em->getRepository('GedDocumentBundle:version')->search($val);

$tail = sizeof($ver);

What does "hard coded" mean?

The antonym of Hard-Coding is Soft-Coding. For a better understanding of Hard Coding, I will introduce both terms.

  • Hard-coding: feature is coded to the system not allowing for configuration;
  • Parametric: feature is configurable via table driven, or properties files with limited parametric values ;
  • Soft-coding: feature uses “engines” that derive results based on any number of parametric values (e.g. business rules in BRE); rules are coded but exist as parameters in system, written in script form

Examples:

// firstName has a hard-coded value of "hello world"
string firstName = "hello world";

// firstName has a non-hard-coded provided as input
Console.WriteLine("first name :");
string firstName = Console.ReadLine();

A hard-coded constant[1]:

float areaOfCircle(int radius)
{
    float area = 0;
    area = 3.14*radius*radius;  //  3.14 is a hard-coded value
    return area;
}

Additionally, hard-coding and soft-coding could be considered to be anti-patterns[2]. Thus, one should strive for balance between hard and soft-coding.

  1. Hard CodingHard coding” is a well-known antipattern against which most web development books warns us right in the preface. Hard coding is the unfortunate practice in which we store configuration or input data, such as a file path or a remote host name, in the source code rather than obtaining it from a configuration file, a database, a user input, or another external source.

    The main problem with hard code is that it only works properly in a certain environment, and at any time the conditions change, we need to modify the source code, usually in multiple separate places.

  2. Soft Coding
    If we try very hard to avoid the pitfall of hard coding, we can easily run into another antipattern called “soft coding”, which is its exact opposite.

    In soft coding, we put things that should be in the source code into external sources, for example we store business logic in the database. The most common reason why we do so, is the fear that business rules will change in the future, therefore we will need to rewrite the code.

    In extreme cases, a soft coded program can become so abstract and convoluted that it is almost impossible to comprehend it (especially for new team members), and extremely hard to maintain and debug.

Sources and Citations:

1: Quora: What does hard-coded something mean in computer programming context?
2: Hongkiat: The 10 Coding Antipatterns You Must Avoid

Further Reading:

Software Engineering SE: Is it ever a good idea to hardcode values into our applications?
Wikipedia: Hardcoding
Wikipedia: Soft-coding

Launch Minecraft from command line - username and password as prefix

For anyone meaning to do this more reliably for different Minecraft versions, I have a Python script (adapted from parts of minecraft-launcher-lib) that does the job very nicely

Besides setting some basic variables near the top after the functions, it calls a get_classpath that goes through for example ~/.minecraft/versions/1.16.5/1.16.5.json, and loops over the libraries array, checking to see if each object (within the array), is supposed to be added to the classpath (cp variable). whether this library is added to the java classpath is governed by the should_use_library function, deterministic based on the computer's architecture and operating system. finally, some jarfiles that are platform specific have extra things prepended to them (ex. natives-linux in org/lwjgl/lwjgl/3.2.1/lwjgl-3.2.1-natives-linux.jar). this extra prepended string is handled by get_natives_string and is empty if it doesn't apply to the current library

tested on Linux, distribution Arch Linux

#!/usr/bin/env python
import json
import os
import platform
from pathlib import Path
import subprocess


"""Debug output
"""
def debug(str):
    if os.getenv('DEBUG') != None:
        print(str)

"""
[Gets the natives_string toprepend to the jar if it exists. If there is nothing native specific, returns and empty string]
"""
def get_natives_string(lib):
    arch = ""
    if platform.architecture()[0] == "64bit":
        arch = "64"
    elif platform.architecture()[0] == "32bit":
        arch = "32"
    else:
        raise Exception("Architecture not supported")

    nativesFile=""
    if not "natives" in lib:
        return nativesFile

    # i've never seen ${arch}, but leave it in just in case
    if "windows" in lib["natives"] and platform.system() == 'Windows':
        nativesFile = lib["natives"]["windows"].replace("${arch}", arch)
    elif "osx" in lib["natives"] and platform.system() == 'Darwin':
        nativesFile = lib["natives"]["osx"].replace("${arch}", arch)
    elif "linux" in lib["natives"] and platform.system() == "Linux":
        nativesFile = lib["natives"]["linux"].replace("${arch}", arch)
    else:
        raise Exception("Platform not supported")

    return nativesFile


"""[Parses "rule" subpropery of library object, testing to see if should be included]
"""
def should_use_library(lib):
    def rule_says_yes(rule):
        useLib = None

        if rule["action"] == "allow":
            useLib = False
        elif rule["action"] == "disallow":
            useLib = True

        if "os" in rule:
            for key, value in rule["os"].items():
                os = platform.system()
                if key == "name":
                    if value == "windows" and os != 'Windows':
                        return useLib
                    elif value == "osx" and os != 'Darwin':
                        return useLib
                    elif value == "linux" and os != 'Linux':
                        return useLib
                elif key == "arch":
                    if value == "x86" and platform.architecture()[0] != "32bit":
                        return useLib

        return not useLib

    if not "rules" in lib:
        return True

    shouldUseLibrary = False
    for i in lib["rules"]:
        if rule_says_yes(i):
            return True

    return shouldUseLibrary

"""
[Get string of all libraries to add to java classpath]
"""
def get_classpath(lib, mcDir):
    cp = []

    for i in lib["libraries"]:
        if not should_use_library(i):
            continue

        libDomain, libName, libVersion = i["name"].split(":")
        jarPath = os.path.join(mcDir, "libraries", *
                               libDomain.split('.'), libName, libVersion)

        native = get_natives_string(i)
        jarFile = libName + "-" + libVersion + ".jar"
        if native != "":
            jarFile = libName + "-" + libVersion + "-" + native + ".jar"

        cp.append(os.path.join(jarPath, jarFile))

    cp.append(os.path.join(mcDir, "versions", lib["id"], f'{lib["id"]}.jar'))

    return os.pathsep.join(cp)

version = '1.16.5'
username = '{username}'
uuid = '{uuid}'
accessToken = '{token}'

mcDir = os.path.join(os.getenv('HOME'), '.minecraft')
nativesDir = os.path.join(os.getenv('HOME'), 'versions', version, 'natives')
clientJson = json.loads(
    Path(os.path.join(mcDir, 'versions', version, f'{version}.json')).read_text())
classPath = get_classpath(clientJson, mcDir)
mainClass = clientJson['mainClass']
versionType = clientJson['type']
assetIndex = clientJson['assetIndex']['id']

debug(classPath)
debug(mainClass)
debug(versionType)
debug(assetIndex)

subprocess.call([
    '/usr/bin/java',
    f'-Djava.library.path={nativesDir}',
    '-Dminecraft.launcher.brand=custom-launcher',
    '-Dminecraft.launcher.version=2.1',
    '-cp',
    classPath,
    'net.minecraft.client.main.Main',
    '--username',
    username,
    '--version',
    version,
    '--gameDir',
    mcDir,
    '--assetsDir',
    os.path.join(mcDir, 'assets'),
    '--assetIndex',
    assetIndex,
    '--uuid',
    uuid,
    '--accessToken',
    accessToken,
    '--userType',
    'mojang',
    '--versionType',
    'release'
])

Reading JSON from a file?

To add on this, today you are able to use pandas to import json:
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_json.html You may want to do a careful use of the orient parameter.

Spark read file from S3 using sc.textFile ("s3n://...)

For Spark 1.4.x "Pre built for Hadoop 2.6 and later":

I just copied needed S3, S3native packages from hadoop-aws-2.6.0.jar to spark-assembly-1.4.1-hadoop2.6.0.jar.

After that I restarted spark cluster and it works. Do not forget to check owner and mode of the assembly jar.

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

#!/bin/bash

git-remote-url() {
 local rmt=$1; shift || { printf "Usage: git-remote-url [REMOTE]\n" >&2; return 1; }
 local url

 if ! git config --get remote.${rmt}.url &>/dev/null; then
  printf "%s\n" "Error: not a valid remote name" && return 1
  # Verify remote using 'git remote -v' command
 fi

 url=`git config --get remote.${rmt}.url`

 # Parse remote if local clone used SSH checkout
 [[ "$url" == git@* ]] \
 && { url="https://github.com/${url##*:}" >&2; }; \
 { url="${url%%.git}" >&2; };

 printf "%s\n" "$url"
}

Usage:

# Either launch a new terminal and copy `git-remote-url` into the current shell process, 
# or create a shell script and add it to the PATH to enable command invocation with bash.

# Create a local clone of your repo with SSH, or HTTPS
git clone [email protected]:your-username/your-repository.git
cd your-repository

git-remote-url origin

Output:

https://github.com/your-username/your-repository

When is TCP option SO_LINGER (0) required?

The typical reason to set a SO_LINGER timeout of zero is to avoid large numbers of connections sitting in the TIME_WAIT state, tying up all the available resources on a server.

When a TCP connection is closed cleanly, the end that initiated the close ("active close") ends up with the connection sitting in TIME_WAIT for several minutes. So if your protocol is one where the server initiates the connection close, and involves very large numbers of short-lived connections, then it might be susceptible to this problem.

This isn't a good idea, though - TIME_WAIT exists for a reason (to ensure that stray packets from old connections don't interfere with new connections). It's a better idea to redesign your protocol to one where the client initiates the connection close, if possible.

How to Identify port number of SQL server

This query works for me:

SELECT DISTINCT 
    local_tcp_port 
FROM sys.dm_exec_connections 
WHERE local_tcp_port IS NOT NULL 

Python Progress Bar

This answer doesn't rely on external packages, I also think that most people just want a ready-made piece of code. The code below can be adapted to fit your needs by customizing: bar progress symbol '#', bar size, text prefix etc.

import sys

def progressbar(it, prefix="", size=60, file=sys.stdout):
    count = len(it)
    def show(j):
        x = int(size*j/count)
        file.write("%s[%s%s] %i/%i\r" % (prefix, "#"*x, "."*(size-x), j, count))
        file.flush()        
    show(0)
    for i, item in enumerate(it):
        yield item
        show(i+1)
    file.write("\n")
    file.flush()

Usage:

import time

for i in progressbar(range(15), "Computing: ", 40):
    time.sleep(0.1) # any calculation you need

Output:

Computing: [################........................] 4/15
  • Doesn't require a second thread. Some solutions/packages above require.

  • Works with any iterable it means anything that len() can be used on. A list, a dict of anything for example ['a', 'b', 'c' ... 'g']

  • Works with generators only have to wrap it with a list(). For example for i in progressbar(list(your_generator), "Computing: ", 40): Unless the work is done in the generator. In that case you need another solution (like tqdm).

You can also change output by changing file to sys.stderr for example

No Application Encryption Key Has Been Specified

In my case, I also needed to reset the cached config files:

php artisan key:generate
php artisan config:cache

PHP how to get value from array if key is in a variable

$value = ( array_key_exists($key, $array) && !empty($array[$key]) ) 
         ? $array[$key] 
         : 'non-existant or empty value key';

How to test a variable is null in python

Testing for name pointing to None and name existing are two semantically different operations.

To check if val is None:

if val is None:
    pass  # val exists and is None

To check if name exists:

try:
    val
except NameError:
    pass  # val does not exist at all

Does swift have a trim method on String?

extension String {
    /// EZSE: Trims white space and new line characters
    public mutating func trim() {
         self = self.trimmed()
    }

    /// EZSE: Trims white space and new line characters, returns a new string
    public func trimmed() -> String {
        return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
    }
}

Taken from this repo of mine: https://github.com/goktugyil/EZSwiftExtensions/commit/609fce34a41f98733f97dfd7b4c23b5d16416206

Read a file line by line with VB.NET

Replaced the reader declaration with this one and now it works!

Dim reader As New StreamReader(filetoimport.Text, Encoding.Default)

Encoding.Default represents the ANSI code page that is set under Windows Control Panel.

How to check syslog in Bash on Linux?

A very cool util is journalctl.

For example, to show syslog to console: journalctl -t <syslog-ident>, where <syslog-ident> is identity you gave to function openlog to initialize syslog.

"Please try running this command again as Root/Administrator" error when trying to install LESS

I was getting this issue for instaling expo cli and I fixed by just following four steps mentioned in the npm documentation here.

Problem is some version of npm fail to locate folder for global installations of package. Following these steps we can create or modify the .profile file in Home directory of user and give it a proper PATH there so it works like a charm.

Try this it helped me and I spent around an hour for this issue. My node version was 6.0

Steps I follow

Back up your computer. On the command line, in your home directory, create a directory for global installations:

mkdir ~/.npm-global

Configure npm to use the new directory path:

npm config set prefix '~/.npm-global'

In your preferred text editor, open or create a ~/.profile file and add this line:

export PATH=~/.npm-global/bin:$PATH

On the command line, update your system variables:

source ~/.profile

To test your new configuration, install a package globally without using sudo:

npm install -g jshint

TypeError: can't pickle _thread.lock objects

You need to change from queue import Queue to from multiprocessing import Queue.

The root reason is the former Queue is designed for threading module Queue while the latter is for multiprocessing.Process module.

For details, you can read some source code or contact me!

Can I execute a function after setState is finished updating?

Making setState return a Promise

In addition to passing a callback to setState() method, you can wrap it around an async function and use the then() method -- which in some cases might produce a cleaner code:

(async () => new Promise(resolve => this.setState({dummy: true}), resolve)()
    .then(() => { console.log('state:', this.state) });

And here you can take this one more step ahead and make a reusable setState function that in my opinion is better than the above version:

const promiseState = async state =>
    new Promise(resolve => this.setState(state, resolve));

promiseState({...})
    .then(() => promiseState({...})
    .then(() => {
        ...  // other code
        return promiseState({...});
    })
    .then(() => {...});

This works fine in React 16.4, but I haven't tested it in earlier versions of React yet.

Also worth mentioning that keeping your callback code in componentDidUpdate method is a better practice in most -- probably all, cases.

How to use <md-icon> in Angular Material?

All md- prefixes are now mat- prefixes as of time of writing this!

Put this in your html head:

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

Import in our module:

import { MatIconModule } from '@angular/material';

Use in your code:

<mat-icon>face</mat-icon>

Here is the latest documentation:

https://material.angular.io/components/icon/overview

For..In loops in JavaScript - key value pairs

You can use a 'for in' loop for this:

for (var key in bar) {
     var value = bar[key];
}

AngularJS event on window innerWidth size change

I found a jfiddle that might help here: http://jsfiddle.net/jaredwilli/SfJ8c/

Ive refactored the code to make it simpler for this.

// In your controller
var w = angular.element($window);
$scope.$watch(
  function () {
    return $window.innerWidth;
  },
  function (value) {
    $scope.windowWidth = value;
  },
  true
);

w.bind('resize', function(){
  $scope.$apply();
});

You can then reference to windowWidth from the html

<span ng-bind="windowWidth"></span>

How can I check if a Perl module is installed on my system from the command line?

For example, to check if the DBI module is installed or not, use

perl -e 'use DBI;'

You will see error if not installed. (from http://www.linuxask.com)

VBA - Select columns using numbers?

You can use resize like this:

For n = 1 To 5
    Columns(n).Resize(, 5).Select
    '~~> rest of your code
Next

In any Range Manipulation that you do, always keep at the back of your mind Resize and Offset property.

Difference between a View's Padding and Margin

In simple words:

  1. Padding - creates space inside the view's border.
  2. Margin - creates space outside the view's border.

PHP script to loop through all of the files in a directory?

For completeness (since this seems to be a high-traffic page), let's not forget the good old dir() function:

$entries = [];
$d = dir("/"); // dir to scan
while (false !== ($entry = $d->read())) { // mind the strict bool check!
    if ($entry[0] == '.') continue; // ignore anything starting with a dot
    $entries[] = $entry;
}
$d->close();
sort($entries); // or whatever desired

print_r($entries);

How to decode a QR-code image in (preferably pure) Python?

I'm answering only the part of the question about zbar installation.

I spent nearly half an hour a few hours to make it work on Windows + Python 2.7 64-bit, so here are additional notes to the accepted answer:

PS: Making it work with Python 3.x is even more difficult: Compile zbar for Python 3.x.

PS2: I just tested pyzbar with pip install pyzbar and it's MUCH easier, it works out-of-the-box (the only thing is you need to have VC Redist 2013 files installed). It is also recommended to use this library in this pyimagesearch.com article.

How can I read comma separated values from a text file in Java?

To split your String by comma(,) use str.split(",") and for tab use str.split("\\t")

    try {
        BufferedReader in = new BufferedReader(
                               new FileReader("G:\\RoutePPAdvant2.txt"));
        String str;

        while ((str = in.readLine())!= null) {
            String[] ar=str.split(",");
            ...
        }
        in.close();
    } catch (IOException e) {
        System.out.println("File Read Error");
    }

Open a workbook using FileDialog and manipulate it in Excel VBA

Thankyou Frank.i got the idea. Here is the working code.

Option Explicit
Private Sub CommandButton1_Click()

  Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
  Dim fd As Office.FileDialog

  Set fd = Application.FileDialog(msoFileDialogFilePicker)

  With fd
    .AllowMultiSelect = False
    .Title = "Please select the file."
    .Filters.Clear
    .Filters.Add "Excel 2003", "*.xls?"

    If .Show = True Then
      fileName = Dir(.SelectedItems(1))

    End If
  End With

  Application.ScreenUpdating = False
  Application.DisplayAlerts = False

  Workbooks.Open (fileName)

  For Each sheet In Workbooks(fileName).Worksheets
    total = Workbooks("import-sheets.xlsm").Worksheets.Count
    Workbooks(fileName).Worksheets(sheet.Name).Copy _
        after:=Workbooks("import-sheets.xlsm").Worksheets(total)
  Next sheet

  Workbooks(fileName).Close

  Application.ScreenUpdating = True
  Application.DisplayAlerts = True

End Sub

How to get a responsive button in bootstrap 3

I know this already has a marked answer, but I feel I have an improvement to it.

The marked answer is a bit misleading. He set a width to the button, which is not necessary, and set widths are not "responsive". To his defense, he mentions in a comment below it, that the width is not necessary and just an example.

One thing not mentioned here, is that the words may break in the middle of a word and look messed up.

My solution, forces the break to happen between words, a nice word wrap.

.btn-responsive {
    white-space: normal !important;
    word-wrap: break-word;
}

<a href="#" class="btn btn-primary btn-responsive">Click Here</a>

matplotlib get ylim values

 ymin, ymax = axes.get_ylim()

If you are using the plt api directly, you can avoid calls to axes altogether:

def myplotfunction(title, values, errors, plot_file_name):

    # plot errorbars
    indices = range(0, len(values))
    fig = plt.figure()
    plt.errorbar(tuple(indices), tuple(values), tuple(errors), marker='.')

    plt.ylim([-0.5, len(values) - 0.5])
    plt.xlabel('My x-axis title')
    plt.ylabel('My y-axis title')

    # title
    plt.title(title)

    # save as file
    plt.savefig(plot_file_name)

   # close figure
    plt.close(fig)

JSON to pandas DataFrame

Once you have the flattened DataFrame obtained by the accepted answer, you can make the columns a MultiIndex ("fancy multiline header") like this:

df.columns = pd.MultiIndex.from_tuples([tuple(c.split('.')) for c in df.columns])

Python list subtraction operation

The answer provided by @aaronasterling looks good, however, it is not compatible with the default interface of list: x = MyList(1, 2, 3, 4) vs x = MyList([1, 2, 3, 4]). Thus, the below code can be used as a more python-list friendly:

class MyList(list):
    def __init__(self, *args):
        super(MyList, self).__init__(*args)

    def __sub__(self, other):
        return self.__class__([item for item in self if item not in other])

Example:

x = MyList([1, 2, 3, 4])
y = MyList([2, 5, 2])
z = x - y

Add click event on div tag using javascript

Try this:

 var div = document.getElementsByClassName('drill_cursor')[0];

 div.addEventListener('click', function (event) {
     alert('Hi!');
 });

Get value of a specific object property in C# without knowing the class behind

Reflection and dynamic value access are correct solutions to this question but are quite slow. If your want something faster then you can create dynamic method using expressions:

  object value = GetValue();
  string propertyName = "MyProperty";

  var parameter = Expression.Parameter(typeof(object));
  var cast = Expression.Convert(parameter, value.GetType());
  var propertyGetter = Expression.Property(cast, propertyName);
  var castResult = Expression.Convert(propertyGetter, typeof(object));//for boxing

  var propertyRetriver = Expression.Lambda<Func<object, object>>(castResult, parameter).Compile();

 var retrivedPropertyValue = propertyRetriver(value);

This way is faster if you cache created functions. For instance in dictionary where key would be the actual type of object assuming that property name is not changing or some combination of type and property name.

How to read/write arbitrary bits in C/C++

Some 2+ years after I asked this question I'd like to explain it the way I'd want it explained back when I was still a complete newb and would be most beneficial to people who want to understand the process.

First of all, forget the "11111111" example value, which is not really all that suited for the visual explanation of the process. So let the initial value be 10111011 (187 decimal) which will be a little more illustrative of the process.

1 - how to read a 3 bit value starting from the second bit:

    ___  <- those 3 bits
10111011 

The value is 101, or 5 in decimal, there are 2 possible ways to get it:

  • mask and shift

In this approach, the needed bits are first masked with the value 00001110 (14 decimal) after which it is shifted in place:

    ___
10111011 AND
00001110 =
00001010 >> 1 =
     ___
00000101

The expression for this would be: (value & 14) >> 1

  • shift and mask

This approach is similar, but the order of operations is reversed, meaning the original value is shifted and then masked with 00000111 (7) to only leave the last 3 bits:

    ___
10111011 >> 1
     ___
01011101 AND
00000111
00000101

The expression for this would be: (value >> 1) & 7

Both approaches involve the same amount of complexity, and therefore will not differ in performance.

2 - how to write a 3 bit value starting from the second bit:

In this case, the initial value is known, and when this is the case in code, you may be able to come up with a way to set the known value to another known value which uses less operations, but in reality this is rarely the case, most of the time the code will know neither the initial value, nor the one which is to be written.

This means that in order for the new value to be successfully "spliced" into byte, the target bits must be set to zero, after which the shifted value is "spliced" in place, which is the first step:

    ___ 
10111011 AND
11110001 (241) =
10110001 (masked original value)

The second step is to shift the value we want to write in the 3 bits, say we want to change that from 101 (5) to 110 (6)

     ___
00000110 << 1 =
    ___
00001100 (shifted "splice" value)

The third and final step is to splice the masked original value with the shifted "splice" value:

10110001 OR
00001100 =
    ___
10111101

The expression for the whole process would be: (value & 241) | (6 << 1)

Bonus - how to generate the read and write masks:

Naturally, using a binary to decimal converter is far from elegant, especially in the case of 32 and 64 bit containers - decimal values get crazy big. It is possible to easily generate the masks with expressions, which the compiler can efficiently resolve during compilation:

  • read mask for "mask and shift": ((1 << fieldLength) - 1) << (fieldIndex - 1), assuming that the index at the first bit is 1 (not zero)
  • read mask for "shift and mask": (1 << fieldLength) - 1 (index does not play a role here since it is always shifted to the first bit
  • write mask : just invert the "mask and shift" mask expression with the ~ operator

How does it work (with the 3bit field beginning at the second bit from the examples above)?

00000001 << 3
00001000  - 1
00000111 << 1
00001110  ~ (read mask)
11110001    (write mask)

The same examples apply to wider integers and arbitrary bit width and position of the fields, with the shift and mask values varying accordingly.

Also note that the examples assume unsigned integer, which is what you want to use in order to use integers as portable bit-field alternative (regular bit-fields are in no way guaranteed by the standard to be portable), both left and right shift insert a padding 0, which is not the case with right shifting a signed integer.

Even easier:

Using this set of macros (but only in C++ since it relies on the generation of member functions):

#define GETMASK(index, size) ((((size_t)1 << (size)) - 1) << (index))
#define READFROM(data, index, size) (((data) & GETMASK((index), (size))) >> (index))
#define WRITETO(data, index, size, value) ((data) = (((data) & (~GETMASK((index), (size)))) | (((value) << (index)) & (GETMASK((index), (size))))))
#define FIELD(data, name, index, size) \
  inline decltype(data) name() const { return READFROM(data, index, size); } \
  inline void set_##name(decltype(data) value) { WRITETO(data, index, size, value); }

You could go for something as simple as:

struct A {
  uint bitData;
  FIELD(bitData, one, 0, 1)
  FIELD(bitData, two, 1, 2)
};

And have the bit fields implemented as properties you can easily access:

A a;
a.set_two(3);
cout << a.two();

Replace decltype with gcc's typeof pre-C++11.

What are the best practices for SQLite on Android?

The Database is very flexible with multi-threading. My apps hit their DBs from many different threads simultaneously and it does just fine. In some cases I have multiple processes hitting the DB simultaneously and that works fine too.

Your async tasks - use the same connection when you can, but if you have to, its OK to access the DB from different tasks.

How to allow only integers in a textbox?

You can use client-side validation:

<asp:textbox onkeydown="return (!(event.keyCode>=65) && event.keyCode!=32);" />

C++11 reverse range-based for-loop

Got this example from cppreference. It works with:

GCC 10.1+ with flag -std=c++20

#include <ranges>
#include <iostream>
 
int main()
{
    static constexpr auto il = {3, 1, 4, 1, 5, 9};
 
    std::ranges::reverse_view rv {il};
    for (int i : rv)
        std::cout << i << ' ';
 
    std::cout << '\n';
 
    for(int i : il | std::views::reverse)
        std::cout << i << ' ';
}

IF...THEN...ELSE using XML

Perhaps another way to code conditional constructs in XML:

<rule>
    <if>
        <conditions>
            <condition var="something" operator="&gt;">400</condition>
            <!-- more conditions possible -->
        </conditions>
        <statements>
            <!-- do something -->
        </statements>
    </if>
    <elseif>
        <conditions></conditions>
        <statements></statements>
    </elseif>
    <else>
        <statements></statements>
    </else>
</rule>

100% width background image with an 'auto' height

You can use the CSS property background-size and set it to cover or contain, depending your preference. Cover will cover the window entirely, while contain will make one side fit the window thus not covering the entire page (unless the aspect ratio of the screen is equal to the image).

Please note that this is a CSS3 property. In older browsers, this property is ignored. Alternatively, you can use javascript to change the CSS settings depending on the window size, but this isn't preferred.

body {
    background-image: url(image.jpg); /* image */
    background-position: center;      /* center the image */
    background-size: cover;           /* cover the entire window */
}

image processing to improve tesseract OCR accuracy

  1. fix DPI (if needed) 300 DPI is minimum
  2. fix text size (e.g. 12 pt should be ok)
  3. try to fix text lines (deskew and dewarp text)
  4. try to fix illumination of image (e.g. no dark part of image)
  5. binarize and de-noise image

There is no universal command line that would fit to all cases (sometimes you need to blur and sharpen image). But you can give a try to TEXTCLEANER from Fred's ImageMagick Scripts.

If you are not fan of command line, maybe you can try to use opensource scantailor.sourceforge.net or commercial bookrestorer.

How to set the Android progressbar's height?

Many solution here with lot of upvotes didn't work for me, even the accepted answer. I solved it by setting the scaleY, but isn't a good solution if you need too much height because the drawable comes pixelated.

Programmatically:


progressBar.setScaleY(2f);

XML Layout:


android:scaleY="2"

Change action bar color in android

if you have in your layout activity_main

<android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

you have to put

in your Activity this code

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    toolbar.setBackgroundColor(Color.CYAN);
}

Get the latest date from grouped MySQL data

Using max(date) didn't solve my problem as there is no assurance that other columns will be from the same row as the max(date) is. Instead of that this one solved my problem and sorted group by in a correct order and values of other columns are from the same row as the max date is:

SELECT model, date 
FROM (SELECT * FROM doc ORDER BY date DESC) as sortedTable
GROUP BY model

MongoDB vs Firebase

Firebase is a suite of features .

  • Realtime Database
  • Hosting
  • Authentication
  • Storage
  • Cloud Messaging
  • Remote Config
  • Test Lab
  • Crash Reporting
  • Notifications
  • App Indexing
  • Dynamic Links
  • Invites
  • AdWords
  • AdMob

I believe you are trying to compare Firebase Realtime Database with Mongo DB . Firebase Realtime Database stores data as JSON format and syncs to all updates of the data to all clients listening to the data . It abstracts you from all complexity that is needed to setup and scale any database . I will not recommend firebase where you have lot of complex scenarios where aggregation of data is needed .(Queries that need SUM/AVERAGE kind of stuff ) . Though this is recently achievable using Firebase functions . Modeling data in Firebase is tricky . But it is the best way to get you started instantaneously . MongoDB is a database. This give you lot of powerful features. But MongoDB when installed in any platform you need to manage it by yourself .

When i try to choose between Firebase or MongoDB(or any DB ) . I try to answer the following .

  1. Are there many aggregation queries that gets executed .(Like in case of reporting tool or BI tool ) . If Yes dont go for Firebase
  2. Do i need to perform lot of transaction . (If yes then i would not like to go with firebase) (Tranactions are somewhat easy though after introduction of functions but that is also a overhead if lot of transactions needs to be maintained)
  3. What timeline do i have to get things up and running .(Firebase is very easy to setup and integrate ).
  4. Do i have expertise to scale up the DB and trouble shoot DB related stuffs . (Firebase is more like SAAS so no need to worry about scaleability)

What does 'var that = this;' mean in JavaScript?

Here is an example `

$(document).ready(function() {
        var lastItem = null;
        $(".our-work-group > p > a").click(function(e) {
            e.preventDefault();

            var item = $(this).html(); //Here value of "this" is ".our-work-group > p > a"
            if (item == lastItem) {
                lastItem = null;
                $('.our-work-single-page').show();
            } else {
                lastItem = item;
                $('.our-work-single-page').each(function() {
                    var imgAlt = $(this).find('img').attr('alt'); //Here value of "this" is '.our-work-single-page'. 
                    if (imgAlt != item) {
                        $(this).hide();
                    } else {
                        $(this).show();
                    }
                });
            }

        });
    });`

So you can see that value of this is two different values depending on the DOM element you target but when you add "that" to the code above you change the value of "this" you are targeting.

`$(document).ready(function() {
        var lastItem = null;
        $(".our-work-group > p > a").click(function(e) {
            e.preventDefault();
            var item = $(this).html(); //Here value of "this" is ".our-work-group > p > a"
            if (item == lastItem) {
                lastItem = null;
                var that = this;
                $('.our-work-single-page').show();
            } else {
                lastItem = item;
                $('.our-work-single-page').each(function() {
                   ***$(that).css("background-color", "#ffe700");*** //Here value of "that" is ".our-work-group > p > a"....
                    var imgAlt = $(this).find('img').attr('alt'); 
                    if (imgAlt != item) {
                        $(this).hide();
                    } else {
                        $(this).show();
                    }
                });
            }

        });
    });`

.....$(that).css("background-color", "#ffe700"); //Here value of "that" is ".our-work-group > p > a" because the value of var that = this; so even though we are at "this"= '.our-work-single-page', still we can use "that" to manipulate previous DOM element.

Compare every item to every other item in ArrayList

What's the problem with using for loop inside, just like outside?

for (int j = i + 1; j < list.size(); ++j) {
    ...
}

In general, since Java 5, I used iterators only once or twice.

How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

Another simple way to exclude the auto configuration classes,

Add below similar configuration to your application.yml file,

---
spring:
  profiles: test
  autoconfigure.exclude: org.springframework.boot.autoconfigure.session.SessionAutoConfiguration

how to reference a YAML "setting" from elsewhere in the same YAML file?

That your example is invalid is only because you chose a reserved character to start your scalars with. If you replace the * with some other non-reserved character (I tend to use non-ASCII characters for that as they are seldom used as part of some specification), you end up with perfectly legal YAML:

paths:
  root: /path/to/root/
  patha: ?root? + a
  pathb: ?root? + b
  pathc: ?root? + c

This will load into the standard representation for mappings in the language your parser uses and does not magically expand anything.
To do that use a locally default object type as in the following Python program:

# coding: utf-8

from __future__ import print_function

import ruamel.yaml as yaml

class Paths:
    def __init__(self):
        self.d = {}

    def __repr__(self):
        return repr(self.d).replace('ordereddict', 'Paths')

    @staticmethod
    def __yaml_in__(loader, data):
        result = Paths()
        loader.construct_mapping(data, result.d)
        return result

    @staticmethod
    def __yaml_out__(dumper, self):
        return dumper.represent_mapping('!Paths', self.d)

    def __getitem__(self, key):
        res = self.d[key]
        return self.expand(res)

    def expand(self, res):
        try:
            before, rest = res.split(u'?', 1)
            kw, rest = rest.split(u'? +', 1)
            rest = rest.lstrip() # strip any spaces after "+"
            # the lookup will throw the correct keyerror if kw is not found
            # recursive call expand() on the tail if there are multiple
            # parts to replace
            return before + self.d[kw] + self.expand(rest)
        except ValueError:
            return res

yaml_str = """\
paths: !Paths
  root: /path/to/root/
  patha: ?root? + a
  pathb: ?root? + b
  pathc: ?root? + c
"""

loader = yaml.RoundTripLoader
loader.add_constructor('!Paths', Paths.__yaml_in__)

paths = yaml.load(yaml_str, Loader=yaml.RoundTripLoader)['paths']

for k in ['root', 'pathc']:
    print(u'{} -> {}'.format(k, paths[k]))

which will print:

root -> /path/to/root/
pathc -> /path/to/root/c

The expanding is done on the fly and handles nested definitions, but you have to be careful about not invoking infinite recursion.

By specifying the dumper, you can dump the original YAML from the data loaded in, because of the on-the-fly expansion:

dumper = yaml.RoundTripDumper
dumper.add_representer(Paths, Paths.__yaml_out__)
print(yaml.dump(paths, Dumper=dumper, allow_unicode=True))

this will change the mapping key ordering. If that is a problem you have to make self.d a CommentedMap (imported from ruamel.yaml.comments.py)

How to insert a column in a specific position in oracle without dropping and recreating the table?

You (still) can not choose the position of the column using ALTER TABLE: it can only be added to the end of the table. You can obviously select the columns in any order you want, so unless you are using SELECT * FROM column order shouldn't be a big deal.

If you really must have them in a particular order and you can't drop and recreate the table, then you might be able to drop and recreate columns instead:-

First copy the table

CREATE TABLE my_tab_temp AS SELECT * FROM my_tab;

Then drop columns that you want to be after the column you will insert

ALTER TABLE my_tab DROP COLUMN three;

Now add the new column (two in this example) and the ones you removed.

ALTER TABLE my_tab ADD (two NUMBER(2), three NUMBER(10));

Lastly add back the data for the re-created columns

UPDATE my_tab SET my_tab.three = (SELECT my_tab_temp.three FROM my_tab_temp WHERE my_tab.one = my_tab_temp.one);

Obviously your update will most likely be more complex and you'll have to handle indexes and constraints and won't be able to use this in some cases (LOB columns etc). Plus this is a pretty hideous way to do this - but the table will always exist and you'll end up with the columns in a order you want. But does column order really matter that much?

How to predict input image using trained model in Keras?

keras predict_classes (docs) outputs A numpy array of class predictions. Which in your model case, the index of neuron of highest activation from your last(softmax) layer. [[0]] means that your model predicted that your test data is class 0. (usually you will be passing multiple image, and the result will look like [[0], [1], [1], [0]] )

You must convert your actual label (e.g. 'cancer', 'not cancer') into binary encoding (0 for 'cancer', 1 for 'not cancer') for binary classification. Then you will interpret your sequence output of [[0]] as having class label 'cancer'

How do you change the formatting options in Visual Studio Code?

Same thing happened to me just now. I set prettier as the Default Formatter in Settings and it started working again. My Default Formatter was null.

To set VSCODE Default Formatter

File -> Preferences -> Settings (for Windows) Code -> Preferences -> Settings (for Mac)

Search for "Default Formatter". In the dropdown, prettier will show as esbenp.prettier-vscode.

VSCODE Editor Option

How to loop over grouped Pandas dataframe?

df.groupby('l_customer_id_i').agg(lambda x: ','.join(x)) does already return a dataframe, so you cannot loop over the groups anymore.

In general:

  • df.groupby(...) returns a GroupBy object (a DataFrameGroupBy or SeriesGroupBy), and with this, you can iterate through the groups (as explained in the docs here). You can do something like:

    grouped = df.groupby('A')
    
    for name, group in grouped:
        ...
    
  • When you apply a function on the groupby, in your example df.groupby(...).agg(...) (but this can also be transform, apply, mean, ...), you combine the result of applying the function to the different groups together in one dataframe (the apply and combine step of the 'split-apply-combine' paradigm of groupby). So the result of this will always be again a DataFrame (or a Series depending on the applied function).

When is the init() function run?

Yes assuming you have this:

var WhatIsThe = AnswerToLife()

func AnswerToLife() int {
    return 42
}

func init() {
    WhatIsThe = 0
}

func main() {
    if WhatIsThe == 0 {
        fmt.Println("It's all a lie.")
    }
}

AnswerToLife() is guaranteed to run before init() is called, and init() is guaranteed to run before main() is called.

Keep in mind that init() is always called, regardless if there's main or not, so if you import a package that has an init function, it will be executed.

Additionally, you can have multiple init() functions per package; they will be executed in the order they show up in the file (after all variables are initialized of course). If they span multiple files, they will be executed in lexical file name order (as pointed out by @benc):

It seems that init() functions are executed in lexical file name order. The Go spec says "build systems are encouraged to present multiple files belonging to the same package in lexical file name order to a compiler". It seems that go build works this way.


A lot of the internal Go packages use init() to initialize tables and such, for example https://github.com/golang/go/blob/883bc6/src/compress/bzip2/bzip2.go#L480

How to see the proxy settings on windows?

You can figure out which proxy server you're using by accessing some websites with a browser and then running the DOS command:

netstat

and you'll see some connections in the Foreign Address column on port 80 or 8080 (common proxy server ports). Ideally you will be able to identify the proxy server by its naming convention.

[see also https://stackoverflow.com/a/8161865/3195477]

Rounding SQL DateTime to midnight

This might look cheap but it's working for me

SELECT CONVERT(DATETIME,LEFT(CONVERT(VARCHAR,@dateFieldOrVariable,101),10)+' 00:00:00.000')

Align DIV's to bottom or baseline

Use the CSS display values of table and table-cell:

HTML

<html>
<body>

  <div class="valign bottom">
    <div>

      <div>my bottom aligned div 1</div>
      <div>my bottom aligned div 2</div>
      <div>my bottom aligned div 3</div>

    </div>
  </div>

</body>
</html>

CSS

html,body {
    width: 100%;
    height: 100%;
}
.valign {
    display: table;
    width: 100%;
    height: 100%;
}
.valign > div {
    display: table-cell;
    width: 100%;
    height: 100%;
}
.valign.bottom > div {
    vertical-align: bottom;
}

I've created a JSBin demo here: http://jsbin.com/INOnAkuF/2/edit

The demo also has an example how to vertically center align using the same technique.

Trim Cells using VBA in Excel

Works fine for me with one change - fourth line should be:

cell.Value = Trim(cell.Value)

Edit: If it appears to be stuck in a loop, I'd add

Debug.Print cell.Address

inside your For ... Next loop to get a bit more info on what's happening.

I also suspect that Trim only strips spaces - are you sure you haven't got some other kind of non-display character in there?

How to compare two NSDates: Which is more recent?

In Swift, you can overload existing operators:

func > (lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs.timeIntervalSinceReferenceDate > rhs.timeIntervalSinceReferenceDate
}

func < (lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs.timeIntervalSinceReferenceDate < rhs.timeIntervalSinceReferenceDate
}

Then, you can compare NSDates directly with <, >, and == (already supported).

How do I kill a process using Vb.NET or C#?

Here is an easy example of how to kill all Word Processes.

Process[] procs = Process.GetProcessesByName("winword");

foreach (Process proc in procs)
    proc.Kill();

jQuery Validation plugin: validate check box

You can validate group checkbox and radio button without extra js code, see below example.

Your JS should be look like:

$("#formid").validate();

You can play with HTML tag and attributes: eg. group checkbox [minlength=2 and maxlength=4]

<fieldset class="col-md-12">
  <legend>Days</legend>
  <div class="form-row">
    <div class="col-12 col-md-12 form-group">
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="1" required="required" data-msg-required="This value is required." minlength="2" maxlength="4" data-msg-maxlength="Max should be 4">Monday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="2">Tuesday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="3">Wednesday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="4">Thursday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="5">Friday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="6">Saturday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="7">Sunday
        </label>
        <label for="daysgroup[]" class="error">Your error message will be display here.</label>
    </div>
  </div>
</fieldset>

You can see here first or any one input should have required, minlength="2" and maxlength="4" attributes. minlength/maxlength as per your requirement.

eg. group radio button:

<fieldset class="col-md-12">
  <legend>Gender</legend>
  <div class="form-row">
    <div class="col-12 col-md-12 form-group">
        <label class="form-check-inline">
          <input type="radio" name="gendergroup[]" value="m" required="required" data-msg-required="This value is required.">man
        </label>
        <label class="form-check-inline">
          <input type="radio" name="gendergroup[]" value="w">woman
        </label>
        <label class="form-check-inline">
          <input type="radio" name="gendergroup[]" value="o">other
        </label>
        <label for="gendergroup[]" class="error">Your error message will be display here.</label>
    </div>
  </div>
</fieldset>

You can check working example here.

  • jQuery v3.3.x
  • jQuery Validation Plugin - v1.17.0

Display HTML form values in same page after submit using Ajax

Try this one:

onsubmit="return f(this.'yourfieldname'.value);"

I hope this will help you.

How do I do string replace in JavaScript to convert ‘9.61’ to ‘9:61’?

It can be done with the regular JavaScript function replace().

value.replace(".", ":");

Case insensitive string compare in LINQ-to-SQL

If you pass a string that is case-insensitive into LINQ-to-SQL it will get passed into the SQL unchanged and the comparison will happen in the database. If you want to do case-insensitive string comparisons in the database all you need to to do is create a lambda expression that does the comparison and the LINQ-to-SQL provider will translate that expression into a SQL query with your string intact.

For example this LINQ query:

from user in Users
where user.Email == "[email protected]"
select user

gets translated to the following SQL by the LINQ-to-SQL provider:

SELECT [t0].[Email]
FROM [User] AS [t0]
WHERE [t0].[Email] = @p0
-- note that "@p0" is defined as nvarchar(11)
-- and is passed my value of "[email protected]"

As you can see, the string parameter will be compared in SQL which means things ought to work just the way you would expect them to.

Left align block of equations

Try to use the fleqn document class option.

\documentclass[fleqn]{article}

(See also http://en.wikibooks.org/wiki/LaTeX/Basics for a list of other options.)

What 'additional configuration' is necessary to reference a .NET 2.0 mixed mode assembly in a .NET 4.0 project?

Add following at this location C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\x64 FileName: sgen.exe.config(If you dont find this file, create and add one)

_x000D_
_x000D_
 <?xml version ="1.0"?>_x000D_
_x000D_
<configuration>_x000D_
 <runtime>        _x000D_
        <generatePublisherEvidence enabled="false"/>    _x000D_
    </runtime>_x000D_
_x000D_
    <startup useLegacyV2RuntimeActivationPolicy="true">_x000D_
_x000D_
                <supportedRuntime version="v4.0" />_x000D_
_x000D_
    </startup>    _x000D_
_x000D_
</configuration>
_x000D_
_x000D_
_x000D_

Doing this resolved the issue

JSON datetime between Python and JavaScript

I've worked it out.

Let's say you have a Python datetime object, d, created with datetime.now(). Its value is:

datetime.datetime(2011, 5, 25, 13, 34, 5, 787000)

You can serialize it to JSON as an ISO 8601 datetime string:

import json    
json.dumps(d.isoformat())

The example datetime object would be serialized as:

'"2011-05-25T13:34:05.787000"'

This value, once received in the Javascript layer, can construct a Date object:

var d = new Date("2011-05-25T13:34:05.787000");

As of Javascript 1.8.5, Date objects have a toJSON method, which returns a string in a standard format. To serialize the above Javascript object back to JSON, therefore, the command would be:

d.toJSON()

Which would give you:

'2011-05-25T20:34:05.787Z'

This string, once received in Python, could be deserialized back to a datetime object:

datetime.strptime('2011-05-25T20:34:05.787Z', '%Y-%m-%dT%H:%M:%S.%fZ')

This results in the following datetime object, which is the same one you started with and therefore correct:

datetime.datetime(2011, 5, 25, 20, 34, 5, 787000)

Add MIME mapping in web.config for IIS Express

I know this is an old question, but...

I was just noticing my instance of IISExpress wasn't serving woff files, so I wen't searching (Found this) and then found:

http://www.tomasmcguinness.com/2011/07/06/adding-support-for-svg-to-iis-express/

I suppose my install has support for SVG since I haven't had issue with that. But the instructions are trivially modifiable for woff:

  • Open a console application with administrator privilages.
  • Navigation to the IIS Express directory. This lives under Program Files or Program Files (x86)
  • Run the command:

    appcmd set config /section:staticContent /+[fileExtension='woff',mimeType='application/x-woff']

Solved my problem, and I didn't have to mess with some crummy config (like I had to to add support for the PUT and DELETE verbs). Yay!

How to get Toolbar from fragment?

In XML

 <androidx.appcompat.widget.Toolbar
  android:id="@+id/main_toolbar"
  android:layout_width="match_parent"
  android:layout_height="?attr/actionBarSize"
  app:layout_scrollFlags="scroll|enterAlways">
 </androidx.appcompat.widget.Toolbar>

Kotlin: In fragment.kt -> onCreateView()

setHasOptionsMenu(true)

val toolbar = view.findViewById<Toolbar>(R.id.main_toolbar)

(activity as? AppCompatActivity)?.setSupportActionBar(toolbar)

(activity as? AppCompatActivity)?.supportActionBar?.show()

-> onCreateOptionsMenu()

   override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
       inflater.inflate(R.menu.app_main_menu,menu)
       super.onCreateOptionsMenu(menu, inflater)
   }

->onOptionsItemSelected()

   override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
             R.id.selected_id->{//to_do}
             else -> super.onOptionsItemSelected(item)
        }
    }

new DateTime() vs default(DateTime)

The simpliest way to understand it is that DateTime is a struct. When you initialize a struct it's initialize to it's minimum value : DateTime.Min

Therefore there is no difference between default(DateTime) and new DateTime() and DateTime.Min

invalid new-expression of abstract class type

for others scratching their heads, I came across this error because I had innapropriately const-qualified one of the arguments to a method in a base class, so the derived class member functions were not over-riding it. so make sure you don't have something like

class Base 
{
  public:
      virtual void foo(int a, const int b) = 0;
}
class D: public Base 
{
 public:
     void foo(int a, int b){};
}

Create the perfect JPA entity

Entity interface

public interface Entity<I> extends Serializable {

/**
 * @return entity identity
 */
I getId();

/**
 * @return HashCode of entity identity
 */
int identityHashCode();

/**
 * @param other
 *            Other entity
 * @return true if identities of entities are equal
 */
boolean identityEquals(Entity<?> other);
}

Basic implementation for all Entities, simplifies Equals/Hashcode implementations:

public abstract class AbstractEntity<I> implements Entity<I> {

@Override
public final boolean identityEquals(Entity<?> other) {
    if (getId() == null) {
        return false;
    }
    return getId().equals(other.getId());
}

@Override
public final int identityHashCode() {
    return new HashCodeBuilder().append(this.getId()).toHashCode();
}

@Override
public final int hashCode() {
    return identityHashCode();
}

@Override
public final boolean equals(final Object o) {
    if (this == o) {
        return true;
    }
    if ((o == null) || (getClass() != o.getClass())) {
        return false;
    }

    return identityEquals((Entity<?>) o);
}

@Override
public String toString() {
    return getClass().getSimpleName() + ": " + identity();
    // OR 
    // return ReflectionToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
}

Room Entity impl:

@Entity
@Table(name = "ROOM")
public class Room extends AbstractEntity<Integer> {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "room_id")
private Integer id;

@Column(name = "number") 
private String number; //immutable

@Column(name = "capacity")
private Integer capacity;

@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "building_id")
private Building building; //immutable

Room() {
    // default constructor
}

public Room(Building building, String number) {
    // constructor with required field
    notNull(building, "Method called with null parameter (application)");
    notNull(number, "Method called with null parameter (name)");

    this.building = building;
    this.number = number;
}

public Integer getId(){
    return id;
}

public Building getBuilding() {
    return building;
}

public String getNumber() {
    return number;
}


public void setCapacity(Integer capacity) {
    this.capacity = capacity;
}

//no setters for number, building nor id
}

I don't see a point of comparing equality of entities based on business fields in every case of JPA Entities. That might be more of a case if these JPA entities are thought of as Domain-Driven ValueObjects, instead of Domain-Driven Entities (which these code examples are for).

Python Unicode Encode Error

Try adding the following line at the top of your python script.

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

How to get the body's content of an iframe in Javascript?

The exact question is how to do it with pure JavaScript not with jQuery.

But I always use the solution that can be found in jQuery's source code. It's just one line of native JavaScript.

For me it's the best, easy readable and even afaik the shortest way to get the iframes content.

First get your iframe

var iframe = document.getElementById('id_description_iframe');

// or
var iframe = document.querySelector('#id_description_iframe');

And then use jQuery's solution

var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;

It works even in the Internet Explorer which does this trick during the contentWindow property of the iframe object. Most other browsers uses the contentDocument property and that is the reason why we proof this property first in this OR condition. If it is not set try contentWindow.document.

Select elements in iframe

Then you can usually use getElementById() or even querySelectorAll() to select the DOM-Element from the iframeDocument:

if (!iframeDocument) {
    throw "iframe couldn't be found in DOM.";
}

var iframeContent = iframeDocument.getElementById('frameBody');

// or
var iframeContent = iframeDocument.querySelectorAll('#frameBody');

Call functions in the iframe

Get just the window element from iframe to call some global functions, variables or whole libraries (e.g. jQuery):

var iframeWindow = iframe.contentWindow;

// you can even call jQuery or other frameworks
// if it is loaded inside the iframe
iframeContent = iframeWindow.jQuery('#frameBody');

// or
iframeContent = iframeWindow.$('#frameBody');

// or even use any other global variable
iframeWindow.myVar = window.myVar;

// or call a global function
var myVar = iframeWindow.myFunction(param1 /*, ... */);

Note

All this is possible if you observe the same-origin policy.

How to loop through all but the last item of a list?

This answers what the OP should have asked, i.e. traverse a list comparing consecutive elements (excellent SilentGhost answer), yet generalized for any group (n-gram): 2, 3, ... n:

zip(*(l[start:] for start in range(0, n)))

Examples:

l = range(0, 4)  # [0, 1, 2, 3]

list(zip(*(l[start:] for start in range(0, 2)))) # == [(0, 1), (1, 2), (2, 3)]
list(zip(*(l[start:] for start in range(0, 3)))) # == [(0, 1, 2), (1, 2, 3)]
list(zip(*(l[start:] for start in range(0, 4)))) # == [(0, 1, 2, 3)]
list(zip(*(l[start:] for start in range(0, 5)))) # == []

Explanations:

  • l[start:] generates a a list/generator starting from index start
  • *list or *generator: passes all elements to the enclosing function zip as if it was written zip(elem1, elem2, ...)

Note:

AFAIK, this code is as lazy as it can be. Not tested.

How to convert minutes to hours/minutes and add various time values together using jQuery?

The function below will take as input # of minutes and output time in the following format: Hours:minutes. I used Math.trunc(), which is a new method added in 2015. It returns the integral part of a number by removing any fractional digits.

function display(a){
  var hours = Math.trunc(a/60);
  var minutes = a % 60;
  console.log(hours +":"+ minutes);
}

display(120); //"2:0"
display(60); //"1:0:
display(100); //"1:40"
display(126); //"2:6"
display(45); //"0:45"

Enabling/Disabling Microsoft Virtual WiFi Miniport

In the device manager you can select View > Show hidden devices

Git Checkout warning: unable to unlink files, permission denied

I encountered this error and I think the issue was that I had 'run as admin' when I started Eclipse and created the files, therefore they were owned by Admin (noticed by running 'ls -la' on the folder). When I later tried to stash the files, it didn't let me ('unable to unlink files' and all that). Doing a chmod on the files was the fix for me.

Two dimensional array in python

x=3#rows
y=3#columns
a=[]#create an empty list first
for i in range(x):
    a.append([0]*y)#And again append empty lists to original list
    for j in range(y):
         a[i][j]=input("Enter the value")

Encrypt and Decrypt in Java

If you use a static key, encrypt and decrypt always give the same result;

public static final String CRYPTOR_KEY = "your static key here";
byte[] keyByte = Base64.getDecoder().decode(CRYPTOR_KEY);
key = new SecretKeySpec(keyByte, "AES");

Display exact matches only with grep

Try this:

Alex Misuno@hp4530s ~
$ cat test.txt
1 OK
2 OK
3 NOTOK
4 OK
5 NOTOK
Alex Misuno@hp4530s ~
$ cat test.txt | grep ".* OK$"
1 OK
2 OK
4 OK

Better way to cast object to int

var intTried = Convert.ChangeType(myObject, typeof(int)) as int?;

How to get parameters from the URL with JSP

About the Implicit Objects of the Unified Expression Language, the Java EE 5 Tutorial writes:

Implicit Objects

The JSP expression language defines a set of implicit objects:

  • pageContext: The context for the JSP page. Provides access to various objects including:
    • servletContext: The context for the JSP page’s servlet and any web components contained in the same application. See Accessing the Web Context.
    • session: The session object for the client. See Maintaining Client State.
    • request: The request triggering the execution of the JSP page. See Getting Information from Requests.
    • response: The response returned by the JSP page. See Constructing Responses.
  • In addition, several implicit objects are available that allow easy access to the following objects:
    • param: Maps a request parameter name to a single value
    • paramValues: Maps a request parameter name to an array of values
    • header: Maps a request header name to a single value
    • headerValues: Maps a request header name to an array of values
    • cookie: Maps a cookie name to a single cookie
    • initParam: Maps a context initialization parameter name to a single value
  • Finally, there are objects that allow access to the various scoped variables described in Using Scope Objects.
    • pageScope: Maps page-scoped variable names to their values
    • requestScope: Maps request-scoped variable names to their values
    • sessionScope: Maps session-scoped variable names to their values
    • applicationScope: Maps application-scoped variable names to their values

The interesting parts are in bold :)

So, to answer your question, you should be able to access it like this (using EL):

${param.accountID}

Or, using JSP Scriptlets (not recommended):

<%
    String accountId = request.getParameter("accountID");
%>

Adding a css class to select using @Html.DropDownList()

Try This

 @Html.DropDownList("Id", null, new { @class = "ct-js-select ct-select-lg" })

How to change content on hover

This exact example is present on mozilla developers page:

::after

As you can see it even allows you to create tooltips! :) Also, instead of embedding the actual text in your CSS, you may use content: attr(data-descr);, and store it in data-descr="ADD" attribute of your HTML tag (which is nice because you can e.g translate it)

CSS content can only be usef with :after and :before pseudo-elements, so you can try to proceed with something like this:

.item a p.new-label span:after{
  position: relative;
  content: 'NEW'
}
.item:hover a p.new-label span:after {
  content: 'ADD';
}

The CSS :after pseudo-element matches a virtual last child of the selected element. Typically used to add cosmetic content to an element, by using the content CSS property. This element is inline by default.

IIS URL Rewrite and Web.config

1) Your existing web.config: you have declared rewrite map .. but have not created any rules that will use it. RewriteMap on its' own does absolutely nothing.

2) Below is how you can do it (it does not utilise rewrite maps -- rules only, which is fine for small amount of rewrites/redirects):

This rule will do SINGLE EXACT rewrite (internal redirect) /page to /page.html. URL in browser will remain unchanged.

<system.webServer>
    <rewrite>
        <rules>
            <rule name="SpecificRewrite" stopProcessing="true">
                <match url="^page$" />
                <action type="Rewrite" url="/page.html" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

This rule #2 will do the same as above, but will do 301 redirect (Permanent Redirect) where URL will change in browser.

<system.webServer>
    <rewrite>
        <rules>
            <rule name="SpecificRedirect" stopProcessing="true">
                <match url="^page$" />
                <action type="Redirect" url="/page.html" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

Rule #3 will attempt to execute such rewrite for ANY URL if there are such file with .html extension (i.e. for /page it will check if /page.html exists, and if it does then rewrite occurs):

<system.webServer>
    <rewrite>
        <rules>
            <rule name="DynamicRewrite" stopProcessing="true">
                <match url="(.*)" />
                <conditions>
                    <add input="{REQUEST_FILENAME}\.html" matchType="IsFile" />
                </conditions>
                <action type="Rewrite" url="/{R:1}.html" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

How to find out "The most popular repositories" on Github?

Ranking by stars or forks is not working. Each promoted or created by a famous company repository is popular at the beginning. Also it is possible to have a number of them which are in trend right now (publications, marketing, events). It doesn't mean that those repositories are useful/popular.

The gitmostwanted.com project (repo at github) analyses GH Archive data in order to highlight the most interesting repositories and exclude others. Just compare the results with mentioned resources.

SQL Server format decimal places with commas

without considering this to be a good idea...

select dbo.F_AddThousandSeparators(convert(varchar, convert(decimal(18, 4), 1234.1234567), 1))

Function

-- Author:      bummi
-- Create date: 20121106
CREATE FUNCTION F_AddThousandSeparators(@NumStr varchar(50)) 
RETURNS Varchar(50)
AS
BEGIN
declare @OutStr varchar(50)
declare @i int
declare @run int

Select @i=CHARINDEX('.',@NumStr)
if @i=0 
    begin
    set @i=LEN(@NumStr)
    Set @Outstr=''
    end
else
    begin   
     Set @Outstr=SUBSTRING(@NUmStr,@i,50)
     Set @i=@i -1
    end 


Set @run=0

While @i>0
    begin
      if @Run=3
        begin
          Set @Outstr=','+@Outstr
          Set @run=0
        end
      Set @Outstr=SUBSTRING(@NumStr,@i,1) +@Outstr  
      Set @i=@i-1
      Set @run=@run + 1     
    end

    RETURN @OutStr

END
GO

Excel Formula: Count cells where value is date

Here's my solution. If your cells will contain only dates or blanks, just compare it to another date. If the cell can be converted to date, it will be counted.

=COUNTIF(C:C,">1/1/1900")
## Counts all the dates in column C

Caution, cells with numbers will be counted.

How can I check if a string contains ANY letters from the alphabet?

Regex should be a fast approach:

re.search('[a-zA-Z]', the_string)

Why fragments, and when to use fragments instead of activities?

Activities are the full screen components in the app with the toolbar, everything else are preferably Fragments. One full screen parent activity with a toolbar can have multiple panes, scrollable pages, dialogs, etc. (all fragments), all of which can be accessed from the parent and communicate via the parent.

Example:

Activity A, Activity B, Activity C:

  • All activities need to have same code repeated, to show a basic toolbar for example, or inherit from a parent activity (becomes cumbersome to manage).
  • To move from one activity to the other, either all of them need to be in memory (overhead) or one needs to be destroyed for the other to open.
  • Communication between activities can be done via Intents.

vs

Activity A, Fragment 1, Fragment 2, Fragment 3:

  • No code repetition, all screens have toolbars etc. from that one activity.
  • Several ways to move from one fragment to next - view pager, multi pane etc.
  • Activity has most data, so minimal inter-fragment communication needed. If still necessary, can be done via interfaces easily.
  • Fragments do not need to be full screen, lots of flexibility in designing them.
  • Fragments do not need to inflate layout if views are not necessary.
  • Several activities can use the same fragment.

How can I make Bootstrap 4 columns all the same height?

You can use the new Bootstrap cards:

_x000D_
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>_x000D_
_x000D_
<div class="card-group">_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This card has supporting text below as a natural lead-in to additional content.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Link: Click here

regards,

What's the opposite of 'make install', i.e. how do you uninstall a library in Linux?

Make

Make is the program that’s used to install the program that’s compiled from the source code. It’s not the Linux package manager so it doesn’t keep track of the files it installs. This makes it difficult to uninstall the files afterward.

The Make Install command copies the built program and packages into the library directory and specified locations from the makefile. These locations can vary based on the examination that’s performed by the configure script.

CheckInstall

CheckInstall is the program that’s used to install or uninstall programs that are compiled from the source code. It monitors and copies the files that are installed using the make program. It also installs the files using the Linux package manager which allows it to be uninstalled like any regular package.

The CheckInstall command is used to call the Make Install command. It monitors the files that are installed and creates a binary package from them. It also installs the binary package with the Linux package manager.

Replace "source_location.deb" and "name" with your information from the Screenshot.

Execute the following commands in the source package directory:

  1. Install CheckInstall sudo apt-get install checkinstall
  2. Run the Configure script sudo ./configure
  3. Run the Make command sudo make
  4. Run CheckInstall sudo checkinstall
  5. Reinstall the package sudo dpkg --install --force-overwrite source_location.deb
  6. Remove the package sudo apt remove name

Here's an article article I wrote that covers the whole process with explanations.

Load a HTML page within another HTML page

The thing you are asking is not popup but lightbox. For this, the trick is to display a semitransparent layer behind (called overlay) and that required div above it.

Hope you are familiar basic javascript. Use the following code. With javascript, change display:block to/from display:none to show/hide popup.

<div style="background-color: rgba(150, 150, 150, 0.5); overflow: hidden; position: fixed; left: 0px; top: 0px; bottom: 0px; right: 0px; z-index: 1000; display:block;">
    <div style="background-color: rgb(255, 255, 255); width: 600px; position: static; margin: 20px auto; padding: 20px 30px 0px; top: 110px; overflow: hidden; z-index: 1001; box-shadow: 0px 3px 8px rgba(34, 25, 25, 0.4);">
        <iframe src="otherpage.html" width="400px"></iframe>
    </div>
</div>

Angular (4, 5, 6, 7) - Simple example of slide in out animation on ngIf

I answered a very similar question, and here is a way of doing this :

First, create a file where you would define your animations and export them. Just to make it more clear in your app.component.ts

In the following example, I used a max-height of the div that goes from 0px (when it's hidden), to 500px, but you would change that according to what you need.

This animation uses states (in and out), that will be toggle when we click on the button, which will run the animtion.

animations.ts

import { trigger, state, style, transition,
    animate, group, query, stagger, keyframes
} from '@angular/animations';

export const SlideInOutAnimation = [
    trigger('slideInOut', [
        state('in', style({
            'max-height': '500px', 'opacity': '1', 'visibility': 'visible'
        })),
        state('out', style({
            'max-height': '0px', 'opacity': '0', 'visibility': 'hidden'
        })),
        transition('in => out', [group([
            animate('400ms ease-in-out', style({
                'opacity': '0'
            })),
            animate('600ms ease-in-out', style({
                'max-height': '0px'
            })),
            animate('700ms ease-in-out', style({
                'visibility': 'hidden'
            }))
        ]
        )]),
        transition('out => in', [group([
            animate('1ms ease-in-out', style({
                'visibility': 'visible'
            })),
            animate('600ms ease-in-out', style({
                'max-height': '500px'
            })),
            animate('800ms ease-in-out', style({
                'opacity': '1'
            }))
        ]
        )])
    ]),
]

Then in your app.component, we import the animation and create the method that will toggle the animation state.

app.component.ts

import { SlideInOutAnimation } from './animations';

@Component({
  ...
  animations: [SlideInOutAnimation]
})
export class AppComponent  {
  animationState = 'in';

  ...

  toggleShowDiv(divName: string) {
    if (divName === 'divA') {
      console.log(this.animationState);
      this.animationState = this.animationState === 'out' ? 'in' : 'out';
      console.log(this.animationState);
    }
  }
}

And here is how your app.component.html would look like :

<div class="wrapper">
  <button (click)="toggleShowDiv('divA')">TOGGLE DIV</button>
  <div [@slideInOut]="animationState" style="height: 100px; background-color: red;">
  THIS DIV IS ANIMATED</div>
  <div class="content">THIS IS CONTENT DIV</div>
</div>

slideInOut refers to the animation trigger defined in animations.ts

Here is a StackBlitz example I have created : https://angular-muvaqu.stackblitz.io/

Side note : If an error ever occurs and asks you to add BrowserAnimationsModule, just import it in your app.module.ts:

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
  imports: [ ..., BrowserAnimationsModule ],
  ...
})

Argparse optional positional arguments?

As an extension to @VinaySajip answer. There are additional nargs worth mentioning.

  1. parser.add_argument('dir', nargs=1, default=os.getcwd())

N (an integer). N arguments from the command line will be gathered together into a list

  1. parser.add_argument('dir', nargs='*', default=os.getcwd())

'*'. All command-line arguments present are gathered into a list. Note that it generally doesn't make much sense to have more than one positional argument with nargs='*', but multiple optional arguments with nargs='*' is possible.

  1. parser.add_argument('dir', nargs='+', default=os.getcwd())

'+'. Just like '*', all command-line args present are gathered into a list. Additionally, an error message will be generated if there wasn’t at least one command-line argument present.

  1. parser.add_argument('dir', nargs=argparse.REMAINDER, default=os.getcwd())

argparse.REMAINDER. All the remaining command-line arguments are gathered into a list. This is commonly useful for command line utilities that dispatch to other command line utilities

If the nargs keyword argument is not provided, the number of arguments consumed is determined by the action. Generally this means a single command-line argument will be consumed and a single item (not a list) will be produced.

Edit (copied from a comment by @Acumenus) nargs='?' The docs say: '?'. One argument will be consumed from the command line if possible and produced as a single item. If no command-line argument is present, the value from default will be produced.

what is an illegal reflective access

If you want to go with the add-open option, here's a command to find which module provides which package ->

java --list-modules | tr @ " " | awk '{ print $1 }' | xargs -n1 java -d

the name of the module will be shown with the @ while the name of the packages without it

NOTE: tested with JDK 11

IMPORTANT: obviously is better than the provider of the package does not do the illegal access

IF... OR IF... in a windows batch file

I don't think so. Just use two IFs and GOTO the same label:

IF cond1 GOTO foundit
IF cond2 GOTO foundit

ECHO Didn't found it
GOTO end

:foundit
ECHO Found it!

:end

Import error No module named skimage

Hey this is pretty simple to solve this error.Just follow this steps:

First uninstall any existing installation:

pip uninstall scikit-image

or, on conda-based systems:

conda uninstall scikit-image

Now, clone scikit-image on your local computer, and install:

git clone https://github.com/scikit-image/scikit-image.git
cd scikit-image
pip install -e .

To update the installation:

git pull  # Grab latest source
pip install -e .  # Reinstall

For other os and manual process please check this Link.

What is the best way to redirect a page using React Router?

Actually it depends on your use case.

1) You want to protect your route from unauthorized users

If that is the case you can use the component called <Redirect /> and can implement the following logic:

import React from 'react'
import  { Redirect } from 'react-router-dom'

const ProtectedComponent = () => {
  if (authFails)
    return <Redirect to='/login'  />
  }
  return <div> My Protected Component </div>
}

Keep in mind that if you want <Redirect /> to work the way you expect, you should place it inside of your component's render method so that it should eventually be considered as a DOM element, otherwise it won't work.

2) You want to redirect after a certain action (let's say after creating an item)

In that case you can use history:

myFunction() {
  addSomeStuff(data).then(() => {
      this.props.history.push('/path')
    }).catch((error) => {
      console.log(error)
    })

or

myFunction() {
  addSomeStuff()
  this.props.history.push('/path')
}

In order to have access to history, you can wrap your component with an HOC called withRouter. When you wrap your component with it, it passes match location and history props. For more detail please have a look at the official documentation for withRouter.

If your component is a child of a <Route /> component, i.e. if it is something like <Route path='/path' component={myComponent} />, you don't have to wrap your component with withRouter, because <Route /> passes match, location, and history to its child.

3) Redirect after clicking some element

There are two options here. You can use history.push() by passing it to an onClick event:

<div onClick={this.props.history.push('/path')}> some stuff </div>

or you can use a <Link /> component:

 <Link to='/path' > some stuff </Link>

I think the rule of thumb with this case is to try to use <Link /> first, I suppose especially because of performance.

How to create Select List for Country and States/province in MVC

Designing You Model:

Public class ModelName
{
    ...// Properties
    public IEnumerable<SelectListItem> ListName { get; set; }
}

Prepare and bind List to Model in Controller :

    public ActionResult Index(ModelName model)
    {
        var items = // Your List of data
        model.ListName = items.Select(x=> new SelectListItem() {
                    Text = x.prop,
                    Value = x.prop2
               });
    }

In You View :

@Html.DropDownListFor(m => Model.prop2,Model.ListName)

Design DFA accepting binary strings divisible by a number 'n'

You can build DFA using simple modular arithmetics. We can interpret w which is a string of k-ary numbers using a following rule

V[0] = 0
V[i] = (S[i-1] * k) + to_number(str[i])

V[|w|] is a number that w is representing. If modify this rule to find w mod N, the rule becomes this.

V[0] = 0
V[i] = ((S[i-1] * k) + to_number(str[i])) mod N

and each V[i] is one of a number from 0 to N-1, which corresponds to each state in DFA. We can use this as the state transition.

See an example.

k = 2, N = 5

| V | (V*2 + 0) mod 5     | (V*2 + 1) mod 5     |
+---+---------------------+---------------------+
| 0 | (0*2 + 0) mod 5 = 0 | (0*2 + 1) mod 5 = 1 |
| 1 | (1*2 + 0) mod 5 = 2 | (1*2 + 1) mod 5 = 3 |
| 2 | (2*2 + 0) mod 5 = 4 | (2*2 + 1) mod 5 = 0 |
| 3 | (3*2 + 0) mod 5 = 1 | (3*2 + 1) mod 5 = 2 |
| 4 | (4*2 + 0) mod 5 = 3 | (4*2 + 1) mod 5 = 4 |

k = 3, N = 5

| V | 0 | 1 | 2 |
+---+---+---+---+
| 0 | 0 | 1 | 2 |
| 1 | 3 | 4 | 0 |
| 2 | 1 | 2 | 3 |
| 3 | 4 | 0 | 1 |
| 4 | 2 | 3 | 4 |

Now you can see a very simple pattern. You can actually build a DFA transition just write repeating numbers from left to right, from top to bottom, from 0 to N-1.

AngularJS - convert dates in controller

i suggest in Javascript:

var item=1387843200000;
var date1=new Date(item);

and then date1 is a Date.

Get the contents of a table row with a button click

Find element with id in row using jquery

$(document).ready(function () {
$("button").click(function() {
    //find content of different elements inside a row.
    var nameTxt = $(this).closest('tr').find('.name').text();
    var emailTxt = $(this).closest('tr').find('.email').text();
    //assign above variables text1,text2 values to other elements.
    $("#name").val( nameTxt );
    $("#email").val( emailTxt );
    });
});

How to analyze disk usage of a Docker container

(this answer is not useful, but leaving it here since some of the comments may be)

docker images will show the 'virtual size', i.e. how much in total including all the lower layers. So some double-counting if you have containers that share the same base image.

documentation

How can I print the contents of a hash in Perl?

The answer depends on what is in your hash. If you have a simple hash a simple

print map { "$_ $h{$_}\n" } keys %h;

or

print "$_ $h{$_}\n" for keys %h;

will do, but if you have a hash that is populated with references you will something that can walk those references and produce a sensible output. This walking of the references is normally called serialization. There are many modules that implement different styles, some of the more popular ones are:

Due to the fact that Data::Dumper is part of the core Perl library, it is probably the most popular; however, some of the other modules have very good things to offer.

Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' (38)

sudo service mysql start

This should serve you just fine. There could be a possibility that you changed some commands that affected the mysql configurations.

Hadoop: «ERROR : JAVA_HOME is not set»

  • hadoop ERROR : JAVA_HOME is not set

Above error is because of the space in between two words.

Eg: Java located in C:\Program Files\Java --> Space in between Program and files would cause the above problem. If you remove the space, it would not show any error.

Where do alpha testers download Google Play Android apps?

Here is a check list for you:

1) Is your app published? (Production APK is not required for publishing)

2) Did your alpha/beta testers "Accept invitation" to Google+ community or Google group?

3) Are your alpha/beta testers logged in their Google+ account?

4) Are your alpha/beta testers using your link from Google Play developer console? It has format like this: https://play.google.com/apps/testing/com.yourdomain.package

How to determine the last Row used in VBA including blank spaces in between

I use the following:

lastrow = ActiveSheet.Columns("A").Cells.Find("*", SearchOrder:=xlByRows, LookIn:=xlValues, SearchDirection:=xlPrevious).Row

It'll find the last row in a specific column. If you want the last used row for any column then:

lastrow = ActiveSheet.Cells.Find("*", SearchOrder:=xlByRows, LookIn:=xlValues, SearchDirection:=xlPrevious).Row

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

You need to read the Python Unicode HOWTO. This error is the very first example.

Basically, stop using str to convert from unicode to encoded text / bytes.

Instead, properly use .encode() to encode the string:

p.agent_info = u' '.join((agent_contact, agent_telno)).encode('utf-8').strip()

or work entirely in unicode.

Create Word Document using PHP in Linux

By far the easiest way to create DOC files on Linux, using PHP is with the Zend Framework component phpLiveDocx.

From the project web site:

"phpLiveDocx allows developers to generate documents by combining structured data from PHP with a template, created in a word processor. The resulting document can be saved as a PDF, DOCX, DOC or RTF file. The concept is the same as with mail-merge."

How to redirect to a route in laravel 5 by using href tag if I'm not using blade or any template?

In addition to @chanafdo answer, you can use route name

when working with laravel blade

<a href="{{route('login')}}">login here</a> with parameter in route name

when go to url like URI: profile/{id} <a href="{{route('profile', ['id' => 1])}}">login here</a>

without blade

<a href="<?php echo route('login')?>">login here</a>

with parameter in route name

when go to url like URI: profile/{id} <a href="<?php echo route('profile', ['id' => 1])?>">login here</a>

As of laravel 5.2 you can use @php @endphp to create as <?php ?> in laravel blade. Using blade your personal opinion but I suggest to use it. Learn it. It has many wonderful features as template inheritance, Components & Slots,subviews etc...

How to check if keras tensorflow backend is GPU or CPU version?

According to the documentation.

If you are running on the TensorFlow or CNTK backends, your code will automatically run on GPU if any available GPU is detected.

You can check what all devices are used by tensorflow by -

from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())

Also as suggested in this answer

import tensorflow as tf
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

This will print whether your tensorflow is using a CPU or a GPU backend. If you are running this command in jupyter notebook, check out the console from where you have launched the notebook.

If you are sceptic whether you have installed the tensorflow gpu version or not. You can install the gpu version via pip.

pip install tensorflow-gpu

Why cannot change checkbox color whatever I do?

Yes, you can. Based on knowledge from colleagues here and researching on web, here you have the best solution for styling a checkbox without any third-party plugin:

_x000D_
_x000D_
input[type='checkbox']{
  width: 14px !important;
  height: 14px !important;
  margin: 5px;
  -webkit-appearance: none;
  -moz-appearance: none;
  -o-appearance: none;
  appearance: none;
  outline: 1px solid gray;
  box-shadow: none;
  font-size: 0.8em;
  text-align: center;
  line-height: 1em;
  background: red;
}

input[type='checkbox']:checked:after {
  content: '?';
  color: white;
}
_x000D_
<input type='checkbox'>
_x000D_
_x000D_
_x000D_

C# int to enum conversion

It's fine just to cast your int to Foo:

int i = 1;
Foo f = (Foo)i;

If you try to cast a value that's not defined it will still work. The only harm that may come from this is in how you use the value later on.

If you really want to make sure your value is defined in the enum, you can use Enum.IsDefined:

int i = 1;
if (Enum.IsDefined(typeof(Foo), i))
{
    Foo f = (Foo)i;
}
else
{
   // Throw exception, etc.
}

However, using IsDefined costs more than just casting. Which you use depends on your implemenation. You might consider restricting user input, or handling a default case when you use the enum.

Also note that you don't have to specify that your enum inherits from int; this is the default behavior.

Is it possible to delete an object's property in PHP?

This also works if you are looping over an object.

unset($object->$key);

No need to use brackets.

How to run Selenium WebDriver test cases in Chrome

To run Selenium WebDriver test cases in Chrome, follow these steps:

  1. First of all, set the property and Chrome driver path:

    System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
    
  2. Initialize the Chrome Driver's object:

    WebDriver driver = new ChromeDriver();
    
  3. Pass the URL into the get method of WebDriver:

    driver.get("http://www.google.com");
    

Create a HTML table where each TR is a FORM

I second Harmen's div suggestion. Alternatively, you can wrap the table in a form, and use javascript to capture the row focus and adjust the form action via javascript before submit.

Obtaining only the filename when using OpenFileDialog property "FileName"

Use OpenFileDialog.SafeFileName

OpenFileDialog.SafeFileName Gets the file name and extension for the file selected in the dialog box. The file name does not include the path.

How to read embedded resource text file

For users that are using VB.Net

Imports System.IO
Imports System.Reflection

Dim reader As StreamReader
Dim ass As Assembly = Assembly.GetExecutingAssembly()
Dim sFileName = "MyApplicationName.JavaScript.js" 
Dim reader = New StreamReader(ass.GetManifestResourceStream(sFileName))
Dim sScriptText = reader.ReadToEnd()
reader.Close()

where MyApplicationName is namespace of my application. It is not the assembly name. This name is define in project's properties (Application tab).

If you don't find correct resource name, you can use GetManifestResourceNames() function

Dim resourceName() As String = ass.GetManifestResourceNames()

or

Dim sName As String 
    = ass.GetManifestResourceNames()
        .Single(Function(x) x.EndsWith("JavaScript.js"))

or

Dim sNameList 
    = ass.GetManifestResourceNames()
        .Where(Function(x As String) x.EndsWith(".js"))

Git: which is the default configured remote for branch?

You can do it more simply, guaranteeing that your .gitconfig is left in a meaningful state:

Using Git version v1.8.0 and above

git push -u hub master when pushing, or:
git branch -u hub/master

OR

(This will set the remote for the currently checked-out branch to hub/master)
git branch --set-upstream-to hub/master

OR

(This will set the remote for the branch named branch_name to hub/master)
git branch branch_name --set-upstream-to hub/master

If you're using v1.7.x or earlier

you must use --set-upstream:
git branch --set-upstream master hub/master

This project references NuGet package(s) that are missing on this computer

Removed below lines in .csproj file

<Import Project="$(SolutionDir)\.nuget\NuGet.targets" 
Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
 <ErrorText>This project references NuGet package(s) that are missing on this computer. 
 Enable NuGet Package Restore to download them.  For more information, see 
 http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" 
Text="$([System.String]::Format('$(ErrorText)', 
'$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>

Composer: Command Not Found

This is for mac or ubuntu user, try this on terminal

curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer

SSH Port forwarding in a ~/.ssh/config file?

You can use the LocalForward directive in your host yam section of ~/.ssh/config:

LocalForward 5901 computer.myHost.edu:5901

SET NAMES utf8 in MySQL?

From the manual:

SET NAMES indicates what character set the client will use to send SQL statements to the server.

More elaborately, (and once again, gratuitously lifted from the manual):

SET NAMES indicates what character set the client will use to send SQL statements to the server. Thus, SET NAMES 'cp1251' tells the server, “future incoming messages from this client are in character set cp1251.” It also specifies the character set that the server should use for sending results back to the client. (For example, it indicates what character set to use for column values if you use a SELECT statement.)

How can I make IntelliJ IDEA update my dependencies from Maven?

IntelliJ IDEA 2016

Import Maven projects automatically

Approach 1

  • File > Settings... > Build, Execution, Deployment > Build Tools > Maven > Importing > check Import Maven projects automatically

    Import Maven projects automatically

Approach 2

  • press Ctrl + Shift + A > type "Import Maven" > choose "Import Maven projects automatically" and press Enter > check Import Maven projects automatically

Reimport

Approach 1

  • In Project view, right click on your project folder > Maven > Reimport

Approach 2

  • View > Tools Windows > Maven Projects:

    • right click on your project > Reimport

    or

    • click on the "Reimport All Maven Projects" icon:

      Reimport All Maven Projects

How to send email from MySQL 5.1

I would be very concerned about putting the load of sending e-mails on my database server (small though it may be). I might suggest one of these alternatives:

  1. Have application logic detect the need to send an e-mail and send it.
  2. Have a MySQL trigger populate a table that queues up the e-mails to be sent and have a process monitor that table and send the e-mails.

What is a MIME type?

MIME stands for Multipurpose Internet Mail Extensions. It's a way of identifying files on the Internet according to their nature and format.

For example, using the Content-type header value defined in a HTTP response, the browser can open the file with the proper extension/plugin.

Internet Media Type (also Content-type) is the same as a MIME type. MIME types were originally created for emails sent using the SMTP protocol. Nowadays, this standard is used in a lot of other protocols, hence the new naming convention "Internet Media Type".

A MIME type is a string identifier composed of two parts: a type and a subtype.

  • The "type" refers to a logical grouping of many MIME types that are closely related to each other; it's no more than a high level category.
  • "subtypes" are specific to one file type within the "type".

The x- prefix of a MIME subtype simply means that it's non-standard.
The vnd prefix means that the MIME value is vendor specific.

Source

Is there an easy way to convert jquery code to javascript?

I can see a reason, unrelated to the original post, to automatically compile jQuery code into standard JavaScript:

16k -- or whatever the gzipped, minified jQuery library is -- might be too much for your website that is intended for a mobile browser. The w3c is recommending that all HTTP requests for mobile websites should be a maximum of 20k.

w3c specs for mobile

So I enjoy coding in my nice, terse, chained jQuery. But now I need to optimize for mobile. Should I really go back and do the difficult, tedious work of rewriting all the helper functions I used in the jQuery library? Or is there some kind of convenient app that will help me recompile?

That would be very sweet. Sadly, I don't think such a thing exists.

How to set .net Framework 4.5 version in IIS 7 application pool

There is no 4.5 application pool. You can use any 4.5 application in 4.0 app pool. The .NET 4.5 is "just" an in-place-update not a major new version.

Node.js: How to read a stream into a buffer?

You can easily do this using node-fetch if you are pulling from http(s) URIs.

From the readme:

fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png')
    .then(res => res.buffer())
    .then(buffer => console.log)

Removing a model in rails (reverse of "rails g model Title...")

Try this

rails destroy model Rating

It will remove model, migration, tests and fixtures

Find Nth occurrence of a character in a string

string theString = "The String";
int index = theString.NthIndexOf("THEVALUE", 3, true);

Creating .pem file for APNS?

NOTE: You must have the Team Agent or Admin role in App Store Connect to perform any of these tasks. If you are not part of a Team in App Store Connect this probably does not affect you.

Sending push notifications to an iOS application requires creating encyption keys. In the past this was a cumbersome process that used SSL keys and certificates. Each SSL certificate was specific to a single iOS application. In 2016 Apple introduced a new authentication key mechanism that is more reliable and easier to use. The new authentication keys are more flexible, simple to maintain and apply to more than on iOS app.

Even though it has been years since authentication keys were introduced not every service supports them. FireBase and Amazon Pinpoint support authentication keys. Amazon SNS, Urban Airship, Twilio, and LeanPlum do not. Many open source software packages do not yet support authentication keys.

To create the required SSL certificate and export it as PEM file containing public and private keys:

  1. Navigate to Certificates, Identifiers & Profiles
  2. Create or Edit Your App ID.
  3. Enable Push Notifications for the App ID
  4. Add an SSL Certificate to the App ID
  5. Convert the certificate to PEM format

If you already have the SSL certificate set up for the app in the Apple Developer Center website you can skip ahead to Convert the certificate to PEM format. Keep in mind that you will run into problems if you do not also have the private key that was generated on the Mac that created the signing request that was uploaded to Apple.

Read on to see how to avoid losing track of that private key.

Navigate to Certificates, Identifiers & Profiles

Xcode does not control certificates or keys for push notifications. To create keys and enable push notifications for an app you must go to the Apple Developer Center website. The Certificates, Identifiers & Profiles section of your account controls App IDs and certificates.

To access certificates and profiles you must either have a paid Apple Developer Program membership or be part of a Team that does.

  1. Log into the Apple Developer website enter image description here
  2. Go to Account, then Certificates, Identifiers & Profiles enter image description here

Create an App ID

Apps that use push notifications can not use wildcard App IDs or provisioning profiles. Each app requires you to set up an App ID record in the Apple Developer Center portal to enable push notifications.

  1. Go to App IDs under Identifiers
  2. Search for your app using the bundle identifier. It may already exist.
  3. If there is no existing App ID for the app click the (+) button to create it.
  4. Select Explicit App ID in the App ID Suffix section. enter image description here
  5. Enter the bundle identifier for the app.
  6. Scroll to the bottom and enable Push Notifications. enter image description here
  7. Click Continue.
  8. On the next screen click Register to complete creating the App ID. enter image description here

Enable Push Notifications for the App ID

  1. Go to App IDs under Identifiers
  2. Click on the App ID to see details and scroll to the bottom. enter image description here
  3. Click Edit enter image description here
  4. In the App ID Settings screen scroll down to Push Notifications enter image description here
  5. Select the checkbox to enable push notifications. enter image description here

Creating SSL certificates for push notifications is a process of several tasks. Each task has several steps. All of these are necessary to export the keys in P12 or PEM format. Review the steps before proceeding.

Add an SSL Certificate to the App ID

  1. Under Development SSL Certificate click Create Certificate. You will need to do this later for production as well.
  2. Apple will ask you to create a Certificate Signing Request enter image description here

To create a certificate you will need to make a Certificate Signing Request (CSR) on a Mac and upload it to Apple.

Later if you need to export this certificate as a pkcs12 (aka p12) file you will need to use the keychain from the same Mac. When the signing request is created Keychain Access generates a set of keys in the default keychain. These keys are necessary for working with the certificate Apple will create from the signing request.

It is a good practice to have a separate keychain specifically for credentials used for development. If you do this make sure this keychain is set to be the default before using Certificate Assistant.

Create a Keychain for Development Credentials

  1. Open Keychain Access on your Mac
  2. In the File menu select New Keychain...
  3. Give your keychain a descriptive name, like "Shared Development" or the name of your application

Create a Certificate Signing Request (CSR)

When creating the Certificate Signing Request the Certificate Assistant generates two encryption keys in the default keychain. It is important to make the development keychain the default so the keys are in the right keychain.

  1. Open Keychain Access on your Mac.
  2. Control-click on the development keychain in the list of keychains
  3. Select Make keychain "Shared Development" Default enter image description here
  4. From the Keychain Access menu select Certificate Assistant, then Request a Certificate From a Certificate Authority... from the sub menu. enter image description here
  5. When the Certificate Assistant appears check Saved To Disk. enter image description here
  6. Enter the email address associated with your Apple Developer Program membership in the User Email Address field.
  7. Enter a name for the key in the Common Name field. It is a good idea to use the bundle ID of the app as part of the common name. This makes it easy to tell what certificates and keys belong to which app.
  8. Click continue. Certificate Assistant will prompt to save the signing request to a file.
  9. In Keychain Access make the "login" keychain the default again.

Creating the signing request generated a pair of keys. Before the signing request is uploaded verify that the development keychain has the keys. Their names will be the same as the Common Name used in the signing request.

enter image description here

Upload the Certificate Signing Request (CSR)

Once the Certicate Signing Request is created upload it to the Apple Developer Center. Apple will create the push notification certificate from the signing request.

  1. Upload the Certificate Signing Request
  2. Download the certificate Apple has created from the Certificate Signing Request enter image description here
  3. In Keychain Access select the development keychain from the list of keychains
  4. From the File menu select Import Items... enter image description here
  5. Import the certificate file downloaded from Apple

Your development keychain should now show the push certificate with a private key under My Certificates in Keychain Access:

enter image description here

At this point the development keychain should be backed up. Many teams keep their push certificates on secure USB drives, commit to internal version control or use a backup solution like Time Machine. The development keychain can be shared between different team members because it does not contain any personal code signing credentials.

Keychain files are located in ~/Library/Keychains.

Some third party push services require certificates in Privacy Enhanced Mail (PEM) format, while others require Public-Key Cryptography Standards #12 (PKCS12 or P12). The certificate downloaded from Apple can be used to export certificates in these formats - but only if you have kept the private key.

Convert the certificate to PEM format

  1. In Keychain Access select the development keychain created earlier.
  2. Select the push certificate in My Certificates. There should be a private key with it. ![Download CER push certificate](keychain/import complete.png)
  3. From the File menu select Export Items... enter image description here
  4. In the save panel that opens, select Privacy Enhanced Mail (.pem) as the file format.
  5. Save the file

Creating and throwing new exception

You can throw your own custom errors by extending the Exception class.

class CustomException : Exception {
    [string] $additionalData

    CustomException($Message, $additionalData) : base($Message) {
        $this.additionalData = $additionalData
    }
}

try {
    throw [CustomException]::new('Error message', 'Extra data')
} catch [CustomException] {
    # NOTE: To access your custom exception you must use $_.Exception
    Write-Output $_.Exception.additionalData

    # This will produce the error message: Didn't catch it the second time
    throw [CustomException]::new("Didn't catch it the second time", 'Extra data')
}

Specifying onClick event type with Typescript and React.Konva

As posted in my update above, a potential solution would be to use Declaration Merging as suggested by @Tyler-sebastion. I was able to define two additional interfaces and add the index property on the EventTarget in this way.

interface KonvaTextEventTarget extends EventTarget {
  index: number
}

interface KonvaMouseEvent extends React.MouseEvent<HTMLElement> {
  target: KonvaTextEventTarget
}

I then can declare the event as KonvaMouseEvent in my onclick MouseEventHandler function.

onClick={(event: KonvaMouseEvent) => {
          makeMove(ownMark, event.target.index)
}}

I'm still not 100% if this is the best approach as it feels a bit Kludgy and overly verbose just to get past the tslint error.

How to set width to 100% in WPF

It is the container of the Grid that is imposing on its width. In this case, that's a ListBoxItem, which is left-aligned by default. You can set it to stretch as follows:

<ListBox>
    <!-- other XAML omitted, you just need to add the following bit -->
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="HorizontalAlignment" Value="Stretch"/>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

What is the "N+1 selects problem" in ORM (Object-Relational Mapping)?

Take Matt Solnit example, imagine that you define an association between Car and Wheels as LAZY and you need some Wheels fields. This means that after the first select, hibernate is going to do "Select * from Wheels where car_id = :id" FOR EACH Car.

This makes the first select and more 1 select by each N car, that's why it's called n+1 problem.

To avoid this, make the association fetch as eager, so that hibernate loads data with a join.

But attention, if many times you don't access associated Wheels, it's better to keep it LAZY or change fetch type with Criteria.

Calculating the area under a curve given a set of coordinates, without knowing the function

The numpy and scipy libraries include the composite trapezoidal (numpy.trapz) and Simpson's (scipy.integrate.simps) rules.

Here's a simple example. In both trapz and simps, the argument dx=5 indicates that the spacing of the data along the x axis is 5 units.

from __future__ import print_function

import numpy as np
from scipy.integrate import simps
from numpy import trapz


# The y values.  A numpy array is used here,
# but a python list could also be used.
y = np.array([5, 20, 4, 18, 19, 18, 7, 4])

# Compute the area using the composite trapezoidal rule.
area = trapz(y, dx=5)
print("area =", area)

# Compute the area using the composite Simpson's rule.
area = simps(y, dx=5)
print("area =", area)

Output:

area = 452.5
area = 460.0

XSS prevention in JSP/Servlet web application

My personal opinion is that you should avoid using JSP/ASP/PHP/etc pages. Instead output to an API similar to SAX (only designed for calling rather than handling). That way there is a single layer that has to create well formed output.

How to use jQuery to select a dropdown option?

The solution:

$("#element-id").val('the value of the option');

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip

You need to add the package containing the executable pg_config.

A prior answer should have details you need: pg_config executable not found

How to get all properties values of a JavaScript Object (without knowing the keys)?

If you have access to Underscore.js, you can use the _.values function like this:

_.values({one : 1, two : 2, three : 3}); // return [1, 2, 3]

Rename package in Android Studio

  • The first part consists of creating a new package under java folder and selecting then dragging all your source files from the old package to this new package. After that you need to remane the package name in android manifest to the name of the new package.

  • In step 2, here is what you need to do.You need to change the old package name in applicationId under the module build.gradle in your android studio in addition to changing the package name in the manifest. So in summary, click on build.gradle which is below the "AndroidManifest.xml" and modify the value of applicationId to your new package name.

  • Then, at the very top, under build. clean your project, then rebuild. It should be fine from here.

How are environment variables used in Jenkins with Windows Batch Command?

I should this On Windows, environment variable expansion is %BUILD_NUMBER%

Django MEDIA_URL and MEDIA_ROOT

This is what I did to achieve image rendering in DEBUG = False mode in Python 3.6 with Django 1.11

from django.views.static import serve
urlpatterns = [
url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),
# other paths
]

How to encrypt String in Java

I would consider using something like https://www.bouncycastle.org/ It is a prebuilt library that allows you to encrypt whatever you like with a number of different Ciphers I understand that you only want to protect from snooping, but if you really want to protect the information, using Base64 won't actually protect you.

How to close activity and go back to previous activity in android

We encountered a very similar situation.

Activity 1 (Opening) -> Activity 2 (Preview) -> Activity 3 (Detail)

Incorrect "on back press" Response

  • Device back press on Activity 3 will also close Activity 2.

I have checked all answers posted above and none of them worked. Java syntax for transition between Activity 2 and Activity 3 was reviewed to be correct.

Fresh from coding on calling out a 3rd party app. by an Activity. We decided to investigate the configuration angle - eventually enabling us to identify the root cause of the problem.

Scope: Configuration of Activity 2 (caller).

Root Cause:

android:launchMode="singleInstance"

Solution:

android:launchMode="singleTask"

Apparently on this "on back press" issue singleInstance considers invoked Activities in one instance with the calling Activity, whereas singleTask will allow for invoked Activities having their own identity enough for the intended on back press to function to work as it should to.

How can I find last row that contains data in a specific column?

Function LastRow(rng As Range) As Long
    Dim iRowN As Long
    Dim iRowI As Long
    Dim iColN As Integer
    Dim iColI As Integer
    iRowN = 0
    iColN = rng.Columns.count
    For iColI = 1 To iColN
        iRowI = rng.Columns(iColI).Offset(65536 - rng.Row, 0).End(xlUp).Row
        If iRowI > iRowN Then iRowN = iRowI
    Next
    LastRow = iRowN
End Function 

PHP add elements to multidimensional array with array_push

if you want to add the data in the increment order inside your associative array you can do this:

$newdata =  array (
      'wpseo_title' => 'test',
      'wpseo_desc' => 'test',
      'wpseo_metakey' => 'test'
    );

// for recipe

$md_array["recipe_type"][] = $newdata;

//for cuisine

 $md_array["cuisine"][] = $newdata;

this will get added to the recipe or cuisine depending on what was the last index.

Array push is usually used in the array when you have sequential index: $arr[0] , $ar[1].. you cannot use it in associative array directly. But since your sub array is had this kind of index you can still use it like this

array_push($md_array["cuisine"],$newdata);

How to upload images into MySQL database using PHP code

This is the perfect code for uploading and displaying image through MySQL database.

<html>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit" name="submit" value="Upload"/>
</form>
<?php
    if(isset($_POST['submit']))
    {
     if(getimagesize($_FILES['image']['tmp_name'])==FALSE)
     {
        echo " error ";
     }
     else
     {
        $image = $_FILES['image']['tmp_name'];
        $image = addslashes(file_get_contents($image));
        saveimage($image);
     }
    }
    function saveimage($image)
    {
        $dbcon=mysqli_connect('localhost','root','','dbname');
        $qry="insert into tablename (name) values ('$image')";
        $result=mysqli_query($dbcon,$qry);
        if($result)
        {
            echo " <br/>Image uploaded.";
            header('location:urlofpage.php');
        }
        else
        {
            echo " error ";
        }
    }
?>
</body>
</html>

Splitting on last delimiter in Python string?

You can use rsplit

string.rsplit('delimeter',1)[1]

To get the string from reverse.

How to convert an entire MySQL database characterset and collation to UTF-8?

In case the data is not in the same character set you might consider this snippet from http://dev.mysql.com/doc/refman/5.0/en/charset-conversion.html

If the column has a nonbinary data type (CHAR, VARCHAR, TEXT), its contents should be encoded in the column character set, not some other character set. If the contents are encoded in a different character set, you can convert the column to use a binary data type first, and then to a nonbinary column with the desired character set.

Here is an example:

 ALTER TABLE t1 CHANGE c1 c1 BLOB;
 ALTER TABLE t1 CHANGE c1 c1 VARCHAR(100) CHARACTER SET utf8;

Make sure to choose the right collation, or you might get unique key conflicts. e.g. Éleanore and Eleanore might be considered the same in some collations.

Aside:

I had a situation where certain characters "broke" in emails even though they were stored as UTF-8 in the database. If you are sending emails using utf8 data, you might want to also convert your emails to send in UTF8.

In PHPMailer, just update this line: public $CharSet = 'utf-8';

What's the difference between & and && in MATLAB?

The single ampersand & is the logical AND operator. The double ampersand && is again a logical AND operator that employs short-circuiting behaviour. Short-circuiting just means the second operand (right hand side) is evaluated only when the result is not fully determined by the first operand (left hand side)

A & B (A and B are evaluated)

A && B (B is only evaluated if A is true)

Can you delete data from influxdb?

You can only delete with your time field, which is a number.

Delete from <measurement> where time=123456

will work. Remember not to give single quotes or double quotes. Its a number.

Why won't bundler install JSON gem?

To solve this problem, simply run:

bundle update

It will update the version of your bundler. Then run:

bundle install

Your problem will get solve. Solution is well explained here.

Fastest way to check a string contain another substring in JavaScript?

It's easy way to use .match() method to string.

var re = /(AND|OR|MAYBE)/;
var str = "IT'S MAYBE BETTER WAY TO USE .MATCH() METHOD TO STRING";
console.log('Do we found something?', Boolean(str.match(re)));

Wish you a nice day, sir!

How to manage exceptions thrown in filters in Spring?

You can use the following method inside the catch block:

response.sendError(HttpStatus.UNAUTHORIZED.value(), "Invalid token")

Notice that you can use any HttpStatus code and a custom message.

Plotting multiple lines, in different colors, with pandas dataframe

Another simple way is to use the pivot function to format the data as you need first.

df.plot() does the rest

df = pd.DataFrame([
    ['red', 0, 0],
    ['red', 1, 1],
    ['red', 2, 2],
    ['red', 3, 3],
    ['red', 4, 4],
    ['red', 5, 5],
    ['red', 6, 6],
    ['red', 7, 7],
    ['red', 8, 8],
    ['red', 9, 9],
    ['blue', 0, 0],
    ['blue', 1, 1],
    ['blue', 2, 4],
    ['blue', 3, 9],
    ['blue', 4, 16],
    ['blue', 5, 25],
    ['blue', 6, 36],
    ['blue', 7, 49],
    ['blue', 8, 64],
    ['blue', 9, 81],
], columns=['color', 'x', 'y'])

df = df.pivot(index='x', columns='color', values='y')

df.plot()

result

pivot effectively turns the data into:

enter image description here

How to count frequency of characters in a string?

You can use a Multiset (from guava). It will give you the count for each object. For example:

Multiset<Character> chars = HashMultiset.create();
for (int i = 0; i < string.length(); i++) {
    chars.add(string.charAt(i));
}

Then for each character you can call chars.count('a') and it returns the number of occurrences

Get form data in ReactJS

Use the change events on the inputs to update the component's state and access it in handleLogin:

handleEmailChange: function(e) {
   this.setState({email: e.target.value});
},
handlePasswordChange: function(e) {
   this.setState({password: e.target.value});
},
render : function() {
      return (
        <form>
          <input type="text" name="email" placeholder="Email" value={this.state.email} onChange={this.handleEmailChange} />
          <input type="password" name="password" placeholder="Password" value={this.state.password} onChange={this.handlePasswordChange}/>
          <button type="button" onClick={this.handleLogin}>Login</button>
        </form>);
},
handleLogin: function() {
    console.log("EMail: " + this.state.email);
    console.log("Password: " + this.state.password);
}

Working fiddle.

Also, read the docs, there is a whole section dedicated to form handling: Forms

Previously you could also use React's two-way databinding helper mixin to achieve the same thing, but now it's deprecated in favor of setting the value and change handler (as above):

var ExampleForm = React.createClass({
  mixins: [React.addons.LinkedStateMixin],
  getInitialState: function() {
    return {email: '', password: ''};
  },
  handleLogin: function() {
    console.log("EMail: " + this.state.email);
    console.log("Password: " + this.state.password);
  },
  render: function() {
    return (
      <form>
        <input type="text" valueLink={this.linkState('email')} />
        <input type="password" valueLink={this.linkState('password')} />
        <button type="button" onClick={this.handleLogin}>Login</button>
      </form>
    );
  }
});

Documentation is here: Two-way Binding Helpers.

Why can't I reference System.ComponentModel.DataAnnotations?

If using .NET Core or .NET Standard

use:

Manage NuGet Packages..

Use Manage NuGet Packages

instead of:

Add Reference...

Don't use Add Reference

How can I read pdf in python?

You can USE PyPDF2 package

#install pyDF2
pip install PyPDF2

# importing all the required modules
import PyPDF2

# creating an object 
file = open('example.pdf', 'rb')

# creating a pdf reader object
fileReader = PyPDF2.PdfFileReader(file)

# print the number of pages in pdf file
print(fileReader.numPages)

Follow this Documentation http://pythonhosted.org/PyPDF2/

Plot size and resolution with R markdown, knitr, pandoc, beamer

Figure sizes are specified in inches and can be included as a global option of the document output format. For example:

---
title: "My Document"
output:
  html_document:
    fig_width: 6
    fig_height: 4
---

And the plot's size in the graphic device can be increased at the chunk level:

```{r, fig.width=14, fig.height=12}          #Expand the plot width to 14 inches

ggplot(aes(x=mycolumn1, y=mycolumn2)) +     #specify the x and y aesthetic
geom_line(size=2) +                         #makes the line thicker
theme_grey(base_size = 25)                  #increases the size of the font
```

You can also use the out.width and out.height arguments to directly define the size of the plot in the output file:

```{r, out.width="200px", out.height="200px"} #Expand the plot width to 200 pixels

ggplot(aes(x=mycolumn1, y=mycolumn2)) +     #specify the x and y aesthetic
geom_line(size=2) +                         #makes the line thicker
theme_grey(base_size = 25)                  #increases the size of the font
```

Set margins in a LinearLayout programmatically

Try this:

MarginLayoutParams params = (MarginLayoutParams) view.getLayoutParams();
params.width = 250;
params.leftMargin = 50;
params.topMargin = 50;

How to center canvas in html5

Add text-align: center; to the parent tag of <canvas>. That's it.

Example:

<div style="text-align: center">
    <canvas width="300" height="300">
        <!--your canvas code -->
    </canvas>
</div>

Histogram using gnuplot?

Be very careful: all of the answers on this page are implicitly taking the decision of where the binning starts - the left-hand edge of the left-most bin, if you like - out of the user's hands. If the user is combining any of these functions for binning data with his/her own decision about where binning starts (as is done on the blog which is linked to above) the functions above are all incorrect. With an arbitrary starting point for binning 'Min', the correct function is:

bin(x) = width*(floor((x-Min)/width)+0.5) + Min

You can see why this is correct sequentially (it helps to draw a few bins and a point somewhere in one of them). Subtract Min from your data point to see how far into the binning range it is. Then divide by binwidth so that you're effectively working in units of 'bins'. Then 'floor' the result to go to the left-hand edge of that bin, add 0.5 to go to the middle of the bin, multiply by the width so that you're no longer working in units of bins but in an absolute scale again, then finally add back on the Min offset you subtracted at the start.

Consider this function in action:

Min = 0.25 # where binning starts
Max = 2.25 # where binning ends
n = 2 # the number of bins
width = (Max-Min)/n # binwidth; evaluates to 1.0
bin(x) = width*(floor((x-Min)/width)+0.5) + Min

e.g. the value 1.1 truly falls in the left bin:

  • this function correctly maps it to the centre of the left bin (0.75);
  • Born2Smile's answer, bin(x)=width*floor(x/width), incorrectly maps it to 1;
  • mas90's answer, bin(x)=width*floor(x/width) + binwidth/2.0, incorrectly maps it to 1.5.

Born2Smile's answer is only correct if the bin boundaries occur at (n+0.5)*binwidth (where n runs over integers). mas90's answer is only correct if the bin boundaries occur at n*binwidth.