Programs & Examples On #Applicationhost

IIS Config Error - This configuration section cannot be used at this path

Most IIS sections are locked by default but you can "unlock" them by setting the attribute overrideModeDefault from "Deny" to "Allow" for the relevant section group by modifying the ApplicationHost.config file located in %windir%\system32\inetsrv\config in Administrator mode

enter image description here

psql - save results of command to a file

Approach for docker

via psql command

 docker exec -i %containerid% psql -U %user% -c '\dt' > tables.txt

or query from sql file

docker exec -i %containerid% psql -U %user% < file.sql > data.txt

How to use "raise" keyword in Python

raise without any arguments is a special use of python syntax. It means get the exception and re-raise it. If this usage it could have been called reraise.

    raise

From The Python Language Reference:

If no expressions are present, raise re-raises the last exception that was active in the current scope.

If raise is used alone without any argument is strictly used for reraise-ing. If done in the situation that is not at a reraise of another exception, the following error is shown: RuntimeError: No active exception to reraise

Base64 Java encode and decode a string

The accepted answer uses the Apache Commons package but this is how I did it using Java's native libraries

Java 11 and up

import java.util.Base64;

public class Base64Encoding {

    public static void main(String[] args) {
        Base64.Encoder enc = Base64.getEncoder();
        Base64.Decoder dec = Base64.getDecoder();
        String str = "77+9x6s=";

        // encode data using BASE64
        String encoded = enc.encodeToString(str.getBytes());
        System.out.println("encoded value is \t" + encoded);

        // Decode data
        String decoded = new String(dec.decode(encoded));
        System.out.println("decoded value is \t" + decoded);
        System.out.println("original value is \t" + str);
    }
}

Java 6 - 10

import java.io.UnsupportedEncodingException;    
import javax.xml.bind.DatatypeConverter;

public class EncodeString64 {
    public static void main(String[] args) throws UnsupportedEncodingException {

        String str = "77+9x6s=";
        // encode data using BASE64
        String encoded = DatatypeConverter.printBase64Binary(str.getBytes());
        System.out.println("encoded value is \t" + encoded);

        // Decode data 
        String decoded = new String(DatatypeConverter.parseBase64Binary(encoded));
        System.out.println("decoded value is \t" + decoded);

        System.out.println("original value is \t" + str);
    }
}

The better way would be to try/catch the encoding/decoding steps but hopefully you get the idea.

When to use .First and when to use .FirstOrDefault with LINQ?

This type of the function belongs to element operators. Some useful element operators are defined below.

  1. First/FirstOrDefault
  2. Last/LastOrDefault
  3. Single/SingleOrDefault

We use element operators when we need to select a single element from a sequence based on a certain condition. Here is an example.

  List<int> items = new List<int>() { 8, 5, 2, 4, 2, 6, 9, 2, 10 };

First() operator returns the first element of a sequence after satisfied the condition. If no element is found then it will throw an exception.

int result = items.Where(item => item == 2).First();

FirstOrDefault() operator returns the first element of a sequence after satisfied the condition. If no element is found then it will return default value of that type.

int result1 = items.Where(item => item == 2).FirstOrDefault();

Body set to overflow-y:hidden but page is still scrollable in Chrome

Another solution I found to work is to set a mousewheel handler on the inside container and make sure it doesn't propagate by setting its last parameter to false and stopping the event bubble.

document.getElementById('content').addEventListener('mousewheel',function(evt){evt.cancelBubble=true;   if (evt.stopPropagation) evt.stopPropagation},false);

Scroll works fine in the inner container, but the event doesn't propagate to the body and so it does not scroll. This is in addition to setting the body properties overflow:hidden and height:100%.

PreparedStatement setNull(..)

Finally I did a small test and while I was programming it it came to my mind, that without the setNull(..) method there would be no way to set null values for the Java primitives. For Objects both ways

setNull(..)

and

set<ClassName>(.., null)) 

behave the same way.

Center button under form in bootstrap

Width:100% and text-align:center would work in my experience

<p style="display:block; line-height: 70px; width:100%; text-align:center; margin:0 auto;"><button type="submit" class="btn">Confirm</button></p>

How to use GROUP_CONCAT in a CONCAT in MySQL

select id, group_concat(`Name` separator ',') as `ColumnName`
from
(
  select 
    id, 
    concat(`Name`, ':', group_concat(`Value` separator ',')) as `Name`
  from mytbl
  group by 
    id, 
    `Name`
) tbl
group by id;

You can see it implemented here : Sql Fiddle Demo. Exactly what you need.

Update Splitting in two steps. First we get a table having all values(comma separated) against a unique[Name,id]. Then from obtained table we get all names and values as a single value against each unique id See this explained here SQL Fiddle Demo (scroll down as it has two result sets)

Edit There was a mistake in reading question, I had grouped only by id. But two group_contacts are needed if (Values are to be concatenated grouped by Name and id and then over all by id). Previous answer was

select 
id,group_concat(concat(`name`,':',`value`) separator ',')
as Result from mytbl group by id

You can see it implemented here : SQL Fiddle Demo

How to change file encoding in NetBeans?

On project explorer, right click on the project, Properties -> General -> Encoding. This will allow you to choose the encoding per project.

Is it possible to make abstract classes in Python?

also this works and is simple:

class A_abstract(object):

    def __init__(self):
        # quite simple, old-school way.
        if self.__class__.__name__ == "A_abstract": 
            raise NotImplementedError("You can't instantiate this abstract class. Derive it, please.")

class B(A_abstract):

        pass

b = B()

# here an exception is raised:
a = A_abstract()

How can I generate a self-signed certificate with SubjectAltName using OpenSSL?

Can someone help me with the exact syntax?

It's a three-step process, and it involves modifying the openssl.cnf file. You might be able to do it with only command line options, but I don't do it that way.

Find your openssl.cnf file. It is likely located in /usr/lib/ssl/openssl.cnf:

$ find /usr/lib -name openssl.cnf
/usr/lib/openssl.cnf
/usr/lib/openssh/openssl.cnf
/usr/lib/ssl/openssl.cnf

On my Debian system, /usr/lib/ssl/openssl.cnf is used by the built-in openssl program. On recent Debian systems it is located at /etc/ssl/openssl.cnf

You can determine which openssl.cnf is being used by adding a spurious XXX to the file and see if openssl chokes.


First, modify the req parameters. Add an alternate_names section to openssl.cnf with the names you want to use. There are no existing alternate_names sections, so it does not matter where you add it.

[ alternate_names ]

DNS.1        = example.com
DNS.2        = www.example.com
DNS.3        = mail.example.com
DNS.4        = ftp.example.com

Next, add the following to the existing [ v3_ca ] section. Search for the exact string [ v3_ca ]:

subjectAltName      = @alternate_names

You might change keyUsage to the following under [ v3_ca ]:

keyUsage = digitalSignature, keyEncipherment

digitalSignature and keyEncipherment are standard fare for a server certificate. Don't worry about nonRepudiation. It's a useless bit thought up by computer science guys/gals who wanted to be lawyers. It means nothing in the legal world.

In the end, the IETF (RFC 5280), browsers and CAs run fast and loose, so it probably does not matter what key usage you provide.


Second, modify the signing parameters. Find this line under the CA_default section:

# Extension copying option: use with caution.
# copy_extensions = copy

And change it to:

# Extension copying option: use with caution.
copy_extensions = copy

This ensures the SANs are copied into the certificate. The other ways to copy the DNS names are broken.


Third, generate your self-signed certificate:

$ openssl genrsa -out private.key 3072
$ openssl req -new -x509 -key private.key -sha256 -out certificate.pem -days 730
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
...

Finally, examine the certificate:

$ openssl x509 -in certificate.pem -text -noout
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 9647297427330319047 (0x85e215e5869042c7)
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
        Validity
            Not Before: Feb  1 05:23:05 2014 GMT
            Not After : Feb  1 05:23:05 2016 GMT
        Subject: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (3072 bit)
                Modulus:
                    00:e2:e9:0e:9a:b8:52:d4:91:cf:ed:33:53:8e:35:
                    ...
                    d6:7d:ed:67:44:c3:65:38:5d:6c:94:e5:98:ab:8c:
                    72:1c:45:92:2c:88:a9:be:0b:f9
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier:
                34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
            X509v3 Authority Key Identifier:
                keyid:34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4

            X509v3 Basic Constraints: critical
                CA:FALSE
            X509v3 Key Usage:
                Digital Signature, Non Repudiation, Key Encipherment, Certificate Sign
            X509v3 Subject Alternative Name:
                DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
    Signature Algorithm: sha256WithRSAEncryption
         3b:28:fc:e3:b5:43:5a:d2:a0:b8:01:9b:fa:26:47:8e:5c:b7:
         ...
         71:21:b9:1f:fa:30:19:8b:be:d2:19:5a:84:6c:81:82:95:ef:
         8b:0a:bd:65:03:d1

Select SQL Server database size

Also compare the results with the following query's result

EXEC sp_helpdb @dbname= 'MSDB'

It produces result similar to the following

enter image description here

There is a good article - Different ways to determine free space for SQL Server databases and database files

How to get a reversed list view on a list in Java?

Collections.reverse(nums) ... It actually reverse the order of the elements. Below code should be much appreciated -

List<Integer> nums = new ArrayList<Integer>();
nums.add(61);
nums.add(42);
nums.add(83);
nums.add(94);
nums.add(15);
//Tosort the collections uncomment the below line
//Collections.sort(nums); 

Collections.reverse(nums);

System.out.println(nums);

Output: 15,94,83,42,61

How do I work with dynamic multi-dimensional arrays in C?

int rows, columns;
/* initialize rows and columns to the desired value */

    arr = (int**)malloc(rows*sizeof(int*));
        for(i=0;i<rows;i++)
        {
            arr[i] = (int*)malloc(cols*sizeof(int));
        }

Validate fields after user has left a field

I solved this by expanding on what @jlmcdonald suggested. I created a directive that would automatically be applied to all input and select elements:

var blurFocusDirective = function () {
    return {
        restrict: 'E',
        require: '?ngModel',
        link: function (scope, elm, attr, ctrl) {
            if (!ctrl) {
                return;
            }

            elm.on('focus', function () {
                elm.addClass('has-focus');

                scope.$apply(function () {
                    ctrl.hasFocus = true;
                });
            });

            elm.on('blur', function () {
                elm.removeClass('has-focus');
                elm.addClass('has-visited');

                scope.$apply(function () {
                    ctrl.hasFocus = false;
                    ctrl.hasVisited = true;
                });
            });

            elm.closest('form').on('submit', function () {
                elm.addClass('has-visited');

                scope.$apply(function () {
                    ctrl.hasFocus = false;
                    ctrl.hasVisited = true;
                });
            });

        }
    };
};

app.directive('input', blurFocusDirective);
app.directive('select', blurFocusDirective);

This will add has-focus and has-visited classes to various elements as the user focuses/visits the elements. You can then add these classes to your CSS rules to show validation errors:

input.has-visited.ng-invalid:not(.has-focus) {
    background-color: #ffeeee;   
}

This works well in that elements still get $invalid properties etc, but the CSS can be used to give the user a better experience.

How to get the public IP address of a user in C#

This is what I use:

protected void GetUser_IP()
{
    string VisitorsIPAddr = string.Empty;
    if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
    {
        VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
    }
    else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
    {
        VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
    }
    uip.Text = "Your IP is: " + VisitorsIPAddr;
}

"uip" is the name of the label in the aspx page that shows the user IP.

best way to get folder and file list in Javascript

In my project I use this function for getting huge amount of files. It's pretty fast (put require("FS") out to make it even faster):

var _getAllFilesFromFolder = function(dir) {

    var filesystem = require("fs");
    var results = [];

    filesystem.readdirSync(dir).forEach(function(file) {

        file = dir+'/'+file;
        var stat = filesystem.statSync(file);

        if (stat && stat.isDirectory()) {
            results = results.concat(_getAllFilesFromFolder(file))
        } else results.push(file);

    });

    return results;

};

usage is clear:

_getAllFilesFromFolder(__dirname + "folder");

SQL Data Reader - handling Null column values

Check sqlreader.IsDBNull(indexFirstName) before you try to read it.

How do I install cygwin components from the command line?

I wanted a solution for this similar to apt-get --print-uris, but unfortunately apt-cyg doesn't do this. The following is a solution that allowed me to download only the packages I needed, with their dependencies, and copy them to the target for installation. Here is a bash script that parses the output of apt-cyg into a list of URIs:

#!/usr/bin/bash

package=$1
depends=$( \
    apt-cyg depends $package \
    | perl -ne 'while ($x = /> ([^>\s]+)/g) { print "$1\n"; }' \
    | sort \
    | uniq)
depends=$(echo -e "$depends\n$package")
for curpkg in $depends; do
    if ! grep -q "^$curpkg " /etc/setup/installed.db; then
    apt-cyg show $curpkg \
        | perl -ne '
            if ($x = /install: ([^\s]+)/) { 
                print "$1\n"; 
            }
            if (/\[prev\]/) { 
                exit; 
            }'
    fi
done

The above will print out the paths of the packages that need downloading, relative to the cygwin mirror root, omitting any packages that are already installed. To download them, I wrote the output to a file cygwin-packages-list and then used wget:

mirror=http://cygwin.mirror.constant.com/
uris=$(for line in $(cat cygwin-packages-list); do echo "$mirror$line"; done)
wget -x $uris

The installer can then be used to install from a local cache directory. Note that for this to work I needed to copy setup.ini from a previous cygwin package cache to the directory with the downloaded files (otherwise the installer doesn't know what's what).

Calling a function on bootstrap modal open

will not work.. use $(window) instead

For Showing

$(window).on('shown.bs.modal', function() { 
    $('#code').modal('show');
    alert('shown');
});

For Hiding

$(window).on('hidden.bs.modal', function() { 
    $('#code').modal('hide');
    alert('hidden');
});

How can I make a CSS table fit the screen width?

table { width: 100%; }

Will not produce the exact result you are expecting, because of all the margins and paddings used in body. So IF scripts are OKAY, then use Jquery.

$("#tableid").width($(window).width());

If not, use this snippet

<style>
    body { margin:0;padding:0; }
</style>
<table width="100%" border="1">
    <tr>
        <td>Just a Test
        </td>
    </tr>
</table>

You will notice that the width is perfectly covering the page.

The main thing is too nullify the margin and padding as I have shown at the body, then you are set.

Java: Why is the Date constructor deprecated, and what do I use instead?

Similar to what binnyb suggested, you might consider using the newer Calendar > GregorianCalendar method. See these more recent docs:

http://download.oracle.com/javase/6/docs/api/java/util/GregorianCalendar.html

How can I import data into mysql database via mysql workbench?

For MySQL Workbench 8.0 navigate to:

Server > Data Import

A new tab called Administration - Data Import/Restore appears. There you can choose to import a Dump Project Folder or use a specific SQL file according to your needs. Then you must select a schema where the data will be imported to, or you have to click the New... button to type a name for the new schema.

Then you can select the database objects to be imported or just click the Start Import button in the lower right part of the tab area.

Having done that and if the import was successful, you'll need to update the Schema Navigator by clicking the arrow circle icon.

That's it!

For more detailed info, check the MySQL Workbench Manual: 6.5.2 SQL Data Export and Import Wizard

Access host database from a docker container

From the 18.03 docs:

I want to connect from a container to a service on the host

The host has a changing IP address (or none if you have no network access). From 18.03 onwards our recommendation is to connect to the special DNS name host.docker.internal, which resolves to the internal IP address used by the host.

The gateway is also reachable as gateway.docker.internal.

EXAMPLE: Here's what I use for my MySQL connection string inside my container to access the MySQL instance on my host:

mysql://host.docker.internal:3306/my_awesome_database

Dynamically display a CSV file as an HTML table on a web page

define "display it dynamically" ? that implies the table is being built via javascript and some sort of Ajax-y update .. if you just want to build the table using PHP that's really not what I would call 'dynamic'

vertical alignment of text element in SVG

According to SVG spec, alignment-baseline only applies to <tspan>, <textPath>, <tref> and <altGlyph>. My understanding is that it is used to offset those from the <text> object above them. I think what you are looking for is dominant-baseline.

Possible values of dominant-baseline are:

auto | use-script | no-change | reset-size | ideographic | alphabetic | hanging | mathematical | central | middle | text-after-edge | text-before-edge | inherit

Check the W3C recommendation for the dominant-baseline property for more information about each possible value.

What is the default maximum heap size for Sun's JVM from Java SE 6?

java 1.6.0_21 or later, or so...

$ java -XX:+PrintFlagsFinal -version 2>&1 | grep MaxHeapSize
uintx MaxHeapSize                         := 12660904960      {product}

It looks like the min(1G) has been removed.

Or on Windows using findstr

C:\>java -XX:+PrintFlagsFinal -version 2>&1 | findstr MaxHeapSize

Fetch API request timeout?

You can create a timeoutPromise wrapper

function timeoutPromise(timeout, err, promise) {
  return new Promise(function(resolve,reject) {
    promise.then(resolve,reject);
    setTimeout(reject.bind(null,err), timeout);
  });
}

You can then wrap any promise

timeoutPromise(100, new Error('Timed Out!'), fetch(...))
  .then(...)
  .catch(...)  

It won't actually cancel an underlying connection but will allow you to timeout a promise.
Reference

What is the use of a cursor in SQL Server?

cursor are used because in sub query we can fetch record row by row so we use cursor to fetch records

Example of cursor:

DECLARE @eName varchar(50), @job varchar(50)

DECLARE MynewCursor CURSOR -- Declare cursor name

FOR
Select eName, job FROM emp where deptno =10

OPEN MynewCursor -- open the cursor

FETCH NEXT FROM MynewCursor
INTO @eName, @job

PRINT @eName + ' ' + @job -- print the name

WHILE @@FETCH_STATUS = 0

BEGIN

FETCH NEXT FROM MynewCursor 
INTO @ename, @job

PRINT @eName +' ' + @job -- print the name

END

CLOSE MynewCursor

DEALLOCATE MynewCursor

OUTPUT:

ROHIT                           PRG  
jayesh                          PRG
Rocky                           prg
Rocky                           prg

Reading *.wav files in Python

Different Python modules to read wav:

There is at least these following libraries to read wave audio files:

The most simple example:

This is a simple example with SoundFile:

import soundfile as sf
data, samplerate = sf.read('existing_file.wav') 

Format of the output:

Warning, the data are not always in the same format, that depends on the library. For instance:

from scikits import audiolab
from scipy.io import wavfile
from sys import argv
for filepath in argv[1:]:
    x, fs, nb_bits = audiolab.wavread(filepath)
    print('Reading with scikits.audiolab.wavread:', x)
    fs, x = wavfile.read(filepath)
    print('Reading with scipy.io.wavfile.read:', x)

Output:

Reading with scikits.audiolab.wavread: [ 0.          0.          0.         ..., -0.00097656 -0.00079346 -0.00097656]
Reading with scipy.io.wavfile.read: [  0   0   0 ..., -32 -26 -32]

SoundFile and Audiolab return floats between -1 and 1 (as matab does, that is the convention for audio signals). Scipy and wave return integers, which you can convert to floats according to the number of bits of encoding, for example:

from scipy.io.wavfile import read as wavread
samplerate, x = wavread(audiofilename)  # x is a numpy array of integers, representing the samples 
# scale to -1.0 -- 1.0
if x.dtype == 'int16':
    nb_bits = 16  # -> 16-bit wav files
elif x.dtype == 'int32':
    nb_bits = 32  # -> 32-bit wav files
max_nb_bit = float(2 ** (nb_bits - 1))
samples = x / (max_nb_bit + 1)  # samples is a numpy array of floats representing the samples 

Java: Literal percent sign in printf statement

Escaped percent sign is double percent (%%):

System.out.printf("2 out of 10 is %d%%", 20);

How to set cornerRadius for only top-left and top-right corner of a UIView?

Try this code,

UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:( UIRectCornerTopLeft | UIRectCornerTopRight) cornerRadii:CGSizeMake(5.0, 5.0)];

CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = self.view.bounds;
maskLayer.path  = maskPath.CGPath;

view.layer.mask = maskLayer;

Convert JSON String to JSON Object c#

there's an interesting way to achive another goal which is to have a strongly type class base on json with a very powerfull tools that i used few days ago for first time to translate tradedoubler json result into classes

Is a simple tool: copy your json source paste and in few second you will have a strongly typed class json oriented . In this manner you will use these classes which is more powerful and simply to use.

Getting rid of bullet points from <ul>

I had an identical problem.

The solution was that the bullet was added via a background image, NOT via list-style-type. A quick 'background: none' and Bob's your uncle!

self.tableView.reloadData() not working in Swift

You'll need to reload the table on the UI thread via:

//swift 2.3
dispatch_async(dispatch_get_main_queue(), { () -> Void in
    self.tableView.reloadData()
})

//swift 5
DispatchQueue.main.async{
    self.tableView.reloadData()
}

Follow up: An easier alternative to the connection.start() approach is to instead use NSURLConnection.sendAsynchronousRequest(...)

//NSOperationQueue.mainQueue() is the main thread
NSURLConnection.sendAsynchronousRequest(NSURLRequest(URL: url), queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in
    //check error
    var jsonError: NSError?
    let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &jsonError)
    //check jsonError
    self.collectionView?.reloadData()
}

This doesn't allow you the flexibility of tracking the bytes though, for example you might want to calculate the progress of the download via bytesDownloaded/bytesNeeded

XAMPP - Port 80 in use by "Unable to open process" with PID 4! 12

If you've SQLServer Reporting Services running locally then you need to stop that also..

Using Javamail to connect to Gmail smtp server ignores specified port and tries to use 25

For anyone looking for a full solution, I got this working with the following code based on maximdim's answer:

import javax.mail.*
import javax.mail.internet.*

private class SMTPAuthenticator extends Authenticator
{
    public PasswordAuthentication getPasswordAuthentication()
    {
        return new PasswordAuthentication('[email protected]', 'test1234');
    }
}

def  d_email = "[email protected]",
        d_uname = "email",
        d_password = "password",
        d_host = "smtp.gmail.com",
        d_port  = "465", //465,587
        m_to = "[email protected]",
        m_subject = "Testing",
        m_text = "Hey, this is the testing email."

def props = new Properties()
props.put("mail.smtp.user", d_email)
props.put("mail.smtp.host", d_host)
props.put("mail.smtp.port", d_port)
props.put("mail.smtp.starttls.enable","true")
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.auth", "true")
props.put("mail.smtp.socketFactory.port", d_port)
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory")
props.put("mail.smtp.socketFactory.fallback", "false")

def auth = new SMTPAuthenticator()
def session = Session.getInstance(props, auth)
session.setDebug(true);

def msg = new MimeMessage(session)
msg.setText(m_text)
msg.setSubject(m_subject)
msg.setFrom(new InternetAddress(d_email))
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to))

Transport transport = session.getTransport("smtps");
transport.connect(d_host, 465, d_uname, d_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();

uncaught syntaxerror unexpected token U JSON

The parameter for the JSON.parse may be returning nothing (i.e. the value given for the JSON.parse is undefined)!

It happened to me while I was parsing the Compiled solidity code from an xyz.sol file.

import web3 from './web3';
import xyz from './build/xyz.json';

const i = new web3.eth.Contract(
  JSON.parse(xyz.interface),
  '0x99Fd6eFd4257645a34093E657f69150FEFf7CdF5'
);

export default i;

which was misspelled as

JSON.parse(xyz.intereface)

which was returning nothing!

How exactly does __attribute__((constructor)) work?

  1. It runs when a shared library is loaded, typically during program startup.
  2. That's how all GCC attributes are; presumably to distinguish them from function calls.
  3. GCC-specific syntax.
  4. Yes, this works in C and C++.
  5. No, the function does not need to be static.
  6. The destructor runs when the shared library is unloaded, typically at program exit.

So, the way the constructors and destructors work is that the shared object file contains special sections (.ctors and .dtors on ELF) which contain references to the functions marked with the constructor and destructor attributes, respectively. When the library is loaded/unloaded the dynamic loader program (ld.so or somesuch) checks whether such sections exist, and if so, calls the functions referenced therein.

Come to think of it, there is probably some similar magic in the normal static linker so that the same code is run on startup/shutdown regardless if the user chooses static or dynamic linking.

How should I multiple insert multiple records?

You should execute the command on every loop instead of building a huge command Text(btw,StringBuilder is made for this) The underlying Connection will not close and re-open for each loop, let the connection pool manager handle this. Have a look at this link for further informations: Tuning Up ADO.NET Connection Pooling in ASP.NET Applications

If you want to ensure that every command is executed successfully you can use a Transaction and Rollback if needed,

HTTP Basic Authentication credentials passed in URL and encryption

Yes, it will be encrypted.

You'll understand it if you simply check what happens behind the scenes.

  1. The browser or application will first break down the URL and try to get the IP of the host using a DNS Query. ie: A DNS request will be made to find the IP address of the domain (www.example.com). Please note that no other information will be sent via this request.
  2. The browser or application will initiate a SSL connection with the IP address received from the DNS request. Certificates will be exchanged and this happens at the transport level. No application level information will be transferred at this point. Remember that the Basic authentication is part of HTTP and HTTP is an application level protocol. Not a transport layer task.
  3. After establishing the SSL connection, now the necessary data will be passed to the server. ie: The path or the URL, the parameters and basic authentication username and password.

Angular 2 Hover event

If you want to perform a hover like event on any HTML element, then you can do it like this.

HTML

 <div (mouseenter) ="mouseEnter('div a') "  (mouseleave) ="mouseLeave('div A')">
        <h2>Div A</h2>
 </div> 
 <div (mouseenter) ="mouseEnter('div b')"  (mouseleave) ="mouseLeave('div B')">
        <h2>Div B</h2>
 </div>

Component

import { Component } from '@angular/core';

@Component({
    moduleId: module.id,
    selector: 'basic-detail',
    templateUrl: 'basic.component.html',
})
export class BasicComponent{

   mouseEnter(div : string){
      console.log("mouse enter : " + div);
   }

   mouseLeave(div : string){
     console.log('mouse leave :' + div);
   }
}

You should use both mouseenter and mouseleave events inorder to implement fully functional hover events in angular 2.

git checkout master error: the following untracked working tree files would be overwritten by checkout

With Git 2.23 (August 2019), that would be, using git switch -f:

git switch -f master

That avoids the confusion with git checkout (which deals with files or branches).

And that will proceeds, even if the index or the working tree differs from HEAD.
Both the index and working tree are restored to match the switching target.
If --recurse-submodules is specified, submodule content is also restored to match the switching target.
This is used to throw away local changes.

jquery background-color change on focus and blur

Tested Code:

$("input").css("background","red");

Complete:

$('input:text').focus(function () {
    $(this).css({ 'background': 'Black' });
});

$('input:text').blur(function () {
    $(this).css({ 'background': 'red' });
});

Tested in version:

jquery-1.9.1.js
jquery-ui-1.10.3.js

Adding a right click menu to an item

This is a comprehensive answer to this question. I have done this because this page is high on the Google search results and the answer does not go into enough detail. This post assumes that you are competent at using Visual Studio C# forms. This is based on VS2012.

  1. Start by simply dragging a ContextMenuStrip onto the form. It will just put it into the top left corner where you can add your menu items and rename it as you see fit.

  2. You will have to view code and enter in an event yourself on the form. Create a mouse down event for the item in question and then assign a right click event for it like so (I have called the ContextMenuStrip "rightClickMenuStrip"):

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
    switch (e.Button)
        {
            case MouseButtons.Right:
            {
                rightClickMenuStrip.Show(this, new Point(e.X, e.Y));//places the menu at the pointer position
            }
            break;
        }
    }
    
  3. Assign the event handler manually to the form.designer (you may need to add a "using" for System.Windows.Forms; You can just resolve it):

    this.pictureBox1.MouseDown += new MouseEventHandler(this.pictureBox1_MouseDown);
    
  4. All that is needed at this point is to simply double click each menu item and do the desired operations for each click event in the same way you would for any other button.

This is the basic code for this operation. You can obviously modify it to fit in with your coding practices.

Convert a string to a datetime

Try to use DateTime.ParseExact method, in which you can specify both of datetime mask and original parsed string. You can read about it here: MSDN: DateTime.ParseExact

Responsive web design is working on desktop but not on mobile device

I have also faced this problem. Finally I got a solution. Use this bellow code. Hope: problem will be solve.

<meta name="viewport" content="initial-scale=1, maximum-scale=1">

Running a single test from unittest.TestCase via the command line

Inspired by yarkee, I combined it with some of the code I already got. You can also call this from another script, just by calling the function run_unit_tests() without requiring to use the command line, or just call it from the command line with python3 my_test_file.py.

import my_test_file
my_test_file.run_unit_tests()

Sadly this only works for Python 3.3 or above:

import unittest

class LineBalancingUnitTests(unittest.TestCase):

    @classmethod
    def setUp(self):
        self.maxDiff = None

    def test_it_is_sunny(self):
        self.assertTrue("a" == "a")

    def test_it_is_hot(self):
        self.assertTrue("a" != "b")

Runner code:

#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
from .somewhere import LineBalancingUnitTests

def create_suite(classes, unit_tests_to_run):
    suite = unittest.TestSuite()
    unit_tests_to_run_count = len( unit_tests_to_run )

    for _class in classes:
        _object = _class()
        for function_name in dir( _object ):
            if function_name.lower().startswith( "test" ):
                if unit_tests_to_run_count > 0 \
                        and function_name not in unit_tests_to_run:
                    continue
                suite.addTest( _class( function_name ) )
    return suite

def run_unit_tests():
    runner = unittest.TextTestRunner()
    classes =  [
        LineBalancingUnitTests,
    ]

    # Comment all the tests names on this list, to run all Unit Tests
    unit_tests_to_run =  [
        "test_it_is_sunny",
        # "test_it_is_hot",
    ]
    runner.run( create_suite( classes, unit_tests_to_run ) )

if __name__ == "__main__":
    print( "\n\n" )
    run_unit_tests()

Editing the code a little, you can pass an array with all unit tests you would like to call:

...
def run_unit_tests(unit_tests_to_run):
    runner = unittest.TextTestRunner()

    classes = \
    [
        LineBalancingUnitTests,
    ]

    runner.run( suite( classes, unit_tests_to_run ) )
...

And another file:

import my_test_file

# Comment all the tests names on this list, to run all unit tests
unit_tests_to_run = \
[
    "test_it_is_sunny",
    # "test_it_is_hot",
]

my_test_file.run_unit_tests( unit_tests_to_run )

Alternatively, you can use load_tests Protocol and define the following method in your test module/file:

def load_tests(loader, standard_tests, pattern):
    suite = unittest.TestSuite()

    # To add a single test from this file
    suite.addTest( LineBalancingUnitTests( 'test_it_is_sunny' ) )

    # To add a single test class from this file
    suite.addTests( unittest.TestLoader().loadTestsFromTestCase( LineBalancingUnitTests ) )

    return suite

If you want to limit the execution to one single test file, you just need to set the test discovery pattern to the only file where you defined the load_tests() function.

#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import unittest

test_pattern = 'mytest/module/name.py'
PACKAGE_ROOT_DIRECTORY = os.path.dirname( os.path.realpath( __file__ ) )

loader = unittest.TestLoader()
start_dir = os.path.join( PACKAGE_ROOT_DIRECTORY, 'testing' )

suite = loader.discover( start_dir, test_pattern )
runner = unittest.TextTestRunner( verbosity=2 )
results = runner.run( suite )

print( "results: %s" % results )
print( "results.wasSuccessful: %s" % results.wasSuccessful() )

sys.exit( not results.wasSuccessful() )

References:

  1. Problem with sys.argv[1] when unittest module is in a script
  2. Is there a way to loop through and execute all of the functions in a Python class?
  3. looping over all member variables of a class in python

Alternatively, to the last main program example, I came up with the following variation after reading the unittest.main() method implementation:

  1. https://github.com/python/cpython/blob/master/Lib/unittest/main.py#L65
#! /usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
import unittest

PACKAGE_ROOT_DIRECTORY = os.path.dirname( os.path.realpath( __file__ ) )
start_dir = os.path.join( PACKAGE_ROOT_DIRECTORY, 'testing' )

from testing_package import main_unit_tests_module
testNames = ["TestCaseClassName.test_nameHelloWorld"]

loader = unittest.TestLoader()
suite = loader.loadTestsFromNames( testNames, main_unit_tests_module )

runner = unittest.TextTestRunner(verbosity=2)
results = runner.run( suite )

print( "results: %s" % results )
print( "results.wasSuccessful: %s" % results.wasSuccessful() )
sys.exit( not results.wasSuccessful() )

Java int to String - Integer.toString(i) vs new Integer(i).toString()

Integer.toString calls the static method in the class Integer. It does not need an instance of Integer.

If you call new Integer(i) you create an instance of type Integer, which is a full Java object encapsulating the value of your int. Then you call the toString method on it to ask it to return a string representation of itself.

If all you want is to print an int, you'd use the first one because it's lighter, faster and doesn't use extra memory (aside from the returned string).

If you want an object representing an integer value—to put it inside a collection for example—you'd use the second one, since it gives you a full-fledged object to do all sort of things that you cannot do with a bare int.

"Full screen" <iframe>

Impossible to say without seeing a live example, but try giving both bodies margin: 0px

Can two or more people edit an Excel document at the same time?

Unfortunately, the file must be locked for updates unless you're using Office 2010 and SharePoint 2010 together. This means that only one user per time can edit a file. The locking and version tracking capabilities of SharePoint are excellent, and this makes it a great tool for the type of collaboration you're talking about, but you would have to split documents into multiple files in order to extend the amount that could be edited at a time. For instance, we sometimes unmerge documents into technical, requirements, and financials sections so that the 3 experts required for the review can work concurrently. We then merge when everyone is finished.

Play audio with Python

It's Simple. I did it this way.

For a wav file

from IPython.display import Audio
from scipy.io.wavfile import read

fs, data = read('StarWars60.wav', mmap=True)  # fs - sampling frequency
data = data.reshape(-1, 1)
Audio(data = data[:, 0], rate = fs)

For mp3 file

import IPython.display import Audio

Audio('audio_file_name.mp3')

Javascript setInterval not working

A lot of other answers are focusing on a pattern that does work, but their explanations aren't really very thorough as to why your current code doesn't work.

Your code, for reference:

function funcName() {
    alert("test");
}

var func = funcName();
var run = setInterval("func",10000)

Let's break this up into chunks. Your function funcName is fine. Note that when you call funcName (in other words, you run it) you will be alerting "test". But notice that funcName() -- the parentheses mean to "call" or "run" the function -- doesn't actually return a value. When a function doesn't have a return value, it defaults to a value known as undefined.

When you call a function, you append its argument list to the end in parentheses. When you don't have any arguments to pass the function, you just add empty parentheses, like funcName(). But when you want to refer to the function itself, and not call it, you don't need the parentheses because the parentheses indicate to run it.

So, when you say:

var func = funcName();

You are actually declaring a variable func that has a value of funcName(). But notice the parentheses. funcName() is actually the return value of funcName. As I said above, since funcName doesn't actually return any value, it defaults to undefined. So, in other words, your variable func actually will have the value undefined.

Then you have this line:

var run = setInterval("func",10000)

The function setInterval takes two arguments. The first is the function to be ran every so often, and the second is the number of milliseconds between each time the function is ran.

However, the first argument really should be a function, not a string. If it is a string, then the JavaScript engine will use eval on that string instead. So, in other words, your setInterval is running the following JavaScript code:

func
// 10 seconds later....
func
// and so on

However, func is just a variable (with the value undefined, but that's sort of irrelevant). So every ten seconds, the JS engine evaluates the variable func and returns undefined. But this doesn't really do anything. I mean, it technically is being evaluated every 10 seconds, but you're not going to see any effects from that.

The solution is to give setInterval a function to run instead of a string. So, in this case:

var run = setInterval(funcName, 10000);

Notice that I didn't give it func. This is because func is not a function in your code; it's the value undefined, because you assigned it funcName(). Like I said above, funcName() will call the function funcName and return the return value of the function. Since funcName doesn't return anything, this defaults to undefined. I know I've said that several times now, but it really is a very important concept: when you see funcName(), you should think "the return value of funcName". When you want to refer to a function itself, like a separate entity, you should leave off the parentheses so you don't call it: funcName.

So, another solution for your code would be:

var func = funcName;
var run = setInterval(func, 10000);

However, that's a bit redundant: why use func instead of funcName?

Or you can stay as true as possible to the original code by modifying two bits:

var func = funcName;
var run = setInterval("func()", 10000);

In this case, the JS engine will evaluate func() every ten seconds. In other words, it will alert "test" every ten seconds. However, as the famous phrase goes, eval is evil, so you should try to avoid it whenever possible.

Another twist on this code is to use an anonymous function. In other words, a function that doesn't have a name -- you just drop it in the code because you don't care what it's called.

setInterval(function () {
    alert("test");
}, 10000);

In this case, since I don't care what the function is called, I just leave a generic, unnamed (anonymous) function there.

Trying to get the average of a count resultset

You just can put your query as a subquery:

SELECT avg(count)
  FROM 
    (
    SELECT COUNT (*) AS Count
      FROM Table T
     WHERE T.Update_time =
               (SELECT MAX (B.Update_time )
                  FROM Table B
                 WHERE (B.Id = T.Id))
    GROUP BY T.Grouping
    ) as counts

Edit: I think this should be the same:

SELECT count(*) / count(distinct T.Grouping)
  FROM Table T
 WHERE T.Update_time =
           (SELECT MAX (B.Update_time)
              FROM Table B
             WHERE (B.Id = T.Id))

Concatenate a NumPy array to another NumPy array

Sven said it all, just be very cautious because of automatic type adjustments when append is called.

In [2]: import numpy as np

In [3]: a = np.array([1,2,3])

In [4]: b = np.array([1.,2.,3.])

In [5]: c = np.array(['a','b','c'])

In [6]: np.append(a,b)
Out[6]: array([ 1.,  2.,  3.,  1.,  2.,  3.])

In [7]: a.dtype
Out[7]: dtype('int64')

In [8]: np.append(a,c)
Out[8]: 
array(['1', '2', '3', 'a', 'b', 'c'], 
      dtype='|S1')

As you see based on the contents the dtype went from int64 to float32, and then to S1

Assigning default values to shell variables with a single command in bash

see here under 3.5.3(shell parameter expansion)

so in your case

${VARIABLE:-default}

How to securely save username/password (local)?

I wanted to encrypt and decrypt the string as a readable string.

Here is a very simple quick example in C# Visual Studio 2019 WinForms based on the answer from @Pradip.

Right click project > properties > settings > Create a username and password setting.

enter image description here

Now you can leverage those settings you just created. Here I save the username and password but only encrypt the password in it's respectable value field in the user.config file.

Example of the encrypted string in the user.config file.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <userSettings>
        <secure_password_store.Properties.Settings>
            <setting name="username" serializeAs="String">
                <value>admin</value>
            </setting>
            <setting name="password" serializeAs="String">
                <value>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAQpgaPYIUq064U3o6xXkQOQAAAAACAAAAAAAQZgAAAAEAACAAAABlQQ8OcONYBr9qUhH7NeKF8bZB6uCJa5uKhk97NdH93AAAAAAOgAAAAAIAACAAAAC7yQicDYV5DiNp0fHXVEDZ7IhOXOrsRUbcY0ziYYTlKSAAAACVDQ+ICHWooDDaUywJeUOV9sRg5c8q6/vizdq8WtPVbkAAAADciZskoSw3g6N9EpX/8FOv+FeExZFxsm03i8vYdDHUVmJvX33K03rqiYF2qzpYCaldQnRxFH9wH2ZEHeSRPeiG</value>
            </setting>
        </secure_password_store.Properties.Settings>
    </userSettings>
</configuration>

enter image description here

Full Code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace secure_password_store
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Exit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void Login_Click(object sender, EventArgs e)
        {
            if (checkBox1.Checked == true)
            {
                Properties.Settings.Default.username = textBox1.Text;
                Properties.Settings.Default.password = EncryptString(ToSecureString(textBox2.Text));
                Properties.Settings.Default.Save();
            }
            else if (checkBox1.Checked == false)
            {
                Properties.Settings.Default.username = "";
                Properties.Settings.Default.password = "";
                Properties.Settings.Default.Save();
            }
            MessageBox.Show("{\"data\": \"some data\"}","Login Message Alert",MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        private void DecryptString_Click(object sender, EventArgs e)
        {
            SecureString password = DecryptString(Properties.Settings.Default.password);
            string readable = ToInsecureString(password);
            textBox4.AppendText(readable + Environment.NewLine);
        }
        private void Form_Load(object sender, EventArgs e)
        {
            //textBox1.Text = "UserName";
            //textBox2.Text = "Password";
            if (Properties.Settings.Default.username != string.Empty)
            {
                textBox1.Text = Properties.Settings.Default.username;
                checkBox1.Checked = true;
                SecureString password = DecryptString(Properties.Settings.Default.password);
                string readable = ToInsecureString(password);
                textBox2.Text = readable;
            }
            groupBox1.Select();
        }


        static byte[] entropy = Encoding.Unicode.GetBytes("SaLtY bOy 6970 ePiC");

        public static string EncryptString(SecureString input)
        {
            byte[] encryptedData = ProtectedData.Protect(Encoding.Unicode.GetBytes(ToInsecureString(input)),entropy,DataProtectionScope.CurrentUser);
            return Convert.ToBase64String(encryptedData);
        }

        public static SecureString DecryptString(string encryptedData)
        {
            try
            {
                byte[] decryptedData = ProtectedData.Unprotect(Convert.FromBase64String(encryptedData),entropy,DataProtectionScope.CurrentUser);
                return ToSecureString(Encoding.Unicode.GetString(decryptedData));
            }
            catch
            {
                return new SecureString();
            }
        }

        public static SecureString ToSecureString(string input)
        {
            SecureString secure = new SecureString();
            foreach (char c in input)
            {
                secure.AppendChar(c);
            }
            secure.MakeReadOnly();
            return secure;
        }

        public static string ToInsecureString(SecureString input)
        {
            string returnValue = string.Empty;
            IntPtr ptr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(input);
            try
            {
                returnValue = System.Runtime.InteropServices.Marshal.PtrToStringBSTR(ptr);
            }
            finally
            {
                System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(ptr);
            }
            return returnValue;
        }

        private void EncryptString_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.password = EncryptString(ToSecureString(textBox2.Text));
            textBox3.AppendText(Properties.Settings.Default.password.ToString() + Environment.NewLine);
        }
    }
}

JavaFX - create custom button with image

You just need to create your own class inherited from parent. Place an ImageView on that, and on the mousedown and mouse up events just change the images of the ImageView.

public class ImageButton extends Parent {

    private static final Image NORMAL_IMAGE = ...;
    private static final Image PRESSED_IMAGE = ...;

    private final ImageView iv;

    public ImageButton() {
        this.iv = new ImageView(NORMAL_IMAGE);
        this.getChildren().add(this.iv);

        this.iv.setOnMousePressed(new EventHandler<MouseEvent>() {

            public void handle(MouseEvent evt) {
                iv.setImage(PRESSED_IMAGE);
            }

        });

        // TODO other event handlers like mouse up

    } 

}

Editing legend (text) labels in ggplot

The tutorial @Henrik mentioned is an excellent resource for learning how to create plots with the ggplot2 package.

An example with your data:

# transforming the data from wide to long
library(reshape2)
dfm <- melt(df, id = "TY")

# creating a scatterplot
ggplot(data = dfm, aes(x = TY, y = value, color = variable)) + 
  geom_point(size=5) +
  labs(title = "Temperatures\n", x = "TY [°C]", y = "Txxx", color = "Legend Title\n") +
  scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
  theme_bw() +
  theme(axis.text.x = element_text(size = 14), axis.title.x = element_text(size = 16),
        axis.text.y = element_text(size = 14), axis.title.y = element_text(size = 16),
        plot.title = element_text(size = 20, face = "bold", color = "darkgreen"))

this results in:

enter image description here

As mentioned by @user2739472 in the comments: If you only want to change the legend text labels and not the colours from ggplot's default palette, you can use scale_color_hue(labels = c("T999", "T888")) instead of scale_color_manual().

Numpy array dimensions

rows = a.shape[0] # 2 
cols = a.shape[1] # 2
a.shape #(2,2)
a.size # rows * cols = 4

How do I connect C# with Postgres?

Here is a walkthrough, Using PostgreSQL in your C# (.NET) application (An introduction):

In this article, I would like to show you the basics of using a PostgreSQL database in your .NET application. The reason why I'm doing this is the lack of PostgreSQL articles on CodeProject despite the fact that it is a very good RDBMS. I have used PostgreSQL back in the days when PHP was my main programming language, and I thought.... well, why not use it in my C# application.

Other than that you will need to give us some specific problems that you are having so that we can help diagnose the problem.

Inline labels in Matplotlib

A simpler approach like the one Ioannis Filippidis do :

import matplotlib.pyplot as plt
import numpy as np

# evenly sampled time at 200ms intervals
tMin=-1 ;tMax=10
t = np.arange(tMin, tMax, 0.1)

# red dashes, blue points default
plt.plot(t, 22*t, 'r--', t, t**2, 'b')

factor=3/4 ;offset=20  # text position in view  
textPosition=[(tMax+tMin)*factor,22*(tMax+tMin)*factor]
plt.text(textPosition[0],textPosition[1]+offset,'22  t',color='red',fontsize=20)
textPosition=[(tMax+tMin)*factor,((tMax+tMin)*factor)**2+20]
plt.text(textPosition[0],textPosition[1]+offset, 't^2', bbox=dict(facecolor='blue', alpha=0.5),fontsize=20)
plt.show()

code python 3 on sageCell

How do you push just a single Git branch (and no other branches)?

yes, just do the following

git checkout feature_x
git push origin feature_x

What are the lengths of Location Coordinates, latitude and longitude?

The ideal datatype for storing Lat Long values in SQL Server is decimal(9,6)

As others have said, this is at approximately 10cm precision, whilst only using 5 bytes of storage.

e.g. CAST(123.456789 as decimal(9,6)) as [LatOrLong]

combining results of two select statements

You can use a Union.

This will return the results of the queries in separate rows.

First you must make sure that both queries return identical columns.

Then you can do :

SELECT tableA.Id, tableA.Name, [tableB].Username AS Owner, [tableB].ImageUrl, [tableB].CompanyImageUrl, COUNT(tableD.UserId) AS Number
FROM tableD 
RIGHT OUTER JOIN [tableB] 
INNER JOIN tableA ON [tableB].Id = tableA.Owner ON tableD.tableAId = tableA.Id 
GROUP BY tableA.Name, [tableB].Username, [tableB].ImageUrl, [tableB].CompanyImageUrl

UNION

SELECT tableA.Id, tableA.Name,  '' AS Owner, '' AS ImageUrl, '' AS CompanyImageUrl, COUNT([tableC].Id) AS Number
FROM 
[tableC] 
RIGHT OUTER JOIN tableA ON [tableC].tableAId = tableA.Id GROUP BY tableA.Id, tableA.Name

As has been mentioned, both queries return quite different data. You would probably only want to do this if both queries return data that could be considered similar.

SO

You can use a Join

If there is some data that is shared between the two queries. This will put the results of both queries into a single row joined by the id, which is probably more what you want to be doing here...

You could do :

SELECT tableA.Id, tableA.Name, [tableB].Username AS Owner, [tableB].ImageUrl, [tableB].CompanyImageUrl, COUNT(tableD.UserId) AS NumberOfUsers, query2.NumberOfPlans
FROM tableD 
RIGHT OUTER JOIN [tableB] 
INNER JOIN tableA ON [tableB].Id = tableA.Owner ON tableD.tableAId = tableA.Id 


INNER JOIN 
  (SELECT tableA.Id, COUNT([tableC].Id) AS NumberOfPlans 
   FROM [tableC] 
   RIGHT OUTER JOIN tableA ON [tableC].tableAId = tableA.Id 
   GROUP BY tableA.Id, tableA.Name) AS query2 
ON query2.Id = tableA.Id

GROUP BY tableA.Name, [tableB].Username, [tableB].ImageUrl, [tableB].CompanyImageUrl

How do you convert a DataTable into a generic list?

With C# 3.0 and System.Data.DataSetExtensions.dll,

List<DataRow> rows = table.Rows.Cast<DataRow>().ToList();

How to set default text for a Tkinter Entry widget

Use Entry.insert. For example:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
e = Entry(root)
e.insert(END, 'default text')
e.pack()
root.mainloop()

Or use textvariable option:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
v = StringVar(root, value='default text')
e = Entry(root, textvariable=v)
e.pack()
root.mainloop()

How to set text color to a text view programmatically

TextView tt;
int color = Integer.parseInt("bdbdbd", 16)+0xFF000000;
tt.setTextColor(color);

also

tt.setBackgroundColor(Integer.parseInt("d4d446", 16)+0xFF000000);

also

tt.setBackgroundColor(Color.parseColor("#d4d446"));

see:

Java/Android String to Color conversion

Detect Scroll Up & Scroll down in ListView

I've used this much simpler solution:

setOnScrollListener( new OnScrollListener() 
{

    private int mInitialScroll = 0;

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
            int visibleItemCount, int totalItemCount) 
    {
        int scrolledOffset = computeVerticalScrollOffset();

        boolean scrollUp = scrolledOffset > mInitialScroll;
        mInitialScroll = scrolledOffset;
    }


    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {


    }

}

OS detecting makefile

I finally found the perfect solution that solves this problem for me.

ifeq '$(findstring ;,$(PATH))' ';'
    UNAME := Windows
else
    UNAME := $(shell uname 2>/dev/null || echo Unknown)
    UNAME := $(patsubst CYGWIN%,Cygwin,$(UNAME))
    UNAME := $(patsubst MSYS%,MSYS,$(UNAME))
    UNAME := $(patsubst MINGW%,MSYS,$(UNAME))
endif

The UNAME variable is set to Linux, Cygwin, MSYS, Windows, FreeBSD, NetBSD (or presumably Solaris, Darwin, OpenBSD, AIX, HP-UX), or Unknown. It can then be compared throughout the remainder of the Makefile to separate any OS-sensitive variables and commands.

The key is that Windows uses semicolons to separate paths in the PATH variable whereas everyone else uses colons. (It's possible to make a Linux directory with a ';' in the name and add it to PATH, which would break this, but who would do such a thing?) This seems to be the least risky method to detect native Windows because it doesn't need a shell call. The Cygwin and MSYS PATH use colons so uname is called for them.

Note that the OS environment variable can be used to detect Windows, but not to distinguish between Cygwin and native Windows. Testing for the echoing of quotes works, but it requires a shell call.

Unfortunately, Cygwin adds some version information to the output of uname, so I added the 'patsubst' calls to change it to just 'Cygwin'. Also, uname for MSYS actually has three possible outputs starting with MSYS or MINGW, but I use also patsubst to transform all to just 'MSYS'.

If it's important to distinguish between native Windows systems with and without some uname.exe on the path, this line can be used instead of the simple assignment:

UNAME := $(shell uname 2>NUL || echo Windows)

Of course in all cases GNU make is required, or another make which supports the functions used.

Using dig to search for SPF records

I believe that I found the correct answer through this dig How To. I was able to look up the SPF records on a specific DNS, by using the following query:

dig @ns1.nameserver1.com domain.com txt

How to check if a windows form is already open, and close it if it is?

Try this, it will work :

//inside main class
Form1 Fm1 = new Form1();<br>

//in button click
if (Fm1.IsDisposed)
{
    Fm1 = new Form();
}
Fm1.Show();
Fm1.BringToFront();
Fm1.Activate();

Media Player called in state 0, error (-38,0)

You get this message in the logs, because you do something that is not allowed in the current state of your MediaPlayer instance.

Therefore you should always register an error handler to catch those things (as @tidbeck suggested).

At first, I advice you to take a look at the documentation for the MediaPlayer class and get an understanding of what that with states means. See: http://developer.android.com/reference/android/media/MediaPlayer.html#StateDiagram

Your mistake here could well be one of the common ones, the others wrote here, but in general, I would take a look at the documentation of what methods are valid to call in what state: http://developer.android.com/reference/android/media/MediaPlayer.html#Valid_and_Invalid_States

In my example it was the method mediaPlayer.CurrentPosition, that I called while the media player was in a state, where it was not allowed to call this property.

Pygame mouse clicking detection

I was looking for the same answer to this question and after much head scratching this is the answer I came up with:

#Python 3.4.3 with Pygame
import pygame

pygame.init()
pygame.display.set_caption('Crash!')
window = pygame.display.set_mode((300, 300))


# Draw Once
Rectplace = pygame.draw.rect(window, (255, 0, 0),(100, 100, 100, 100))
pygame.display.update()
# Main Loop
while True:
    # Mouse position and button clicking.
    pos = pygame.mouse.get_pos()
    pressed1, pressed2, pressed3 = pygame.mouse.get_pressed()
    # Check if the rect collided with the mouse pos
    # and if the left mouse button was pressed.
    if Rectplace.collidepoint(pos) and pressed1:
        print("You have opened a chest!")
    # Quit pygame.
            for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit(1)

ios app maximum memory budget

In my app, user experience is better if more memory is used, so I have to decide if I really should free all the memory I can in didReceiveMemoryWarning. Based on Split's and Jasper Pol's answer, using a maximum of 45% of the total device memory appears to be a safe threshold (thanks guys).

In case someone wants to look at my actual implementation:

#import "mach/mach.h"

- (void)didReceiveMemoryWarning
{
    // Remember to call super
    [super didReceiveMemoryWarning];

    // If we are using more than 45% of the memory, free even important resources,
    // because the app might be killed by the OS if we don't
    if ([self __getMemoryUsedPer1] > 0.45)
    {
        // Free important resources here
    }

    // Free regular unimportant resources always here
}

- (float)__getMemoryUsedPer1
{
    struct mach_task_basic_info info;
    mach_msg_type_number_t size = sizeof(info);
    kern_return_t kerr = task_info(mach_task_self(), MACH_TASK_BASIC_INFO, (task_info_t)&info, &size);
    if (kerr == KERN_SUCCESS)
    {
        float used_bytes = info.resident_size;
        float total_bytes = [NSProcessInfo processInfo].physicalMemory;
        //NSLog(@"Used: %f MB out of %f MB (%f%%)", used_bytes / 1024.0f / 1024.0f, total_bytes / 1024.0f / 1024.0f, used_bytes * 100.0f / total_bytes);
        return used_bytes / total_bytes;
    }
    return 1;
}

Swift (based on this answer):

func __getMemoryUsedPer1() -> Float
{
    let MACH_TASK_BASIC_INFO_COUNT = (sizeof(mach_task_basic_info_data_t) / sizeof(natural_t))
    let name = mach_task_self_
    let flavor = task_flavor_t(MACH_TASK_BASIC_INFO)
    var size = mach_msg_type_number_t(MACH_TASK_BASIC_INFO_COUNT)
    var infoPointer = UnsafeMutablePointer<mach_task_basic_info>.alloc(1)
    let kerr = task_info(name, flavor, UnsafeMutablePointer(infoPointer), &size)
    let info = infoPointer.move()
    infoPointer.dealloc(1)
    if kerr == KERN_SUCCESS
    {
        var used_bytes: Float = Float(info.resident_size)
        var total_bytes: Float = Float(NSProcessInfo.processInfo().physicalMemory)
        println("Used: \(used_bytes / 1024.0 / 1024.0) MB out of \(total_bytes / 1024.0 / 1024.0) MB (\(used_bytes * 100.0 / total_bytes)%%)")
        return used_bytes / total_bytes
    }
    return 1
}

What is the easiest way to parse an INI file in Java?

Here's a simple, yet powerful example, using the apache class HierarchicalINIConfiguration:

HierarchicalINIConfiguration iniConfObj = new HierarchicalINIConfiguration(iniFile); 

// Get Section names in ini file     
Set setOfSections = iniConfObj.getSections();
Iterator sectionNames = setOfSections.iterator();

while(sectionNames.hasNext()){

 String sectionName = sectionNames.next().toString();

 SubnodeConfiguration sObj = iniObj.getSection(sectionName);
 Iterator it1 =   sObj.getKeys();

    while (it1.hasNext()) {
    // Get element
    Object key = it1.next();
    System.out.print("Key " + key.toString() +  " Value " +  
                     sObj.getString(key.toString()) + "\n");
}

Commons Configuration has a number of runtime dependencies. At a minimum, commons-lang and commons-logging are required. Depending on what you're doing with it, you may require additional libraries (see previous link for details).

Python: How would you save a simple settings/config file?

If you want to use something like an INI file to hold settings, consider using configparser which loads key value pairs from a text file, and can easily write back to the file.

INI file has the format:

[Section]
key = value
key with spaces = somevalue

Verifying that a string contains only letters in C#

Please find the method to validate if char is letter, number or space, otherwise attach underscore (Be free to modified according your needs)

public String CleanStringToLettersNumbers(String data)
{
    var result = String.Empty;

    foreach (var item in data)
    {
        var c = '_';

        if ((int)item >= 97 && (int)item <= 122 ||
            (int)item >= 65 && (int)item <= 90 ||
            (int)item >= 48 && (int)item <= 57 ||
            (int)item == 32)
        {
            c = item;
        }

        result = result + c;
    }

    return result;
}

How to set image in circle in swift

First you need to set equal width and height for getting Circular ImageView.Below I set width and height as 100,100.If you want to set equal width and height according to your required size,set here.

 var imageCircle = UIImageView(frame: CGRectMake(0, 0, 100, 100))

Then you need to set height/2 for corner radius

 imageCircle.layer.cornerRadius = imageCircle.frame.size.height/2
 imageCircle.layer.borderWidth = 1
 imageCircle.layer.borderColor = UIColor.blueColor().CGColor
 imageCircle.clipsToBounds = true
 self.view.addSubview(imageCircle)

Android: keep Service running when app is killed

inside onstart command put START_STICKY... This service won't kill unless it is doing too much task and kernel wants to kill it for it...

@Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            Log.i("LocalService", "Received start id " + startId + ": " + intent);
            // We want this service to continue running until it is explicitly
            // stopped, so return sticky.
            return START_STICKY;
        }

add a string prefix to each value in a string column using Pandas

As an alternative, you can also use an apply combined with format (or better with f-strings) which I find slightly more readable if one e.g. also wants to add a suffix or manipulate the element itself:

df = pd.DataFrame({'col':['a', 0]})

df['col'] = df['col'].apply(lambda x: "{}{}".format('str', x))

which also yields the desired output:

    col
0  stra
1  str0

If you are using Python 3.6+, you can also use f-strings:

df['col'] = df['col'].apply(lambda x: f"str{x}")

yielding the same output.

The f-string version is almost as fast as @RomanPekar's solution (python 3.6.4):

df = pd.DataFrame({'col':['a', 0]*200000})

%timeit df['col'].apply(lambda x: f"str{x}")
117 ms ± 451 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit 'str' + df['col'].astype(str)
112 ms ± 1.04 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Using format, however, is indeed far slower:

%timeit df['col'].apply(lambda x: "{}{}".format('str', x))
185 ms ± 1.07 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Form inside a table

If you want a "editable grid" i.e. a table like structure that allows you to make any of the rows a form, use CSS that mimics the TABLE tag's layout: display:table, display:table-row, and display:table-cell.

There is no need to wrap your whole table in a form and no need to create a separate form and table for each apparent row of your table.

Try this instead:

<style>
DIV.table 
{
    display:table;
}
FORM.tr, DIV.tr
{
    display:table-row;
}
SPAN.td
{
    display:table-cell;
}
</style>
...
<div class="table">
    <form class="tr" method="post" action="blah.html">
        <span class="td"><input type="text"/></span>
        <span class="td"><input type="text"/></span>
    </form>
    <div class="tr">
        <span class="td">(cell data)</span>
        <span class="td">(cell data)</span>
    </div>
    ...
</div>

The problem with wrapping the whole TABLE in a FORM is that any and all form elements will be sent on submit (maybe that is desired but probably not). This method allows you to define a form for each "row" and send only that row of data on submit.

The problem with wrapping a FORM tag around a TR tag (or TR around a FORM) is that it's invalid HTML. The FORM will still allow submit as usual but at this point the DOM is broken. Note: Try getting the child elements of your FORM or TR with JavaScript, it can lead to unexpected results.

Note that IE7 doesn't support these CSS table styles and IE8 will need a doctype declaration to get it into "standards" mode: (try this one or something equivalent)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Any other browser that supports display:table, display:table-row and display:table-cell should display your css data table the same as it would if you were using the TABLE, TR and TD tags. Most of them do.

Note that you can also mimic THEAD, TBODY, TFOOT by wrapping your row groups in another DIV with display: table-header-group, table-row-group and table-footer-group respectively.

NOTE: The only thing you cannot do with this method is colspan.

Check out this illustration: http://jsfiddle.net/ZRQPP/

How can I convert the "arguments" object to an array in JavaScript?

In ECMAScript 6 there's no need to use ugly hacks like Array.prototype.slice(). You can instead use spread syntax (...).

_x000D_
_x000D_
(function() {_x000D_
  console.log([...arguments]);_x000D_
}(1, 2, 3))
_x000D_
_x000D_
_x000D_

It may look strange, but it's fairly simple. It just extracts arguments' elements and put them back into the array. If you still don't understand, see this examples:

_x000D_
_x000D_
console.log([1, ...[2, 3], 4]);_x000D_
console.log([...[1, 2, 3]]);_x000D_
console.log([...[...[...[1]]]]);
_x000D_
_x000D_
_x000D_

Note that it doesn't work in some older browsers like IE 11, so if you want to support these browsers, you should use Babel.

How is "mvn clean install" different from "mvn install"?

To stick with the Maven terms:

  • "clean" is a phase of the clean lifecycle
  • "install" is a phase of the default lifecycle

http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html#Lifecycle_Reference

How to add a char/int to an char array in C?

In C/C++ a string is an array of char terminated with a NULL byte ('\0');

  1. Your string str has not been initialized.
  2. You must concatenate strings and you are trying to concatenate a single char (without the null byte so it's not a string) to a string.

The code should look like this:

char str[1024] = "Hello World"; //this will add all characters and a NULL byte to the array
char tmp[2] = "."; //this is a string with the dot 
strcat(str, tmp);  //here you concatenate the two strings

Note that you can assign a string literal to an array only during its declaration.
For example the following code is not permitted:

char str[1024];
str = "Hello World"; //FORBIDDEN

and should be replaced with

char str[1024];
strcpy(str, "Hello World"); //here you copy "Hello World" inside the src array 

Giving my function access to outside variable

$myArr = array();

function someFuntion(array $myArr) {
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;

    return $myArr;
}

$myArr = someFunction($myArr);

.NET: Simplest way to send POST with data and read response

Personally, I think the simplest approach to do an http post and get the response is to use the WebClient class. This class nicely abstracts the details. There's even a full code example in the MSDN documentation.

http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.80).aspx

In your case, you want the UploadData() method. (Again, a code sample is included in the documentation)

http://msdn.microsoft.com/en-us/library/tdbbwh0a(VS.80).aspx

UploadString() will probably work as well, and it abstracts it away one more level.

http://msdn.microsoft.com/en-us/library/system.net.webclient.uploadstring(VS.80).aspx

Can I set a breakpoint on 'memory access' in GDB?

What you're looking for is called a watchpoint.

Usage

(gdb) watch foo: watch the value of variable foo

(gdb) watch *(int*)0x12345678: watch the value pointed by an address, casted to whatever type you want

(gdb) watch a*b + c/d: watch an arbitrarily complex expression, valid in the program's native language

Watchpoints are of three kinds:

  • watch: gdb will break when a write occurs
  • rwatch: gdb will break wnen a read occurs
  • awatch: gdb will break in both cases

You may choose the more appropriate for your needs.

For more information, check this out.

How to validate a form with multiple checkboxes to have atleast one checked

The above addMethod by Lod Lawson is not completely correct. It's $.validator and not $.validate and the validator method name cb_selectone requires quotes. Here is a corrected version that I tested:

$.validator.addMethod('cb_selectone', function(value,element){
    if(element.length>0){
        for(var i=0;i<element.length;i++){
            if($(element[i]).val('checked')) return true;
        }
        return false;
    }
    return false;
}, 'Please select at least one option');

Want to move a particular div to right

This will do the job:

_x000D_
_x000D_
<div style="position:absolute; right:0;">Hello world</div>
_x000D_
_x000D_
_x000D_

Call asynchronous method in constructor?

I'd like to share a pattern that I've been using to solve these kinds of problems. It works rather well I think. Of course, it only works if you have control over what calls the constructor. Example below

public class MyClass
{
    public static async Task<MyClass> Create()
    {
        var myClass = new MyClass();
        await myClass.Initialize();
        return myClass;
    }

    private MyClass()
    {

    }

    private async Task Initialize()
    {
        await Task.Delay(1000); // Do whatever asynchronous work you need to do
    }
}

Basicly what we do is we make the constructor private and make our own public static async method that is responsible for creating an instance of MyClass. By making the constructor private and keeping the static method within the same class we have made sure that noone could "accidently" create an instance of this class without calling the proper initialization methods. All the logic around the creation of the object is still contained within the class (just within a static method).

var myClass1 = new MyClass() // Cannot be done, the constructor is private
var myClass2 = MyClass.Create() // Returns a Task that promises an instance of MyClass once it's finished
var myClass3 = await MyClass.Create() // asynchronously creates and initializes an instance of MyClass

Implemented on the current scenario it would look something like:

public partial class Page2 : PhoneApplicationPage
{
    public static async Task<Page2> Create()
    {
        var page = new Page2();
        await page.getWritings();
        return page;
    }

    List<Writing> writings;

    private Page2()
    {
        InitializeComponent();
    }

    private async Task getWritings()
    {
        string jsonData = await JsonDataManager.GetJsonAsync("1");
        JObject obj = JObject.Parse(jsonData);
        JArray array = (JArray)obj["posts"];

        for (int i = 0; i < array.Count; i++)
        {
            Writing writing = new Writing();
            writing.content = JsonDataManager.JsonParse(array, i, "content");
            writing.date = JsonDataManager.JsonParse(array, i, "date");
            writing.image = JsonDataManager.JsonParse(array, i, "url");
            writing.summary = JsonDataManager.JsonParse(array, i, "excerpt");
            writing.title = JsonDataManager.JsonParse(array, i, "title");

            writings.Add(writing);
        }

        myLongList.ItemsSource = writings;
    }
}

And instead of doing

var page = new Page2();

You would be doing

var page = await Page2.Create();

How line ending conversions work with git core.autocrlf between different operating systems

The issue of EOLs in mixed-platform projects has been making my life miserable for a long time. The problems usually arise when there are already files with different and mixed EOLs already in the repo. This means that:

  1. The repo may have different files with different EOLs
  2. Some files in the repo may have mixed EOL, e.g. a combination of CRLF and LF in the same file.

How this happens is not the issue here, but it does happen.

I ran some conversion tests on Windows for the various modes and their combinations.
Here is what I got, in a slightly modified table:

                 | Resulting conversion when       | Resulting conversion when 
                 | committing files with various   | checking out FROM repo - 
                 | EOLs INTO repo and              | with mixed files in it and
                 |  core.autocrlf value:           | core.autocrlf value:           
--------------------------------------------------------------------------------
File             | true       | input      | false | true       | input | false
--------------------------------------------------------------------------------
Windows-CRLF     | CRLF -> LF | CRLF -> LF | as-is | as-is      | as-is | as-is
Unix -LF         | as-is      | as-is      | as-is | LF -> CRLF | as-is | as-is
Mac  -CR         | as-is      | as-is      | as-is | as-is      | as-is | as-is
Mixed-CRLF+LF    | as-is      | as-is      | as-is | as-is      | as-is | as-is
Mixed-CRLF+LF+CR | as-is      | as-is      | as-is | as-is      | as-is | as-is

As you can see, there are 2 cases when conversion happens on commit (3 left columns). In the rest of the cases the files are committed as-is.

Upon checkout (3 right columns), there is only 1 case where conversion happens when:

  1. core.autocrlf is true and
  2. the file in the repo has the LF EOL.

Most surprising for me, and I suspect, the cause of many EOL problems is that there is no configuration in which mixed EOL like CRLF+LF get normalized.

Note also that "old" Mac EOLs of CR only also never get converted.
This means that if a badly written EOL conversion script tries to convert a mixed ending file with CRLFs+LFs, by just converting LFs to CRLFs, then it will leave the file in a mixed mode with "lonely" CRs wherever a CRLF was converted to CRCRLF.
Git will then not convert anything, even in true mode, and EOL havoc continues. This actually happened to me and messed up my files really badly, since some editors and compilers (e.g. VS2010) don't like Mac EOLs.

I guess the only way to really handle these problems is to occasionally normalize the whole repo by checking out all the files in input or false mode, running a proper normalization and re-committing the changed files (if any). On Windows, presumably resume working with core.autocrlf true.

'invalid value encountered in double_scalars' warning, possibly numpy

I encount this while I was calculating np.var(np.array([])). np.var will divide size of the array which is zero in this case.

Java better way to delete file if exists

Use Apache Commons FileUtils.deleteDirectory() or FileUtils.forceDelete() to log exceptions in case of any failures,

or FileUtils.deleteQuietly() if you're not concerned about exceptions thrown.

Chrome says "Resource interpreted as script but transferred with MIME type text/plain.", what gives?

If you are using Spring MVC, you can add following mvn tag to exclude resources file from Spring Dispatch Servlet

<mvc:resources mapping="/js/*.js" location="/js/"/>
<mvc:resources mapping="/css/*.css" location="/css/"/>
<mvc:resources mapping="/images/*.*" location="/images/"/>

Jenkins / Hudson environment variables

Michael,

Two things:

When Jenkins connects to a computer, it goes to the sh shell, and not the bash shell (at least this is what I have noticed - I may be wrong). So any changes you make to $PATH in your bashrc file are not considered.

Also, any changes you make to $PATH in your local shell (one that you personally ssh into) will not show up in Jenkins.

To change the path that Jenkins uses, you have two options (AFAIK):

1) Edit your /etc/profile file and add the paths that you want there

2) Go to the configuration page of your slave, and add environment variable PATH, with value: $PATH:/followed-by/paths/you/want/to/add

If you use the second option, your System Information will still not show it, but your builds will see the added paths.

Want to show/hide div based on dropdown box selection

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
    $('#purpose').on('change', function() {
      if ( this.value == '1')
      //.....................^.......
      {
           $("#business_new").hide();
        $("#business").show();
      }
      else  if ( this.value == '2')
      {
          $("#business").hide();
        $("#business_new").show();
      }
       else  
      {
        $("#business").hide();
      }
    });
});
</script>
<body>
<select id='purpose'>
<option value="0">Personal use</option>
<option value="1">Business use</option>
<option value="2">Passing on to a client</option>
</select>
<div style='display:none;' id='business'>Business Name<br/>&nbsp;
<br/>&nbsp;
    <input type='text' class='text' name='business' value size='20' />
    <input type='text' class='text' name='business' value size='20' />
    <br/>
</div>
<div style='display:none;' id='business_new'>Business Name<br/>&nbsp;
<br/>&nbsp;
    <input type='text' class='text' name='business' value="1254" size='20' />
    <input type='text' class='text' name='business' value size='20' />
    <br/>
</div>
</body>

How to delete the first row of a dataframe in R?

No one probably really wants to remove row one. So if you are looking for something meaningful, that is conditional selection

#remove rows that have long length and "0" value for vector E

>> setNew<-set[!(set$length=="long" & set$E==0),]

C# Parsing JSON array of objects

I have just got an solution a little bit easier do get an list out of an JSON object. Hope this can help.

I got an JSON like this:

{"Accounts":"[{\"bank\":\"Itau\",\"account\":\"456\",\"agency\":\"0444\",\"digit\":\"5\"}]"}

And made some types like this

    public class FinancialData
{
    public string Accounts { get; set; } // this will store the JSON string
    public List<Accounts> AccountsList { get; set; } // this will be the actually list. 
}

    public class Accounts
{
    public string bank { get; set; }
    public string account { get; set; }
    public string agency { get; set; }
    public string digit { get; set; }

}

and the "magic" part

 Models.FinancialData financialData = (Models.FinancialData)JsonConvert.DeserializeObject(myJSON,typeof(Models.FinancialData));
        var accounts = JsonConvert.DeserializeObject(financialData.Accounts) as JArray;

        foreach (var account in  accounts)
        {
            if (financialData.AccountsList == null)
            {
                financialData.AccountsList = new List<Models.Accounts>();
            }

            financialData.AccountsList.Add(JsonConvert.DeserializeObject<Models.Accounts>(account.ToString()));
        }

What is web.xml file and what are all things can I do with it?

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet>
    <description></description>
    <display-name>pdfServlet</display-name>
    <servlet-name>pdfServlet</servlet-name>
    <servlet-class>com.sapta.smartcam.servlet.pdfServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>pdfServlet</servlet-name>
    <url-pattern>/pdfServlet</url-pattern>
  </servlet-mapping>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

insert datetime value in sql database with c#

The following should work and is my recommendation (parameterized query):

DateTime dateTimeVariable = //some DateTime value, e.g. DateTime.Now;
SqlCommand cmd = new SqlCommand("INSERT INTO <table> (<column>) VALUES (@value)", connection);
cmd.Parameters.AddWithValue("@value", dateTimeVariable);

cmd.ExecuteNonQuery();

Difference between "managed" and "unmanaged"

Managed Code

Managed code is what Visual Basic .NET and C# compilers create. It runs on the CLR (Common Language Runtime), which, among other things, offers services like garbage collection, run-time type checking, and reference checking. So, think of it as, "My code is managed by the CLR."

Visual Basic and C# can only produce managed code, so, if you're writing an application in one of those languages you are writing an application managed by the CLR. If you are writing an application in Visual C++ .NET you can produce managed code if you like, but it's optional.

Unmanaged Code

Unmanaged code compiles straight to machine code. So, by that definition all code compiled by traditional C/C++ compilers is 'unmanaged code'. Also, since it compiles to machine code and not an intermediate language it is non-portable.

No free memory management or anything else the CLR provides.

Since you cannot create unmanaged code with Visual Basic or C#, in Visual Studio all unmanaged code is written in C/C++.

Mixing the two

Since Visual C++ can be compiled to either managed or unmanaged code it is possible to mix the two in the same application. This blurs the line between the two and complicates the definition, but it's worth mentioning just so you know that you can still have memory leaks if, for example, you're using a third party library with some badly written unmanaged code.

Here's an example I found by googling:

#using <mscorlib.dll>
using namespace System;

#include "stdio.h"

void ManagedFunction()
{
    printf("Hello, I'm managed in this section\n");
}

#pragma unmanaged
UnmanagedFunction()
{
    printf("Hello, I am unmanaged through the wonder of IJW!\n");
    ManagedFunction();
}

#pragma managed
int main()
{
    UnmanagedFunction();
    return 0;
}

Change EditText hint color when using TextInputLayout

You must set hint color on TextInputLayout.

gpg: no valid OpenPGP data found

In my case, the problem turned out to be that the keyfile was behind a 301 Moved Permanently redirect, which the curl command failed to follow. I fixed it by using wget instead:

wget URL
sudo apt-key add FILENAME

...where FILENAME is the file name that wget outputs after it downloads the file.

Update: Alternatively, you can use curl -L to make curl follow redirects.

Mailbox unavailable. The server response was: 5.7.1 Unable to relay Error

The default configuration of most SMTP servers is not to relay from an untrusted source to outside domains. For example, imagine that you contact the SMTP server for foo.com and ask it to send a message to [email protected]. Because the SMTP server doesn't really know who you are, it will refuse to relay the message. If the server did do that for you, it would be considered an open relay, which is how spammers often do their thing.

If you contact the foo.com mail server and ask it to send mail to [email protected], it might let you do it. It depends on if they trust that you're who you say you are. Often, the server will try to do a reverse DNS lookup, and refuse to send mail if the IP you're sending from doesn't match the IP address of the MX record in DNS. So if you say that you're the bar.com mail server but your IP address doesn't match the MX record for bar.com, then it will refuse to deliver the message.

You'll need to talk to the administrator of that SMTP server to get the authentication information so that it will allow relay for you. You'll need to present those credentials when you contact the SMTP server. Usually it's either a user name/password, or it can use Windows permissions. Depends on the server and how it's configured.

See Unable to send emails to external domain using SMTP for an example of how to send the credentials.

What is the purpose of the var keyword and when should I use it (or omit it)?

I see people are confused when declaring variables with or without var and inside or outside the function. Here is a deep example that will walk you through these steps:

See the script below in action here at jsfiddle

a = 1;// Defined outside the function without var
var b = 1;// Defined outside the function with var
alert("Starting outside of all functions... \n \n a, b defined but c, d not defined yet: \n a:" + a + "\n b:" + b + "\n \n (If I try to show the value of the undefined c or d, console.log would throw 'Uncaught ReferenceError: c is not defined' error and script would stop running!)");

function testVar1(){
    c = 1;// Defined inside the function without var
    var d = 1;// Defined inside the function with var
    alert("Now inside the 1. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);

    a = a + 5;
    b = b + 5;
    c = c + 5;
    d = d + 5;

    alert("After added values inside the 1. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);
};


testVar1();
alert("Run the 1. function again...");
testVar1();

function testVar2(){
    var d = 1;// Defined inside the function with var
    alert("Now inside the 2. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);

    a = a + 5;
    b = b + 5;
    c = c + 5;
    d = d + 5;

    alert("After added values inside the 2. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);
};

testVar2();

alert("Now outside of all functions... \n \n Final Values: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n You will not be able to see d here because then the value is requested, console.log would throw error 'Uncaught ReferenceError: d is not defined' and script would stop. \n ");
alert("**************\n Conclusion \n ************** \n \n 1. No matter declared with or without var (like a, b) if they get their value outside the function, they will preserve their value and also any other values that are added inside various functions through the script are preserved.\n 2. If the variable is declared without var inside a function (like c), it will act like the previous rule, it will preserve its value across all functions from now on. Either it got its first value in function testVar1() it still preserves the value and get additional value in function testVar2() \n 3. If the variable is declared with var inside a function only (like d in testVar1 or testVar2) it will will be undefined whenever the function ends. So it will be temporary variable in a function.");
alert("Now check console.log for the error when value d is requested next:");
alert(d);

Conclusion

  1. No matter declared with or without var (like a, b) if they get their value outside the function, they will preserve their value and also any other values that are added inside various functions through the script are preserved.
  2. If the variable is declared without var inside a function (like c), it will act like the previous rule, it will preserve its value across all functions from now on. Either it got its first value in function testVar1() it still preserves the value and get additional value in function testVar2()
  3. If the variable is declared with var inside a function only (like d in testVar1 or testVar2) it will will be undefined whenever the function ends. So it will be temporary variable in a function.

ToList().ForEach in Linq

You can use Array.ForEach()

Array.ForEach(employees, employee => {
   Array.ForEach(employee.Departments, department => department.SomeProperty = null);
   Collection.AddRange(employee.Departments);
});

Android Studio - Failed to notify project evaluation listener error

Just restart Android Studio - Usually then everything works again. (Invalidate Caches + Restart is actually not required).

How to get controls in WPF to fill available space?

Well, I figured it out myself, right after posting, which is the most embarassing way. :)

It seems every member of a StackPanel will simply fill its minimum requested size.

In the DockPanel, I had docked things in the wrong order. If the TextBox or ListBox is the only docked item without an alignment, or if they are the last added, they WILL fill the remaining space as wanted.

I would love to see a more elegant method of handling this, but it will do.

DateTime and CultureInfo

You may try the following:

System.Globalization.CultureInfo cultureinfo =
        new System.Globalization.CultureInfo("nl-NL");
DateTime dt = DateTime.Parse(date, cultureinfo);

How to force a SQL Server 2008 database to go Offline

Go offline

USE master
GO
ALTER DATABASE YourDatabaseName
SET OFFLINE WITH ROLLBACK IMMEDIATE
GO

Go online

USE master
GO
ALTER DATABASE YourDatabaseName
SET ONLINE
GO

Translating touch events from Javascript to jQuery

$(window).on("touchstart", function(ev) {
    var e = ev.originalEvent;
    console.log(e.touches);
});

I know it been asked a long time ago, but I thought a concrete example might help.

How to call a C# function from JavaScript?

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

Get JSF managed bean by name in any Servlet related class

In a servlet based artifact, such as @WebServlet, @WebFilter and @WebListener, you can grab a "plain vanilla" JSF @ManagedBean @RequestScoped by:

Bean bean = (Bean) request.getAttribute("beanName");

and @ManagedBean @SessionScoped by:

Bean bean = (Bean) request.getSession().getAttribute("beanName");

and @ManagedBean @ApplicationScoped by:

Bean bean = (Bean) getServletContext().getAttribute("beanName");

Note that this prerequires that the bean is already autocreated by JSF beforehand. Else these will return null. You'd then need to manually create the bean and use setAttribute("beanName", bean).


If you're able to use CDI @Named instead of the since JSF 2.3 deprecated @ManagedBean, then it's even more easy, particularly because you don't anymore need to manually create the beans:

@Inject
private Bean bean;

Note that this won't work when you're using @Named @ViewScoped because the bean can only be identified by JSF view state and that's only available when the FacesServlet has been invoked. So in a filter which runs before that, accessing an @Injected @ViewScoped will always throw ContextNotActiveException.


Only when you're inside @ManagedBean, then you can use @ManagedProperty:

@ManagedProperty("#{bean}")
private Bean bean;

Note that this doesn't work inside a @Named or @WebServlet or any other artifact. It really works inside @ManagedBean only.


If you're not inside a @ManagedBean, but the FacesContext is readily available (i.e. FacesContext#getCurrentInstance() doesn't return null), you can also use Application#evaluateExpressionGet():

FacesContext context = FacesContext.getCurrentInstance();
Bean bean = context.getApplication().evaluateExpressionGet(context, "#{beanName}", Bean.class);

which can be convenienced as follows:

@SuppressWarnings("unchecked")
public static <T> T findBean(String beanName) {
    FacesContext context = FacesContext.getCurrentInstance();
    return (T) context.getApplication().evaluateExpressionGet(context, "#{" + beanName + "}", Object.class);
}

and can be used as follows:

Bean bean = findBean("bean");

See also:

Concatenate a list of pandas dataframes together

Given that all the dataframes have the same columns, you can simply concat them:

import pandas as pd
df = pd.concat(list_of_dataframes)

Style disabled button with CSS

input[type="button"]:disabled,
input[type="submit"]:disabled,
input[type="reset"]:disabled,
{
  //  apply css here what u like it will definitely work...
}

C++ - struct vs. class

Ok, POD means plain old data. That usually refers to structs without any methods because these types are then used to structure multiple data that belong together.

As for structs not having methods: I have seen more than once that a struct had methods, and I don't feel that this would be unnatural.

what is an illegal reflective access

Apart from an understanding of the accesses amongst modules and their respective packages. I believe the crux of it lies in the Module System#Relaxed-strong-encapsulation and I would just cherry-pick the relevant parts of it to try and answer the question.

What defines an illegal reflective access and what circumstances trigger the warning?

To aid in the migration to Java-9, the strong encapsulation of the modules could be relaxed.

  • An implementation may provide static access, i.e. by compiled bytecode.

  • May provide a means to invoke its run-time system with one or more packages of one or more of its modules open to code in all unnamed modules, i.e. to code on the classpath. If the run-time system is invoked in this way, and if by doing so some invocations of the reflection APIs succeed where otherwise they would have failed.

In such cases, you've actually ended up making a reflective access which is "illegal" since in a pure modular world you were not meant to do such accesses.

How it all hangs together and what triggers the warning in what scenario?

This relaxation of the encapsulation is controlled at runtime by a new launcher option --illegal-access which by default in Java9 equals permit. The permit mode ensures

The first reflective-access operation to any such package causes a warning to be issued, but no warnings are issued after that point. This single warning describes how to enable further warnings. This warning cannot be suppressed.

The modes are configurable with values debug(message as well as stacktrace for every such access), warn(message for each such access), and deny(disables such operations).


Few things to debug and fix on applications would be:-

  • Run it with --illegal-access=deny to get to know about and avoid opening packages from one module to another without a module declaration including such a directive(opens) or explicit use of --add-opens VM arg.
  • Static references from compiled code to JDK-internal APIs could be identified using the jdeps tool with the --jdk-internals option

The warning message issued when an illegal reflective-access operation is detected has the following form:

WARNING: Illegal reflective access by $PERPETRATOR to $VICTIM

where:

$PERPETRATOR is the fully-qualified name of the type containing the code that invoked the reflective operation in question plus the code source (i.e., JAR-file path), if available, and

$VICTIM is a string that describes the member being accessed, including the fully-qualified name of the enclosing type

Questions for such a sample warning: = JDK9: An illegal reflective access operation has occurred. org.python.core.PySystemState

Last and an important note, while trying to ensure that you do not face such warnings and are future safe, all you need to do is ensure your modules are not making those illegal reflective accesses. :)

Authentication issue when debugging in VS2013 - iis express

It appears that the right answer is provided by user3149240 above. However, As Neil Watson pointed out, the applicationhost.config file is at play here.

The changes can actually be made in the VS Property pane or in the file albeit in a different spot. Near the bottom of the applicationhost.config file is a set of location elements. Each app for IIS Express seems to have one of these. Changing the settings in the UI updates this section of the file. So, you can either change the settings through the UI or modify this file.

Here is an example with anonymous auth off and Windows auth on:

<location path="MyApp">
    <system.webServer>
        <security>
            <authentication>
                <windowsAuthentication enabled="true" />
                <anonymousAuthentication enabled="false" />
            </authentication>
        </security>
    </system.webServer>
</location>

This is equivalent in the VS UI to:

Anonymous Authentication: Disabled
Windows Authentication: Enabled

Explanation of "ClassCastException" in Java

A very good example that I can give you for classcastException in Java is while using "Collection"

List list = new ArrayList();
list.add("Java");
list.add(new Integer(5));

for(Object obj:list) {
    String str = (String)obj;
}

This above code will give you ClassCastException on runtime. Because you are trying to cast Integer to String, that will throw the exception.

Bundling data files with PyInstaller (--onefile)

i use this based on max solution

def getPath(filename):
    import os
    import sys
    from os import chdir
    from os.path import join
    from os.path import dirname
    from os import environ
    
    if hasattr(sys, '_MEIPASS'):
        # PyInstaller >= 1.6
        chdir(sys._MEIPASS)
        filename = join(sys._MEIPASS, filename)
    elif '_MEIPASS2' in environ:
        # PyInstaller < 1.6 (tested on 1.5 only)
        chdir(environ['_MEIPASS2'])
        filename = join(environ['_MEIPASS2'], filename)
    else:
        chdir(dirname(sys.argv[0]))
        filename = join(dirname(sys.argv[0]), filename)
        
    return filename

Why must wait() always be in synchronized block

directly from this java oracle tutorial:

When a thread invokes d.wait, it must own the intrinsic lock for d — otherwise an error is thrown. Invoking wait inside a synchronized method is a simple way to acquire the intrinsic lock.

How do I connect to a Websphere Datasource with a given JNDI name?

You need to define a resource reference in your application and then map that logical resource reference to the physical resource (data source) during deployment.

In your web.xml, add the following configuration (modifying the names and properties as appropriate):

<resource-ref>
    <description>Resource reference to my database</description>
    <res-ref-name>jdbc/MyDB</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    <res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>

Then, during application deployment, WAS will prompt you to map this resource reference (jdbc/MyDB) to the data source you created in WAS.

In your code, you can obtain the DataSource similar to how you've shown it in your example; however, the JNDI name you'll use to look it up should actually be the resource reference's name you defined (res-ref-name), rather than the JNDI name of the physical data source. Also, you'll need to prefix the res-ref-name with the application naming context (java:comp/env/).

Context ctx = new InitialContext();
DataSource dataSource = (DataSource) ctx.lookup("java:comp/env/jdbc/MyDB");

HTML5 Dynamically create Canvas

Alternative

Use element .innerHTML= which is quite fast in modern browsers

_x000D_
_x000D_
document.body.innerHTML = "<canvas width=500 height=150 id='CursorLayer'>";


// TEST

var ctx = CursorLayer.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(100, 100, 50, 50);
_x000D_
canvas { border: 1px solid black }
_x000D_
_x000D_
_x000D_

How to read a file from jar in Java?

Check first your class loader.

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

if (classLoader == null) {
    classLoader = Class.class.getClassLoader();
}

classLoader.getResourceAsStream("xmlFileNameInJarFile.xml");

// xml file location at xxx.jar
// + folder
// + folder
// xmlFileNameInJarFile.xml

Magento addFieldToFilter: Two fields, match as OR, not AND

To create simple OR condition for collection, use format below:

    $orders = Mage::getModel('sales/order')->getResourceCollection();
    $orders->addFieldToFilter(
      'status',
      array(
        'processing',
        'pending',
      )
    );

This will produce SQL like this:

WHERE (((`status` = 'processing') OR (`status` = 'pending')))

Convert Linq Query Result to Dictionary

Use namespace

using System.Collections.Specialized;

Make instance of DataContext Class

LinqToSqlDataContext dc = new LinqToSqlDataContext();

Use

OrderedDictionary dict = dc.TableName.ToDictionary(d => d.key, d => d.value);

In order to retrieve the values use namespace

   using System.Collections;

ICollection keyCollections = dict.Keys;
ICOllection valueCollections = dict.Values;

String[] myKeys = new String[dict.Count];
String[] myValues = new String[dict.Count];

keyCollections.CopyTo(myKeys,0);
valueCollections.CopyTo(myValues,0);

for(int i=0; i<dict.Count; i++)
{
Console.WriteLine("Key: " + myKeys[i] + "Value: " + myValues[i]);
}
Console.ReadKey();

C# difference between == and Equals()

==

The == operator can be used to compare two variables of any kind, and it simply compares the bits.

int a = 3;
byte b = 3;
if (a == b) { // true }

Note : there are more zeroes on the left side of the int but we don't care about that here.

int a (00000011) == byte b (00000011)

Remember == operator cares only about the pattern of the bits in the variable.

Use == If two references (primitives) refers to the same object on the heap.

Rules are same whether the variable is a reference or primitive.

Foo a = new Foo();
Foo b = new Foo();
Foo c = a;

if (a == b) { // false }
if (a == c) { // true }
if (b == c) { // false }

a == c is true a == b is false

the bit pattern are the same for a and c, so they are equal using ==.

Equal():

Use the equals() method to see if two different objects are equal.

Such as two different String objects that both represent the characters in "Jane"

Sublime text 3. How to edit multiple lines?

Select multiple lines by clicking first line then holding shift and clicking last line. Then press:

CTRL+SHIFT+L

or on MAC: CMD+SHIFT+L (as per comments)

Alternatively you can select lines and go to SELECTION MENU >> SPLIT INTO LINES.

Now you can edit multiple lines, move cursors etc. for all selected lines.

Angular 2.0 router not working on reloading the browser

I wanted to preserve the URL path of sub pages in HTML5 mode without a redirect back to index and none of the solutions out there told me how to do this, so this is how I accomplished it:

Create simple virtual directories in IIS for all your routes and point them to the app root.

Wrap your system.webServer in your Web.config.xml with this location tag, otherwise you will get duplicate errors from it loading Web.config a second time with the virtual directory:

<configuration>
    <location path="." inheritInChildApplications="false">
    <system.webServer>
        <defaultDocument enabled="true">
            <files>
                <add value="index.html" />
            </files>
        </defaultDocument>
    </system.webServer>
  </location>
</configuration>

iloc giving 'IndexError: single positional indexer is out-of-bounds'

This error is caused by:

Y = Dataset.iloc[:,18].values

Indexing is out of bounds here most probably because there are less than 19 columns in your Dataset, so column 18 does not exist. The following code you provided doesn't use Y at all, so you can just comment out this line for now.

What is "loose coupling?" Please provide examples

Definition

Essentially, coupling is how much a given object or set of object relies on another object or another set of objects in order to accomplish its task.

High Coupling

Think of a car. In order for the engine to start, a key must be inserted into the ignition, turned, gasoline must be present, a spark must occur, pistons must fire, and the engine must come alive. You could say that a car engine is highly coupled to several other objects. This is high coupling, but it's not really a bad thing.

Loose Coupling

Think of a user control for a web page that is responsible for allowing users to post, edit, and view some type of information. The single control could be used to let a user post a new piece of information or edit a new piece of information. The control should be able to be shared between two different paths - new and edit. If the control is written in such a way that it needs some type of data from the pages that will contain it, then you could say it's too highly coupled. The control should not need anything from its container page.

How to pass values between Fragments

This simple implementation helps to pass data between fragments in a simple way. Think you want to pass data from 'Frgment1' to 'Fragment2'

In Fragment1(Set data to send)

 Bundle bundle = new Bundle();
 bundle.putString("key","Jhon Doe"); // set your parameteres

 Fragment2 nextFragment = new Fragment2();
 nextFragment.setArguments(bundle);

 FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
 fragmentManager.beginTransaction().replace(R.id.content_drawer, nextFragment).commit();

In Fragment2 onCreateView method (Get parameteres)

String value = this.getArguments().getString("key");//get your parameters
Toast.makeText(getActivity(), value+" ", Toast.LENGTH_LONG).show();//show data in tost

Accessing Websites through a Different Port?

To clarify earlier answers, the HTTP protocol is 'registered' with port 80, and HTTP over SSL (aka HTTPS) is registered with port 443.

Well known port numbers are documented by IANA.

If you mean "bypass logging software" on the web server, no. It will see the traffic coming from you through the proxy system's IP address, at least. If you're trying to circumvent controls put into place by your IT department, then you need to rethink this. If your IT department blocks traffic to port 80, 8080 or 443 anywhere outbound, there is a reason. Ask your IT director. If you need access to these ports outbound from your local workstation to do your job, make your case with them.

Installing a proxy server, or using a free proxy service, may be a violation of company policies and could put your employment at risk.

Show/Hide Div on Scroll

Here is my answer when you want to animate it and start fading it out after couple of seconds. I used opacity because first of all i didn't want to fade it out completely, second, it does not go back and force after many scrolls.

$(window).scroll(function () {
    var elem = $('div');
    setTimeout(function() {
        elem.css({"opacity":"0.2","transition":"2s"});
    },4000);            
    elem.css({"opacity":"1","transition":"1s"});    
});

Error "There is already an open DataReader associated with this Command which must be closed first" when using 2 distinct commands

  1. The optimal solution could be to try to transform your solution into a form where you don't need to have two readers open at a time. Ideally it could be a single query. I don't have time to do that now.
  2. If your problem is so special that you really need to have more readers open simultaneously, and your requirements allow not older than SQL Server 2005 DB backend, then the magic word is MARS (Multiple Active Result Sets). http://msdn.microsoft.com/en-us/library/ms345109%28v=SQL.90%29.aspx. Bob Vale's linked topic's solution shows how to enable it: specify MultipleActiveResultSets=true in your connection string. I just tell this as an interesting possibility, but you should rather transform your solution.

    • in order to avoid the mentioned SQL injection possibility, set the parameters to the SQLCommand itself instead of embedding them into the query string. The query string should only contain the references to the parameters what you pass into the SqlCommand.

Laravel Password & Password_Confirmation Validation

You can use the confirmed validation rule.

$this->validate($request, [
    'name' => 'required|min:3|max:50',
    'email' => 'email',
    'vat_number' => 'max:13',
    'password' => 'required|confirmed|min:6',
]);

Show/hide forms using buttons and JavaScript

There's the global attribute called hidden. But I'm green to all this and maybe there was a reason it wasn't mentioned yet?

_x000D_
_x000D_
var someCondition = true;_x000D_
_x000D_
if (someCondition == true){_x000D_
    document.getElementById('hidden div').hidden = false;_x000D_
}
_x000D_
<div id="hidden div" hidden>_x000D_
    stuff hidden by default_x000D_
</div>
_x000D_
_x000D_
_x000D_

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/hidden

How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?

Using the idea of totem and zlangner, I have created a KnownTypeConverter that will be able to determine the most appropriate inheritor, while taking into account that json data may not have optional elements.

So, the service sends a JSON response that contains an array of documents (incoming and outgoing). Documents have both a common set of elements and different ones. In this case, the elements related to the outgoing documents are optional and may be absent.

In this regard, a base class Document was created that includes a common set of properties. Two inheritor classes are also created: - OutgoingDocument adds two optional elements "device_id" and "msg_id"; - IncomingDocument adds one mandatory element "sender_id";

The task was to create a converter that based on json data and information from KnownTypeAttribute will be able to determine the most appropriate class that allows you to save the largest amount of information received. It should also be taken into account that json data may not have optional elements. To reduce the number of comparisons of json elements and properties of data models, I decided not to take into account the properties of the base class and to correlate with json elements only the properties of the inheritor classes.

Data from the service:

{
    "documents": [
        {
            "document_id": "76b7be75-f4dc-44cd-90d2-0d1959922852",
            "date": "2019-12-10 11:32:49",
            "processed_date": "2019-12-10 11:32:49",
            "sender_id": "9dedee17-e43a-47f1-910e-3a88ff6bc258",
        },
        {
            "document_id": "5044a9ac-0314-4e9a-9e0c-817531120753",
            "date": "2019-12-10 11:32:44",
            "processed_date": "2019-12-10 11:32:44",
        }
    ], 
    "total": 2
}

Data models:

/// <summary>
/// Service response model
/// </summary>
public class DocumentsRequestIdResponse
{
    [JsonProperty("documents")]
    public Document[] Documents { get; set; }

    [JsonProperty("total")]
    public int Total { get; set; }
}

// <summary>
/// Base document
/// </summary>
[JsonConverter(typeof(KnownTypeConverter))]
[KnownType(typeof(OutgoingDocument))]
[KnownType(typeof(IncomingDocument))]
public class Document
{
    [JsonProperty("document_id")]
    public Guid DocumentId { get; set; }

    [JsonProperty("date")]
    public DateTime Date { get; set; }

    [JsonProperty("processed_date")]
    public DateTime ProcessedDate { get; set; } 
}

/// <summary>
/// Outgoing document
/// </summary>
public class OutgoingDocument : Document
{
    // this property is optional and may not be present in the service's json response
    [JsonProperty("device_id")]
    public string DeviceId { get; set; }

    // this property is optional and may not be present in the service's json response
    [JsonProperty("msg_id")]
    public string MsgId { get; set; }
}

/// <summary>
/// Incoming document
/// </summary>
public class IncomingDocument : Document
{
    // this property is mandatory and is always populated by the service
    [JsonProperty("sender_sys_id")]
    public Guid SenderSysId { get; set; }
}

Converter:

public class KnownTypeConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return System.Attribute.GetCustomAttributes(objectType).Any(v => v is KnownTypeAttribute);
    }

    public override bool CanWrite => false;

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // load the object 
        JObject jObject = JObject.Load(reader);

        // take custom attributes on the type
        Attribute[] attrs = Attribute.GetCustomAttributes(objectType);

        Type mostSuitableType = null;
        int countOfMaxMatchingProperties = -1;

        // take the names of elements from json data
        HashSet<string> jObjectKeys = GetKeys(jObject);

        // take the properties of the parent class (in our case, from the Document class, which is specified in DocumentsRequestIdResponse)
        HashSet<string> objectTypeProps = objectType.GetProperties(BindingFlags.Instance | BindingFlags.Public)
            .Select(p => p.Name)
            .ToHashSet();

        // trying to find the right "KnownType"
        foreach (var attr in attrs.OfType<KnownTypeAttribute>())
        {
            Type knownType = attr.Type;
            if(!objectType.IsAssignableFrom(knownType))
                continue;

            // select properties of the inheritor, except properties from the parent class and properties with "ignore" attributes (in our case JsonIgnoreAttribute and XmlIgnoreAttribute)
            var notIgnoreProps = knownType.GetProperties(BindingFlags.Instance | BindingFlags.Public)
                .Where(p => !objectTypeProps.Contains(p.Name)
                            && p.CustomAttributes.All(a => a.AttributeType != typeof(JsonIgnoreAttribute) && a.AttributeType != typeof(System.Xml.Serialization.XmlIgnoreAttribute)));

            //  get serializable property names
            var jsonNameFields = notIgnoreProps.Select(prop =>
            {
                string jsonFieldName = null;
                CustomAttributeData jsonPropertyAttribute = prop.CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(JsonPropertyAttribute));
                if (jsonPropertyAttribute != null)
                {
                    // take the name of the json element from the attribute constructor
                    CustomAttributeTypedArgument argument = jsonPropertyAttribute.ConstructorArguments.FirstOrDefault();
                    if(argument != null && argument.ArgumentType == typeof(string) && !string.IsNullOrEmpty((string)argument.Value))
                        jsonFieldName = (string)argument.Value;
                }
                // otherwise, take the name of the property
                if (string.IsNullOrEmpty(jsonFieldName))
                {
                    jsonFieldName = prop.Name;
                }

                return jsonFieldName;
            });


            HashSet<string> jKnownTypeKeys = new HashSet<string>(jsonNameFields);

            // by intersecting the sets of names we determine the most suitable inheritor
            int count = jObjectKeys.Intersect(jKnownTypeKeys).Count();

            if (count == jKnownTypeKeys.Count)
            {
                mostSuitableType = knownType;
                break;
            }

            if (count > countOfMaxMatchingProperties)
            {
                countOfMaxMatchingProperties = count;
                mostSuitableType = knownType;
            }
        }

        if (mostSuitableType != null)
        {
            object target = Activator.CreateInstance(mostSuitableType);
            using (JsonReader jObjectReader = CopyReaderForObject(reader, jObject))
            {
                serializer.Populate(jObjectReader, target);
            }
            return target;
        }

        throw new SerializationException($"Could not serialize to KnownTypes and assign to base class {objectType} reference");
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    private HashSet<string> GetKeys(JObject obj)
    {
        return new HashSet<string>(((IEnumerable<KeyValuePair<string, JToken>>) obj).Select(k => k.Key));
    }

    public static JsonReader CopyReaderForObject(JsonReader reader, JObject jObject)
    {
        JsonReader jObjectReader = jObject.CreateReader();
        jObjectReader.Culture = reader.Culture;
        jObjectReader.DateFormatString = reader.DateFormatString;
        jObjectReader.DateParseHandling = reader.DateParseHandling;
        jObjectReader.DateTimeZoneHandling = reader.DateTimeZoneHandling;
        jObjectReader.FloatParseHandling = reader.FloatParseHandling;
        jObjectReader.MaxDepth = reader.MaxDepth;
        jObjectReader.SupportMultipleContent = reader.SupportMultipleContent;
        return jObjectReader;
    }
}

PS: In my case, if no one inheritor has not been selected by converter (this can happen if the JSON data contains information only from the base class or the JSON data does not contain optional elements from the OutgoingDocument), then an object of the OutgoingDocument class will be created, since it is listed first in the list of KnownTypeAttribute attributes. At your request, you can vary the implementation of the KnownTypeConverter in this situation.

How to remove trailing whitespaces with sed?

I have a script in my .bashrc that works under OSX and Linux (bash only !)

function trim_trailing_space() {
  if [[ $# -eq 0 ]]; then
    echo "$FUNCNAME will trim (in place) trailing spaces in the given file (remove unwanted spaces at end of lines)"
    echo "Usage :"
    echo "$FUNCNAME file"
    return
  fi
  local file=$1
  unamestr=$(uname)
  if [[ $unamestr == 'Darwin' ]]; then
    #specific case for Mac OSX
    sed -E -i ''  's/[[:space:]]*$//' $file
  else
    sed -i  's/[[:space:]]*$//' $file
  fi
}

to which I add:

SRC_FILES_EXTENSIONS="js|ts|cpp|c|h|hpp|php|py|sh|cs|sql|json|ini|xml|conf"

function find_source_files() {
  if [[ $# -eq 0 ]]; then
    echo "$FUNCNAME will list sources files (having extensions $SRC_FILES_EXTENSIONS)"
    echo "Usage :"
    echo "$FUNCNAME folder"
    return
  fi
  local folder=$1

  unamestr=$(uname)
  if [[ $unamestr == 'Darwin' ]]; then
    #specific case for Mac OSX
    find -E $folder -iregex '.*\.('$SRC_FILES_EXTENSIONS')'
  else
    #Rhahhh, lovely
    local extensions_escaped=$(echo $SRC_FILES_EXTENSIONS | sed s/\|/\\\\\|/g)
    #echo "extensions_escaped:$extensions_escaped"
    find $folder -iregex '.*\.\('$extensions_escaped'\)$'
  fi
}

function trim_trailing_space_all_source_files() {
  for f in $(find_source_files .); do trim_trailing_space $f;done
}

How to get names of enum entries?

You can use the enum-values package I wrote when I had the same problem:

Git: enum-values

var names = EnumValues.getNames(myEnum);

How to use a findBy method with comparative criteria

$criteria = new \Doctrine\Common\Collections\Criteria();
    $criteria->where($criteria->expr()->gt('id', 'id'))
        ->setMaxResults(1)
        ->orderBy(array("id" => $criteria::DESC));

$results = $articlesRepo->matching($criteria);

Importing csv file into R - numeric values read as characters

Whatever algebra you are doing in Excel to create the new column could probably be done more effectively in R.

Please try the following: Read the raw file (before any excel manipulation) into R using read.csv(... stringsAsFactors=FALSE). [If that does not work, please take a look at ?read.table (which read.csv wraps), however there may be some other underlying issue].

For example:

   delim = ","  # or is it "\t" ?
   dec = "."    # or is it "," ?
   myDataFrame <- read.csv("path/to/file.csv", header=TRUE, sep=delim, dec=dec, stringsAsFactors=FALSE)

Then, let's say your numeric columns is column 4

   myDataFrame[, 4]  <- as.numeric(myDataFrame[, 4])  # you can also refer to the column by "itsName"


Lastly, if you need any help with accomplishing in R the same tasks that you've done in Excel, there are plenty of folks here who would be happy to help you out

read input separated by whitespace(s) or newline...?

std::getline( stream, where to?, delimiter ie

std::string in;
std::getline(std::cin, in, ' '); //will split on space

or you can read in a line, then tokenize it based on whichever delimiter you wish.

How to change the minSdkVersion of a project?

Delete this line:

<uses-sdk android:targetSdkVersion="..." />

in the file:

AndroidManifest.xml

What's the most efficient way to test two integer ranges for overlap?

I suppose the question was about the fastest, not the shortest code. The fastest version have to avoid branches, so we can write something like this:

for simple case:

static inline bool check_ov1(int x1, int x2, int y1, int y2){
    // insetead of x1 < y2 && y1 < x2
    return (bool)(((unsigned int)((y1-x2)&(x1-y2))) >> (sizeof(int)*8-1));
};

or, for this case:

static inline bool check_ov2(int x1, int x2, int y1, int y2){
    // insetead of x1 <= y2 && y1 <= x2
    return (bool)((((unsigned int)((x2-y1)|(y2-x1))) >> (sizeof(int)*8-1))^1);
};

Concatenating strings in C, which method is more efficient?

size_t lf = strlen(first);
size_t ls = strlen(second);

char *both = (char*) malloc((lf + ls + 2) * sizeof(char));

strcpy(both, first);

both[lf] = ' ';
strcpy(&both[lf+1], second);

How do I load an url in iframe with Jquery

$("#button").click(function () { 
    $("#frame").attr("src", "http://www.example.com/");
});

HTML:

 <div id="mydiv">
     <iframe id="frame" src="" width="100%" height="300">
     </iframe>
 </div>
 <button id="button">Load</button>

python getoutput() equivalent in subprocess

To catch errors with subprocess.check_output(), you can use CalledProcessError. If you want to use the output as string, decode it from the bytecode.

# \return String of the output, stripped from whitespace at right side; or None on failure.
def runls():
    import subprocess
    try:
        byteOutput = subprocess.check_output(['ls', '-a'], timeout=2)
        return byteOutput.decode('UTF-8').rstrip()
    except subprocess.CalledProcessError as e:
        print("Error in ls -a:\n", e.output)
        return None

Create line after text with css

There's no need for extra wrappers or span elements anymore. Flexbox and Grid can handle this easily.

_x000D_
_x000D_
h2 {_x000D_
  display: flex;_x000D_
  align-items: center;_x000D_
}_x000D_
_x000D_
h2::after {_x000D_
  content: '';_x000D_
  flex: 1;_x000D_
  margin-left: 1rem;_x000D_
  height: 1px;_x000D_
  background-color: #000;_x000D_
}
_x000D_
<h2>Heading</h2>
_x000D_
_x000D_
_x000D_

@Transactional(propagation=Propagation.REQUIRED)

If you need a laymans explanation of the use beyond that provided in the Spring Docs

Consider this code...

class Service {
    @Transactional(propagation=Propagation.REQUIRED)
    public void doSomething() {
        // access a database using a DAO
    }
}

When doSomething() is called it knows it has to start a Transaction on the database before executing. If the caller of this method has already started a Transaction then this method will use that same physical Transaction on the current database connection.

This @Transactional annotation provides a means of telling your code when it executes that it must have a Transaction. It will not run without one, so you can make this assumption in your code that you wont be left with incomplete data in your database, or have to clean something up if an exception occurs.

Transaction management is a fairly complicated subject so hopefully this simplified answer is helpful

PHP String to Float

Dealing with markup in floats is a non trivial task. In the English/American notation you format one thousand plus 46*10-2:

1,000.46

But in Germany you would change comma and point:

1.000,46


This makes it really hard guessing the right number in multi-language applications.
I strongly suggest using Zend_Measure of the Zend Framework for this task. This component will parse the string to a float by the users language.

How to unstash only certain files?

First list all the stashes

git stash list

?

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

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

git stash show 1 --name-only

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

?

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

Then apply the file you like to:

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

or whole folder:

git checkout stash@{1} /errors

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

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

Android Activity as a dialog

You can define this style in values/styles.xml to perform a more former Splash :

   <style name="Theme.UserDialog" parent="android:style/Theme.Dialog">
        <item name="android:windowFrame">@null</item>
        <item name="android:windowIsFloating">true</item>
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:background">@android:color/transparent</item>
        <item name="android:windowBackground">@drawable/trans</item>
    </style>

And use it AndroidManifest.xml:

   <activity android:name=".SplashActivity"
          android:configChanges="orientation"
          android:screenOrientation="sensor"
          android:theme="@style/Theme.UserDialog">

Shrink to fit content in flexbox, or flex-basis: content workaround?

It turns out that it was shrinking and growing correctly, providing the desired behaviour all along; except that in all current browsers flexbox wasn't accounting for the vertical scrollbar! Which is why the content appears to be getting cut off.

You can see here, which is the original code I was using before I added the fixed widths, that it looks like the column isn't growing to accomodate the text:

http://jsfiddle.net/2w157dyL/1/

However if you make the content in that column wider, you'll see that it always cuts it off by the same amount, which is the width of the scrollbar.

So the fix is very, very simple - add enough right padding to account for the scrollbar:

http://jsfiddle.net/2w157dyL/2/

_x000D_
_x000D_
  main > section {_x000D_
    overflow-y: auto;_x000D_
    padding-right: 2em;_x000D_
  }
_x000D_
_x000D_
_x000D_

It was when I was trying some things suggested by Michael_B (specifically adding a padding buffer) that I discovered this, thanks so much!

Edit: I see that he also posted a fiddle which does the same thing - again, thanks so much for all your help

Are there any Java method ordering conventions?

  1. Class (static) variables: First the public class variables, then the protected, and then the private.

  2. Instance variables: First public, then protected, and then private.

  3. Constructors

  4. Methods: These methods should be grouped by functionality rather than by scope or accessibility. For example, a private class method can be in between two public instance methods. The goal is to make reading and understanding the code easier.

Source: http://www.oracle.com/technetwork/java/codeconventions-141855.html

How to run TypeScript files from command line?

Just in case anyone is insane like me and wants to just run typescript script as though it was a .js script, you can try this. I've written a hacky script that appears to execute the .ts script using node.

#!/usr/bin/env bash

NODEPATH="$HOME/.nvm/versions/node/v8.11.3/bin" # set path to your node/tsc

export TSC="$NODEPATH/tsc"
export NODE="$NODEPATH/node"

TSCFILE=$1 # only parameter is the name of the ts file you created.

function show_usage() {
    echo "ts2node [ts file]"
    exit 0
}

if [ "$TSCFILE" == "" ]
then
    show_usage;
fi

JSFILE="$(echo $TSCFILE|cut -d"." -f 1).js"

$TSC $TSCFILE && $NODE $JSFILE

You can do this or write your own but essentially, it creates the .js file and then uses node to run it like so:

# tsrun myscript.ts

Simple. Just make sure your script only has one "." else you'll need to change your JSFILE in a different way than what I've shown.

How to enable local network users to access my WAMP sites?

In WAMPServer 3 you dont do this in httpd.conf

Instead edit \wamp\bin\apache\apache{version}\conf\extra\httpd-vhost.conf and do the same chnage to the Virtual Host defined for localhost

WAMPServer 3 comes with a Virtual Host pre defined for localhost

How to display an image stored as byte array in HTML/JavaScript?

Try putting this HTML snippet into your served document:

<img id="ItemPreview" src="">

Then, on JavaScript side, you can dynamically modify image's src attribute with so-called Data URL.

document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;

Alternatively, using jQuery:

$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);

This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..." part) in the URL accordingly.

Similar Questions:

How do I select elements of an array given condition?

Add one detail to @J.F. Sebastian's and @Mark Mikofski's answers:
If one wants to get the corresponding indices (rather than the actual values of array), the following code will do:

For satisfying multiple (all) conditions:

select_indices = np.where( np.logical_and( x > 1, x < 5) )[0] #   1 < x <5

For satisfying multiple (or) conditions:

select_indices = np.where( np.logical_or( x < 1, x > 5 ) )[0] # x <1 or x >5

How to get a enum value from string in C#?

Using Enum.TryParse you don't need the Exception handling:

baseKey e;

if ( Enum.TryParse(s, out e) )
{
 ...
}

Is "delete this" allowed in C++?

Delete this is legal as long as object is in heap. You would need to require object to be heap only. The only way to do that is to make the destructor protected - this way delete may be called ONLY from class , so you would need a method that would ensure deletion

How can I generate an INSERT script for an existing SQL Server table that includes all stored rows?

Just to share, I've developed my own script to do it. Feel free to use it. It generates "SELECT" statements that you can then run on the tables to generate the "INSERT" statements.

select distinct 'SELECT ''INSERT INTO ' + schema_name(ta.schema_id) + '.' + so.name + ' (' + substring(o.list, 1, len(o.list)-1) + ') VALUES ('
+ substring(val.list, 1, len(val.list)-1) + ');''  FROM ' + schema_name(ta.schema_id) + '.' + so.name + ';'
from    sys.objects so
join sys.tables ta on ta.object_id=so.object_id
cross apply
(SELECT '  ' +column_name + ', '
 from information_schema.columns c
 join syscolumns co on co.name=c.COLUMN_NAME and object_name(co.id)=so.name and OBJECT_NAME(co.id)=c.TABLE_NAME and co.id=so.object_id and c.TABLE_SCHEMA=SCHEMA_NAME(so.schema_id)
 where table_name = so.name
 order by ordinal_position
FOR XML PATH('')) o (list)
cross apply
(SELECT '''+' +case
         when data_type = 'uniqueidentifier' THEN 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '])+'''''''' END '
         WHEN data_type = 'timestamp' then '''''''''+CONVERT(NVARCHAR(MAX),CONVERT(BINARY(8),[' + COLUMN_NAME + ']),1)+'''''''''
         WHEN data_type = 'nvarchar' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE([' + COLUMN_NAME + '],'''''''','''''''''''')+'''''''' END'
         WHEN data_type = 'varchar' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE([' + COLUMN_NAME + '],'''''''','''''''''''')+'''''''' END'
         WHEN data_type = 'char' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE([' + COLUMN_NAME + '],'''''''','''''''''''')+'''''''' END'
         WHEN data_type = 'nchar' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE([' + COLUMN_NAME + '],'''''''','''''''''''')+'''''''' END'
         when DATA_TYPE='datetime' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],121)+'''''''' END '
         when DATA_TYPE='datetime2' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],121)+'''''''' END '
         when DATA_TYPE='geography' and column_name<>'Shape' then 'ST_GeomFromText(''POINT('+column_name+'.Lat '+column_name+'.Long)'') '
         when DATA_TYPE='geography' and column_name='Shape' then '''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '])+'''''''''
         when DATA_TYPE='bit' then '''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '])+'''''''''
         when DATA_TYPE='xml' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE(CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + ']),'''''''','''''''''''')+'''''''' END '
         WHEN DATA_TYPE='image' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),CONVERT(VARBINARY(MAX),[' + COLUMN_NAME + ']),1)+'''''''' END '
         WHEN DATA_TYPE='varbinary' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],1)+'''''''' END '
         WHEN DATA_TYPE='binary' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],1)+'''''''' END '
         when DATA_TYPE='time' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '])+'''''''' END '
         ELSE 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE CONVERT(NVARCHAR(MAX),['+column_name+']) END' end
   + '+'', '
 from information_schema.columns c
 join syscolumns co on co.name=c.COLUMN_NAME and object_name(co.id)=so.name and OBJECT_NAME(co.id)=c.TABLE_NAME and co.id=so.object_id and c.TABLE_SCHEMA=SCHEMA_NAME(so.schema_id)
 where table_name = so.name
 order by ordinal_position
FOR XML PATH('')) val (list)
where   so.type = 'U'

Pandas create empty DataFrame with only column names

You can create an empty DataFrame with either column names or an Index:

In [4]: import pandas as pd
In [5]: df = pd.DataFrame(columns=['A','B','C','D','E','F','G'])
In [6]: df
Out[6]:
Empty DataFrame
Columns: [A, B, C, D, E, F, G]
Index: []

Or

In [7]: df = pd.DataFrame(index=range(1,10))
In [8]: df
Out[8]:
Empty DataFrame
Columns: []
Index: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Edit: Even after your amendment with the .to_html, I can't reproduce. This:

df = pd.DataFrame(columns=['A','B','C','D','E','F','G'])
df.to_html('test.html')

Produces:

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>A</th>
      <th>B</th>
      <th>C</th>
      <th>D</th>
      <th>E</th>
      <th>F</th>
      <th>G</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

MIT vs GPL license

IANAL but as I see it....

While you can combine GPL and MIT code, the GPL is tainting. Which means the package as a whole gets the limitations of the GPL. As that is more restrictive you can no longer use it in commercial (or rather closed source) software. Which also means if you have a MIT/BSD/ASL project you will not want to add dependencies to GPL code.

Adding a GPL dependency does not change the license of your code but it will limit what people can do with the artifact of your project. This is also why the ASF does not allow dependencies to GPL code for their projects.

http://www.apache.org/licenses/GPL-compatibility.html

How to get the 'height' of the screen using jquery

$(window).height();

To set anything in the middle you can use CSS.

<style>
#divCentre 
{ 
    position: absolute;
    left: 50%;
    top: 50%;
    width: 300px;
    height: 400px;
    margin-left: -150px;
    margin-top: -200px;
}
</style>
<div id="divCentre">I am at the centre</div>

remove space between paragraph and unordered list

This simple way worked fine for me:

<ul style="margin-top:-30px;">

AVD Manager - Cannot Create Android Virtual Device

I opened monitor.bat in android-sdks\tools and started the device manager there and I was able to create the AVD.

How to combine two strings together in PHP?

This should work for you:

$result = $data1." ".$data2;

Reference: PHP String Variables

How to check if any Checkbox is checked in Angular

This is re-post for insert code also. This example included: - One object list - Each object hast child list. Ex:

var list1 = {
    name: "Role A",
    name_selected: false,
    subs: [{
      sub: "Read",
      id: 1,
      selected: false
    }, {
      sub: "Write",
      id: 2,
      selected: false
    }, {
      sub: "Update",
      id: 3,
      selected: false
    }],
  };

I'll 3 list like above and i'll add to a one object list

newArr.push(list1);
  newArr.push(list2);
  newArr.push(list3);

Then i'll do how to show checkbox with multiple group:

$scope.toggleAll = function(item) {
    var toogleStatus = !item.name_selected;
    console.log(toogleStatus);
    angular.forEach(item, function() {
      angular.forEach(item.subs, function(sub) {
        sub.selected = toogleStatus;
      });
    });
  };

  $scope.optionToggled = function(item, subs) {
    item.name_selected = subs.every(function(itm) {
      return itm.selected;
    })
    $scope.txtRet = item.name_selected;
  }

HTML:

<li ng-repeat="item in itemDisplayed" class="ng-scope has-pretty-child">
      <div>
        <ul>
          <input type="checkbox" class="checkall" ng-model="item.name_selected" ng-click="toggleAll(item)"><span>{{item.name}}</span>
          <div>
            <li ng-repeat="sub in item.subs" class="ng-scope has-pretty-child">
              <input type="checkbox" kv-pretty-check="" ng-model="sub.selected" ng-change="optionToggled(item,item.subs)"><span>{{sub.sub}}</span>
            </li>
          </div>
        </ul>
      </div>
      <span>{{txtRet}}</span>
    </li>

Fiddle: example

Change Tomcat Server's timeout in Eclipse

The issue is also created if you have setup breakpoints in the code and trying to start tomcat in debug mode post some code overhaul.

Solution is to clear all the breakpoints.

Join between tables in two different databases?

SELECT *
FROM A.tableA JOIN B.tableB 

or

SELECT *
  FROM A.tableA JOIN B.tableB
  ON A.tableA.id = B.tableB.a_id;

How to find an available port?

Starting from Java 1.7 you can use try-with-resources like this:

  private Integer findRandomOpenPortOnAllLocalInterfaces() throws IOException {
    try (
        ServerSocket socket = new ServerSocket(0);
    ) {
      return socket.getLocalPort();

    }
  }

If you need to find an open port on a specific interface check ServerSocket documentation for alternative constructors.

Warning: Any code using the port number returned by this method is subject to a race condition - a different process / thread may bind to the same port immediately after we close the ServerSocket instance.

How can I return camelCase JSON serialized by JSON.NET from ASP.NET MVC controller methods?

An alternative to the custom filter is to create an extension method to serialize any object to JSON.

public static class ObjectExtensions
{
    /// <summary>Serializes the object to a JSON string.</summary>
    /// <returns>A JSON string representation of the object.</returns>
    public static string ToJson(this object value)
    {
        var settings = new JsonSerializerSettings
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver(),
            Converters = new List<JsonConverter> { new StringEnumConverter() }
        };

        return JsonConvert.SerializeObject(value, settings);
    }
}

Then call it when returning from the controller action.

return Content(person.ToJson(), "application/json");

SQL Server - copy stored procedures from one db to another

Late one but gives more details that might be useful…

Here is a list of things you can do with advantages and disadvantages

Generate scripts using SSMS

  • Pros: extremely easy to use and supported by default
  • Cons: scripts might not be in the correct execution order and you might get errors if stored procedure already exists on secondary database. Make sure you review the script before executing.

Third party tools

  • Pros: tools such as ApexSQL Diff (this is what I use but there are many others like tools from Red Gate or Dev Art) will compare two databases in one click and generate script that you can execute immediately
  • Cons: these are not free (most vendors have a fully functional trial though)

System Views

  • Pros: You can easily see which stored procedures exist on secondary server and only generate those you don’t have.
  • Cons: Requires a bit more SQL knowledge

Here is how to get a list of all procedures in some database that don’t exist in another database

select *
from DB1.sys.procedures P
where P.name not in 
 (select name from DB2.sys.procedures P2)

Convert Date format into DD/MMM/YYYY format in SQL Server

Anyone trying to manually enter the date to sql server 'date type' variable use this format while entering :

'yyyy-mm-dd'

Convert iterator to pointer?

The direct answer to your question is yes. If foo is a vector, you can do this: &foo[1].

This only works for vectors however, because the standard says that vectors implement storage by using contigious memory.

But you still can (and probably should) pass iterators instead of raw pointers because it is more expressive. Passing iterators does not make a copy of the vector.

Reading value from console, interactively

I've used another API for this purpose..

var readline = require('readline');
var rl = readline.createInterface(process.stdin, process.stdout);
rl.setPrompt('guess> ');
rl.prompt();
rl.on('line', function(line) {
    if (line === "right") rl.close();
    rl.prompt();
}).on('close',function(){
    process.exit(0);
});

This allows to prompt in loop until the answer is right. Also it gives nice little console.You can find the details @ http://nodejs.org/api/readline.html#readline_example_tiny_cli

String replacement in batch file

I was able to use Joey's Answer to create a function:

Use it as:

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION

SET "MYTEXT=jump over the chair"
echo !MYTEXT!
call:ReplaceText "!MYTEXT!" chair table RESULT
echo !RESULT!

GOTO:EOF

And these Functions to the bottom of your Batch File.

:FUNCTIONS
@REM FUNCTIONS AREA
GOTO:EOF
EXIT /B

:ReplaceText
::Replace Text In String
::USE:
:: CALL:ReplaceText "!OrginalText!" OldWordToReplace NewWordToUse  Result
::Example
::SET "MYTEXT=jump over the chair"
::  echo !MYTEXT!
::  call:ReplaceText "!MYTEXT!" chair table RESULT
::  echo !RESULT!
::
:: Remember to use the "! on the input text, but NOT on the Output text.
:: The Following is Wrong: "!MYTEXT!" !chair! !table! !RESULT!
:: ^^Because it has a ! around the chair table and RESULT
:: Remember to add quotes "" around the MYTEXT Variable when calling.
:: If you don't add quotes, it won't treat it as a single string
::
set "OrginalText=%~1"
set "OldWord=%~2"
set "NewWord=%~3"
call set OrginalText=%%OrginalText:!OldWord!=!NewWord!%%
SET %4=!OrginalText!
GOTO:EOF

And remember you MUST add "SETLOCAL ENABLEDELAYEDEXPANSION" to the top of your batch file or else none of this will work properly.

SETLOCAL ENABLEDELAYEDEXPANSION
@REM # Remember to add this to the top of your batch file.

java.lang.UnsupportedClassVersionError Unsupported major.minor version 51.0

These guys gave you the reason why is failing but not how to solve it. This problem may appear even if you have a jdk which matches JVM which you are trying it into.

Project -> Properties -> Java Compiler

Enable project specific settings.

Then select Compiler Compliance Level to 1.6 or 1.5, build and test your app.

Now, it should be fine.

Returning null in a method whose signature says return int?

Change your return type to java.lang.Integer . This way you can safely return null

Add vertical scroll bar to panel

Panel has an AutoScroll property. Just set that property to True and the panel will automatically add a scroll bar when needed.

How to create a simple http proxy in node.js?

Super simple and readable, here's how you create a local proxy server to a local HTTP server with just Node.js (tested on v8.1.0). I've found it particular useful for integration testing so here's my share:

/**
 * Once this is running open your browser and hit http://localhost
 * You'll see that the request hits the proxy and you get the HTML back
 */

'use strict';

const net = require('net');
const http = require('http');

const PROXY_PORT = 80;
const HTTP_SERVER_PORT = 8080;

let proxy = net.createServer(socket => {
    socket.on('data', message => {
        console.log('---PROXY- got message', message.toString());

        let serviceSocket = new net.Socket();

        serviceSocket.connect(HTTP_SERVER_PORT, 'localhost', () => {
            console.log('---PROXY- Sending message to server');
            serviceSocket.write(message);
        });

        serviceSocket.on('data', data => {
            console.log('---PROXY- Receiving message from server', data.toString();
            socket.write(data);
        });
    });
});

let httpServer = http.createServer((req, res) => {
    switch (req.url) {
        case '/':
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.end('<html><body><p>Ciao!</p></body></html>');
            break;
        default:
            res.writeHead(404, {'Content-Type': 'text/plain'});
            res.end('404 Not Found');
    }
});

proxy.listen(PROXY_PORT);
httpServer.listen(HTTP_SERVER_PORT);

https://gist.github.com/fracasula/d15ae925835c636a5672311ef584b999

How to preview an image before and after upload?

meVeekay's answer was good and am just making it more improvised by doing 2 things.

  1. Check whether browser supports HTML5 FileReader() or not.

  2. Allow only image file to be upload by checking its extension.

HTML :

<div id="wrapper">
    <input id="fileUpload" type="file" />
    <br />
    <div id="image-holder"></div>
</div> 

jQuery :

$("#fileUpload").on('change', function () {

    var imgPath = $(this)[0].value;
    var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();

    if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
        if (typeof (FileReader) != "undefined") {

            var image_holder = $("#image-holder");
            image_holder.empty();

            var reader = new FileReader();
            reader.onload = function (e) {
                $("<img />", {
                    "src": e.target.result,
                        "class": "thumb-image"
                }).appendTo(image_holder);

            }
            image_holder.show();
            reader.readAsDataURL($(this)[0].files[0]);
        } else {
            alert("This browser does not support FileReader.");
        }
    } else {
        alert("Pls select only images");
    }
});

For detail understanding of FileReader()

Check this Article : Using FileReader() preview image before uploading.

Selection with .loc in python

  1. Whenever slicing (a:n) can be used, it can be replaced by fancy indexing (e.g. [a,b,c,...,n]). Fancy indexing is nothing more than listing explicitly all the index values instead of specifying only the limits.

  2. Whenever fancy indexing can be used, it can be replaced by a list of Boolean values (a mask) the same size than the index. The value will be True for index values that would have been included in the fancy index, and False for the values that would have been excluded. It's another way of listing some index values, but which can be easily automated in NumPy and Pandas, e.g by a logical comparison (like in your case).

The second replacement possibility is the one used in your example. In:

iris_data.loc[iris_data['class'] == 'versicolor', 'class'] = 'Iris-versicolor'

the mask

iris_data['class'] == 'versicolor'

is a replacement for a long and silly fancy index which would be list of row numbers where class column (a Series) has the value versicolor.

Whether a Boolean mask appears within a .iloc or .loc (e.g. df.loc[mask]) indexer or directly as the index (e.g. df[mask]) depends on wether a slice is allowed as a direct index. Such cases are shown in the following indexer cheat-sheet:

Pandas indexers loc and iloc cheat-sheet
Pandas indexers loc and iloc cheat-sheet

ToggleClass animate jQuery?

I attempted to use the toggleClass method to hide an item on my site (using visibility:hidden as opposed to display:none) with a slight animation, but for some reason the animation would not work (possibly due to an older version of jQuery UI).

The class was removed and added correctly, but the duration I added did not seem to make any difference - the item was simply added or removed with no effect.

So to resolve this I used a second class in my toggle method and applied a CSS transition instead:

The CSS:

.hidden{
    visibility:hidden;
    opacity: 0;
    -moz-transition: opacity 1s, visibility 1.3s;
    -webkit-transition: opacity 1s, visibility 1.3s;
    -o-transition: opacity 1s, visibility 1.3s;
    transition: opacity 1s, visibility 1.3s;
}
.shown{
    visibility:visible;
    opacity: 1;
    -moz-transition: opacity 1s, visibility 1.3s;
    -webkit-transition: opacity 1s, visibility 1.3s;
    -o-transition: opacity 1s, visibility 1.3s;
    transition: opacity 1s, visibility 1.3s;
}

The JS:

    function showOrHide() {
        $('#element').toggleClass("hidden shown");
    }

Thanks @tomas.satinsky for the awesome (and super simple) answer on this post.

Storing Objects in HTML5 localStorage

https://github.com/adrianmay/rhaboo is a localStorage sugar layer that lets you write things like this:

var store = Rhaboo.persistent('Some name');
store.write('count', store.count ? store.count+1 : 1);
store.write('somethingfancy', {
  one: ['man', 'went'],
  2: 'mow',
  went: [  2, { mow: ['a', 'meadow' ] }, {}  ]
});
store.somethingfancy.went[1].mow.write(1, 'lawn');

It doesn't use JSON.stringify/parse because that would be inaccurate and slow on big objects. Instead, each terminal value has its own localStorage entry.

You can probably guess that I might have something to do with rhaboo.

Convert Variable Name to String?

as long as it's a variable and not a second class, this here works for me:

def print_var_name(variable):
 for name in globals():
     if eval(name) == variable:
        print name
foo = 123
print_var_name(foo)
>>>foo

this happens for class members:

class xyz:
     def __init__(self):
         pass
member = xyz()
print_var_name(member)
>>>member

ans this for classes (as example):

abc = xyz
print_var_name(abc)
>>>abc
>>>xyz

So for classes it gives you the name AND the properteries

jQuery: get data attribute

This works for me

$('.someclass').click(function() {
    $varName = $(this).data('fulltext');
    console.log($varName);
});

Display special characters when using print statement

Do you merely want to print the string that way, or do you want that to be the internal representation of the string? If the latter, create it as a raw string by prefixing it with r: r"Hello\tWorld\nHello World".

>>> a = r"Hello\tWorld\nHello World"
>>> a # in the interpreter, this calls repr()
'Hello\\tWorld\\nHello World'
>>> print a
Hello\tWorld\nHello World

Also, \s is not an escape character, except in regular expressions, and then it still has a much different meaning than what you're using it for.

How to check whether an array is empty using PHP?

This seems working for all cases

if(!empty(sizeof($array)))

Find CRLF in Notepad++

Just do a \r with a find and replace with a blank in the replace field so everything goes up to one line. Then do a find and replace (in my case by semi colon) and replace with ;\n

:) -T&C

How to force 'cp' to overwrite directory instead of creating another one inside?

The following command ensures dotfiles (hidden files) are included in the copy:

$ cp -Rf foo/. bar

Array of arrays (Python/NumPy)

You'll have problems creating lists without commas. It shouldn't be too hard to transform your data so that it uses commas as separating character.

Once you have commas in there, it's a relatively simple list creation operations:

array1 = [1,2,3]
array2 = [4,5,6]

array3 = [array1, array2]

array4 = [7,8,9]
array5 = [10,11,12]

array3 = [array3, [array4, array5]]

When testing we get:

print(array3)

[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]

And if we test with indexing it works correctly reading the matrix as made up of 2 rows and 2 columns:

array3[0][1]
[4, 5, 6]

array3[1][1]
[10, 11, 12]

Hope that helps.

Oracle: How to find out if there is a transaction pending?

This is the query I normally use,

select s.sid
      ,s.serial#
      ,s.username
      ,s.machine
      ,s.status
      ,s.lockwait
      ,t.used_ublk
      ,t.used_urec
      ,t.start_time
from v$transaction t
inner join v$session s on t.addr = s.taddr;

What is the difference between XML and XSD?

Basically an XSD file defines how the XML file is going to look like. It's a Schema file which defines the structure of the XML file. So it specifies what the possible fields are and what size they are going to be.

An XML file is an instance of XSD as it uses the rules defined in the XSD.