Programs & Examples On #System properties

System properties a key value pairs that can be provided to an application, often used to configure it at run time.

Driver executable must be set by the webdriver.ie.driver system property

The error message says

"The path to the driver executable must be set by the webdriver.ie.driver system property;"

You are setting the path for the Chrome Driver with "webdriver.chrome.driver" property. You are not setting the file location when for InternetExplorerDriver, to do that you must set "webdriver.ie.driver" property.

You can set these properties in your shell, via maven, or your IDE with the -DpropertyName=Value

-Dwebdriver.ie.driver="C:/.../IEDriverServer.exe" 

You need to use quotes because of spaces or slashes in your path on windows machines, or alternatively reverse the slashes other wise they are the string string escape prefix.

You could also use

System.setProperty("webdriver.ie.driver","C:/.../IEDriverServer.exe"); 

inside your code.

Specify system property to Maven project

If your test and webapp are in the same Maven project, you can use a property in the project POM. Then you can filter certain files which will allow Maven to set the property in those files. There are different ways to filter, but the most common is during the resources phase - http://books.sonatype.com/mvnref-book/reference/resource-filtering-sect-description.html

If the test and webapp are in different Maven projects, you can put the property in settings.xml, which is in your maven repository folder (C:\Documents and Settings\username.m2) on Windows. You will still need to use filtering or some other method to read the property into your test and webapp.

Set multiple system properties Java command line

You may be able to use the JAVA_TOOL_OPTIONS environment variable to set options. It worked for me with Rasbian. See Environment Variables and System Properties which has this to say:

In many environments, the command line is not readily accessible to start the application with the necessary command-line options.

This often happens with applications that use embedded VMs (meaning they use the Java Native Interface (JNI) Invocation API to start the VM), or where the startup is deeply nested in scripts. In these environments the JAVA_TOOL_OPTIONS environment variable can be useful to augment a command line.

When this environment variable is set, the JNI_CreateJavaVM function (in the JNI Invocation API), the JNI_CreateJavaVM function adds the value of the environment variable to the options supplied in its JavaVMInitArgs argument.

However this environment variable use may be disabled for security reasons.

In some cases, this option is disabled for security reasons. For example, on the Oracle Solaris operating system, this option is disabled when the effective user or group ID differs from the real ID.

See this example showing the difference between specifying on the command line versus using the JAVA_TOOL_OPTIONS environment variable.

screenshot showing use of JAVA_TOOL_OPTIONS environment variable

How can I specify system properties in Tomcat configuration on startup?

You could add necessary properties to catalina.properties file in <tomcat installation directory>/conf directory.

Reference: https://tomcat.apache.org/tomcat-8.0-doc/config/index.html

All system properties are available including those set using the -D syntax, those automatically made available by the JVM and those configured in the $CATALINA_BASE/conf/catalina.properties file.

How to validate IP address in Python?

Don't parse it. Just ask.

import socket

try:
    socket.inet_aton(addr)
    # legal
except socket.error:
    # Not legal

Setting default values to null fields when mapping with Jackson

Only one proposed solution keeps the default-value when some-value:null was set explicitly (POJO readability is lost there and it's clumsy)

Here's how one can keep the default-value and never set it to null

@JsonProperty("some-value")
public String someValue = "default-value";

@JsonSetter("some-value")
public void setSomeValue(String s) {
    if (s != null) { 
        someValue = s; 
    }
}

How to get file size in Java

Use the length() method in the File class. From the javadocs:

Returns the length of the file denoted by this abstract pathname. The return value is unspecified if this pathname denotes a directory.

UPDATED Nowadays we should use the Files.size() method:

Paths path = Paths.get("/path/to/file");
long size = Files.size(path);

For the second part of the question, straight from File's javadocs:

  • getUsableSpace() Returns the number of bytes available to this virtual machine on the partition named by this abstract pathname

  • getTotalSpace() Returns the size of the partition named by this abstract pathname

  • getFreeSpace() Returns the number of unallocated bytes in the partition named by this abstract path name

React - uncaught TypeError: Cannot read property 'setState' of undefined

You have to bind your methods with 'this' (default object). So whatever your function may be just bind that in the constructor.

constructor(props) {
    super(props);
    this.state = { checked:false };

    this.handleChecked = this.handleChecked.bind(this);
}

handleChecked(){
    this.setState({
        checked: !(this.state.checked)
    })
}

render(){
    var msg;

    if(this.state.checked){
        msg = 'checked'
    }
    else{
        msg = 'not checked'
    }

    return (
        <div>               
            <input type='checkbox' defaultChecked = {this.state.checked} onChange = {this.handleChecked} />
            <h3>This is {msg}</h3>
        </div>
    );

TypeScript - Append HTML to container element in Angular 2

With the new angular class Renderer2

constructor(private renderer:Renderer2) {}

  @ViewChild('one', { static: false }) d1: ElementRef;

  ngAfterViewInit() {
    const d2 = this.renderer.createElement('div');
    const text = this.renderer.createText('two');
    this.renderer.appendChild(d2, text);
    this.renderer.appendChild(this.d1.nativeElement, d2);
  }

How to create a new img tag with JQuery, with the src and id from a JavaScript object?

In jQuery, a new element can be created by passing a HTML string to the constructor, as shown below:

var img = $('<img id="dynamic">'); //Equivalent: $(document.createElement('img'))
img.attr('src', responseObject.imgurl);
img.appendTo('#imagediv');

How can I see the current value of my $PATH variable on OS X?

You need to use the command echo $PATH to display the PATH variable or you can just execute set or env to display all of your environment variables.

By typing $PATH you tried to run your PATH variable contents as a command name.

Bash displayed the contents of your path any way. Based on your output the following directories will be searched in the following order:

/usr/local/share/npm/bin
/Library/Frameworks/Python.framework/Versions/2.7/bin
/usr/local/bin
/usr/local/sbin
~/bin
/Library/Frameworks/Python.framework/Versions/Current/bin
/usr/bin
/bin
/usr/sbin
/sbin
/usr/local/bin
/opt/X11/bin
/usr/local/git/bin

To me this list appears to be complete.

Bootstrap : TypeError: $(...).modal is not a function

Use this. It will work. I have used bootstrap 3.3.5 and jquery 1.11.3

_x000D_
_x000D_
$('document').ready(function() {_x000D_
  $('#btnTest').click(function() {_x000D_
    $('#dummyModal').modal('show');_x000D_
  });_x000D_
});
_x000D_
body {_x000D_
  background-color: #eee;_x000D_
  padding-top: 40px;_x000D_
  padding-bottom: 40px;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf8">_x000D_
  <meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
  <meta name="viewport" content="width=device-width,initial-scale=1">_x000D_
  <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">_x000D_
  <title>Modal Test</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div class="container">_x000D_
    <button id="btnTest" class="btn btn-default">Show Modal</button>_x000D_
    <div id="dummyModal" role="dialog" class="modal fade">_x000D_
      <div class="modal-dialog">_x000D_
        <div class="modal-content">_x000D_
          <div class="modal-header">_x000D_
            <button type="button" data-dismiss="modal" class="close">&times;</button>_x000D_
            <h4 class="modal-title">Error</h4>_x000D_
          </div>_x000D_
          <div class="modal-body">_x000D_
            <p>Quick Brown Fox Jumps Over The Lazy Dog</p>_x000D_
          </div>_x000D_
          <div class="modal-footer">_x000D_
            <button type="button" data-dismiss="modal" class="btn btn-default">Close</button>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
  <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>_x000D_
  <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

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 do I write a correct micro-benchmark in Java?

Tips about writing micro benchmarks from the creators of Java HotSpot:

Rule 0: Read a reputable paper on JVMs and micro-benchmarking. A good one is Brian Goetz, 2005. Do not expect too much from micro-benchmarks; they measure only a limited range of JVM performance characteristics.

Rule 1: Always include a warmup phase which runs your test kernel all the way through, enough to trigger all initializations and compilations before timing phase(s). (Fewer iterations is OK on the warmup phase. The rule of thumb is several tens of thousands of inner loop iterations.)

Rule 2: Always run with -XX:+PrintCompilation, -verbose:gc, etc., so you can verify that the compiler and other parts of the JVM are not doing unexpected work during your timing phase.

Rule 2.1: Print messages at the beginning and end of timing and warmup phases, so you can verify that there is no output from Rule 2 during the timing phase.

Rule 3: Be aware of the difference between -client and -server, and OSR and regular compilations. The -XX:+PrintCompilation flag reports OSR compilations with an at-sign to denote the non-initial entry point, for example: Trouble$1::run @ 2 (41 bytes). Prefer server to client, and regular to OSR, if you are after best performance.

Rule 4: Be aware of initialization effects. Do not print for the first time during your timing phase, since printing loads and initializes classes. Do not load new classes outside of the warmup phase (or final reporting phase), unless you are testing class loading specifically (and in that case load only the test classes). Rule 2 is your first line of defense against such effects.

Rule 5: Be aware of deoptimization and recompilation effects. Do not take any code path for the first time in the timing phase, because the compiler may junk and recompile the code, based on an earlier optimistic assumption that the path was not going to be used at all. Rule 2 is your first line of defense against such effects.

Rule 6: Use appropriate tools to read the compiler's mind, and expect to be surprised by the code it produces. Inspect the code yourself before forming theories about what makes something faster or slower.

Rule 7: Reduce noise in your measurements. Run your benchmark on a quiet machine, and run it several times, discarding outliers. Use -Xbatch to serialize the compiler with the application, and consider setting -XX:CICompilerCount=1 to prevent the compiler from running in parallel with itself. Try your best to reduce GC overhead, set Xmx(large enough) equals Xms and use UseEpsilonGC if it is available.

Rule 8: Use a library for your benchmark as it is probably more efficient and was already debugged for this sole purpose. Such as JMH, Caliper or Bill and Paul's Excellent UCSD Benchmarks for Java.

Init function in javascript and how it works

That pattern will create a new execution context (EC) in which any local variable objects (VO's) will live, and will likewise die when the EC exits. The only exception to this lifetime is for VO's which become part of a closure.

Please note that JavaScript has no magic "init" function. You might associate this pattern with such since most any self-respecting JS library (jQuery, YUI, etc.) will do this so that they don't pollute the global NS more than they need to.

A demonstration:

var x = 1; // global VO
(function(){        
    var x = 2; // local VO
})();
x == 1; // global VO, unchanged by the local VO

The 2nd set of "brackets" (those are actually called parens, or a set of parentheses), are simply to invoke the function expression directly preceding it (as defined by the prior set of parenthesis).

Can I make 'git diff' only the line numbers AND changed file names?

Line numbers as in number of changed lines or the actual line numbers containing the changes? If you want the number of changed lines, use git diff --stat. This gives you a display like this:

[me@somehost:~/newsite:master]> git diff --stat
 whatever/views/gallery.py |    8 ++++++++
 1 files changed, 8 insertions(+), 0 deletions(-)

There is no option to get the line numbers of the changes themselves.

Maven Could not resolve dependencies, artifacts could not be resolved

As an alternative source to the same problem, this answer cites using Maven 3 versus Maven 2 as the potential cause of this issue. Near as I can tell, this is due to changes in local repository resolution that was changed in Maven 3. Putting this here in case anyone else googles for it and reaches this answer (as I did).

How can I determine if an image has loaded, using Javascript/jQuery?

Either add an event listener, or have the image announce itself with onload. Then figure out the dimensions from there.

<img id="photo"
     onload='loaded(this.id)'
     src="a_really_big_file.jpg"
     alt="this is some alt text"
     title="this is some title text" />

How to escape the equals sign in properties files

You can look here Can the key in a Java property include a blank character?

for escape equal '=' \u003d

table.whereclause=where id=100

key:[table.whereclause] value:[where id=100]

table.whereclause\u003dwhere id=100

key:[table.whereclause=where] value:[id=100]

table.whereclause\u003dwhere\u0020id\u003d100

key:[table.whereclause=where id=100] value:[]

How do I implement basic "Long Polling"?

Thanks for the code, dbr. Just a small typo in long_poller.htm around the line

1000 /* ..after 1 seconds */

I think it should be

"1000"); /* ..after 1 seconds */

for it to work.

For those interested, I tried a Django equivalent. Start a new Django project, say lp for long polling:

django-admin.py startproject lp

Call the app msgsrv for message server:

python manage.py startapp msgsrv

Add the following lines to settings.py to have a templates directory:

import os.path
PROJECT_DIR = os.path.dirname(__file__)
TEMPLATE_DIRS = (
    os.path.join(PROJECT_DIR, 'templates'),
)

Define your URL patterns in urls.py as such:

from django.views.generic.simple import direct_to_template
from lp.msgsrv.views import retmsg

urlpatterns = patterns('',
    (r'^msgsrv\.php$', retmsg),
    (r'^long_poller\.htm$', direct_to_template, {'template': 'long_poller.htm'}),
)

And msgsrv/views.py should look like:

from random import randint
from time import sleep
from django.http import HttpResponse, HttpResponseNotFound

def retmsg(request):
    if randint(1,3) == 1:
        return HttpResponseNotFound('<h1>Page not found</h1>')
    else:
        sleep(randint(2,10))
        return HttpResponse('Hi! Have a random number: %s' % str(randint(1,10)))

Lastly, templates/long_poller.htm should be the same as above with typo corrected. Hope this helps.

Password encryption/decryption code in .NET

You can use the managed .Net cryptography library, then save the encrypted string into the database. When you want to verify the password you can compare the stored database string with the hashed value of the user input. See here for more info about SHA512Managed

using System.Security.Cryptography;

    public static string EncryptSHA512Managed(string password)
    {
        UnicodeEncoding uEncode = new UnicodeEncoding();
        byte[] bytPassword = uEncode.GetBytes(password);
        SHA512Managed sha = new SHA512Managed();
        byte[] hash = sha.ComputeHash(bytPassword);
        return Convert.ToBase64String(hash);
    }

What is boilerplate code?

Boilerplate code means a piece of code which can be used over and over again. On the other hand, anyone can say that it's a piece of reusable code.

The term actually came from the steel industries.

For a little bit of history, according to Wikipedia:

In the 1890s, boilerplate was actually cast or stamped in metal ready for the printing press and distributed to newspapers around the United States. Until the 1950s, thousands of newspapers received and used this kind of boilerplate from the nation's largest supplier, the Western Newspaper Union. Some companies also sent out press releases as boilerplate so that they had to be printed as written.

Now according to Wikipedia:

In object-oriented programs, classes are often provided with methods for getting and setting instance variables. The definitions of these methods can frequently be regarded as boilerplate. Although the code will vary from one class to another, it is sufficiently stereotypical in structure that it would be better generated automatically than written by hand. For example, in the following Java class representing a pet, almost all the code is boilerplate except for the declarations of Pet, name and owner:

public class Pet {
    private PetName name;
    private Person owner;

    public Pet(PetName name, Person owner) {
        this.name = name;
        this.owner = owner;
    }

    public PetName getName() {
        return name;
    }

    public void setName(PetName name) {
        this.name = name;
    }

    public Person getOwner() {
        return owner;
    }

    public void setOwner(Person owner) {
        this.owner = owner;
    }
}

restrict edittext to single line

At XML file. Just add

android:maxLines="1"

JUnit Testing private variables?

I can't tell if you've found some special case code which requires you to test against private fields. But in my experience you never have to test something private - always public. Maybe you could give an example of some code where you need to test private?

Make outer div be automatically the same height as its floating content

You can set the outerdiv's CSS to this

#outerdiv {
    overflow: hidden; /* make sure this doesn't cause unexpected behaviour */
}

You can also do this by adding an element at the end with clear: both. This can be added normally, with JS (not a good solution) or with :after CSS pseudo element (not widely supported in older IEs).

The problem is that containers won't naturally expand to include floated children. Be warned with using the first example, if you have any children elements outside the parent element, they will be hidden. You can also use 'auto' as the property value, but this will invoke scrollbars if any element appears outside.

You can also try floating the parent container, but depending on your design, this may be impossible/difficult.

Is a view faster than a simple query?

My understanding is that a while back, a view would be faster because SQL Server could store an execution plan and then just use it instead of trying to figure one out on the fly. I think the performance gains nowadays is probably not as great as it once was, but I would have to guess there would be some marginal improvement to use the view.

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

Presumably you have it in a variable and are using JSON.parse(data);. In which case, use:

JSON.parse(data.replace(/&quot;/g,'"'));

You might want to fix your JSON-writing script though, because &quot; is not valid in a JSON object.

How to apply bold text style for an entire row using Apache POI?

Please find below the easy way :

XSSFCellStyle style = workbook.createCellStyle();
style.setBorderTop((short) 6); // double lines border
style.setBorderBottom((short) 1); // single line border
XSSFFont font = workbook.createFont();
font.setFontHeightInPoints((short) 15);
font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
style.setFont(font);                 

Row row = sheet.createRow(0);   
Cell cell0 = row.createCell(0);
cell0.setCellValue("Nav Value");
cell0.setCellStyle(style);  
for(int j = 0; j<=3; j++)
row.getCell(j).setCellStyle(style);

Simple example of threading in C++

When searching for an example of a C++ class that calls one of its own instance methods in a new thread, this question comes up, but we were not able to use any of these answers that way. Here's an example that does that:

Class.h

class DataManager
{
public:
    bool hasData;
    void getData();
    bool dataAvailable();
};

Class.cpp

#include "DataManager.h"

void DataManager::getData()
{
    // perform background data munging
    hasData = true;
    // be sure to notify on the main thread
}

bool DataManager::dataAvailable()
{
    if (hasData)
    {
        return true;
    }
    else
    {
        std::thread t(&DataManager::getData, this);
        t.detach(); // as opposed to .join, which runs on the current thread
    }
}

Note that this example doesn't get into mutex or locking.

Warning about SSL connection when connecting to MySQL database

Mention the url like:

jdbc:mysql://hostname:3306/hibernatedb?autoReconnect=true&useSSL=false

But in xml configuration when you mention & sign, the IDE shows below error:

The reference to entity "useSSL" must end with the ';' delimiter.

And then you have to explicitly use the &amp; instead of & to be determined as & by xml thereafter in xml you have to give the url in xml configuration like this:

<property name="connection.url">jdbc:mysql://hostname:3306/hibernatedb?autoReconnect=true&amp;useSSL=false</property>

How to use CURL via a proxy?

root@APPLICATIOSERVER:/var/www/html# php connectiontest.php
61e23468-949e-4103-8e08-9db09249e8s1 OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to 10.172.123.1:80 root@APPLICATIOSERVER:/var/www/html#

Post declaring the proxy settings in the php script file issue has been fixed.

$proxy = '10.172.123.1:80';
curl_setopt($cSession, CURLOPT_PROXY, $proxy); // PROXY details with port

Pylint, PyChecker or PyFlakes?

Well, I am a bit curious, so I just tested the three myself right after asking the question ;-)

Ok, this is not a very serious review, but here is what I can say:

I tried the tools with the default settings (it's important because you can pretty much choose your check rules) on the following script:

#!/usr/local/bin/python
# by Daniel Rosengren modified by e-satis

import sys, time
stdout = sys.stdout

BAILOUT = 16
MAX_ITERATIONS = 1000

class Iterator(object) :

    def __init__(self):

        print 'Rendering...'
        for y in xrange(-39, 39):
            stdout.write('\n')
            for x in xrange(-39, 39):
                if self.mandelbrot(x/40.0, y/40.0) :
                    stdout.write(' ')
                else:
                    stdout.write('*')


    def mandelbrot(self, x, y):
        cr = y - 0.5
        ci = x
        zi = 0.0
        zr = 0.0

        for i in xrange(MAX_ITERATIONS) :
            temp = zr * zi
            zr2 = zr * zr
            zi2 = zi * zi
            zr = zr2 - zi2 + cr
            zi = temp + temp + ci

            if zi2 + zr2 > BAILOUT:
                return i

        return 0

t = time.time()
Iterator()
print '\nPython Elapsed %.02f' % (time.time() - t)

As a result:

  • PyChecker is troublesome because it compiles the module to analyze it. If you don't want your code to run (e.g, it performs a SQL query), that's bad.
  • PyFlakes is supposed to be light. Indeed, it decided that the code was perfect. I am looking for something quite severe so I don't think I'll go for it.
  • PyLint has been very talkative and rated the code 3/10 (OMG, I'm a dirty coder !).

Strong points of PyLint:

  • Very descriptive and accurate report.
  • Detect some code smells. Here it told me to drop my class to write something with functions because the OO approach was useless in this specific case. Something I knew, but never expected a computer to tell me :-p
  • The fully corrected code run faster (no class, no reference binding...).
  • Made by a French team. OK, it's not a plus for everybody, but I like it ;-)

Cons of Pylint:

  • Some rules are really strict. I know that you can change it and that the default is to match PEP8, but is it such a crime to write 'for x in seq'? Apparently yes because you can't write a variable name with less than 3 letters. I will change that.
  • Very very talkative. Be ready to use your eyes.

Corrected script (with lazy doc strings and variable names):

#!/usr/local/bin/python
# by Daniel Rosengren, modified by e-satis
"""
Module doctring
"""


import time
from sys import stdout

BAILOUT = 16
MAX_ITERATIONS = 1000

def mandelbrot(dim_1, dim_2):
    """
    function doc string
    """
    cr1 = dim_1 - 0.5
    ci1 = dim_2
    zi1 = 0.0
    zr1 = 0.0

    for i in xrange(MAX_ITERATIONS) :
        temp = zr1 * zi1
        zr2 = zr1 * zr1
        zi2 = zi1 * zi1
        zr1 = zr2 - zi2 + cr1
        zi1 = temp + temp + ci1

        if zi2 + zr2 > BAILOUT:
            return i

    return 0

def execute() :
    """
    func doc string
    """
    print 'Rendering...'
    for dim_1 in xrange(-39, 39):
        stdout.write('\n')
        for dim_2 in xrange(-39, 39):
            if mandelbrot(dim_1/40.0, dim_2/40.0) :
                stdout.write(' ')
            else:
                stdout.write('*')


START_TIME = time.time()
execute()
print '\nPython Elapsed %.02f' % (time.time() - START_TIME)

Thanks to Rudiger Wolf, I discovered pep8 that does exactly what its name suggests: matching PEP8. It has found several syntax no-nos that Pylint did not. But Pylint found stuff that was not specifically linked to PEP8 but interesting. Both tools are interesting and complementary.

Eventually I will use both since there are really easy to install (via packages or setuptools) and the output text is so easy to chain.

To give you a little idea of their output:

pep8:

./python_mandelbrot.py:4:11: E401 multiple imports on one line
./python_mandelbrot.py:10:1: E302 expected 2 blank lines, found 1
./python_mandelbrot.py:10:23: E203 whitespace before ':'
./python_mandelbrot.py:15:80: E501 line too long (108 characters)
./python_mandelbrot.py:23:1: W291 trailing whitespace
./python_mandelbrot.py:41:5: E301 expected 1 blank line, found 3

Pylint:

************* Module python_mandelbrot
C: 15: Line too long (108/80)
C: 61: Line too long (85/80)
C:  1: Missing docstring
C:  5: Invalid name "stdout" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)
C: 10:Iterator: Missing docstring
C: 15:Iterator.__init__: Invalid name "y" (should match [a-z_][a-z0-9_]{2,30}$)
C: 17:Iterator.__init__: Invalid name "x" (should match [a-z_][a-z0-9_]{2,30}$)

[...] and a very long report with useful stats like :

Duplication
-----------

+-------------------------+------+---------+-----------+
|                         |now   |previous |difference |
+=========================+======+=========+===========+
|nb duplicated lines      |0     |0        |=          |
+-------------------------+------+---------+-----------+
|percent duplicated lines |0.000 |0.000    |=          |
+-------------------------+------+---------+-----------+

MySQL Multiple Where Clause

I think that you are after this:

SELECT image_id
FROM list
WHERE (style_id, style_value) IN ((24,'red'),(25,'big'),(27,'round'))
GROUP BY image_id
HAVING count(distinct style_id, style_value)=3

You can't use AND, because values can't be 24 red and 25 big and 27 round at the same time in the same row, but you need to check the presence of style_id, style_value in multiple rows, under the same image_id.

In this query I'm using IN (that, in this particular example, is equivalent to an OR), and I am counting the distinct rows that match. If 3 distinct rows match, it means that all 3 attributes are present for that image_id, and my query will return it.

How do I get the entity that represents the current user in Symfony2?

The thread is a bit old but i think this could probably save someone's time ...

I ran into the same problem as the original question, that the type is showed as Symfony\Component\Security\Core\User\User

It eventually turned out that i was logged in using an in memory user

my security.yml looks something like this

security:
    providers:
        chain_provider:
            chain:
                providers: [in_memory, fos_userbundle]
        fos_userbundle:
            id: fos_user.user_manager
        in_memory:
            memory:
                users:
                    user:  { password: userpass, roles: [ 'ROLE_USER' ] }
                    admin: { password: adminpass, roles: [ 'ROLE_ADMIN', 'ROLE_SONATA_ADMIN' ] }

the in_memory user type is always Symfony\Component\Security\Core\User\User if you want to use your own entity, log in using that provider's user.

Thanks, hj

How to upload multiple files using PHP, jQuery and AJAX

HTML

<form enctype="multipart/form-data" action="upload.php" method="post">
    <input name="file[]" type="file" />
    <button class="add_more">Add More Files</button>
    <input type="button" value="Upload File" id="upload"/>
</form>

Javascript

 $(document).ready(function(){
    $('.add_more').click(function(e){
        e.preventDefault();
        $(this).before("<input name='file[]' type='file'/>");
    });
});

for ajax upload

$('#upload').click(function() {
    var filedata = document.getElementsByName("file"),
            formdata = false;
    if (window.FormData) {
        formdata = new FormData();
    }
    var i = 0, len = filedata.files.length, img, reader, file;

    for (; i < len; i++) {
        file = filedata.files[i];

        if (window.FileReader) {
            reader = new FileReader();
            reader.onloadend = function(e) {
                showUploadedItem(e.target.result, file.fileName);
            };
            reader.readAsDataURL(file);
        }
        if (formdata) {
            formdata.append("file", file);
        }
    }
    if (formdata) {
        $.ajax({
            url: "/path to upload/",
            type: "POST",
            data: formdata,
            processData: false,
            contentType: false,
            success: function(res) {

            },       
            error: function(res) {

             }       
             });
            }
        });

PHP

for($i=0; $i<count($_FILES['file']['name']); $i++){
    $target_path = "uploads/";
    $ext = explode('.', basename( $_FILES['file']['name'][$i]));
    $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1]; 

    if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
        echo "The file has been uploaded successfully <br />";
    } else{
        echo "There was an error uploading the file, please try again! <br />";
    }
}

/** 
    Edit: $target_path variable need to be reinitialized and should 
    be inside for loop to avoid appending previous file name to new one. 
*/

Please use the script above script for ajax upload. It will work

CAML query with nested ANDs and ORs for multiple fields

This code will dynamically generate the expression for you with the nested clauses. I have a scenario where the number of "OR" s was unknown, so I'm using the below. Usage:

        private static void Main(string[] args)
        {
            var query = new PropertyString(@"<Query><Where>{{WhereClauses}}</Where></Query>");
            var whereClause =
                new PropertyString(@"<Eq><FieldRef Name='ID'/><Value Type='Counter'>{{NestClauseValue}}</Value></Eq>");
            var andClause = new PropertyString("<Or>{{FirstExpression}}{{SecondExpression}}</Or>");

            string[] values = {"1", "2", "3", "4", "5", "6"};

            query["WhereClauses"] = NestEq(whereClause, andClause, values);

            Console.WriteLine(query);
        }

And here's the code:

   private static string MakeExpression(PropertyString nestClause, string value)
        {
            var expr = nestClause.New();
            expr["NestClauseValue"] = value;
            return expr.ToString();
        }

        /// <summary>
        /// Recursively nests the clause with the nesting expression, until nestClauseValue is empty.
        /// </summary>
        /// <param name="whereClause"> A property string in the following format: <Eq><FieldRef Name='Title'/><Value Type='Text'>{{NestClauseValue}}</Value></Eq>"; </param>
        /// <param name="nestingExpression"> A property string in the following format: <And>{{FirstExpression}}{{SecondExpression}}</And> </param>
        /// <param name="nestClauseValues">A string value which NestClauseValue will be filled in with.</param>
        public static string NestEq(PropertyString whereClause, PropertyString nestingExpression, string[] nestClauseValues, int pos=0)
        {
            if (pos > nestClauseValues.Length)
            {
                return "";
            }

            if (nestClauseValues.Length == 1)
            {
                return MakeExpression(whereClause, nestClauseValues[0]);
            }

            var expr = nestingExpression.New();
            if (pos == nestClauseValues.Length - 2)
            {
                expr["FirstExpression"] = MakeExpression(whereClause, nestClauseValues[pos]);
                expr["SecondExpression"] = MakeExpression(whereClause, nestClauseValues[pos + 1]);
                return expr.ToString();
            }
            else
            {
                expr["FirstExpression"] = MakeExpression(whereClause, nestClauseValues[pos]);
                expr["SecondExpression"] = NestEq(whereClause, nestingExpression, nestClauseValues, pos + 1);
                return expr.ToString();
            }
        }






          public class PropertyString
    {
        private string _propStr;

        public PropertyString New()
        {
            return new PropertyString(_propStr );
        }

        public PropertyString(string propStr)
        {
            _propStr = propStr;
            _properties = new Dictionary<string, string>();
        }

        private Dictionary<string, string> _properties;
        public string this[string key]
        {
            get
            {
                return _properties.ContainsKey(key) ? _properties[key] : string.Empty;
            }
            set
            {
                if (_properties.ContainsKey(key))
                {
                    _properties[key] = value;
                }
                else
                {
                    _properties.Add(key, value);
                }
            }
        }



        /// <summary>
        /// Replaces properties in the format {{propertyName}} in the source string with values from KeyValuePairPropertiesDictionarysupplied dictionary.nce you've set a property it's replaced in the string and you 
        /// </summary>
        /// <param name="originalStr"></param>
        /// <param name="keyValuePairPropertiesDictionary"></param>
        /// <returns></returns>
        public override string ToString()
        {
            string modifiedStr = _propStr;
            foreach (var keyvaluePair in _properties)
            {
                modifiedStr = modifiedStr.Replace("{{" + keyvaluePair.Key + "}}", keyvaluePair.Value);
            }

            return modifiedStr;
        }
    }

Rotate a div using javascript

I recently had to build something similar. You can check it out in the snippet below.

The version I had to build uses the same button to start and stop the spinner, but you can manipulate to code if you have a button to start the spin and a different button to stop the spin

Basically, my code looks like this...

Run Code Snippet

_x000D_
_x000D_
var rocket = document.querySelector('.rocket');_x000D_
var btn = document.querySelector('.toggle');_x000D_
var rotate = false;_x000D_
var runner;_x000D_
var degrees = 0;_x000D_
_x000D_
function start(){_x000D_
    runner = setInterval(function(){_x000D_
        degrees++;_x000D_
        rocket.style.webkitTransform = 'rotate(' + degrees + 'deg)';_x000D_
    },50)_x000D_
}_x000D_
_x000D_
function stop(){_x000D_
    clearInterval(runner);_x000D_
}_x000D_
_x000D_
btn.addEventListener('click', function(){_x000D_
    if (!rotate){_x000D_
        rotate = true;_x000D_
        start();_x000D_
    } else {_x000D_
        rotate = false;_x000D_
        stop();_x000D_
    }_x000D_
})
_x000D_
body {_x000D_
  background: #1e1e1e;_x000D_
}    _x000D_
_x000D_
.rocket {_x000D_
    width: 150px;_x000D_
    height: 150px;_x000D_
    margin: 1em;_x000D_
    border: 3px dashed teal;_x000D_
    border-radius: 50%;_x000D_
    background-color: rgba(128,128,128,0.5);_x000D_
    display: flex;_x000D_
    justify-content: center;_x000D_
    align-items: center;_x000D_
  }_x000D_
  _x000D_
  .rocket h1 {_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
    font-size: .8em;_x000D_
    color: skyblue;_x000D_
    letter-spacing: 1em;_x000D_
    text-shadow: 0 0 10px black;_x000D_
  }_x000D_
  _x000D_
  .toggle {_x000D_
    margin: 10px;_x000D_
    background: #000;_x000D_
    color: white;_x000D_
    font-size: 1em;_x000D_
    padding: .3em;_x000D_
    border: 2px solid red;_x000D_
    outline: none;_x000D_
    letter-spacing: 3px;_x000D_
  }
_x000D_
<div class="rocket"><h1>SPIN ME</h1></div>_x000D_
<button class="toggle">I/0</button>
_x000D_
_x000D_
_x000D_

Optional query string parameters in ASP.NET Web API

Default values cannot be supplied for parameters that are not declared 'optional'

 Function GetFindBooks(id As Integer, ByVal pid As Integer, Optional sort As String = "DESC", Optional limit As Integer = 99)

In your WebApiConfig

 config.Routes.MapHttpRoute( _
          name:="books", _
          routeTemplate:="api/{controller}/{action}/{id}/{pid}/{sort}/{limit}", _
          defaults:=New With {.id = RouteParameter.Optional, .pid = RouteParameter.Optional, .sort = UrlParameter.Optional, .limit = UrlParameter.Optional} _
      )

How do I use typedef and typedef enum in C?

typedef defines a new data type. So you can have:

typedef char* my_string;
typedef struct{
  int member1;
  int member2;
} my_struct;

So now you can declare variables with these new data types

my_string s;
my_struct x;

s = "welcome";
x.member1 = 10;

For enum, things are a bit different - consider the following examples:

enum Ranks {FIRST, SECOND};
int main()
{
   int data = 20;
   if (data == FIRST)
   {
      //do something
   }
}

using typedef enum creates an alias for a type:

typedef enum Ranks {FIRST, SECOND} Order;
int main()
{
   Order data = (Order)20;  // Must cast to defined type to prevent error

   if (data == FIRST)
   {
      //do something
   }
}

phpMyAdmin - config.inc.php configuration?

Do Ctrl+alt+t and then:

  1. sudo chmod 777 /opt/lampp/phpmyadmin/config.inc.php

  2. open config.inc.php

  3. test

    1. change config to cookie
      $cfg['Servers'][$i]['auth_type'] = 'config';
    2. donot change this
      $cfg['Servers'][$i]['user'] = 'root';
    3. change '' to 'root'
      $cfg['Servers'][$i]['password'] = '';
  4. save config.inc.php

  5. sudo chmod 644 /opt/lampp/phpmyadmin/config.inc.php

  6. restart the xampp and check phpmyadmin

If it works i think i am glad to help you!!!

Android Whatsapp/Chat Examples

If you are looking to create an instant messenger for Android, this code should get you started somewhere.

Excerpt from the source :

This is a simple IM application runs on Android, application makes http request to a server, implemented in php and mysql, to authenticate, to register and to get the other friends' status and data, then it communicates with other applications in other devices by socket interface.

EDIT : Just found this! Maybe it's not related to WhatsApp. But you can use the source to understand how chat applications are programmed.

There is a website called Scringo. These awesome people provide their own SDK which you can integrate in your existing application to exploit cool features like radaring, chatting, feedback, etc. So if you are looking to integrate chat in application, you could just use their SDK. And did I say the best part? It's free!

*UPDATE : * Scringo services will be closed down on 15 February, 2015.

How to get the mouse position without events (without moving the mouse)?

Edit 2020: This does not work any more. It seems so, that the browser vendors patched this out. Because the most browsers rely on chromium, it might be in its core.

Old answer: You can also hook mouseenter (this event is fired after page reload, when the mousecursor is inside the page). Extending Corrupted's code should do the trick:

_x000D_
_x000D_
var x = null;_x000D_
var y = null;_x000D_
    _x000D_
document.addEventListener('mousemove', onMouseUpdate, false);_x000D_
document.addEventListener('mouseenter', onMouseUpdate, false);_x000D_
    _x000D_
function onMouseUpdate(e) {_x000D_
  x = e.pageX;_x000D_
  y = e.pageY;_x000D_
  console.log(x, y);_x000D_
}_x000D_
_x000D_
function getMouseX() {_x000D_
  return x;_x000D_
}_x000D_
_x000D_
function getMouseY() {_x000D_
  return y;_x000D_
}
_x000D_
_x000D_
_x000D_

You can also set x and y to null on mouseleave-event. So you can check if the user is on your page with it's cursor.

Maven: repository element was not specified in the POM inside distributionManagement?

The ID of the two repos are both localSnap; that's probably not what you want and it might confuse Maven.

If that's not it: There might be more repository elements in your POM. Search the output of mvn help:effective-pom for repository to make sure the number and place of them is what you expect.

Understanding dispatch_async

Swift version

This is the Swift version of David's Objective-C answer. You use the global queue to run things in the background and the main queue to update the UI.

DispatchQueue.global(qos: .background).async {
    
    // Background Thread
    
    DispatchQueue.main.async {
        // Run UI Updates
    }
}

Loading inline content using FancyBox

Just something I found for Wordpress users,

As obvious as it sounds, If your div is returning some AJAX content based on say a header that would commonly link out to a new post page, some tutorials will say to return false since you're returning the post data on the same page and the return would prevent the page from moving. However if you return false, you also prevent Fancybox2 from doing it's thing as well. I spent hours trying to figure that stupid simple thing out.

So for these kind of links, just make sure that the href property is the hashed (#) div you wish to select, and in your javascript, make sure that you do not return false since you no longer will need to.

Simple I know ^_^

Unable to access JSON property with "-" dash

jsonObj.profile-id is a subtraction expression (i.e. jsonObj.profile - id).

To access a key that contains characters that cannot appear in an identifier, use brackets:

jsonObj["profile-id"]

c# datatable insert column at position 0

Just to improve Wael's answer and put it on a single line:

dt.Columns.Add("Better", typeof(Boolean)).SetOrdinal(0);

UPDATE: Note that this works when you don't need to do anything else with the DataColumn. Add() returns the column in question, SetOrdinal() returns nothing.

How does "cat << EOF" work in bash?

Long story short, EOF marker(but a different literal can be used as well) is a heredoc format that allows you to provide your input as multiline. A lot of confusion comes from how cat actually works it seems. You can use cat with >> or > as follows:

$ cat >> temp.txt
line 1
line 2

While cat can be used this way when writing manually into console, it's not convenient if I want to provide the input in a more declarative way so that it can be reused by tools and also to keep indentations, whitespaces, etc.
Heredoc allows to define your entire input as if you are not working with stdin but typing in a separate text editor. This is what Wikipedia article means by:

it is a section of a source code file that is treated as if it were a separate file.

How to make use of SQL (Oracle) to count the size of a string?

You can use LENGTH() for CHAR / VARCHAR2 and DBMS_LOB.GETLENGTH() for CLOB. Both functions will count actual characters (not bytes).

See the linked documentation if you do need bytes.

How to find the largest file in a directory and its subdirectories?

On Solaris I use:

find . -type f -ls|sort -nr -k7|awk 'NR==1{print $7,$11}' #formatted

or

find . -type f -ls | sort -nrk7 | head -1 #unformatted

because anything else posted here didn't work. This will find the largest file in $PWD and subdirectories.

What are queues in jQuery?

This thread helped me a lot with my problem, but I've used $.queue in a different way and thought I would post what I came up with here. What I needed was a sequence of events (frames) to be triggered, but the sequence to be built dynamically. I have a variable number of placeholders, each of which should contain an animated sequence of images. The data is held in an array of arrays, so I loop through the arrays to build each sequence for each of the placeholders like this:

/* create an empty queue */
var theQueue = $({});
/* loop through the data array */
for (var i = 0; i < ph.length; i++) {
    for (var l = 0; l < ph[i].length; l++) {
        /* create a function which swaps an image, and calls the next function in the queue */
        theQueue.queue("anim", new Function("cb", "$('ph_"+i+"' img').attr('src', '/images/"+i+"/"+l+".png');cb();"));
        /* set the animation speed */
        theQueue.delay(200,'anim');
    }
}
/* start the animation */
theQueue.dequeue('anim');

This is a simplified version of the script I have arrived at, but should show the principle - when a function is added to the queue, it is added using the Function constructor - this way the function can be written dynamically using variables from the loop(s). Note the way the function is passed the argument for the next() call, and this is invoked at the end. The function in this case has no time dependency (it doesn't use $.fadeIn or anything like that), so I stagger the frames using $.delay.

Batch script to delete files

Lets say you saved your software onto your desktop.
if you want to remove an entire folder like an uninstaller program you could use this.

cd C:\Users\User\Detsktop\
rd /s /q SOFTWARE

this will delete the entire folder called software and all of its files and subfolders

Make Sure You Delete The Correct Folder Cause This Does Not Have A Yes / No Option

How do I check if an array includes a value in JavaScript?

While array.indexOf(x)!=-1 is the most concise way to do this (and has been supported by non-Internet Explorer browsers for over decade...), it is not O(1), but rather O(N), which is terrible. If your array will not be changing, you can convert your array to a hashtable, then do table[x]!==undefined or ===undefined:

Array.prototype.toTable = function() {
    var t = {};
    this.forEach(function(x){t[x]=true});
    return t;
}

Demo:

var toRemove = [2,4].toTable();
[1,2,3,4,5].filter(function(x){return toRemove[x]===undefined})

(Unfortunately, while you can create an Array.prototype.contains to "freeze" an array and store a hashtable in this._cache in two lines, this would give wrong results if you chose to edit your array later. JavaScript has insufficient hooks to let you keep this state, unlike Python for example.)

Android: Clear the back stack

Use this code for starting a new Activity and close or destroy all other activity stack or back stack.

Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);

Intro to GPU programming

Check out CUDA by NVidia, IMO it's the easiest platform to do GPU programming. There are tons of cool materials to read. http://www.nvidia.com/object/cuda_home.html

Hello world would be to do any kind of calculation using GPU.

Hope that helps.

What is the best way to programmatically detect porn images?

I shall not today attempt further to define the kinds of material I understand to be embraced within that shorthand description ["hard-core pornography"]; and perhaps I could never succeed in intelligibly doing so. But I know it when I see it, and the motion picture involved in this case is not that.

United States Supreme Court Justice Potter Stewart, 1964

How to debug a bash script?

Install VSCode, then add bash debug extension and you are ready to debug in visual mode. see Here in action.

enter image description here

How to get table cells evenly spaced?

In your CSS file:

.TableHeader { width: 100px; }

This will set all of the td tags below each header to 100px. You can also add a width definition (in the markup) to each individual th tag, but the above solution would be easier.

Multiplying Two Columns in SQL Server

select InitialPayment * MonthlyRate as MultiplyingCalculation, InitialPayment - MonthlyRate as SubtractingCalculation from Payment

How to send a JSON object using html form data

I'm late but I need to say for those who need an object, using only html, there's a way. In some server side frameworks like PHP you can write the follow code:

<form action="myurl" method="POST" name="myForm">
        <p><label for="first_name">First Name:</label>
        <input type="text" name="name[first]" id="fname"></p>

        <p><label for="last_name">Last Name:</label>
        <input type="text" name="name[last]" id="lname"></p>

        <input value="Submit" type="submit">
    </form>

So, we need setup the name of the input as object[property] for got an object. In the above example, we got a data with the follow JSON:

{
"name": {
  "first": "some data",
  "last": "some data"
 }
}

How to read a specific line using the specific line number from a file in Java?

Another way.

try (BufferedReader reader = Files.newBufferedReader(
        Paths.get("file.txt"), StandardCharsets.UTF_8)) {
    List<String> line = reader.lines()
                              .skip(31)
                              .limit(1)
                              .collect(Collectors.toList());

    line.stream().forEach(System.out::println);
}

JUnit assertEquals(double expected, double actual, double epsilon)

Epsilon is your "fuzz factor," since doubles may not be exactly equal. Epsilon lets you describe how close they have to be.

If you were expecting 3.14159 but would take anywhere from 3.14059 to 3.14259 (that is, within 0.001), then you should write something like

double myPi = 22.0d / 7.0d; //Don't use this in real life!
assertEquals(3.14159, myPi, 0.001);

(By the way, 22/7 comes out to 3.1428+, and would fail the assertion. This is a good thing.)

What are the differences between C, C# and C++ in terms of real-world applications?

From your other posts, I guess you want to learn a new language to get new skills. My advice is that the language is not really important, what is important is the quality of its community (advice, but also existing code you can read and learn from) and the available libraries/frameworks. In this respect, I think the "C family" is not the best choice for you: web libraries and frameworks are few, not portable and not great, and coding style of code you can study varies a lot and may confuse you a lot (although C is my favorite language).

I would advise to just learn C, and try to really understand the concept of pointers, then move to other languages more adapted to the web (Python or JavaScript comes to mind - or even Java). Also, in the C family, Objective-C has the best mix of power and simplicity in my opinion, but is a niche player.

How to validate email id in angularJs using ng-pattern

There is nice example how to deal with this kind of problem modyfing built-in validators angulardocs. I have only added more strict validation pattern.

app.directive('validateEmail', function() {
  var EMAIL_REGEXP = /^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;

  return {
    require: 'ngModel',
    restrict: '',
    link: function(scope, elm, attrs, ctrl) {
      // only apply the validator if ngModel is present and Angular has added the email validator
      if (ctrl && ctrl.$validators.email) {

        // this will overwrite the default Angular email validator
        ctrl.$validators.email = function(modelValue) {
          return ctrl.$isEmpty(modelValue) || EMAIL_REGEXP.test(modelValue);
        };
      }
    }
  };
});

And simply add

<input type='email' validate-email name='email' id='email' ng-model='email' required>  

How to get everything after last slash in a URL?

urlparse is fine to use if you want to (say, to get rid of any query string parameters).

import urllib.parse

urls = [
    'http://www.test.com/TEST1',
    'http://www.test.com/page/TEST2',
    'http://www.test.com/page/page/12345',
    'http://www.test.com/page/page/12345?abc=123'
]

for i in urls:
    url_parts = urllib.parse.urlparse(i)
    path_parts = url_parts[2].rpartition('/')
    print('URL: {}\nreturns: {}\n'.format(i, path_parts[2]))

Output:

URL: http://www.test.com/TEST1
returns: TEST1

URL: http://www.test.com/page/TEST2
returns: TEST2

URL: http://www.test.com/page/page/12345
returns: 12345

URL: http://www.test.com/page/page/12345?abc=123
returns: 12345

adding css file with jquery

This is how I add css using jQuery ajax. Hope it helps someone..

$.ajax({
            url:"site/test/style.css",
            success:function(data){
                 $("<style></style>").appendTo("head").html(data);
            }
        })

Deny access to one specific folder in .htaccess

In an .htaccess file you need to use

Deny from  all

Put this in site/includes/.htaccess to make it specific to the includes directory

If you just wish to disallow a listing of directory files you can use

Options -Indexes 

How to display Toast in Android?

If it's fragment,

Toast.makeText(getActivity(), "this is my Toast message!!! =)",
                   Toast.LENGTH_LONG).show();

php function mail() isn't working

I think you are not configured properly,

if you are using XAMPP then you can easily send mail from localhost.

for example you can configure C:\xampp\php\php.ini and c:\xampp\sendmail\sendmail.ini for gmail to send mail.

in C:\xampp\php\php.ini find extension=php_openssl.dll and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.

in php.ini file find [mail function] and change

SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"

(use the above send mail path only and it will work)

Now Open C:\xampp\sendmail\sendmail.ini. Replace all the existing code in sendmail.ini with following code

[sendmail]

smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]

Now you have done!! create php file with mail function and send mail from localhost.

Update

First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()).

You can set the following settings in your PHP.ini:

ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");

How could I create a list in c++?

If you are going to use std::list, you need to pass a type parameter:

list<int> intList;  
list<int>* intListPtr = new list<int>;

If you want to know how lists work, I recommending googling for some C/C++ tutorials to gain an understanding of that subject. Next step would then be learning enough C++ to create a list class, and finally a list template class.

If you have more questions, ask back here.

How to select an element with 2 classes

Just chain them together:

.a.b {
  color: #666;
}

HTTP client timeout and server timeout

According to https://bugzilla.mozilla.org/show_bug.cgi?id=592284, the pref network.http.connection-retry-timeout controls the amount of time in ms (Milliseconds !) to wait for success on the initial connection before beginning the second one. Setting it to 0 disables the parallel connection.

Entity Framework is Too Slow. What are my options?

If you're purely fetching data, it's a big help to performance when you tell EF to not keep track of the entities it fetches. Do this by using MergeOption.NoTracking. EF will just generate the query, execute it and deserialize the results to objects, but will not attempt to keep track of entity changes or anything of that nature. If a query is simple (doesn't spend much time waiting on the database to return), I've found that setting it to NoTracking can double query performance.

See this MSDN article on the MergeOption enum:

Identity Resolution, State Management, and Change Tracking

This seems to be a good article on EF performance:

Performance and the Entity Framework

Change package name for Android in React Native

If you are using Android Studio-

changing com.myapp to com.mycompany.myapp

  1. create a new package hierarchy com.mycompany.myapp under android/app/src/main/java

  2. Copy all classes from com.myapp to com.mycompany.myapp using Android studio GUI

  3. Android studio will take care of putting suitable package name for all copied classes. This is useful if you have some custom modules and don't want to manually replace in all the .java files.

  4. Update android/app/src/main/AndroidManifest.xml and android/app/build.gradle (replace com.myapp to com.mycompany.myapp

  5. Sync the project (gradle build)

Laravel 5 - redirect to HTTPS

In Laravel 5.1, I used: File: app\Providers\AppServiceProvider.php

public function boot()
{
    if ($this->isSecure()) {
        \URL::forceSchema('https');
    }
}

public function isSecure()
{
    $isSecure = false;
    if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
        $isSecure = true;
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') {
        $isSecure = true;
    }

    return $isSecure;
}

NOTE: use forceSchema, NOT forceScheme

FloatingActionButton example with Support Library

I just found some issues on FAB and I want to enhance another answer.


setRippleColor issue

So, the issue will come once you set the ripple color (FAB color on pressed) programmatically through setRippleColor. But, we still have an alternative way to set it, i.e. by calling:

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
ColorStateList rippleColor = ContextCompat.getColorStateList(context, R.color.fab_ripple_color);
fab.setBackgroundTintList(rippleColor);

Your project need to has this structure:

/res/color/fab_ripple_color.xml

enter image description here

And the code from fab_ripple_color.xml is:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="@color/fab_color_pressed" />
    <item android:state_focused="true" android:color="@color/fab_color_pressed" />
    <item android:color="@color/fab_color_normal"/>
</selector>

Finally, alter your FAB slightly:

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_action_add"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    app:fabSize="normal"
    app:borderWidth="0dp"
    app:elevation="6dp"
    app:pressedTranslationZ="12dp"
    app:rippleColor="@android:color/transparent"/> <!-- set to transparent color -->

For API level 21 and higher, set margin right and bottom to 24dp:

...
android:layout_marginRight="24dp"
android:layout_marginBottom="24dp" />

FloatingActionButton design guides

As you can see on my FAB xml code above, I set:

        ...
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        app:elevation="6dp"
        app:pressedTranslationZ="12dp"
        ...
  • By setting these attributes, you don't need to set layout_marginTop and layout_marginRight again (only on pre-Lollipop). Android will place it automatically on the right corned side of the screen, which the same as normal FAB in Android Lollipop.

        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
    

Or, you can use this in CoordinatorLayout:

        android:layout_gravity="end|bottom"
  • You need to have 6dp elevation and 12dp pressedTranslationZ, according to this guide from Google.

FAB rules

When should I use curly braces for ES6 import?

  • If there is any default export in the file, there isn't any need to use the curly braces in the import statement.

  • if there are more than one export in the file then we need to use curly braces in the import file so that which are necessary we can import.

  • You can find the complete difference when to use curly braces and default statement in the below YouTube video (very heavy Indian accent, including rolling on the r's...).

    21. ES6 Modules. Different ways of using import/export, Default syntax in the code. ES6 | ES2015

Unexpected token ILLEGAL in webkit

You can use online Minify, it removes these invisible characters efficiently but also changes your code. So be careful.

http://jscompress.com/

Gridview row editing - dynamic binding to a DropDownList

I am using a ListView instead of a GridView in 3.5. When the user wants to edit I have set the selected item of the dropdown to the exising value of that column for the record. I am able to access the dropdown in the ItemDataBound event. Here's the code:

protected void listViewABC_ItemDataBound(object sender, ListViewItemEventArgs e)
{
    // This stmt is used to execute the code only in case of edit 
    if (((ListView)(sender)).EditIndex != -1 && ((ListViewDataItem)(e.Item)).DisplayIndex == ((ListView)(sender)).EditIndex)
    {
        ((DropDownList)(e.Item.FindControl("ddlXType"))).SelectedValue = ((MyClass)((ListViewDataItem)e.Item).DataItem).XTypeId.ToString();
        ((DropDownList)(e.Item.FindControl("ddlIType"))).SelectedValue = ((MyClass)((ListViewDataItem)e.Item).DataItem).ITypeId.ToString();
    }
}

Best way to check for "empty or null value"

Something that I saw people using is stringexpression > ''. This may be not the fastest one, but happens to be one of the shortest.

Tried it on MS SQL as well as on PostgreSQL.

Truncate Two decimal places without rounding

        public static void ReminderDigints(decimal? number, out decimal? Value,  out decimal? Reminder)
        {
            Reminder = null;
            Value = null;
            if (number.HasValue)
            {
                Value = Math.Floor(number.Value);
                Reminder = (number - Math.Truncate(number.Value));
            }
        }



        decimal? number= 50.55m;             
        ReminderDigints(number, out decimal? Value, out decimal? Reminder);

How does Google calculate my location on a desktop?

They use a combination of IP geolocation, as well as comparing the results of a scan for nearby wireless networks with a database on their side (which is built by collecting GPS coordinates alongside wifi scan data when Android phone users use their GPS)

AJAX post error : Refused to set unsafe header "Connection"

Remove these two lines:

xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");

XMLHttpRequest isn't allowed to set these headers, they are being set automatically by the browser. The reason is that by manipulating these headers you might be able to trick the server into accepting a second request through the same connection, one that wouldn't go through the usual security checks - that would be a security vulnerability in the browser.

What does AND 0xFF do?

The danger of the second expression comes if the type of byte1 is char. In that case, some implementations can have it signed char, which will result in sign extension when evaluating.

signed char byte1 = 0x80;
signed char byte2 = 0x10;

unsigned short value1 = ((byte2 << 8) | (byte1 & 0xFF));
unsigned short value2 = ((byte2 << 8) | byte1);

printf("value1=%hu %hx\n", value1, value1);
printf("value2=%hu %hx\n", value2, value2);

will print

value1=4224 1080     right
value2=65408 ff80    wrong!!

I tried it on gcc v3.4.6 on Solaris SPARC 64 bit and the result is the same with byte1 and byte2 declared as char.

TL;DR

The masking is to avoid implicit sign extension.

EDIT: I checked, it's the same behaviour in C++.

EDIT2: As requested explanation of sign extension. Sign extension is a consequence of the way C evaluates expressions. There is a rule in C called promotion rule. C will implicitly cast all small types to int before doing the evaluation. Let's see what happens to our expression:

unsigned short value2 = ((byte2 << 8) | byte1);

byte1 is a variable containing bit pattern 0xFF. If char is unsigned that value is interpreted as 255, if it is signed it is -128. When doing the calculation, C will extend the value to an int size (16 or 32 bits generally). This means that if the variable is unsigned and we will keep the value 255, the bit-pattern of that value as int will be 0x000000FF. If it is signed we want the value -128 which bit pattern is 0xFFFFFFFF. The sign was extended to the size of the tempory used to do the calculation. And thus oring the temporary will yield the wrong result.

On x86 assembly it is done with the movsx instruction (movzx for the zero extend). Other CPU's had other instructions for that (6809 had SEX).

Generate pdf from HTML in div using Javascript

  • No depenencies, pure JS
  • To add CSS or images - do not use relative URLs, use full URLs http://...domain.../path.css or so. It creates separate HTML document and it has no context of main thing.
  • you can also embed images as base64

This served me for years now:

export default function printDiv({divId, title}) {
  let mywindow = window.open('', 'PRINT', 'height=650,width=900,top=100,left=150');

  mywindow.document.write(`<html><head><title>${title}</title>`);
  mywindow.document.write('</head><body >');
  mywindow.document.write(document.getElementById(divId).innerHTML);
  mywindow.document.write('</body></html>');

  mywindow.document.close(); // necessary for IE >= 10
  mywindow.focus(); // necessary for IE >= 10*/

  mywindow.print();
  mywindow.close();

  return true;
}

Most concise way to convert a Set<T> to a List<T>

If you are using Guava, you statically import newArrayList method from Lists class:

List<String> l = newArrayList(setOfAuthors);

Where can I find MySQL logs in phpMyAdmin?

In phpMyAdmin 4.0, you go to Status > Monitor. In there you can enable the slow query log and general log, see a live monitor, select a portion of the graph, see the related queries and analyse them.

increment date by one month

 <?php
              $selectdata ="select fromd,tod  from register where username='$username'";
            $q=mysqli_query($conm,$selectdata);
            $row=mysqli_fetch_array($q);

            $startdate=$row['fromd']; 
            $stdate=date('Y', strtotime($startdate));  

            $endate=$row['tod']; 
            $enddate=date('Y', strtotime($endate));  

            $years = range ($stdate,$enddate);
            echo '<select name="years" class="form-control">';
            echo '<option>SELECT</option>';
            foreach($years as $year)
              {   echo '<option value="'.$year.'"> '.$year.' </option>';  }
                echo '</select>'; ?>

XSLT equivalent for JSON

XSLT equivalents for JSON - a list of candidates (tools and specs)

Tools

1. XSLT

You can use XSLT for JSON with the aim of fn:json-to-xml.

This section describes facilities allowing JSON data to be processed using XSLT.

2. jq

jq is like sed for JSON data - you can use it to slice and filter and map and transform structured data with the same ease that sed, awk, grep and friends let you play with text. There are install packages for different OS.

3. jj

JJ is a command line utility that provides a fast and simple way to retrieve or update values from JSON documents. It's powered by GJSON and SJSON under the hood.

4. fx

Command-line JSON processing tool - Don't need to learn new syntax - Plain JavaScript - Formatting and highlighting - Standalone binary

5. jl

jl ("JSON lambda") is a tiny functional language for querying and manipulating JSON.

6. JOLT

JSON to JSON transformation library written in Java where the "specification" for the transform is itself a JSON document.

7. gron

Make JSON greppable! gron transforms JSON into discrete assignments to make it easier to grep for what you want and see the absolute 'path' to it. It eases the exploration of APIs that return large blobs of JSON but have terrible documentation.

8. json-e

JSON-e is a data-structure parameterization system for embedding context in JSON objects. The central idea is to treat a data structure as a "template" and transform it, using another data structure as context, to produce an output data structure.

9. JSLT

JSLT is a complete query and transformation language for JSON. The language design is inspired by jq, XPath, and XQuery.

10. JSONata

JSONata is a lightweight query and transformation language for JSON data. Inspired by the 'location path' semantics of XPath 3.1, it allows sophisticated queries to be expressed in a compact and intuitive notation.

11. JSONPath Plus

Analyse, transform, and selectively extract data from JSON documents (and JavaScript objects). jsonpath-plus expands on the original specification to add some additional operators and makes explicit some behaviors the original did not spell out.

12. json-transforms Last Commit Dec 1, 2017

Provides a recursive, pattern-matching approach to transforming JSON data. Transformations are defined as a set of rules which match the structure of a JSON object. When a match occurs, the rule emits the transformed data, optionally recursing to transform child objects.

13. json Last commit Jun 23, 2018

json is a fast CLI tool for working with JSON. It is a single-file node.js script with no external deps (other than node.js itself).

14. jsawk Last commit Mar 4, 2015

Jsawk is like awk, but for JSON. You work with an array of JSON objects read from stdin, filter them using JavaScript to produce a results array that is printed to stdout.

15. yate Last Commit Mar 13, 2017

Tests can be used as docu https://github.com/pasaran/yate/tree/master/tests

16. jsonpath-object-transform Last Commit Jan 18, 2017

Pulls data from an object literal using JSONPath and generate a new objects based on a template.

17. Stapling Last Commit Sep 16, 2013

Stapling is a JavaScript library that enables XSLT formatting for JSON objects. Instead of using a JavaScript templating engine and text/html templates, Stapling gives you the opportunity to use XSLT templates - loaded asynchronously with Ajax and then cached client side - to parse your JSON datasources.

Specs:

JSON Pointer defines a string syntax for identifying a specific value within a JavaScript Object Notation (JSON) document.

JSONPath expressions always refer to a JSON structure in the same way as XPath expression are used in combination with an XML document

JSPath for JSON is like XPath for XML."

The main source of inspiration behind JSONiq is XQuery, which has been proven so far a successful and productive query language for semi-structured data

Is there a C++ decompiler?

I haven't seen any decompilers that generate C++ code. I've seen a few experimental ones that make a reasonable attempt at generating C code, but they tended to be dependent on matching the code-generation patterns of a particular compiler (that may have changed, it's been awhile since I last looked into this). Of course any symbolic information will be gone. Google for "decompiler".

Separating class code into a header and cpp file

Usually you put only declarations and really short inline functions in the header file:

For instance:

class A {
 public:
  A(); // only declaration in the .h unless only a short initialization list is used.

  inline int GetA() const {
    return a_;
  }

  void DoSomethingCoplex(); // only declaration
  private:
   int a_;
 };

How do I fix maven error The JAVA_HOME environment variable is not defined correctly?

A very common mistake people make is that, when they set JAVA_HOME or JRE_HOME, they set the value to C:\Program Files\Java\jdk1.8.0_221\bin or similar.

Please note JAVA_HOME and JRE_HOME value should not contain \bin

How can I call a shell command in my Perl script?

As you become more experienced with using Perl, you'll find that there are fewer and fewer occasions when you need to run shell commands. For example, one way to get a list of files is to use Perl's built-in glob function. If you want the list in sorted order you could combine it with the built-in sort function. If you want details about each file, you can use the stat function. Here's an example:

#!/usr/bin/perl

use strict;
use warnings;

foreach my $file ( sort glob('/home/grant/*') ) {
    my($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks)
        = stat($file);
    printf("%-40s %8u bytes\n", $file, $size);
}

'MOD' is not a recognized built-in function name

for your exact sample, it should be like this.

DECLARE @m INT
SET @m = 321%11
SELECT @m

Creating a LinkedList class from scratch

How about a fully functional implementation of a non-recursive Linked List?

I created this for my Algorithms I class as a stepping stone to gain a better understanding before moving onto writing a doubly-linked queue class for an assignment.

Here's the code:

import java.util.Iterator;
import java.util.NoSuchElementException;

public class LinkedList<T> implements Iterable<T> {
    private Node first;
    private Node last;
    private int N;

    public LinkedList() {
        first = null;
        last = null;
        N = 0;
    }

    public void add(T item) {
        if (item == null) { throw new NullPointerException("The first argument for addLast() is null."); }
        if (!isEmpty()) {
            Node prev = last;
            last = new Node(item, null);
            prev.next = last;
        }
        else {
            last = new Node(item, null);
            first = last;
        }
        N++;
    }

    public boolean remove(T item) {
        if (isEmpty()) { throw new IllegalStateException("Cannot remove() from and empty list."); }
        boolean result = false;
        Node prev = first;
        Node curr = first;
        while (curr.next != null || curr == last) {
            if (curr.data.equals(item)) {
                // remove the last remaining element
                if (N == 1) { first = null; last = null; }
                // remove first element
                else if (curr.equals(first)) { first = first.next; }
                // remove last element
                else if (curr.equals(last)) { last = prev; last.next = null; }
                // remove element
                else { prev.next = curr.next; }
                N--;
                result = true;
                break;
            }
            prev = curr;
            curr = prev.next;
        }
        return result;
    }

    public int size() {
        return N;
    }

    public boolean isEmpty() {
        return N == 0;
    }

    private class Node {
        private T data;
        private Node next;

        public Node(T data, Node next) {
            this.data = data;
            this.next = next;
        }
    }

    public Iterator<T> iterator() { return new LinkedListIterator(); }

    private class LinkedListIterator implements Iterator<T> {
        private Node current = first;

        public T next() {
            if (!hasNext()) { throw new NoSuchElementException(); }
            T item = current.data;
            current = current.next;
            return item;
        }

        public boolean hasNext() { return current != null; }

        public void remove() { throw new UnsupportedOperationException(); }
    }

    @Override public String toString() {
        StringBuilder s = new StringBuilder();
        for (T item : this)
            s.append(item + " ");
        return s.toString();
    }

    public static void main(String[] args) {
        LinkedList<String> list = new LinkedList<>();
        while(!StdIn.isEmpty()) {
            String input = StdIn.readString();
            if (input.equals("print")) { StdOut.println(list.toString()); continue; }
            if (input.charAt(0) == ('+')) { list.add(input.substring(1)); continue; }
            if (input.charAt(0) == ('-')) { list.remove(input.substring(1)); continue; }
            break;
        }
    }
}

Note: It's a pretty basic implementation of a singly-linked-list. The 'T' type is a generic type placeholder. Basically, this linked list should work with any type that inherits from Object. If you use it for primitive types be sure to use the nullable class equivalents (ex 'Integer' for the 'int' type). The 'last' variable isn't really necessary except that it shortens insertions to O(1) time. Removals are slow since they run in O(N) time but it allows you to remove the first occurrence of a value in the list.

If you want you could also look into implementing:

  • addFirst() - add a new item to the beginning of the LinkedList
  • removeFirst() - remove the first item from the LinkedList
  • removeLast() - remove the last item from the LinkedList
  • addAll() - add a list/array of items to the LinkedList
  • removeAll() - remove a list/array of items from the LinkedList
  • contains() - check to see if the LinkedList contains an item
  • contains() - clear all items in the LinkedList

Honestly, it only takes a few lines of code to make this a doubly-linked list. The main difference between this and a doubly-linked-list is that the Node instances of a doubly-linked list require an additional reference that points to the previous element in the list.

The benefit of this over a recursive implementation is that it's faster and you don't have to worry about flooding the stack when you traverse large lists.

There are 3 commands to test this in the debugger/console:

  • Prefixing a value by a '+' will add it to the list.
  • Prefixing with a '-' will remove the first occurrence from the list.
  • Typing 'print' will print out the list with the values separated by spaces.

If you have never seen the internals of how one of these works I suggest you step through the following in the debugger:

  • add() - tacks a new node onto the end or initializes the first/last values if the list is empty
  • remove() - walks the list from the start-to-end. If it finds a match it removes that item and connects the broken links between the previous and next links in the chain. Special exceptions are added when there is no previous or next link.
  • toString() - uses the foreach iterator to simply walk the list chain from beginning-to-end.

While there are better and more efficient approaches for lists like array-lists, understanding how the application traverses via references/pointers is integral to understanding how many higher-level data structures work.

How do I call a JavaScript function on page load?

If you want the onload method to take parameters, you can do something similar to this:

window.onload = function() {
  yourFunction(param1, param2);
};

This binds onload to an anonymous function, that when invoked, will run your desired function, with whatever parameters you give it. And, of course, you can run more than one function from inside the anonymous function.

Add a CSS border on hover without moving the element

add margin:-1px; which reduces 1px to each side. or if you need only for side you can do margin-left:-1px etc.

How to run iPhone emulator WITHOUT starting Xcode?

Try below instruction for launching iphone simulator:

Goto Application Folder-->Xcode app-->right click to Show Package Contents-->now show files in xcode contents-->Developer-->Platforms-->iPhoneSimulator.platform-->Developer-->Applications--> now show iOS Simulator app click to launch iphone simulator...!

How do I get formatted JSON in .NET using C#?

All this can be done in one simple line:

string jsonString = JsonConvert.SerializeObject(yourObject, Formatting.Indented);

m2e error in MavenArchiver.getManifest()

I also faced the similar issues, changing the version from 2.0.0.RELEASE to 1.5.10.RELEASE worked for me, please try it before downgrading the maven version

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
</parent>
<dependencies>
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-web</artifactId>
 </dependency>  
</dependencies>

Xcode 9 error: "iPhone has denied the launch request"

I just cleared the profiles with the Apple Configurator, restarted the iDevice and worked again as usual.

Use stored procedure to insert some data into a table

If you are trying to return back the ID within the scope, using the SCOPE_IDENTITY() would be a better approach. I would not advice to use @@IDENTITY, as this can return any ID.

CREATE PROC [dbo].[sp_Test] (
  @myID int output,
  @myFirstName nvarchar(50),
  @myLastName nvarchar(50),
  @myAddress nvarchar(50),
  @myPort int
) AS
BEGIN
    INSERT INTO Dvds (myFirstName, myLastName, myAddress, myPort)
    VALUES (@myFirstName, @myLastName, @myAddress, @myPort);

    SET @myID = SCOPE_IDENTITY();
END
GO

Google Maps JavaScript API RefererNotAllowedMapError

I struggled to make this work as well, but here are some pointers:

  • The URLs set as referrers include http, e.g. http://example.com/*
  • Google Maps JavaScript API was enabled
  • Billing was set-up on this account

Once all of this above was resolved, the maps displayed as expected.

Compression/Decompression string with C#

according to this snippet i use this code and it's working fine:

using System;
using System.IO;
using System.IO.Compression;
using System.Text;

namespace CompressString
{
    internal static class StringCompressor
    {
        /// <summary>
        /// Compresses the string.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <returns></returns>
        public static string CompressString(string text)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(text);
            var memoryStream = new MemoryStream();
            using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Compress, true))
            {
                gZipStream.Write(buffer, 0, buffer.Length);
            }

            memoryStream.Position = 0;

            var compressedData = new byte[memoryStream.Length];
            memoryStream.Read(compressedData, 0, compressedData.Length);

            var gZipBuffer = new byte[compressedData.Length + 4];
            Buffer.BlockCopy(compressedData, 0, gZipBuffer, 4, compressedData.Length);
            Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gZipBuffer, 0, 4);
            return Convert.ToBase64String(gZipBuffer);
        }

        /// <summary>
        /// Decompresses the string.
        /// </summary>
        /// <param name="compressedText">The compressed text.</param>
        /// <returns></returns>
        public static string DecompressString(string compressedText)
        {
            byte[] gZipBuffer = Convert.FromBase64String(compressedText);
            using (var memoryStream = new MemoryStream())
            {
                int dataLength = BitConverter.ToInt32(gZipBuffer, 0);
                memoryStream.Write(gZipBuffer, 4, gZipBuffer.Length - 4);

                var buffer = new byte[dataLength];

                memoryStream.Position = 0;
                using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
                {
                    gZipStream.Read(buffer, 0, buffer.Length);
                }

                return Encoding.UTF8.GetString(buffer);
            }
        }
    }
}

Does the Java &= operator apply & or &&?

It's the last one:

a = a & b;

Random numbers with Math.random() in Java

A better approach is:

int x = rand.nextInt(max - min + 1) + min;

Your formula generates numbers between min and min + max.

Random random = new Random(1234567);
int min = 5;
int max = 20;
while (true) {
    int x = (int)(Math.random() * max) + min;
    System.out.println(x);
    if (x < min || x >= max) { break; }
}       

Result:

10
16
13
21 // Oops!!

See it online here: ideone

2D character array initialization in C

I think what you originally meant to do was to make an array only of characters, not of pointers:

char options[2][100];

options[0][0]='t';
options[0][1]='e';
options[0][2]='s';
options[0][3]='t';
options[0][4]='1';
options[0][5]='\0';  /* NUL termination of C string */

/* A standard C library function which copies strings. */
strcpy(options[1], "test2");

The code above shows two distinct methods of setting the character values in memory you have set aside to contain characters.

How to convert UTC timestamp to device local time in android

This may help some one with same requirement

private String getDate(long time){
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm a");
        String dateString = formatter.format(new Date(time));
        String date = ""+dateString;
        return date;
    }

Load JSON text into class object in c#

I recommend you to use JSON.NET. it is an open source library to serialize and deserialize your c# objects into json and Json objects into .net objects ...

Serialization Example:

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string json = JsonConvert.SerializeObject(product);
//{
//  "Name": "Apple",
//  "Expiry": new Date(1230422400000),
//  "Price": 3.99,
//  "Sizes": [
//    "Small",
//    "Medium",
//    "Large"
//  ]
//}

Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);

Performance Comparison To Other JSON serializiation Techniques enter image description here

Understanding Matlab FFT example

1) Why does the x-axis (frequency) end at 500? How do I know that there aren't more frequencies or are they just ignored?

It ends at 500Hz because that is the Nyquist frequency of the signal when sampled at 1000Hz. Look at this line in the Mathworks example:

f = Fs/2*linspace(0,1,NFFT/2+1);

The frequency axis of the second plot goes from 0 to Fs/2, or half the sampling frequency. The Nyquist frequency is always half the sampling frequency, because above that, aliasing occurs: Aliasing illustration

The signal would "fold" back on itself, and appear to be some frequency at or below 500Hz.

2) How do I know the frequencies are between 0 and 500? Shouldn't the FFT tell me, in which limits the frequencies are?

Due to "folding" described above (the Nyquist frequency is also commonly known as the "folding frequency"), it is physically impossible for frequencies above 500Hz to appear in the FFT; higher frequencies will "fold" back and appear as lower frequencies.

Does the FFT only return the amplitude value without the frequency?

Yes, the MATLAB FFT function only returns one vector of amplitudes. However, they map to the frequency points you pass to it.

Let me know what needs clarification so I can help you further.

What's the best visual merge tool for Git?

If you are just looking for a diff tool beyond compare is pretty nice: http://www.scootersoftware.com/moreinfo.php

LaTeX: Prevent line break in a span of text

Use \nolinebreak

\nolinebreak[number]

The \nolinebreak command prevents LaTeX from breaking the current line at the point of the command. With the optional argument, number, you can convert the \nolinebreak command from a demand to a request. The number must be a number from 0 to 4. The higher the number, the more insistent the request is.

Source: http://www.personal.ceu.hu/tex/breaking.htm#nolinebreak

Put content in HttpResponseMessage object?

No doubt that you are correct Florin. I was working on this project, and found that this piece of code:

product = await response.Content.ReadAsAsync<Product>();

Could be replaced with:

response.Content = new StringContent(string product);

How to print all key and values from HashMap in Android?

HashMap <Integer,Integer> hm = new HashMap<Integer,Integer>();

Set<Integer> keys = hm.keySet();  //get all keys
for(Integer i: keys)
{
    System.out.println(hm.get(i));
}

Jenkins "Console Output" log location in filesystem

Jenkins stores the console log on master. If you want programmatic access to the log, and you are running on master, you can access the log that Jenkins already has, without copying it to the artifacts or having to GET the http job URL.

From http://javadoc.jenkins.io/archive/jenkins-1.651/hudson/model/Run.html#getLogFile(), this returns the File object for the console output (in the jenkins file system, this is the "log" file in the build output directory).

In my case, we use a chained (child) job to do parsing and analysis on a parent job's build.

When using a groovy script run in Jenkins, you get an object named "build" for the run. We use this to get the http://javadoc.jenkins.io/archive/jenkins-1.651/hudson/model/Build.html for the upstream job, then call this job's .getLogFile().

Added bonus; since it's just a File object, we call .getParent() to get the folder where Jenkins stores build collateral (like test xmls, environment variables, and other things that may not be explicitly exposed through the artifacts) which we can also parse.

Double added bonus; we also use matrix jobs. This sometimes makes inferring the file path on the system a pain. .getLogFile().getParent() takes away all the pain.

Maximum call stack size exceeded on npm install

In case none of these answer work for you, it may be because the terminal you're using isn't the right one/ your node_modules is used by another part of your computer.

In my case I kept juggling between this error (maximum call stack size exceeded) and the access error event when I did a sudo npm i.

The fix was to close my IDE (which was WebStorm), run npm i in a basic terminal, and that was it.

T-SQL: Deleting all duplicate rows but keeping one

Here's my twist on it, with a runnable example. Note this will only work in the situation where Id is unique, and you have duplicate values in other columns.

DECLARE @SampleData AS TABLE (Id int, Duplicate varchar(20))

INSERT INTO @SampleData
SELECT 1, 'ABC' UNION ALL
SELECT 2, 'ABC' UNION ALL
SELECT 3, 'LMN' UNION ALL
SELECT 4, 'XYZ' UNION ALL
SELECT 5, 'XYZ'

DELETE FROM @SampleData WHERE Id IN (
    SELECT Id FROM (
        SELECT 
            Id
            ,ROW_NUMBER() OVER (PARTITION BY [Duplicate] ORDER BY Id) AS [ItemNumber]
            -- Change the partition columns to include the ones that make the row distinct
        FROM 
            @SampleData
    ) a WHERE ItemNumber > 1 -- Keep only the first unique item
)

SELECT * FROM @SampleData

And the results:

Id          Duplicate
----------- ---------
1           ABC
3           LMN
4           XYZ

Not sure why that's what I thought of first... definitely not the simplest way to go but it works.

How to get the first and last date of the current year?

Here's a fairly simple way;

SELECT DATEFROMPARTS(YEAR(GETDATE()), 1, 1) AS 'First Day of Current Year';
SELECT DATEFROMPARTS(YEAR(GETDATE()), 12, 31) AS 'End of Current Year';

It's not sexy, but it works.

How to search a string in String array

At first shot, I could come up with something like this (but it's pseudo code and assuming you cannot use any .NET built-in libaries). Might require a bit of tweaking and re-thinking, but should be good enough for a head-start, maybe?

int findString(String var, String[] stringArray, int currentIndex, int stringMaxIndex)
    {
    if currentIndex > stringMaxIndex 
       return (-stringMaxIndex-1);
    else if var==arr[currentIndex] //or use any string comparison op or function
       return 0;
    else 
       return findString(var, stringArray, currentIndex++, stringMaxIndex) + 1 ;
    }



    //calling code
    int index = findString(var, arr, 0, getMaxIndex(arr));

    if index == -1 printOnScreen("Not found");
    else printOnScreen("Found on index: " + index);

VBA collection: list of keys

An alternative solution is to store the keys in a separate Collection:

'Initialise these somewhere.
Dim Keys As Collection, Values As Collection

'Add types for K and V as necessary.
Sub Add(K, V) 
Keys.Add K
Values.Add V, K
End Sub

You can maintain a separate sort order for the keys and the values, which can be useful sometimes.

How can I monitor the thread count of a process on linux?

try

ps huH p <PID_OF_U_PROCESS> | wc -l

or htop

Does Python SciPy need BLAS?

Try using

sudo apt-get install python3-scipy

How to configure the web.config to allow requests of any length

Add the following to your web.config:

<system.webServer>
  <security>
    <requestFiltering>
      <requestLimits maxQueryString="32768"/>
    </requestFiltering>
  </security>
</system.webServer>

See:

http://www.iis.net/ConfigReference/system.webServer/security/requestFiltering/requestLimits

Updated to reflect comments.

requestLimits Element for requestFiltering [IIS Settings Schema]

You may have to add the following in your web.config as well

<system.web>
    <httpRuntime maxQueryStringLength="32768" maxUrlLength="65536"/>
</system.web>

See: httpRuntime Element (ASP.NET Settings Schema)

Of course the numbers (32768 and 65536) in the config settings above are just examples. You don't have to use those exact values.

Using Transactions or SaveChanges(false) and AcceptAllChanges()?

Because some database can throw an exception at dbContextTransaction.Commit() so better this:

using (var context = new BloggingContext()) 
{ 
  using (var dbContextTransaction = context.Database.BeginTransaction()) 
  { 
    try 
    { 
      context.Database.ExecuteSqlCommand( 
          @"UPDATE Blogs SET Rating = 5" + 
              " WHERE Name LIKE '%Entity Framework%'" 
          ); 

      var query = context.Posts.Where(p => p.Blog.Rating >= 5); 
      foreach (var post in query) 
      { 
          post.Title += "[Cool Blog]"; 
      } 

      context.SaveChanges(false); 

      dbContextTransaction.Commit(); 

      context.AcceptAllChanges();
    } 
    catch (Exception) 
    { 
      dbContextTransaction.Rollback(); 
    } 
  } 
} 

How to add an image to an svg container using D3.js

My team also wanted to add images inside d3-drawn circles, and came up with the following (fiddle):

index.html:

<!doctype html>
<html>
<head>
  <link rel="stylesheet" type="text/css" href="timeline.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.js"></script>
  <script src="https://code.jquery.com/jquery-2.2.4.js"
    integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI="
    crossorigin="anonymous"></script>
  <script src="./timeline.js"></script>
</head>
  <body>
    <div class="timeline"></div>
  </body>
</html>

timeline.css:

.axis path,
.axis line,
.tick line,
.line {
  fill: none;
  stroke: #000000;
  stroke-width: 1px;
}

timeline.js:

// container target
var elem = ".timeline";

var props = {
  width: 1000,
  height: 600,
  class: "timeline-point",

  // margins
  marginTop: 100,
  marginRight: 40,
  marginBottom: 100,
  marginLeft: 60,

  // data inputs
  data: [
    {
      x: 10,
      y: 20,
      key: "a",
      image: "https://unsplash.it/300/300",
      id: "a"
    },
    {
      x: 20,
      y: 10,
      key: "a",
      image: "https://unsplash.it/300/300",
      id: "b"
    },
    {
      x: 60,
      y: 30,
      key: "a",
      image: "https://unsplash.it/300/300",
      id: "c"
    },
    {
      x: 40,
      y: 30,
      key: "a",
      image: "https://unsplash.it/300/300",
      id: "d"
    },
    {
      x: 50,
      y: 70,
      key: "a",
      image: "https://unsplash.it/300/300",
      id: "e"
    },
    {
      x: 30,
      y: 50,
      key: "a",
      image: "https://unsplash.it/300/300",
      id: "f"
    },
    {
      x: 50,
      y: 60,
      key: "a",
      image: "https://unsplash.it/300/300",
      id: "g"
    }
  ],

  // y label
  yLabel: "Y label",
  yLabelLength: 50,

  // axis ticks
  xTicks: 10,
  yTicks: 10

}

// component start
var Timeline = {};

/***
*
* Create the svg canvas on which the chart will be rendered
*
***/

Timeline.create = function(elem, props) {

  // build the chart foundation
  var svg = d3.select(elem).append('svg')
      .attr('width', props.width)
      .attr('height', props.height);

  var g = svg.append('g')
      .attr('class', 'point-container')
      .attr("transform",
              "translate(" + props.marginLeft + "," + props.marginTop + ")");

  var g = svg.append('g')
      .attr('class', 'line-container')
      .attr("transform", 
              "translate(" + props.marginLeft + "," + props.marginTop + ")");

  var xAxis = g.append('g')
    .attr("class", "x axis")
    .attr("transform", "translate(0," + (props.height - props.marginTop - props.marginBottom) + ")");

  var yAxis = g.append('g')
    .attr("class", "y axis");

  svg.append("text")
    .attr("class", "y label")
    .attr("text-anchor", "end")
    .attr("y", 1)
    .attr("x", 0 - ((props.height - props.yLabelLength)/2) )
    .attr("dy", ".75em")
    .attr("transform", "rotate(-90)")
    .text(props.yLabel);

  // add placeholders for the axes
  this.update(elem, props);
};

/***
*
* Update the svg scales and lines given new data
*
***/

Timeline.update = function(elem, props) {
  var self = this;
  var domain = self.getDomain(props);
  var scales = self.scales(elem, props, domain);

  self.drawPoints(elem, props, scales);
};


/***
*
* Use the range of values in the x,y attributes
* of the incoming data to identify the plot domain
*
***/

Timeline.getDomain = function(props) {
  var domain = {};
  domain.x = props.xDomain || d3.extent(props.data, function(d) { return d.x; });
  domain.y = props.yDomain || d3.extent(props.data, function(d) { return d.y; });
  return domain;
};


/***
*
* Compute the chart scales
*
***/

Timeline.scales = function(elem, props, domain) {

  if (!domain) {
    return null;
  }

  var width = props.width - props.marginRight - props.marginLeft;
  var height = props.height - props.marginTop - props.marginBottom;

  var x = d3.scale.linear()
    .range([0, width])
    .domain(domain.x);

  var y = d3.scale.linear()
    .range([height, 0])
    .domain(domain.y);

  return {x: x, y: y};
};


/***
*
* Create the chart axes
*
***/

Timeline.axes = function(props, scales) {

  var xAxis = d3.svg.axis()
    .scale(scales.x)
    .orient("bottom")
    .ticks(props.xTicks)
    .tickFormat(d3.format("d"));

  var yAxis = d3.svg.axis()
    .scale(scales.y)
    .orient("left")
    .ticks(props.yTicks);

  return {
    xAxis: xAxis,
    yAxis: yAxis
  }
};


/***
*
* Use the general update pattern to draw the points
*
***/

Timeline.drawPoints = function(elem, props, scales, prevScales, dispatcher) {
  var g = d3.select(elem).selectAll('.point-container');
  var color = d3.scale.category10();

  // add images
  var image = g.selectAll('.image')
    .data(props.data)

  image.enter()
    .append("pattern")
    .attr("id", function(d) {return d.id})
    .attr("class", "svg-image")
    .attr("x", "0")
    .attr("y", "0")
    .attr("height", "70px")
    .attr("width", "70px")
    .append("image")
      .attr("x", "0")
      .attr("y", "0")
      .attr("height", "70px")
      .attr("width", "70px")
      .attr("xlink:href", function(d) {return d.image})

  var point = g.selectAll('.point')
    .data(props.data);

  // enter
  point.enter()
    .append("circle")
      .attr("class", "point")
      .on('mouseover', function(d) {
        d3.select(elem).selectAll(".point").classed("active", false);
        d3.select(this).classed("active", true);
        if (props.onMouseover) {
          props.onMouseover(d)
        };
      })
      .on('mouseout', function(d) {
        if (props.onMouseout) {
          props.onMouseout(d)
        };
      })

  // enter and update
  point.transition()
    .duration(1000)
    .attr("cx", function(d) {
      return scales.x(d.x); 
    })
    .attr("cy", function(d) { 
      return scales.y(d.y); 
    })
    .attr("r", 30)
    .style("stroke", function(d) {
      if (props.pointStroke) {
        return d.color = props.pointStroke;
      } else {
        return d.color = color(d.key);
      }
    })
    .style("fill", function(d) {
      if (d.image) {
        return ("url(#" + d.id + ")");
      }

      if (props.pointFill) {
        return d.color = props.pointFill;
      } else {
        return d.color = color(d.key);
      }
    });

  // exit
  point.exit()
    .remove();

  // update the axes
  var axes = this.axes(props, scales);
  d3.select(elem).selectAll('g.x.axis')
    .transition()
    .duration(1000)
    .call(axes.xAxis);

  d3.select(elem).selectAll('g.y.axis')
    .transition()
    .duration(1000)
    .call(axes.yAxis);
};


$(document).ready(function() {
  Timeline.create(elem, props);
})

CMake error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found

Make sure you have selected the correct version of Visual Studio. This is trickier than it seems because Visual Studio 2015 is actually Visual Studio 14, and similarly Visual Studio 2012 is Visual Studio 11. I had incorrectly selected Visual Studio 15 which is actually Visual Studio 2017, when I had 2015 installed.

How can I check if an array contains a specific value in php?

Use the in_array() function.

$array = array('kitchen', 'bedroom', 'living_room', 'dining_room');

if (in_array('kitchen', $array)) {
    echo 'this array contains kitchen';
}

What is the equivalent of Select Case in Access SQL?

You can use IIF for a similar result.

Note that you can nest the IIF statements to handle multiple cases. There is an example here: http://forums.devshed.com/database-management-46/query-ms-access-iif-statement-multiple-conditions-358130.html

SELECT IIf([Combinaison] = "Mike", 12, IIf([Combinaison] = "Steve", 13)) As Answer 
FROM MyTable;

Anaconda version with Python 3.5

Per this announcement, Anaconda upgraded to Python 3.6 starting with version 4.3, so... you probably want the 4.2.0 package from the installer archive.

What causes signal 'SIGILL'?

It could be some un-initialized function pointer, in particular if you have corrupted memory (then the bogus vtable of C++ bad pointers to invalid objects might give that).

BTW gdb watchpoints & tracepoints, and also valgrind might be useful (if available) to debug such issues. Or some address sanitizer.

Run multiple python scripts concurrently

I am working in Windows 7 with Python IDLE. I have two programs,

# progA
while True:
    m = input('progA is running ')
    print (m)

and

# progB
while True:
    m = input('progB is running ')
    print (m)

I open up IDLE and then open file progA.py. I run the program, and when prompted for input I enter "b" + <Enter> and then "c" + <Enter>

I am looking at this window:

Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 
= RESTART: C:\Users\Mike\AppData\Local\Programs\Python\Python36-32\progA.py =
progA is running b
b
progA is running c
c
progA is running 

Next, I go back to Windows Start and open up IDLE again, this time opening file progB.py. I run the program, and when prompted for input I enter "x" + <Enter> and then "y" + <Enter>

I am looking at this window:

Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 
= RESTART: C:\Users\Mike\AppData\Local\Programs\Python\Python36-32\progB.py =
progB is running x
x
progB is running y
y
progB is running 

Now two IDLE Python 3.6.3 Shell programs are running at the same time, one shell running progA while the other one is running progB.

How to change font-color for disabled input?

Replace disabled with readonly="readonly". I think it is the same function.

<input type="text" class="details-dialog" readonly="readonly" style="color: ur color;">

Normalization in DOM parsing with java - how does it work?

The rest of the sentence is:

where only structure (e.g., elements, comments, processing instructions, CDATA sections, and entity references) separates Text nodes, i.e., there are neither adjacent Text nodes nor empty Text nodes.

This basically means that the following XML element

<foo>hello 
wor
ld</foo>

could be represented like this in a denormalized node:

Element foo
    Text node: ""
    Text node: "Hello "
    Text node: "wor"
    Text node: "ld"

When normalized, the node will look like this

Element foo
    Text node: "Hello world"

And the same goes for attributes: <foo bar="Hello world"/>, comments, etc.

Why do I get "warning longer object length is not a multiple of shorter object length"?

I had a similar problem but it had to do with the structure and class of the object. I would check how dih_y2$MemberID is formatted.

Using Python, how can I access a shared folder on windows network?

I had the same issue as OP but none of the current answers solved my issue so to add a slightly different answer that did work for me:

Running Python 3.6.5 on a Windows Machine, I used the format

r"\DriveName\then\file\path\txt.md"

so the combination of double backslashes from reading @Johnsyweb UNC link and adding the r in front as recommended solved my similar to OP's issue.

Should I test private methods or only public ones?

We test private methods by inference, by which I mean we look for total class test coverage of at least 95%, but only have our tests call into public or internal methods. To get the coverage, we need to make multiple calls to the public/internals based on the different scenarios that may occur. This makes our tests more intentful around the purpose of the code they are testing.

Trumpi's answer to the post you linked is the best one.

In Chart.js set chart title, name of x axis and y axis?

just use this:

<script>
  var ctx = document.getElementById("myChart").getContext('2d');
  var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: ["1","2","3","4","5","6","7","8","9","10","11",],
      datasets: [{
        label: 'YOUR LABEL',
        backgroundColor: [
          "#566573",
          "#99a3a4",
          "#dc7633",
          "#f5b041",
          "#f7dc6f",
          "#82e0aa",
          "#73c6b6",
          "#5dade2",
          "#a569bd",
          "#ec7063",
          "#a5754a"
        ],
        data: [12, 19, 3, 17, 28, 24, 7, 2,4,14,6],            
      },]
    },
    //HERE COMES THE AXIS Y LABEL
    options : {
      scales: {
        yAxes: [{
          scaleLabel: {
            display: true,
            labelString: 'probability'
          }
        }]
      }
    }
  });
</script>

How can I write data in YAML format in a file?

import yaml

data = dict(
    A = 'a',
    B = dict(
        C = 'c',
        D = 'd',
        E = 'e',
    )
)

with open('data.yml', 'w') as outfile:
    yaml.dump(data, outfile, default_flow_style=False)

The default_flow_style=False parameter is necessary to produce the format you want (flow style), otherwise for nested collections it produces block style:

A: a
B: {C: c, D: d, E: e}

Is there a /dev/null on Windows?

You have to use start and $NUL for this in Windows PowerShell:

Type in this command assuming mySum is the name of your application and 5 10 are command line arguments you are sending.

start .\mySum  5 10 > $NUL 2>&1

The start command will start a detached process, a similar effect to &. The /B option prevents start from opening a new terminal window if the program you are running is a console application. and NUL is Windows' equivalent of /dev/null. The 2>&1 at the end will redirect stderr to stdout, which will all go to NUL.

Mix Razor and Javascript code

A non conventional method to separate javascript from the view, but still use razor in it is to make a Scripts.cshtml file and place your mixed javascript/razor there.

Index.cshtml

<div id="Result">
</div>

<button id="btnLoad">Click me</button>

@section scripts
{
    @Html.Partial("Scripts")
}

Scripts.cshtml

<script type="text/javascript">
    var url = "@Url.Action("Index", "Home")";

    $(document).ready(function() {
        $("#btnLoad").click(function() {
            $.ajax({
                type: "POST",
                url: url ,
                data: {someParameter: "some value"},
                contentType: "application/json; charset=utf-8",
                dataType: "json",

                success: function(msg) {
                    $("#Result").text(msg.d);
                }
            });
        });
    });
</script>

Move SQL Server 2008 database files to a new folder location

You can use Detach/Attach Option in SQL Server Management Studio.

Check this: Move a Database Using Detach and Attach

Correlation heatmap

Another alternative is to use the heatmap function in seaborn to plot the covariance. This example uses the Auto data set from the ISLR package in R (the same as in the example you showed).

import pandas.rpy.common as com
import seaborn as sns
%matplotlib inline

# load the R package ISLR
infert = com.importr("ISLR")

# load the Auto dataset
auto_df = com.load_data('Auto')

# calculate the correlation matrix
corr = auto_df.corr()

# plot the heatmap
sns.heatmap(corr, 
        xticklabels=corr.columns,
        yticklabels=corr.columns)

enter image description here

If you wanted to be even more fancy, you can use Pandas Style, for example:

cmap = cmap=sns.diverging_palette(5, 250, as_cmap=True)

def magnify():
    return [dict(selector="th",
                 props=[("font-size", "7pt")]),
            dict(selector="td",
                 props=[('padding', "0em 0em")]),
            dict(selector="th:hover",
                 props=[("font-size", "12pt")]),
            dict(selector="tr:hover td:hover",
                 props=[('max-width', '200px'),
                        ('font-size', '12pt')])
]

corr.style.background_gradient(cmap, axis=1)\
    .set_properties(**{'max-width': '80px', 'font-size': '10pt'})\
    .set_caption("Hover to magify")\
    .set_precision(2)\
    .set_table_styles(magnify())

enter image description here

What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, pipenv, etc?

UPDATE 20200825:

Added below "Conclusion" paragraph

I've went down the pipenv rabbit hole (it's a deep and dark hole indeed...) and since the last answer is over 2 years ago, felt it was useful to update the discussion with the latest developments on the Python virtual envelopes topic I've found.

DISCLAIMER:

This answer is NOT about continuing the raging debate about the merits of pipenv versus venv as envelope solutions- I make no endorsement of either. It's about PyPA endorsing conflicting standards and how future development of virtualenv promises to negate making an either/or choice between them at all. I focused on these two tools precisely because they are the anointed ones by PyPA.

venv

As the OP notes, venv is a tool for virtualizing environments. NOT a third party solution, but native tool. PyPA endorses venv for creating VIRTUAL ENVELOPES: "Changed in version 3.5: The use of venv is now recommended for creating virtual environments".

pipenv

pipenv- like venv - can be used to create virtual envelopes but additionally rolls-in package management and vulnerability checking functionality. Instead of using requirements.txt, pipenv delivers package management via Pipfile. As PyPA endorses pipenv for PACKAGE MANAGEMENT, that would seem to imply pipfile is to supplant requirements.txt.

HOWEVER: pipenv uses virtualenv as its tool for creating virtual envelopes, NOT venv which is endorsed by PyPA as the go-to tool for creating virtual envelopes.

Conflicting Standards:

So if settling on a virtual envelope solution wasn't difficult enough, we now have PyPA endorsing two different tools which use different virtual envelope solutions. The raging Github debate on venv vs virtualenv which highlights this conflict can be found here.

Conflict Resolution:

The Github debate referenced in above link has steered virtualenv development in the direction of accommodating venv in future releases:

prefer built-in venv: if the target python has venv we'll create the environment using that (and then perform subsequent operations on that to facilitate other guarantees we offer)

Conclusion:

So it looks like there will be some future convergence between the two rival virtual envelope solutions, but as of now pipenv- which uses virtualenv - varies materially from venv.

Given the problems pipenv solves and the fact that PyPA has given its blessing, it appears to have a bright future. And if virtualenv delivers on its proposed development objectives, choosing a virtual envelope solution should no longer be a case of either pipenv OR venv.

Update 20200825:

An oft repeated criticism of Pipenv I saw when producing this analysis was that it was not actively maintained. Indeed, what's the point of using a solution whose future could be seen questionable due to lack of continuous development? After a dry spell of about 18 months, Pipenv is once again being actively developed. Indeed, large and material updates have since been released.

Simple way to convert datarow array to datatable

Simple way is:

// dtData is DataTable that contain data
DataTable dt = dtData.Select("Condition=1").CopyToDataTable();

// or existing typed DataTable dt
dt.Merge(dtData.Select("Condition=1").CopyToDataTable());

How can I format date by locale in Java?

Joda-Time

Using the Joda-Time 2.4 library. The DateTimeFormat class is a factory of DateTimeFormatter formatters. That class offers a forStyle method to access formatters appropriate to a Locale.

DateTimeFormatter formatter = DateTimeFormat.forStyle( "MM" ).withLocale( Java.util.Locale.CANADA_FRENCH );
String output = formatter.print( DateTime.now( DateTimeZone.forID( "America/Montreal" ) ) );

The argument with two letters specifies a format for the date portion and the time portion. Specify a character of 'S' for short style, 'M' for medium, 'L' for long, and 'F' for full. A date or time may be ommitted by specifying a style character '-' HYPHEN.

Note that we specified both a Locale and a time zone. Some people confuse the two.

  • A time zone is an offset from UTC and a set of rules for Daylight Saving Time and other anomalies along with their historical changes.
  • A Locale is a human language such as Français, plus a country code such as Canada that represents cultural practices including formatting of date-time strings.

We need all those pieces to properly generate a string representation of a date-time value.

How to parse a CSV file using PHP

Just use the function for parsing a CSV file

http://php.net/manual/en/function.fgetcsv.php

$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
  while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $num = count($data);
    echo "<p> $num fields in line $row: <br /></p>\n";
    $row++;
    for ($c=0; $c < $num; $c++) {
        echo $data[$c] . "<br />\n";
    }
  }
  fclose($handle);
}

Apply function to pandas groupby

Try:

g = pd.DataFrame(['A','B','A','C','D','D','E'])

# Group by the contents of column 0 
gg = g.groupby(0)  

# Create a DataFrame with the counts of each letter
histo = gg.apply(lambda x: x.count())

# Add a new column that is the count / total number of elements    
histo[1] = histo.astype(np.float)/len(g) 

print histo

Output:

   0         1
0             
A  2  0.285714
B  1  0.142857
C  1  0.142857
D  2  0.285714
E  1  0.142857

Styling Google Maps InfoWindow

I used the following code to apply some external CSS:

boxText = document.createElement("html");
boxText.innerHTML = "<head><link rel='stylesheet' href='style.css'/></head><body>[some html]<body>";

infowindow.setContent(boxText);
infowindow.open(map, marker);

Passing string parameter in JavaScript function

The question has been answered, but for your future coding reference you might like to consider this.

In your HTML, add the name as an attribute to the button and remove the onclick reference.

<button id="button" data-name="Mathew" type="button">click</button>

In your JavaScript, grab the button using its ID, assign the function to the button's click event, and use the function to display the button's data-name attribute.

var button = document.getElementById('button');

button.onclick = myfunction;

function myfunction() {
  var name = this.getAttribute('data-name');
  alert(name);
}

DEMO

Parsing JSON in Excel VBA

Lots of good answers here - just chipping in my own.

I had a requirement to parse a very specific JSON string, representing the results of making a web-API call. The JSON described a list of objects, and looked something like this:

[
   {
     "property1": "foo",
     "property2": "bar",
     "timeOfDay": "2019-09-30T00:00:00",
     "numberOfHits": 98,
     "isSpecial": false,
     "comment": "just to be awkward, this contains a comma"
   },
   {
     "property1": "fool",
     "property2": "barrel",
     "timeOfDay": "2019-10-31T00:00:00",
     "numberOfHits": 11,
     "isSpecial": false,
     "comment": null
   },
   ...
]

There are a few things to note about this:

  1. The JSON should always describe a list (even if empty), which should only contain objects.
  2. The objects in the list should only contain properties with simple types (string / date / number / boolean or null).
  3. The value of a property may contain a comma - which makes parsing the JSON somewhat harder - but may not contain any quotes (because I'm too lazy to deal with that).

The ParseListOfObjects function in the code below takes the JSON string as input, and returns a Collection representing the items in the list. Each item is represented as a Dictionary, where the keys of the dictionary correspond to the names of the object's properties. The values are automatically converted to the appropriate type (String, Date, Double, Boolean - or Empty if the value is null).

Your VBA project will need a reference to the Microsoft Scripting Runtime library to use the Dictionary object - though it would not be difficult to remove this dependency if you use a different way of encoding the results.

Here's my JSON.bas:

Option Explicit

' NOTE: a fully-featured JSON parser in VBA would be a beast.
' This simple parser only supports VERY simple JSON (which is all we need).
' Specifically, it supports JSON comprising a list of objects, each of which has only simple properties.

Private Const strSTART_OF_LIST As String = "["
Private Const strEND_OF_LIST As String = "]"

Private Const strLIST_DELIMITER As String = ","

Private Const strSTART_OF_OBJECT As String = "{"
Private Const strEND_OF_OBJECT As String = "}"

Private Const strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR As String = ":"

Private Const strQUOTE As String = """"

Private Const strNULL_VALUE As String = "null"
Private Const strTRUE_VALUE As String = "true"
Private Const strFALSE_VALUE As String = "false"


Public Function ParseListOfObjects(ByVal strJson As String) As Collection

    ' Takes a JSON string that represents a list of objects (where each object has only simple value properties), and
    ' returns a collection of dictionary objects, where the keys and values of each dictionary represent the names and
    ' values of the JSON object properties.

    Set ParseListOfObjects = New Collection

    Dim strList As String: strList = Trim(strJson)

    ' Check we have a list
    If Left(strList, Len(strSTART_OF_LIST)) <> strSTART_OF_LIST _
    Or Right(strList, Len(strEND_OF_LIST)) <> strEND_OF_LIST Then
        Err.Raise vbObjectError, Description:="The provided JSON does not appear to be a list (it does not start with '" & strSTART_OF_LIST & "' and end with '" & strEND_OF_LIST & "')"
    End If

    ' Get the list item text (between the [ and ])
    Dim strBody As String: strBody = Trim(Mid(strList, 1 + Len(strSTART_OF_LIST), Len(strList) - Len(strSTART_OF_LIST) - Len(strEND_OF_LIST)))

    If strBody = "" Then
        Exit Function
    End If

    ' Check we have a list of objects
    If Left(strBody, Len(strSTART_OF_OBJECT)) <> strSTART_OF_OBJECT Then
        Err.Raise vbObjectError, Description:="The provided JSON does not appear to be a list of objects (the content of the list does not start with '" & strSTART_OF_OBJECT & "')"
    End If

    ' We now have something like:
    '    {"property":"value", "property":"value"}, {"property":"value", "property":"value"}, ...
    ' so we can't just split on a comma to get the various items (because the items themselves have commas in them).
    ' HOWEVER, since we know we're dealing with very simple JSON that has no nested objects, we can split on "}," because
    ' that should only appear between items. That'll mean that all but the last item will be missing it's closing brace.
    Dim astrItems() As String: astrItems = Split(strBody, strEND_OF_OBJECT & strLIST_DELIMITER)

    Dim ixItem As Long
    For ixItem = LBound(astrItems) To UBound(astrItems)

        Dim strItem As String: strItem = Trim(astrItems(ixItem))

        If Left(strItem, Len(strSTART_OF_OBJECT)) <> strSTART_OF_OBJECT Then
            Err.Raise vbObjectError, Description:="Mal-formed list item (does not start with '" & strSTART_OF_OBJECT & "')"
        End If

        ' Only the last item will have a closing brace (see comment above)
        Dim bIsLastItem As Boolean: bIsLastItem = ixItem = UBound(astrItems)

        If bIsLastItem Then
            If Right(strItem, Len(strEND_OF_OBJECT)) <> strEND_OF_OBJECT Then
                Err.Raise vbObjectError, Description:="Mal-formed list item (does not end with '" & strEND_OF_OBJECT & "')"
            End If
        End If

        Dim strContent: strContent = Mid(strItem, 1 + Len(strSTART_OF_OBJECT), Len(strItem) - Len(strSTART_OF_OBJECT) - IIf(bIsLastItem, Len(strEND_OF_OBJECT), 0))

        ParseListOfObjects.Add ParseObjectContent(strContent)

    Next ixItem

End Function

Private Function ParseObjectContent(ByVal strContent As String) As Scripting.Dictionary

    Set ParseObjectContent = New Scripting.Dictionary
    ParseObjectContent.CompareMode = TextCompare

    ' The object content will look something like:
    '    "property":"value", "property":"value", ...
    ' ... although the value may not be in quotes, since numbers are not quoted.
    ' We can't assume that the property value won't contain a comma, so we can't just split the
    ' string on the commas, but it's reasonably safe to assume that the value won't contain further quotes
    ' (and we're already assuming no sub-structure).
    ' We'll need to scan for commas while taking quoted strings into account.

    Dim ixPos As Long: ixPos = 1
    Do While ixPos <= Len(strContent)

        Dim strRemainder As String

        ' Find the opening quote for the name (names should always be quoted)
        Dim ixOpeningQuote As Long: ixOpeningQuote = InStr(ixPos, strContent, strQUOTE)

        If ixOpeningQuote <= 0 Then
            ' The only valid reason for not finding a quote is if we're at the end (though white space is permitted)
            strRemainder = Trim(Mid(strContent, ixPos))
            If Len(strRemainder) = 0 Then
                Exit Do
            End If
            Err.Raise vbObjectError, Description:="Mal-formed object (the object name does not start with a quote)"
        End If

        ' Now find the closing quote for the name, which we assume is the very next quote
        Dim ixClosingQuote As Long: ixClosingQuote = InStr(ixOpeningQuote + 1, strContent, strQUOTE)
        If ixClosingQuote <= 0 Then
            Err.Raise vbObjectError, Description:="Mal-formed object (the object name does not end with a quote)"
        End If

        If ixClosingQuote - ixOpeningQuote - Len(strQUOTE) = 0 Then
            Err.Raise vbObjectError, Description:="Mal-formed object (the object name is blank)"
        End If

        Dim strName: strName = Mid(strContent, ixOpeningQuote + Len(strQUOTE), ixClosingQuote - ixOpeningQuote - Len(strQUOTE))

        ' The next thing after the quote should be the colon

        Dim ixNameValueSeparator As Long: ixNameValueSeparator = InStr(ixClosingQuote + Len(strQUOTE), strContent, strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR)

        If ixNameValueSeparator <= 0 Then
            Err.Raise vbObjectError, Description:="Mal-formed object (missing '" & strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR & "')"
        End If

        ' Check that there was nothing between the closing quote and the colon

        strRemainder = Trim(Mid(strContent, ixClosingQuote + Len(strQUOTE), ixNameValueSeparator - ixClosingQuote - Len(strQUOTE)))
        If Len(strRemainder) > 0 Then
            Err.Raise vbObjectError, Description:="Mal-formed object (unexpected content between name and '" & strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR & "')"
        End If

        ' What comes after the colon is the value, which may or may not be quoted (e.g. numbers are not quoted).
        ' If the very next thing we see is a quote, then it's a quoted value, and we need to find the matching
        ' closing quote while ignoring any commas inside the quoted value.
        ' If the next thing we see is NOT a quote, then it must be an unquoted value, and we can scan directly
        ' for the next comma.
        ' Either way, we're looking for a quote or a comma, whichever comes first (or neither, in which case we
        ' have the last - unquoted - value).

        ixOpeningQuote = InStr(ixNameValueSeparator + Len(strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR), strContent, strQUOTE)
        Dim ixPropertySeparator As Long: ixPropertySeparator = InStr(ixNameValueSeparator + Len(strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR), strContent, strLIST_DELIMITER)

        If ixOpeningQuote > 0 And ixPropertySeparator > 0 Then
            ' Only use whichever came first
            If ixOpeningQuote < ixPropertySeparator Then
                ixPropertySeparator = 0
            Else
                ixOpeningQuote = 0
            End If
        End If

        Dim strValue As String
        Dim vValue As Variant

        If ixOpeningQuote <= 0 Then ' it's not a quoted value

            If ixPropertySeparator <= 0 Then ' there's no next value; this is the last one
                strValue = Trim(Mid(strContent, ixNameValueSeparator + Len(strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR)))
                ixPos = Len(strContent) + 1
            Else ' this is not the last value
                strValue = Trim(Mid(strContent, ixNameValueSeparator + Len(strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR), ixPropertySeparator - ixNameValueSeparator - Len(strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR)))
                ixPos = ixPropertySeparator + Len(strLIST_DELIMITER)
            End If

            vValue = ParseUnquotedValue(strValue)

        Else ' It is a quoted value

            ' Find the corresponding closing quote, which should be the very next one

            ixClosingQuote = InStr(ixOpeningQuote + Len(strQUOTE), strContent, strQUOTE)

            If ixClosingQuote <= 0 Then
                Err.Raise vbObjectError, Description:="Mal-formed object (the value does not end with a quote)"
            End If

            strValue = Mid(strContent, ixOpeningQuote + Len(strQUOTE), ixClosingQuote - ixOpeningQuote - Len(strQUOTE))
            vValue = ParseQuotedValue(strValue)

            ' Re-scan for the property separator, in case we hit one that was part of the quoted value
            ixPropertySeparator = InStr(ixClosingQuote + Len(strQUOTE), strContent, strLIST_DELIMITER)

            If ixPropertySeparator <= 0 Then ' this was the last value

                ' Check that there's nothing between the closing quote and the end of the text
                strRemainder = Trim(Mid(strContent, ixClosingQuote + Len(strQUOTE)))
                If Len(strRemainder) > 0 Then
                    Err.Raise vbObjectError, Description:="Mal-formed object (there is content after the last value)"
                End If

                ixPos = Len(strContent) + 1

            Else ' this is not the last value

                ' Check that there's nothing between the closing quote and the property separator
                strRemainder = Trim(Mid(strContent, ixClosingQuote + Len(strQUOTE), ixPropertySeparator - ixClosingQuote - Len(strQUOTE)))
                If Len(strRemainder) > 0 Then
                    Err.Raise vbObjectError, Description:="Mal-formed object (there is content after the last value)"
                End If

                ixPos = ixPropertySeparator + Len(strLIST_DELIMITER)

            End If

        End If

        ParseObjectContent.Add strName, vValue

    Loop

End Function

Private Function ParseUnquotedValue(ByVal strValue As String) As Variant

    If StrComp(strValue, strNULL_VALUE, vbTextCompare) = 0 Then
        ParseUnquotedValue = Empty
    ElseIf StrComp(strValue, strTRUE_VALUE, vbTextCompare) = 0 Then
        ParseUnquotedValue = True
    ElseIf StrComp(strValue, strFALSE_VALUE, vbTextCompare) = 0 Then
        ParseUnquotedValue = False
    ElseIf IsNumeric(strValue) Then
        ParseUnquotedValue = CDbl(strValue)
    Else
        Err.Raise vbObjectError, Description:="Mal-formed value (not null, true, false or a number)"
    End If

End Function

Private Function ParseQuotedValue(ByVal strValue As String) As Variant

    ' Both dates and strings are quoted; we'll treat it as a date if it has the expected date format.
    ' Dates are in the form:
    '    2019-09-30T00:00:00
    If strValue Like "####-##-##T##:00:00" Then
        ' NOTE: we just want the date part
        ParseQuotedValue = CDate(Left(strValue, Len("####-##-##")))
    Else
        ParseQuotedValue = strValue
    End If

End Function

A simple test:

Const strJSON As String = "[{""property1"":""foo""}]"
Dim oObjects As Collection: Set oObjects = Json.ParseListOfObjects(strJSON)

MsgBox oObjects(1)("property1") ' shows "foo"

SQL to Query text in access with an apostrophe in it

You escape ' by doubling it, so:

Select * from tblStudents where name like 'Daniel O''Neal' 

Note that if you're accepting "Daniel O'Neal" from user input, the broken quotation is a serious security issue. You should always sanitize the string or use parametrized queries.

Setting Environment Variables for Node to retrieve

Environment variables (in this case) are being used to pass credentials to your application. USER_ID and USER_KEY can both be accessed from process.env.USER_ID and process.env.USER_KEY respectively. You don't need to edit them, just access their contents.

It looks like they are simply giving you the choice between loading your USER_ID and USER_KEY from either process.env or some specificed file on disk.

Now, the magic happens when you run the application.

USER_ID=239482 USER_KEY=foobar node app.js

That will pass the user id 239482 and the user key as foobar. This is suitable for testing, however for production, you will probably be configuring some bash scripts to export variables.

jQuery document.createElement equivalent?

var div = $('<div/>');
div.append('Hello World!');

Is the shortest/easiest way to create a DIV element in jQuery.

Div with horizontal scrolling only

try this:

HTML:

<div class="container">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
  <div class="item">5</div>
</div>

CSS:

.container {
  width: 200px;
  height: 100px;
  display: flex;
  overflow-x: auto;
}

.item {
  width: 100px;
  flex-shrink: 0;
  height: 100px;
}

The white-space: nowrap; property dont let you wrap text. Just see here for an example: https://codepen.io/oezkany/pen/YoVgYK

Basic CSS - how to overlay a DIV with semi-transparent DIV on top

Using CSS3 you don't need to make your own image with the transparency.

Just have a div with the following

position:absolute;
left:0;
background: rgba(255,255,255,.5);

The last parameter in background (.5) is the level of transparency (a higher number is more opaque).

Example Fiddle

Select first 4 rows of a data.frame in R

Use head:

dnow <- data.frame(x=rnorm(100), y=runif(100))
head(dnow,4) ## default is 6

XSS prevention in JSP/Servlet web application

The how-to-prevent-xss has been asked several times. You will find a lot of information in StackOverflow. Also, OWASP website has an XSS prevention cheat sheet that you should go through.

On the libraries to use, OWASP's ESAPI library has a java flavour. You should try that out. Besides that, every framework that you use has some protection against XSS. Again, OWASP website has information on most popular frameworks, so I would recommend going through their site.

error TS1086: An accessor cannot be declared in an ambient context in Angular 9

Adding skipLibCheck: true in compilerOptions inside tsconfig.json file fixed my issue.

"compilerOptions": {
   "skipLibCheck": true,
},

Elastic Search: how to see the indexed data

Kibana is also a good solution. It is a data visualization platform for Elastic.If installed it runs by default on port 5601.

Out of the many things it provides. It has "Dev Tools" where we can do your debugging.

For example you can check your available indexes here using the command

GET /_cat/indices

How can I declare a two dimensional string array?

A 3x3 (multidimensional) array can also be initialized (you have already declared it) like this:

string[,] Tablero =  {
                        { "a", "b", "c" },
                        { "d", "e", "f" }, 
                        { "g", "h", "i"} 
                     };

C++ Boost: undefined reference to boost::system::generic_category()

Same problem on building a simple boost example, solved after i changed the g++ compiler flag from -std=c++14 to -std=c++11.

And I noticed that it's a C++11 Example...

"detached entity passed to persist error" with JPA/EJB code

Here .persist() only will insert the record.If we use .merge() it will check is there any record exist with the current ID, If it exists, it will update otherwise it will insert a new record.

Difference between numpy.array shape (R, 1) and (R,)

1) The reason not to prefer a shape of (R, 1) over (R,) is that it unnecessarily complicates things. Besides, why would it be preferable to have shape (R, 1) by default for a length-R vector instead of (1, R)? It's better to keep it simple and be explicit when you require additional dimensions.

2) For your example, you are computing an outer product so you can do this without a reshape call by using np.outer:

np.outer(M[:,0], numpy.ones((1, R)))

compare two files in UNIX

I got the solution by using comm

comm -23 file1 file2 

will give you the desired output.

The files need to be sorted first anyway.

Configure cron job to run every 15 minutes on Jenkins

1) Your cron is wrong. If you want to run job every 15 mins on Jenkins use this:

H/15 * * * *

2) Warning from Jenkins Spread load evenly by using ‘...’ rather than ‘...’ came with JENKINS-17311:

To allow periodically scheduled tasks to produce even load on the system, the symbol H (for “hash”) should be used wherever possible. For example, using 0 0 * * * for a dozen daily jobs will cause a large spike at midnight. In contrast, using H H * * * would still execute each job once a day, but not all at the same time, better using limited resources.

Examples:

  • H/15 * * * * - every fifteen minutes (perhaps at :07, :22, :37, :52):
  • H(0-29)/10 * * * * - every ten minutes in the first half of every hour (three times, perhaps at :04, :14, :24)
  • H 9-16/2 * * 1-5 - once every two hours every weekday (perhaps at 10:38 AM, 12:38 PM, 2:38 PM, 4:38 PM)
  • H H 1,15 1-11 * - once a day on the 1st and 15th of every month except December

How can I bind a background color in WPF/XAML?

You can still use "Background" as the property name, as long as you give your window a name and use this name on the "Source" of the Binding.

Fit Image into PictureBox

You could use the SizeMode property of the PictureBox Control and set it to Center. This will match the center of your image to the center of your picture box.

pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage;

Hope it could help.

The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256

Basically the error was because I was using old version of aws-sdk and I updated the version so this error occured.

in my case with node js i was using signatureVersion in parmas object like this :

const AWS_S3 = new AWS.S3({
  params: {
    Bucket: process.env.AWS_S3_BUCKET,
    signatureVersion: 'v4',
    region: process.env.AWS_S3_REGION
  }
});

Then I put signature out of params object and worked like charm :

const AWS_S3 = new AWS.S3({
  params: {
    Bucket: process.env.AWS_S3_BUCKET,
    region: process.env.AWS_S3_REGION
  },
  signatureVersion: 'v4'
});

How to allow users to check for the latest app version from inside the app?

Here's how to find the current and latest available versions:

       try {
            String curVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
            String newVersion = curVersion;
            newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + getPackageName() + "&hl=en")
                    .timeout(30000)
                    .userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
                    .referrer("http://www.google.com")
                    .get()
                    .select("div.hAyfc:nth-child(4) .IQ1z0d .htlgb")
                    .first()
                    .ownText();
            Log.d("Curr Version" , curVersion);
            Log.d("New Version" , newVersion);

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

Absolute positioning ignoring padding of parent

Could have easily done using an extra level of Div.

<div style="background-color: blue; padding: 10px; position: relative; height: 100px;">
  <div style="position: absolute; left: 0px; right: 0px; bottom: 10px; padding:0px 10px;">
    <div style="background-color: gray;">css sux</div>
  </div>
</div>

Demo: https://jsfiddle.net/soxv3vr0/

Convert one date format into another in PHP

The second parameter to date() needs to be a proper timestamp (seconds since January 1, 1970). You are passing a string, which date() can't recognize.

You can use strtotime() to convert a date string into a timestamp. However, even strtotime() doesn't recognize the y-m-d-h-i-s format.

PHP 5.3 and up

Use DateTime::createFromFormat. It allows you to specify an exact mask - using the date() syntax - to parse incoming string dates with.

PHP 5.2 and lower

You will have to parse the elements (year, month, day, hour, minute, second) manually using substr() and hand the results to mktime() that will build you a timestamp.

But that's a lot of work! I recommend using a different format that strftime() can understand. strftime() understands any date input short of the next time joe will slip on the ice. for example, this works:

$old_date = date('l, F d y h:i:s');              // returns Saturday, January 30 10 02:06:34
$old_date_timestamp = strtotime($old_date);
$new_date = date('Y-m-d H:i:s', $old_date_timestamp);   

HTML not loading CSS file

Here is another cause to add to the collection on this page. In this code...

<link rel="stylesheet" type="text/css" href="styles/styles.css" media="screen">

...I misspelled rel as ref.

Host binding and Host listening

@HostListener is a decorator for the callback/event handler method, so remove the ; at the end of this line:

@HostListener('click', ['$event.target']);

Here's a working plunker that I generated by copying the code from the API docs, but I put the onClick() method on the same line for clarity:

import {Component, HostListener, Directive} from 'angular2/core';

@Directive({selector: 'button[counting]'})
class CountClicks {
  numberOfClicks = 0;
  @HostListener('click', ['$event.target']) onClick(btn) {
    console.log("button", btn, "number of clicks:", this.numberOfClicks++);
  }
}
@Component({
  selector: 'my-app',
  template: `<button counting>Increment</button>`,
  directives: [CountClicks]
})
export class AppComponent {
  constructor() { console.clear(); }
}

Host binding can also be used to listen to global events:

To listen to global events, a target must be added to the event name. The target can be window, document or body (reference)

@HostListener('document:keyup', ['$event'])
handleKeyboardEvent(kbdEvent: KeyboardEvent) { ... }

How to get form values in Symfony2 controller

In Symfony 2 ( to be more specific, the 2.3 version ) you can get a data of an field by

$var = $form->get('yourformfieldname')->getData();

or you can get all data sent

$data = $form->getData();

where '$data' is an array containing your form fields' values.

Convert JSONArray to String Array

I do post an answer here for the question here that was closed even though the asnwers here helped, but were not sufficient.

So, this is in order to get a json array to a String[] using jsonsimple.

According to the (marvelous) decode examples and docs, JSONArrays are java List, so we can access List methods.

From there, is it possible to transform it to a String[] with the following:

    JSONObject assemblingTags = (JSONObject) obj.get("assembling-tags");
    JSONArray aTagsList = (JSONArray) assemblingTags.get("list");
    String[] tagsList = (String[]) aTagsList.stream().toArray(String[]::new);

How to delete a specific line in a file?

You can use the re library

Assuming that you are able to load your full txt-file. You then define a list of unwanted nicknames and then substitute them with an empty string "".

# Delete unwanted characters
import re

# Read, then decode for py2 compat.
path_to_file = 'data/nicknames.txt'
text = open(path_to_file, 'rb').read().decode(encoding='utf-8')

# Define unwanted nicknames and substitute them
unwanted_nickname_list = ['SourDough']
text = re.sub("|".join(unwanted_nickname_list), "", text)

How to create an ArrayList from an Array in PowerShell?

Probably the shortest version:

[System.Collections.ArrayList]$someArray

It is also faster because it does not call relatively expensive New-Object.

Parsing GET request parameters in a URL that contains another URL

While creating url encode them with urlencode

$val=urlencode('http://google.com/?var=234&key=234')

<a href="http://localhost/test.php?id=<?php echo $val ?>">Click here</a>

and while fetching decode it wiht urldecode

Variable declaration in a header file

If you declare it like

int x;

in a header file which is then included in multiple places, you'll end up with multiple instances of x (and potentially compile or link problems).

The correct way to approach this is to have the header file say

extern int x; /* declared in foo.c */

and then in foo.c you can say

int x; /* exported in foo.h */

THen you can include your header file in as many places as you like.

How ViewBag in ASP.NET MVC works

The ViewBag is an System.Dynamic.ExpandoObject as suggested. The properties in the ViewBag are essentially KeyValue pairs, where you access the value by the key. In this sense these are equivalent:

ViewBag.Foo = "Bar";
ViewBag["Foo"] = "Bar";

How to style a select tag's option element?

I have a workaround using jquery... although we cannot style a particular option, we can style the select itself - and use javascript to change the class of the select based on what is selected. It works sufficiently for simple cases.

_x000D_
_x000D_
$('select.potentially_red').on('change', function() {_x000D_
 if ($(this).val()=='red') {_x000D_
  $(this).addClass('option_red');_x000D_
 } else {_x000D_
  $(this).removeClass('option_red');_x000D_
 }_x000D_
});_x000D_
$('select.potentially_red').each( function() {_x000D_
 if ($(this).val()=='red') {_x000D_
  $(this).addClass('option_red');_x000D_
 } else {_x000D_
  $(this).removeClass('option_red');_x000D_
 }_x000D_
});
_x000D_
.option_red {_x000D_
    background-color: #cc0000; _x000D_
    font-weight: bold; _x000D_
    font-size: 12px; _x000D_
    color: white;_x000D_
}
_x000D_
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
<!-- The js will affect all selects which have the class 'potentially_red' -->_x000D_
<select name="color" class="potentially_red">_x000D_
    <option value="red">Red</option>_x000D_
    <option value="white">White</option>_x000D_
    <option value="blue">Blue</option>_x000D_
    <option value="green">Green</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Note that the js is in two parts, the each part for initializing everything on the page correctly, the .on('change', ... part for responding to change. I was unable to mangle the js into a function to DRY it up, it breaks it for some reason

How to add an UIViewController's view as subview

Thanks to this guys I did it http://highoncoding.com/Articles/848_Creating_iPad_Dashboard_Using_UIViewController_Containment.aspx

Add UIView, connect it to header:

@property (weak, nonatomic) IBOutlet UIView *addViewToAddPlot;

In - (void)viewDidLoad do this:

ViewControllerToAdd *nonSystemsController = [[ViewControllerToAdd alloc] initWithNibName:@"ViewControllerToAdd" bundle:nil];
    nonSystemsController.view.frame = self.addViewToAddPlot.bounds;
    [self.addViewToAddPlot addSubview:nonSystemsController.view];
    [self addChildViewController:nonSystemsController];
    [nonSystemsController didMoveToParentViewController:self];

Enjoy

How to do joins in LINQ on multiple fields in single join

var result = from x in entity
             join y in entity2
             on new { X1= x.field1, X2= x.field2 } equals new { X1=y.field1, X2= y.field2 }
             select new 
             {
               /// Columns
              };

Re-enabling window.alert in Chrome

Close and re-open the tab. That should do the trick.

'\r': command not found - .bashrc / .bash_profile

I am using cygwin and Windows7, the trick was NOT to put the set -o igncr into your .bashrc but put the whole SHELLOPTS into you environment variables under Windows. (So nothing with unix / cygwin...) I think it does not work from .bashrc because "the drops is already sucked" as we would say in german. ;-) So my SHELLOPTS looks like this

braceexpand:emacs:hashall:histexpand:history:igncr:interactive-comments:monitor

XmlSerializer giving FileNotFoundException at constructor

I was getting the same error, and it was due to the type I was trying to deserialize not having a default parameterless constructor. I added a constructor, and it started working.

How to create a 100% screen width div inside a container in bootstrap?

2019's answer as this is still actively seen today

You should likely change the .container to .container-fluid, which will cause your container to stretch the entire screen. This will allow any div's inside of it to naturally stretch as wide as they need.

original hack from 2015 that still works in some situations

You should pull that div outside of the container. You're asking a div to stretch wider than its parent, which is generally not recommended practice.

If you cannot pull it out of the div for some reason, you should change the position style with this css:

.full-width-div {
    position: absolute;
    width: 100%;
    left: 0;
}

Instead of absolute, you could also use fixed, but then it will not move as you scroll.

Format date and Subtract days using Moment.js

startdate = moment().subtract(1, 'days').format('DD-MM-YYYY');

How do I convert a number to a letter in Java?

for(int i=0;i<ar.length();i++) {
            char ch = ar.charAt(i);
                    System.out.println((char)(ch+16));;
        }

How to filter array when object key value is in array

Old way of doing it. Many might hate this way of doing but i still many time find this is still better in my perspective.

Input:

var records = [{
    "empid":1,
    "fname": "X",
    "lname": "Y"
},
{
    "empid":2,
    "fname": "A",
    "lname": "Y"
},
{
    "empid":3,
    "fname": "B",
    "lname": "Y"
},
{
    "empid":4,
    "fname": "C",
    "lname": "Y"
},
{
    "empid":5,
    "fname": "C",
    "lname": "Y"
}
]

var newArr = [1,4,5];

Code:

var newObj = [];
for(var a = 0 ; a < records.length ; a++){
 if(newArr.indexOf(records[a].empid) > -1){
  newObj.push(records[a]);
 }
}

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

Reference - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

Output:

[{
    "empid": 1,
    "fname": "X",
    "lname": "Y"
}, {
    "empid": 4,
    "fname": "C",
    "lname": "Y"
}, {
    "empid": 5,
    "fname": "C",
    "lname": "Y"
}]

What is the syntax for Typescript arrow functions with generics?

so late, but with ES6 no need extends it still work for me.... :)

let getArray = <T>(items: T[]): T[] => {
    return new Array<T>().concat(items)
}

let myNumArr = getArray<number>([100, 200, 300]);
let myStrArr = getArray<string>(["Hello", "World"]);
myNumArr.push(1)
console.log(myNumArr)

Which maven dependencies to include for spring 3.0?

You can try this

<dependencies>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>3.1.0.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>3.1.0.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>3.1.0.RELEASE</version>
    </dependency>
</dependencies>`

Use sed to replace all backslashes with forward slashes

If your text is in a Bash variable, then Parameter Substitution ${var//\\//} can replace substrings:

$ p='C:\foo\bar.xml'
$ printf '%s\n' "$p"
C:\foo\bar.xml
$ printf '%s\n' "${p//\\//}"
C:/foo/bar.xml

This may be leaner and clearer that filtering through a command such as tr or sed.

What is the technology behind wechat, whatsapp and other messenger apps?

The WhatsApp Architecture Facebook Bought For $19 Billion explains the architecture involved in design of whatsapp.

Here is the general explanation from the link

  • WhatsApp server is almost completely implemented in Erlang.

  • Server systems that do the backend message routing are done in Erlang.

  • Great achievement is that the number of active users is managed with a really small server footprint. Team consensus is that it is largely because of Erlang.

  • Interesting to note Facebook Chat was written in Erlang in 2009, but they went away from it because it was hard to find qualified programmers.

  • WhatsApp server has started from ejabberd

  • Ejabberd is a famous open source Jabber server written in Erlang.

  • Originally chosen because its open, had great reviews by developers, ease of start and the promise of Erlang’s long term suitability for large communication system.

  • The next few years were spent re-writing and modifying quite a few parts of ejabberd, including switching from XMPP to internally developed protocol, restructuring the code base and redesigning some core components, and making lots of important modifications to Erlang VM to optimize server performance.

  • To handle 50 billion messages a day the focus is on making a reliable system that works. Monetization is something to look at later, it’s far far down the road.

  • A primary gauge of system health is message queue length. The message queue length of all the processes on a node is constantly monitored and an alert is sent out if they accumulate backlog beyond a preset threshold. If one or more processes falls behind that is alerted on, which gives a pointer to the next bottleneck to attack.

  • Multimedia messages are sent by uploading the image, audio or video to be sent to an HTTP server and then sending a link to the content along with its Base64 encoded thumbnail (if applicable).

  • Some code is usually pushed every day. Often, it’s multiple times a day, though in general peak traffic times are avoided. Erlang helps being aggressive in getting fixes and features into production. Hot-loading means updates can be pushed without restarts or traffic shifting. Mistakes can usually be undone very quickly, again by hot-loading. Systems tend to be much more loosely-coupled which makes it very easy to roll changes out incrementally.

  • What protocol is used in Whatsapp app? SSL socket to the WhatsApp server pools. All messages are queued on the server until the client reconnects to retrieve the messages. The successful retrieval of a message is sent back to the whatsapp server which forwards this status back to the original sender (which will see that as a "checkmark" icon next to the message). Messages are wiped from the server memory as soon as the client has accepted the message

  • How does the registration process work internally in Whatsapp? WhatsApp used to create a username/password based on the phone IMEI number. This was changed recently. WhatsApp now uses a general request from the app to send a unique 5 digit PIN. WhatsApp will then send a SMS to the indicated phone number (this means the WhatsApp client no longer needs to run on the same phone). Based on the pin number the app then request a unique key from WhatsApp. This key is used as "password" for all future calls. (this "permanent" key is stored on the device). This also means that registering a new device will invalidate the key on the old device.

How to clear the logs properly for a Docker container?

Not sure if this is helpful for you, but removing the container always helps.

So, if you use docker-compose for your setup, you can simply use docker-compose down && docker-compose up instead of docker-compose restart. With a proper setup (make sure to use volume mounts for persistent data), you don't lose any data this way.

Sure, this is more than the OP requested. But there are various situations where the other answers cannot help (if using a remote docker server or working on a Windows machine, accessing the underlying filesystem is proprietary and difficult)

curl: (6) Could not resolve host: google.com; Name or service not known

Issues were:

  1. IPV6 enabled
  2. Wrong DNS server

Here is how I fixed it:

IPV6 Disabling

  • Open Terminal
  • Type su and enter to log in as the super user
  • Enter the root password
  • Type cd /etc/modprobe.d/ to change directory to /etc/modprobe.d/
  • Type vi disableipv6.conf to create a new file there
  • Press Esc + i to insert data to file
  • Type install ipv6 /bin/true on the file to avoid loading IPV6 related modules
  • Type Esc + : and then wq for save and exit
  • Type reboot to restart fedora
  • After reboot open terminal and type lsmod | grep ipv6
  • If no result, it means you properly disabled IPV6

Add Google DNS server

  • Open Terminal
  • Type su and enter to log in as the super user
  • Enter the root password
  • Type cat /etc/resolv.conf to check what DNS server your Fedora using. Mostly this will be your Modem IP address.
  • Now we have to Find a powerful DNS server. Luckily there is a open DNS server maintain by Google.
  • Go to this page and find out what are the "Google Public DNS IP addresses"
  • Today those are 8.8.8.8 and 8.8.4.4. But in future those may change.
  • Type vi /etc/resolv.conf to edit the resolv.conf file
  • Press Esc + i for insert data to file
  • Comment all the things in the file by inserting # at the begin of the each line. Do not delete anything because can be useful in future.
  • Type below two lines in the file

    nameserver 8.8.8.8
    nameserver 8.8.4.4

    -Type Esc + : and then wq for save and exit

  • Now you are done and everything works fine (Not necessary to restart).
  • But every time when you restart the computer your /etc/resolv.conf will be replaced by default. So I'll let you find a way to avoid that.

Here is my blog post about this: http://codeketchup.blogspot.sg/2014/07/how-to-fix-curl-6-could-not-resolve.html

Typing Greek letters etc. in Python plots

You need to make the strings raw and use latex:

fig.gca().set_ylabel(r'$\lambda$')

As of matplotlib 2.0 the default font supports most western alphabets and can simple do

ax.set_xlabel('?')

with unicode.

How to check if a string contains a specific text

http://php.net/manual/en/function.strpos.php I think you are wondiner if 'some text' exists in the string right?

if(strpos( $a , 'some text' ) !== false)

What is difference between sjlj vs dwarf vs seh?

There's a short overview at MinGW-w64 Wiki:

Why doesn't mingw-w64 gcc support Dwarf-2 Exception Handling?

The Dwarf-2 EH implementation for Windows is not designed at all to work under 64-bit Windows applications. In win32 mode, the exception unwind handler cannot propagate through non-dw2 aware code, this means that any exception going through any non-dw2 aware "foreign frames" code will fail, including Windows system DLLs and DLLs built with Visual Studio. Dwarf-2 unwinding code in gcc inspects the x86 unwinding assembly and is unable to proceed without other dwarf-2 unwind information.

The SetJump LongJump method of exception handling works for most cases on both win32 and win64, except for general protection faults. Structured exception handling support in gcc is being developed to overcome the weaknesses of dw2 and sjlj. On win64, the unwind-information are placed in xdata-section and there is the .pdata (function descriptor table) instead of the stack. For win32, the chain of handlers are on stack and need to be saved/restored by real executed code.

GCC GNU about Exception Handling:

GCC supports two methods for exception handling (EH):

  • DWARF-2 (DW2) EH, which requires the use of DWARF-2 (or DWARF-3) debugging information. DW-2 EH can cause executables to be slightly bloated because large call stack unwinding tables have to be included in th executables.
  • A method based on setjmp/longjmp (SJLJ). SJLJ-based EH is much slower than DW2 EH (penalising even normal execution when no exceptions are thrown), but can work across code that has not been compiled with GCC or that does not have call-stack unwinding information.

[...]

Structured Exception Handling (SEH)

Windows uses its own exception handling mechanism known as Structured Exception Handling (SEH). [...] Unfortunately, GCC does not support SEH yet. [...]

See also:

How to negate a method reference predicate

Predicate has methods and, or and negate.

However, String::isEmpty is not a Predicate, it's just a String -> Boolean lambda and it could still become anything, e.g. Function<String, Boolean>. Type inference is what needs to happen first. The filter method infers type implicitly. But if you negate it before passing it as an argument, it no longer happens. As @axtavt mentioned, explicit inference can be used as an ugly way:

s.filter(((Predicate<String>) String::isEmpty).negate()).count()

There are other ways advised in other answers, with static not method and lambda most likely being the best ideas. This concludes the tl;dr section.


However, if you want some deeper understanding of lambda type inference, I'd like to explain it a bit more to depth, using examples. Look at these and try to figure out what happens:

Object obj1                  = String::isEmpty;
Predicate<String> p1         = s -> s.isEmpty();
Function<String, Boolean> f1 = String::isEmpty;
Object obj2                  = p1;
Function<String, Boolean> f2 = (Function<String, Boolean>) obj2;
Function<String, Boolean> f3 = p1::test;
Predicate<Integer> p2        = s -> s.isEmpty();
Predicate<Integer> p3        = String::isEmpty;
  • obj1 doesn't compile - lambdas need to infer a functional interface (= with one abstract method)
  • p1 and f1 work just fine, each inferring a different type
  • obj2 casts a Predicate to Object - silly but valid
  • f2 fails at runtime - you cannot cast Predicate to Function, it's no longer about inference
  • f3 works - you call the predicate's method test that is defined by its lambda
  • p2 doesn't compile - Integer doesn't have isEmpty method
  • p3 doesn't compile either - there is no String::isEmpty static method with Integer argument

I hope this helps get some more insight into how type inferrence works.

What is the difference between a static and const variable?

Static variables are common across all instances of a type.

constant variables are specific to each individual instance of a type but their values are known and fixed at compile time and it cannot be changed at runtime.

unlike constants, static variable values can be changed at runtime.

How to center a subview of UIView

Using the same center in the view and subview is the simplest way of doing it. You can do something like this,

UIView *innerView = ....;
innerView.view.center = self.view.center;
[self.view addSubView:innerView];