Programs & Examples On #Boost lambda

How to insert TIMESTAMP into my MySQL table?

$insertation = "INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', CURRENT_TIMESTAMP(), '$comments')";

You can use this Query. CURRENT_TIMESTAMP

Remember to use the parenthesis CURRENT_TIMESTAMP()

C++ compile time error: expected identifier before numeric constant

Initializations with (...) in the class body is not allowed. Use {..} or = .... Unfortunately since the respective constructor is explicit and vector has an initializer list constructor, you need a functional cast to call the wanted constructor

vector<string> name = decltype(name)(5);
vector<int> val = decltype(val)(5,0);

As an alternative you can use constructor initializer lists

 Attribute():name(5), val(5, 0) {}

Namespace not recognized (even though it is there)

In my case I got the error only in VS 2015. When opening the project in VS 2017 the error was gone.

How does one create an InputStream from a String?

Java 7+

It's possible to take advantage of the StandardCharsets JDK class:

String str=...
InputStream is = new ByteArrayInputStream(StandardCharsets.UTF_16.encode(str).array());

Object passed as parameter to another class, by value or reference?

Objects will be passed by reference irrespective of within methods of same class or another class. Here is a modified version of same sample code to help you understand. The value will be changed to 'xyz.'

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    public class Employee
    {
        public string Name { get; set; }
    }

    public class MyClass
    {
        public Employee EmpObj;

        public void SetObject(Employee obj)
        {
            EmpObj = obj;
        }
    }

    public class Program
    {
       static void Main(string[] args)
        {
            Employee someTestObj = new Employee();
            someTestObj.Name = "ABC";

            MyClass cls = new MyClass();
            cls.SetObject(someTestObj);

            Console.WriteLine("Changing Emp Name To xyz");
            someTestObj.Name = "xyz";

            Console.WriteLine("Accessing Assigned Emp Name");
            Console.WriteLine(cls.EmpObj.Name); 

           Console.ReadLine();
       }       
    }
 }

How to convert JSON data into a Python object

You can use

x = Map(json.loads(response))
x.__class__ = MyClass

where

class Map(dict):
    def __init__(self, *args, **kwargs):
        super(Map, self).__init__(*args, **kwargs)
        for arg in args:
            if isinstance(arg, dict):
                for k, v in arg.iteritems():
                    self[k] = v
                    if isinstance(v, dict):
                        self[k] = Map(v)

        if kwargs:
            # for python 3 use kwargs.items()
            for k, v in kwargs.iteritems():
                self[k] = v
                if isinstance(v, dict):
                    self[k] = Map(v)

    def __getattr__(self, attr):
        return self.get(attr)

    def __setattr__(self, key, value):
        self.__setitem__(key, value)

    def __setitem__(self, key, value):
        super(Map, self).__setitem__(key, value)
        self.__dict__.update({key: value})

    def __delattr__(self, item):
        self.__delitem__(item)

    def __delitem__(self, key):
        super(Map, self).__delitem__(key)
        del self.__dict__[key]

For a generic, future-proof solution.

Right way to write JSON deserializer in Spring or extend it

I've searched a lot and the best way I've found so far is on this article:

Class to serialize

package net.sghill.example;

import net.sghill.example.UserDeserializer
import net.sghill.example.UserSerializer
import org.codehaus.jackson.map.annotate.JsonDeserialize;
import org.codehaus.jackson.map.annotate.JsonSerialize;

@JsonDeserialize(using = UserDeserializer.class)
public class User {
    private ObjectId id;
    private String   username;
    private String   password;

    public User(ObjectId id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public ObjectId getId()       { return id; }
    public String   getUsername() { return username; }
    public String   getPassword() { return password; }
}

Deserializer class

package net.sghill.example;

import net.sghill.example.User;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.ObjectCodec;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;

import java.io.IOException;

public class UserDeserializer extends JsonDeserializer<User> {

    @Override
    public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        ObjectCodec oc = jsonParser.getCodec();
        JsonNode node = oc.readTree(jsonParser);
        return new User(null, node.get("username").getTextValue(), node.get("password").getTextValue());
    }
}

Edit: Alternatively you can look at this article which uses new versions of com.fasterxml.jackson.databind.JsonDeserializer.

How to split one string into multiple variables in bash shell?

If your solution doesn't have to be general, i.e. only needs to work for strings like your example, you could do:

var1=$(echo $STR | cut -f1 -d-)
var2=$(echo $STR | cut -f2 -d-)

I chose cut here because you could simply extend the code for a few more variables...

How do you extract a column from a multi-dimensional array?

I think you want to extract a column from an array such as an array below

import numpy as np
A = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])

Now if you want to get the third column in the format

D=array[[3],
[7],
[11]]

Then you need to first make the array a matrix

B=np.asmatrix(A)
C=B[:,2]
D=asarray(C)

And now you can do element wise calculations much like you would do in excel.

Simplest way to read json from a URL in java

Here's a full sample of how to parse Json content. The example takes the Android versions statistics (found from Android Studio source code here, which links to here).

Copy the "distributions.json" file you get from there into res/raw, as a fallback.

build.gradle

    implementation 'com.google.code.gson:gson:2.8.6'

manifest

  <uses-permission android:name="android.permission.INTERNET" />

MainActivity.kt

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        if (savedInstanceState != null)
            return
        thread {
            // https://cs.android.com/android/platform/superproject/+/studio-master-dev:tools/adt/idea/android/src/com/android/tools/idea/stats/DistributionService.java
            var root: JsonArray
            Log.d("AppLog", "loading...")
            try {
                HttpURLConnection.setFollowRedirects(true)
                val statsUrl = "https://dl.google.com/android/studio/metadata/distributions.json" //just a string
                val url = URL(statsUrl)
                val request: HttpURLConnection = url.openConnection() as HttpURLConnection
                request.connectTimeout = 3000
                request.connect()
                InputStreamReader(request.content as InputStream).use {
                    root = JsonParser.parseReader(it).asJsonArray
                }
            } catch (e: Exception) {
                Log.d("AppLog", "error while loading from Internet, so using fallback")
                e.printStackTrace()
                InputStreamReader(resources.openRawResource(R.raw.distributions)).use {
                    root = JsonParser.parseReader(it).asJsonArray
                }
            }
            val decimalFormat = DecimalFormat("0.00")
            Log.d("AppLog", "result:")

            root.forEach {
                val androidVersionInfo = it.asJsonObject
                val versionNickName = androidVersionInfo.get("name").asString
                val versionName = androidVersionInfo.get("version").asString
                val versionApiLevel = androidVersionInfo.get("apiLevel").asInt
                val marketSharePercentage = androidVersionInfo.get("distributionPercentage").asFloat * 100f
                Log.d("AppLog", "\"$versionNickName\" - $versionName - API$versionApiLevel - ${decimalFormat.format(marketSharePercentage)}%")
            }
        }
    }
}

As alternative to the dependency, you can also use this instead:

InputStreamReader(request.content as InputStream).use {
    val jsonArray = JSONArray(it.readText())
}

and the fallback:

InputStreamReader(resources.openRawResource(R.raw.distributions)).use {
    val jsonArray = JSONArray(it.readText())
}

The result of running this:

loading...
result:
"Ice Cream Sandwich" - 4.0 - API15 - 0.20%
"Jelly Bean" - 4.1 - API16 - 0.60%
"Jelly Bean" - 4.2 - API17 - 0.80%
"Jelly Bean" - 4.3 - API18 - 0.30%
"KitKat" - 4.4 - API19 - 4.00%
"Lollipop" - 5.0 - API21 - 1.80%
"Lollipop" - 5.1 - API22 - 7.40%
"Marshmallow" - 6.0 - API23 - 11.20%
"Nougat" - 7.0 - API24 - 7.50%
"Nougat" - 7.1 - API25 - 5.40%
"Oreo" - 8.0 - API26 - 7.30%
"Oreo" - 8.1 - API27 - 14.00%
"Pie" - 9.0 - API28 - 31.30%
"Android 10" - 10.0 - API29 - 8.20%

Pandas dataframe groupby plot

Simple plot,

you can use:

df.plot(x='Date',y='adj_close')

Or you can set the index to be Date beforehand, then it's easy to plot the column you want:

df.set_index('Date', inplace=True)
df['adj_close'].plot()

If you want a chart with one series by ticker on it

You need to groupby before:

df.set_index('Date', inplace=True)
df.groupby('ticker')['adj_close'].plot(legend=True)

enter image description here


If you want a chart with individual subplots:

grouped = df.groupby('ticker')

ncols=2
nrows = int(np.ceil(grouped.ngroups/ncols))

fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(12,4), sharey=True)

for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):
    grouped.get_group(key).plot(ax=ax)

ax.legend()
plt.show()

enter image description here

how to determine size of tablespace oracle 11g

One of the way is Using below sql queries

--Size of All Table Space

--1. Used Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "USED SPACE(IN GB)" FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME
--2. Free Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "FREE SPACE(IN GB)" FROM   USER_FREE_SPACE GROUP BY TABLESPACE_NAME

--3. Both Free & Used
SELECT USED.TABLESPACE_NAME, USED.USED_BYTES AS "USED SPACE(IN GB)",  FREE.FREE_BYTES AS "FREE SPACE(IN GB)"
FROM
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS USED_BYTES FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME) USED
INNER JOIN
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS FREE_BYTES FROM  USER_FREE_SPACE GROUP BY TABLESPACE_NAME) FREE
ON (USED.TABLESPACE_NAME = FREE.TABLESPACE_NAME);

How to set default values in Go structs

One possible idea is to write separate constructor function

//Something is the structure we work with
type Something struct {
     Text string 
     DefaultText string 
} 
// NewSomething create new instance of Something
func NewSomething(text string) Something {
   something := Something{}
   something.Text = text
   something.DefaultText = "default text"
   return something
}

delete image from folder PHP

<?php

    require 'database.php';

    $id = $_GET['id'];

    $image = "SELECT * FROM slider WHERE id = '$id'";
    $query = mysqli_query($connect, $image);
    $after = mysqli_fetch_assoc($query);

    if ($after['image'] != 'default.png') {
        unlink('../slider/'.$after['image']);
    }

    $delete = "DELETE FROM slider WHERE id = $id";
    $query = mysqli_query($connect, $delete);

    if ($query) {
        header('location: slider.php');
    }

?>

Postgres user does not exist?

The solution is simple:
log in as root
and after:

su - postgres

psql

LINK : fatal error LNK1561: entry point must be defined ERROR IN VC++

In Visual Studio: Properties -> Advanced -> Entry Point -> write just the name of the function you want the program to begin running from, case sensitive, without any brackets and command line arguments.

Convert double to float in Java

First of all, the fact that the value in the database is a float does not mean that it also fits in a Java float. Float is short for floating point, and floating point types of various precisions exist. Java types float and double are both floating point types of different precision. In a database both are called FLOAT. Since double has a higher precision than float, it probably is a better idea not to cast your value to a float, because you might lose precision.

You might also use BigDecimal, which represent an arbitrary-precision number.

EF 5 Enable-Migrations : No context type was found in the assembly

I have encountered this problem a few times and in my case I uninstalled EntityFramework nuget package and installed EntityFrameworkCore nuget package, entityFramework.design and entityframework.tools

How do I horizontally center an absolute positioned element inside a 100% width div?

If you want to align center on left attribute.
The same thing is for top alignment, you could use margin-top: (width/2 of your div), the concept is the same of left attribute.
It's important to set header element to position:relative.
try this:

#logo {
    background:red;
    height:50px;
    position:absolute;
    width:50px;
    left:50%;
    margin-left:-25px;
}

DEMO

If you would like to not use calculations you can do this:

#logo {
  background:red;
  width:50px;
  height:50px;
  position:absolute;
  left: 0;
  right: 0;
  margin: 0 auto;
}

DEMO2

What is the symbol for whitespace in C?

To check a space symbol you can use the following approach

if ( c == ' ' ) { /*...*/ }

To check a space and/or a tab symbol (standard blank characters) you can use the following approach

#include <ctype.h>

//...

if ( isblank( c ) ) { /*...*/ }

To check a white space you can use the following approach

#include <ctype.h>

//...

if ( isspace( c ) ) { /*...*/ }

Webdriver and proxy server for firefox

FirefoxProfile profile = new FirefoxProfile();
String PROXY = "xx.xx.xx.xx:xx";
OpenQA.Selenium.Proxy proxy = new OpenQA.Selenium.Proxy();
proxy.HttpProxy=PROXY;
proxy.FtpProxy=PROXY;
proxy.SslProxy=PROXY;
profile.SetProxyPreferences(proxy);
FirefoxDriver driver = new FirefoxDriver(profile);

It is for C#

Start index for iterating Python list

Here's a rotation generator which doesn't need to make a warped copy of the input sequence ... may be useful if the input sequence is much larger than 7 items.

>>> def rotated_sequence(seq, start_index):
...     n = len(seq)
...     for i in xrange(n):
...         yield seq[(i + start_index) % n]
...
>>> s = 'su m tu w th f sa'.split()
>>> list(rotated_sequence(s, s.index('m')))
['m', 'tu', 'w', 'th', 'f', 'sa', 'su']
>>>

How to get value by key from JObject?

Try this:

private string GetJArrayValue(JObject yourJArray, string key)
{
    foreach (KeyValuePair<string, JToken> keyValuePair in yourJArray)
    {
        if (key == keyValuePair.Key)
        {
            return keyValuePair.Value.ToString();
        }
    }
}

How to increment datetime by custom months in python without using library

To calculate the current, previous and next month:

import datetime
this_month = datetime.date.today().month
last_month = datetime.date.today().month - 1 or 12
next_month = (datetime.date.today().month + 1) % 12 or 12

String's Maximum length in Java - calling length() method

As mentioned in Takahiko Kawasaki's answer, java represents Unicode strings in the form of modified UTF-8 and in JVM-Spec CONSTANT_UTF8_info Structure, 2 bytes are allocated to length (and not the no. of characters of String).
To extend the answer, the ASM jvm bytecode library's putUTF8 method, contains this:

public ByteVector putUTF8(final String stringValue) {
    int charLength = stringValue.length();
    if (charLength > 65535) {   
   // If no. of characters> 65535, than however UTF-8 encoded length, wont fit in 2 bytes.
      throw new IllegalArgumentException("UTF8 string too large");
    }
    for (int i = 0; i < charLength; ++i) {
      char charValue = stringValue.charAt(i);
      if (charValue >= '\u0001' && charValue <= '\u007F') {
        // Unicode code-point encoding in utf-8 fits in 1 byte.
        currentData[currentLength++] = (byte) charValue;
      } else {
        // doesnt fit in 1 byte.
        length = currentLength;
        return encodeUtf8(stringValue, i, 65535);
      }
    }
    ...
}

But when code-point mapping > 1byte, it calls encodeUTF8 method:

final ByteVector encodeUtf8(final String stringValue, final int offset, final int maxByteLength /*= 65535 */) {
    int charLength = stringValue.length();
    int byteLength = offset;
    for (int i = offset; i < charLength; ++i) {
      char charValue = stringValue.charAt(i);
      if (charValue >= 0x0001 && charValue <= 0x007F) {
        byteLength++;
      } else if (charValue <= 0x07FF) {
        byteLength += 2;
      } else {
        byteLength += 3;
      }
    }
   ...
}

In this sense, the max string length is 65535 bytes, i.e the utf-8 encoding length. and not char count
You can find the modified-Unicode code-point range of JVM, from the above utf8 struct link.

Converting a vector<int> to string

template<typename T>
string str(T begin, T end)
{
    stringstream ss;
    bool first = true;
    for (; begin != end; begin++)
    {
        if (!first)
            ss << ", ";
        ss << *begin;
        first = false;
    }
    return ss.str();
}

This is the str function that can make integers turn into a string and not into a char for what the integer represents. Also works for doubles.

What is the python "with" statement designed for?

See PEP 343 - The 'with' statement, there is an example section at the end.

... new statement "with" to the Python language to make it possible to factor out standard uses of try/finally statements.

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

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

What is the hamburger menu icon called and the three vertical dots icon called?

We call it the "ant" menu. Guess it was a good time to change since everyone had just gotten used to the hamburger.

Defined Edges With CSS3 Filter Blur

If you are using background image, the best way I found is:

filter: blur(5px);
margin-top: -5px;
padding-bottom: 10px;
margin-left: -5px;
padding-right: 10px;

Listing all extras of an Intent

You could use for (String key : keys) { Object o = get(key); to return an Object, call getClass().getName() on it to get the type, and then do a set of if name.equals("String") type things to work out which method you should actually be calling, in order to get the value?

jQuery autoComplete view all on click?

this shows all the options: "%" (see below)

The important thing is that you have to place it underneath the previous #example declaration, like in the example below. This took me a while to figure out.

$( "#example" ).autocomplete({
            source: "countries.php",
            minLength: 1,
            selectFirst: true
});

$("#example").autocomplete( "search", "%" );

What is the C# equivalent of friend?

There's no direct equivalent of "friend" - the closest that's available (and it isn't very close) is InternalsVisibleTo. I've only ever used this attribute for testing - where it's very handy!

Example: To be placed in AssemblyInfo.cs

[assembly: InternalsVisibleTo("OtherAssembly")]

Apache HttpClient 4.0.3 - how do I set cookie with sessionID for POST request?

HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
response = client.execute(httppost, localContext);

doesn't work in 4.5 version without

cookie.setDomain(".domain.com");
cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "true");

Extract every nth element of a vector

a <- 1:120
b <- a[seq(1, length(a), 6)]

How to indent HTML tags in Notepad++

The answers on this question are not only wrong, but dangerous. CTRL+ALT+SHIFT+B will not indent HTML but XML. Consider the following HTML code:

<span class="myClass"></span>

The function 'Notepad++ -> Plugins -> XmlTools -> Pretty print (Xml only with line breaks)' (CTRL+ALT+SHIFT+B) will transform this to:

<span class="myClass"/>

which will not be displayed correctly anymore by your browser! I strongly advice against using this function to indent HTML.

Instead use the plugin Tidy2. This will indent the HTML correctly without bad side-effects (but it will also create <html>, <head>, <body>, ... elements around your code, if these are not there).

Does Python support short-circuiting?

Yep, both and and or operators short-circuit -- see the docs.

Twitter bootstrap progress bar animation on page load

Here's a cross-browser CSS-only solution. Hope it helps!

DEMO

_x000D_
_x000D_
.progress .progress-bar {_x000D_
    -moz-animation-name: animateBar;_x000D_
    -moz-animation-iteration-count: 1;_x000D_
    -moz-animation-timing-function: ease-in;_x000D_
    -moz-animation-duration: .4s;_x000D_
_x000D_
    -webkit-animation-name: animateBar;_x000D_
    -webkit-animation-iteration-count: 1;_x000D_
    -webkit-animation-timing-function: ease-in;_x000D_
    -webkit-animation-duration: .4s;_x000D_
_x000D_
    animation-name: animateBar;_x000D_
    animation-iteration-count: 1;_x000D_
    animation-timing-function: ease-in;_x000D_
    animation-duration: .4s;_x000D_
}_x000D_
_x000D_
@-moz-keyframes animateBar {_x000D_
    0% {-moz-transform: translateX(-100%);}_x000D_
    100% {-moz-transform: translateX(0);}_x000D_
}_x000D_
@-webkit-keyframes animateBar {_x000D_
    0% {-webkit-transform: translateX(-100%);}_x000D_
    100% {-webkit-transform: translateX(0);}_x000D_
}_x000D_
@keyframes animateBar {_x000D_
    0% {transform: translateX(-100%);}_x000D_
    100% {transform: translateX(0);}_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="container">_x000D_
  _x000D_
  <h3>Progress bar animation on load</h3>_x000D_
  _x000D_
  <div class="progress">_x000D_
    <div class="progress-bar progress-bar-success" style="width: 75%;"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

div inside php echo

You can also do this,

<?php 
if ( ($cart->count_product) > 0) { 
  $print .= "<div class='my_class'>"
  $print .= $cart->count_product; 
  $print .= "</div>"
} else { 
   $print = ''; 
} 
echo  $print;
?>

Reading json files in C++

  1. Yes you can create a nested data structure people which can be indexed by Anna and Ben. However, you can't index it directly by age and profession (I will get to this part in the code).

  2. The data type of people is of type Json::Value (which is defined in jsoncpp). You are right, it is similar to the nested map, but Value is a data structure which is defined such that multiple types can be stored and accessed. It is similar to a map with a string as the key and Json::Value as the value. It could also be a map between an unsigned int as key and Json::Value as the value (In case of json arrays).

Here's the code:

#include <json/value.h>
#include <fstream>

std::ifstream people_file("people.json", std::ifstream::binary);
people_file >> people;

cout<<people; //This will print the entire json object.

//The following lines will let you access the indexed objects.
cout<<people["Anna"]; //Prints the value for "Anna"
cout<<people["ben"]; //Prints the value for "Ben"
cout<<people["Anna"]["profession"]; //Prints the value corresponding to "profession" in the json for "Anna"

cout<<people["profession"]; //NULL! There is no element with key "profession". Hence a new empty element will be created.

As you can see, you can index the json object only based on the hierarchy of the input data.

Error converting data types when importing from Excel to SQL Server 2008

When Excel finds mixed data types in same column it guesses what is the right format for the column (the majority of the values determines the type of the column) and dismisses all other values by inserting NULLs. But Excel does it far badly (e.g. if a column is considered text and Excel finds a number then decides that the number is a mistake and insert a NULL instead, or if some cells containing numbers are "text" formatted, one may get NULL values into an integer column of the database).

Solution:

  1. Create a new excel sheet with the name of the columns in the first row
  2. Format the columns as text
  3. Paste the rows without format (use CVS format or copy/paste in Notepad to get only text)

Note that formatting the columns on an existing Excel sheet is not enough.

Getting Chrome to accept self-signed localhost certificate

2020-05-22: With only 5 openssl commands, you can accomplish this.

Please do not change your browser security settings.

With the following code, you can (1) become your own CA, (2) then sign your SSL certificate as a CA. (3) Then import the CA certificate (not the SSL certificate, which goes onto your server) into Chrome/Chromium. (Yes, this works even on Linux.)

NB: For Windows, some reports say that openssl must be run with winpty to avoid a crash.

######################
# Become a Certificate Authority
######################

# Generate private key
openssl genrsa -des3 -out myCA.key 2048
# Generate root certificate
openssl req -x509 -new -nodes -key myCA.key -sha256 -days 825 -out myCA.pem

######################
# Create CA-signed certs
######################

NAME=mydomain.com # Use your own domain name
# Generate a private key
openssl genrsa -out $NAME.key 2048
# Create a certificate-signing request
openssl req -new -key $NAME.key -out $NAME.csr
# Create a config file for the extensions
>$NAME.ext cat <<-EOF
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = $NAME # Be sure to include the domain name here because Common Name is not so commonly honoured by itself
DNS.2 = bar.$NAME # Optionally, add additional domains (I've added a subdomain here)
IP.1 = 192.168.0.13 # Optionally, add an IP address (if the connection which you have planned requires it)
EOF
# Create the signed certificate
openssl x509 -req -in $NAME.csr -CA myCA.pem -CAkey myCA.key -CAcreateserial \
-out $NAME.crt -days 825 -sha256 -extfile $NAME.ext

To recap:

  1. Become a CA
  2. Sign your certificate using your CA cert+key
  3. Import myCA.pem as an "Authority" (not into "Your Certificates") in your Chrome settings (Settings > Manage certificates > Authorities > Import)
  4. Use the $NAME.crt and $NAME.key files in your server

Extra steps (for Mac, at least):

  1. Import the CA cert at "File > Import file", then also find it in the list, right click it, expand "> Trust", and select "Always"
  2. Add extendedKeyUsage=serverAuth,clientAuth below basicConstraints=CA:FALSE, and make sure you set the "CommonName" to the same as $NAME when it's asking for setup

You can check your work to ensure that the certificate is built correctly:

openssl verify -CAfile myCA.pem -verify_hostname bar.mydomain.com mydomain.com.crt

How do I parse a HTML page with Node.js

Use htmlparser2, its way faster and pretty straightforward. Consult this usage example:

https://www.npmjs.org/package/htmlparser2#usage

And the live demo here:

http://demos.forbeslindesay.co.uk/htmlparser2/

How to install an APK file on an Android phone?

I quote Hello Android because I can't say it better ;-)

You need to enable USB debugging on the phone itself (by starting the Settings application and selecting Applications > Development > USB Debugging), install the Android USB device driver if you haven’t already (Windows only), and then plug the phone into your computer using the USB cable that came with the phone.

Close the emulator window if it’s already open. As long as the phone is plugged in, Eclipse will load and run applications on the phone instead. You need to right-click the project and select Run As > Android Application.

How do you perform wireless debugging in Xcode 9 with iOS 11, Apple TV 4K, etc?

Step 1 : First time connect phone with Cable

Step 2 : Go to Organizer & Devices

Step 3 : Tick Connect as Network

Now simple trick which works everytime.

Step 4 : Turn on hotspot on iphone

Step 5 : Connect your mac with that hotspot.

Step 6 : Now run the code.

This will always work.

Insert Unicode character into JavaScript

Although @ruakh gave a good answer, I will add some alternatives for completeness:

You could in fact use even var Omega = '&#937;' in JavaScript, but only if your JavaScript code is:

  • inside an event attribute, as in onclick="var Omega = '&#937'; alert(Omega)" or
  • in a script element inside an XHTML (or XHTML + XML) document served with an XML content type.

In these cases, the code will be first (before getting passed to the JavaScript interpreter) be parsed by an HTML parser so that character references like &#937; are recognized. The restrictions make this an impractical approach in most cases.

You can also enter the O character as such, as in var Omega = 'O', but then the character encoding must allow that, the encoding must be properly declared, and you need software that let you enter such characters. This is a clean solution and quite feasible if you use UTF-8 encoding for everything and are prepared to deal with the issues created by it. Source code will be readable, and reading it, you immediately see the character itself, instead of code notations. On the other hand, it may cause surprises if other people start working with your code.

Using the \u notation, as in var Omega = '\u03A9', works independently of character encoding, and it is in practice almost universal. It can however be as such used only up to U+FFFF, i.e. up to \uffff, but most characters that most people ever heard of fall into that area. (If you need “higher” characters, you need to use either surrogate pairs or one of the two approaches above.)

You can also construct a character using the String.fromCharCode() method, passing as a parameter the Unicode number, in decimal as in var Omega = String.fromCharCode(937) or in hexadecimal as in var Omega = String.fromCharCode(0x3A9). This works up to U+FFFF. This approach can be used even when you have the Unicode number in a variable.

How do I close an open port from the terminal on the Mac?

One liner is best

kill -9 $(lsof -i:PORT -t) 2> /dev/null

Example : On mac, wanted to clear port 9604. Following command worked like a charm

 kill -9 $(lsof -i:9604 -t) 2> /dev/null 

Font from origin has been blocked from loading by Cross-Origin Resource Sharing policy

If you want to allow all the fonts from a folder for a specific domain then you can use this:

  <location path="assets/font">
    <system.webServer>
      <httpProtocol>
        <customHeaders>
          <add name="Access-Control-Allow-Origin" value="http://localhost:3000" />
        </customHeaders>
      </httpProtocol>
    </system.webServer>
  </location>

where assets/font is the location where all fonts are and http://localhost:3000 is the location which you want to allow.

Python: Generate random number between x and y which is a multiple of 5

The simplest way is to generate a random nuber between 0-1 then strech it by multiplying, and shifting it.
So yo would multiply by (x-y) so the result is in the range of 0 to x-y,
Then add x and you get the random number between x and y.

To get a five multiplier use rounding. If this is unclear let me know and I'll add code snippets.

"Object doesn't support property or method 'find'" in IE

You are using the JavaScript array.find() method. Note that this is standard JS, and has nothing to do with jQuery. In fact, your entire code in the question makes no use of jQuery at all.

You can find the documentation for array.find() here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find

If you scroll to the bottom of this page, you will note that it has browser support info, and you will see that it states that IE does not support this method.

Ironically, your best way around this would be to use jQuery, which does have similar functionality that is supported in all browsers.

Visual Studio keyboard shortcut to display IntelliSense

The most efficient one is Ctrl + ..

It helps to automate insertions of using directives. It works if the focus is on a new identifier, e.g. class name.

Auto increment in MongoDB to store sequence of Unique User ID

You can, but you should not https://web.archive.org/web/20151009224806/http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/

Each object in mongo already has an id, and they are sortable in insertion order. What is wrong with getting collection of user objects, iterating over it and use this as incremented ID? Er go for kind of map-reduce job entirely

How to run a shell script on a Unix console or Mac terminal?

First, give permission for execution:-
chmod +x script_name

  1. If script is not executable:-
    For running sh script file:-
    sh script_name
    For running bash script file:-
    bash script_name
  2. If script is executable:-
    ./script_name

NOTE:-you can check if the file is executable or not by using 'ls -a'

How do you create a static class in C++?

Consider Matt Price's solution.

  1. In C++, a "static class" has no meaning. The nearest thing is a class with only static methods and members.
  2. Using static methods will only limit you.

What you want is, expressed in C++ semantics, to put your function (for it is a function) in a namespace.

Edit 2011-11-11

There is no "static class" in C++. The nearest concept would be a class with only static methods. For example:

// header
class MyClass
{
   public :
      static void myMethod() ;
} ;

// source
void MyClass::myMethod()
{
   // etc.
}

But you must remember that "static classes" are hacks in the Java-like kind of languages (e.g. C#) that are unable to have non-member functions, so they have instead to move them inside classes as static methods.

In C++, what you really want is a non-member function that you'll declare in a namespace:

// header
namespace MyNamespace
{
   void myMethod() ;
}

// source
namespace MyNamespace
{
   void myMethod()
   {
      // etc.
   }
}

Why is that?

In C++, the namespace is more powerful than classes for the "Java static method" pattern, because:

  • static methods have access to the classes private symbols
  • private static methods are still visible (if inaccessible) to everyone, which breaches somewhat the encapsulation
  • static methods cannot be forward-declared
  • static methods cannot be overloaded by the class user without modifying the library header
  • there is nothing that can be done by a static method that can't be done better than a (possibly friend) non-member function in the same namespace
  • namespaces have their own semantics (they can be combined, they can be anonymous, etc.)
  • etc.

Conclusion: Do not copy/paste that Java/C#'s pattern in C++. In Java/C#, the pattern is mandatory. But in C++, it is bad style.

Edit 2010-06-10

There was an argument in favor to the static method because sometimes, one needs to use a static private member variable.

I disagree somewhat, as show below:

The "Static private member" solution

// HPP

class Foo
{
   public :
      void barA() ;
   private :
      void barB() ;
      static std::string myGlobal ;
} ;

First, myGlobal is called myGlobal because it is still a global private variable. A look at the CPP source will clarify that:

// CPP
std::string Foo::myGlobal ; // You MUST declare it in a CPP

void Foo::barA()
{
   // I can access Foo::myGlobal
}

void Foo::barB()
{
   // I can access Foo::myGlobal, too
}

void barC()
{
   // I CAN'T access Foo::myGlobal !!!
}

At first sight, the fact the free function barC can't access Foo::myGlobal seems a good thing from an encapsulation viewpoint... It's cool because someone looking at the HPP won't be able (unless resorting to sabotage) to access Foo::myGlobal.

But if you look at it closely, you'll find that it is a colossal mistake: Not only your private variable must still be declared in the HPP (and so, visible to all the world, despite being private), but you must declare in the same HPP all (as in ALL) functions that will be authorized to access it !!!

So using a private static member is like walking outside in the nude with the list of your lovers tattooed on your skin : No one is authorized to touch, but everyone is able to peek at. And the bonus: Everyone can have the names of those authorized to play with your privies.

private indeed... :-D

The "Anonymous namespaces" solution

Anonymous namespaces will have the advantage of making things private really private.

First, the HPP header

// HPP

namespace Foo
{
   void barA() ;
}

Just to be sure you remarked: There is no useless declaration of barB nor myGlobal. Which means that no one reading the header knows what's hidden behind barA.

Then, the CPP:

// CPP
namespace Foo
{
   namespace
   {
      std::string myGlobal ;

      void Foo::barB()
      {
         // I can access Foo::myGlobal
      }
   }

   void barA()
   {
      // I can access myGlobal, too
   }
}

void barC()
{
   // I STILL CAN'T access myGlobal !!!
}

As you can see, like the so-called "static class" declaration, fooA and fooB are still able to access myGlobal. But no one else can. And no one else outside this CPP knows fooB and myGlobal even exist!

Unlike the "static class" walking on the nude with her address book tattooed on her skin the "anonymous" namespace is fully clothed, which seems quite better encapsulated AFAIK.

Does it really matter?

Unless the users of your code are saboteurs (I'll let you, as an exercise, find how one can access to the private part of a public class using a dirty behaviour-undefined hack...), what's private is private, even if it is visible in the private section of a class declared in a header.

Still, if you need to add another "private function" with access to the private member, you still must declare it to all the world by modifying the header, which is a paradox as far as I am concerned: If I change the implementation of my code (the CPP part), then the interface (the HPP part) should NOT change. Quoting Leonidas : "This is ENCAPSULATION!"

Edit 2014-09-20

When are classes static methods are actually better than namespaces with non-member functions?

When you need to group together functions and feed that group to a template:

namespace alpha
{
   void foo() ;
   void bar() ;
}

struct Beta
{
   static void foo() ;
   static void bar() ;
};

template <typename T>
struct Gamma
{
   void foobar()
   {
      T::foo() ;
      T::bar() ;
   }
};

Gamma<alpha> ga ; // compilation error
Gamma<Beta> gb ;  // ok
gb.foobar() ;     // ok !!!

Because, if a class can be a template parameter, a namespaces cannot.

How to add an item to an ArrayList in Kotlin?

You can add element to arrayList using add() method in Kotlin. For example,

arrayList.add(10)

Above code will add element 10 to arrayList.

However, if you are using Array or List, then you can not add element. This is because Array and List are Immutable. If you want to add element, you will have to use MutableList.

Several workarounds:

  1. Using System.arraycopy() method: You can achieve same target by creating new array and copying all the data from existing array into new one along with new values. This way you will have new array with all desired values(Existing and New values)
  2. Using MutableList:: Convert array into mutableList using toMutableList() method. Then, add element into it.
  3. Using Array.copyof(): Somewhat similar as System.arraycopy() method.

Where value in column containing comma delimited values

If you know the ID's rather than the strings, use this approach:

where mylookuptablecolumn IN (myarrayorcommadelimitedarray)

Just make sure that myarrayorcommadelimitedarray is not put in string quotes.

works if you want A OR B, but not AND.

Min/Max of dates in an array?

Code is tested with IE,FF,Chrome and works properly:

var dates=[];
dates.push(new Date("2011/06/25"))
dates.push(new Date("2011/06/26"))
dates.push(new Date("2011/06/27"))
dates.push(new Date("2011/06/28"))
var maxDate=new Date(Math.max.apply(null,dates));
var minDate=new Date(Math.min.apply(null,dates));

Deleting queues in RabbitMQ

With the rabbitmq_management plugin installed you can run this to delete all the unwanted queues:

rabbitmqctl list_queues -p vhost_name |\
grep -v "fast\|medium\|slow" |\
tr "[:blank:]" " " |\
cut -d " " -f 1 |\
xargs -I {} curl -i -u guest:guest -H "content-type:application/json" -XDELETE http://localhost:15672/api/queues/<vhost_name>/{}

Let's break the command down:

rabbitmqctl list_queues -p vhost_name will list all the queues and how many task they have currently.

grep -v "fast\|medium\|slow" will filter the queues you don't want to delete, let's say we want to delete every queue without the words fast, medium or slow.

tr "[:blank:]" " " will normalize the delimiter on rabbitmqctl between the name of the queue and the amount of tasks there are

cut -d " " -f 1 will split each line by the whitespace and pick the 1st column (the queue name)

xargs -I {} curl -i -u guest:guest -H "content-type:application/json" -XDELETE http://localhost:15672/api/queues/<vhost>/{} will pick up the queue name and will set it into where we set the {} character deleting all queues not filtered in the process.

Be sure the user been used has administrator permissions.

What are Transient and Volatile Modifiers?

Transient :

First need to know where it needed how it bridge the gap.

1) An Access modifier transient is only applicable to variable component only. It will not used with method or class.

2) Transient keyword cannot be used along with static keyword.

3) What is serialization and where it is used? Serialization is the process of making the object's state persistent. That means the state of the object is converted into a stream of bytes to be used for persisting (e.g. storing bytes in a file) or transferring (e.g. sending bytes across a network). In the same way, we can use the deserialization to bring back the object's state from bytes. This is one of the important concepts in Java programming because serialization is mostly used in networking programming. The objects that need to be transmitted through the network have to be converted into bytes. Before understanding the transient keyword, one has to understand the concept of serialization. If the reader knows about serialization, please skip the first point.

Note 1) Transient is mainly use for serialzation process. For that the class must implement the java.io.Serializable interface. All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.

Note 2) When deserialized process taken place they get set to the default value - zero, false, or null as per type constraint.

Note 3) Transient keyword and its purpose? A field which is declare with transient modifier it will not take part in serialized process. When an object is serialized(saved in any state), the values of its transient fields are ignored in the serial representation, while the field other than transient fields will take part in serialization process. That is the main purpose of the transient keyword.

How to add an event after close the modal window?

Few answers that may be useful, especially if you have dynamic content.

$('#dialogueForm').live("dialogclose", function(){
   //your code to run on dialog close
});

Or, when opening the modal, have a callback.

$( "#dialogueForm" ).dialog({
              autoOpen: false,
              height: "auto",
              width: "auto",
              modal: true,
                my: "center",
                at: "center",
                of: window,
              close : function(){
                  // functionality goes here
              }  
              });

Rails: Default sort order for a rails model?

A quick update to Michael's excellent answer above.

For Rails 4.0+ you need to put your sort in a block like this:

class Book < ActiveRecord::Base
  default_scope { order('created_at DESC') }
end

Notice that the order statement is placed in a block denoted by the curly braces.

They changed it because it was too easy to pass in something dynamic (like the current time). This removes the problem because the block is evaluated at runtime. If you don't use a block you'll get this error:

Support for calling #default_scope without a block is removed. For example instead of default_scope where(color: 'red'), please use default_scope { where(color: 'red') }. (Alternatively you can just redefine self.default_scope.)

As @Dan mentions in his comment below, you can do a more rubyish syntax like this:

class Book < ActiveRecord::Base
  default_scope { order(created_at: :desc) }
end

or with multiple columns:

class Book < ActiveRecord::Base
  default_scope { order({begin_date: :desc}, :name) }
end

Thanks @Dan!

How to fix getImageData() error The canvas has been tainted by cross-origin data?

Your problem is that you load an external image, meaning from another domain. This causes a security error when you try to access any data of your canvas context.

inline if statement java, why is not working

cond? statementA: statementB

Equals to:

if (cond)
    statementA
else
    statementB

For your case, you may just delete all "if". If you totally use if-else instead of ?:. Don't mix them together.

Regular Expressions: Is there an AND operator?

Use a non-consuming regular expression.

The typical (i.e. Perl/Java) notation is:

(?=expr)

This means "match expr but after that continue matching at the original match-point."

You can do as many of these as you want, and this will be an "and." Example:

(?=match this expression)(?=match this too)(?=oh, and this)

You can even add capture groups inside the non-consuming expressions if you need to save some of the data therein.

How to correctly set the ORACLE_HOME variable on Ubuntu 9.x?

This is the right way to clear this error.

export ORACLE_HOME=/u01/app/oracle/product/10.2.0/db_1 sqlplus / as sysdba

What do $? $0 $1 $2 mean in shell script?

These are positional arguments of the script.

Executing

./script.sh Hello World

Will make

$0 = ./script.sh
$1 = Hello
$2 = World

Note

If you execute ./script.sh, $0 will give output ./script.sh but if you execute it with bash script.sh it will give output script.sh.

How do I deserialize a JSON string into an NSDictionary? (For iOS 5+)

With Swift 3 and Swift 4, String has a method called data(using:allowLossyConversion:). data(using:allowLossyConversion:) has the following declaration:

func data(using encoding: String.Encoding, allowLossyConversion: Bool = default) -> Data?

Returns a Data containing a representation of the String encoded using a given encoding.

With Swift 4, String's data(using:allowLossyConversion:) can be used in conjunction with JSONDecoder's decode(_:from:) in order to deserialize a JSON string into a dictionary.

Furthermore, with Swift 3 and Swift 4, String's data(using:allowLossyConversion:) can also be used in conjunction with JSONSerialization's json?Object(with:?options:?) in order to deserialize a JSON string into a dictionary.


#1. Swift 4 solution

With Swift 4, JSONDecoder has a method called decode(_:from:). decode(_:from:) has the following declaration:

func decode<T>(_ type: T.Type, from data: Data) throws -> T where T : Decodable

Decodes a top-level value of the given type from the given JSON representation.

The Playground code below shows how to use data(using:allowLossyConversion:) and decode(_:from:) in order to get a Dictionary from a JSON formatted String:

let jsonString = """
{"password" : "1234",  "user" : "andreas"}
"""

if let data = jsonString.data(using: String.Encoding.utf8) {
    do {
        let decoder = JSONDecoder()
        let jsonDictionary = try decoder.decode(Dictionary<String, String>.self, from: data)
        print(jsonDictionary) // prints: ["user": "andreas", "password": "1234"]
    } catch {
        // Handle error
        print(error)
    }
}

#2. Swift 3 and Swift 4 solution

With Swift 3 and Swift 4, JSONSerialization has a method called json?Object(with:?options:?). json?Object(with:?options:?) has the following declaration:

class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any

Returns a Foundation object from given JSON data.

The Playground code below shows how to use data(using:allowLossyConversion:) and json?Object(with:?options:?) in order to get a Dictionary from a JSON formatted String:

import Foundation

let jsonString = "{\"password\" : \"1234\",  \"user\" : \"andreas\"}"

if let data = jsonString.data(using: String.Encoding.utf8) {
    do {
        let jsonDictionary = try JSONSerialization.jsonObject(with: data, options: []) as? [String : String]
        print(String(describing: jsonDictionary)) // prints: Optional(["user": "andreas", "password": "1234"])
    } catch {
        // Handle error
        print(error)
    }
}

Split by comma and strip whitespace in Python

Split using a regular expression. Note I made the case more general with leading spaces. The list comprehension is to remove the null strings at the front and back.

>>> import re
>>> string = "  blah, lots  ,  of ,  spaces, here "
>>> pattern = re.compile("^\s+|\s*,\s*|\s+$")
>>> print([x for x in pattern.split(string) if x])
['blah', 'lots', 'of', 'spaces', 'here']

This works even if ^\s+ doesn't match:

>>> string = "foo,   bar  "
>>> print([x for x in pattern.split(string) if x])
['foo', 'bar']
>>>

Here's why you need ^\s+:

>>> pattern = re.compile("\s*,\s*|\s+$")
>>> print([x for x in pattern.split(string) if x])
['  blah', 'lots', 'of', 'spaces', 'here']

See the leading spaces in blah?

Clarification: above uses the Python 3 interpreter, but results are the same in Python 2.

.rar, .zip files MIME Type

For upload:

An official list of mime types can be found at The Internet Assigned Numbers Authority (IANA) . According to their list Content-Type header for zip is application/zip.

The media type for rar files is not officially registered at IANA but the unofficial commonly used mime-type value is application/x-rar-compressed.

application/octet-stream means as much as: "I send you a file stream and the content of this stream is not specified" (so it is true that it can be a zip or rar file as well). The server is supposed to detect what the actual content of the stream is.

Note: For upload it is not safe to rely on the mime type set in the Content-Type header. The header is set on the client and can be set to any random value. Instead you can use the php file info functions to detect the file mime-type on the server.


For download:

If you want to download a zip file and nothing else you should only set one single Accept header value. Any additional values set will be used as a fallback in case the server cannot satisfy your in the Accept header requested mime-type.

According to the WC3 specifications this:

application/zip, application/octet-stream 

will be intrepreted as: "I prefer a application/zip mime-type, but if you cannot deliver this an application/octet-stream (a file stream) is also fine".

So only a single:

application/zip

Will guarantee you a zip file (or a 406 - Not Acceptable response in case the server is unable to satisfy your request).

How to detect if CMD is running as Administrator/has elevated privileges?

A "not-a-one-liner" version of https://stackoverflow.com/a/38856823/2193477

@echo off
net.exe session 1>NUL 2>NUL || goto :not_admin
echo SUCCESS
goto :eof

:not_admin
echo ERROR: Please run as a local administrator.
exit /b 1

Routing with multiple Get methods in ASP.NET Web API

Also you will specify route on action for set route

[HttpGet]
[Route("api/customers/")]
public List<Customer> Get()
{
   //gets all customer logic
}

[HttpGet]
[Route("api/customers/currentMonth")]
public List<Customer> GetCustomerByCurrentMonth()
{
     //gets some customer 
}

[HttpGet]
[Route("api/customers/{id}")]
public Customer GetCustomerById(string id)
{
  //gets a single customer by specified id
}
[HttpGet]
[Route("api/customers/customerByUsername/{username}")]
public Customer GetCustomerByUsername(string username)
{
    //gets customer by its username
}

How to get root directory of project in asp.net core. Directory.GetCurrentDirectory() doesn't seem to work correctly on a mac

Working on .Net Core 2.2 and 3.0 as of now.

To get the projects root directory within a Controller:

  • Create a property for the hosting environment

    private readonly IHostingEnvironment _hostingEnvironment;
    
  • Add Microsoft.AspNetCore.Hosting to your controller

    using Microsoft.AspNetCore.Hosting;
    
  • Register the service in the constructor

    public HomeController(IHostingEnvironment hostingEnvironment) {
        _hostingEnvironment = hostingEnvironment;
    }
    
  • Now, to get the projects root path

    string projectRootPath = _hostingEnvironment.ContentRootPath;
    

To get the "wwwroot" path, use

_hostingEnvironment.WebRootPath

What are the differences between a clustered and a non-clustered index?

Clustered Index

  • Only one per table
  • Faster to read than non clustered as data is physically stored in index order

Non Clustered Index

  • Can be used many times per table
  • Quicker for insert and update operations than a clustered index

Both types of index will improve performance when select data with fields that use the index but will slow down update and insert operations.

Because of the slower insert and update clustered indexes should be set on a field that is normally incremental ie Id or Timestamp.

SQL Server will normally only use an index if its selectivity is above 95%.

MySQL - ERROR 1045 - Access denied

use this command to check the possible output

mysql> select user,host,password from mysql.user;

output

mysql> select user,host,password from mysql.user;
+-------+-----------------------+-------------------------------------------+
| user  | host                  | password                                  |
+-------+-----------------------+-------------------------------------------+
| root  | localhost             | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| root  | localhost.localdomain | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| root  | 127.0.0.1             | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| admin | localhost             | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 |
| admin | %                     |                                           |
+-------+-----------------------+-------------------------------------------+
5 rows in set (0.00 sec)
  1. In this user admin will not be allowed to login from another host though you have granted permission. the reason is that user admin is not identified by any password.
  2. Grant the user admin with password using GRANT command once again

    mysql> GRANT ALL PRIVILEGES ON *.* TO 'admin'@'%' IDENTIFIED by 'password'
    

then check the GRANT LIST the out put will be like his

mysql> select user,host,password from mysql.user;

+-------+-----------------------+-------------------------------------------+
| user  | host                  | password                                  |
+-------+-----------------------+-------------------------------------------+
| root  | localhost             | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| root  | localhost.localdomain | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| root  | 127.0.0.1             | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| admin | localhost             | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 |
| admin | %                     | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 |
+-------+-----------------------+-------------------------------------------+
5 rows in set (0.00 sec)

if the desired user for example user 'admin' is need to be allowed login then use once GRANT command and execute the command.

Now the user should be allowed to login.

Java multiline string

In the IntelliJ IDE you just need to type:

""

Then position your cursor inside the quotation marks and paste your string. The IDE will expand it into multiple concatenated lines.

Entityframework Join using join method and lambdas

Generally i prefer the lambda syntax with LINQ, but Join is one example where i prefer the query syntax - purely for readability.

Nonetheless, here is the equivalent of your above query (i think, untested):

var query = db.Categories         // source
   .Join(db.CategoryMaps,         // target
      c => c.CategoryId,          // FK
      cm => cm.ChildCategoryId,   // PK
      (c, cm) => new { Category = c, CategoryMaps = cm }) // project result
   .Select(x => x.Category);  // select result

You might have to fiddle with the projection depending on what you want to return, but that's the jist of it.

Listing information about all database files in SQL Server

I am using script to get empty space in each file:

Create Table ##temp
(
    DatabaseName sysname,
    Name sysname,
    physical_name nvarchar(500),
    size decimal (18,2),
    FreeSpace decimal (18,2)
)   
Exec sp_msforeachdb '
Use [?];
Insert Into ##temp (DatabaseName, Name, physical_name, Size, FreeSpace)
    Select DB_NAME() AS [DatabaseName], Name,  physical_name,
    Cast(Cast(Round(cast(size as decimal) * 8.0/1024.0,2) as decimal(18,2)) as nvarchar) Size,
    Cast(Cast(Round(cast(size as decimal) * 8.0/1024.0,2) as decimal(18,2)) -
        Cast(FILEPROPERTY(name, ''SpaceUsed'') * 8.0/1024.0 as decimal(18,2)) as nvarchar) As FreeSpace
    From sys.database_files
'
Select * From ##temp
drop table ##temp

Size is expressed in KB.

phpMyAdmin - Error > Incorrect format parameter?

I had this error and as I'm on shared hosting I don't have access to the php.ini so wasn't sure how I could fix it, the host didn't seem to have a clue either. In the end I emptied my browser cache and reloaded phpmyadmin and it came back!

Concat scripts in order with Gulp

I just use gulp-angular-filesort

function concatOrder() {

    return gulp.src('./build/src/app/**/*.js')
        .pipe(sort())
        .pipe(plug.concat('concat.js'))
        .pipe(gulp.dest('./output/'));
}

What is the best way to iterate over a dictionary?

Generally, asking for "the best way" without a specific context is like asking what is the best color?

One the one hand, there are many colors and there's no best color. It depends on the need and often on taste, too.

On the other hand, there are many ways to iterate over a Dictionary in C# and there's no best way. It depends on the need and often on taste, too.

Most straightforward way

foreach (var kvp in items)
{
    // key is kvp.Key
    doStuff(kvp.Value)
}

If you need only the value (allows to call it item, more readable than kvp.Value).

foreach (var item in items.Values)
{
    doStuff(item)
}

If you need a specific sort order

Generally, beginners are surprised about order of enumeration of a Dictionary.

LINQ provides a concise syntax that allows to specify order (and many other things), e.g.:

foreach (var kvp in items.OrderBy(kvp => kvp.Key))
{
    // key is kvp.Key
    doStuff(kvp.Value)
}

Again you might only need the value. LINQ also provides a concise solution to:

  • iterate directly on the value (allows to call it item, more readable than kvp.Value)
  • but sorted by the keys

Here it is:

foreach (var item in items.OrderBy(kvp => kvp.Key).Select(kvp => kvp.Value))
{
    doStuff(item)
}

There are many more real-world use case you can do from these examples. If you don't need a specific order, just stick to the "most straightforward way" (see above)!

Create an array of integers property in Objective-C

This should work:

@interface MyClass
{
    int _doubleDigits[10]; 
}

@property(readonly) int *doubleDigits;

@end

@implementation MyClass

- (int *)doubleDigits
{
    return _doubleDigits;
}

@end

RandomForestClassfier.fit(): ValueError: could not convert string to float

You may not pass str to fit this kind of classifier.

For example, if you have a feature column named 'grade' which has 3 different grades:

A,B and C.

you have to transfer those str "A","B","C" to matrix by encoder like the following:

A = [1,0,0]

B = [0,1,0]

C = [0,0,1]

because the str does not have numerical meaning for the classifier.

In scikit-learn, OneHotEncoder and LabelEncoder are available in inpreprocessing module. However OneHotEncoder does not support to fit_transform() of string. "ValueError: could not convert string to float" may happen during transform.

You may use LabelEncoder to transfer from str to continuous numerical values. Then you are able to transfer by OneHotEncoder as you wish.

In the Pandas dataframe, I have to encode all the data which are categorized to dtype:object. The following code works for me and I hope this will help you.

 from sklearn import preprocessing
    le = preprocessing.LabelEncoder()
    for column_name in train_data.columns:
        if train_data[column_name].dtype == object:
            train_data[column_name] = le.fit_transform(train_data[column_name])
        else:
            pass

how to log in to mysql and query the database from linux terminal

1.- How do I get mysql prompt in linux terminal?

mysql -u root -p

At the Enter password: prompt, well, enter root's password :)

You can find further reference by typing mysql --help or at the online manual.

2. How I stop the mysql server from linux terminal?

It depends. Red Hat based distros have the service command:

service mysqld stop

Other distros require to call the init script directly:

/etc/init.d/mysqld stop

3. How I start the mysql server from linux terminal?

Same as #2, but with start.

4. How do I get mysql prompt in linux terminal?

Same as #1.

5. How do I login to mysql server from linux terminal?

Same as #1.

6. How do I solve following error?

Same as #1.

Can regular expressions be used to match nested patterns?

Using the recursive matching in the PHP regex engine is massively faster than procedural matching of brackets. especially with longer strings.

http://php.net/manual/en/regexp.reference.recursive.php

e.g.

$patt = '!\( (?: (?: (?>[^()]+) | (?R) )* ) \)!x';

preg_match_all( $patt, $str, $m );

vs.

matchBrackets( $str );

function matchBrackets ( $str, $offset = 0 ) {

    $matches = array();

    list( $opener, $closer ) = array( '(', ')' );

    // Return early if there's no match
    if ( false === ( $first_offset = strpos( $str, $opener, $offset ) ) ) {
        return $matches;
    }

    // Step through the string one character at a time storing offsets
    $paren_score = -1;
    $inside_paren = false;
    $match_start = 0;
    $offsets = array();

    for ( $index = $first_offset; $index < strlen( $str ); $index++ ) {
        $char = $str[ $index ];

        if ( $opener === $char ) {
            if ( ! $inside_paren ) {
                $paren_score = 1;
                $match_start = $index;
            }
            else {
                $paren_score++;
            }
            $inside_paren = true;
        }
        elseif ( $closer === $char ) {
            $paren_score--;
        }

        if ( 0 === $paren_score ) {
            $inside_paren = false;
            $paren_score = -1;
            $offsets[] = array( $match_start, $index + 1 );
        }
    }

    while ( $offset = array_shift( $offsets ) ) {

        list( $start, $finish ) = $offset;

        $match = substr( $str, $start, $finish - $start );
        $matches[] = $match;
    }

    return $matches;
}

Iterating over Numpy matrix rows to apply a function each?

Here's my take if you want to try using multiprocesses to process each row of numpy array,

from multiprocessing import Pool
import numpy as np

def my_function(x):
    pass     # do something and return something

if __name__ == '__main__':    
    X = np.arange(6).reshape((3,2))
    pool = Pool(processes = 4)
    results = pool.map(my_function, map(lambda x: x, X))
    pool.close()
    pool.join()

pool.map take in a function and an iterable.
I used 'map' function to create an iterator over each rows of the array.
Maybe there's a better to create the iterable though.

Convert a JSON string to object in Java ME?

JSON official site is where you should look at. It provides various libraries which can be used with Java, I've personally used this one, JSON-lib which is an implementation of the work in the site, so it has exactly the same class - methods etc in this page.

If you click the html links there you can find anything you want.

In short:

to create a json object and a json array, the code is:

JSONObject obj = new JSONObject();
obj.put("variable1", o1);
obj.put("variable2", o2);
JSONArray array = new JSONArray();
array.put(obj);

o1, o2, can be primitive types (long, int, boolean), Strings or Arrays.

The reverse process is fairly simple, I mean converting a string to json object/array.

String myString;

JSONObject obj = new JSONObject(myString);

JSONArray array = new JSONArray(myString);

In order to be correctly parsed you just have to know if you are parsing an array or an object.

What is Haskell used for in the real world?

I think people in this post are missing the most important point for anyone who has never used a functional programming language: expanding your mind. If you are new to functional programming then Haskell will make you think in ways you've never thought before. As a result your programming in other areas and other languages will improve. How much? Hard to quantify.

Rename Oracle Table or View

To rename a table you can use:

RENAME mytable TO othertable;

or

ALTER TABLE mytable RENAME TO othertable;

or, if owned by another schema:

ALTER TABLE owner.mytable RENAME TO othertable;

Interestingly, ALTER VIEW does not support renaming a view. You can, however:

RENAME myview TO otherview;

The RENAME command works for tables, views, sequences and private synonyms, for your own schema only.

If the view is not in your schema, you can recompile the view with the new name and then drop the old view.

(tested in Oracle 10g)

Starting of Tomcat failed from Netbeans

None of the answers here solved my issue (as at February 2020), so I raised an issue at https://issues.apache.org/jira/browse/NETBEANS-3903 and Netbeans fixed the issue!

They're working on a pull request so the fix will be in a future .dmg installer soon, but in the meantime you can copy a file referenced in the bug and replace one in your netbeans modules folder.

Tip - if you right click on Applications > Netbeans and choose Show Package Contents Show Package Contents then you can find and replace the file org-netbeans-modules-tomcat5.jar that they refer to in your Netbeans folder, e.g. within /Applications/NetBeans/Apache NetBeans 11.2.app/Contents/Resources/NetBeans/netbeans/enterprise/modules

Best equivalent VisualStudio IDE for Mac to program .NET/C#

Whilst more of a workaround, if you're running an Intel Mac, you could go the virtualisation route - at least then you can run the same tools.

Type converting slices of interfaces

In case you need more shorting your code, you can creating new type for helper

type Strings []string

func (ss Strings) ToInterfaceSlice() []interface{} {
    iface := make([]interface{}, len(ss))
    for i := range ss {
        iface[i] = ss[i]
    }
    return iface
}

then

a := []strings{"a", "b", "c", "d"}
sliceIFace := Strings(a).ToInterfaceSlice()

Bootstrap 3 - jumbotron background image effect

Example: http://bootply.com/103783

One way to achieve this is using a position:fixed container for the background image and place it outside of the .jumbotron. Make the bg container the same height as the .jumbotron and center the background image:

background: url('/assets/example/...jpg') no-repeat center center;

CSS

.bg {
  background: url('/assets/example/bg_blueplane.jpg') no-repeat center center;
  position: fixed;
  width: 100%;
  height: 350px; /*same height as jumbotron */
  top:0;
  left:0;
  z-index: -1;
}

.jumbotron {
  margin-bottom: 0px;
  height: 350px;
  color: white;
  text-shadow: black 0.3em 0.3em 0.3em;
  background:transparent;
}

Then use jQuery to decrease the height of the .jumbtron as the window scrolls. Since the background image is centered in the DIV it will adjust accordingly -- creating a parallax affect.

JavaScript

var jumboHeight = $('.jumbotron').outerHeight();
function parallax(){
    var scrolled = $(window).scrollTop();
    $('.bg').css('height', (jumboHeight-scrolled) + 'px');
}

$(window).scroll(function(e){
    parallax();
});

Demo

http://bootply.com/103783

Difference between AutoPostBack=True and AutoPostBack=False?

Taken from http://www.dotnetspider.com/resources/189-AutoPostBack-What-How-works.aspx:

Autopostback is the mechanism by which the page will be posted back to the server automatically based on some events in the web controls. In some of the web controls, the property called auto post back, if set to true, will send the request to the server when an event happens in the control.

Whenever we set the autopostback attribute to true on any of the controls, the .NET framework will automatically insert a few lines of code into the HTML generated to implement this functionality.

  1. A JavaScript method with name __doPostBack (eventtarget, eventargument)
  2. Two hidden variables with name __EVENTTARGET and __EVENTARGUMENT
  3. OnChange JavaScript event to the control

How can I throw a general exception in Java?

You could create your own Exception class:

public class InvalidSpeedException extends Exception {

  public InvalidSpeedException(String message){
     super(message);
  }

}

In your code:

throw new InvalidSpeedException("TOO HIGH");

What version of javac built my jar?

You check in Manifest file of jar example:

Manifest-Version: 1.0 Created-By: 1.6.0 (IBM Corporation)

What's the whole point of "localhost", hosts and ports at all?

Some databases are designed to communicate over the web using ports assigned by the Internet Assigned Number Authority (IANA) and when run on individual PC use the ports with localhost. Some common databases with their default ports (the defualts can usually be overridden):

Port Database

1433 Microsoft SQL Server https://support.microsoft.com/en-us/kb/287932

3306 MySQL https://dev.mysql.com/doc/refman/4.1/en/connecting.html

5432 PostgreSQL

1527 Apache Derby (database)

Some web servers and databases are paired together such as Apache/MySQL (as in LAMP or XXAMP) or MS Internet Information Server (IIS)/MS SQL Server (IIS/SQL Server) in which case you have to be concerned with both the port of the database and the web server -- a common example of this is WordPress which uses Apache/MySQL.

What is the equivalent of Select Case in Access SQL?

You could do below:

select
iif ( OpeningBalance>=0 And OpeningBalance<=500 , 20, 

                  iif ( OpeningBalance>=5001 And OpeningBalance<=10000 , 30, 

                       iif ( OpeningBalance>=10001 And OpeningBalance<=20000 , 40, 

50 ) ) ) as commission
from table

Including non-Python files with setup.py

I just wanted to follow up on something I found working with Python 2.7 on Centos 6. Adding the package_data or data_files as mentioned above did not work for me. I added a MANIFEST.IN with the files I wanted which put the non-python files into the tarball, but did not install them on the target machine via RPM.

In the end, I was able to get the files into my solution using the "options" in the setup/setuptools. The option files let you modify various sections of the spec file from setup.py. As follows.

from setuptools import setup


setup(
    name='theProjectName',
    version='1',
    packages=['thePackage'],
    url='',
    license='',
    author='me',
    author_email='[email protected]',
    description='',
    options={'bdist_rpm': {'install_script': 'filewithinstallcommands'}},
)

file - MANIFEST.in:

include license.txt

file - filewithinstallcommands:

mkdir -p $RPM_BUILD_ROOT/pathtoinstall/
#this line installs your python files
python setup.py install -O1 --root=$RPM_BUILD_ROOT --record=INSTALLED_FILES
#install license.txt into /pathtoinstall folder
install -m 700 license.txt $RPM_BUILD_ROOT/pathtoinstall/
echo /pathtoinstall/license.txt >> INSTALLED_FILES

How do you change text to bold in Android?

Here is the solution

TextView questionValue = (TextView) findViewById(R.layout.TextView01);
questionValue.setTypeface(null, Typeface.BOLD);

Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException

Use all the jackson dependencies(databind,core, annotations, scala(if you are using spark and scala)) with the same version.. and upgrade the versions to the latest releases..

<dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-scala_2.11</artifactId>
            <version>2.9.4</version>
        </dependency>

        <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.4</version>
        <exclusions>
            <exclusion>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-core</artifactId>
            </exclusion>
            <exclusion>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-annotations</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.9.4</version>
    </dependency>

        <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.9.4</version>

        </dependency>

Note: Use Scala dependency only if you are working with scala. Otherwise it is not needed.

What is the ultimate postal code and zip regex?

We use the following:

Canada

([A-Z]{1}[0-9]{1}){3}   //We raise to upper first

America

[0-9]{5}                //-or-
[0-9]{5}-[0-9]{4}       //10 digit zip

Other

Accept as is

printing all contents of array in C#

There are many ways to do it, the other answers are good, here's an alternative:

Console.WriteLine(string.Join("\n", myArrayOfObjects));

How to set ChartJS Y axis title?

For me it works like this:

    options : {
      scales: {
        yAxes: [{
          scaleLabel: {
            display: true,
            labelString: 'probability'
          }
        }]
      }
    }

Is it possible to simulate key press events programmatically?

You can dispatch keyboard events on an element like this

element.dispatchEvent(new KeyboardEvent('keydown',{'key':'a'}));

However, dispatchEvent might not update the input field value


Example:

_x000D_
_x000D_
let element = document.querySelector('input');
element.onkeydown = e => alert(e.key);
element.dispatchEvent(new KeyboardEvent('keydown',{'key':'a'}));
  
_x000D_
<input/>
_x000D_
_x000D_
_x000D_


You can add more properties to the event as needed, like this answer

  element.dispatchEvent(new KeyboardEvent("keydown", {
    key: "e",
    keyCode: 69, // example values.
    code: "KeyE", // put everything you need in this object.
    which: 69,
    shiftKey: false, // you don't need to include values
    ctrlKey: false,  // if you aren't going to use them.
    metaKey: false   // these are here for example's sake.
  }));
    

Also, since keypress is deprecated you can use keydown + keyup, for example

element.dispatchEvent(new KeyboardEvent('keydown', {'key':'Shift'} ));
element.dispatchEvent(new KeyboardEvent( 'keyup' , {'key':'Shift'} ));

Using find to locate files that match one of multiple patterns

Braces within the pattern \(\) is required for name pattern with or

find Documents -type f \( -name "*.py" -or -name "*.html" \)

While for the name pattern with and operator it is not required

find Documents -type f ! -name "*.py" -and ! -name "*.html" 

Form inline inside a form horizontal in twitter bootstrap?

Don't nest <form> tags, that will not work. Just use Bootstrap classes.

Bootstrap 3

<form class="form-horizontal" role="form">
    <div class="form-group">
      <label for="inputType" class="col-md-2 control-label">Type</label>
      <div class="col-md-3">
          <input type="text" class="form-control" id="inputType" placeholder="Type">
      </div>
    </div>
    <div class="form-group">
        <span class="col-md-2 control-label">Metadata</span>
        <div class="col-md-6">
            <div class="form-group row">
                <label for="inputKey" class="col-md-1 control-label">Key</label>
                <div class="col-md-2">
                    <input type="text" class="form-control" id="inputKey" placeholder="Key">
                </div>
                <label for="inputValue" class="col-md-1 control-label">Value</label>
                <div class="col-md-2">
                    <input type="text" class="form-control" id="inputValue" placeholder="Value">
                </div>
            </div>
        </div>
    </div>
</form>

You can achieve that behaviour in many ways, that's just an example. Test it on this bootply

Bootstrap 2

<form class="form-horizontal">
    <div class="control-group">
        <label class="control-label" for="inputType">Type</label>
        <div class="controls">
            <input type="text" id="inputType" placeholder="Type">
        </div>
    </div>
    <div class="control-group">
        <span class="control-label">Metadata</span>
        <div class="controls form-inline">
            <label for="inputKey">Key</label>
            <input type="text" class="input-small" placeholder="Key" id="inputKey">
            <label for="inputValue">Value</label>
            <input type="password" class="input-small" placeholder="Value" id="inputValue">
        </div>
    </div>
</form>

Note that I'm using .form-inline to get the propper styling inside a .controls.
You can test it on this jsfiddle

onClick not working on mobile (touch)

better to use touchstart event with .on() jQuery method:

$(window).load(function() { // better to use $(document).ready(function(){
    $('.List li').on('click touchstart', function() {
        $('.Div').slideDown('500');
    });
});

And i don't understand why you are using $(window).load() method because it waits for everything on a page to be loaded, this tend to be slow, while you can use $(document).ready() method which does not wait for each element on the page to be loaded first.

Math constant PI value in C

I don't know exactly how C calculates PI directly as I'm more familiar with C++ than C; however, you could either have a predefined C macro or const such as:

#define PI 3.14159265359.....
const float PI = 3.14159265359.....
const double PI = 3.14159265359.....
/* If your machine,os & compiler supports the long double */
const long double PI = 3.14159265359..... 

or you could calculate it with either of these two formulas:

#define M_PI acos(-1.0);
#define M_PI (4.0 * atan(1.0)); // tan(pi/4) = 1 or acos(-1)

IMHO I'm not 100% certain but I think atan() is cheaper than acos().

How to send redirect to JSP page in Servlet

Look at the HttpServletResponse#sendRedirect(String location) method.

Use it as:

response.sendRedirect(request.getContextPath() + "/welcome.jsp")

Alternatively, look at HttpServletResponse#setHeader(String name, String value) method.

The redirection is set by adding the location header:

response.setHeader("Location", request.getContextPath() + "/welcome.jsp");

Change the size of a JTextField inside a JBorderLayout

Try to play with

setMinSize()
setMaxSize()
setPreferredSize()

These method are used by layout when it decide what should be the size of current element. The layout manager calls setSize() and actually overrides your values.

Very simple log4j2 XML configuration file using Console and File appender

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </Console>
        <File name="MyFile" fileName="all.log" immediateFlush="false" append="false">
            <PatternLayout pattern="%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </File>
    </Appenders>
    <Loggers>
        <Root level="debug">
            <AppenderRef ref="Console" />
            <AppenderRef ref="MyFile"/>
        </Root>
    </Loggers>
</Configuration>

Notes:

  • Put the following content in your configuration file.
  • Name the configuration file log4j2.xml
  • Put the log4j2.xml in a folder which is in the class-path (i.e. your source folder "src")
  • Use Logger logger = LogManager.getLogger(); to initialize your logger
  • I did set the immediateFlush="false" since this is better for SSD lifetime. If you need the log right away in your log-file remove the parameter or set it to true

How to convert DateTime to a number with a precision greater than days in T-SQL?

You can use T-SQL to convert the date before it gets to your .NET program. This often is simpler if you don't need to do additional date conversion in your .NET program.

DECLARE @Date DATETIME = Getdate()
DECLARE @DateInt INT = CONVERT(VARCHAR(30), @Date, 112)
DECLARE @TimeInt INT = REPLACE(CONVERT(VARCHAR(30), @Date, 108), ':', '')
DECLARE @DateTimeInt BIGINT = CONVERT(VARCHAR(30), @Date, 112) + REPLACE(CONVERT(VARCHAR(30), @Date, 108), ':', '')
SELECT @Date as Date, @DateInt DateInt, @TimeInt TimeInt, @DateTimeInt DateTimeInt

Date                    DateInt     TimeInt     DateTimeInt
------------------------- ----------- ----------- --------------------
2013-01-07 15:08:21.680 20130107    150821      20130107150821

Solving sslv3 alert handshake failure when trying to use a client certificate

Not a definite answer but too much to fit in comments:

I hypothesize they gave you a cert that either has a wrong issuer (although their server could use a more specific alert code for that) or a wrong subject. We know the cert matches your privatekey -- because both curl and openssl client paired them without complaining about a mismatch; but we don't actually know it matches their desired CA(s) -- because your curl uses openssl and openssl SSL client does NOT enforce that a configured client cert matches certreq.CAs.

Do openssl x509 <clientcert.pem -noout -subject -issuer and the same on the cert from the test P12 that works. Do openssl s_client (or check the one you did) and look under Acceptable client certificate CA names; the name there or one of them should match (exactly!) the issuer(s) of your certs. If not, that's most likely your problem and you need to check with them you submitted your CSR to the correct place and in the correct way. Perhaps they have different regimes in different regions, or business lines, or test vs prod, or active vs pending, etc.

If the issuer of your cert does match desiredCAs, compare its subject to the working (test-P12) one: are they in similar format? are there any components in the working one not present in yours? If they allow it, try generating and submitting a new CSR with a subject name exactly the same as the test-P12 one, or as close as you can get, and see if that produces a cert that works better. (You don't have to generate a new key to do this, but if you choose to, keep track of which certs match which keys so you don't get them mixed up.) If that doesn't help look at the certificate extensions with openssl x509 <cert -noout -text for any difference(s) that might reasonably be related to subject authorization, like KeyUsage, ExtendedKeyUsage, maybe Policy, maybe Constraints, maybe even something nonstandard.

If all else fails, ask the server operator(s) what their logs say about the problem, or if you have access look at the logs yourself.

Getting char from string at specified index

If s is your string than you could do it this way:

Mid(s, index, 1)

Edit based on comment below question.

It seems that you need a bit different approach which should be easier. Try in this way:

Dim character As String 'Integer if for numbers
's = ActiveDocument.Content.Text - we don't need it
character = Activedocument.Characters(index)

PHP How to find the time elapsed since a date time?

Here I am using custom function for finding the time elapsed since a date time.


echo Datetodays('2013-7-26 17:01:10');

function Datetodays($d) {

        $date_start = $d;
        $date_end = date('Y-m-d H:i:s');

        define('SECOND', 1);
        define('MINUTE', SECOND * 60);
        define('HOUR', MINUTE * 60);
        define('DAY', HOUR * 24);
        define('WEEK', DAY * 7);

        $t1 = strtotime($date_start);
        $t2 = strtotime($date_end);
        if ($t1 > $t2) {
            $diffrence = $t1 - $t2;
        } else {
            $diffrence = $t2 - $t1;
        }

        //echo "
".$date_end." ".$date_start." ".$diffrence; $results['major'] = array(); // whole number representing larger number in date time relationship $results1 = array(); $string = ''; $results['major']['weeks'] = floor($diffrence / WEEK); $results['major']['days'] = floor($diffrence / DAY); $results['major']['hours'] = floor($diffrence / HOUR); $results['major']['minutes'] = floor($diffrence / MINUTE); $results['major']['seconds'] = floor($diffrence / SECOND); //print_r($results); // Logic: // Step 1: Take the major result and transform it into raw seconds (it will be less the number of seconds of the difference) // ex: $result = ($results['major']['weeks']*WEEK) // Step 2: Subtract smaller number (the result) from the difference (total time) // ex: $minor_result = $difference - $result // Step 3: Take the resulting time in seconds and convert it to the minor format // ex: floor($minor_result/DAY) $results1['weeks'] = floor($diffrence / WEEK); $results1['days'] = floor((($diffrence - ($results['major']['weeks'] * WEEK)) / DAY)); $results1['hours'] = floor((($diffrence - ($results['major']['days'] * DAY)) / HOUR)); $results1['minutes'] = floor((($diffrence - ($results['major']['hours'] * HOUR)) / MINUTE)); $results1['seconds'] = floor((($diffrence - ($results['major']['minutes'] * MINUTE)) / SECOND)); //print_r($results1); if ($results1['weeks'] != 0 && $results1['days'] == 0) { if ($results1['weeks'] == 1) { $string = $results1['weeks'] . ' week ago'; } else { if ($results1['weeks'] == 2) { $string = $results1['weeks'] . ' weeks ago'; } else { $string = '2 weeks ago'; } } } elseif ($results1['weeks'] != 0 && $results1['days'] != 0) { if ($results1['weeks'] == 1) { $string = $results1['weeks'] . ' week ago'; } else { if ($results1['weeks'] == 2) { $string = $results1['weeks'] . ' weeks ago'; } else { $string = '2 weeks ago'; } } } elseif ($results1['weeks'] == 0 && $results1['days'] != 0) { if ($results1['days'] == 1) { $string = $results1['days'] . ' day ago'; } else { $string = $results1['days'] . ' days ago'; } } elseif ($results1['days'] != 0 && $results1['hours'] != 0) { $string = $results1['days'] . ' day and ' . $results1['hours'] . ' hours ago'; } elseif ($results1['days'] == 0 && $results1['hours'] != 0) { if ($results1['hours'] == 1) { $string = $results1['hours'] . ' hour ago'; } else { $string = $results1['hours'] . ' hours ago'; } } elseif ($results1['hours'] != 0 && $results1['minutes'] != 0) { $string = $results1['hours'] . ' hour and ' . $results1['minutes'] . ' minutes ago'; } elseif ($results1['hours'] == 0 && $results1['minutes'] != 0) { if ($results1['minutes'] == 1) { $string = $results1['minutes'] . ' minute ago'; } else { $string = $results1['minutes'] . ' minutes ago'; } } elseif ($results1['minutes'] != 0 && $results1['seconds'] != 0) { $string = $results1['minutes'] . ' minute and ' . $results1['seconds'] . ' seconds ago'; } elseif ($results1['minutes'] == 0 && $results1['seconds'] != 0) { if ($results1['seconds'] == 1) { $string = $results1['seconds'] . ' second ago'; } else { $string = $results1['seconds'] . ' seconds ago'; } } return $string; } ?>

How to update cursor limit for ORA-01000: maximum open cursors exceed

RUn the following query to find if you are running spfile or not:

SELECT DECODE(value, NULL, 'PFILE', 'SPFILE') "Init File Type" 
       FROM sys.v_$parameter WHERE name = 'spfile';

If the result is "SPFILE", then use the following command:

alter system set open_cursors = 4000 scope=both; --4000 is the number of open cursor

if the result is "PFILE", then use the following command:

alter system set open_cursors = 1000 ;

You can read about SPFILE vs PFILE here,

http://www.orafaq.com/node/5

What is define([ , function ]) in JavaScript?

define() is part of the AMD spec of js

See:

Edit: Also see Claudio's answer below. Likely the more relevant explanation.

What is the difference between FragmentPagerAdapter and FragmentStatePagerAdapter?

FragmentPagerAdapter stores the previous data which is fetched from the adapter while FragmentStatePagerAdapter takes the new value from the adapter everytime it is executed.

jQuery DataTables Getting selected row values

More a comment than an answer - but I cannot add comments yet: Thanks for your help, the count was the easy part. Just for others that might come here. I hope that it will save you some time.

It took me a while to get the attributes from the rows and to understand how to access them from the data() Object (that the data() is an Array and the Attributes can be read by adding them with a dot and not with brackets:

$('#button').click( function () {
    for (var i = 0; i < table.rows('.selected').data().length; i++) { 
       console.log( table.rows('.selected').data()[i].attributeNameFromYourself);
    }
} );

(by the way: I get the data for my table using AJAX and JSON)

SQL Server IF EXISTS THEN 1 ELSE 2

If you want to do it this way then this is the syntax you're after;

IF EXISTS (SELECT * FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx') 
BEGIN
   SELECT 1 
END
ELSE
BEGIN
    SELECT 2
END

You don't strictly need the BEGIN..END statements but it's probably best to get into that habit from the beginning.

How do I get the total number of unique pairs of a set in the database?

TLDR; The formula is n(n-1)/2 where n is the number of items in the set.

Explanation:

To find the number of unique pairs in a set, where the pairs are subject to the commutative property (AB = BA), you can calculate the summation of 1 + 2 + ... + (n-1) where n is the number of items in the set.

The reasoning is as follows, say you have 4 items:

A
B
C
D

The number of items that can be paired with A is 3, or n-1:

AB
AC
AD

It follows that the number of items that can be paired with B is n-2 (because B has already been paired with A):

BC
BD

and so on...

(n-1) + (n-2) + ... + (n-(n-1))

which is the same as

1 + 2 + ... + (n-1)

or

n(n-1)/2

Javascript wait() function

You shouldn't edit it, you should completely scrap it.

Any attempt to make execution stop for a certain amount of time will lock up the browser and switch it to a Not Responding state. The only thing you can do is use setTimeout correctly.

MySQL LIMIT on DELETE statement

There is a workaround to solve this problem by using a derived table.

DELETE t1 FROM test t1 JOIN (SELECT t.id FROM test LIMIT 1) t2 ON t1.id = t2.id

Because the LIMIT is inside the derived table the join will match only 1 row and thus the query will delete only this row.

Batch script to find and replace a string in text file without creating an extra output file for storing the modified file

@echo off 
    setlocal enableextensions disabledelayedexpansion

    set "search=%1"
    set "replace=%2"

    set "textFile=Input.txt"

    for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        >>"%textFile%" echo(!line:%search%=%replace%!
        endlocal
    )

for /f will read all the data (generated by the type comamnd) before starting to process it. In the subprocess started to execute the type, we include a redirection overwritting the file (so it is emptied). Once the do clause starts to execute (the content of the file is in memory to be processed) the output is appended to the file.

Multiple Java versions running concurrently under Windows

Invoking Java with "java -version:1.5", etc. should run with the correct version of Java. (Obviously replace 1.5 with the version you want.)

If Java is properly installed on Windows there are paths to the vm for each version stored in the registry which it uses so you don't need to mess about with environment versions on Windows.

Spring JSON request getting 406 (not Acceptable)

Check <mvc:annotation-driven /> in dispatcherservlet.xml , if not add it. And add

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-core-asl</artifactId>
    <version>1.9.13</version>
</dependency>

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>

these dependencies in your pom.xml

How do I include the string header?

For using the string header first we must have include string header file as #include <string> and then we can include string header in the following ways in C++:

1)

string header = "--- Demonstrates Unformatted Input ---";

2)

string header("**** Counts words****\n"), prompt("Enter a text and terminate"
" with a period and return:"), line( 60, '-'), text;

Named capturing groups in JavaScript regex?

Another possible solution: create an object containing the group names and indexes.

var regex = new RegExp("(.*) (.*)");
var regexGroups = { FirstName: 1, LastName: 2 };

Then, use the object keys to reference the groups:

var m = regex.exec("John Smith");
var f = m[regexGroups.FirstName];

This improves the readability/quality of the code using the results of the regex, but not the readability of the regex itself.

Multi-Column Join in Hibernate/JPA Annotations

This worked for me . In my case 2 tables foo and boo have to be joined based on 3 different columns.Please note in my case ,in boo the 3 common columns are not primary key

i.e., one to one mapping based on 3 different columns

@Entity
@Table(name = "foo")
public class foo implements Serializable
{
    @Column(name="foocol1")
    private String foocol1;
    //add getter setter
    @Column(name="foocol2")
    private String foocol2;
    //add getter setter
    @Column(name="foocol3")
    private String foocol3;
    //add getter setter
    private Boo boo;
    private int id;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "brsitem_id", updatable = false)
    public int getId()
    {
        return this.id;
    }
    public void setId(int id)
    {
        this.id = id;
    }
    @OneToOne
    @JoinColumns(
    {
        @JoinColumn(updatable=false,insertable=false, name="foocol1", referencedColumnName="boocol1"),
        @JoinColumn(updatable=false,insertable=false, name="foocol2", referencedColumnName="boocol2"),
        @JoinColumn(updatable=false,insertable=false, name="foocol3", referencedColumnName="boocol3")
    }
    )
    public Boo getBoo()
    {
        return boo;
    }
    public void setBoo(Boo boo)
    {
        this.boo = boo;
    }
}





@Entity
@Table(name = "boo")
public class Boo implements Serializable
{
    private int id;
    @Column(name="boocol1")
    private String boocol1;
    //add getter setter
    @Column(name="boocol2")
    private String boocol2;
    //add getter setter
    @Column(name="boocol3")
    private String boocol3;
    //add getter setter
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "item_id", updatable = false)
    public int getId()
    {
        return id;
    }
    public void setId(int id)
    {
        this.id = id;
    }
}

Symfony 2 EntityManager injection in service

Since 2017 and Symfony 3.3 you can register Repository as service, with all its advantages it has.

Check my post How to use Repository with Doctrine as Service in Symfony for more general description.


To your specific case, original code with tuning would look like this:

1. Use in your services or Controller

<?php

namespace Test\CommonBundle\Services;

use Doctrine\ORM\EntityManagerInterface;

class UserService
{
    private $userRepository;

    // use custom repository over direct use of EntityManager
    // see step 2
    public function __constructor(UserRepository $userRepository)
    {
        $this->userRepository = $userRepository;
    }

    public function getUser($userId)
    {
        return $this->userRepository->find($userId);
    }
}

2. Create new custom repository

<?php

namespace Test\CommonBundle\Repository;

use Doctrine\ORM\EntityManagerInterface;

class UserRepository
{
    private $repository;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->repository = $entityManager->getRepository(UserEntity::class);
    }

    public function find($userId)
    {
        return  $this->repository->find($userId);
    }
}

3. Register services

# app/config/services.yml
services:
    _defaults:
        autowire: true

    Test\CommonBundle\:
       resource: ../../Test/CommonBundle

Can You Get A Users Local LAN IP Address Via JavaScript?

As it turns out, the recent WebRTC extension of HTML5 allows javascript to query the local client IP address. A proof of concept is available here: http://net.ipcalf.com

This feature is apparently by design, and is not a bug. However, given its controversial nature, I would be cautious about relying on this behaviour. Nevertheless, I think it perfectly and appropriately addresses your intended purpose (revealing to the user what their browser is leaking).

Python os.path.join on Windows

answering to your comment : "the others '//' 'c:', 'c:\\' did not work (C:\\ created two backslashes, C:\ didn't work at all)"

On windows using os.path.join('c:', 'sourcedir') will automatically add two backslashes \\ in front of sourcedir.

To resolve the path, as python works on windows also with forward slashes -> '/', simply add .replace('\\','/') with os.path.join as below:-

os.path.join('c:\\', 'sourcedir').replace('\\','/')

e.g: os.path.join('c:\\', 'temp').replace('\\','/')

output : 'C:/temp'

How to use mysql JOIN without ON condition?

See some example in http://www.sitepoint.com/understanding-sql-joins-mysql-database/

You can use 'USING' instead of 'ON' as in the query

SELECT * FROM table1 LEFT JOIN table2 USING (id);

How to get single value of List<object>

Define a class like this :

public class myclass {
       string id ;
       string title ;
       string content;
 }

 public class program {
        public void Main () {
               List<myclass> objlist = new List<myclass> () ;
               foreach (var value in objlist)  {
                       TextBox1.Text = value.id ;
                       TextBox2.Text= value.title;
                       TextBox3.Text= value.content ;
                }
         }
  }

I tried to draw a sketch and you can improve it in many ways. Instead of defining class "myclass", you can define struct.

How to sanity check a date in Java

Key is df.setLenient(false);. This is more than enough for simple cases. If you are looking for a more robust (I doubt) and/or alternate libraries like joda-time then look at the answer by the user "tardate"

final static String DATE_FORMAT = "dd-MM-yyyy";

public static boolean isDateValid(String date) 
{
        try {
            DateFormat df = new SimpleDateFormat(DATE_FORMAT);
            df.setLenient(false);
            df.parse(date);
            return true;
        } catch (ParseException e) {
            return false;
        }
}

What is the difference between JAX-RS and JAX-WS?

JAX-WS - is Java API for the XML-Based Web Services - a standard way to develop a Web- Services in SOAP notation (Simple Object Access Protocol).

Calling of the Web Services is performed via remote procedure calls. For the exchange of information between the client and the Web Service is used SOAP protocol. Message exchange between the client and the server performed through XML- based SOAP messages.

Clients of the JAX-WS Web- Service need a WSDL file to generate executable code that the clients can use to call Web- Service.

JAX-RS - Java API for RESTful Web Services. RESTful Web Services are represented as resources and can be identified by Uniform Resource Identifiers (URI). Remote procedure call in this case is represented a HTTP- request and the necessary data is passed as parameters of the query. Web Services RESTful - more flexible, can use several different MIME- types. Typically used for XML data exchange or JSON (JavaScript Object Notation) data exchange...

Java: Sending Multiple Parameters to Method

You can use varargs

public function yourFunction(Parameter... parameters)

See also

Java multiple arguments dot notation - Varargs

PHP shorthand for isset()?

Update for PHP 7 (thanks shock_gone_wild)

PHP 7 introduces the so called null coalescing operator which simplifies the below statements to:

$var = $var ?? "default";

Before PHP 7

No, there is no special operator or special syntax for this. However, you could use the ternary operator:

$var = isset($var) ? $var : "default";

Or like this:

isset($var) ?: $var = 'default';

In excel how do I reference the current row but a specific column?

If you dont want to hard-code the cell addresses you can use the ROW() function.

eg: =AVERAGE(INDIRECT("A" & ROW()), INDIRECT("C" & ROW()))

Its probably not the best way to do it though! Using Auto-Fill and static columns like @JaiGovindani suggests would be much better.

How to access the contents of a vector from a pointer to the vector in C++?

The easiest way use it as array is use vector::data() member.

CSS: Background image and padding

You can be more precise with CSS background-origin:

background-origin: content-box;

This will make image respect the padding of the box.

Destroy or remove a view in Backbone.js

Without knowing all the information... You could bind a reset trigger to your model or controller:

this.bind("reset", this.updateView);

and when you want to reset the views, trigger a reset.

For your callback, do something like:

updateView: function() {
  view.remove();
  view.render();
};

Getting Data from Android Play Store

The Google Play Store doesn't provide this data, so the sites must just be scraping it.

Change the color of glyphicons to blue in some- but not at all places using Bootstrap 2

If it is only a bootstrap icon. Note that icons are under text or rather typography. Just add the text color class like this. E.g text-primary, text-info and so on and so forth to the icon class:

<i class="icon features-icon icons8-collaboration-2 text-primary"></i>
<i class="icon features-icon icons8-collaboration-2 text-secondary"></i>

Converting string to integer

The function you need is CInt.

ie CInt(PrinterLabel)

See Type Conversion Functions (Visual Basic) on MSDN

Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!

How to Multi-thread an Operation Within a Loop in Python

You can split the processing into a specified number of threads using an approach like this:

import threading                                                                

def process(items, start, end):                                                 
    for item in items[start:end]:                                               
        try:                                                                    
            api.my_operation(item)                                              
        except Exception:                                                       
            print('error with item')                                            


def split_processing(items, num_splits=4):                                      
    split_size = len(items) // num_splits                                       
    threads = []                                                                
    for i in range(num_splits):                                                 
        # determine the indices of the list this thread will handle             
        start = i * split_size                                                  
        # special case on the last chunk to account for uneven splits           
        end = None if i+1 == num_splits else (i+1) * split_size                 
        # create the thread                                                     
        threads.append(                                                         
            threading.Thread(target=process, args=(items, start, end)))         
        threads[-1].start() # start the thread we just created                  

    # wait for all threads to finish                                            
    for t in threads:                                                           
        t.join()                                                                



split_processing(items)

How do I make a text input non-editable?

if you really want to use CSS, use following property which will make field non-editable.

pointer-events: none;

Difference between staticmethod and classmethod

You might want to consider the difference between:

class A:
    def foo():  # no self parameter, no decorator
        pass

and

class B:
    @staticmethod
    def foo():  # no self parameter
        pass

This has changed between python2 and python3:

python2:

>>> A.foo()
TypeError
>>> A().foo()
TypeError
>>> B.foo()
>>> B().foo()

python3:

>>> A.foo()
>>> A().foo()
TypeError
>>> B.foo()
>>> B().foo()

So using @staticmethod for methods only called directly from the class has become optional in python3. If you want to call them from both class and instance, you still need to use the @staticmethod decorator.

The other cases have been well covered by unutbus answer.

What is the most "pythonic" way to iterate over a list in chunks?

The more-itertools package has chunked method which does exactly that:

import more_itertools
for s in more_itertools.chunked(range(9), 4):
    print(s)

Prints

[0, 1, 2, 3]
[4, 5, 6, 7]
[8]

chunked returns the items in a list. If you'd prefer iterables, use ichunked.

default value for struct member in C

Create a default struct as the other answers have mentioned:

struct MyStruct
{
    int flag;
}

MyStruct_default = {3};

However, the above code will not work in a header file - you will get error: multiple definition of 'MyStruct_default'. To solve this problem, use extern instead in the header file:

struct MyStruct
{
    int flag;
};

extern const struct MyStruct MyStruct_default;

And in the c file:

const struct MyStruct MyStruct_default = {3};

Hope this helps anyone having trouble with the header file.

Adding click event listener to elements with the same class

I find it more convenient to use something like the following:

document.querySelector('*').addEventListener('click',function(event){

    if( event.target.tagName != "IMG"){
        return;
    }

    // HANDLE CLICK ON IMAGES HERE
});

Android: TextView: Remove spacing and padding on top and bottom

Add android:includeFontPadding="false" to see if it helps.And make text view size same as that of text size rather than "wrap content".It will definitely work.

How can I check if a Perl array contains a particular value?

Simply turn the array into a hash:

my %params = map { $_ => 1 } @badparams;

if(exists($params{$someparam})) { ... }

You can also add more (unique) params to the list:

$params{$newparam} = 1;

And later get a list of (unique) params back:

@badparams = keys %params;

WCF ServiceHost access rights

Open a command prompt as the administrator and you write below command to add your URL:

netsh http add urlacl url=http://+:8000/YourServiceLibrary/YourService user=Everyone

What "wmic bios get serialnumber" actually retrieves?

the wmic bios get serialnumber command call the Win32_BIOS wmi class and get the value of the SerialNumber property, which retrieves the serial number of the BIOS Chip of your system.

Create a list with initial capacity in Python

Concerns about preallocation in Python arise if you're working with NumPy, which has more C-like arrays. In this instance, preallocation concerns are about the shape of the data and the default value.

Consider NumPy if you're doing numerical computation on massive lists and want performance.

Java compile error: "reached end of file while parsing }"

You need to enclose your class in { and }. A few extra pointers: According to the Java coding conventions, you should

  • Put your { on the same line as the method declaration:
  • Name your classes using CamelCase (with initial capital letter)
  • Name your methods using camelCase (with small initial letter)

Here's how I would write it:

public class ModMyMod extends BaseMod {

    public String version() {
         return "1.2_02";
    }

    public void addRecipes(CraftingManager recipes) {
       recipes.addRecipe(new ItemStack(Item.diamond), new Object[] {
          "#", Character.valueOf('#'), Block.dirt
       });
    }
}

Read a XML (from a string) and get some fields - Problems reading XML

I used the System.Xml.Linq.XElement for the purpose. Just check code below for reading the value of first child node of the xml(not the root node).

        string textXml = "<xmlroot><firstchild>value of first child</firstchild>........</xmlroot>";
        XElement xmlroot = XElement.Parse(textXml);
        string firstNodeContent = ((System.Xml.Linq.XElement)(xmlroot.FirstNode)).Value;

How to remove a character at the end of each line in unix

Try doing this :

awk '{print substr($0, 1, length($0)-1)}' file.txt

This is more generic than just removing the final comma but any last character

If you'd want to only remove the last comma with awk :

awk '{gsub(/,$/,""); print}' file.txt

No log4j2 configuration file found. Using default configuration: logging only errors to the console

I am getting this error because log4j2 file got deleted from my src folder

Simply add xml file under src folder

<Appenders>
    <Console name="Console" target="SYSTEM_OUT">
        <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %msg%n" />
    </Console>

    <RollingFile name="RollingFile" filename="logs/B2CATA-hybrid.log"
        filepattern="${logPath}/%d{yyyyMMddHHmmss}-fargo.log">
        <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %msg%n" />
        <Policies>
            <SizeBasedTriggeringPolicy size="100 MB" />
        </Policies>
        <DefaultRolloverStrategy max="20" />
    </RollingFile>

</Appenders>
<Loggers>
   <Logger name="com.pragiti." level="trace" />
    <Root level="info">
        <AppenderRef ref="Console" />
        <AppenderRef ref="RollingFile" />
    </Root>
</Loggers>

jQuery 'input' event

I think 'input' simply works here the same way 'oninput' does in the DOM Level O Event Model.

Incidentally:

Just as silkfire commented it, I too googled for 'jQuery input event'. Thus I was led to here and astounded to learn that 'input' is an acceptable parameter to jquery's bind() command. In jQuery in Action (p. 102, 2008 ed.) 'input' is not mentionned as a possible event (against 20 others, from 'blur' to 'unload'). It is true that, on p. 92, the contrary could be surmised from rereading (i.e. from a reference to different string identifiers between Level 0 and Level 2 models). That is quite misleading.

Get pandas.read_csv to read empty values as empty string instead of nan

I added a ticket to add an option of some sort here:

https://github.com/pydata/pandas/issues/1450

In the meantime, result.fillna('') should do what you want

EDIT: in the development version (to be 0.8.0 final) if you specify an empty list of na_values, empty strings will stay empty strings in the result

How to return PDF to browser in MVC?

You would normally do a Response.Flush followed by a Response.Close, but for some reason the iTextSharp library doesn't seem to like this. The data doesn't make it through and Adobe thinks the PDF is corrupt. Leave out the Response.Close function and see if your results are better:

Response.Clear();
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-disposition", "attachment; filename=file.pdf"); // open in a new window
Response.OutputStream.Write(outStream.GetBuffer(), 0, outStream.GetBuffer().Length);
Response.Flush();

// For some reason, if we close the Response stream, the PDF doesn't make it through
//Response.Close();

Show ProgressDialog Android

While creating the object for the progressbar check the following.

This fails:

dialog = new ProgressDialog(getApplicationContext());

While adding the activities context works..

dialog = new ProgressDialog(MainActivity.this);

Image is not showing in browser?

the easy way to do it to place the image in Web Content and then right click on it and then open it by your eclipse or net beans web Browser it will show the page where you can see the URL which is the exact path then copy the URL and place it on src=" paste URL " ;

How to unstash only certain files?

First list all the stashes

git stash list

?

stash@{0}: WIP on Produktkonfigurator: 132c06a5 Cursor bei glyphicon plus und close zu zeigende Hand ändern
stash@{1}: WIP on Produktkonfigurator: 132c06a5 Cursor bei glyphicon plus und close zu zeigende Hand ändern
stash@{2}: WIP on master: 7e450c81 Merge branch 'Offlineseite'

Then show which files are in the stash (lets pick stash 1):

git stash show 1 --name-only

//Hint: you can also write
//git stash show stash@{1} --name-only

?

 ajax/product.php
 ajax/productPrice.php
 errors/Company/js/offlineMain.phtml
 errors/Company/mage.php
 errors/Company/page.phtml
 js/konfigurator/konfigurator.js

Then apply the file you like to:

git checkout stash@{1} -- <filename>

or whole folder:

git checkout stash@{1} /errors

It also works without -- but it is recommended to use them. See this post.

It is also conventional to recognize a double hyphen as a signal to stop option interpretation and treat all following arguments literally.

How to select true/false based on column value?

You can try something like

SELECT  e.EntityId, 
        e.EntityName, 
        CASE 
            WHEN ep.EntityId IS NULL THEN 'False' 
            ELSE 'TRUE' 
        END AS HasProfile 
FROM    Entities e LEFT JOIN 
        EntityProfiles ep ON e.EntityID = ep.EntityID

Or

SELECT e.EntityId, 
        e.EntityName, 
        CASE 
            WHEN e.EntityProfile IS NULL THEN 'False' 
            ELSE 'TRUE' 
        END AS HasProfile 

FROM    Entities e

SELECT query with CASE condition and SUM()

I don't think you need a case statement. You just need to update your where clause and make sure you have correct parentheses to group the clauses.

SELECT Sum(CAMount) as PaymentAmount 
from TableOrderPayment 
where (CStatus = 'Active' AND CPaymentType = 'Cash') 
OR (CStatus = 'Active' and CPaymentType = 'Check' and CDate<=SYSDATETIME())

The answers posted before mine assume that CDate<=SYSDATETIME() is also appropriate for Cash payment type as well. I think I split mine out so it only looks for that clause for check payments.

Disable sorting on last column when using jQuery DataTables

Try to use minus sign for count from backside

<script>
    $(document).ready(function () {
        $('#example-2').DataTable({               
            'order':[],
            'columnDefs': [{
                "targets": [-1],
                "orderable": false
            }]
        });
    });
</script>

PHP display current server path

  • To get your current working directory: getcwd() (documentation)
  • To get the document root directory: $_SERVER['DOCUMENT_ROOT']
  • To get the filename of the current script: $_SERVER['SCRIPT_FILENAME']

Convert Float to Int in Swift

You can type cast like this:

 var float:Float = 2.2
 var integer:Int = Int(float)

Spaces cause split in path with PowerShell

You can escape the space by using single quotations and a backtick before the space:

$path = 'C:\Windows Services\MyService.exe'
$path -replace ' ', '` '
invoke-expression $path

How to vertically align elements in a div?

By default h1 is a block element and will render on the line after the first img, and will cause the second img to appear on the line following the block.

To stop this from occurring you can set the h1 to have inline flow behaviour:

#header > h1 { display: inline; }

As for absolutely positioning the img inside the div, you need to set the containing div to have a "known size" before this will work properly. In my experience, you also need to change the position attribute away from the default - position: relative works for me:

#header { position: relative; width: 20em; height: 20em; }
#img-for-abs-positioning { position: absolute; top: 0; left: 0; }

If you can get that to work, you might want to try progressively removing the height, width, position attributes from div.header to get the minimal required attributes to get the effect you want.

UPDATE:

Here is a complete example that works on Firefox 3:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
    <head>
        <title>Example of vertical positioning inside a div</title>
        <style type="text/css">
            #header > h1 { display: inline; }
            #header { border: solid 1px red; 
                      position: relative; }
            #img-for-abs-positioning { position: absolute;
                                       bottom: -1em; right: 2em; }
        </style>
    </head>

    <body>
        <div id="header">
            <img src="#" alt="Image 1" width="40" height="40" />
            <h1>Header</h1>
            <img src="#" alt="Image 2" width="40" height="40" 
                 id="img-for-abs-positioning" />
        </div>
    </body>
</html>

What is &amp used for

HTML doesn't recognize the & but it will recognize &amp; because it is equal to & in HTML

I looked over this post someone had made: http://www.webmasterworld.com/forum21/8851.htm

How to set up subdomains on IIS 7

If your computer can't find the IP address associated with SUBDOMAIN1.example.COM, it will not find the site.

You need to either change your hosts file (so you can at least test things - this will be a local change, only available to yourself), or update DNS so the name will resolve correctly (so the rest of the world can see it).

How do I create a right click context menu in Java Swing?

There's a section on Bringing Up a Popup Menu in the How to Use Menus article of The Java Tutorials which explains how to use the JPopupMenu class.

The example code in the tutorial shows how to add MouseListeners to the components which should display a pop-up menu, and displays the menu accordingly.

(The method you describe is fairly similar to the way the tutorial presents the way to show a pop-up menu on a component.)

How to Navigate from one View Controller to another using Swift

let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let home = storyBoard.instantiateViewController(withIdentifier: "HOMEVC") as! HOMEVC
navigationController?.pushViewController(home, animated: true);

How to enable multidexing with the new Android Multidex support library

Edit:

Android 5.0 (API level 21) and higher uses ART which supports multidexing. Therefore, if your minSdkVersion is 21 or higher, the multidex support library is not needed.


Modify your build.gradle:

android {
    compileSdkVersion 22
    buildToolsVersion "23.0.0"

         defaultConfig {
             minSdkVersion 14 //lower than 14 doesn't support multidex
             targetSdkVersion 22

             // Enabling multidex support.
             multiDexEnabled true
         }
}

dependencies {
    implementation 'com.android.support:multidex:1.0.3'
}

If you are running unit tests, you will want to include this in your Application class:

public class YouApplication extends Application {

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

}

Or just make your application class extend MultiDexApplication

public class Application extends MultiDexApplication {

}

For more info, this is a good guide.

How to get exception message in Python properly

from traceback import format_exc


try:
    fault = 10/0
except ZeroDivision:
    print(format_exc())

Another possibility is to use the format_exc() method from the traceback module.

How to specify the port an ASP.NET Core application is hosted on?

In ASP.NET Core 3.1, there are 4 main ways to specify a custom port:

  • Using command line arguments, by starting your .NET application with --urls=[url]:
dotnet run --urls=http://localhost:5001/
  • Using appsettings.json, by adding a Urls node:
{
  "Urls": "http://localhost:5001"
}
  • Using environment variables, with ASPNETCORE_URLS=http://localhost:5001/.
  • Using UseUrls(), if you prefer doing it programmatically:
public static class Program
{
    public static void Main(string[] args) =>
        CreateHostBuilder(args).Build().Run();

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(builder =>
            {
                builder.UseStartup<Startup>();
                builder.UseUrls("http://localhost:5001/");
            });
}

Or, if you're still using the web host builder instead of the generic host builder:

public class Program
{
    public static void Main(string[] args) =>
        new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseUrls("http://localhost:5001/")
            .Build()
            .Run();
}

get string from right hand side

I Had the same problem. This worked for me:

 CASE WHEN length(sp.tele_phone_number) = 10 THEN
                   SUBSTR(sp.tele_phone_number,4)

How to remove duplicates from a list?

Assuming you want to keep the current order and don't want a Set, perhaps the easiest is:

List<Customer> depdupeCustomers =
    new ArrayList<>(new LinkedHashSet<>(customers));

If you want to change the original list:

Set<Customer> depdupeCustomers = new LinkedHashSet<>(customers);
customers.clear();
customers.addAll(dedupeCustomers);

How to find which git branch I am on when my disk is mounted on other server

git branch with no arguments displays the current branch marked with an asterisk in front of it:

user@host:~/gittest$ git branch
* master
  someotherbranch

In order to not have to type this all the time, I can recommend git prompt:

https://github.com/git/git/blob/master/contrib/completion/git-prompt.sh

In the AIX box how I can see that I am using master or inside a particular branch. What changes inside .git that drives which branch I am on?

Git stores the HEAD in the file .git/HEAD. If you're on the master branch, it could look like this:

$ cat .git/HEAD
ref: refs/heads/master

How can I concatenate a string within a loop in JSTL/JSP?

define a String variable using the JSP tags

<%!
String test = new String();
%>

then refer to that variable in your loop as

<c:forEach items="${myParams.items}" var="currentItem" varStatus="stat">
test+= whaterver_value
</c:forEach>

Use of Finalize/Dispose method in C#

Dispose pattern:

public abstract class DisposableObject : IDisposable
{
    public bool Disposed { get; private set;}      

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    ~DisposableObject()
    {
        Dispose(false);
    }

    private void Dispose(bool disposing)
    {
        if (!Disposed)
        {
            if (disposing)
            {
                DisposeManagedResources();
            }

            DisposeUnmanagedResources();
            Disposed = true;
        }
    }

    protected virtual void DisposeManagedResources() { }
    protected virtual void DisposeUnmanagedResources() { }
}

Example of inheritance:

public class A : DisposableObject
{
    public Component components_a { get; set; }
    private IntPtr handle_a;

    protected override void DisposeManagedResources()
    {
        try
        {
          Console.WriteLine("A_DisposeManagedResources");
          components_a.Dispose();
          components_a = null;
        }
        finally
        { 
          base.DisposeManagedResources();
        }
    }

    protected override void DisposeUnmanagedResources()
    {
        try
        {
          Console.WriteLine("A_DisposeUnmanagedResources");
          CloseHandle(handle_a);
          handle_a = IntPtr.Zero;
        }
        finally
        { 
          base.DisposeUnmanagedResources();
        }
    }
}

public class B : A
{
    public Component components_b { get; set; }
    private IntPtr handle_b;

    protected override void DisposeManagedResources()
    {
        try
        {
          Console.WriteLine("B_DisposeManagedResources");
          components_b.Dispose();
          components_b = null;
        }
        finally
        { 
          base.DisposeManagedResources();
        }
    }

    protected override void DisposeUnmanagedResources()
    {
        try
        {
          Console.WriteLine("B_DisposeUnmanagedResources");
          CloseHandle(handle_b);
          handle_b = IntPtr.Zero;
        }
        finally
        { 
          base.DisposeUnmanagedResources();
        }
    }
}

How to view DLL functions?

For native code it's probably best to use Dependency Walker. It also possible to use dumpbin command line utility that comes with Visual Studio.

Multiple distinct pages in one HTML file

Let's say you have multiple pages, with id #page1 #page2 and #page3. #page1 is the ID of your start page. The first thing you want to do is to redirect to your start page each time the webpage is loading. You do this with javascript:

document.location.hash = "#page1";

Then the next thing you want to do is place some links in your document to the different pages, like for example:

<a href="#page2">Click here to get to page 2.</a>

Then, lastly, you'd want to make sure that only the active page, or target-page is visible, and all other pages stay hidden. You do this with the following declarations in the <style> element:

<style>
#page1 {display:none}
#page1:target {display:block}
#page2 {display:none}
#page2:target {display:block}
#page3 {display:none}
#page3:target {display:block}
</style>

Modifying list while iterating

Use a while loop that checks for the truthfulness of the array:

while array:
    value = array.pop(0)
    # do some calculation here

And it should do it without any errors or funny behaviour.

PHP: How to remove specific element from an array?

I was looking for the answer to the same question and came across this topic. I see two main ways: the combination of array_search & unset and the use of array_diff. At first glance, it seemed to me that the first method would be faster, since does not require the creation of an additional array (as when using array_diff). But I wrote a small benchmark and made sure that the second method is not only more concise, but also faster! Glad to share this with you. :)

https://glot.io/snippets/f6ow6biaol

Ring Buffer in Java

None of the previously given examples were meeting my needs completely, so I wrote my own queue that allows following functionality: iteration, index access, indexOf, lastIndexOf, get first, get last, offer, remaining capacity, expand capacity, dequeue last, dequeue first, enqueue / add element, dequeue / remove element, subQueueCopy, subArrayCopy, toArray, snapshot, basics like size, remove or contains.

EjectingQueue

EjectingIntQueue

Reduce size of legend area in barplot

The cex parameter will do that for you.

a <- c(3, 2, 2, 2, 1, 2 )
barplot(a, beside = T,
        col = 1:6, space = c(0, 2))
legend("topright", 
       legend = c("a", "b", "c", "d", "e", "f"), 
       fill = 1:6, ncol = 2,
       cex = 0.75)

The plot

RegEx for matching UK Postcodes

I have the regex for UK Postcode validation.

This is working for all type of Postcode either inner or outer

^((([A-PR-UWYZ][0-9])|([A-PR-UWYZ][0-9][0-9])|([A-PR-UWYZ][A-HK-Y][0-9])|([A-PR-UWYZ][A-HK-Y][0-9][0-9])|([A-PR-UWYZ][0-9][A-HJKSTUW])|([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY]))) || ^((GIR)[ ]?(0AA))$|^(([A-PR-UWYZ][0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$|^(([A-PR-UWYZ][0-9][0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$|^(([A-PR-UWYZ][A-HK-Y0-9][0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$|^(([A-PR-UWYZ][A-HK-Y0-9][0-9][0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$|^(([A-PR-UWYZ][0-9][A-HJKS-UW0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$|^(([A-PR-UWYZ][A-HK-Y0-9][0-9][ABEHMNPRVWXY0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$

This is working for all type of format.

Example:

AB10-------------------->ONLY OUTER POSTCODE

A1 1AA------------------>COMBINATION OF (OUTER AND INNER) POSTCODE

WC2A-------------------->OUTER

How do I delete rows in a data frame?

For completeness, I'll add that this can be done with dplyr as well using slice. The advantage of using this is that it can be part of a piped workflow.

df <- df %>%
  .
  .
  slice(-c(2, 4, 6)) %>%
  .
  .

Of course, you can also use it without pipes.

df <- slice(df, -c(2, 4, 6))

The "not vector" format, -c(2, 4, 6) means to get everything that is not at rows 2, 4 and 6. For an example using a range, let's say you wanted to remove the first 5 rows, you could do slice(df, 6:n()). For more examples, see the docs.

Return array from function

At a minimum, change this:

function BlockID() {
    var IDs = new Array();
        images['s'] = "Images/Block_01.png";
        images['g'] = "Images/Block_02.png";
        images['C'] = "Images/Block_03.png";
        images['d'] = "Images/Block_04.png";
    return IDs;
}

To this:

function BlockID() {
    var IDs = new Object();
        IDs['s'] = "Images/Block_01.png";
        IDs['g'] = "Images/Block_02.png";
        IDs['C'] = "Images/Block_03.png";
        IDs['d'] = "Images/Block_04.png";
    return IDs;
}

There are a couple fixes to point out. First, images is not defined in your original function, so assigning property values to it will throw an error. We correct that by changing images to IDs. Second, you want to return an Object, not an Array. An object can be assigned property values akin to an associative array or hash -- an array cannot. So we change the declaration of var IDs = new Array(); to var IDs = new Object();.

After those changes your code will run fine, but it can be simplified further. You can use shorthand notation (i.e., object literal property value shorthand) to create the object and return it immediately:

function BlockID() {
    return {
            "s":"Images/Block_01.png"
            ,"g":"Images/Block_02.png"
            ,"C":"Images/Block_03.png"
            ,"d":"Images/Block_04.png"
    };
}

Laravel 5.4 create model, controller and migration in single artisan command

Laravel 5.4 You can use

 php artisan make:model --migration --controller --resource Test

This will create 1) Model 2) controller with default resource function 3) Migration file

And Got Answer

Model created successfully.

Created Migration: 2018_04_30_055346_create_tests_table

Controller created successfully.

How do you fix a MySQL "Incorrect key file" error when you can't repair the table?

The storage engine (MyISAM) DOES support repair table. You should be able to repair it.

If the repair fails then it's a sign that the table is very corrupted, you have no choice but to restore it from backups.

If you have other systems (e.g. non-production with same software versions and schema) with an identical table then you might be able to fix it with some hackery (copying the frm an MYI files, followed by a repair).

In essence, the trick is to avoid getting broken tables in the first place. This means always shutting your db down cleanly, never having it crash and never having hardware or power problems. In practice this isn't very likely, so if durability matters you may want to consider a more crash-safe storage engine.