Programs & Examples On #Resume download

Tag for questions regarding resuming an interrrupted download - for example, using HTTP Range and Content-range headers.

jQuery - how to write 'if not equal to' (opposite of ==)

if ("one" !== 1 )

would evaluate as true, the string "one" is not equal to the number 1

Mock a constructor with parameter

The code you posted works for me with the latest version of Mockito and Powermockito. Maybe you haven't prepared A? Try this:

A.java

public class A {
     private final String test;

    public A(String test) {
        this.test = test;
    }

    public String check() {
        return "checked " + this.test;
    }
}

MockA.java

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(A.class)
public class MockA {
    @Test
    public void test_not_mocked() throws Throwable {
        assertThat(new A("random string").check(), equalTo("checked random string"));
    }
    @Test
    public void test_mocked() throws Throwable {
         A a = mock(A.class); 
         when(a.check()).thenReturn("test");
         PowerMockito.whenNew(A.class).withArguments(Mockito.anyString()).thenReturn(a);
         assertThat(new A("random string").check(), equalTo("test"));
    }
}

Both tests should pass with mockito 1.9.0, powermockito 1.4.12 and junit 4.8.2

New xampp security concept: Access Forbidden Error 403 - Windows 7 - phpMyAdmin

Update for XAMPP 7.3.*

If you get into same problem for phpmyadmin in the newest XAMPP, as I had.

The solution is written inside the official documentation located in [XAMPP IP]/dashboard/docs/access-phpmyadmin-remotely.html

To enable remote access to phpMyAdmin from other hosts, follow these steps:

  1. Launch the stack manager by double-clicking the XAMPP icon in the mounted disk image.
  1. Ensure that Apache and MySQL services are running in the "Services" tab of the stack manager (or start them as needed).
  1. Open a new terminal from the "General" tab of the stack manager.
  1. Edit the /opt/lampp/etc/extra/httpd-xampp.conf file.
  1. Within this file, find the block <Directory "/opt/lampp/phpmyadmin">

Update this block and replace Require local with Require all granted,

  1. Save the file and restart the Apache service using the stack manager.

Note for section (4) To edit this file make sure you have vim installed.

Note for section (5) Instead of allowing access to all, which is highly insecure, if your computer is connected to a network. A safer approach is to limit the access to only set of IPs as suggested by @Gunnar Bernstein.

In my case I did:

<Directory "/opt/lampp/phpmyadmin">
  AllowOverride AuthConfig Limit
  Require local
  Require ip 192.168
  ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>

How to pass a user / password in ansible command

As mentioned before you can use --extra-vars (-e) , but instead of specifying the pwd on the commandline so it doesn't end up in the history files you can save it to an environment variable. This way it also goes away when you close the session.

read -s PASS
ansible windows -i hosts -m win_ping -e "ansible_password=$PASS"

Speed tradeoff of Java's -Xms and -Xmx options

I have found that in some cases too much memory can slow the program down.

For example I had a hibernate based transform engine that started running slowly as the load increased. It turned out that each time we got an object from the db, hibernate was checking memory for objects that would never be used again.

The solution was to evict the old objects from the session.

Stuart

How to get name of calling function/method in PHP?

I just wrote a version of this called "get_caller", I hope it helps. Mine is pretty lazy. You can just run get_caller() from a function, you don't have to specify it like this:

get_caller(__FUNCTION__);

Here's the script in full with a quirky test case:

<?php

/* This function will return the name string of the function that called $function. To return the
    caller of your function, either call get_caller(), or get_caller(__FUNCTION__).
*/
function get_caller($function = NULL, $use_stack = NULL) {
    if ( is_array($use_stack) ) {
        // If a function stack has been provided, used that.
        $stack = $use_stack;
    } else {
        // Otherwise create a fresh one.
        $stack = debug_backtrace();
        echo "\nPrintout of Function Stack: \n\n";
        print_r($stack);
        echo "\n";
    }

    if ($function == NULL) {
        // We need $function to be a function name to retrieve its caller. If it is omitted, then
        // we need to first find what function called get_caller(), and substitute that as the
        // default $function. Remember that invoking get_caller() recursively will add another
        // instance of it to the function stack, so tell get_caller() to use the current stack.
        $function = get_caller(__FUNCTION__, $stack);
    }

    if ( is_string($function) && $function != "" ) {
        // If we are given a function name as a string, go through the function stack and find
        // it's caller.
        for ($i = 0; $i < count($stack); $i++) {
            $curr_function = $stack[$i];
            // Make sure that a caller exists, a function being called within the main script
            // won't have a caller.
            if ( $curr_function["function"] == $function && ($i + 1) < count($stack) ) {
                return $stack[$i + 1]["function"];
            }
        }
    }

    // At this stage, no caller has been found, bummer.
    return "";
}

// TEST CASE

function woman() {
    $caller = get_caller(); // No need for get_caller(__FUNCTION__) here
    if ($caller != "") {
        echo $caller , "() called " , __FUNCTION__ , "(). No surprises there.\n";
    } else {
        echo "no-one called ", __FUNCTION__, "()\n";
    }
}

function man() {
    // Call the woman.
    woman();
}

// Don't keep him waiting
man();

// Try this to see what happens when there is no caller (function called from main script)
//woman();

?>

man() calls woman(), who calls get_caller(). get_caller() doesn't know who called it yet, because the woman() was cautious and didn't tell it, so it recurses to find out. Then it returns who called woman(). And the printout in source-code mode in a browser shows the function stack:

Printout of Function Stack: 

Array
(
    [0] => Array
        (
            [file] => /Users/Aram/Development/Web/php/examples/get_caller.php
            [line] => 46
            [function] => get_caller
            [args] => Array
                (
                )

        )

    [1] => Array
        (
            [file] => /Users/Aram/Development/Web/php/examples/get_caller.php
            [line] => 56
            [function] => woman
            [args] => Array
                (
                )

        )

    [2] => Array
        (
            [file] => /Users/Aram/Development/Web/php/examples/get_caller.php
            [line] => 60
            [function] => man
            [args] => Array
                (
                )

        )

)

man() called woman(). No surprises there.

android on Text Change Listener

We can remove the TextWatcher for a field just before editing its text then add it back after editing the text.

Declare Text Watchers for both field1 and field2 as separate variables to give them a name: e.g. for field1

private TextWatcher Field_1_Watcher = new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void afterTextChanged(Editable s) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

};

then add the watcher using its name: field1.addTextChangedListener(Field_1_Watcher) for field1, and field2.addTextChangedListener(Field_2_Watcher) for field2

Before changing the field2 text remove the TextWatcher: field2.removeTextChangedListener(Field_2_Watcher) change the text: field2.setText("")

then add the TextWatcher back: field2.addTextChangedListener(Field_2_Watcher)

Do the same for the other field

Change the Value of h1 Element within a Form with JavaScript

You can use this: document.getElementById('h1_id').innerHTML = 'the new text';

How can I resize an image using Java?

FWIW I just released (Apache 2, hosted on GitHub) a simple image-scaling library for Java called imgscalr (available on Maven central).

The library implements a few different approaches to image-scaling (including Chris Campbell's incremental approach with a few minor enhancements) and will either pick the most optimal approach for you if you ask it to, or give you the fastest or best looking (if you ask for that).

Usage is dead-simple, just a bunch of static methods. The simplest use-case is:

BufferedImage scaledImage = Scalr.resize(myImage, 200);

All operations maintain the image's original proportions, so in this case you are asking imgscalr to resize your image within a bounds of 200 pixels wide and 200 pixels tall and by default it will automatically select the best-looking and fastest approach for that since it wasn't specified.

I realize on the outset this looks like self-promotion (it is), but I spent my fair share of time googling this exact same subject and kept coming up with different results/approaches/thoughts/suggestions and decided to sit down and write a simple implementation that would address that 80-85% use-cases where you have an image and probably want a thumbnail for it -- either as fast as possible or as good-looking as possible (for those that have tried, you'll notice doing a Graphics.drawImage even with BICUBIC interpolation to a small enough image, it still looks like garbage).

Copying data from one SQLite database to another

Objective-C code for copy Table from a Database to another Database

-(void) createCopyDatabase{

          NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
          NSString *documentsDir = [paths objectAtIndex:0];

          NSString *maindbPath = [documentsDir stringByAppendingPathComponent:@"User.sqlite"];;

          NSString *newdbPath = [documentsDir stringByAppendingPathComponent:@"User_copy.sqlite"];
          NSFileManager *fileManager = [NSFileManager defaultManager];
          char *error;

         if ([fileManager fileExistsAtPath:newdbPath]) {
             [fileManager removeItemAtPath:newdbPath error:nil];
         }
         sqlite3 *database;
         //open database
        if (sqlite3_open([newdbPath UTF8String], &database)!=SQLITE_OK) {
            NSLog(@"Error to open database");
        }

        NSString *attachQuery = [NSString stringWithFormat:@"ATTACH DATABASE \"%@\" AS aDB",maindbPath];

       sqlite3_exec(database, [attachQuery UTF8String], NULL, NULL, &error);
       if (error) {
           NSLog(@"Error to Attach = %s",error);
       }

       //Query for copy Table
       NSString *sqlString = @"CREATE TABLE Info AS SELECT * FROM aDB.Info";
       sqlite3_exec(database, [sqlString UTF8String], NULL, NULL, &error);
        if (error) {
            NSLog(@"Error to copy database = %s",error);
        }

        //Query for copy Table with Where Clause

        sqlString = @"CREATE TABLE comments AS SELECT * FROM aDB.comments Where user_name = 'XYZ'";
        sqlite3_exec(database, [sqlString UTF8String], NULL, NULL, &error);
        if (error) {
            NSLog(@"Error to copy database = %s",error);
        }
 }

How to sort an array based on the length of each element?

If you want to preserve the order of the element with the same length as the original array, use bubble sort.

Input = ["ab","cdc","abcd","de"];

Output  = ["ab","cd","cdc","abcd"]

Function:

function bubbleSort(strArray){
  const arrayLength = Object.keys(strArray).length;
    var swapp;
    var newLen = arrayLength-1;
    var sortedStrArrByLenght=strArray;
    do {
        swapp = false;
        for (var i=0; i < newLen; i++)
        {
            if (sortedStrArrByLenght[i].length > sortedStrArrByLenght[i+1].length)
            {
               var temp = sortedStrArrByLenght[i];
               sortedStrArrByLenght[i] = sortedStrArrByLenght[i+1];
               sortedStrArrByLenght[i+1] = temp;
               swapp = true;
            }
        }
        newLen--;
    } while (swap);
  return sortedStrArrByLenght;
}

Retrieve a single file from a repository

for bitbucket directly from browser (I used safari...) right-click on 'View Raw" and choose "Download Linked File":

enter image description here

How can I download a specific Maven artifact in one command line?

Here's an example to get ASM-7 using Maven 3.6:

mvn dependency:get -DremoteRepositories=maven.apache.org -Dartifact=org.ow2.asm:7.0:sources:jar

Or you can download the jar from here: https://search.maven.org/search?q=g:org.ow2.asm%20AND%20a:asm and then

mvn install:install-file -DgroupId=org.ow2.asm -DartifactId=asm -Dversion=7.0 -Dclassifier=sources -Dpackaging=jar -Dfile=/path/to/asm-7.0.jar

Get the real width and height of an image with JavaScript? (in Safari/Chrome)

Check out this repository in github!

Great Example to check the Width and Height using Javascript

https://github.com/AzizAK/ImageRealSize

---Edited is requested from some comments ..

Javascript code:

 function CheckImageSize(){
var image = document.getElementById("Image").files[0];
           createReader(image, function (w, h) {

                alert("Width is: " + w + " And Height is: "+h);
});            
}


  function  createReader(file, whenReady) {
        var reader = new FileReader;
        reader.onload = function (evt) {
            var image = new Image();
            image.onload = function (evt) {
                var width = this.width;
                var height = this.height;
                if (whenReady) whenReady(width, height);
            };
            image.src = evt.target.result;
        };
        reader.readAsDataURL(file);
    }

and HTML code :

<html>
<head>
<title>Image Real Size</title>
<script src="ImageSize.js"></script>
</head>
<body>
<input type="file" id="Image"/>
<input type="button" value="Find the dimensions" onclick="CheckImageSize()"/>
</body>
<html>

How to fix Error: laravel.log could not be opened?

You need to adjust the permissions of storage and bootstrap/cache.

  • cd into your Laravel project.
  • sudo chmod -R 755 storage
  • sudo chmod -R 755 bootstrap/cache

You can try 777 if 755 doesn't work. 777 is not secure though!

Depending on how your web server is setup, you may be able to be more specific with your permissions, and only grant them to your web server user. Google WEB SERVER NAME Laravel file permissions for more information.

At the time of writing, this is for Laravel 5.4

How can I do string interpolation in JavaScript?

Supplant more for ES6 version of @Chris Nielsen's post.

String.prototype.supplant = function (o) {
  return this.replace(/\${([^\${}]*)}/g,
    (a, b) => {
      var r = o[b];
      return typeof r === 'string' || typeof r === 'number' ? r : a;
    }
  );
};

string = "How now ${color} cow? {${greeting}}, ${greeting}, moo says the ${color} cow.";

string.supplant({color: "brown", greeting: "moo"});
=> "How now brown cow? {moo}, moo, moo says the brown cow."

git pull error "The requested URL returned error: 503 while accessing"

Had the same error while using SourceTree connected to BitBucket repository.

When navigating to repository url on bitbucket.org the warning message appeared:

This repository is in read-only mode. You caught us doing some quick maintenance.

After around 2 hours repository was accessible again.

You can check status and uptime of bitbucket here: http://status.bitbucket.org/

When does a cookie with expiration time 'At end of session' expire?

Cookies that 'expire at end of the session' expire unpredictably from the user's perspective!

On iOS with Safari they expire whenever you switch apps!

On Android with Chrome they don't expire when you close the browser.

On Windows desktop running Chrome they expire when you close the browser. That's not when you close your website's tab; its when you close all tabs. Nor do they expire if there are any other browser windows open. If users run web apps as windows they might not even know they are browser windows. So your cookie's life depends on what the user is doing with some apparently unrelated app.

Changing the maximum length of a varchar column?

As an alternative, you can save old data and create a new table with new parameters.

see image

In SQL Server Management Studio: "your database" => task => generatescripts => select specific database object => "your table" => advanced => types of data to script - schema and data => generate

Personally, I did so.

How to read a PEM RSA private key from .NET

ok, Im using mac to generate my self signed keys. Here is the working method I used.

I created a shell script to speed up my key generation.

genkey.sh

#/bin/sh

ssh-keygen -f host.key
openssl req -new -key host.key -out request.csr
openssl x509 -req -days 99999 -in request.csr -signkey host.key -out server.crt
openssl pkcs12 -export -inkey host.key -in server.crt -out private_public.p12 -name "SslCert"
openssl base64 -in private_public.p12 -out Base64.key

add the +x execute flag to the script

chmod +x genkey.sh

then call genkey.sh

./genkey.sh

I enter a password (important to include a password at least for the export at the end)

Enter pass phrase for host.key:
Enter Export Password:   {Important to enter a password here}
Verifying - Enter Export Password: { Same password here }

I then take everything in Base64.Key and put it into a string named sslKey

private string sslKey = "MIIJiAIBA...................................." +
                        "......................ETC...................." +
                        "......................ETC...................." +
                        "......................ETC...................." +
                        ".............ugICCAA=";

I then used a lazy load Property getter to get my X509 Cert with a private key.

X509Certificate2 _serverCertificate = null;
X509Certificate2 serverCertificate{
    get
    {
        if (_serverCertificate == null){
            string pass = "Your Export Password Here";
            _serverCertificate = new X509Certificate(Convert.FromBase64String(sslKey), pass, X509KeyStorageFlags.Exportable);
        }
        return _serverCertificate;
    }
}

I wanted to go this route because I am using .net 2.0 and Mono on mac and I wanted to use vanilla Framework code with no compiled libraries or dependencies.

My final use for this was the SslStream to secure TCP communication to my app

SslStream sslStream = new SslStream(serverCertificate, false, SslProtocols.Tls, true);

I hope this helps other people.

NOTE

Without a password I was unable to correctly unlock the private key for export.

String.Replace ignoring case

You could use a Regex and perform a case insensitive replace:

class Program
{
    static void Main()
    {
        string input = "hello WoRlD";
        string result = 
           Regex.Replace(input, "world", "csharp", RegexOptions.IgnoreCase);
        Console.WriteLine(result); // prints "hello csharp"
    }
}

Mapping composite keys using EF code first

I thought I would add to this question as it is the top google search result.

As has been noted in the comments, in EF Core there is no support for using annotations (Key attribute) and it must be done with fluent.

As I was working on a large migration from EF6 to EF Core this was unsavoury and so I tried to hack it by using Reflection to look for the Key attribute and then apply it during OnModelCreating

// get all composite keys (entity decorated by more than 1 [Key] attribute
foreach (var entity in modelBuilder.Model.GetEntityTypes()
    .Where(t => 
        t.ClrType.GetProperties()
            .Count(p => p.CustomAttributes.Any(a => a.AttributeType == typeof(KeyAttribute))) > 1))
{
    // get the keys in the appropriate order
    var orderedKeys = entity.ClrType
        .GetProperties()
        .Where(p => p.CustomAttributes.Any(a => a.AttributeType == typeof(KeyAttribute)))
        .OrderBy(p => 
            p.CustomAttributes.Single(x => x.AttributeType == typeof(ColumnAttribute))?
                .NamedArguments?.Single(y => y.MemberName == nameof(ColumnAttribute.Order))
                .TypedValue.Value ?? 0)
        .Select(x => x.Name)
        .ToArray();

    // apply the keys to the model builder
    modelBuilder.Entity(entity.ClrType).HasKey(orderedKeys);
}

I haven't fully tested this in all situations, but it works in my basic tests. Hope this helps someone

Is there Unicode glyph Symbol to represent "Search"

Displayed correct at Chrome OS - screenshots from this system.

tibetan astrological sign sgra gcan -char rtags U+0F17 ? U+0F17

telephone recorder (U+2315) ? U+2315

lepcha letter gla (U+1C04) ? U+1C04

Disable XML validation in Eclipse

Ensure your encoding is correct for all of your files, this can sometimes happen if you have the encoding wrong for your file or the wrong encoding in your XML header.

So, if I have the following NewFile.xml:

<?xml version="1.0" encoding="UTF-16"?>
<bar foo="foiré" />

And the eclipse encoding is UTF-8:

Eclipse Encoding Resource

The encoding of your file, the defined encoding in Eclipse (through Properties->Resource) and the declared encoding in the XML document all need to agree.

The validator is attempting to read the file, expecting <?xml ... but because the encoding is different from that expected, it's not finding it. Hence the error: Content is not allowed in prolog. The prolog is the bit before the <?xml declaration.

EDIT: Sorry, didn't realise that the .xml files were generated and actually contain javascript.

When you suspend the validators, the error messages that you've generated don't go away. To get them to go away, you have to manually delete them.

  1. Suspend the validators
  2. Click on the 'Content is not allowed in prolog' message, right click and delete. You can select multiple ones, or all of them.
  3. Do a Project->Clean. The messages should not come back.

I think that because you've suspended the validators, Eclipse doesn't realise it has to delete the old error messages which came from the validators.

How do you align left / right a div without using float?

you could use things like display: inline-block but I think you would need to set up another div to move it over, if there is nothing going to the left of the button you could use margins to move it into place.

Alternatively but not a good solution, you could position tags; put the encompassing div as position: relative and then the div of the button as position: absolute; right: 0, but like I said this is probably not the best solution

HTML

<div class="parent">
  <div>Left Div</div>
  <div class="right">Right Div</div>
</div>

CSS

.parent {
  position: relative;
}
.right {
    position: absolute;
    right: 0;
}

splitting a string based on tab in the file

Python has support for CSV files in the eponymous csv module. It is relatively misnamed since it support much more that just comma separated values.

If you need to go beyond basic word splitting you should take a look. Say, for example, because you are in need to deal with quoted values...

Difference between `constexpr` and `const`

const applies for variables, and prevents them from being modified in your code.

constexpr tells the compiler that this expression results in a compile time constant value, so it can be used in places like array lengths, assigning to const variables, etc. The link given by Oli has a lot of excellent examples.

Basically they are 2 different concepts altogether, and can (and should) be used together.

How to change a <select> value from JavaScript

$('#select').val('defaultValue'); 
$('#select').change();

This will also trigger events hooked to this select

How do I run a Python program?

if you dont want call filename.py you can add .PY to the PATHEXT, that way you will just call filename

MySQL Join Where Not Exists

I'd use a 'where not exists' -- exactly as you suggest in your title:

SELECT `voter`.`ID`, `voter`.`Last_Name`, `voter`.`First_Name`,
       `voter`.`Middle_Name`, `voter`.`Age`, `voter`.`Sex`,
       `voter`.`Party`, `voter`.`Demo`, `voter`.`PV`,
       `household`.`Address`, `household`.`City`, `household`.`Zip`
FROM (`voter`)
JOIN `household` ON `voter`.`House_ID`=`household`.`id`
WHERE `CT` = '5'
AND `Precnum` = 'CTY3'
AND  `Last_Name`  LIKE '%Cumbee%'
AND  `First_Name`  LIKE '%John%'

AND NOT EXISTS (
  SELECT * FROM `elimination`
   WHERE `elimination`.`voter_id` = `voter`.`ID`
)

ORDER BY `Last_Name` ASC
LIMIT 30

That may be marginally faster than doing a left join (of course, depending on your indexes, cardinality of your tables, etc), and is almost certainly much faster than using IN.

Django - limiting query results

Looks like the solution in the question doesn't work with Django 1.7 anymore and raises an error: "Cannot reorder a query once a slice has been taken"

According to the documentation https://docs.djangoproject.com/en/dev/topics/db/queries/#limiting-querysets forcing the “step” parameter of Python slice syntax evaluates the Query. It works this way:

Model.objects.all().order_by('-id')[:10:1]

Still I wonder if the limit is executed in SQL or Python slices the whole result array returned. There is no good to retrieve huge lists to application memory.

Javascript + Regex = Nothing to repeat error?

You need to double the backslashes used to escape the regular expression special characters. However, as @Bohemian points out, most of those backslashes aren't needed. Unfortunately, his answer suffers from the same problem as yours. What you actually want is:

The backslash is being interpreted by the code that reads the string, rather than passed to the regular expression parser. You want:

"[\\[\\]?*+|{}\\\\()@.\n\r]"

Note the quadrupled backslash. That is definitely needed. The string passed to the regular expression compiler is then identical to @Bohemian's string, and works correctly.

Is there a way to run Python on Android?

Yes! : Android Scripting Environment

An example via Matt Cutts via SL4A -- "here’s a barcode scanner written in six lines of Python code:

import android
droid = android.Android()
code = droid.scanBarcode()
isbn = int(code['result']['SCAN_RESULT'])
url = "http://books.google.com?q=%d" % isbn
droid.startActivity('android.intent.action.VIEW', url)

How do a LDAP search/authenticate against this LDAP in Java

You can also use the following code :

package com.agileinfotech.bsviewer.ldap;

import java.util.Hashtable;
import java.util.ResourceBundle;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

public class LDAPLoginAuthentication {
    public LDAPLoginAuthentication() {
        // TODO Auto-generated constructor
    }

    ResourceBundle resBundle = ResourceBundle.getBundle("settings");

    @SuppressWarnings("unchecked")
    public String authenticateUser(String username, String password) {
        String strUrl = "success";
        Hashtable env = new Hashtable(11);
        boolean b = false;
        String Securityprinciple = "cn=" + username + "," + resBundle.getString("UserSearch");
        env.put(Context.INITIAL_CONTEXT_FACTORY, resBundle.getString("InitialContextFactory"));
        env.put(Context.PROVIDER_URL, resBundle.getString("Provider_url"));
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, Securityprinciple);
        env.put(Context.SECURITY_CREDENTIALS, password);

        try {
            // Create initial context
            DirContext ctx = new InitialDirContext(env);
            // Close the context when we're done
            b = true;
            ctx.close();

        } catch (NamingException e) {
            b = false;
        } finally {
            if (b) {
                strUrl = "success";
            } else {
                strUrl = "failer";
            }
        }
        return strUrl;
    }
}

Difference between 2 dates in SQLite

This answer is a little long-winded, and the documentation will not tell you this (because they assume you are storing your dates as UTC dates in the database), but the answer to this question depends largely on the timezone that your dates are stored in. You also don't use Date('now'), but use the julianday() function, to calculate both dates back against a common date, then subtract the difference of those results from each other.

If your dates are stored in UTC:

SELECT julianday('now') - julianday(DateCreated) FROM Payment;

This is what the top-ranked answer has, and is also in the documentation. It is only part of the picture, and a very simplistic answer, if you ask me.

If your dates are stored in local time, using the above code will make your answer WRONG by the number of hours your GMT offset is. If you are in the Eastern U.S. like me, which is GMT -5, your result will have 5 hours added onto it. And if you try making DateCreated conform to UTC because julianday('now') goes against a GMT date:

SELECT julianday('now') - julianday(DateCreated, 'utc') FROM Payment;

This has a bug where it will add an hour for a DateCreated that is during Daylight Savings Time (March-November). Say that "now" is at noon on a non-DST day, and you created something back in June (during DST) at noon, your result will give 1 hour apart, instead of 0 hours, for the hours portion. You'd have to write a function in your application's code that is displaying the result to modify the result and subtract an hour from DST dates. I did that, until I realized there's a better solution to that problem that I was having: SQLite vs. Oracle - Calculating date differences - hours

Instead, as was pointed out to me, for dates stored in local time, make both match to local time:

SELECT julianday('now', 'localtime') - julianday(DateCreated) FROM Payment;

Or append 'Z' to local time:

julianday(datetime('now', 'localtime')||'Z') - julianday(CREATED_DATE||'Z')

Both of these seem to compensate and do not add the extra hour for DST dates and do straight subtraction - so that item created at noon on a DST day, when checking at noon on a non-DST day, will not get an extra hour when performing the calculation.

And while I recognize most will say don't store dates in local time in your database, and to store them in UTC so you don't run into this, well not every application has a world-wide audience, and not every programmer wants to go through the conversion of EVERY date in their system to UTC and back again every time they do a GET or SET in the database and deal with figuring out if something is local or in UTC.

OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

Unless there is some other requirement not specified, I would simply convert your color image to grayscale and work with that only (no need to work on the 3 channels, the contrast present is too high already). Also, unless there is some specific problem regarding resizing, I would work with a downscaled version of your images, since they are relatively large and the size adds nothing to the problem being solved. Then, finally, your problem is solved with a median filter, some basic morphological tools, and statistics (mostly for the Otsu thresholding, which is already done for you).

Here is what I obtain with your sample image and some other image with a sheet of paper I found around:

enter image description here enter image description here

The median filter is used to remove minor details from the, now grayscale, image. It will possibly remove thin lines inside the whitish paper, which is good because then you will end with tiny connected components which are easy to discard. After the median, apply a morphological gradient (simply dilation - erosion) and binarize the result by Otsu. The morphological gradient is a good method to keep strong edges, it should be used more. Then, since this gradient will increase the contour width, apply a morphological thinning. Now you can discard small components.

At this point, here is what we have with the right image above (before drawing the blue polygon), the left one is not shown because the only remaining component is the one describing the paper:

enter image description here

Given the examples, now the only issue left is distinguishing between components that look like rectangles and others that do not. This is a matter of determining a ratio between the area of the convex hull containing the shape and the area of its bounding box; the ratio 0.7 works fine for these examples. It might be the case that you also need to discard components that are inside the paper, but not in these examples by using this method (nevertheless, doing this step should be very easy especially because it can be done through OpenCV directly).

For reference, here is a sample code in Mathematica:

f = Import["http://thwartedglamour.files.wordpress.com/2010/06/my-coffee-table-1-sa.jpg"]
f = ImageResize[f, ImageDimensions[f][[1]]/4]
g = MedianFilter[ColorConvert[f, "Grayscale"], 2]
h = DeleteSmallComponents[Thinning[
     Binarize[ImageSubtract[Dilation[g, 1], Erosion[g, 1]]]]]
convexvert = ComponentMeasurements[SelectComponents[
     h, {"ConvexArea", "BoundingBoxArea"}, #1 / #2 > 0.7 &], 
     "ConvexVertices"][[All, 2]]
(* To visualize the blue polygons above: *)
Show[f, Graphics[{EdgeForm[{Blue, Thick}], RGBColor[0, 0, 1, 0.5], 
     Polygon @@ convexvert}]]

If there are more varied situations where the paper's rectangle is not so well defined, or the approach confuses it with other shapes -- these situations could happen due to various reasons, but a common cause is bad image acquisition -- then try combining the pre-processing steps with the work described in the paper "Rectangle Detection based on a Windowed Hough Transform".

How to display line numbers in 'less' (GNU)

You can set an enviroment variable to always have these options apply to all less'd file:

export LESS='-RS#3NM~g'

You seem to not be depending on "@angular/core". This is an error

This happened to me when I was mixing package managers. My project was generated with Yarn, and after that, I added a couple of dependencies using npm install (this created the package-lock.json with only added dependencies).

Apparently, ng serve used package-lock.json and couldn't find Angular dependencies there. After I started using only Yarn, i.e. yarn add instead of npm install, the error was gone.

Undefined variable: $_SESSION

You need make sure to start the session at the top of every PHP file where you want to use the $_SESSION superglobal. Like this:

<?php
  session_start();
  echo $_SESSION['youritem'];
?>

You forgot the Session HELPER.

Check this link : book.cakephp.org/2.0/en/core-libraries/helpers/session.html

What is the meaning of "int(a[::-1])" in Python?

The notation that is used in

a[::-1]

means that for a given string/list/tuple, you can slice the said object using the format

<object_name>[<start_index>, <stop_index>, <step>]

This means that the object is going to slice every "step" index from the given start index, till the stop index (excluding the stop index) and return it to you.

In case the start index or stop index is missing, it takes up the default value as the start index and stop index of the given string/list/tuple. If the step is left blank, then it takes the default value of 1 i.e it goes through each index.

So,

a = '1234'
print a[::2]

would print

13

Now the indexing here and also the step count, support negative numbers. So, if you give a -1 index, it translates to len(a)-1 index. And if you give -x as the step count, then it would step every x'th value from the start index, till the stop index in the reverse direction. For example

a = '1234'
print a[3:0:-1]

This would return

432

Note, that it doesn't return 4321 because, the stop index is not included.

Now in your case,

str(int(a[::-1]))

would just reverse a given integer, that is stored in a string, and then convert it back to a string

i.e "1234" -> "4321" -> 4321 -> "4321"

If what you are trying to do is just reverse the given string, then simply a[::-1] would work .

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger

I had the same issue, for me this fixed the issue:
right click on the project ->maven -> update project

maven -> update project

"Data too long for column" - why?

Very old question, but I tried everything suggested above and still could not get it resolved.

Turns out that, I had after insert/update trigger for the main table which tracked the changes by inserting the record in history table having similar structure. I increased the size in the main table column but forgot to change the size of history table column and that created the problem.

I did similar changes in the other table and error is gone.

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

Using bash regex capabilities:

re="^([^-]+)-(.*)$"
[[ "ABCDE-123456" =~ $re ]] && var1="${BASH_REMATCH[1]}" && var2="${BASH_REMATCH[2]}"
echo $var1
echo $var2

OUTPUT

ABCDE
123456

'readline/readline.h' file not found

You reference a Linux distribution, so you need to install the readline development libraries

On Debian based platforms, like Ubuntu, you can run:

sudo apt-get install libreadline-dev 

and that should install the correct headers in the correct places,.

If you use a platform with yum, like SUSE, then the command should be:

yum install readline-devel

How to convert Excel values into buckets?

Here is a solution which:

  • Is self contained
  • Does not require VBA
  • Is not limited in the same way as IF regarding bucket maximums
  • Does not require precise values as LOOKUP does

 

=INDEX({"Small","Medium","Large"},LARGE(IF([INPUT_VALUE]>{0,11,21},{1,2,3}),1))

 

Replace [INPUT_VALUE] with the appropriate cell reference and make sure to press Ctrl+Shift+Enter as this is an array formula.

Each of the array constants can be expanded to be arbitrarily long; as long as the formula does not exceed Excel's maximum of 8,192 characters. The first constant should contain the return values, the second should contain ordered thresholds,and the third should simply be ascending integers.

Component is not part of any NgModule or the module has not been imported into your module

I ran into this same issue and none of what I was seeing here was working. If you are listing your Component in the app-routing.module issue you may have run into the same problem I was having.

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { NavbarComponent } from './navbar/navbar.component';
import { TopbarComponent } from './topbar/topbar.component';
import { FooterbarComponent } from './footerbar/footerbar.component';
import { MRDBGlobalConstants } from './shared/mrdb.global.constants';
import {AppRoutingModule} from './app.routing';
import {HomeModule} from './Home/home.module';
// import HomeComponent here

@NgModule({
  declarations: [
    AppComponent,
    FooterbarComponent,
    TopbarComponent,
    NavbarComponent,
    // add HomeComponent here
  ],
  imports: [
    BrowserModule,
    HttpModule,
    AppRoutingModule,
    HomeModule  // remove this

  ],
  providers: [MRDBGlobalConstants],
  bootstrap: [AppComponent]
})
export class AppModule { }

home/index.ts

export * from './';

app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './components';

const routes: Routes = [
    { path: 'app/home', component: HomeComponent },
    { path: '', redirectTo: 'app/home', pathMatch: 'full' },
    { path: '**', redirectTo: 'app/home' }
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule { }

home/home.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
// import { HomeComponent } from './home.component'; This would cause app to break
import { HomeComponent } from './';
@NgModule({
  imports: [
    CommonModule
  ],
  exports: [HomeComponent],
  declarations: [HomeComponent]
})
export class HomeModule { }

I won't claim to understand exactly why this is the case, but when using indexing to export components (and I would assume the same for services, etc.), when referencing the same component in separate modules you need to import them from the same file, in this case the index, in order to avoid this issue.

href around input type submit

I agree with Quentin. It doesn't make sense as to why you want to do it like that. It's part of the Semantic Web concept. You have to plan out the objects of your web site for future integration/expansion. Another web app or web site cannot interact with your content if it doesn't follow the proper use-case.

IE and Firefox are two different beasts. There are a lot of things that IE allows that Firefox and other standards-aware browsers reject.

If you're trying to create buttons without actually submitting data then use a combination of DIV/CSS.

Get file from project folder java

If you don't specify any path and put just the file (Just like you did), the default directory is always the one of your project (It's not inside the "src" folder. It's just inside the folder of your project).

How to convert map to url query string?

The most robust one I saw off-the-shelf is the URLEncodedUtils class from Apache Http Compoments (HttpClient 4.0).

The method URLEncodedUtils.format() is what you need.

It doesn't use map so you can have duplicate parameter names, like,

  a=1&a=2&b=3

Not that I recommend this kind of use of parameter names.

How do pointer-to-pointer's work in C? (and when might you use them?)

Consider the below figure and program to understand this concept better.

Double pointer diagram

As per the figure, ptr1 is a single pointer which is having address of variable num.

ptr1 = &num;

Similarly ptr2 is a pointer to pointer(double pointer) which is having the address of pointer ptr1.

ptr2 = &ptr1;

A pointer which points to another pointer is known as double pointer. In this example ptr2 is a double pointer.

Values from above diagram :

Address of variable num has : 1000
Address of Pointer ptr1 is: 2000
Address of Pointer ptr2 is: 3000

Example:

#include <stdio.h>

int main ()
{
   int  num = 10;
   int  *ptr1;
   int  **ptr2;

   // Take the address of var 
   ptr1 = &num;

   // Take the address of ptr1 using address of operator &
   ptr2 = &ptr1;

   // Print the value
   printf("Value of num = %d\n", num );
   printf("Value available at *ptr1 = %d\n", *ptr1 );
   printf("Value available at **ptr2 = %d\n", **ptr2);
}

Output:

Value of num = 10
Value available at *ptr1 = 10
Value available at **ptr2 = 10

Extract regression coefficient values

Just pass your regression model into the following function:

    plot_coeffs <- function(mlr_model) {
      coeffs <- coefficients(mlr_model)
      mp <- barplot(coeffs, col="#3F97D0", xaxt='n', main="Regression Coefficients")
      lablist <- names(coeffs)
      text(mp, par("usr")[3], labels = lablist, srt = 45, adj = c(1.1,1.1), xpd = TRUE, cex=0.6)
    }

Use as follows:

model <- lm(Petal.Width ~ ., data = iris)

plot_coeffs(model)

enter image description here

Switch with if, else if, else, and loops inside case

Seems like kind of a homely way of doing things, but if you must... you could restructure it as such to fit your needs:

boolean found = false;

case 1:

for (Element arrayItem : array) {
    if (arrayItem == whateverValue) {
        found = true;    
    } // else if ...
}
if (found) {
    break;
}
case 2:

Combining a class selector and an attribute selector with jQuery

Combine them. Literally combine them; attach them together without any punctuation.

$('.myclass[reference="12345"]')

Your first selector looks for elements with the attribute value, contained in elements with the class.
The space is being interpreted as the descendant selector.

Your second selector, like you said, looks for elements with either the attribute value, or the class, or both.
The comma is being interpreted as the multiple selector operator — whatever that means (CSS selectors don't have a notion of "operators"; the comma is probably more accurately known as a delimiter).

Splitting a continuous variable into equal sized groups

If you want to split into 3 equally distributed groups, the answer is the same as Ben Bolker's answer above - use ggplot2::cut_number(). For sake of completion here are the 3 methods of converting continuous to categorical (binning).

  • cut_number(): Makes n groups with (approximately) equal numbers of observation
  • cut_interval(): Makes n groups with equal range
  • cut_width(): Makes groups of width

My go-to is cut_number() because this uses evenly spaced quantiles for binning observations. Here's an example with skewed data.

library(tidyverse)

skewed_tbl <- tibble(
    counts = c(1:100, 1:50, 1:20, rep(1:10, 3), 
               rep(1:5, 5), rep(1:2, 10), rep(1, 20))
    ) %>%
    mutate(
        counts_cut_number   = cut_number(counts, n = 4),
        counts_cut_interval = cut_interval(counts, n = 4),
        counts_cut_width    = cut_width(counts, width = 25)
        ) 

# Data
skewed_tbl
#> # A tibble: 265 x 4
#>    counts counts_cut_number counts_cut_interval counts_cut_width
#>     <dbl> <fct>             <fct>               <fct>           
#>  1      1 [1,3]             [1,25.8]            [-12.5,12.5]    
#>  2      2 [1,3]             [1,25.8]            [-12.5,12.5]    
#>  3      3 [1,3]             [1,25.8]            [-12.5,12.5]    
#>  4      4 (3,13]            [1,25.8]            [-12.5,12.5]    
#>  5      5 (3,13]            [1,25.8]            [-12.5,12.5]    
#>  6      6 (3,13]            [1,25.8]            [-12.5,12.5]    
#>  7      7 (3,13]            [1,25.8]            [-12.5,12.5]    
#>  8      8 (3,13]            [1,25.8]            [-12.5,12.5]    
#>  9      9 (3,13]            [1,25.8]            [-12.5,12.5]    
#> 10     10 (3,13]            [1,25.8]            [-12.5,12.5]    
#> # ... with 255 more rows

summary(skewed_tbl$counts)
#>    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
#>    1.00    3.00   13.00   25.75   42.00  100.00

# Histogram showing skew
skewed_tbl %>%
    ggplot(aes(counts)) +
    geom_histogram(bins = 30)

# cut_number() evenly distributes observations into bins by quantile
skewed_tbl %>%
    ggplot(aes(counts_cut_number)) +
    geom_bar()

# cut_interval() evenly splits the interval across the range
skewed_tbl %>%
    ggplot(aes(counts_cut_interval)) +
    geom_bar()

# cut_width() uses the width = 25 to create bins that are 25 in width
skewed_tbl %>%
    ggplot(aes(counts_cut_width)) +
    geom_bar()

Created on 2018-11-01 by the reprex package (v0.2.1)

Setting selection to Nothing when programming Excel

If you select a cell in an already selected range, it will not work. But, Selecting a range outside the original selection will clear the original selection.

'* The original selection *' ActiveSheet.range("A1:K10").Select

'* New Selections *' Activesheet.Range("L1").Select

'* Then *' Activesheet.Range("A1").Select

How to use XPath preceding-sibling correctly

I also like to build locators from up to bottom like:

//div[contains(@class,'btn-group')][./button[contains(.,'Arcade Reader')]]/button[@name='settings']

It's pretty simple, as we just search btn-group with button[contains(.,'Arcade Reader')] and get it's button[@name='settings']

That's just another option to build xPath locators

What is the profit of searching wrapper element: you can return it by method (example in java) and just build selenium constructions like:

getGroupByName("Arcade Reader").find("button[name='settings']");
getGroupByName("Arcade Reader").find("button[name='delete']");

or even simplify more

getGroupButton("Arcade Reader", "delete").click();

How can I compile my Perl script so it can be executed on systems without perl installed?

Look at PAR (Perl Archiving Toolkit).

PAR is a Cross-Platform Packaging and Deployment tool, dubbed as a cross between Java's JAR and Perl2EXE/PerlApp.

Iterating over Typescript Map

You can also apply the array map method to the Map.entries() iterable:

[...myMap.entries()].map(
     ([key, value]: [string, number]) => console.log(key, value)
);

Also, as noted in other answers, you may have to enable down level iteration in your tsconfig.json (under compiler options):

  "downlevelIteration": true,

php - How do I fix this illegal offset type error

check $xml->entry[$i] exists and is an object before trying to get a property of it

 if(isset($xml->entry[$i]) && is_object($xml->entry[$i])){
   $source = $xml->entry[$i]->source;          
   $s[$source] += 1;
 }

or $source might not be a legal array offset but an array, object, resource or possibly null

Entity Framework is Too Slow. What are my options?

I used EF, LINQ to SQL and dapper. Dapper is the fastest. Example: I needed 1000 main records with 4 sub records each. I used LINQ to sql, it took about 6 seconds. I then switched to dapper, retrieved 2 record sets from the single stored procedure and for each record added the sub records. Total time 1 second.

Also the stored procedure used table value functions with cross apply, I found scalar value functions to be very slow.

My advice would be to use EF or LINQ to SQL and for certain situations switch to dapper.

How to get names of classes inside a jar file?

Mac OS: On Terminal:

vim <your jar location>

after jar gets opened, press / and pass your class name and hit enter

How to check for an empty struct?

Just a quick addition, because I tackled the same issue today:

With Go 1.13 it is possible to use the new isZero() method:

if reflect.ValueOf(session).IsZero() {
     // do stuff...
}

I didn't test this regarding performance, but I guess that this should be faster, than comparing via reflect.DeepEqual().

Setting Margin Properties in code

The Margin property returns a Thickness structure, of which Left is a property. What the statement does is copying the structure value from the Margin property and setting the Left property value on the copy. You get an error because the value that you set will not be stored back into the Margin property.

(Earlier versions of C# would just let you do it without complaining, causing a lot of questions in newsgroups and forums on why a statement like that had no effect at all...)

To set the property you would need to get the Thickness structure from the Margin property, set the value and store it back:

Thickness m = MyControl.Margin;
m.Left = 10;
MyControl.Margin = m;

If you are going to set all the margins, just create a Thickness structure and set them all at once:

MyControl.Margin = new Thickness(10, 10, 10, 10);

Where to place the 'assets' folder in Android Studio?

right click on app folder->new->folder->Assets folder->set Target Source set->click on finish button

Serializing/deserializing with memory stream

This code works for me:

public void Run()
{
    Dog myDog = new Dog();
    myDog.Name= "Foo";
    myDog.Color = DogColor.Brown;

    System.Console.WriteLine("{0}", myDog.ToString());

    MemoryStream stream = SerializeToStream(myDog);

    Dog newDog = (Dog)DeserializeFromStream(stream);

    System.Console.WriteLine("{0}", newDog.ToString());
}

Where the types are like this:

[Serializable]
public enum DogColor
{
    Brown,
    Black,
    Mottled
}

[Serializable]
public class Dog
{
    public String Name
    {
        get; set;
    }

    public DogColor Color
    {
        get;set;
    }

    public override String ToString()
    {
        return String.Format("Dog: {0}/{1}", Name, Color);
    }
}

and the utility methods are:

public static MemoryStream SerializeToStream(object o)
{
    MemoryStream stream = new MemoryStream();
    IFormatter formatter = new BinaryFormatter();
    formatter.Serialize(stream, o);
    return stream;
}

public static object DeserializeFromStream(MemoryStream stream)
{
    IFormatter formatter = new BinaryFormatter();
    stream.Seek(0, SeekOrigin.Begin);
    object o = formatter.Deserialize(stream);
    return o;
}

Can I escape html special chars in javascript?

This is, by far, the fastest way I have seen it done. Plus, it does it all without adding, removing, or changing elements on the page.

function escapeHTML(unsafeText) {
    let div = document.createElement('div');
    div.innerText = unsafeText;
    return div.innerHTML;
}

Calculate RSA key fingerprint

If your SSH agent is running, it is

ssh-add -l

to list RSA fingerprints of all identities, or -L for listing public keys.

If your agent is not running, try:

ssh-agent sh -c 'ssh-add; ssh-add -l'

And for your public keys:

ssh-agent sh -c 'ssh-add; ssh-add -L'

If you get the message: 'The agent has no identities.', then you have to generate your RSA key by ssh-keygen first.

Loop through JSON object List

I have the following call:

$('#select_box_id').change(function() {
        var action = $('#my_form').attr('action');
    $.get(action,{},function(response){
        $.each(response.result,function(i) {

            alert("key is: " + i + ", val is: " + response.result[i]);

        });
    }, 'json');
    });

The structure coming back from the server look like:

{"result":{"1":"waterskiing","2":"canoeing","18":"windsurfing"}}

Add some word to all or some rows in Excel?

  1. Insert a column left to the column in question(adding column A beside column B).
  2. Provide the value you want to append in 1st cell of column A
  3. Insert a column right to the column in question ( column C)
  4. Add this formula -> =CONCATENATE("A1","B1")
  5. Drag it down to apply to all values in column
  6. You will find concatenated values in column C

This worked for me !

How to print a double with two decimals in Android?

For Displaying digit upto two decimal places there are two possibilities - 1) Firstly, you only want to display decimal digits if it's there. For example - i) 12.10 to be displayed as 12.1, ii) 12.00 to be displayed as 12. Then use-

DecimalFormat formater = new DecimalFormat("#.##"); 

2) Secondly, you want to display decimal digits irrespective of decimal present For example -i) 12.10 to be displayed as 12.10. ii) 12 to be displayed as 12.00.Then use-

DecimalFormat formater = new DecimalFormat("0.00"); 

What is the best way to return different types of ResponseEntity in Spring MVC or Spring-Boot

Here is a way that I would do it:

public ResponseEntity < ? extends BaseResponse > message(@PathVariable String player) { //REST Endpoint.

 try {
  Integer.parseInt(player);
  return new ResponseEntity < ErrorResponse > (new ErrorResponse("111", "player is not found"), HttpStatus.BAD_REQUEST);
 } catch (Exception e) {


 }
 Message msg = new Message(player, "Hello " + player);
 return new ResponseEntity < Message > (msg, HttpStatus.OK);

}

@RequestMapping(value = "/getAll/{player}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity < List < ? extends BaseResponse >> messageAll(@PathVariable String player) { //REST Endpoint.

 try {
  Integer.parseInt(player);
  List < ErrorResponse > errs = new ArrayList < ErrorResponse > ();
  errs.add(new ErrorResponse("111", "player is not found"));
  return new ResponseEntity < List < ? extends BaseResponse >> (errs, HttpStatus.BAD_REQUEST);
 } catch (Exception e) {


 }
 Message msg = new Message(player, "Hello " + player);
 List < Message > msgList = new ArrayList < Message > ();
 msgList.add(msg);
 return new ResponseEntity < List < ? extends BaseResponse >> (msgList, HttpStatus.OK);

}

Maven: How to run a .java file from command line passing arguments

Adding a shell script e.g. run.sh makes it much more easier:

#!/usr/bin/env bash
export JAVA_PROGRAM_ARGS=`echo "$@"`
mvn exec:java -Dexec.mainClass="test.Main" -Dexec.args="$JAVA_PROGRAM_ARGS"

Then you are able to execute:

./run.sh arg1 arg2 arg3

Purpose of #!/usr/bin/python3 shebang

The exec system call of the Linux kernel understands shebangs (#!) natively

When you do on bash:

./something

on Linux, this calls the exec system call with the path ./something.

This line of the kernel gets called on the file passed to exec: https://github.com/torvalds/linux/blob/v4.8/fs/binfmt_script.c#L25

if ((bprm->buf[0] != '#') || (bprm->buf[1] != '!'))

It reads the very first bytes of the file, and compares them to #!.

If the comparison is true, then the rest of the line is parsed by the Linux kernel, which makes another exec call with path /usr/bin/python3 and current file as the first argument:

/usr/bin/python3 /path/to/script.py

and this works for any scripting language that uses # as a comment character.

And analogously, if you decide to use env instead, which you likely should always do to work on systems that have the python3 in a different location, notably pyenv, see also this question, the shebang:

#!/usr/bin/env python3

ends up calling analogously:

/usr/bin/env python3 /path/to/script.py

which does what you expect from env python3: searches PATH for python3 and runs /usr/bin/python3 /path/to/script.py.

And yes, you can make an infinite loop with:

printf '#!/a\n' | sudo tee /a
sudo chmod +x /a
/a

Bash recognizes the error:

-bash: /a: /a: bad interpreter: Too many levels of symbolic links

#! just happens to be human readable, but that is not required.

If the file started with different bytes, then the exec system call would use a different handler. The other most important built-in handler is for ELF executable files: https://github.com/torvalds/linux/blob/v4.8/fs/binfmt_elf.c#L1305 which checks for bytes 7f 45 4c 46 (which also happens to be human readable for .ELF). Let's confirm that by reading the 4 first bytes of /bin/ls, which is an ELF executable:

head -c 4 "$(which ls)" | hd 

output:

00000000  7f 45 4c 46                                       |.ELF|
00000004                                                                 

So when the kernel sees those bytes, it takes the ELF file, puts it into memory correctly, and starts a new process with it. See also: How does kernel get an executable binary file running under linux?

Finally, you can add your own shebang handlers with the binfmt_misc mechanism. For example, you can add a custom handler for .jar files. This mechanism even supports handlers by file extension. Another application is to transparently run executables of a different architecture with QEMU.

I don't think POSIX specifies shebangs however: https://unix.stackexchange.com/a/346214/32558 , although it does mention in on rationale sections, and in the form "if executable scripts are supported by the system something may happen". macOS and FreeBSD also seem to implement it however.

PATH search motivation

Likely, one big motivation for the existence of shebangs is the fact that in Linux, we often want to run commands from PATH just as:

basename-of-command

instead of:

/full/path/to/basename-of-command

But then, without the shebang mechanism, how would Linux know how to launch each type of file?

Hardcoding the extension in commands:

 basename-of-command.py

or implementing PATH search on every interpreter:

python3 basename-of-command

would be a possibility, but this has the major problem that everything breaks if we ever decide to refactor the command into another language.

Shebangs solve this problem beautifully.

See also: Why do people write #!/usr/bin/env python on the first line of a Python script?

Gunicorn worker timeout error

Could it be this? http://docs.gunicorn.org/en/latest/settings.html#timeout

Other possibilities could be your response is taking too long or is stuck waiting.

Dart SDK is not configured

I followed the following steps to solve this problem:

First, Go to: File->Settings->Language & Framework->Flutter

There under the: 'flutter SDK path', put in the location where you have installed Flutter Mine was at: C:\src\flutter

Click Apply then OK and the android studio will refresh. The problem will be solved.

Is it possible to use 'else' in a list comprehension?

Also, would I be right in concluding that a list comprehension is the most efficient way to do this?

Maybe. List comprehensions are not inherently computationally efficient. It is still running in linear time.

From my personal experience: I have significantly reduced computation time when dealing with large data sets by replacing list comprehensions (specifically nested ones) with for-loop/list-appending type structures you have above. In this application I doubt you will notice a difference.

Node.js check if file exists

Edit: Since node v10.0.0we could use fs.promises.access(...)

Example async code that checks if file exists:

async function checkFileExists(file) {
  return fs.promises.access(file, fs.constants.F_OK)
           .then(() => true)
           .catch(() => false)
}

An alternative for stat might be using the new fs.access(...):

minified short promise function for checking:

s => new Promise(r=>fs.access(s, fs.constants.F_OK, e => r(!e)))

Sample usage:

let checkFileExists = s => new Promise(r=>fs.access(s, fs.constants.F_OK, e => r(!e)))
checkFileExists("Some File Location")
  .then(bool => console.log(´file exists: ${bool}´))

expanded Promise way:

// returns a promise which resolves true if file exists:
function checkFileExists(filepath){
  return new Promise((resolve, reject) => {
    fs.access(filepath, fs.constants.F_OK, error => {
      resolve(!error);
    });
  });
}

or if you wanna do it synchronously:

function checkFileExistsSync(filepath){
  let flag = true;
  try{
    fs.accessSync(filepath, fs.constants.F_OK);
  }catch(e){
    flag = false;
  }
  return flag;
}

How to style SVG with external CSS?

I know its an old post, but just to clear this problem... you're just using your classes at the wrong place :D

First of all you could use

svg { fill: red; }

in your main.css to get it red. This does have effect. You could probably use node selectors as well to get specific paths.

Second thing is, you declared the class to the img-tag.

<img class='socIcon'....

You actually should declare it inside your SVG. if you have different paths you could define more of course.

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet href="stylesheets/main.css" type="text/css"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 56.69 56.69">
<g>
    <path class="myClassForMyPath" d="M28.44......./>
</g>
</svg>

Now you could change the color in your main.css like

.myClassForMyPath {
    fill: yellow;
}

Linux: command to open URL in default browser

I think using xdg-open http://example.com is probably the best choice.

In case they don't have it installed I suppose they might have just kde-open or gnome-open (both of which take a single file/url) or some other workaround such as looping over common browser executable names until you find one which can be executed(using which). If you want a full list of workarounds/fallbacks I suggest reading xdg-open(it's a shell script which calls out to kde-open/gnome-open/etc. or some other fallback).

But since xdg-open and xdg-mime(used for one of the fallbacks,) are shell scripts I'd recommend including them in your application and if calling which xdg-open fails add them to temporary PATH variable in your subprograms environment and call out to them. If xdg-open fails, I'd recommend throwing an Exception with an error message from what it output on stderr and catching the exception and printing/displaying the error message.

I would ignore the java awt Desktop solution as the bug seems to indicate they don't plan on supporting non-gnome desktops anytime soon.

How can one grab a stack trace in C?

Solaris has the pstack command, which was also copied into Linux.

Highlight label if checkbox is checked

You can't do this with CSS alone. Using jQuery you can do

HTML

<label id="lab">Checkbox</label>
<input id="check" type="checkbox" />

CSS

.highlight{
    background:yellow;
}

jQuery

$('#check').click(function(){
    $('#lab').toggleClass('highlight')
})

This will work in all browsers

Check working example at http://jsfiddle.net/LgADZ/

2 ways for "ClearContents" on VBA Excel, but 1 work fine. Why?

That is because you are not fully qualifying your cells object. Try this

With Worksheets("SheetName")
    .Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With

Notice the DOT before Cells?

T-test in Pandas

it depends what sort of t-test you want to do (one sided or two sided dependent or independent) but it should be as simple as:

from scipy.stats import ttest_ind

cat1 = my_data[my_data['Category']=='cat1']
cat2 = my_data[my_data['Category']=='cat2']

ttest_ind(cat1['values'], cat2['values'])
>>> (1.4927289925706944, 0.16970867501294376)

it returns a tuple with the t-statistic & the p-value

see here for other t-tests http://docs.scipy.org/doc/scipy/reference/stats.html

How to set text size in a button in html

Try this, its working in FF

body,
input,
select,
button {
 font-family: Arial,Helvetica,sans-serif;
 font-size: 14px;
}

How can I install pip on Windows?

Here how to install pip the easy way.

  1. Copy and paste this content in a file as get-pip.py.
  2. Copy and paste get-pip.py into the Python folder.C:\Python27.
  3. Double click on get-pip.py file. It will install pip on your computer.
  4. Now you have to add C:\Python27\Scripts path to your environment variable. Because it includes the pip.exe file.
  5. Now you are ready to use pip. Open cmd and type as
    pip install package_name

Accessing member of base class

You are incorrectly using the super and this keyword. Here is an example of how they work:

class Animal {
    public name: string;
    constructor(name: string) { 
        this.name = name;
    }
    move(meters: number) {
        console.log(this.name + " moved " + meters + "m.");
    }
}

class Horse extends Animal {
    move() {
        console.log(super.name + " is Galloping...");
        console.log(this.name + " is Galloping...");
        super.move(45);
    }
}

var tom: Animal = new Horse("Tommy the Palomino");

Animal.prototype.name = 'horseee'; 

tom.move(34);
// Outputs:

// horseee is Galloping...
// Tommy the Palomino is Galloping...
// Tommy the Palomino moved 45m.

Explanation:

  1. The first log outputs super.name, this refers to the prototype chain of the object tom, not the object tom self. Because we have added a name property on the Animal.prototype, horseee will be outputted.
  2. The second log outputs this.name, the this keyword refers to the the tom object itself.
  3. The third log is logged using the move method of the Animal base class. This method is called from Horse class move method with the syntax super.move(45);. Using the super keyword in this context will look for a move method on the prototype chain which is found on the Animal prototype.

Remember TS still uses prototypes under the hood and the class and extends keywords are just syntactic sugar over prototypical inheritance.

Difference between web reference and service reference?

The service reference is the newer interface for adding references to all manner of WCF services (they may not be web services) whereas Web reference is specifically concerned with ASMX web references.

You can access web references via the advanced options in add service reference (if I recall correctly).

I'd use service reference because as I understand it, it's the newer mechanism of the two.

How should strace be used?

In simple words, strace traces all system calls issued by a program along with their return codes. Think things such as file/socket operations and a lot more obscure ones.

It is most useful if you have some working knowledge of C since here system calls would more accurately stand for standard C library calls.

Let's say your program is /usr/local/bin/cough. Simply use:

strace /usr/local/bin/cough <any required argument for cough here>

or

strace -o <out_file> /usr/local/bin/cough <any required argument for cough here>

to write into 'out_file'.

All strace output will go to stderr (beware, the sheer volume of it often asks for a redirection to a file). In the simplest cases, your program will abort with an error and you'll be able to see what where its last interactions with the OS in strace output.

More information should be available with:

man strace

When to use RabbitMQ over Kafka?

Technically, Kafka offers a huge superset of features when compared to the set of features offered by Rabbit MQ.


If the question is

Is Rabbit MQ technically better than Kafka?

then the answer is

No.


However, if the question is

Is Rabbit MQ better than Kafka from a business perspective?

then, the answer is

Probably 'Yes', in some business scenarios


Rabbit MQ can be better than Kafka, from a business perspective, for the following reasons:

  1. Maintenance of legacy applications that depend on Rabbit MQ

  2. Staff training cost and steep learning curve required for implementing Kafka

  3. Infrastructure cost for Kafka is higher than that for Rabbit MQ.

  4. Troubleshooting problems in Kafka implementation is difficult when compared to that in Rabbit MQ implementation.

    • A Rabbit MQ Developer can easily maintain and support applications that use Rabbit MQ.

    • The same is not true with Kafka. Experience with just Kafka development is not sufficient to maintain and support applications that use Kafka. The support personnel require other skills like zoo-keeper, networking, disk storage too.

How to hide Bootstrap modal with javascript?

This is the bad practice but you can use this technique to close modal by calling close button in javascript. This will close modal after 3 seconds.

<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<script>
window.onload=function()
{
setInterval(function(){ 

$("#closemodal").click();
}, 3000);

}
</script> 
</head>
<body>

   <div class="container">
 <h2>Modal Example</h2>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal"   data-target="#myModal">Open Modal</button>

<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">

    <!-- Modal content-->
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal">&times;</button>
      <h4 class="modal-title">Modal Header</h4>
    </div>
    <div class="modal-body">
      <p>Some text in the modal.</p>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default" data-dismiss="modal" id="closemodal">Close</button>
    </div>
  </div>

</div>
</div>

 </div>

</body>
</html>

Closing Bootstrap modal onclick

You can hide the modal and popup the window to review the carts in validateShipping() function itself.

function validateShipping(){
...
...
$('#product-options').modal('hide');
//pop the window to select items
}

Error 415 Unsupported Media Type: POST not reaching REST if JSON, but it does if XML

Add Content-Type: application/json and Accept: application/json in REST Client header section

Angularjs $http post file and form data

I was unable to get Pavel's answer working as in when posting to a Web.Api application.

The issue appears to be with the deleting of the headers.

headersGetter();
delete headers['Content-Type'];

In order to ensure the browsers was allowed to default the Content-Type along with the boundary parameter, I needed to set the Content-Type to undefined. Using Pavel's example the boundary was never being set resulting in a 400 HTTP exception.

The key was to remove the code deleting the headers shown above and to set the headers content type to null manually. Thus allowing the browser to set the properties.

headers: {'Content-Type': undefined}

Here is a full example.

$scope.Submit = form => {
                $http({
                    method: 'POST',
                    url: 'api/FileTest',
                    headers: {'Content-Type': undefined},
                    data: {
                        FullName: $scope.FullName,
                        Email: $scope.Email,
                        File1: $scope.file
                    },
                    transformRequest: function (data, headersGetter) {
                        var formData = new FormData();
                        angular.forEach(data, function (value, key) {
                            formData.append(key, value);
                        });
                        return formData;
                    }
                })
                .success(function (data) {

                })
                .error(function (data, status) {

                });

                return false;
            }

How to print jquery object/array

I was having similar problem and

var dataObj = JSON.parse(data);

console.log(dataObj[0].category); //will return Damskie
console.log(dataObj[1].category); //will return Meskie

This solved my problem. Thanks Selvakumar Arumugam

Custom Date Format for Bootstrap-DatePicker

I solve it editing the file bootstrap-datapicker.js.

Look for the text bellow in the file and edit the variable "Format:"

var defaults = $.fn.datepicker.defaults = {
    assumeNearbyYear: false,
    autoclose: false,
    beforeShowDay: $.noop,
    beforeShowMonth: $.noop,
    beforeShowYear: $.noop,
    beforeShowDecade: $.noop,
    beforeShowCentury: $.noop,
    calendarWeeks: false,
    clearBtn: false,
    toggleActive: false,
    daysOfWeekDisabled: [],
    daysOfWeekHighlighted: [],
    datesDisabled: [],
    endDate: Infinity,
    forceParse: true,
    format: 'dd/mm/yyyy',
    keyboardNavigation: true,
    language: 'en',
    minViewMode: 0,
    maxViewMode: 4,
    multidate: false,
    multidateSeparator: ',',
    orientation: "auto",
    rtl: false,
    startDate: -Infinity,
    startView: 0,
    todayBtn: false,
    todayHighlight: false,
    weekStart: 0,
    disableTouchKeyboard: false,
    enableOnReadonly: true,
    showOnFocus: true,
    zIndexOffset: 10,
    container: 'body',
    immediateUpdates: false,
    title: '',
    templates: {
        leftArrow: '&laquo;',
        rightArrow: '&raquo;'
    }
};

How do I uniquely identify computers visiting my web site?

A possibility is using flash cookies:

  • Ubiquitous availability (95 percent of visitors will probably have flash)
  • You can store more data per cookie (up to 100 KB)
  • Shared across browsers, so more likely to uniquely identify a machine
  • Clearing the browser cookies does not remove the flash cookies.

You'll need to build a small (hidden) flash movie to read and write them.

Whatever route you pick, make sure your users opt IN to being tracked, otherwise you're invading their privacy and become one of the bad guys.

SQL Order By Count

Below gives me opposite of what you have. (Notice Group column)

SELECT
    *
FROM
    myTable
GROUP BY
    Group_value,
    ID
ORDER BY
    count(Group_value)

Let me know if this is fine with you...

I am trying to get what you want too...

ASP.NET Background image

resize your background image in an image editor to the size you want related to your login box, which should help page loading and preserve image quality...

hard-size your DIV relative to your image

position your asp:login control where needed...

On select change, get data attribute value

$('#foo option:selected').data('id');

How can I check whether an array is null / empty?

I am from .net background. However, java/c# are more/less same.

If you instantiate a non-primitive type (array in your case), it won't be null.
e.g. int[] numbers = new int[3];
In this case, the space is allocated & each of the element has a default value of 0.

It will be null, when you don't new it up.
e.g.

int[] numbers = null; // changed as per @Joachim's suggestion.
if (numbers == null)
{
   System.out.println("yes, it is null. Please new it up");
}

What is the OAuth 2.0 Bearer Token exactly?

Bearer token is one or more repetition of alphabet, digit, "-" , "." , "_" , "~" , "+" , "/" followed by 0 or more "=".

RFC 6750 2.1. Authorization Request Header Field (Format is ABNF (Augmented BNF))

The syntax for Bearer credentials is as follows:

     b64token    = 1*( ALPHA / DIGIT /
                       "-" / "." / "_" / "~" / "+" / "/" ) *"="
     credentials = "Bearer" 1*SP b64token

It looks like Base64 but according to Should the token in the header be base64 encoded?, it is not.

Digging a bit deeper in to "HTTP/1.1, part 7: Authentication"**, however, I see that b64token is just an ABNF syntax definition allowing for characters typically used in base64, base64url, etc.. So the b64token doesn't define any encoding or decoding but rather just defines what characters can be used in the part of the Authorization header that will contain the access token.

This fully addresses the first 3 items in the OP question's list. So I'm extending this answer to address the 4th question, about whether the token must be validated, so @mon feel free to remove or edit:

The authorizer is responsible for accepting or rejecting the http request. If the authorizer says the token is valid, it's up to you to decide what this means:

  • Does the authorizer have a way of inspecting the URL, identifying the operation, and looking up some role-based access control database to see if it is allowed? If yes and the request comes through, the service can assume it is allowed, and does not need to verify.
  • Is the token an all-or-nothing, so if the token is correct, all operations are allowed? Then the service doesn't need to verify.
  • Does the token mean "this request is allowed, but here is the UUID for the role, you check whether the operation is allowed". Then it's up to the service to look up that role, and see if the operation is allowed.

References

Cannot find either column "dbo" or the user-defined function or aggregate "dbo.Splitfn", or the name is ambiguous

It's a table-valued function, but you're using it as a scalar function.

Try:

where Emp_Id IN (SELECT i.items FROM dbo.Splitfn(@Id,',') AS i)

But... also consider changing your function into an inline TVF, as it'll perform better.

What is the function of FormulaR1C1?

Here's some info from my blog on how I like to use formular1c1 outside of vba:

You’ve just finished writing a formula, copied it to the whole spreadsheet, formatted everything and you realize that you forgot to make a reference absolute: every formula needed to reference Cell B2 but now, they all reference different cells.

How are you going to do a Find/Replace on the cells, considering that one has B5, the other C12, the third D25, etc., etc.?

The easy way is to update your Reference Style to R1C1. The R1C1 reference works with relative positioning: R marks the Row, C the Column and the numbers that follow R and C are either relative positions (between [ ]) or absolute positions (no [ ]).

Examples:

  • R[2]C refers to the cell two rows below the cell in which the formula’s in
  • RC[-1] refers to the cell one column to the left
  • R1C1 refers the cell in the first row and first cell ($A$1)

What does it matter? Well, When you wrote your first formula back in the beginning of this post, B2 was the cell 4 rows above the cell you wrote it in, i.e. R[-4]C. When you copy it across and down, while the A1 reference changes, the R1C1 reference doesn’t. Throughout the whole spreadsheet, it’s R[-4]C. If you switch to R1C1 Reference Style, you can replace R[-4]C by R2C2 ($B$2) with a simple Find / Replace and be done in one fell swoop.

Google Maps API v3 adding an InfoWindow to each marker

You can use this in event:

google.maps.event.addListener(marker, 'click', function() {  
    // this = marker
    var marker_map = this.getMap();
    this.info.open(marker_map);
    // this.info.open(marker_map, this);
    // Note: If you call open() without passing a marker, the InfoWindow will use the position specified upon construction through the InfoWindowOptions object literal.
});

How do I catch a numpy warning like it's an exception (not just for testing)?

To elaborate on @Bakuriu's answer above, I've found that this enables me to catch a runtime warning in a similar fashion to how I would catch an error warning, printing out the warning nicely:

import warnings

with warnings.catch_warnings():
    warnings.filterwarnings('error')
    try:
        answer = 1 / 0
    except Warning as e:
        print('error found:', e)

You will probably be able to play around with placing of the warnings.catch_warnings() placement depending on how big of an umbrella you want to cast with catching errors this way.

How to Right-align flex item?

Example code based on answer by TetraDev

Images on right:

_x000D_
_x000D_
* {_x000D_
  outline: .4px dashed red;_x000D_
}_x000D_
_x000D_
.main {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  align-items: center;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
  flex-basis: 100%;_x000D_
}_x000D_
_x000D_
img {_x000D_
  margin: 0 5px;_x000D_
  height: 30px;_x000D_
}
_x000D_
<div class="main">_x000D_
  <h1>Secure Payment</h1>_x000D_
  <img src="https://i.stack.imgur.com/i65gn.png">_x000D_
  <img src="https://i.stack.imgur.com/i65gn.png">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Images on left:

_x000D_
_x000D_
* {_x000D_
  outline: .4px dashed red;_x000D_
}_x000D_
_x000D_
.main {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  align-items: center;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
  flex-basis: 100%;_x000D_
  text-align: right;_x000D_
}_x000D_
_x000D_
img {_x000D_
  margin: 0 5px;_x000D_
  height: 30px;_x000D_
}
_x000D_
<div class="main">_x000D_
  <img src="https://i.stack.imgur.com/i65gn.png">_x000D_
  <img src="https://i.stack.imgur.com/i65gn.png">_x000D_
  <h1>Secure Payment</h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I add a Maven dependency in Eclipse?

  1. On the top menu bar, open Window -> Show View -> Other
  2. In the Show View window, open Maven -> Maven Repositories

Show View - Maven Repositories

  1. In the window that appears, right-click on Global Repositories and select Go Into
  2. Right-click on "central (http://repo.maven.apache.org/maven2)" and select "Rebuild Index"
  • Note that it will take very long to complete the download!!!
  1. Once indexing is complete, Right-click on the project -> Maven -> Add Dependency and start typing the name of the project you want to import (such as "hibernate").
  • The search results will auto-fill in the "Search Results" box below.

ASP.NET Core Web API Authentication

ASP.NET Core 2.0 with Angular

https://fullstackmark.com/post/13/jwt-authentication-with-aspnet-core-2-web-api-angular-5-net-core-identity-and-facebook-login

Make sure to use type of authentication filter

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

socket.emit() vs. socket.send()

With socket.emit you can register custom event like that:

server:

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

client:

var socket = io.connect('http://localhost');
socket.on('news', function (data) {
  console.log(data);
  socket.emit('my other event', { my: 'data' });
});

Socket.send does the same, but you don't register to 'news' but to message:

server:

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
  socket.send('hi');
});

client:

var socket = io.connect('http://localhost');
socket.on('message', function (message) {
  console.log(message);
});

Cannot read property 'addEventListener' of null

Add all event listeners when a window loads.Works like a charm no matter where you put script tags.

window.addEventListener("load", startup);

function startup() {

  document.getElementById("el").addEventListener("click", myFunc);
  document.getElementById("el2").addEventListener("input", myFunc);

}

myFunc(){}

Get the Year/Month/Day from a datetime in php?

Try below code if you want to use php loop to display

<span>
  <select name="birth_month">
    <?php for( $m=1; $m<=12; ++$m ) { 
      $month_label = date('F', mktime(0, 0, 0, $m, 1));
    ?>
      <option value="<?php echo $month_label; ?>"><?php echo $month_label; ?></option>
    <?php } ?>
  </select> 
</span>
<span>
  <select name="birth_day">
    <?php 
      $start_date = 1;
      $end_date   = 31;
      for( $j=$start_date; $j<=$end_date; $j++ ) {
        echo '<option value='.$j.'>'.$j.'</option>';
      }
    ?>
  </select>
</span>
<span>
  <select name="birth_year">
    <?php 
      $year = date('Y');
      $min = $year - 60;
      $max = $year;
      for( $i=$max; $i>=$min; $i-- ) {
        echo '<option value='.$i.'>'.$i.'</option>';
      }
    ?>
  </select>
</span>

What does servletcontext.getRealPath("/") mean and when should I use it

A web application's context path is the directory that contains the web application's WEB-INF directory. It can be thought of as the 'home' of the web app. Often, when writing web applications, it can be important to get the actual location of this directory in the file system, since this allows you to do things such as read from files or write to files.

This location can be obtained via the ServletContext object's getRealPath() method. This method can be passed a String parameter set to File.separator to get the path using the operating system's file separator ("/" for UNIX, "\" for Windows).

Can't find @Nullable inside javax.annotation.*

In case someone has this while trying to compile an Android project, there is an alternative Nullable implementation in android.support.annotation.Nullable. So take care which package you've referenced in your imports.

How to assert two list contain the same elements in Python?

Needs ensure library but you can compare list by:

ensure([1, 2]).contains_only([2, 1])

This will not raise assert exception. Documentation of thin is really thin so i would recommend to look at ensure's codes on github

How to set DataGrid's row Background, based on a property value using data bindings

In XAML, add and define a RowStyle Property for the DataGrid with a goal to set the Background of the Row, to the Color defined in my Employee Object.

<DataGrid AutoGenerateColumns="False" ItemsSource="EmployeeList">
   <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
             <Setter Property="Background" Value="{Binding ColorSet}"/>
        </Style>
   </DataGrid.RowStyle>

And in my Employee Class

public class Employee {

    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }

    public string ColorSet { get; set; }

    public Employee() { }

    public Employee(int id, string name, int age)
    {
        Id = id;
        Name = name;
        Age = age;
        if (Age > 50)
        {
            ColorSet = "Green";
        }
        else if (Age > 100)
        {
            ColorSet = "Red";
        }
        else
        {
            ColorSet = "White";
        }
    }
}

This way every Row of the DataGrid has the BackGround Color of the ColorSet Property of my Object.

Select records from NOW() -1 Day

You're almost there: it's NOW() - INTERVAL 1 DAY

Where does npm install packages?

The command npm root will tell you the effective installation directory of your npm packages.

If your current working directory is a node package or a sub-directory of a node package, npm root will tell you the local installation directory. npm root -g will show the global installation root regardless of current working directory.

Example:

$ npm root -g
/usr/local/lib/node_modules

See the documentation.

How do you set autocommit in an SQL Server session?

You can turn autocommit ON by setting implicit_transactions OFF:

SET IMPLICIT_TRANSACTIONS OFF

When the setting is ON, it returns to implicit transaction mode. In implicit transaction mode, every change you make starts a transactions which you have to commit manually.

Maybe an example is clearer. This will write a change to the database:

SET IMPLICIT_TRANSACTIONS ON
UPDATE MyTable SET MyField = 1 WHERE MyId = 1
COMMIT TRANSACTION

This will not write a change to the database:

SET IMPLICIT_TRANSACTIONS ON
UPDATE MyTable SET MyField = 1 WHERE MyId = 1
ROLLBACK TRANSACTION

The following example will update a row, and then complain that there's no transaction to commit:

SET IMPLICIT_TRANSACTIONS OFF
UPDATE MyTable SET MyField = 1 WHERE MyId = 1
ROLLBACK TRANSACTION

Like Mitch Wheat said, autocommit is the default for Sql Server 2000 and up.

What is the max size of localStorage values?

I wrote this simple code that is testing localStorage size in bytes.

https://github.com/gkucmierz/Test-of-localStorage-limits-quota

const check = bytes => {
  try {
    localStorage.clear();
    localStorage.setItem('a', '0'.repeat(bytes));
    localStorage.clear();
    return true;
  } catch(e) {
    localStorage.clear();
    return false;
  }
};

Github pages:

https://gkucmierz.github.io/Test-of-localStorage-limits-quota/

I have the same results on desktop chrome, opera, firefox, brave and mobile chrome which is ~5Mbytes

enter image description here

And half smaller result in safari ~2Mbytes

enter image description here

How do I perform an insert and return inserted identity with Dapper?

I see answer for sql server, well here it is for MySql using a transaction


    Dim sql As String = "INSERT INTO Empleado (nombres, apepaterno, apematerno, direccion, colonia, cp, municipio, estado, tel, cel, correo, idrol, relojchecadorid, relojchecadorid2, `activo`,`extras`,`rfc`,`nss`,`curp`,`imagen`,sueldoXHra, IMSSCotiza, thumb) VALUES (@nombres, @apepaterno, @apematerno, @direccion, @colonia, @cp, @municipio, @estado, @tel, @cel, @correo, @idrol, @relojchecadorid, @relojchecadorid2, @activo, @extras, @rfc, @nss, @curp, @imagen,@sueldoXHra,@IMSSCotiza, @thumb)"
    
            Using connection As IDbConnection = New MySqlConnection(getConnectionString())
                connection.Open()
                Using transaction = connection.BeginTransaction
                    Dim res = connection.Execute(sql, New With {reg.nombres, reg.apepaterno, reg.apematerno, reg.direccion, reg.colonia, reg.cp, reg.municipio, reg.estado, reg.tel, reg.cel, reg.correo, reg.idrol, reg.relojchecadorid, reg.relojchecadorid2, reg.activo, reg.extras, reg.rfc, reg.nss, reg.curp, reg.imagen, reg.thumb, reg.sueldoXHra, reg.IMSSCotiza}, commandTimeout:=180, transaction:=transaction)
                    lastInsertedId = connection.ExecuteScalar("SELECT LAST_INSERT_ID();", transaction:=transaction)
                    If res > 0 Then 
transaction.Commit()
return true
end if
                    
                End Using
            End Using

ImportError: libSM.so.6: cannot open shared object file: No such file or directory

There is now a headless version of opencv-python which removes the graphical dependencies (like libSM). You can see the normal / headless version on the releases page (and the GitHub issue leading to this); just add -headless when installing, e.g.,

pip install opencv-python-headless
# also contrib, if needed
pip install opencv-contrib-python-headless

Maximum value for long integer

Long integers:

There is no explicitly defined limit. The amount of available address space forms a practical limit.
(Taken from this site). See the docs on Numeric Types where you'll see that Long integers have unlimited precision. In Python 2, Integers will automatically switch to longs when they grow beyond their limit:

>>> import sys
>>> type(sys.maxsize)
<type 'int'>
>>> type(sys.maxsize+1)
<type 'long'>


for integers we have

maxint and maxsize:

The maximum value of an int can be found in Python 2.x with sys.maxint. It was removed in Python 3, but sys.maxsize can often be used instead. From the changelog:

The sys.maxint constant was removed, since there is no longer a limit to the value of integers. However, sys.maxsize can be used as an integer larger than any practical list or string index. It conforms to the implementation’s “natural” integer size and is typically the same as sys.maxint in previous releases on the same platform (assuming the same build options).

and, for anyone interested in the difference (Python 2.x):

sys.maxint The largest positive integer supported by Python’s regular integer type. This is at least 2**31-1. The largest negative integer is -maxint-1 — the asymmetry results from the use of 2’s complement binary arithmetic.

sys.maxsize The largest positive integer supported by the platform’s Py_ssize_t type, and thus the maximum size lists, strings, dicts, and many other containers can have.

and for completeness, here's the Python 3 version:

sys.maxsize An integer giving the maximum value a variable of type Py_ssize_t can take. It’s usually 2^31 - 1 on a 32-bit platform and 2^63 - 1 on a 64-bit platform.

floats:

There's float("inf") and float("-inf"). These can be compared to other numeric types:

>>> import sys
>>> float("inf") > sys.maxsize
True

'Property does not exist on type 'never'

if you're receiving the error in parameter, so keep any or any[] type of input like below

getOptionLabel={(option: any) => option!.name}
 <Autocomplete
    options={tests}
    getOptionLabel={(option: any) => option!.name}
    ....
  />

How can I display a JavaScript object?

If you want to use alert, to print your object, you can do this:

alert("myObject is " + myObject.toSource());

It should print each property and its corresponding value in string format.

Parse String to Date with Different Format in Java

Take a look at SimpleDateFormat. The code goes something like this:

SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");

try {

    String reformattedStr = myFormat.format(fromUser.parse(inputString));
} catch (ParseException e) {
    e.printStackTrace();
}

Limit the length of a string with AngularJS

Limit the number of words with a custom Angular filter: Here is how I used an Angular filter to limit the number of words displayed using a custom filter.

HTML:

<span>{{dataModelObject.TextValue | limitWordsTo: 38}} ......</span>

Angular/Javascript Code

angular.module('app')
.filter('limitWordsTo', function () {
    return function (stringData, numberOfWords) {
        //Get array of words (determined by spaces between words)
        var arrayOfWords = stringData.split(" ");

        //Get loop limit
        var loopLimit = numberOfWords > arrayOfWords.length ? arrayOfWords.length : numberOfWords;

        //Create variables to hold limited word string and array iterator
        var limitedString = '', i;
        //Create limited string bounded by limit passed in
        for (i = 0; i < loopLimit; i++) {
            if (i === 0) {
                limitedString = arrayOfWords[i];
            } else {
                limitedString = limitedString + ' ' + arrayOfWords[i];
            }
        }
        return limitedString;
    }; 
}); //End filter

GridLayout (not GridView) how to stretch all children evenly

The best solution I could find is to use a linear layout(horizontal) for each row you want and within it assign the button (cell) width to 0dp and the weight to 1. For each of the linear layouts(rows) assign the height to 0dp and the weight to 1. Find the code below- also android:layout_gravity="center_vertical" is used to align the buttons in a row in case they contain variable length text. Use of 0dp and weight it a pretty neat yet not so well known trick.

<LinearLayout
 android:id="@+id/parent_layout"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:background="@drawable/button_bue_3d"
 android:orientation="vertical" >

            <LinearLayout
                android:id="@+id/layout_row1"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1"

                android:orientation="horizontal" >

                <Button
                    android:id="@+id/button1"
                    style="?android:attr/buttonStyleSmall"
                   android:layout_height="wrap_content"
                   android:layout_width="0dp"
                   android:layout_weight="1"
                    android:clickable="false"
                   android:layout_gravity="center_vertical"
                    android:text="ssssssssssssssssssssssssss" />

                <Button
                    android:id="@+id/button2"
                    style="?android:attr/buttonStyleSmall"
                    android:clickable="false"
                    android:layout_height="wrap_content"
                     android:layout_width="0dp"
                   android:layout_weight="1"
                   android:layout_gravity="center_vertical"
                    android:text="sggggggg" />


            </LinearLayout>

            <LinearLayout
                android:id="@+id/layout_row2"
                android:layout_weight="1"
                android:layout_width="match_parent"
                  android:layout_height="0dp"

                android:orientation="horizontal" >

                <Button
                    android:id="@+id/button3"
                    style="?android:attr/buttonStyleSmall"
                    android:layout_height="wrap_content"
                     android:layout_width="0dp"
                   android:layout_weight="1"
                    android:layout_gravity="center_vertical"
                    android:text="s" />

                <Button
                    android:id="@+id/button4"
                    style="?android:attr/buttonStyleSmall"
                    android:layout_height="wrap_content"
                     android:layout_width="0dp"
                   android:layout_weight="1"
                    android:clickable="false"
                     android:layout_gravity="center_vertical"
                    android:text="s" />


            </LinearLayout>


       </LinearLayout>

Creating a byte array from a stream

MemoryStream ms = new MemoryStream();
file.PostedFile.InputStream.CopyTo(ms);
var byts = ms.ToArray();
ms.Dispose();

How to resolve Unneccessary Stubbing exception

I had UnnecessaryStubbingException when I tried to use the when methods on a Spy object. Mockito.lenient() silenced the exception but the test results were not correct.

In case of Spy objects, one has to call the methods directly.

@ExtendWith(MockitoExtension.class)
@RunWith(JUnitPlatform.class)
class ArithmTest {

    @Spy
    private Arithm arithm;

    @Test
    void testAddition() {

        int res = arithm.add(2, 5);

        // doReturn(7).when(arithm).add(2, 5);
        assertEquals(res, 7);
    }
}

Converting a Uniform Distribution to a Normal Distribution

The Ziggurat algorithm is pretty efficient for this, although the Box-Muller transform is easier to implement from scratch (and not crazy slow).

How to center horizontally div inside parent div

<div id='child' style='width: 50px; height: 100px; margin:0 auto;'>Text</div>

javascript close current window

** Update **

Since posting the answer the latest versions of browsers prevent the command from working. I'll leave the answer visible but note it ONLY works on older browser versions.


Most browsers prevent you from closing windows with javascript that were not opened with window.open("https://example_url.com") however, it is still possible to close the current window using the following command:

window.open('','_self').close()

This loads a blank url (the first argument) in the current window (the second argument) and then instantaneously closes the window. This works because when close() is called, the current window has been opened by javascript.

How to vertically align text in input type="text"?

Use padding to fake it since vertical-align doesn't work on text inputs.

jsFiddle example

CSS

.date-input {     
    width: 145px;
    padding-top: 80px;
}?

Composer: how can I install another dependency without updating old ones?

To install a new package and only that, you have two options:

  1. Using the require command, just run:

    composer require new/package
    

    Composer will guess the best version constraint to use, install the package, and add it to composer.lock.

    You can also specify an explicit version constraint by running:

    composer require new/package ~2.5
    

–OR–

  1. Using the update command, add the new package manually to composer.json, then run:

    composer update new/package
    

If Composer complains, stating "Your requirements could not be resolved to an installable set of packages.", you can resolve this by passing the flag --with-dependencies. This will whitelist all dependencies of the package you are trying to install/update (but none of your other dependencies).

Regarding the question asker's issues with Laravel and mcrypt: check that it's properly enabled in your CLI php.ini. If php -m doesn't list mcrypt then it's missing.

Important: Don't forget to specify new/package when using composer update! Omitting that argument will cause all dependencies, as well as composer.lock, to be updated.

How to programmatically set drawableLeft on Android button?

You can use the setCompoundDrawables method to do this. See the example here. I used this without using the setBounds and it worked. You can try either way.

UPDATE: Copying the code here incase the link goes down

Drawable img = getContext().getResources().getDrawable(R.drawable.smiley);
img.setBounds(0, 0, 60, 60);
txtVw.setCompoundDrawables(img, null, null, null);

or

Drawable img = getContext().getResources().getDrawable(R.drawable.smiley);
txtVw.setCompoundDrawablesWithIntrinsicBounds(img, null, null, null);

or

txtVw.setCompoundDrawablesWithIntrinsicBounds(R.drawable.smiley, 0, 0, 0);

Scala vs. Groovy vs. Clojure

I'm reading the Pragmatic Programmers book "Groovy Recipes: Greasing the wheels of Java" by Scott Davis, Copyright 2008 and printed in April of the same year.

It's a bit out of date but the book makes it clear that Groovy is literally an extension of Java. I can write Java code that functions exactly like Java and rename the file *.groovy and it works fine. According to the book, the reverse is true if I include the requisite libraries. So far, experimentation seems to bear this out.

How to create a listbox in HTML without allowing multiple selection?

Just use the size attribute:

<select name="sometext" size="5">
  <option>text1</option>
  <option>text2</option>
  <option>text3</option>
  <option>text4</option>
  <option>text5</option>
</select>

To clarify, adding the size attribute did not remove the multiple selection.

The single selection works because you removed the multiple="multiple" attribute.

Adding the size="5" attribute is still a good idea, it means that at least 5 lines must be displayed. See the full reference here

How to get an Array with jQuery, multiple <input> with the same name

To catch the names array, i use that:

$("input[name*='task']")

How to input automatically when running a shell over SSH?

ssh-key with passphrase, with keychain

keychain is a small utility which manages ssh-agent on your behalf and allows the ssh-agent to remain running when the login session ends. On subsequent logins, keychain will connect to the existing ssh-agent instance. In practice, this means that the passphrase must be be entered only during the first login after a reboot. On subsequent logins, the unencrypted key from the existing ssh-agent instance is used. This can also be useful for allowing passwordless RSA/DSA authentication in cron jobs without passwordless ssh-keys.

To enable keychain, install it and add something like the following to ~/.bash_profile:

eval keychain --agents ssh --eval id_rsa From a security point of view, ssh-ident and keychain are worse than ssh-agent instances limited to the lifetime of a particular session, but they offer a high level of convenience. To improve the security of keychain, some people add the --clear option to their ~/.bash_profile keychain invocation. By doing this passphrases must be re-entered on login as above, but cron jobs will still have access to the unencrypted keys after the user logs out. The keychain wiki page has more information and examples.

Got this info from;

https://unix.stackexchange.com/questions/90853/how-can-i-run-ssh-add-automatically-without-password-prompt

Hope this helps

I have personally been able to automatically enter my passphrase upon terminal launch by doing this: (you can, of course, modify the script and fit it to your needs)

  1. edit the bashrc file to add this script;

    Check if the SSH agent is awake

    if [ -z "$SSH_AUTH_SOCK" ] ; then exec ssh-agent bash -c "ssh-add ; $0" echo "The SSH agent was awakened" exit fi

    Above line will start the expect script upon terminal launch.

    ./ssh.exp

here's the content of this expect script

#!/usr/bin/expect

set timeout 20

set passphrase "test"

spawn "./keyadding.sh"

expect "Enter passphrase for /the/path/of/yourkey_id_rsa:"

send "$passphrase\r";

interact

Here's the content of my keyadding.sh script (you must put both scripts in your home folder, usually /home/user)

#!/bin/bash

ssh-add /the/path/of/yourkey_id_rsa

exit 0

I would HIGHLY suggest encrypting the password on the .exp script as well as renaming this .exp file to something like term_boot.exp or whatever else for security purposes. Don't forget to create the files directly from the terminal using nano or vim (ex: nano ~/.bashrc | nano term_boot.exp) and also a chmod +x script.sh to make it executable. A chmod +r term_boot.exp would be also useful but you'll have to add sudo before ./ssh.exp in your bashrc file. So you'll have to enter your sudo password each time you launch your terminal. For me, it's more convenient than the passphrase cause I remember my admin (sudo) password by the hearth.

Also, here's another way to do it I think; https://www.cyberciti.biz/faq/noninteractive-shell-script-ssh-password-provider/

Will certainly change my method for this one when I'll have the time.

HTML -- two tables side by side

With CSS: table {float:left;}? ?

What are the correct version numbers for C#?

You can check the latest C# versions here C# Versions

Need to get a string after a "word" in a string in c#

var code = myString.Split(new [] {"code"}, StringSplitOptions.None)[1];
// code = " : -1"

You can tweak the string to split by - if you use "code : ", the second member of the returned array ([1]) will contain "-1", using your example.

Ruby: What is the easiest way to remove the first element from an array?

Use shift method

array.shift(n) => Remove first n elements from array 
array.shift(1) => Remove first element

https://ruby-doc.org/core-2.2.0/Array.html#method-i-shift

psql - save results of command to a file

I assume that there exist some internal psql command for this, but you could also run the script command from util-linux-ng package:

DESCRIPTION Script makes a typescript of everything printed on your terminal.

OpenCV resize fails on large image with "error: (-215) ssize.area() > 0 in function cv::resize"

Turns out for me this error was actually telling the truth - I was trying to resize a Null image, which was usually the 'last' frame of a video file, so the assertion was valid.

Now I have an extra step before attempting the resize operation, which is to do the assertion myself:

def getSizedFrame(width, height):
"""Function to return an image with the size I want"""    
    s, img = self.cam.read()

    # Only process valid image frames
    if s:
            img = cv2.resize(img, (width, height), interpolation = cv2.INTER_AREA)
    return s, img

Now I don't see the error.

When to use NSInteger vs. int

On iOS, it currently does not matter if you use int or NSInteger. It will matter more if/when iOS moves to 64-bits.

Simply put, NSIntegers are ints in 32-bit code (and thus 32-bit long) and longs on 64-bit code (longs in 64-bit code are 64-bit wide, but 32-bit in 32-bit code). The most likely reason for using NSInteger instead of long is to not break existing 32-bit code (which uses ints).

CGFloat has the same issue: on 32-bit (at least on OS X), it's float; on 64-bit, it's double.

Update: With the introduction of the iPhone 5s, iPad Air, iPad Mini with Retina, and iOS 7, you can now build 64-bit code on iOS.

Update 2: Also, using NSIntegers helps with Swift code interoperability.

Multiple arguments to function called by pthread_create()?

use

struct arg_struct *args = (struct arg_struct *)arguments;

in place of

struct arg_struct *args = (struct arg_struct *)args;

How do you create a foreign key relationship in a SQL Server CE (Compact Edition) Database?

Alan is correct when he says there's designer support. Rhywun is incorrect when he implies you cannot choose the foreign key table. What he means is that in the UI the foreign key table drop down is greyed out - all that means is he has not right clicked on the correct table to add the foreign key to.

In summary, right click on the foriegn key table and then via the 'Table Properties' > 'Add Relations' option you select the related primary key table.

I've done it numerous times and it works.

Write to Windows Application Event Log

Yes, there is a way to write to the event log you are looking for. You don't need to create a new source, just simply use the existent one, which often has the same name as the EventLog's name and also, in some cases like the event log Application, can be accessible without administrative privileges*.

*Other cases, where you cannot access it directly, are the Security EventLog, for example, which is only accessed by the operating system.

I used this code to write directly to the event log Application:

using (EventLog eventLog = new EventLog("Application")) 
{
    eventLog.Source = "Application"; 
    eventLog.WriteEntry("Log message example", EventLogEntryType.Information, 101, 1); 
}

As you can see, the EventLog source is the same as the EventLog's name. The reason of this can be found in Event Sources @ Windows Dev Center (I bolded the part which refers to source name):

Each log in the Eventlog key contains subkeys called event sources. The event source is the name of the software that logs the event. It is often the name of the application or the name of a subcomponent of the application if the application is large. You can add a maximum of 16,384 event sources to the registry.

How do I set the version information for an existing .exe, .dll?

I'm doing it with no additional tool. I have just added the following files to my Win32 app project.

One header file which defines some constants than we can reuse on our resource file and even on the program code. We only need to maintain one file. Thanks to the Qt team that showed me how to do it on a Qt project, it now also works on my Win32 app.

----[version.h]----

#ifndef VERSION_H
#define VERSION_H

#define VER_FILEVERSION             0,3,0,0
#define VER_FILEVERSION_STR         "0.3.0.0\0"

#define VER_PRODUCTVERSION          0,3,0,0
#define VER_PRODUCTVERSION_STR      "0.3.0.0\0"

#define VER_COMPANYNAME_STR         "IPanera"
#define VER_FILEDESCRIPTION_STR     "Localiza archivos duplicados"
#define VER_INTERNALNAME_STR        "MyProject"
#define VER_LEGALCOPYRIGHT_STR      "Copyright 2016 [email protected]"
#define VER_LEGALTRADEMARKS1_STR    "All Rights Reserved"
#define VER_LEGALTRADEMARKS2_STR    VER_LEGALTRADEMARKS1_STR
#define VER_ORIGINALFILENAME_STR    "MyProject.exe"
#define VER_PRODUCTNAME_STR         "My project"

#define VER_COMPANYDOMAIN_STR       "www.myurl.com"

#endif // VERSION_H

----[MyProjectVersion.rc]----

#include <windows.h>
#include "version.h"

VS_VERSION_INFO VERSIONINFO
FILEVERSION     VER_FILEVERSION
PRODUCTVERSION  VER_PRODUCTVERSION
BEGIN
    BLOCK "StringFileInfo"
    BEGIN
        BLOCK "040904E4"
        BEGIN
            VALUE "CompanyName",        VER_COMPANYNAME_STR
            VALUE "FileDescription",    VER_FILEDESCRIPTION_STR
            VALUE "FileVersion",        VER_FILEVERSION_STR
            VALUE "InternalName",       VER_INTERNALNAME_STR
            VALUE "LegalCopyright",     VER_LEGALCOPYRIGHT_STR
            VALUE "LegalTrademarks1",   VER_LEGALTRADEMARKS1_STR
            VALUE "LegalTrademarks2",   VER_LEGALTRADEMARKS2_STR
            VALUE "OriginalFilename",   VER_ORIGINALFILENAME_STR
            VALUE "ProductName",        VER_PRODUCTNAME_STR
            VALUE "ProductVersion",     VER_PRODUCTVERSION_STR
        END
    END

    BLOCK "VarFileInfo"
    BEGIN
        VALUE "Translation", 0x409, 1252
    END
END

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

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

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

fatal error LNK1104: cannot open file 'libboost_system-vc110-mt-gd-1_51.lib'

The C++ ? General ? Additional Include Directories parameter is for listing directories where the compiler will search for header files.

You need to tell the linker where to look for libraries to link to. To access this setting, right-click on the project name in the Solution Explorer window, then Properties ? Linker ? General ? Additional Library Directories. Enter <boost_path>\stage\lib here (this is the path where the libraries are located if you build Boost using default options).

How can I make my custom objects Parcelable?

1. Import Android Parcelable code generator

enter image description here

2. Create a class

public class Sample {
    int id;
    String name;
}

3. Generate > Parcelable from menu

enter image description here enter image description here

Done.

PHP 7 RC3: How to install missing MySQL PDO

For thoses running Linux with apache2 you need to install php-mysql

apt-get install php-mysql

or if you are running ubuntu 16.04 or higher just running the following command will be enought, no need to edit your php.ini file

apt-get install php7.2-mysql

If you are running ubuntu 15.10 or below:

Edit your php.ini file, it's located at /etc/php/[version]/apache2/php.ini and search for pdo_mysql you might found something like this

;extension=pdo_mysql.so

Change it to this

extension=pdo_mysql.so

Save the file and restart apache

service apache2 restart

Check that it's available in your phpinfo()

Encode a FileStream to base64 with c#

You can also encode bytes to Base64. How to get this from a stream see here: How to convert an Stream into a byte[] in C#?

Or I think it should be also possible to use the .ToString() method and encode this.

What is difference between functional and imperative programming languages?

I think it's possible to express functional programming in an imperative fashion:

  • Using a lot of state check of objects and if... else/ switch statements
  • Some timeout/ wait mechanism to take care of asynchornousness

There are huge problems with such approach:

  • Rules/ procedures are repeated
  • Statefulness leaves chances for side-effects/ mistakes

Functional programming, treating functions/ methods like objects and embracing statelessness, was born to solve those problems I believe.

Example of usages: frontend applications like Android, iOS or web apps' logics incl. communication with backend.

Other challenges when simulating functional programming with imperative/ procedural code:

  • Race condition
  • Complex combination and sequence of events. For example, user tries to send money in a banking app. Step 1) Do all of the following in parallel, only proceed if all is good a) Check if user is still good (fraud, AML) b) check if user has enough balance c) Check if recipient is valid and good (fraud, AML) etc. Step 2) perform the transfer operation Step 3) Show update on user's balance and/ or some kind of tracking. With RxJava for example, the code is concise and sensible. Without it, I can imagine there'd be a lot of code, messy and error prone code

I also believe that at the end of the day, functional code will get translated into assembly or machine code which is imperative/ procedural by the compilers. However, unless you write assembly, as humans writing code with high level/ human-readable language, functional programming is the more appropriate way of expression for the listed scenarios

What is the simplest way to SSH using Python?

Like hughdbrown, I like Fabric. Please notice that while it implement its own declarative scripting (for making deploys and the such) it can also be imported as a Python module and used on your programs without having to write a Fabric script.

Fabric has a new maintainer and is in the process of being rewriten; that means that most tutorials you'll (currently) find on the web will not work with the current version. Also, Google still shows the old Fabric page as the first result.

For up to date documentation you can check: http://docs.fabfile.org

What is the most efficient way to create a dictionary of two pandas Dataframe columns?

I found a faster way to solve the problem, at least on realistically large datasets using: df.set_index(KEY).to_dict()[VALUE]

Proof on 50,000 rows:

df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB'))
df['A'] = df['A'].apply(chr)

%timeit dict(zip(df.A,df.B))
%timeit pd.Series(df.A.values,index=df.B).to_dict()
%timeit df.set_index('A').to_dict()['B']

Output:

100 loops, best of 3: 7.04 ms per loop  # WouterOvermeire
100 loops, best of 3: 9.83 ms per loop  # Jeff
100 loops, best of 3: 4.28 ms per loop  # Kikohs (me)

MongoDB Show all contents from all collections

This will do:

db.getCollectionNames().forEach(c => {
    db[c].find().forEach(d => {
        print(c); 
        printjson(d)
    })
})

Activity transition in Android

create res>anim>fadein.xml

<?xml version="1.0" encoding="utf-8"?>
    <alpha xmlns:android="http://schemas.android.com/apk/res/android"
       android:interpolator="@android:anim/accelerate_interpolator"
       android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="500" />

create res>anim>fadeout.xml

<?xml version="1.0" encoding="utf-8"?>
    <alpha xmlns:android="http://schemas.android.com/apk/res/android"
       android:interpolator="@android:anim/accelerate_interpolator"
       android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="500" />

In res>values>styles.xml

<style name="Fade">
        <item name="android:windowEnterAnimation">@anim/fadein</item>
        <item name="android:windowExitAnimation">@anim/fadeout</item>
    </style>

In activities onCreate()

getWindow().getAttributes().windowAnimations = R.style.Fade;

Using Rsync include and exclude options to include directory and file by pattern

rsync include exclude pattern examples:

"*"         means everything
"dir1"      transfers empty directory [dir1]
"dir*"      transfers empty directories like: "dir1", "dir2", "dir3", etc...
"file*"     transfers files whose names start with [file]
"dir**"     transfers every path that starts with [dir] like "dir1/file.txt", "dir2/bar/ffaa.html", etc...
"dir***"    same as above
"dir1/*"    does nothing
"dir1/**"   does nothing
"dir1/***"  transfers [dir1] directory and all its contents like "dir1/file.txt", "dir1/fooo.sh", "dir1/fold/baar.py", etc...

And final note is that simply dont rely on asterisks that are used in the beginning for evaluating paths; like "**dir" (its ok to use them for single folders or files but not paths) and note that more than two asterisks dont work for file names.

Where is the visual studio HTML Designer?

The solution of creating a new HTML file with HTML (Web Forms) Designer worked for that file but not for other, individual HTML files that I wanted to edit.

I did find the Open With option in the Open File dialogue and was able to select the HTML (Web Forms) Editor there. Having clicked the "Set as Default" option in that window, VS then remembered to use that editor when I opened other HTML files.

Compute a confidence interval from sample data

import numpy as np
import scipy.stats


def mean_confidence_interval(data, confidence=0.95):
    a = 1.0 * np.array(data)
    n = len(a)
    m, se = np.mean(a), scipy.stats.sem(a)
    h = se * scipy.stats.t.ppf((1 + confidence) / 2., n-1)
    return m, m-h, m+h

you can calculate like this way.

How to tell if a JavaScript function is defined

All of the current answers use a literal string, which I prefer to not have in my code if possible - this does not (and provides valuable semantic meaning, to boot):

function isFunction(possibleFunction) {
  return typeof(possibleFunction) === typeof(Function);
}

Personally, I try to reduce the number of strings hanging around in my code...


Also, while I am aware that typeof is an operator and not a function, there is little harm in using syntax that makes it appear as the latter.

Element count of an array in C++

It seems that if you know the type of elements in the array you can also use that to your advantage with sizeof.

int numList[] = { 0, 1, 2, 3, 4 };

cout << sizeof(numList) / sizeof(int);

// => 5

How to import existing Android project into Eclipse?

I had the problem of getting errors when checking out an Android project from SVN. This is what I did and the whole thing settled down.
1. checkout the project from SVN as we normally do any other project
2. right click and get properties of the project
3. In the java build path->order and export tab select the android API and OK it

this removed all the project issues
so far so good but not sure if this is the 100% correct method

How do I check if a string contains another string in Swift?

Here you are:

let s = "hello Swift"
if let textRange = s.rangeOfString("Swift") {
    NSLog("exists")
}

Match multiline text using regular expression

This has nothing to do with the MULTILINE flag; what you're seeing is the difference between the find() and matches() methods. find() succeeds if a match can be found anywhere in the target string, while matches() expects the regex to match the entire string.

Pattern p = Pattern.compile("xyz");

Matcher m = p.matcher("123xyzabc");
System.out.println(m.find());    // true
System.out.println(m.matches()); // false

Matcher m = p.matcher("xyz");
System.out.println(m.matches()); // true

Furthermore, MULTILINE doesn't mean what you think it does. Many people seem to jump to the conclusion that you have to use that flag if your target string contains newlines--that is, if it contains multiple logical lines. I've seen several answers here on SO to that effect, but in fact, all that flag does is change the behavior of the anchors, ^ and $.

Normally ^ matches the very beginning of the target string, and $ matches the very end (or before a newline at the end, but we'll leave that aside for now). But if the string contains newlines, you can choose for ^ and $ to match at the start and end of any logical line, not just the start and end of the whole string, by setting the MULTILINE flag.

So forget about what MULTILINE means and just remember what it does: changes the behavior of the ^ and $ anchors. DOTALL mode was originally called "single-line" (and still is in some flavors, including Perl and .NET), and it has always caused similar confusion. We're fortunate that the Java devs went with the more descriptive name in that case, but there was no reasonable alternative for "multiline" mode.

In Perl, where all this madness started, they've admitted their mistake and gotten rid of both "multiline" and "single-line" modes in Perl 6 regexes. In another twenty years, maybe the rest of the world will have followed suit.

Python list iterator behavior and next(iterator)

It behaves the way you want if called as a function:

>>> def test():
...     a = iter(list(range(10)))
...     for i in a:
...         print(i)
...         next(a)
... 
>>> test()
0
2
4
6
8

How do I get the resource id of an image if I know its name?

Example for a public system resource:

// this will get id for android.R.drawable.ic_dialog_alert
int id = Resources.getSystem().getIdentifier("ic_dialog_alert", "drawable", "android");

alert

Another way is to refer the documentation for android.R.drawable class.

How to turn off page breaks in Google Docs?

Just double click on the break and it will collaspe. However, it will still display the line where it will break but it's better than downloading add-ons etc.

CSS Border Not Working

Do this:

border: solid #000;
border-width: 0 1px;

Live demo: http://jsfiddle.net/aFzKy/

Regular expression to detect semi-colon terminated C++ for & while loops

This is the kind of thing you really shouldn't do with a regular expression. Just parse the string one character at a time, keeping track of opening/closing parentheses.

If this is all you're looking for, you definitely don't need a full-blown C++ grammar lexer/parser. If you want practice, you can write a little recursive-decent parser, but even that's a bit much for just matching parentheses.

Error occurred during initialization of VM (java/lang/NoClassDefFoundError: java/lang/Object)

Try placing the desired java directory in PATH before not needed java directories in your PATH.

Detecting scroll direction

This is an addition to what prateek has answered.There seems to be a glitch in the code in IE so i decided to modify it a bit nothing fancy(just another condition)

$('document').ready(function() {
var lastScrollTop = 0;
$(window).scroll(function(event){
   var st = $(this).scrollTop();
   if (st > lastScrollTop){
       console.log("down")
   }
   else if(st == lastScrollTop)
   {
     //do nothing 
     //In IE this is an important condition because there seems to be some instances where the last scrollTop is equal to the new one
   }
   else {
      console.log("up")
   }
   lastScrollTop = st;
});});

Vue.js data-bind style backgroundImage not working

The issue is that the value for backgroundImage needs to be a string like this:

<div class="circular" v-bind:style="{ backgroundImage: 'url(' + image + ')' }"></div>

Here's a simplified fiddle that's working: https://jsfiddle.net/89af0se9/1/

Re: the comment below about kebab-case, this is how you can do that:

<div class="circular" v-bind:style="{ 'background-image': 'url(' + image + ')' }"></div>

In other words, the value for v-bind:style is just a plain Javascript object and follows the same rules.

UPDATE: One other note about why you may have trouble getting this to work.

You should make sure your image value is quoted so that the end resulting string is:

url('some/url/path/to/image.jpeg')

Otherwise, if your image URL has special characters in it (such as whitespace or parentheses) the browser may not apply it properly. In Javascript, the assignment would look like:

this.image = "'some/url/path/to/image.jpeg'"

or

this.image = "'" + myUrl + "'"

Technically, this could be done in the template, but the escaping required to keep it valid HTML isn't worth it.

More info here: Is quoting the value of url() really necessary?

How to set text size of textview dynamically for different screens

I think You should use the textView.setTextSize(float size) method to set the size of text. textView.setText(arg) used to set the text in the Text View.

How to dynamically change a web page's title?

Since search engines ignore most javascript, you will need to make it so that search engines can crawl using the tabs without using Ajax. Make each tab a link with an href that loads the entire page with that tab selected. Then the page can have that title in the tag.

The onclick event handler can still load the pages via ajax for human viewers.

To see the pages as most search engines see them, turn off Javascript in your browser, and try to make it so that clicking the tabs will load the page with that tab selected and the correct title.

If you are loading via ajax and you want to dynamically change the page title with just Javascript, then do:

document.title = 'Put the new title here';

However, search engines will not see this change made in javascript.

MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

Full Steps For MySQL 8

Connect to MySQL

$ mysql -u root -p
Enter password: (enter your root password)

Reset your password

(Replace your_new_password with the password you want to use)

mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your_new_password';
mysql> FLUSH PRIVILEGES;
mysql> quit

Then try connecting using node

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 23: ordinal not in range(128)

When you get a UnicodeEncodeError, it means that somewhere in your code you convert directly a byte string to a unicode one. By default in Python 2 it uses ascii encoding, and utf8 encoding in Python3 (both may fail because not every byte is valid in either encoding)

To avoid that, you must use explicit decoding.

If you may have 2 different encoding in your input file, one of them accepts any byte (say UTF8 and Latin1), you can try to first convert a string with first and use the second one if a UnicodeDecodeError occurs.

def robust_decode(bs):
    '''Takes a byte string as param and convert it into a unicode one.
First tries UTF8, and fallback to Latin1 if it fails'''
    cr = None
    try:
        cr = bs.decode('utf8')
    except UnicodeDecodeError:
        cr = bs.decode('latin1')
    return cr

If you do not know original encoding and do not care for non ascii character, you can set the optional errors parameter of the decode method to replace. Any offending byte will be replaced (from the standard library documentation):

Replace with a suitable replacement character; Python will use the official U+FFFD REPLACEMENT CHARACTER for the built-in Unicode codecs on decoding and ‘?’ on encoding.

bs.decode(errors='replace')

Convert string to BigDecimal in java

Spring Framework provides an excellent utils class for achieving this.

Util class : NumberUtils

String to BigDecimal conversion -

NumberUtils.parseNumber("135.00", BigDecimal.class);

.NET Core vs Mono

You have chosen not only a realistic path, but arguably one of the best ecosystems strongly backed(also X-platforms) by MS. Still you should consider following points:

  • Update: Main doc about .Net platform standard is here: https://github.com/dotnet/corefx/blob/master/Documentation/architecture/net-platform-standard.md
  • Update: Current Mono 4.4.1 cannot run latest Asp.Net core 1.0 RTM
  • Although mono is more feature complete, its future is unclear, because MS owns it for some months now and its a duplicate work for them to support it. But MS is definitely committed to .Net Core and betting big on it.
  • Although .Net core is released, the 3rd party ecosystem is not quite there. For example Nhibernate, Umbraco etc cannot run over .Net core yet. But they have a plan.
  • There are some features missing in .Net Core like System.Drawing, you should look for 3rd party libraries
  • You should use nginx as front server with kestrelserver for asp.net apps, because kestrelserver is not quite ready for production. For example HTTP/2 is not implemented.

I hope it helps

How to solve maven 2.6 resource plugin dependency?

Seems your settings.xml file is missing your .m2 (local maven repo) folder.

When using eclipse navigate to Window -> Preferences -> Maven -> User Settings -> Browse to your settings.xml and click apply.

Then do maven Update Project.

enter image description here

Force GUI update from UI Thread

I had the same problem with property Enabled and I discovered a first chance exception raised because of it is not thread-safe. I found solution about "How to update the GUI from another thread in C#?" here https://stackoverflow.com/a/661706/1529139 And it works !

php, mysql - Too many connections to database error

This can happen due to too many connection same time or many chat at same time. Also it can happen due too many session.

The best way to sort out this issue is restart MySQL.

service mysqld restart

or

service mysql restart

or

 /etc/init.d/mysqld restart

How to get a jqGrid cell value when editing

Here is an example of basic solution with a user function.

    ondblClickRow: function(rowid) {
        var cont = $('#grid').getCell(rowid, 'MyCol');
        var val = getCellValue(cont);
    }

...

function getCellValue(content) {
    var k1 = content.indexOf(' value=', 0);
    var k2 = content.indexOf(' name=', k1);
    var val = '';
    if (k1 > 0) {
        val = content.substr(k1 + 7, k2 - k1 - 6);
    }
    return val;
}

Switch firefox to use a different DNS than what is in the windows.host file

DNS resolving is usually done at the system level and not at the application level, so you can't normally have one program use one dns and another program use a different dns. I'm not aware of any firefox extensions that allow you to use a different dns.

How to rotate a div using jQuery

EDIT: Updated for jQuery 1.8

Since jQuery 1.8 browser specific transformations will be added automatically. jsFiddle Demo

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: Added code to make it a jQuery function.

For those of you who don't want to read any further, here you go. For more details and examples, read on. jsFiddle Demo.

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
                 '-moz-transform' : 'rotate('+ degrees +'deg)',
                 '-ms-transform' : 'rotate('+ degrees +'deg)',
                 'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: One of the comments on this post mentioned jQuery Multirotation. This plugin for jQuery essentially performs the above function with support for IE8. It may be worth using if you want maximum compatibility or more options. But for minimal overhead, I suggest the above function. It will work IE9+, Chrome, Firefox, Opera, and many others.


Bobby... This is for the people who actually want to do it in the javascript. This may be required for rotating on a javascript callback.

Here is a jsFiddle.

If you would like to rotate at custom intervals, you can use jQuery to manually set the css instead of adding a class. Like this! I have included both jQuery options at the bottom of the answer.

HTML

<div class="rotate">
    <h1>Rotatey text</h1>
</div>

CSS

/* Totally for style */
.rotate {
    background: #F02311;
    color: #FFF;
    width: 200px;
    height: 200px;
    text-align: center;
    font: normal 1em Arial;
    position: relative;
    top: 50px;
    left: 50px;
}

/* The real code */
.rotated {
    -webkit-transform: rotate(45deg);  /* Chrome, Safari 3.1+ */
    -moz-transform: rotate(45deg);  /* Firefox 3.5-15 */
    -ms-transform: rotate(45deg);  /* IE 9 */
    -o-transform: rotate(45deg);  /* Opera 10.50-12.00 */
    transform: rotate(45deg);  /* Firefox 16+, IE 10+, Opera 12.10+ */
}

jQuery

Make sure these are wrapped in $(document).ready

$('.rotate').click(function() {
    $(this).toggleClass('rotated');
});

Custom intervals

var rotation = 0;
$('.rotate').click(function() {
    rotation += 5;
    $(this).css({'-webkit-transform' : 'rotate('+ rotation +'deg)',
                 '-moz-transform' : 'rotate('+ rotation +'deg)',
                 '-ms-transform' : 'rotate('+ rotation +'deg)',
                 'transform' : 'rotate('+ rotation +'deg)'});
});

How to resolve Value cannot be null. Parameter name: source in linq?

Error message clearly says that source parameter is null. Source is the enumerable you are enumerating. In your case it is ListMetadataKor object. And its definitely null at the time you are filtering it second time. Make sure you never assign null to this list. Just check all references to this list in your code and look for assignments.

XSLT string replace

Note: In case you wish to use the already-mentioned algo for cases where you need to replace huge number of instances in the source string (e.g. new lines in long text) there is high probability you'll end up with StackOverflowException because of the recursive call.

I resolved this issue thanks to Xalan's (didn't look how to do it in Saxon) built-in Java type embedding:

<xsl:stylesheet version="1.0" exclude-result-prefixes="xalan str"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:xalan="http://xml.apache.org/xalan"
                xmlns:str="xalan://java.lang.String"
        >
...
<xsl:value-of select="str:replaceAll(
    str:new(text()),
    $search_string,
    $replace_string)"/>
...
</xsl:stylesheet>

Grep and Python

You might be interested in pyp. Citing my other answer:

"The Pyed Piper", or pyp, is a linux command line text manipulation tool similar to awk or sed, but which uses standard python string and list methods as well as custom functions evolved to generate fast results in an intense production environment.

How do implement a breadth first traversal?

//traverse
public void traverse()
{
    if(node == null)
        System.out.println("Empty tree");
    else
    {
        Queue<Node> q= new LinkedList<Node>();
        q.add(node);
        while(q.peek() != null)
        {
            Node temp = q.remove();
            System.out.println(temp.getData());
            if(temp.left != null)
                q.add(temp.left);
            if(temp.right != null)
                q.add(temp.right);
        }
    }
}

}

Sort a list alphabetically

You can sort a list in-place just by calling List<T>.Sort:

list.Sort();

That will use the natural ordering of elements, which is fine in your case.

EDIT: Note that in your code, you'd need

_details.Sort();

as the Sort method is only defined in List<T>, not IList<T>. If you need to sort it from the outside where you don't have access to it as a List<T> (you shouldn't cast it as the List<T> part is an implementation detail) you'll need to do a bit more work.

I don't know of any IList<T>-based in-place sorts in .NET, which is slightly odd now I come to think of it. IList<T> provides everything you'd need, so it could be written as an extension method. There are lots of quicksort implementations around if you want to use one of those.

If you don't care about a bit of inefficiency, you could always use:

public void Sort<T>(IList<T> list)
{
    List<T> tmp = new List<T>(list);
    tmp.Sort();
    for (int i = 0; i < tmp.Count; i++)
    {
        list[i] = tmp[i];
    }
}

In other words, copy, sort in place, then copy the sorted list back.


You can use LINQ to create a new list which contains the original values but sorted:

var sortedList = list.OrderBy(x => x).ToList();

It depends which behaviour you want. Note that your shuffle method isn't really ideal:

  • Creating a new Random within the method runs into some of the problems shown here
  • You can declare val inside the loop - you're not using that default value
  • It's more idiomatic to use the Count property when you know you're working with an IList<T>
  • To my mind, a for loop is simpler to understand than traversing the list backwards with a while loop

There are other implementations of shuffling with Fisher-Yates on Stack Overflow - search and you'll find one pretty quickly.

Floating point exception( core dump

You are getting Floating point exception because Number % i, when i is 0:

int Is_Prime( int Number ){

  int i ;

  for( i = 0 ; i < Number / 2 ; i++ ){

    if( Number % i != 0 ) return -1 ;

  }

  return Number ;

}

Just start the loop at i = 2. Since i = 1 in Number % i it always be equal to zero, since Number is a int.

How to select a value in dropdown javascript?

Yes. As mentioned in the posts, value property is nonstandard and does not work with IE. You will need to use the selectedIndex property to achieve this. You can refer to the w3schools DOM reference to see the properties of HTML elements. The following link will give you the list of properties you can work with on the select element.

http://www.w3schools.com/jsref/dom_obj_select.asp

Update

This was not supported during 2011 on IE. As commented by finnTheHuman, it is supported at present.

C++ printing spaces or tabs given a user input integer

Appending single space to output file with stream variable.

// declare output file stream varaible and open file ofstream fout; fout.open("flux_capacitor.txt"); fout << var << " ";

How to write asynchronous functions for Node.js

Try this, it works for both node and the browser.

isNode = (typeof exports !== 'undefined') &&
(typeof module !== 'undefined') &&
(typeof module.exports !== 'undefined') &&
(typeof navigator === 'undefined' || typeof navigator.appName === 'undefined') ? true : false,
asyncIt = (isNode ? function (func) {
  process.nextTick(function () {
    func();
  });
} : function (func) {
  setTimeout(func, 5);
});

Python; urllib error: AttributeError: 'bytes' object has no attribute 'read'

I'm not familiar with python 3 yet, but it seems like urllib.request.urlopen().read() returns a byte object rather than string.

You might try to feed it into a StringIO object, or even do a str(response).