Programs & Examples On #Filereference

A file reference is an object that allows programs to refer to files on a file system, and operate on them. Browser-based applications (e.g. JavaScript and ActionScript) need them to save and upload files to / from the user's file system because all file system interaction is policed by the browser itself.

How to check if curl is enabled or disabled

you can check by putting these code in php file.

<?php
if(in_array  ('curl', get_loaded_extensions())) {
    echo "CURL is available on your web server";
}
else{
    echo "CURL is not available on your web server";
}

OR

var_dump(extension_loaded('curl'));

PHP regular expressions: No ending delimiter '^' found in

You can use T-Regx library, that doesn't need delimiters

pattern('^([0-9]+)$')->match($input);

Maven - Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.4.1:clean

you may need to check whether the settings.xml file is correct. such as user name, password, third party url.

Whether a variable is undefined

http://constc.blogspot.com/2008/07/undeclared-undefined-null-in-javascript.html

Depends on how specific you want the test to be. You could maybe get away with

if(page_name){ string += "&page_name=" + page_name; }

How do I run two commands in one line in Windows CMD?

& is the Bash equivalent for ; ( run commands) and && is the Bash equivalent of && (run commands only when the previous has not caused an error).

Extract month and year from a zoo::yearmon object

Use the format() method for objects of class "yearmon". Here is your example date (properly created!)

date1 <- as.yearmon("Mar 2012", "%b %Y")

Then we can extract the date parts as required:

> format(date1, "%b") ## Month, char, abbreviated
[1] "Mar"
> format(date1, "%Y") ## Year with century
[1] "2012"
> format(date1, "%m") ## numeric month
[1] "03"

These are returned as characters. Where appropriate, wrap in as.numeric() if you want the year or numeric month as a numeric variable, e.g.

> as.numeric(format(date1, "%m"))
[1] 3
> as.numeric(format(date1, "%Y"))
[1] 2012

See ?yearmon and ?strftime for details - the latter explains the placeholder characters you can use.

.ssh directory not being created

As a slight improvement over the other answers, you can do the mkdir and chmod as a single operation using mkdir's -m switch.

$ mkdir -m 700 ${HOME}/.ssh

Usage

From a Linux system

$ mkdir --help
Usage: mkdir [OPTION]... DIRECTORY...
Create the DIRECTORY(ies), if they do not already exist.

Mandatory arguments to long options are mandatory for short options too.
  -m, --mode=MODE   set file mode (as in chmod), not a=rwx - umask
...
...

Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

Intro: There are the (probably) best solutions. But you have to know it and remember it and sometimes you have to hope that your Python version isn't too old or whatever the issue could be.

Then there are the most 'hacky' solutions. They are great and short but sometimes are hard to understand, to read and to remember.

There is, though, an alternative which is to to try to reinvent the wheel. - Why reinventing the wheel? - Generally because it's a really good way to learn (and sometimes just because the already-existing tool doesn't do exactly what you would like and/or the way you would like it) and the easiest way if you don't know or don't remember the perfect tool for your problem.

So, I propose to reinvent the wheel of the Counter class from the collections module (partially at least):

class MyDict(dict):
    def __add__(self, oth):
        r = self.copy()

        try:
            for key, val in oth.items():
                if key in r:
                    r[key] += val  # You can custom it here
                else:
                    r[key] = val
        except AttributeError:  # In case oth isn't a dict
            return NotImplemented  # The convention when a case isn't handled

        return r

a = MyDict({'a':1, 'b':2, 'c':3})
b = MyDict({'b':3, 'c':4, 'd':5})

print(a+b)  # Output {'a':1, 'b': 5, 'c': 7, 'd': 5}

There would probably others way to implement that and there are already tools to do that but it's always nice to visualize how things would basically works.

Printing the last column of a line in a file

One way using awk:

tail -f file.txt | awk '/A1/ { print $NF }'

ThreadStart with parameters

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ConsoleApp6
{
    class Program
    {
        static void Main(string[] args)
        {

            int x = 10;
            Thread t1 =new Thread(new ParameterizedThreadStart(order1));
            t1.IsBackground = true;//i can stope 
            t1.Start(x);

            Thread t2=new Thread(order2);
            t2.Priority = ThreadPriority.Highest;
            t2.Start();

            Console.ReadKey();
        }//Main

        static void  order1(object args)
        {
            int x = (int)args;


                for (int i = 0; i < x; i++)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.Write(i.ToString() + " ");
            }
        }

        static void order2()
        {
            for (int i = 100; i > 0; i--)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Write(i.ToString() + " ");
            }
        }`enter code here`
    }
}

How to call multiple JavaScript functions in onclick event?

I would use the element.addEventListener method to link it to a function. From that function you can call multiple functions.

The advantage I see in binding an event to a single function and then calling multiple functions is that you can perform some error checking, have some if else statements so that some functions only get called if certain criteria are met.

In C/C++ what's the simplest way to reverse the order of bits in a byte?

How about this one...

int value = 0xFACE;

value = ((0xFF & value << 8) | (val >> 8);

Compare two List<T> objects for equality, ignoring order

This worked for me:
If you are comparing two lists of objects depend upon single entity like ID, and you want a third list which matches that condition, then you can do the following:

var list3 = List1.Where(n => !List2.select(n1 => n1.Id).Contains(n.Id));

Refer: MSDN - C# Compare Two lists of objects

Docker: Multiple Dockerfiles in project

Use docker-compose and multiple Dockerfile in separate directories

Don't rename your Dockerfile to Dockerfile.db or Dockerfile.web, it may not be supported by your IDE and you will lose syntax highlighting.

As Kingsley Uchnor said, you can have multiple Dockerfile, one per directory, which represent something you want to build.

I like to have a docker folder which holds each applications and their configuration. Here's an example project folder hierarchy for a web application that has a database.

docker-compose.yml
docker
+-- web
¦   +-- Dockerfile
+-- db
    +-- Dockerfile

docker-compose.yml example:

version: '3'
services:
  web:
    # will build ./docker/web/Dockerfile
    build: ./docker/web
    ports:
     - "5000:5000"
    volumes:
     - .:/code
  db:
    # will build ./docker/db/Dockerfile
    build: ./docker/db
    ports:
      - "3306:3306"
  redis:
    # will use docker hub's redis prebuilt image from here:
    # https://hub.docker.com/_/redis/
    image: "redis:alpine"

docker-compose command line usage example:

# The following command will create and start all containers in the background
# using docker-compose.yml from current directory
docker-compose up -d

# get help
docker-compose --help

In case you need files from previous folders when building your Dockerfile

You can still use the above solution and place your Dockerfile in a directory such as docker/web/Dockerfile, all you need is to set the build context in your docker-compose.yml like this:

version: '3'
services:
  web:
    build:
      context: .
      dockerfile: ./docker/web/Dockerfile
    ports:
     - "5000:5000"
    volumes:
     - .:/code

This way, you'll be able to have things like this:

config-on-root.ini
docker-compose.yml
docker
+-- web
    +-- Dockerfile
    +-- some-other-config.ini

and a ./docker/web/Dockerfile like this:

FROM alpine:latest

COPY config-on-root.ini /
COPY docker/web/some-other-config.ini /

Here are some quick commands from tldr docker-compose. Make sure you refer to official documentation for more details.

Difference between FetchType LAZY and EAGER in Java Persistence API?

public enum FetchType extends java.lang.Enum Defines strategies for fetching data from the database. The EAGER strategy is a requirement on the persistence provider runtime that data must be eagerly fetched. The LAZY strategy is a hint to the persistence provider runtime that data should be fetched lazily when it is first accessed. The implementation is permitted to eagerly fetch data for which the LAZY strategy hint has been specified. Example: @Basic(fetch=LAZY) protected String getName() { return name; }

Source

Disable/enable an input with jQuery?

    // Disable #x
    $( "#x" ).prop( "disabled", true );
    // Enable #x
    $( "#x" ).prop( "disabled", false );

Sometimes you need to disable/enable the form element like input or textarea. Jquery helps you to easily make this with setting disabled attribute to "disabled". For e.g.:

  //To disable 
  $('.someElement').attr('disabled', 'disabled');

To enable disabled element you need to remove "disabled" attribute from this element or empty it's string. For e.g:

//To enable 
$('.someElement').removeAttr('disabled');

// OR you can set attr to "" 
$('.someElement').attr('disabled', '');

refer :http://garmoncheg.blogspot.fr/2011/07/how-to-disableenable-element-with.html

How do I convert special UTF-8 chars to their iso-8859-1 equivalent using javascript?

There are libraries that do charset conversion in Javascript. But if you want something simple, this function does approximately what you want:

function stringToBytes(text) {
  const length = text.length;
  const result = new Uint8Array(length);
  for (let i = 0; i < length; i++) {
    const code = text.charCodeAt(i);
    const byte = code > 255 ? 32 : code;
    result[i] = byte;
  }
  return result;
}

If you want to convert the resulting byte array into a Blob, you would do something like this:

const originalString = 'ååå';
const bytes = stringToBytes(originalString);
const blob = new Blob([bytes.buffer], { type: 'text/plain; charset=ISO-8859-1' });

Now, keep in mind that some apps do accept UTF-8 encoding, but they can't guess the encoding unless you prepend a BOM character, as explained here.

Run a task every x-minutes with Windows Task Scheduler

Hourly task example

While taking the advice above with schtasks, you can see in the UI what must be done to perform an hourly task. When you edit trigger begin the task on a schedule, One Time (this is the key). Then you can select "Repeat task every:" 1 hour or whatever you wish. See screenshot:

How to determine the encoding of text?

If you know the some content of the file you can try to decode it with several encoding and see which is missing. In general there is no way since a text file is a text file and those are stupid ;)

Aligning a float:left div to center?

use display:inline-block; instead of float

you can't centre floats, but inline-blocks centre as if they were text, so on the outer overall container of your "row" - you would set text-align: center; then for each image/caption container (it's those which would be inline-block;) you can re-align the text to left if you require

SQL INSERT INTO from multiple tables

You only need one INSERT:

INSERT INTO table4 ( name, age, sex, city, id, number, nationality)
SELECT name, age, sex, city, p.id, number, n.nationality
FROM table1 p
INNER JOIN table2 c ON c.Id = p.Id
INNER JOIN table3 n ON p.Id = n.Id

How can I disable a specific LI element inside a UL?

I usualy use <li> to include <a> link. I disabled click action writing like this; You may not include <a> link, then you will ignore my post.

_x000D_
_x000D_
a.noclick       {_x000D_
  pointer-events: none;_x000D_
}
_x000D_
<a class="noclick" href="#">this is disabled</a>
_x000D_
_x000D_
_x000D_

How to delete duplicate rows in SQL Server?

Without using CTE and ROW_NUMBER() you can just delete the records just by using group by with MAX function here is and example

DELETE
FROM MyDuplicateTable
WHERE ID NOT IN
(
SELECT MAX(ID)
FROM MyDuplicateTable
GROUP BY DuplicateColumn1, DuplicateColumn2, DuplicateColumn3)

How to get a shell environment variable in a makefile?

for those who want some official document to confirm the behavior

Variables in make can come from the environment in which make is run. Every environment variable that make sees when it starts up is transformed into a make variable with the same name and value. However, an explicit assignment in the makefile, or with a command argument, overrides the environment. (If the ‘-e’ flag is specified, then values from the environment override assignments in the makefile.

https://www.gnu.org/software/make/manual/html_node/Environment.html

My C# application is returning 0xE0434352 to Windows Task Scheduler but it is not crashing

When setup a job in new windows you have two fields "program/script" and "Start in(Optional)". Put program name in first and program location in second. If you will not do that and your program start not in directory with exe, it will not find files that are located in it.

How to make an app's background image repeat

There is a property in the drawable xml to do it. android:tileMode="repeat"

See this site: http://androidforbeginners.blogspot.com/2010/06/how-to-tile-background-image-in-android.html

java SSL and cert keystore

SSL properties are set at the JVM level via system properties. Meaning you can either set them when you run the program (java -D....) Or you can set them in code by doing System.setProperty.

The specific keys you have to set are below:

javax.net.ssl.keyStore- Location of the Java keystore file containing an application process's own certificate and private key. On Windows, the specified pathname must use forward slashes, /, in place of backslashes.

javax.net.ssl.keyStorePassword - Password to access the private key from the keystore file specified by javax.net.ssl.keyStore. This password is used twice: To unlock the keystore file (store password), and To decrypt the private key stored in the keystore (key password).

javax.net.ssl.trustStore - Location of the Java keystore file containing the collection of CA certificates trusted by this application process (trust store). On Windows, the specified pathname must use forward slashes, /, in place of backslashes, \.

If a trust store location is not specified using this property, the SunJSSE implementation searches for and uses a keystore file in the following locations (in order):

  1. $JAVA_HOME/lib/security/jssecacerts
  2. $JAVA_HOME/lib/security/cacerts

javax.net.ssl.trustStorePassword - Password to unlock the keystore file (store password) specified by javax.net.ssl.trustStore.

javax.net.ssl.trustStoreType - (Optional) For Java keystore file format, this property has the value jks (or JKS). You do not normally specify this property, because its default value is already jks.

javax.net.debug - To switch on logging for the SSL/TLS layer, set this property to ssl.

Git removing upstream from local repository

In git version 2.14.3,

You can remove upstream using

git branch --unset-upstream

The above command will also remove the tracking stream branch, hence if you want to rebase from repository you have use

git rebase origin master 

instead of git pull --rebase

Property 'map' does not exist on type 'Observable<Response>'

I am using Angular 5.2 and when I use import 'rxjs/Rx'; it throws me the following lint error: TSLint: This import is blacklisted, import a submodule instead (import-blacklist)

See the screenshot below: Import of rxjs/Rx is blacklisted in Angular 5.2

SOLUTION: Solved it by importing only the operators that I needed. Example follows:

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

So the fix would be to import specifically only the necessary operators.

fatal error: Python.h: No such file or directory

Sometimes even after installing python-dev the error persists, Check for the error if it is 'gcc' missing.

First download as stated in https://stackoverflow.com/a/21530768/8687063, then install gcc

For apt (Ubuntu, Debian...):

sudo apt-get install gcc

For yum (CentOS, RHEL...):

sudo yum install gcc

For dnf (Fedora...):

sudo dnf install gcc

For zypper (openSUSE...):

sudo zypper in gcc

For apk (Alpine...):

sudo apk gcc

How to get current relative directory of your Makefile?

One line in the Makefile should be enough:

DIR := $(notdir $(CURDIR))

React - How to pass HTML tags in props?

Here is a solution that doesn't use the dangerouslySetInnerHTML which is dangerous as the name says.

import { IntlProvider, FormattedMessage } from "react-intl";

<FormattedMessage
          id="app.greeting"
          description="Bold text example"
          defaultMessage="Look here, I can include HTML tags in plain string and render them as HTML: <b>Bold</b>, <i>Italics</i> and <a>links too</a>."
          values={{
            b: (chunks) => <b>{chunks}</b>,
            i: (chunks) => <i>{chunks}</i>,
            a: (chunks) => (
              <a class="external_link" target="_blank" href="https://jiga.dev/">
                {chunks}
              </a>
            )
          }}
        />

This should be rendered as:

react jiga.dev

Full example in https://jiga.dev/react-render-string-with-html-tags-from-props/

How do I send a cross-domain POST request via JavaScript?

  1. Create two hidden iframes (add "display: none;" to the css style). Make your second iframe point to something on your own domain.

  2. Create a hidden form, set its method to "post" with target = your first iframe, and optionally set enctype to "multipart/form-data" (I'm thinking you want to do POST because you want to send multipart data like pictures?)

  3. When ready, make the form submit() the POST.

  4. If you can get the other domain to return javascript that will do Cross-Domain Communication With Iframes (http://softwareas.com/cross-domain-communication-with-iframes) then you are in luck, and you can capture the response as well.

Of course, if you want to use your server as a proxy, you can avoid all this. Simply submit the form to your own server, which will proxy the request to the other server (assuming the other server isn't set up to notice IP discrepancies), get the response, and return whatever you like.

How to export data from Spark SQL to CSV

Since Spark 2.X spark-csv is integrated as native datasource. Therefore, the necessary statement simplifies to (windows)

df.write
  .option("header", "true")
  .csv("file:///C:/out.csv")

or UNIX

df.write
  .option("header", "true")
  .csv("/var/out.csv")

Notice: as the comments say, it is creating the directory by that name with the partitions in it, not a standard CSV file. This, however, is most likely what you want since otherwise your either crashing your driver (out of RAM) or you could be working with a non distributed environment.

How to loop through all the properties of a class?

VB version of C# given by Brannon:

Public Sub DisplayAll(ByVal Someobject As Foo)
    Dim _type As Type = Someobject.GetType()
    Dim properties() As PropertyInfo = _type.GetProperties()  'line 3
    For Each _property As PropertyInfo In properties
        Console.WriteLine("Name: " + _property.Name + ", Value: " + _property.GetValue(Someobject, Nothing))
    Next
End Sub

Using Binding flags in instead of line no.3

    Dim flags As BindingFlags = BindingFlags.Public Or BindingFlags.Instance
    Dim properties() As PropertyInfo = _type.GetProperties(flags)

HashMap and int as key

You can't use a primitive because HashMap use object internally for the key. So you can only use an object that inherits from Object (that is any object).

That is the function put() in HashMap and as you can see it uses Object for K:

public V put(K key, V value) {
    if (key == null)
        return putForNullKey(value);
    int hash = hash(key);
    int i = indexFor(hash, table.length);
    for (Entry<K,V> e = table[i]; e != null; e = e.next) {
        Object k;
        if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
            V oldValue = e.value;
            e.value = value;
            e.recordAccess(this);
            return oldValue;
        }
    }

    modCount++;
    addEntry(hash, key, value, i);
    return null;
}

The expression "k = e.key" should make it clear.

I suggest to use a wrapper like Integer and autoboxing.

How to position background image in bottom right corner? (CSS)

This should do it:

<style>
body {
    background:url(bg.jpg) fixed no-repeat bottom right;
}
</style>

http://www.w3schools.com/cssref/pr_background-position.asp

ERROR 2013 (HY000): Lost connection to MySQL server at 'reading authorization packet', system error: 0

Another possibility can be connection reset from the TCP wrappers (/etc/hosts.deny and /etc/hosts.allow). Just check what is coming in from the telnet to port 3306 - if it is nothing, then there is something is in the middle preventing communication from happening.

How to set iPhone UIView z index?

IB and Swift

Given the flowing layout where yellow is the superview and red, green, and blue are sibling subviews of yellow,

views - red view on top

the goal is to move a subview (let's say green) to the top.

views - green view on top

In Interface Builder

In the Interface Builder all you need to do is drag the view you want showing on the top to the bottom of the list in the Documents Outline.

order of views in Interface Builder

Alternatively, you can select the view and then in the menu go to Editor > Arrange > Send to Front.

In Swift

There are a couple of different ways to do this programmatically.

Method 1

yellowView.bringSubviewToFront(greenView)
  • This method is the programmatic equivalent of the IB answer above.

  • It only works if the subviews are siblings of each other.

  • An array of the subviews is contained in yellowView.subviews. Here, bringSubviewToFront moves the greenView from index 0 to 2. This can be observed with

      print(yellowView.subviews.indexOf(greenView))
    

Method 2

greenView.layer.zPosition = 1
  • This method just moves the 3D position of the layer higher (closer to the user) on the z-axis. Since the default is 0 for all the other views, the result is that the greenView looks like it is on top. However, it still remains at index 0 of the yellowView.subviews array. This can cause some unexpected results, though, because things like tap events will still go first to the view with the highest index number. For that reason, it might be better to go with Method 1 above.
  • The zPosition could be set to CGFloat.greatestFiniteMagnitude (CGFloat(FLT_MAX) in older versions of Swift) to ensure that it is on top.

Error - is not marked as serializable

Leaving my specific solution of this for prosperity, as it's a tricky version of this problem:

Type 'System.Linq.Enumerable+WhereSelectArrayIterator[T...] was not marked as serializable

Due to a class with an attribute IEnumerable<int> eg:

[Serializable]
class MySessionData{
    public int ID;
    public IEnumerable<int> RelatedIDs; //This can be an issue
}

Originally the problem instance of MySessionData was set from a non-serializable list:

MySessionData instance = new MySessionData(){ 
    ID = 123,
    RelatedIDs = nonSerizableList.Select<int>(item => item.ID)
};

The cause here is the concrete class that the Select<int>(...) returns, has type data that's not serializable, and you need to copy the id's to a fresh List<int> to resolve it.

RelatedIDs = nonSerizableList.Select<int>(item => item.ID).ToList();

What is the best JavaScript code to create an img element

var img = document.createElement('img');
img.src = 'my_image.jpg';
document.getElementById('container').appendChild(img);

Binding objects defined in code-behind

Just a little more clarification: A property without 'get','set' won't be able to be bound

I'm facing the case just like the asker's case. And I must have the following things in order for the bind to work properly:

//(1) Declare a property with 'get','set' in code behind
public partial class my_class:Window {
  public String My_Property { get; set; }
  ...

//(2) Initialise the property in constructor of code behind
public partial class my_class:Window {
  ...
  public my_class() {
     My_Property = "my-string-value";
     InitializeComponent();
  }

//(3) Set data context in window xaml and specify a binding
<Window ...
DataContext="{Binding RelativeSource={RelativeSource Self}}">
  <TextBlock Text="{Binding My_Property}"/>
</Window>

MySQL show current connection info

If you want to know the port number of your local host on which Mysql is running you can use this query on MySQL Command line client --

SHOW VARIABLES WHERE Variable_name = 'port';


mysql> SHOW VARIABLES WHERE Variable_name = 'port';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| port          | 3306  |
+---------------+-------+
1 row in set (0.00 sec)

It will give you the port number on which MySQL is running.


If you want to know the hostname of your Mysql you can use this query on MySQL Command line client --

SHOW VARIABLES WHERE Variable_name = 'hostname';


mysql> SHOW VARIABLES WHERE Variable_name = 'hostname';
+-------------------+-------+
| Variable_name     | Value |
+-------------------+-------+
| hostname          | Dell  |
+-------------------+-------+
1 row in set (0.00 sec)

It will give you the hostname for mysql.


If you want to know the username of your Mysql you can use this query on MySQL Command line client --

select user();   


mysql> select user();
+----------------+
| user()         |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.00 sec)

It will give you the username for mysql.

Identify duplicate values in a list in Python

You can print duplicate and Unqiue using below logic using list.

def dup(x):
    duplicate = []
    unique = []
    for i in x:
        if i in unique:
            duplicate.append(i)
        else:
            unique.append(i)
    print("Duplicate values: ",duplicate)
    print("Unique Values: ",unique)

list1 = [1, 2, 1, 3, 2, 5]
dup(list1)

try/catch with InputMismatchException creates infinite loop

To follow debobroto das's answer you can also put after

input.reset();
input.next(); 

I had the same problem and when I tried this. It completely fixed it.

Hadoop cluster setup - java.net.ConnectException: Connection refused

In /etc/hosts:

  1. Add this line:

your-ip-address your-host-name

example: 192.168.1.8 master

In /etc/hosts:

  1. Delete the line with 127.0.1.1 (This will cause loopback)

  2. In your core-site, change localhost to your-ip or your-hostname

Now, restart the cluster.

How to sort Map values by key in Java?

List<String> list = new ArrayList<String>();
Map<String, String> map = new HashMap<String, String>();
for (String str : map.keySet()) {
 list.add(str);
}
Collections.sort(list);
for (String str : list) {
 System.out.println(str);
}

Remove white space above and below large text in an inline-block element

I had a similar problem. As you increase the line-height the space above the text increases. It's not padding but it will affect the vertical space between content. I found that adding a -ve top margin seemed to do the trick. It had to be done for all of the different instances of line-height and it varies with font-family too. Maybe this is something which designers need to be more aware of when passing design requirements (?) So for a particular instance of font-family and line-height:

h1 {
    font-family: 'Garamond Premier Pro Regular';
    font-size: 24px;
    color: #001230;
    line-height: 29px;
    margin-top: -5px;    /* CORRECTION FOR LINE-HEIGHT */
}

How do I remove duplicates from a C# array?

Add all the strings to a dictionary and get the Keys property afterwards. This will produce each unique string, but not necessarily in the same order your original input had them in.

If you require the end result to have the same order as the original input, when you consider the first occurance of each string, use the following algorithm instead:

  1. Have a list (final output) and a dictionary (to check for duplicates)
  2. For each string in the input, check if it exists in the dictionary already
  3. If not, add it both to the dictionary and to the list

At the end, the list contains the first occurance of each unique string.

Make sure you consider things like culture and such when constructing your dictionary, to make sure you handle duplicates with accented letters correctly.

Bootstrap date time picker

Well, here the positioning of the css and script links makes a to of difference. Bootstrap executes in CSS and then Scripts fashion. So if you have even one script written at incorrect place it makes a lot of difference. You can follow the below snippet and change your code accordingly.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <meta charset="utf-8">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
_x000D_
    <!-- <link rel="stylesheet" type="text/css" href="css/bootstrap-datetimepicker.css"> -->_x000D_
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>_x000D_
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker.min.css"> _x000D_
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker-standalone.css"> _x000D_
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/js/bootstrap-datetimepicker.min.js"></script>_x000D_
    _x000D_
</head>_x000D_
<body>_x000D_
     <div class="container">_x000D_
          <div class="row">_x000D_
            <div class='col-sm-6'>_x000D_
                <div class="form-group">_x000D_
                    <div class='input-group date' id='datetimepicker1'>_x000D_
                        <input type='text' class="form-control" />_x000D_
                        <span class="input-group-addon">_x000D_
                            <span class="glyphicon glyphicon-calendar"></span>_x000D_
                        </span>_x000D_
                    </div>_x000D_
                </div>_x000D_
            </div>_x000D_
            <script type="text/javascript">_x000D_
                $(function () {_x000D_
                    $('#datetimepicker1').datetimepicker();_x000D_
                });_x000D_
            </script>_x000D_
          </div>_x000D_
       </div>_x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Last Run Date on a Stored Procedure in SQL Server

If you enable Query Store on SQL Server 2016 or newer you can use the following query to get last SP execution. The history depends on the Query Store Configuration.

SELECT 
      ObjectName = '[' + s.name + '].[' + o.Name  + ']'
    , LastModificationDate  = MAX(o.modify_date)
    , LastExecutionTime     = MAX(q.last_execution_time)
FROM sys.query_store_query q 
    INNER JOIN sys.objects o
        ON q.object_id = o.object_id
    INNER JOIN sys.schemas s
        ON o.schema_id = s.schema_id
WHERE o.type IN ('P')
GROUP BY o.name , + s.name 

What is the difference between IQueryable<T> and IEnumerable<T>?

In simple words other major difference is that IEnumerable execute select query on server side, load data in-memory on client side and then filter data while IQueryable execute select query on server side with all filters.

How do I edit an incorrect commit message in git ( that I've pushed )?

Suppose you have a tree like this:

dd2e86 - 946992 - 9143a9 - a6fd86 - 5a6057 [master]

First, checkout a temp branch:

git checkout -b temp

On temp branch, reset --hard to a commit that you want to change its message (for example, that commit is 946992):

git reset --hard 946992

Use amend to change the message:

git commit --amend -m "<new_message>"

After that the tree will look like this:

dd2e86 - 946992 - 9143a9 - a6fd86 - 5a6057 [master]
           \
            b886a0 [temp]

Then, cherry-pick all the commit that is ahead of 946992 from master to temp and commit them, use amend if you want to change their messages as well:

git cherry-pick 9143a9
git commit --amend -m "<new_message>
...
git cherry-pick 5a6057
git commit --amend -m "<new_message>

The tree now looks like this:

dd2e86 - 946992 - 9143a9 - a6fd86 - 5a6057 [master]
               \
                b886a0 - 41ab2c - 6c2a3s - 7c88c9 [temp]

Now force push the temp branch to remote:

git push --force origin temp:master

The final step, delete branch master on local, git fetch origin to pull branch master from the server, then switch to branch master and delete branch temp.

Now both your local and remote will have all the messages updated.

Android: failed to convert @drawable/picture into a drawable

If re-starting Eclipse does not correct the problem, make sure that the image name begins with an alpha character (non-numeric).

How to add parameters into a WebRequest?

For doing FORM posts, the best way is to use WebClient.UploadValues() with a POST method.

Change Select List Option background colour on hover in html

No, it's not possible.

It's really, if not use native selects, if you create custom select widget from html elements, t.e. "li".

MVC 4 Data Annotations "Display" Attribute

If two different views are sharing the same model (for instance, maybe one is for mobile output and one is regular), it could be nice to have the string reside in a single place: as metadata on the ViewModel.

Additionally, if you had an inherited version of the model that necessitated a different display, it could be useful. For instance:

public class BaseViewModel
{
    [Display(Name = "Basic Name")]
    public virtual string Name { get; set; }
}

public class OtherViewModel : BaseViewModel
{
    [Display(Name = "Customized Inherited Name")]
    public override string Name { get; set; }
}

I'll admit that that example is pretty contrived...

Those are the best arguments in favor of using the attribute that I can come up with. My personal opinion is that, for the most part, that sort of thing is best left to the markup.

"405 method not allowed" in IIS7.5 for "PUT" method

I had the same problem, with a RESTful API running on aspnet core.

I didn't want to uninstall the WebDAV, and I tried most of the remedies described above. I tried to set the verbs="*" both on the site and on the server itself, but without success.

What did the trick for me was the following:

IIS Manager -> Sites -> MySite -> HandlerMappings -> aspNetCore -> Edit

-> Request Restrictions -> Access -> None (it was Script).

After that everything worked, even if I replaced the original WebDAV options.

How can I create a border around an Android LinearLayout?

you can do it Pragmatically also

  GradientDrawable gradientDrawable=new GradientDrawable();
   gradientDrawable.setStroke(4,getResources().getColor(R.color.line_Input));

Then set the background of layout as :

LinearLayout layout = (LinearLayout ) findViewById(R.id.ayout); layout .setBackground(gradientDrawable);

How to check if type of a variable is string?

Edit based on better answer below. Go down about 3 answers and find out about the coolness of basestring.

Old answer: Watch out for unicode strings, which you can get from several places, including all COM calls in Windows.

if isinstance(target, str) or isinstance(target, unicode):

CSS scale height to match width - possibly with a formfactor

Solution with Jquery

$(window).resize(function () {
    var width = $("#map").width();
    $("#map").height(width * 1.72);
});

gdb: "No symbol table is loaded"

I have the same problem and I followed this Post, it solved my problem.

Follow the following 2 steps:

  1. Make sure the optimization level is -O0
  2. Add -ggdb flag when compiling your program

Good luck!

Convert DateTime in C# to yyyy-MM-dd format and Store it to MySql DateTime Field

Have you tried?

var isoDateTimeFormat = CultureInfo.InvariantCulture.DateTimeFormat;

// "2013-10-10T22:10:00"
 dateValue.ToString(isoDateTimeFormat.SortableDateTimePattern); 

// "2013-10-10 22:10:00Z"    
dateValue.ToString(isoDateTimeFormat.UniversalSortableDateTimePattern)

Also try using parameters when you store the c# datetime value in the mySql database, this might help.

In Postgresql, force unique on combination of two columns

CREATE TABLE someTable (
    id serial PRIMARY KEY,
    col1 int NOT NULL,
    col2 int NOT NULL,
    UNIQUE (col1, col2)
)

autoincrement is not postgresql. You want a serial.

If col1 and col2 make a unique and can't be null then they make a good primary key:

CREATE TABLE someTable (
    col1 int NOT NULL,
    col2 int NOT NULL,
    PRIMARY KEY (col1, col2)
)

How to convert NSDate into unix timestamp iphone sdk?

- (void)GetCurrentTimeStamp
    {
        NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
        [objDateformat setDateFormat:@"yyyy-MM-dd"];
        NSString    *strTime = [objDateformat stringFromDate:[NSDate date]];
        NSString    *strUTCTime = [self GetUTCDateTimeFromLocalTime:strTime];//You can pass your date but be carefull about your date format of NSDateFormatter.
        NSDate *objUTCDate  = [objDateformat dateFromString:strUTCTime];
        long long milliseconds = (long long)([objUTCDate timeIntervalSince1970] * 1000.0);

        NSString *strTimeStamp = [Nsstring stringwithformat:@"%lld",milliseconds];
        NSLog(@"The Timestamp is = %@",strTimestamp);
    }

 - (NSString *) GetUTCDateTimeFromLocalTime:(NSString *)IN_strLocalTime
    {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        NSDate  *objDate    = [dateFormatter dateFromString:IN_strLocalTime];
        [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
        NSString *strDateTime   = [dateFormatter stringFromDate:objDate];
        return strDateTime;
    }

NOTE :- The Timestamp must be in UTC Zone, So I convert our local Time to UTC Time.

Username and password in https url

When you put the username and password in front of the host, this data is not sent that way to the server. It is instead transformed to a request header depending on the authentication schema used. Most of the time this is going to be Basic Auth which I describe below. A similar (but significantly less often used) authentication scheme is Digest Auth which nowadays provides comparable security features.

With Basic Auth, the HTTP request from the question will look something like this:

GET / HTTP/1.1
Host: example.com
Authorization: Basic Zm9vOnBhc3N3b3Jk

The hash like string you see there is created by the browser like this: base64_encode(username + ":" + password).

To outsiders of the HTTPS transfer, this information is hidden (as everything else on the HTTP level). You should take care of logging on the client and all intermediate servers though. The username will normally be shown in server logs, but the password won't. This is not guaranteed though. When you call that URL on the client with e.g. curl, the username and password will be clearly visible on the process list and might turn up in the bash history file.

When you send passwords in a GET request as e.g. http://example.com/login.php?username=me&password=secure the username and password will always turn up in server logs of your webserver, application server, caches, ... unless you specifically configure your servers to not log it. This only applies to servers being able to read the unencrypted http data, like your application server or any middleboxes such as loadbalancers, CDNs, proxies, etc. though.

Basic auth is standardized and implemented by browsers by showing this little username/password popup you might have seen already. When you put the username/password into an HTML form sent via GET or POST, you have to implement all the login/logout logic yourself (which might be an advantage and allows you to more control over the login/logout flow for the added "cost" of having to implement this securely again). But you should never transfer usernames and passwords by GET parameters. If you have to, use POST instead. The prevents the logging of this data by default.

When implementing an authentication mechanism with a user/password entry form and a subsequent cookie-based session as it is commonly used today, you have to make sure that the password is either transported with POST requests or one of the standardized authentication schemes above only.

Concluding I could say, that transfering data that way over HTTPS is likely safe, as long as you take care that the password does not turn up in unexpected places. But that advice applies to every transfer of any password in any way.

Downcasting in Java

Using your example, you could do:

public void doit(A a) {
    if(a instanceof B) {
        // needs to cast to B to access draw2 which isn't present in A
        // note that this is probably not a good OO-design, but that would
        // be out-of-scope for this discussion :)
        ((B)a).draw2();
    }
    a.draw();
}

CakePHP select default value in SELECT input

The best answer to this could be

Don't use selct for this job use input instead

like this

echo  $this->Form->input('field_name', array(
          'type' => 'select',
            'options' => $options_arr, 
            'label' => 'label here',
            'value' => $id,  // default value
            'escape' => false,  // prevent HTML being automatically escaped
            'error' => false,
            'class' => 'form-control' // custom class you want to enter
        ));

Hope it helps.

is inaccessible due to its protection level

It's because you cannot access protected member data through its class instance. You should correct your code as follows:

namespace homeworkchap8
{
    class main
    {    
        static void Main(string[] args)
        {    
            SteelClubs myClub = new SteelClubs();
            Console.WriteLine("How far to the hole?");
            myClub.mydistance = Console.ReadLine();
            Console.WriteLine("what club are you going to hit?");
            myClub.myclub = Console.ReadLine();
            myClub.SwingClub();

            SteelClubs mycleanclub = new SteelClubs();
            Console.WriteLine("\nDid you clean your club after?");
            mycleanclub.mycleanclub = Console.ReadLine();
            mycleanclub.clean();

            SteelClubs myScoreonHole = new SteelClubs();
            Console.WriteLine("\nWhat hole are you on?");
            myScoreonHole.myhole = Console.ReadLine();
            Console.WriteLine("What did you score on the hole?");
            myScoreonHole.myscore = Console.ReadLine();
            Console.WriteLine("What is the par of the hole?");
            myScoreonHole.parhole = Console.ReadLine();

            myScoreonHole.score();

            Console.ReadKey();    
        }
    }
}

How can I de-install a Perl module installed via `cpan`?

  1. Install App::cpanminus from CPAN (use: cpan App::cpanminus for this).
  2. Type cpanm --uninstall Module::Name (note the "m") to uninstall the module with cpanminus.

This should work.

Remove the last line from a file in Bash

I had trouble with all the answers here because I was working with a HUGE file (~300Gb) and none of the solutions scaled. Here's my solution:

dd if=/dev/null of=<filename> bs=1 seek=$(echo $(stat --format=%s <filename> ) - $( tail -n1 <filename> | wc -c) | bc )

In words: Find out the length of the file you want to end up with (length of file minus length of length of its last line, using bc) and, set that position to be the end of the file (by dding one byte of /dev/null onto it).

This is fast because tail starts reading from the end, and dd will overwrite the file in place rather than copy (and parse) every line of the file, which is what the other solutions do.

NOTE: This removes the line from the file in place! Make a backup or test on a dummy file before trying it out on your own file!

PHP/MySQL insert row then get 'id'

$link = mysqli_connect('127.0.0.1', 'my_user', 'my_pass', 'my_db');
mysqli_query($link, "INSERT INTO mytable (1, 2, 3, 'blah')");
$id = mysqli_insert_id($link);

See mysqli_insert_id().

Whatever you do, don't insert and then do a "SELECT MAX(id) FROM mytable". Like you say, it's a race condition and there's no need. mysqli_insert_id() already has this functionality.

How do I find the time difference between two datetime objects in python?

In Other ways to get difference between date;

import dateutil.parser
import datetime
last_sent_date = "" # date string
timeDifference = current_date - dateutil.parser.parse(last_sent_date)
time_difference_in_minutes = (int(timeDifference.days) * 24 * 60) + int((timeDifference.seconds) / 60)

So get output in Min.

Thanks

What is the difference between varchar and nvarchar?

My two cents

  1. Indexes can fail when not using the correct datatypes:
    In SQL Server: When you have an index over a VARCHAR column and present it a Unicode String, SQL Server does not make use of the index. The same thing happens when you present a BigInt to a indexed-column containing SmallInt. Even if the BigInt is small enough to be a SmallInt, SQL Server is not able to use the index. The other way around you do not have this problem (when providing SmallInt or Ansi-Code to an indexed BigInt ot NVARCHAR column).

  2. Datatypes can vary between different DBMS's (DataBase Management System):
    Know that every database has slightly different datatypes and VARCHAR does not means the same everywhere. While SQL Server has VARCHAR and NVARCHAR, an Apache/Derby database has only VARCHAR and there VARCHAR is in Unicode.

Convert string to integer type in Go?

Try this

import ("strconv")

value := "123"
number,err := strconv.ParseUint(value, 10, 32)
finalIntNum := int(number) //Convert uint64 To int

Html.Partial vs Html.RenderPartial & Html.Action vs Html.RenderAction

More about the question:

"When Html.RenderPartial() is called with just the name of the partial view, ASP.NET MVC will pass to the partial view the same Model and ViewData dictionary objects used by the calling view template."

“NerdDinner” from Professional ASP.NET MVC 1.0

Turn off enclosing <p> tags in CKEditor 3.0

Set such config:

    CKEDITOR.config.enterMode = CKEDITOR.ENTER_BR
    CKEDITOR.config.forcePasteAsPlainText = true

Tomcat starts but home page cannot open with url http://localhost:8080

I had the same issue. My tomcat was started but I was getting HTTP 404 page not found.However, in my situation, I installed tree instances of tomcat. Each instance contains conf, temp, work, webapps and logs folders. Unless I forgot, to copy the global web.xml under conf folder of each tomcat.

    e.g: /opt/tomcat/mytomcatInstance/conf/web.xml 

The web.xml Deployment Descriptor file describes how to deploy a web application in a servlet container.

So even if my tomcat was up, my web apps could not be deployed properly.

Restoring Nuget References?

In case this helps someone, for me, none of the above was sufficient. I still couldn't build, VS still couldn't find the references. The key was simply to close and reopen the solution after restoring the packages.

Here's the scenario (using Visual Studio 2012):

You open a Solution that has missing packages. The references show that VS can't find them. There are many ways to restore the missing packages, including

  • building a solution that is set to auto-restore
  • opening the Package Manager Console and clicking the nice "Restore" button
  • doing nuget restore if you have the command line nuget installed

But no matter what the approach, those references will still be shown as missing. And when you build it will fail. Sigh. However if you close the solution and re-open it, now VS checks those nice <HintPath>s again, finds that the packages are back where they belong, and all is well with the world.

Update

Is Visual Studio still not seeing that you have the package? Still showing a reference that it can't resolve? Make sure that the version of package you restored is exactly the same as the <HintPath> in your .csproj file. Even a minor bug fix number (e.g. 1.10.1 to 1.10.2) will cause the reference to fail. You can fix this either by directly editing your csproj xml, or else by removing the reference and making a new one pointing at the newly-restored version in the packages directory.

Java getting the Enum name given the Enum Value

Try, the following code..

    @Override
    public String toString() {
    return this.name();
    }

Rails: How does the respond_to block work?

From what I know, respond_to is a method attached to the ActionController, so you can use it in every single controller, because all of them inherits from the ActionController. Here is the Rails respond_to method:

def respond_to(&block)
  responder = Responder.new(self)
  block.call(responder)
  responder.respond
end

You are passing it a block, like I show here:

respond_to <<**BEGINNING OF THE BLOCK**>> do |format|
  format.html
  format.xml  { render :xml => @whatever }
end <<**END OF THE BLOCK**>>

The |format| part is the argument that the block is expecting, so inside the respond_to method we can use that. How?

Well, if you notice we pass the block with a prefixed & in the respond_to method, and we do that to treat that block as a Proc. Since the argument has the ".xml", ".html" we can use that as methods to be called.

What we basically do in the respond_to class is call methods ".html, .xml, .json" to an instance of a Responder class.

How can you search Google Programmatically Java API

Indeed there is an API to search google programmatically. The API is called google custom search. For using this API, you will need an Google Developer API key and a cx key. A simple procedure for accessing google search from java program is explained in my blog.

Now dead, here is the Wayback Machine link.

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

In Android O and later this error happens when you set

 android:screenOrientation="portrait"

in Manifest.

Remove that line and use

 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

in your activity.

This will fix your issue.

Bootstrap 3.0: How to have text and input on same line?

You can do it like this:

<form class="form-horizontal" role="form">
    <div class="form-group">
        <label for="inputType" class="col-sm-2 control-label">Label</label>
        <div class="col-sm-4">
            <input type="text" class="form-control" id="input" placeholder="Input text">
        </div>
    </div>
</form>

Fiddle

How to call javascript from a href?

<a href="javascript:call_func();">...</a>

where the function then has to return false so that the browser doesn't go to another page.

But I'd recommend to use jQuery (with $(...).click(function () {})))

Is there an easy way to add a border to the top and bottom of an Android View?

Why not just create a 1dp high view with a background color? Then it can be easily placed where you want.

How to call a mysql stored procedure, with arguments, from command line?

With quotes around the date:

mysql> CALL insertEvent('2012.01.01 12:12:12');

CSS set li indent

li{
    margin-left:50px;
}

or replace 50px with whatever you want.

Git: How to update/checkout a single file from remote origin master?

What you can do is:

  1. Update your local git repo:

    git fetch

  2. Build a local branch and checkout on it:

    git branch pouet && git checkout pouet

  3. Apply the commit you want on this branch:

    git cherry-pick abcdefabcdef

    (abcdefabcdef is the sha1 of the commit you want to apply)

Test iOS app on device without apple developer program or jailbreak

Seven years after the inception of the App Store (July 10, 2008), Apple has finally introduced a new feature in Xcode 7 that allows you to deploy and run any number of apps on any of your devices, simply by logging in with your Apple ID. You will no longer need a paid Program membership to deploy apps on your own device (and you certainly no longer have to jailbreak your device if you're not comfortable doing so).

Well, not for the majority of use cases anyway. For obvious reasons, certain capabilities and entitlements that require Program membership such as Game Center and in-app purchases will not be available to apps deployed using this method. From Apple's developer documentation:

Launch Your App on Devices Using Free Provisioning (iOS, watchOS)

If you don’t join the Apple Developer Program, you can still build and run your app on your devices using free provisioning. However, the capabilities available to your app, described in Adding Capabilities, are restricted when you don’t belong to the Apple Developer Program.

The precise steps to getting your app onto your iOS device or Apple Watch follow immediately thus (screenshots omitted for ease of skimming):

  1. In Xcode, add your Apple ID to Accounts preferences, described in Adding Your Apple ID Account in Xcode.

  2. In the project navigator, select the project and your target to display the project editor.

  3. Click General and choose your name from the Team pop-up menu.

  4. Connect the device to your Mac and choose your device from the Scheme toolbar menu.

  5. Below the Team pop-up menu, click Fix Issue.

    Xcode creates a free provisioning profile for you and the warning text under the Team pop-up menu disappears.

  6. Click the Run button.

    Xcode installs the app on the device before launching the app.

Prior to Xcode 7, a Program membership was indeed required in order to sign the provisioning certificates required to deploy apps to devices. The only other alternative was jailbreaking. With Xcode 7, you no longer need to jailbreak your device just to run apps distributed outside the App Store, or to test apps if you cannot afford to join the Program, or to deploy and use apps that you have developed for your own personal use if you do not intend to distribute them through the App Store (in which case you probably don't need the entitlements offered by Program membership anyway).

adb connection over tcp not working now

I solved that issue follow that:

Steps:

  1. Make sure that Aggressive Wi-Fi to Cellular handover under Networking section in the device's developer options is turned off.
  2. Ping continuously from your pc to the device to make sure it's not in network idle mode ping -t 194.68.0.100 (windows cmd), unlock the device and even try to surf to some website just to make it get out of the network idle.
  3. If ping doesn't work, turn off / on Android Wifi and go back to step 2.
  4. When it replies to the ping, connect it via USB, and:

    adb usb

    adb tcpip 5555

    adb connect 194.68.0.100:5555

In casr it's still not connected, try to switch the usb connection mode as MTP / PTP / Camera while the device is connected through usb and repeat these steps over again...

How do I remove an item from a stl vector with a certain value?

std::remove does not actually erase the element from the container, but it does return the new end iterator which can be passed to container_type::erase to do the REAL removal of the extra elements that are now at the end of the container:

std::vector<int> vec;
// .. put in some values ..
int int_to_remove = n;
vec.erase(std::remove(vec.begin(), vec.end(), int_to_remove), vec.end());

ModelState.IsValid == false, why?

Sometimes a binder throwns an exception with no error message. You can retrieve the exception with the following snippet to find out whats wrong:

(Often if the binder is trying to convert strings to complex types etc)

 if (!ModelState.IsValid)
            {
var errors = ModelState.SelectMany(x => x.Value.Errors.Select(z => z.Exception));

// Breakpoint, Log or examine the list with Exceptions.

  }

How do I remove quotes from a string?

str_replace('"', "", $string);
str_replace("'", "", $string);

I assume you mean quotation marks?

Otherwise, go for some regex, this will work for html quotes for example:

preg_replace("/<!--.*?-->/", "", $string);

C-style quotes:

preg_replace("/\/\/.*?\n/", "\n", $string);

CSS-style quotes:

preg_replace("/\/*.*?\*\//", "", $string);

bash-style quotes:

preg-replace("/#.*?\n/", "\n", $string);

Etc etc...

How to check if one DateTime is greater than the other in C#

I had the same requirement, but when using the accepted answer, it did not fulfill all of my unit tests. The issue for me is when you have a new object, with Start and End dates and you have to set the Start date ( at this stage your End date has the minimum date value of 01/01/0001) - this solution did pass all my unit tests:

    public DateTime Start
    {
        get { return _start; }
        set
        {
            if (_end.Equals(DateTime.MinValue))
            {
                _start = value;
            }
            else if (value.Date < _end.Date)
            {
                _start = value;
            }
            else
            {
                throw new ArgumentException("Start date must be before the End date.");
            }
        }
    }


    public DateTime End
    {
        get { return _end; }
        set
        {
            if (_start.Equals(DateTime.MinValue))
            {
                _end = value;
            }
            else if (value.Date > _start.Date)
            {
                _end = value;
            }
            else
            {
                throw new ArgumentException("End date must be after the Start date.");
            }
        }
    }

It does miss the edge case where both Start and End dates can be 01/01/0001 but I'm not concerned about that.

Windows could not start the Apache2 on Local Computer - problem

I've had this problem twice. The first problem was fixed using the marked answer on this page (thank you for that). However, the second time proved a bit more difficult.

I found that in my httpd-vhosts.conf file that I made a mistake when assigning the document root to a domain name. Fixing this solved my problem. It is well worth checking (or even reverting to a blank copy) your httpd-vhosts.conf file for any errors and typo's.

Using BeautifulSoup to search HTML for string

The following line is looking for the exact NavigableString 'Python':

>>> soup.body.findAll(text='Python')
[]

Note that the following NavigableString is found:

>>> soup.body.findAll(text='Python Jobs') 
[u'Python Jobs']

Note this behaviour:

>>> import re
>>> soup.body.findAll(text=re.compile('^Python$'))
[]

So your regexp is looking for an occurrence of 'Python' not the exact match to the NavigableString 'Python'.

How to call a C# function from JavaScript?

If you're meaning to make a server call from the client, you should use Ajax - look at something like Jquery and use $.Ajax() or $.getJson() to call the server function, depending on what kind of return you're after or action you want to execute.

Converting a list to a set changes element order

In mathematics, there are sets and ordered sets (osets).

  • set: an unordered container of unique elements (Implemented)
  • oset: an ordered container of unique elements (NotImplemented)

In Python, only sets are directly implemented. We can emulate osets with regular dict keys (3.7+).

Given

a = [1, 2, 20, 6, 210, 2, 1]
b = {2, 6}

Code

oset = dict.fromkeys(a).keys()
# dict_keys([1, 2, 20, 6, 210])

Demo

Replicates are removed, insertion-order is preserved.

list(oset)
# [1, 2, 20, 6, 210]

Set-like operations on dict keys.

oset - b
# {1, 20, 210}

oset | b
# {1, 2, 5, 6, 20, 210}

oset & b
# {2, 6}

oset ^ b
# {1, 5, 20, 210}

Details

Note: an unordered structure does not preclude ordered elements. Rather, maintained order is not guaranteed. Example:

assert {1, 2, 3} == {2, 3, 1}                    # sets (order is ignored)

assert [1, 2, 3] != [2, 3, 1]                    # lists (order is guaranteed)

One may be pleased to discover that a list and multiset (mset) are two more fascinating, mathematical data structures:

  • list: an ordered container of elements that permits replicates (Implemented)
  • mset: an unordered container of elements that permits replicates (NotImplemented)*

Summary

Container | Ordered | Unique | Implemented
----------|---------|--------|------------
set       |    n    |    y   |     y
oset      |    y    |    y   |     n
list      |    y    |    n   |     y
mset      |    n    |    n   |     n*  

*A multiset can be indirectly emulated with collections.Counter(), a dict-like mapping of multiplicities (counts).

JavaScript Infinitely Looping slideshow with delays?

You can infinitely loop easily enough via recursion.

function it_keeps_going_and_going_and_going() {
  it_keeps_going_and_going_and_going();
}

it_keeps_going_and_going_and_going()

How to pass multiple checkboxes using jQuery ajax post

Could use the following and then explode the post result explode(",", $_POST['data']); to give an array of results.

var data = new Array();
$("input[name='checkBoxesName']:checked").each(function(i) {
    data.push($(this).val());
});

CSS: Fix row height

Simply add style="line-height:0" to each cell. This works in IE because it sets the line-height of both existant and non-existant text to about 19px and that forces the cells to expand vertically in most versions of IE. Regardless of whether or not you have text this needs to be done for IE to correctly display rows less than 20px high.

$watch'ing for data changes in an Angular directive

Because if you want to trigger your data with deep of it,you have to pass 3th argument true of your listener.By default it's false and it meens that you function will trigger,only when your variable will change not it's field.

Browser detection in JavaScript?

Not exactly what you want, but close to it:

var jscriptVersion = /*@cc_on @if(@_jscript) @_jscript_version @else @*/ false /*@end @*/;
var geckoVersion = navigator.product === 'Gecko' && navigator.productSub;
var operaVersion = 'opera' in window && 'version' in opera && opera.version();

The variables will contain the appropriate version or false if it is not available.

I'd appreciate it if someone using Chrome could find out if you can use window.chrome in a similar way to window.opera.

Recursive query in SQL Server

Something like this (not tested)

with match_groups as (

  select product_id, 
         matching_product_id,
         product_id as group_id
  from matches
  where product_id not in (select matching_product_id from matches)

  union all

  select m.product_id, m.matching_product_id, p.group_id
  from matches m
    join match_groups p on m.product_id = p.matching_product_id
)
select group_id, product_id
from match_groups
order by group_id;

Openssl : error "self signed certificate in certificate chain"

Here is one-liner to verify certificate chain:

openssl verify -verbose -x509_strict -CAfile ca.pem cert_chain.pem

This doesn't require to install CA anywhere.

See How does an SSL certificate chain bundle work? for details.

Git command to display HEAD commit id?

You can use

git log -g branchname

to see git reflog information formatted like the git log output

Global javascript variable inside document.ready

JavaScript has Function-Level variable scope which means you will have to declare your variable outside $(document).ready() function.

Or alternatively to make your variable to have global scope, simply dont use var keyword before it like shown below. However generally this is considered bad practice because it pollutes the global scope but it is up to you to decide.

$(document).ready(function() {
   intro = null; // it is in global scope now

To learn more about it, check out:

Interactive shell using Docker Compose

You need to include the following lines in your docker-compose.yml:

version: "3"
services:
  app:
    image: app:1.2.3
    stdin_open: true # docker run -i
    tty: true        # docker run -t

The first corresponds to -i in docker run and the second to -t.

Connecting to SQL Server with Visual Studio Express Editions

My guess is that with VWD your solutions are more likely to be deployed to third party servers, many of which do not allow for a dynamically attached SQL Server database file. Thus the allowing of the other connection type.

This difference in IDE behavior is one of the key reasons for upgrading to a full version.

Fatal error: "No Target Architecture" in Visual Studio

It would seem that _AMD64_ is not defined, since I can't imagine you are compiling for Itanium (_IA64_).

Are there best practices for (Java) package organization?

Package organization or package structuring is usually a heated discussion. Below are some simple guidelines for package naming and structuring:

  • Follow java package naming conventions
  • Structure your packages according to their functional role as well as their business role
    • Break down your packages according to their functionality or modules. e.g. com.company.product.modulea
    • Further break down could be based on layers in your software. But don't go overboard if you have only few classes in the package, then it makes sense to have everything in the package. e.g. com.company.product.module.web or com.company.product.module.util etc.
    • Avoid going overboard with structuring, IMO avoid separate packaging for exceptions, factories, etc. unless there's a pressing need.
  • If your project is small, keep it simple with few packages. e.g. com.company.product.model and com.company.product.util, etc.
  • Take a look at some of the popular open source projects out there on Apache projects. See how they use structuring, for various sized projects.
  • Also consider build and distribution when naming ( allowing you to distribute your api or SDK in a different package, see servlet api)

After a few experiments and trials you should be able to come up with a structuring that you are comfortable with. Don't be fixated on one convention, be open to changes.

m2eclipse error

In this particular case, the solution was the right proxy configuration of eclipse (Window -> Preferences -> Network Connection), the company possessed a strict security system. I will leave the question, because there are answers that can help the community. Thank you very much for the answers above.

Dictionary returning a default value if the key does not exist

TryGetValue will already assign the default value for the type to the dictionary, so you can just use:

dictionary.TryGetValue(key, out value);

and just ignore the return value. However, that really will just return default(TValue), not some custom default value (nor, more usefully, the result of executing a delegate). There's nothing more powerful built into the framework. I would suggest two extension methods:

public static TValue GetValueOrDefault<TKey, TValue>
    (this IDictionary<TKey, TValue> dictionary, 
     TKey key,
     TValue defaultValue)
{
    TValue value;
    return dictionary.TryGetValue(key, out value) ? value : defaultValue;
}

public static TValue GetValueOrDefault<TKey, TValue>
    (this IDictionary<TKey, TValue> dictionary,
     TKey key,
     Func<TValue> defaultValueProvider)
{
    TValue value;
    return dictionary.TryGetValue(key, out value) ? value
         : defaultValueProvider();
}

(You may want to put argument checking in, of course :)

How to specify 64 bit integers in c

Use int64_t, that portable C99 code.

int64_t var = 0x0000444400004444LL;

For printing:

#define __STDC_FORMAT_MACROS
#include <inttypes.h>

printf("blabla %" PRIi64 " blabla\n", var);

Connection Java-MySql : Public Key Retrieval is not allowed

First of all, please make sure your Database server is up and running. I was getting the same error, after trying all the answers listed here I found out that my Database server was not running.

You can check the same from MySQL Workbench, or Command line using

mysql -u USERNAME -p

This sounds obvious, but many times we assume that Database server is up and running all the time, especially when we are working on our local machine, when we restart/shutdown the machine, Database server will be shutdown automatically.

OS X Framework Library not loaded: 'Image not found'

[Xcode 11+]

The only thing to do is to add the framework to the General->Frameworks, Libraries And Embedded Content section in the General tab of your app target.

Make sure you select the 'Embed & Sign' option.

enter image description here

[Xcode v6 -> Xcode v10]

The only thing to do is to add the framework to the Embedded binaries section in the General tab of your app target.

Screenshot from Xcode

How do I prevent a form from being resized by the user?

Add some code to the Form Load event:

me.maximumsize = new size(Width, Height)
me.minimumsize = me.maximumsize
me.maximizebox = false
me.minimizebox = false

Example: For a Form height and width of 50 pixels each:

me.maximumsize = new size(50, 50)
me.minimumsize = me.maximumsize
me.maximizebox = false
me.minimizebox = false

Note that setting maximumsize and minimumsize to the same size as shown here prevents resizing the Form.

How to check for registry value using VbScript

Set objShell = WScript.CreateObject("WScript.Shell") 
skey = "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{9A25302D-30C0-39D9-BD6F-21E6EC160475}\"
with CreateObject("WScript.Shell")
    on error resume next            ' turn off error trapping
    sValue = .regread(sKey)       ' read attempt
    bFound = (err.number = 0)     ' test for success
end with
if bFound then
    msgbox "exists"
else
  msgbox "not exists" 
End If

Android Studio - Emulator - eglSurfaceAttrib not implemented

I've found the same thing, but only on emulators that have the Use Host GPU setting ticked. Try turning that off, you'll no longer see those warnings (and the emulator will run horribly, horribly slowly..)

In my experience those warnings are harmless. Notice that the "error" is EGL_SUCCESS, which would seem to indicate no error at all!

Apply CSS Style to child elements

div.test td, div.test caption, div.test th 

works for me.

The child selector > does not work in IE6.

How to strip a specific word from a string?

Providing you know the index value of the beginning and end of each word you wish to replace in the character array, and you only wish to replace that particular chunk of data, you could do it like this.

>>> s = "papa is papa is papa"
>>> s = s[:8]+s[8:13].replace("papa", "mama")+s[13:]
>>> print(s)
papa is mama is papa

Alternatively, if you also wish to retain the original data structure, you could store it in a dictionary.

>>> bin = {}
>>> s = "papa is papa is papa"
>>> bin["0"] = s
>>> s = s[:8]+s[8:13].replace("papa", "mama")+s[13:]
>>> print(bin["0"])
papa is papa is papa
>>> print(s)
papa is mama is papa

Changing the default icon in a Windows Forms application

I found that the easiest way is:

  1. Add an Icon file into your WinForms project.
  2. Change the icon files' build action into Embedded Resource
  3. In the Main Form Load function:

    Icon = LoadIcon("< the file name of that icon file >");

What is logits, softmax and softmax_cross_entropy_with_logits?

Tensorflow 2.0 Compatible Answer: The explanations of dga and stackoverflowuser2010 are very detailed about Logits and the related Functions.

All those functions, when used in Tensorflow 1.x will work fine, but if you migrate your code from 1.x (1.14, 1.15, etc) to 2.x (2.0, 2.1, etc..), using those functions result in error.

Hence, specifying the 2.0 Compatible Calls for all the functions, we discussed above, if we migrate from 1.x to 2.x, for the benefit of the community.

Functions in 1.x:

  1. tf.nn.softmax
  2. tf.nn.softmax_cross_entropy_with_logits
  3. tf.nn.sparse_softmax_cross_entropy_with_logits

Respective Functions when Migrated from 1.x to 2.x:

  1. tf.compat.v2.nn.softmax
  2. tf.compat.v2.nn.softmax_cross_entropy_with_logits
  3. tf.compat.v2.nn.sparse_softmax_cross_entropy_with_logits

For more information about migration from 1.x to 2.x, please refer this Migration Guide.

How to insert text in a td with id, using JavaScript

Use jQuery

Look how easy it would be if you did.

Example:

$('#td1').html('hello world');

batch file to check 64bit or 32bit OS

Many DOS commands in the different versions of Windows are similar but may support different parameters. Plus, newer versions of Windows may support new commands or retire older ones. Thus, if you wish to write a batch file that can run on different types of machines, it may prove beneficial to determine the version of Windows on which the batch file is running. This way the batch file can execute commands appropriate to the operating system.

The following batch file will determine whether or not the machine is running Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003, Windows XP, Windows 2000, or Windows NT. It can easily be modified to support other versions of Windows as necessary or to set an environment variable based on the version of Windows detected. Note that for this batch file to correctly discern between newer versions of Windows Server and consumer versions of Windows, it is more convoluted than batch files you may see elsewhere. I have explained the reasoning below.

1) Open a Notepad window.

2) Copy the following text into Notepad (you may want to access this tip's printed version as some lines wrap):

@echo off

ver | find "2003" > nul
if %ERRORLEVEL% == 0 goto ver_2003

ver | find "XP" > nul
if %ERRORLEVEL% == 0 goto ver_xp

ver | find "2000" > nul
if %ERRORLEVEL% == 0 goto ver_2000

ver | find "NT" > nul
if %ERRORLEVEL% == 0 goto ver_nt

if not exist %SystemRoot%\system32\systeminfo.exe goto warnthenexit

systeminfo | find "OS Name" > %TEMP%\osname.txt
FOR /F "usebackq delims=: tokens=2" %%i IN (%TEMP%\osname.txt) DO set vers=%%i

echo %vers% | find "Windows 7" > nul
if %ERRORLEVEL% == 0 goto ver_7

echo %vers% | find "Windows Server 2008" > nul
if %ERRORLEVEL% == 0 goto ver_2008

echo %vers% | find "Windows Vista" > nul
if %ERRORLEVEL% == 0 goto ver_vista

goto warnthenexit

:ver_7
:Run Windows 7 specific commands here.
echo Windows 7
goto exit

:ver_2008
:Run Windows Server 2008 specific commands here.
echo Windows Server 2008
goto exit

:ver_vista
:Run Windows Vista specific commands here.
echo Windows Vista
goto exit

:ver_2003
:Run Windows Server 2003 specific commands here.
echo Windows Server 2003
goto exit

:ver_xp
:Run Windows XP specific commands here.
echo Windows XP
goto exit

:ver_2000
:Run Windows 2000 specific commands here.
echo Windows 2000
goto exit

:ver_nt
:Run Windows NT specific commands here.
echo Windows NT
goto exit

:warnthenexit
echo Machine undetermined.

:exit

3) Save the file as %WINDIR%\whichvers.bat

4) Now, from the command prompt, enter:

whichvers

This will display which version of Windows you are running.

NOTES:

  1. The reasoning for using the SYSTEMINFO command rather than relying on the VER command is because Windows Server 2008 "shares" version numbers with other Windows releases (see Microsoft). Thus relying on a "version number" of 6.0 to detect Windows Vista or 6.1 to detect Windows 7 fails to differentiate a machine from Windows Server 2008 or Windows Server 2008 R2.

  2. The creation of %TEMP%\osname.txt is solely because I could not place the results of systeminfo | find "OS Name" directly into the for /f command - it does not like piped commands. You may find an easier way to handle grabbing the information from SYSTEMINFO - if so, please comment.

  3. The environment variable %vers% has leading spaces. I could remove these with a longer batch file, but in this case it is not necessary.

  4. The batch file detects for SYSTEMINFO as it assumes if it gets beyond the older operating system detections, the running version of Windows is even older and will not have this utility. On Windows 7 64-bit it is still located in the %SystemRoot%\system32 folder - if later versions of Windows become 64-bit only, this batch file may have to be updated.

Return to the Windows XP and DOS page.

How to group pandas DataFrame entries by date in a non-unique column

This might be easier to explain with a sample dataset.

Create Sample Data

Let's assume we have a single column of Timestamps, date and another column we would like to perform an aggregation on, a.

df = pd.DataFrame({'date':pd.DatetimeIndex(['2012-1-1', '2012-6-1', '2015-1-1', '2015-2-1', '2015-3-1']),
                   'a':[9,5,1,2,3]}, columns=['date', 'a'])

df

        date  a
0 2012-01-01  9
1 2012-06-01  5
2 2015-01-01  1
3 2015-02-01  2
4 2015-03-01  3

There are several ways to group by year

  • Use the dt accessor with year property
  • Put date in index and use anonymous function to access year
  • Use resample method
  • Convert to pandas Period

.dt accessor with year property

When you have a column (and not an index) of pandas Timestamps, you can access many more extra properties and methods with the dt accessor. For instance:

df['date'].dt.year

0    2012
1    2012
2    2015
3    2015
4    2015
Name: date, dtype: int64

We can use this to form our groups and calculate some aggregations on a particular column:

df.groupby(df['date'].dt.year)['a'].agg(['sum', 'mean', 'max'])

      sum  mean  max
date                
2012   14     7    9
2015    6     2    3

put date in index and use anonymous function to access year

If you set the date column as the index, it becomes a DateTimeIndex with the same properties and methods as the dt accessor gives normal columns

df1 = df.set_index('date')
df1.index.year

Int64Index([2012, 2012, 2015, 2015, 2015], dtype='int64', name='date')

Interestingly, when using the groupby method, you can pass it a function. This function will be implicitly passed the DataFrame's index. So, we can get the same result from above with the following:

df1.groupby(lambda x: x.year)['a'].agg(['sum', 'mean', 'max'])

      sum  mean  max
2012   14     7    9
2015    6     2    3

Use the resample method

If your date column is not in the index, you must specify the column with the on parameter. You also need to specify the offset alias as a string.

df.resample('AS', on='date')['a'].agg(['sum', 'mean', 'max'])

             sum  mean  max
date                       
2012-01-01  14.0   7.0  9.0
2013-01-01   NaN   NaN  NaN
2014-01-01   NaN   NaN  NaN
2015-01-01   6.0   2.0  3.0

Convert to pandas Period

You can also convert the date column to a pandas Period object. We must pass in the offset alias as a string to determine the length of the Period.

df['date'].dt.to_period('A')

0   2012
1   2012
2   2015
3   2015
4   2015
Name: date, dtype: object

We can then use this as a group

df.groupby(df['date'].dt.to_period('Y'))['a'].agg(['sum', 'mean', 'max'])


      sum  mean  max
2012   14     7    9
2015    6     2    3

How to check whether a variable is a class or not?

The inspect.isclass is probably the best solution, and it's really easy to see how it's actually implemented

def isclass(object):
    """Return true if the object is a class.

    Class objects provide these attributes:
        __doc__         documentation string
        __module__      name of module in which this class was defined"""
    return isinstance(object, (type, types.ClassType))

How to serialize/deserialize to `Dictionary<int, string>` from custom XML not using XElement?

Write a class A, that contains of an array of class B. Class B should have an id property and a value property. Deserialize the xml to class A. Convert the array in A to the wanted dictionary.

To serialize the dictionary convert it to an instance of class A, and serialize...

VS Code - Search for text in all files in a directory

Search across files - Press Ctrl+Shift+F

Find - Press Ctrl+F

Find and Replace - Ctrl+H

For basic editing options follow this link - https://code.visualstudio.com/docs/editor/codebasics

Note : For mac the Ctrl represents the command button

how to set JAVA_OPTS for Tomcat in Windows?

It is recommended that you create a file named setenv.bat and place it in the Tomcat bin directory. With this file (which is run by the catalina.bat and catalina.sh scripts), you can change the following Tomcat environment settings with the JAVA_OPTS variable:

You can set the minimum and maximum memory heap size with the

JVM -Xms and -Xmx parameters.

The best limits depend on many conditions, such as transformations that Integrator ETL should execute. For Information Discovery transformations, a maximum of 1 GB is recommended. For example, to set the minimum heap size to 128 MB and the maximum heap size to 1024 MB, use

JAVA_OPTS=-Xms128m -Xmx1024m        

You should set the maximum limit of the PermGen (Permanent Generation) memory space to a size larger than the default. The default of 64 MB is not enough for enterprise applications. A suitable memory limit depends on various criteria, but 256 MB would make a good choice in most cases. If the PermGen space maximum is too low, OutOfMemoryError: PermGen space errors may occur. You can set the PermGen maximum limit with the following JVM parameter

    -XX:MaxPermSize=256m

For performance reasons, it is recommended that the application is run in Server mode. Apache Tomcat does not run in Server mode by default. You can set the Server mode by using the JVM -server parameter. You can set the JVM parameter in the JAVA_OPTS variable in the environment variable in the setenv file.

The following is an example of a setenv.bat file:

set "JAVA_OPTS=%JAVA_OPTS% -Xms128m -Xmx1024m -XX:MaxPermSize=256m -server"

What is the use of join() in Python threading?

A somewhat clumsy ascii-art to demonstrate the mechanism: The join() is presumably called by the main-thread. It could also be called by another thread, but would needlessly complicate the diagram.

join-calling should be placed in the track of the main-thread, but to express thread-relation and keep it as simple as possible, I choose to place it in the child-thread instead.

without join:
+---+---+------------------                     main-thread
    |   |
    |   +...........                            child-thread(short)
    +..................................         child-thread(long)

with join
+---+---+------------------***********+###      main-thread
    |   |                             |
    |   +...........join()            |         child-thread(short)
    +......................join()......         child-thread(long)

with join and daemon thread
+-+--+---+------------------***********+###     parent-thread
  |  |   |                             |
  |  |   +...........join()            |        child-thread(short)
  |  +......................join()......        child-thread(long)
  +,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,     child-thread(long + daemonized)

'-' main-thread/parent-thread/main-program execution
'.' child-thread execution
'#' optional parent-thread execution after join()-blocked parent-thread could 
    continue
'*' main-thread 'sleeping' in join-method, waiting for child-thread to finish
',' daemonized thread - 'ignores' lifetime of other threads;
    terminates when main-programs exits; is normally meant for 
    join-independent tasks

So the reason you don't see any changes is because your main-thread does nothing after your join. You could say join is (only) relevant for the execution-flow of the main-thread.

If, for example, you want to concurrently download a bunch of pages to concatenate them into a single large page, you may start concurrent downloads using threads, but need to wait until the last page/thread is finished before you start assembling a single page out of many. That's when you use join().

Decimal to Hexadecimal Converter in Java

Simple:

  public static String decToHex(int dec)
  {
        return Integer.toHexString(dec);
  }

As mentioned here: Java Convert integer to hex integer

How can I convert a timestamp from yyyy-MM-ddThh:mm:ss:SSSZ format to MM/dd/yyyy hh:mm:ss.SSS format? From ISO8601 to UTC

Yes. you can use SimpleDateFormat like this.

SimpleDateFormat formatter, FORMATTER;
formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String oldDate = "2011-03-10T11:54:30.207Z";
Date date = formatter.parse(oldDate.substring(0, 24));
FORMATTER = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss.SSS");
System.out.println("OldDate-->"+oldDate);
System.out.println("NewDate-->"+FORMATTER.format(date));

Output OldDate-->2011-03-10T11:54:30.207Z NewDate-->10-Mar-2011 11:54:30.207

How to change max_allowed_packet size

Many of the answerers spotted the issue and already gave the solution.

I just want to suggest another solution, which is changing the Glogal variable value from within the tool Mysql Workbench. That is ofcourse IF you use Workbench running locally on server (or via SSH connection)

You just connect to your instance and go on menu:

Server -> Options File -> Networking -> max_allowed_packed

You set the desired value and then you need to restart MySql Service.

Get current time in milliseconds using C++ and Boost

If you mean milliseconds since epoch you could do

ptime time_t_epoch(date(1970,1,1)); 
ptime now = microsec_clock::local_time();
time_duration diff = now - time_t_epoch;
x = diff.total_milliseconds();

However, it's not particularly clear what you're after.

Have a look at the example in the documentation for DateTime at Boost Date Time

How can I find where Python is installed on Windows?

I installed 2 and 3 and had the same problem finding 3. Fortunately, typing path at the windows path let me find where I had installed it. The path was an option when I installed Python which I just forgot. If you didn't select setting the path when you installed Python 3 that probably won't work - unless you manually updated the path when you installed it. In my case it was at c:\Program Files\Python37\python.exe

Installed Ruby 1.9.3 with RVM but command line doesn't show ruby -v

You have broken version of RVM. Ubuntu does something to RVM that produces lots of errors, the only safe way of fixing for now is to:

sudo apt-get --purge remove ruby-rvm
sudo rm -rf /usr/share/ruby-rvm /etc/rvmrc /etc/profile.d/rvm.sh

open new terminal and validate environment is clean from old RVM settings (should be no output):

env | grep rvm

if there was output, try to open new terminal, if it does not help then restart your computer.

install RVM:

\curl -L https://get.rvm.io | 
  bash -s stable --ruby --autolibs=enable --auto-dotfiles

If you find you need some hand-holding, take a look at Installing Ruby on Ubuntu 12.04, which gives a bit more explanation.

Add legend to ggplot2 line plot

I tend to find that if I'm specifying individual colours in multiple geom's, I'm doing it wrong. Here's how I would plot your data:

##Subset the necessary columns
dd_sub = datos[,c(20, 2,3,5)]
##Then rearrange your data frame
library(reshape2)
dd = melt(dd_sub, id=c("fecha"))

All that's left is a simple ggplot command:

ggplot(dd) + geom_line(aes(x=fecha, y=value, colour=variable)) +
  scale_colour_manual(values=c("red","green","blue"))

Example plot

enter image description here

Android Button setOnClickListener Design

public class MainActivity extends AppCompatActivity  implements View.OnClickListener{

    Button b1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        b1=(Button)findViewById(R.id.button);
        b1.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Toast.makeText(getApplicationContext(),"Button is Working",Toast.LENGTH_LONG).show();
    }

}

Dropdown using javascript onchange

It does not work because your script in JSFiddle is running inside it's own scope (see the "OnLoad" drop down on the left?).

One way around this is to bind your event handler in javascript (where it should be):

document.getElementById('optionID').onchange = function () {
    document.getElementById("message").innerHTML = "Having a Baby!!";
};

Another way is to modify your code for the fiddle environment and explicitly declare your function as global so it can be found by your inline event handler:

window.changeMessage() {
    document.getElementById("message").innerHTML = "Having a Baby!!";
};

?

dropzone.js - how to do something after ALL files are uploaded

Just use queuecomplete that's what its there for and its so so simple. Check the docs http://www.dropzonejs.com/

queuecomplete > Called when all files in the queue finished uploading.

      this.on("queuecomplete", function (file) {
          alert("All files have uploaded ");
      });

How can I combine two commits into one commit?

You want to git rebase -i to perform an interactive rebase.

If you're currently on your "commit 1", and the commit you want to merge, "commit 2", is the previous commit, you can run git rebase -i HEAD~2, which will spawn an editor listing all the commits the rebase will traverse. You should see two lines starting with "pick". To proceed with squashing, change the first word of the second line from "pick" to "squash". Then save your file, and quit. Git will squash your first commit into your second last commit.

Note that this process rewrites the history of your branch. If you are pushing your code somewhere, you'll have to git push -f and anybody sharing your code will have to jump through some hoops to pull your changes.

Note that if the two commits in question aren't the last two commits on the branch, the process will be slightly different.

What is special about /dev/tty?

The 'c' means it's a character device. tty is a special file representing the 'controlling terminal' for the current process.

Character Devices

Unix supports 'device files', which aren't really files at all, but file-like access points to hardware devices. A 'character' device is one which is interfaced byte-by-byte (as opposed to buffered IO).

TTY

/dev/tty is a special file, representing the terminal for the current process. So, when you echo 1 > /dev/tty, your message ('1') will appear on your screen. Likewise, when you cat /dev/tty, your subsequent input gets duplicated (until you press Ctrl-C).

/dev/tty doesn't 'contain' anything as such, but you can read from it and write to it (for what it's worth). I can't think of a good use for it, but there are similar files which are very useful for simple IO operations (e.g. /dev/ttyS0 is normally your serial port)

This quote is from http://tldp.org/HOWTO/Text-Terminal-HOWTO-7.html#ss7.3 :

/dev/tty stands for the controlling terminal (if any) for the current process. To find out which tty's are attached to which processes use the "ps -a" command at the shell prompt (command line). Look at the "tty" column. For the shell process you're in, /dev/tty is the terminal you are now using. Type "tty" at the shell prompt to see what it is (see manual pg. tty(1)). /dev/tty is something like a link to the actually terminal device name with some additional features for C-programmers: see the manual page tty(4).

Here is the man page: http://linux.die.net/man/4/tty

Script Tag - async & defer

async and defer will download the file during HTML parsing. Both will not interrupt the parser.

  • The script with async attribute will be executed once it is downloaded. While the script with defer attribute will be executed after completing the DOM parsing.

  • The scripts loaded with async doesn't guarantee any order. While the scripts loaded with defer attribute maintains the order in which they appear on the DOM.

Use <script async> when the script does not rely on anything. when the script depends use <script defer>.

Best solution would be add the <script> at the bottom of the body. There will be no issue with blocking or rendering.

Best way to save a trained model in PyTorch?

A common PyTorch convention is to save models using either a .pt or .pth file extension.

Save/Load Entire Model Save:

path = "username/directory/lstmmodelgpu.pth"
torch.save(trainer, path)

Load:

Model class must be defined somewhere

model = torch.load(PATH)
model.eval()

How to write and read a file with a HashMap?

You can write an object to a file using writeObject in ObjectOutputStream

ObjectOutputStream

Java Keytool error after importing certificate , "keytool error: java.io.FileNotFoundException & Access Denied"

I got this error too even I ran cmd as an Administrator.

The root cause is: The file is from VCS(subversion, perforce, etc.), and when I checked the properties of this file, its' Attributes is Read-only.

So the solution is:

  • (1) disable the 'Read-only' Attribute;
  • (2) check out from VCS, let the file under the status of read&write.

Why do we use web.xml?

Web.xml is called as deployment descriptor file and its is is an XML file that contains information on the configuration of the web application, including the configuration of servlets.

NameError: name 'datetime' is not defined

It can also be used as below:

from datetime import datetime
start_date = datetime(2016,3,1)
end_date = datetime(2016,3,10)

How to search through all Git and Mercurial commits in the repository for a certain string?

Building on rq's answer, I found this line does what I want:

git grep "search for something" $(git log -g --pretty=format:%h -S"search for something")

Which will report the commit ID, filename, and display the matching line, like this:

91ba969:testFile:this is a test

... Does anyone agree that this would be a nice option to be included in the standard git grep command?

Correct way to populate an Array with a Range in Ruby

I just tried to use ranges from bigger to smaller amount and got the result I didn't expect:

irb(main):007:0> Array(1..5)
=> [1, 2, 3, 4, 5]
irb(main):008:0> Array(5..1)
=> []

That's because of ranges implementations.
So I had to use the following option:

(1..5).to_a.reverse

Converting List<Integer> to List<String>

List<String> stringList = integerList.stream().map((Object s)->String.valueOf(s)).collect(Collectors.toList())

Tesseract running error

I'm using Visual Studio 2017 Community Edition.
I solved this problem by making a directory called tessdata in the Debug directory of my project. Then I put the eng.traineddata file into said directory.

How do I check to see if my array includes an object?

If you want to check if an object is within in array by checking an attribute on the object, you can use any? and pass a block that evaluates to true or false:

unless @suggested_horses.any? {|h| h.id == horse.id }
  @suggested_horses << horse
end

Using AJAX to pass variable to PHP and retrieve those using AJAX again

In your PhP file there's going to be a variable called $_REQUEST and it contains an array with all the data send from Javascript to PhP using AJAX.

Try this: var_dump($_REQUEST); and check if you're receiving the values.

AngularJS : ng-click not working

Have a look at this plunker

HTML:

<!DOCTYPE html>
<html ng-app="app">

  <head>
    <script data-require="[email protected]" data-semver="1.3.0-beta.16" src="https://code.angularjs.org/1.3.0-beta.16/angular.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="FollowsController">
    <div class="row" ng:repeat="follower in myform.all_followers">
      <ons-col class="views-row" size="50" ng-repeat="data in follower">
        <img ng-src="http://dealsscanner.com/obaidtnc/plugmug/uploads/{{data.token}}/thumbnail/{{data.Path}}" alt="{{data.fname}}" ng-click="showDetail2(data.token)" />
        <h3 class="title" ng-click="showDetail2('ss')">{{data.fname}}</h3>
      </ons-col>
    </div>
  </body>

</html>

Javascript:

var app = angular.module('app', []);
//Follows Controller
app.controller('FollowsController', function($scope, $http) {
    var ukey = window.localStorage.ukey;
    //alert(dataFromServer);
    $scope.showDetail = function(index) {
        profileusertoken =  index;
        $scope.ons.navigator.pushPage('profile.html'); 
    }

    function showDetail2(index) {
        alert("here");
    }

    $scope.showDetail2 = showDetail2;
    $scope.myform ={};
    $scope.myform.reports ="";
    $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
    var dataObject = "usertoken="+ukey;
    //var responsePromise = $http.post("follows/", dataObject,{});
    //responsePromise.success(function(dataFromServer, status,    headers, config) {

    $scope.myform.all_followers = [[{fname: "blah"}, {fname: "blah"}, {fname: "blah"}, {fname: "blah"}]];
});

error code 1292 incorrect date value mysql

Insert date in the following format yyyy-MM-dd example,

INSERT INTO `PROGETTO`.`ALBERGO`(`ID`, `nome`, `viale`, `num_civico`, `data_apertura`, `data_chiusura`, `orario_apertura`, `orario_chiusura`, `posti_liberi`, `costo_intero`, `costo_ridotto`, `stelle`, `telefono`, `mail`, `web`, `Nome-paese`, `Comune`) 
VALUES(0, 'Hotel Centrale', 'Via Passo Rolle', '74', '2012-05-01', '2012-09-31', '06:30', '24:00', 80, 50, 25, 3, '43968083', '[email protected]', 'http://www.hcentrale.it/', 'Trento', 'TN')

VSCode single to double quote automatic replace

Try one of these solutions

  1. In vscode settings.json file add this entry "prettier.singleQuote": true
  2. In vscode if you have .editorconfig file, add this line under the root [*] symbol quote_type = single
  3. In vscode if you have .prettierrc file, add this line
{
    "singleQuote": true,
    "vetur.format.defaultFormatterOptions": {
        "prettier": {
            "singleQuote": true
        }
    }
}

Format y axis as percent

This is a few months late, but I have created PR#6251 with matplotlib to add a new PercentFormatter class. With this class you just need one line to reformat your axis (two if you count the import of matplotlib.ticker):

import ...
import matplotlib.ticker as mtick

ax = df['myvar'].plot(kind='bar')
ax.yaxis.set_major_formatter(mtick.PercentFormatter())

PercentFormatter() accepts three arguments, xmax, decimals, symbol. xmax allows you to set the value that corresponds to 100% on the axis. This is nice if you have data from 0.0 to 1.0 and you want to display it from 0% to 100%. Just do PercentFormatter(1.0).

The other two parameters allow you to set the number of digits after the decimal point and the symbol. They default to None and '%', respectively. decimals=None will automatically set the number of decimal points based on how much of the axes you are showing.

Update

PercentFormatter was introduced into Matplotlib proper in version 2.1.0.

What exactly is the difference between Web API and REST API in MVC?

I have been there, like so many of us. There are so many confusing words like Web API, REST, RESTful, HTTP, SOAP, WCF, Web Services... and many more around this topic. But I am going to give brief explanation of only those which you have asked.

REST

It is neither an API nor a framework. It is just an architectural concept. You can find more details here.

RESTful

I have not come across any formal definition of RESTful anywhere. I believe it is just another buzzword for APIs to say if they comply with REST specifications.

EDIT: There is another trending open source initiative OpenAPI Specification (OAS) (formerly known as Swagger) to standardise REST APIs.

Web API

It in an open source framework for writing HTTP APIs. These APIs can be RESTful or not. Most HTTP APIs we write are not RESTful. This framework implements HTTP protocol specification and hence you hear terms like URIs, request/response headers, caching, versioning, various content types(formats).

Note: I have not used the term Web Services deliberately because it is a confusing term to use. Some people use this as a generic concept, I preferred to call them HTTP APIs. There is an actual framework named 'Web Services' by Microsoft like Web API. However it implements another protocol called SOAP.

Is there a way to get a list of all current temporary tables in SQL Server?

SELECT left(NAME, charindex('_', NAME) - 1)
FROM tempdb..sysobjects
WHERE NAME LIKE '#%'
    AND NAME NOT LIKE '##%'
    AND upper(xtype) = 'U'
    AND NOT object_id('tempdb..' + NAME) IS NULL

you can remove the ## line if you want to include global temp tables.

adb doesn't show nexus 5 device

In my case:

  • The phone was connected as a media device.
  • Clicked on that message and got a menu. "USB computer connection"
  • In that menu chose to connect it as a camera (for devices that do not support MTP)

And then it worked.

The OutputPath property is not set for this project

This happened to me because I had moved the following line close to the beginning of the .csproj file:

  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets"/>

It needs to be placed after the PropertyGroups that define your Configuration|Platform.

git add remote branch

You can check if you got your remote setup right and have the proper permissions with

git ls-remote origin

if you called your remote "origin". If you get an error you probably don't have your security set up correctly such as uploading your public key to github for example. If things are setup correctly, you will get a list of the remote references. Now

git fetch origin

will work barring any other issues like an unplugged network cable.

Once you have that done, you can get any branch you want that the above command listed with

git checkout some-branch

this will create a local branch of the same name as the remote branch and check it out.

How to remove &quot; from my Json in javascript?

Accepted answer is right, however I had a trouble with that. When I add in my code, checking on debugger, I saw that it changes from

result.replace(/&quot;/g,'"')

to

result.replace(/&#34;/g,'"')

Instead of this I use that:

result.replace(/(&quot\;)/g,"\"")

By this notation it works.

pip installation /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory

I had used home-brew to install 2.7 on OS X 10.10 and the new install was missing the sym links. I ran

brew link --overwrite python

as mentioned in How to symlink python in Homebrew? and it solved the problem.

LaTeX source code listing like in professional books

Take a look at algorithms package, especially the algorithm environment.

How do I open workbook programmatically as read-only?

Does this work?

Workbooks.Open Filename:=filepath, ReadOnly:=True

Or, as pointed out in a comment, to keep a reference to the opened workbook:

Dim book As Workbook
Set book = Workbooks.Open(Filename:=filepath, ReadOnly:=True)

java.lang.UnsupportedClassVersionError: Unsupported major.minor version 51.0 (unable to load class frontend.listener.StartupListener)

What is your output when you do java -version? This will tell you what version the running JVM is.

The Unsupported major.minor version 51.0 error could mean:

  • Your server is running a lower Java version then the one used to compile your Servlet and vice versa

Either way, uninstall all JVM runtimes including JDK and download latest and re-install. That should fix any Unsupported major.minor error as you will have the lastest JRE and JDK (Maybe even newer then the one used to compile the Servlet)

See: http://www.java.com/en/download/manual.jsp (7 Update 25 )

and here: http://www.oracle.com/technetwork/java/javase/downloads/index.html (Java Platform (JDK) 7u25)

for the latest version of the JRE and JDK respectively.

EDIT:

Most likely your code was written in Java7 however maybe it was done using Java7update4 and your system is running Java7update3. Thus they both are effectively the same major version but the minor versions differ. Only the larger minor version is backward compatible with the lower minor version.

Edit 2 : If you have more than one jdk installed on your pc. you should check that Apache Tomcat is using the same one (jre) you are compiling your programs with. If you installed a new jdk after installing apache it normally won't select the new version.

error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)' -- Missing /var/run/mysqld/mysqld.sock

My solution;

Ubuntu 18.04 (WSL)

/etc/mysql/my.cnf

!includedir /etc/mysql/conf.d/
!includedir /etc/mysql/mysql.conf.d/

/etc/mysql/mysql.conf.d/mysqld.cnf

[mysqld]
user            = mysql
pid-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock
port            = 3306

I changed the port. It's worked for me. You can write another port. Example 3355

How to delete files recursively from an S3 bucket

With the latest aws-cli python command line tools, to recursively delete all the files under a folder in a bucket is just:

aws s3 rm --recursive s3://your_bucket_name/foo/

Or delete everything under the bucket:

aws s3 rm --recursive s3://your_bucket_name

If what you want is to actually delete the bucket, there is one-step shortcut:

aws s3 rb --force s3://your_bucket_name

which will remove the contents in that bucket recursively then delete the bucket.

Note: the s3:// protocol prefix is required for these commands to work

AngularJS - $http.post send data as json

i think the most proper way is to use the same piece of code angular use when doing a "get" request using you $httpParamSerializer will have to inject it to your controller so you can simply do the following without having to use Jquery at all , $http.post(url,$httpParamSerializer({param:val}))

app.controller('ctrl',function($scope,$http,$httpParamSerializer){
  $http.post(url,$httpParamSerializer({param:val,secondParam:secondVal}));
}

.NET NewtonSoft JSON deserialize map to a different property name

Json.NET has a JsonPropertyAttribute which allows you to specify the name of a JSON property, so your code should be:

public class TeamScore
{
    [JsonProperty("eighty_min_score")]
    public string EightyMinScore { get; set; }
    [JsonProperty("home_or_away")]
    public string HomeOrAway { get; set; }
    [JsonProperty("score ")]
    public string Score { get; set; }
    [JsonProperty("team_id")]
    public string TeamId { get; set; }
}

public class Team
{
    public string v1 { get; set; }
    [JsonProperty("attributes")]
    public TeamScore TeamScores { get; set; }
}

public class RootObject
{
    public List<Team> Team { get; set; }
}

Documentation: Serialization Attributes

angularjs: allows only numbers to be typed into a text box

I had a similar issue and ended up hooking and event

ng-change="changeCount()" 

then:

self.changeCount = function () {
      if (!self.info.itemcount) {
        self.info.itemcount = 1;
      }
 };

So the user is defaulted to 1 if a invalid number is inserted.

How to capture UIView to UIImage without loss of quality on retina display

I have created a Swift extension based on @Dima solution:

extension UIImage {
    class func imageWithView(view: UIView) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0)
        view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img
    }
}

EDIT: Swift 4 improved version

extension UIImage {
    class func imageWithView(_ view: UIView) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.isOpaque, 0)
        defer { UIGraphicsEndImageContext() }
        view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
        return UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
    }
}

Usage:

let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))  
let image = UIImage.imageWithView(view)

How can a Javascript object refer to values in itself?

This is not JSON. JSON was designed to be simple; allowing arbitrary expressions is not simple.

In full JavaScript, I don't think you can do this directly. You cannot refer to this until the object called obj is fully constructed. So you need a workaround, that someone with more JavaScript-fu than I will provide.

How to create id with AUTO_INCREMENT on Oracle?

This is how I did this on an existing table and column (named id):

UPDATE table SET id=ROWNUM;
DECLARE
  maxval NUMBER;
BEGIN
  SELECT MAX(id) INTO maxval FROM table;
  EXECUTE IMMEDIATE 'DROP SEQUENCE table_seq';
  EXECUTE IMMEDIATE 'CREATE SEQUENCE table_seq START WITH '|| TO_CHAR(TO_NUMBER(maxval)+1) ||' INCREMENT BY 1 NOMAXVALUE';
END;
CREATE TRIGGER table_trigger
  BEFORE INSERT ON table
  FOR EACH ROW
BEGIN
  :new.id := table_seq.NEXTVAL;
END;

Making authenticated POST requests with Spring RestTemplate for Android

I was recently dealing with an issue when I was trying to get past authentication while making a REST call from Java, and while the answers in this thread (and other threads) helped, there was still a bit of trial and error involved in getting it working.

What worked for me was encoding credentials in Base64 and adding them as Basic Authorization headers. I then added them as an HttpEntity to restTemplate.postForEntity, which gave me the response I needed.

Here's the class I wrote for this in full (extending RestTemplate):

public class AuthorizedRestTemplate extends RestTemplate{

    private String username;
    private String password;

    public AuthorizedRestTemplate(String username, String password){
        this.username = username;
        this.password = password;
    }

    public String getForObject(String url, Object... urlVariables){
        return authorizedRestCall(this, url, urlVariables);
    }

    private String authorizedRestCall(RestTemplate restTemplate, 
            String url, Object... urlVariables){
        HttpEntity<String> request = getRequest();
        ResponseEntity<String> entity = restTemplate.postForEntity(url, 
                request, String.class, urlVariables);
        return entity.getBody();
    }

    private HttpEntity<String> getRequest(){
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Basic " + getBase64Credentials());
        return new HttpEntity<String>(headers);
    }

    private String getBase64Credentials(){
        String plainCreds = username + ":" + password;
        byte[] plainCredsBytes = plainCreds.getBytes();
        byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
        return new String(base64CredsBytes);
    }
}

SQL Developer is returning only the date, not the time. How do I fix this?

Well I found this way :

Oracle SQL Developer (Left top icon) > Preferences > Database > NLS and set the Date Format as MM/DD/YYYY HH24:MI:SS

enter image description here

What's a clean way to stop mongod on Mac OS X?

If you have installed mongodb community server via homebrew, then you can do:

brew services list

This will list the current services as below:

Name              Status  User          Plist
mongodb-community started thehaystacker /Users/thehaystacker/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist

redis             stopped

Then you can restart mongodb by first stopping and restart:

brew services stop mongodb
brew services start mongodb

Should I use encodeURI or encodeURIComponent for encoding URLs?

xkr.us has a great discussion, with examples. To quote their summary:

The escape() method does not encode the + character which is interpreted as a space on the server side as well as generated by forms with spaces in their fields. Due to this shortcoming and the fact that this function fails to handle non-ASCII characters correctly, you should avoid use of escape() whenever possible. The best alternative is usually encodeURIComponent().

escape() will not encode: @*/+

Use of the encodeURI() method is a bit more specialized than escape() in that it encodes for URIs as opposed to the querystring, which is part of a URL. Use this method when you need to encode a string to be used for any resource that uses URIs and needs certain characters to remain un-encoded. Note that this method does not encode the ' character, as it is a valid character within URIs.

encodeURI() will not encode: ~!@#$&*()=:/,;?+'

Lastly, the encodeURIComponent() method should be used in most cases when encoding a single component of a URI. This method will encode certain chars that would normally be recognized as special chars for URIs so that many components may be included. Note that this method does not encode the ' character, as it is a valid character within URIs.

encodeURIComponent() will not encode: ~!*()'

How to bring an activity to foreground (top of stack)?

i.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);

Note Your homeactivity launchmode should be single_task

Detecting real time window size changes in Angular 4

The answer is very simple. write the below code

import { Component, OnInit, OnDestroy, Input } from "@angular/core";
// Import this, and write at the top of your .ts file
import { HostListener } from "@angular/core";

@Component({
 selector: "app-login",
 templateUrl: './login.component.html',
 styleUrls: ['./login.component.css']
})

export class LoginComponent implements OnInit, OnDestroy {
// Declare height and width variables
scrHeight:any;
scrWidth:any;

@HostListener('window:resize', ['$event'])
getScreenSize(event?) {
      this.scrHeight = window.innerHeight;
      this.scrWidth = window.innerWidth;
      console.log(this.scrHeight, this.scrWidth);
}

// Constructor
constructor() {
    this.getScreenSize();
}
}

Why is JsonRequestBehavior needed?

To make it easier for yourself you could also create an actionfilterattribute

public class AllowJsonGetAttribute : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        var jsonResult = filterContext.Result as JsonResult;

        if (jsonResult == null)
            throw new ArgumentException("Action does not return a JsonResult, 
                                                   attribute AllowJsonGet is not allowed");

        jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;            

        base.OnResultExecuting(filterContext);
    }
}

and use it on your action

[AllowJsonGet]
public JsonResult MyAjaxAction()
{
    return Json("this is my test");
}

Difference between array_push() and $array[] =

No one said, but array_push only pushes a element to the END OF THE ARRAY, where $array[index] can insert a value at any given index. Big difference.

Running a cron every 30 seconds

Run in a shell loop, example:

#!/bin/sh    
counter=1
while true ; do
 echo $counter
 counter=$((counter+1))
 if [[ "$counter" -eq 60 ]]; then
  counter=0
 fi
 wget -q http://localhost/tool/heartbeat/ -O - > /dev/null 2>&1 &
 sleep 1
done

InputStream from a URL

Here is a full example which reads the contents of the given web page. The web page is read from an HTML form. We use standard InputStream classes, but it could be done more easily with JSoup library.

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>

</dependency>

<dependency>
    <groupId>commons-validator</groupId>
    <artifactId>commons-validator</artifactId>
    <version>1.6</version>
</dependency>  

These are the Maven dependencies. We use Apache Commons library to validate URL strings.

package com.zetcode.web;

import com.zetcode.service.WebPageReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "ReadWebPage", urlPatterns = {"/ReadWebPage"})
public class ReadWebpage extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/plain;charset=UTF-8");

        String page = request.getParameter("webpage");

        String content = new WebPageReader().setWebPageName(page).getWebPageContent();

        ServletOutputStream os = response.getOutputStream();
        os.write(content.getBytes(StandardCharsets.UTF_8));
    }
}

The ReadWebPage servlet reads the contents of the given web page and sends it back to the client in plain text format. The task of reading the page is delegated to WebPageReader.

package com.zetcode.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import org.apache.commons.validator.routines.UrlValidator;

public class WebPageReader {

    private String webpage;
    private String content;

    public WebPageReader setWebPageName(String name) {

        webpage = name;
        return this;
    }

    public String getWebPageContent() {

        try {

            boolean valid = validateUrl(webpage);

            if (!valid) {

                content = "Invalid URL; use http(s)://www.example.com format";
                return content;
            }

            URL url = new URL(webpage);

            try (InputStream is = url.openStream();
                    BufferedReader br = new BufferedReader(
                            new InputStreamReader(is, StandardCharsets.UTF_8))) {

                content = br.lines().collect(
                      Collectors.joining(System.lineSeparator()));
            }

        } catch (IOException ex) {

            content = String.format("Cannot read webpage %s", ex);
            Logger.getLogger(WebPageReader.class.getName()).log(Level.SEVERE, null, ex);
        }

        return content;
    }

    private boolean validateUrl(String webpage) {

        UrlValidator urlValidator = new UrlValidator();

        return urlValidator.isValid(webpage);
    }
}

WebPageReader validates the URL and reads the contents of the web page. It returns a string containing the HTML code of the page.

<!DOCTYPE html>
<html>
    <head>
        <title>Home page</title>
        <meta charset="UTF-8">
    </head>
    <body>
        <form action="ReadWebPage">

            <label for="page">Enter a web page name:</label>
            <input  type="text" id="page" name="webpage">

            <button type="submit">Submit</button>

        </form>
    </body>
</html>

Finally, this is the home page containing the HTML form. This is taken from my tutorial about this topic.

How do I mount a host directory as a volume in docker compose

If you would like to mount a particular host directory (/disk1/prometheus-data in the following example) as a volume in the volumes section of the Docker Compose YAML file, you can do it as below, e.g.:

version: '3'

services:
  prometheus:
    image: prom/prometheus
    volumes:
      - prometheus-data:/prometheus

volumes:
  prometheus-data:
    driver: local
    driver_opts:
      o: bind
      type: none
      device: /disk1/prometheus-data

By the way, in prometheus's Dockerfile, You may find the VOLUME instruction as below, which marks it as holding externally mounted volumes from native host, etc. (Note however: this instruction is not a must though to mount a volume into a container.):

Dockerfile

...
VOLUME ["/prometheus"]
...

Refs:

Using switch statement with a range of value in each case?

For input number in range 0..100

int n1 = 75; // input value
String res; int n=0; 
int[] a ={0,20,35,55,70,85,101};

for(; n1>=a[n]; n++);
switch(6-n+1) {
  case 1: res="A"; break;
  case 2: res="B"; break;
  case 3: res="C"; break;
  case 4: res="D"; break;
  case 5: res="E"; break;
  default:res="F";
}
System.out.println(res);

CSS /JS to prevent dragging of ghost image?

For Firefox you need to go a little deeper with this:

var imgs = document.getElementsByTagName('img');

    // loop through fetched images
    for (i = 0; i < imgs.length; i++) {
        // and define onmousedown event handler
        imgs[i].onmousedown = disableDragging;
    }

function disableDragging(e) {
        e.preventDefault();
    }

Enjoy.

Comparing object properties in c#

I ended up doing this:

    public static string ToStringNullSafe(this object obj)
    {
        return obj != null ? obj.ToString() : String.Empty;
    }
    public static bool Compare<T>(T a, T b)
    {
        int count = a.GetType().GetProperties().Count();
        string aa, bb;
        for (int i = 0; i < count; i++)
        {
            aa = a.GetType().GetProperties()[i].GetValue(a, null).ToStringNullSafe();
            bb = b.GetType().GetProperties()[i].GetValue(b, null).ToStringNullSafe();
            if (aa != bb)
            {
                return false;
            }
        }
        return true;
    }

Usage:

    if (Compare<ObjectType>(a, b))

Update

If you want to ignore some properties by name:

    public static string ToStringNullSafe(this object obj)
    {
        return obj != null ? obj.ToString() : String.Empty;
    }
    public static bool Compare<T>(T a, T b, params string[] ignore)
    {
        int count = a.GetType().GetProperties().Count();
        string aa, bb;
        for (int i = 0; i < count; i++)
        {
            aa = a.GetType().GetProperties()[i].GetValue(a, null).ToStringNullSafe();
            bb = b.GetType().GetProperties()[i].GetValue(b, null).ToStringNullSafe();
            if (aa != bb && ignore.Where(x => x == a.GetType().GetProperties()[i].Name).Count() == 0)
            {
                return false;
            }
        }
        return true;
    }

Usage:

    if (MyFunction.Compare<ObjType>(a, b, "Id","AnotherProp"))

How to select multiple files with <input type="file">?

<form action="" method="post" enctype="multipart/form-data">
<input type="file" multiple name="img[]"/>
<input type="submit">
</form>
<?php
print_r($_FILES['img']['name']);
?>

Can a table have two foreign keys?

create table Table1
(
  id varchar(2),
  name varchar(2),
  PRIMARY KEY (id)
)


Create table Table1_Addr
(
  addid varchar(2),
  Address varchar(2),
  PRIMARY KEY (addid)
)

Create table Table1_sal
(
  salid varchar(2),`enter code here`
  addid varchar(2),
  id varchar(2),
  PRIMARY KEY (salid),
  index(addid),
  index(id),
  FOREIGN KEY (addid) REFERENCES Table1_Addr(addid),
  FOREIGN KEY (id) REFERENCES Table1(id)
)

No module named Image

You can this query:

pip install image 

I had pillow installed, and still, I got the error that you mentioned. But after I executed the above command, the error vanished. And My program worked perfectly.

how to run command "mysqladmin flush-hosts" on Amazon RDS database Server instance?

When an Amazon RDS instance is blocked because the value of max_connect_errors has been exceeded, you cannot use the host that generated the connection errors to issue the "flush hosts" command, as the MySQL Server running on the instance is at that point blocking connections from that host.

You therefore need to issue the "flush hosts" command from another EC2 instance or remote server that has access to that RDS instance.

mysqladmin -h [YOUR RDS END POINT URL] -P 3306 -u [DB USER] -p flush-hosts

If this involved launching a new instance, or creating/modifying security groups to permit external access, it may be quicker to simply login to the RDS user interface and reboot the RDS instance that is blocked.

Get div height with plain JavaScript

Here's one more alternative:

var classElements = document.getElementsByClassName("className");

function setClassHeight (classElements, desiredHeightValue) 
    {
        var arrayElements = Object.entries(classElements);
        for(var i = 0; i< arrayElements.length; i++) {
            arrayElements[i][1].style.height = desiredHeightValue;
        }

    }