Programs & Examples On #Xunit

xUnit is the collection name for unit-testing compliant frameworks following a specific architecture. Implementation differs from language to language but the framework should consist of a Test Runner, Test Case, Test Fixture (Context), Test Suite, Test Execution, Test Result Formatter and Assertions

Visual Studio 2015 or 2017 does not discover unit tests

This happened to me because my test project contained an app.config. It was automatically added by NuGet packages for assembly redirection, but my tests seemed to run fine without it.

See: https://developercommunity.visualstudio.com/comments/42858/view.html.

What is the JUnit XML format specification that Hudson supports?

I just grabbed the junit-4.xsd that others have linked to and used a tool named XMLSpear to convert the schema to a blank XML file with the options shown below. This is the (slightly cleaned up) result:

<?xml version="1.0" encoding="UTF-8"?>
<testsuites disabled="" errors="" failures="" name="" tests="" time="">
    <testsuite disabled="" errors="" failures="" hostname="" id=""
               name="" package="" skipped="" tests="" time="" timestamp="">
        <properties>
            <property name="" value=""/>
        </properties>
        <testcase assertions="" classname="" name="" status="" time="">
            <skipped/>
            <error message="" type=""/>
            <failure message="" type=""/>
            <system-out/>
            <system-err/>
        </testcase>
        <system-out/>
        <system-err/>
    </testsuite>
</testsuites>

Some of these items can occur multiple times:

  • There can only be one testsuites element, since that’s how XML works, but there can be multiple testsuite elements within the testsuites element.
  • Each properties element can have multiple property children.
  • Each testsuite element can have multiple testcase children.
  • Each testcase element can have multiple error, failure, system-out, or system-err children.

XMLSpear options

mysqld: Can't change dir to data. Server doesn't start

First run

mysqld -u root --initialize-insecure 

It will create data folder with root as user without password. Then run

mysqld.exe -u root --console

Custom pagination view in Laravel 5

Hi there is my code for pagination: Use in blade @include('pagination.default', ['paginator' => $users])

Views/pagination/default.blade.php

@if ($paginator->lastPage() > 1)

si la pagina actual es distinto a 1 y hay mas de 5 hojas muestro el boton de 1era hoja --> if actual page is not equals 1, and there is more than 5 pages then I show first page button --> @if ($paginator->currentPage() != 1 && $paginator->lastPage() >= 5) << @endif
    <!-- si la pagina actual es distinto a 1 muestra el boton de atras -->
    @if($paginator->currentPage() != 1)
        <li>
            <a href="{{ $paginator->url($paginator->currentPage()-1) }}" >
                <
            </a>
        </li>
    @endif

    <!-- dibuja las hojas... Tomando un rango de 5 hojas, siempre que puede muestra 2 hojas hacia atras y 2 hacia adelante -->
    <!-- I draw the pages... I show 2 pages back and 2 pages forward -->
    @for($i = max($paginator->currentPage()-2, 1); $i <= min(max($paginator->currentPage()-2, 1)+4,$paginator->lastPage()); $i++)
            <li class="{{ ($paginator->currentPage() == $i) ? ' active' : '' }}">
                <a href="{{ $paginator->url($i) }}">{{ $i }}</a>
            </li>
    @endfor

    <!-- si la pagina actual es distinto a la ultima muestra el boton de adelante -->
    <!-- if actual page is not equal last page then I show the forward button-->
    @if ($paginator->currentPage() != $paginator->lastPage())
        <li>
            <a href="{{ $paginator->url($paginator->currentPage()+1) }}" >
                >
            </a>
        </li>
    @endif

    <!-- si la pagina actual es distinto a la ultima y hay mas de 5 hojas muestra el boton de ultima hoja -->
    <!-- if actual page is not equal last page, and there is more than 5 pages then I show last page button -->
    @if ($paginator->currentPage() != $paginator->lastPage() && $paginator->lastPage() >= 5)
        <li>
            <a href="{{ $paginator->url($paginator->lastPage()) }}" >
                >>
            </a>
        </li>
    @endif
</ul>

How to change the icon of an Android app in Eclipse?

Go into your AndroidManifest.xml file

  • Click on the Application Tab
  • Find the Text Box Labelled "Icon"
  • Then click the "Browse" button at the end of the text box
  • Click the Button Labelled: "Create New Icon..."

  • Create your icon
  • Click Finish
  • Click "Yes to All" if you already have the icon set to something else.

Enjoy using a gui rather then messing with an image editor! Hope this helps!

SQL Query NOT Between Two Dates

How about trying:

select * from 'test_table'
where end_date < CAST('2009-12-15' AS DATE)
or start_date > CAST('2010-01-02' AS DATE)

which will return all date ranges which do not overlap your date range at all.

How do I fix "The expression of type List needs unchecked conversion...'?

Since getEntries returns a raw List, it could hold anything.

The warning-free approach is to create a new List<SyndEntry>, then cast each element of the sf.getEntries() result to SyndEntry before adding it to your new list. Collections.checkedList does not do this checking for you—although it would have been possible to implement it to do so.

By doing your own cast up front, you're "complying with the warranty terms" of Java generics: if a ClassCastException is raised, it will be associated with a cast in the source code, not an invisible cast inserted by the compiler.

How do I set the eclipse.ini -vm option?

Anything after the "vmargs" is taken to be vm arguments. Just make sure it's before that, which is the last piece in eclipse.ini.

Switch on Enum in Java

You might be using the enums incorrectly in the switch cases. In comparison with the above example by CoolBeans.. you might be doing the following:

switch(day) {
    case Day.MONDAY:
        // Something..
        break;
    case Day.FRIDAY:
        // Something friday
        break;
}

Make sure that you use the actual enum values instead of EnumType.EnumValue

Eclipse points out this mistake though..

Which icon sizes should my Windows application's icon include?

TL;DR. In Visual Studio 2019, when you add an Icon resource to a Win32 (desktop) application you get an auto-generated icon file that has the formats below. I assume that the #1 developer tool for Windows does this right. Thus, a Windows compatible should have the following formats:

| Resolution | Color depth | Format |
|:-----------|------------:|:------:|
| 256x256    |      32-bit |  PNG   |
| 64x64      |      32-bit |  BMP   |
| 48x48      |      32-bit |  BMP   |
| 32x32      |      32-bit |  BMP   |
| 16x16      |      32-bit |  BMP   |
| 48x48      |       8-bit |  BMP   |
| 32x32      |       8-bit |  BMP   |
| 16x16      |       8-bit |  BMP   |

CSS: Position text in the middle of the page

Even though you've accepted an answer, I want to post this method. I use jQuery to center it vertically instead of css (although both of these methods work). Here is a fiddle, and I'll post the code here anyways.

HTML:

<h1>Hello world!</h1>

Javascript (jQuery):

$(document).ready(function(){
  $('h1').css({ 'width':'100%', 'text-align':'center' });
  var h1 = $('h1').height();
  var h = h1/2;
  var w1 = $(window).height();
  var w = w1/2;
  var m = w - h
  $('h1').css("margin-top",m + "px")
});

This takes the height of the viewport, divides it by two, subtracts half the height of the h1, and sets that number to the margin-top of the h1. The beauty of this method is that it works on multiple-line h1s.

EDIT: I modified it so that it centered it every time the window is resized.

How to check if a string starts with a specified string?

There is also the strncmp() function and strncasecmp() function which is perfect for this situation:

if (strncmp($string_n, "http", 4) === 0)

In general:

if (strncmp($string_n, $prefix, strlen($prefix)) === 0)

The advantage over the substr() approach is that strncmp() just does what needs to be done, without creating a temporary string.

How do I update the GUI from another thread?

The vast majority of answers use Control.Invoke which is a race condition waiting to happen. For example, consider the accepted answer:

string newText = "abc"; // running on worker thread
this.Invoke((MethodInvoker)delegate { 
    someLabel.Text = newText; // runs on UI thread
});

If the user closes the form just before this.Invoke is called (remember, this is the Form object), an ObjectDisposedException will be likely fired.

The solution is to use SynchronizationContext, specifically SynchronizationContext.Current as hamilton.danielb suggests (other answers rely on specific SynchronizationContext implementations which is completely unnecessary). I would slightly modify his code to use SynchronizationContext.Post rather than SynchronizationContext.Send though (as there's typically no need for the worker thread to wait):

public partial class MyForm : Form
{
    private readonly SynchronizationContext _context;
    public MyForm()
    {
        _context = SynchronizationContext.Current
        ...
    }

    private MethodOnOtherThread()
    {
         ...
         _context.Post(status => someLabel.Text = newText,null);
    }
}

Note that on .NET 4.0 and up you should really be using tasks for async operations. See n-san's answer for the equivalent task-based approach (using TaskScheduler.FromCurrentSynchronizationContext).

Finally, on .NET 4.5 and up you can also use Progress<T> (which basically captures SynchronizationContext.Current upon its creation) as demonstrated by Ryszard Dzegan's for cases where the long-running operation needs to run UI code while still working.

Writing BMP image in pure c/c++ without other libraries

C++ answer, flexible API, assumes little-endian system to code-golf it a bit. Note this uses the bmp native y-axis (0 at the bottom).

#include <vector>
#include <fstream>

struct image
{   
    image(int width, int height)
    :   w(width), h(height), rgb(w * h * 3)
    {}
    uint8_t & r(int x, int y) { return rgb[(x + y*w)*3 + 2]; }
    uint8_t & g(int x, int y) { return rgb[(x + y*w)*3 + 1]; }
    uint8_t & b(int x, int y) { return rgb[(x + y*w)*3 + 0]; }

    int w, h;
    std::vector<uint8_t> rgb;
};

template<class Stream>
Stream & operator<<(Stream & out, image const& img)
{   
    uint32_t w = img.w, h = img.h;
    uint32_t pad = w * -3 & 3;
    uint32_t total = 54 + 3*w*h + pad*h;
    uint32_t head[13] = {total, 0, 54, 40, w, h, (24<<16)|1};
    char const* rgb = (char const*)img.rgb.data();

    out.write("BM", 2);
    out.write((char*)head, 52);
    for(uint32_t i=0 ; i<h ; i++)
    {   out.write(rgb + (3 * w * i), 3 * w);
        out.write((char*)&pad, pad);
    }
    return out;
}

int main()
{
    image img(100, 100);
    for(int x=0 ; x<100 ; x++)
    {   for(int y=0 ; y<100 ; y++)
        {   img.r(x,y) = x;
            img.g(x,y) = y;
            img.b(x,y) = 100-x;
        }
    }
    std::ofstream("/tmp/out.bmp") << img;
}

path.join vs path.resolve with __dirname

From the doc for path.resolve:

The resulting path is normalized and trailing slashes are removed unless the path is resolved to the root directory.

But path.join keeps trailing slashes

So

__dirname = '/';
path.resolve(__dirname, 'foo/'); // '/foo'
path.join(__dirname, 'foo/'); // '/foo/'

Match groups in Python

You could create a little class that returns the boolean result of calling match, and retains the matched groups for subsequent retrieval:

import re

class REMatcher(object):
    def __init__(self, matchstring):
        self.matchstring = matchstring

    def match(self,regexp):
        self.rematch = re.match(regexp, self.matchstring)
        return bool(self.rematch)

    def group(self,i):
        return self.rematch.group(i)


for statement in ("I love Mary", 
                  "Ich liebe Margot", 
                  "Je t'aime Marie", 
                  "Te amo Maria"):

    m = REMatcher(statement)

    if m.match(r"I love (\w+)"): 
        print "He loves",m.group(1) 

    elif m.match(r"Ich liebe (\w+)"):
        print "Er liebt",m.group(1) 

    elif m.match(r"Je t'aime (\w+)"):
        print "Il aime",m.group(1) 

    else: 
        print "???"

Update for Python 3 print as a function, and Python 3.8 assignment expressions - no need for a REMatcher class now:

import re

for statement in ("I love Mary",
                  "Ich liebe Margot",
                  "Je t'aime Marie",
                  "Te amo Maria"):

    if m := re.match(r"I love (\w+)", statement):
        print("He loves", m.group(1))

    elif m := re.match(r"Ich liebe (\w+)", statement):
        print("Er liebt", m.group(1))

    elif m := re.match(r"Je t'aime (\w+)", statement):
        print("Il aime", m.group(1))

    else:
        print()

How do you create nested dict in Python?

UPDATE: For an arbitrary length of a nested dictionary, go to this answer.

Use the defaultdict function from the collections.

High performance: "if key not in dict" is very expensive when the data set is large.

Low maintenance: make the code more readable and can be easily extended.

from collections import defaultdict

target_dict = defaultdict(dict)
target_dict[key1][key2] = val

Convert double to Int, rounded down

If you explicitly cast double to int, the decimal part will be truncated. For example:

int x = (int) 4.97542;   //gives 4 only
int x = (int) 4.23544;   //gives 4 only

Moreover, you may also use Math.floor() method to round values in case you want double value in return.

Reading JSON POST using PHP

Hello this is a snippet from an old project of mine that uses curl to get ip information from some free ip databases services which reply in json format. I think it might help you.

$ip_srv = array("http://freegeoip.net/json/$this->ip","http://smart-ip.net/geoip-json/$this->ip");

getUserLocation($ip_srv);

Function:

function getUserLocation($services) {

        $ctx = stream_context_create(array('http' => array('timeout' => 15))); // 15 seconds timeout

        for ($i = 0; $i < count($services); $i++) {

            // Configuring curl options
            $options = array (
                CURLOPT_RETURNTRANSFER => true, // return web page
                //CURLOPT_HEADER => false, // don't return headers
                CURLOPT_HTTPHEADER => array('Content-type: application/json'),
                CURLOPT_FOLLOWLOCATION => true, // follow redirects
                CURLOPT_ENCODING => "", // handle compressed
                CURLOPT_USERAGENT => "test", // who am i
                CURLOPT_AUTOREFERER => true, // set referer on redirect
                CURLOPT_CONNECTTIMEOUT => 5, // timeout on connect
                CURLOPT_TIMEOUT => 5, // timeout on response
                CURLOPT_MAXREDIRS => 10 // stop after 10 redirects
            ); 

            // Initializing curl
            $ch = curl_init($services[$i]);
            curl_setopt_array ( $ch, $options );

            $content = curl_exec ( $ch );
            $err = curl_errno ( $ch );
            $errmsg = curl_error ( $ch );
            $header = curl_getinfo ( $ch );
            $httpCode = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );

            curl_close ( $ch );

            //echo 'service: ' . $services[$i] . '</br>';
            //echo 'err: '.$err.'</br>';
            //echo 'errmsg: '.$errmsg.'</br>';
            //echo 'httpCode: '.$httpCode.'</br>';
            //print_r($header);
            //print_r(json_decode($content, true));

            if ($err == 0 && $httpCode == 200 && $header['download_content_length'] > 0) {

                return json_decode($content, true);

            } 

        }
    }

Send POST request using NSURLSession

Motivation

Sometimes I have been getting some errors when you want to pass httpBody serialized to Data from Dictionary, which on most cases is due to the wrong encoding or malformed data due to non NSCoding conforming objects in the Dictionary.

Solution

Depending on your requirements one easy solution would be to create a String instead of Dictionary and convert it to Data. You have the code samples below written on Objective-C and Swift 3.0.

Objective-C

// Create the URLSession on the default configuration
NSURLSessionConfiguration *defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultSessionConfiguration];

// Setup the request with URL
NSURL *url = [NSURL URLWithString:@"yourURL"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];

// Convert POST string parameters to data using UTF8 Encoding
NSString *postParams = @"api_key=APIKEY&[email protected]&password=password";
NSData *postData = [postParams dataUsingEncoding:NSUTF8StringEncoding];

// Convert POST string parameters to data using UTF8 Encoding
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:postData];

// Create dataTask
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    // Handle your response here
}];

// Fire the request
[dataTask resume];

Swift

// Create the URLSession on the default configuration
let defaultSessionConfiguration = URLSessionConfiguration.default
let defaultSession = URLSession(configuration: defaultSessionConfiguration)

// Setup the request with URL
let url = URL(string: "yourURL")
var urlRequest = URLRequest(url: url!)  // Note: This is a demo, that's why I use implicitly unwrapped optional

// Convert POST string parameters to data using UTF8 Encoding
let postParams = "api_key=APIKEY&[email protected]&password=password"
let postData = postParams.data(using: .utf8)

// Set the httpMethod and assign httpBody
urlRequest.httpMethod = "POST"
urlRequest.httpBody = postData

// Create dataTask
let dataTask = defaultSession.dataTask(with: urlRequest) { (data, response, error) in
    // Handle your response here
}

// Fire the request
dataTask.resume()

Javascript change font color

You can use the HTML tag in order to apply font size, font color in one line on JavaScript, as well as you can use .fontcolor() method to define color, .fontsize() method to define the font size, .bold() method to define bold, etc. These are called JavaScript Built-in Functions.

  • Here is a list of some JavaScript built-in functions:

    .big()
    .small()
    .italics()
    .fixed()
    .strike()
    .sup()

  • The below built-in functions require parameters:

    .fontsize() //e.g.: the size to be applied in number .fontsize(4)

    .fontcolor("") //e.g.: the color to be applied in string .fontcolor("red")

    .txt.link("") //e.g.: the url to be linkable as string .link("www.test.com")

    .toUpperCase() //e.g.: the converted to uppercase to be applied in string .toUpperCase()

  • Remember the syntax is: string.functionName() e.g.:

    var txt = "Hello World!"; txt.bold();

  • This also can be done in one line:

    var txt = "Hello World!".bold();

    The result will be: Hello World!

  • You can use multiple built-in functions in one line, adding one next to the other. e.g.:

    "10/22/2018".fontcolor("red").fontsize(4).bold()

  • The following is an example how I used it on my JavaScript code to change font (color, size, bold) using both HTML tags and JavaScript functions:

vForm.message = "<HTML><font size = 4 color = 'red'><b> Application Deadline was </b></font></HTML> " + "10/22/2018".fontcolor("red").fontsize(4).bold(); /* setting HTML font color, size, bold and combined them with JavaScript functions to change font color, size, bold in JavaScript code */

  • Here is the result:

Application Deadline was  10/22/2018

How to expire a cookie in 30 minutes using jQuery?

30 minutes is 30 * 60 * 1000 miliseconds. Add that to the current date to specify an expiration date 30 minutes in the future.

 var date = new Date();
 var minutes = 30;
 date.setTime(date.getTime() + (minutes * 60 * 1000));
 $.cookie("example", "foo", { expires: date });

Can we have multiple "WITH AS" in single sql - Oracle SQL

You can do this as:

WITH abc AS( select
             FROM ...)
, XYZ AS(select
         From abc ....) /*This one uses "abc" multiple times*/
  Select 
  From XYZ....   /*using abc, XYZ multiple times*/

Can I load a .NET assembly at runtime and instantiate a type knowing only the name?

Yes. I don't have any examples that I've done personally available right now. I'll post later when I find some. Basically you'll use reflection to load the assembly and then to pull whatever types you need for it.

In the meantime, this link should get you started:

Using reflection to load unreferenced assemblies at runtime

Default FirebaseApp is not initialized

I downgrade project gms:google_services to classpath 'com.google.gms:google-services:4.0.1' and it work for me.

how do I change text in a label with swift?

Swift uses the same cocoa-touch API. You can call all the same methods, but they will use Swift's syntax. In this example you can do something like this:

self.simpleLabel.text = "message"

Note the setText method isn't available. Setting the label's text with = will automatically call the setter in swift.

T-SQL: Using a CASE in an UPDATE statement to update certain columns depending on a condition

I know this is a very old question and the problem is marked as fixed. However, if someone with a case like mine where the table have trigger for data logging on update events, this will cause problem. Both the columns will get the update and log will make useless entries. The way I did

IF (CONDITION) IS TRUE
BEGIN
    UPDATE table SET columnx = 25
END
ELSE
BEGIN
    UPDATE table SET columny = 25
END

Now this have another benefit that it does not have unnecessary writes on the table like the above solutions.

Facebook Open Graph not clearing cache

Had a similar experience. Website link was showing a 404 in the preview that facebook generated. Turns out the og:url metadata was wrong. We had already fixed it a few days back but were still seeing a 404 on the preview. We used the tool at https://developers.facebook.com/tools/debug/ and that forced the refresh (didn't have to append any parameters by the way) In our case, Facebook didn't refresh the cache after 24 hours but the tool helped force it.

Why does calling sumr on a stream with 50 tuples not complete

sumr is implemented in terms of foldRight:

 final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append) 

foldRight is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.

Convenient way to parse incoming multipart/form-data parameters in a Servlet

Not always there's a servlet before of an upload (I could use a filter for example). Or could be that the same controller ( again a filter or also a servelt ) can serve many actions, so I think that rely on that servlet configuration to use the getPart method (only for Servlet API >= 3.0), I don't know, I don't like.

In general, I prefer independent solutions, able to live alone, and in this case http://commons.apache.org/proper/commons-fileupload/ is one of that.

List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
    for (FileItem item : multiparts) {
        if (!item.isFormField()) {
            //your operations on file
        } else {
            String name = item.getFieldName();
            String value = item.getString();
            //you operations on paramters
        }
}

open new tab(window) by clicking a link in jquery

Try this:

window.open(url, '_blank');

This will open in new tab (if your code is synchronous and in this case it is. in other case it would open a window)

How do I lowercase a string in C?

Looping the pointer to gain better performance:

#include <ctype.h>

char* toLower(char* s) {
  for(char *p=s; *p; p++) *p=tolower(*p);
  return s;
}
char* toUpper(char* s) {
  for(char *p=s; *p; p++) *p=toupper(*p);
  return s;
}

The specified DSN contains an architecture mismatch between the Driver and Application. JAVA

Have you created the DSN first in Control Panel>Administrative Tools>ODBC>System DSN. Name it same as "myDatabase" and if i is asking for locating the database/access file specify the path using browse option. Once ur DSN will be created successfully you will be easily able to access ur DB.

fatal: This operation must be run in a work tree

You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree option for single commands, or the GIT_WORK_TREE environment variable. There is also the core.worktree configuration option but it will not work in a bare repository (check the man page for what it does).

# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status

Is this a good way to clone an object in ES6?

This is good for shallow cloning. The object spread is a standard part of ECMAScript 2018.

For deep cloning you'll need a different solution.

const clone = {...original} to shallow clone

const newobj = {...original, prop: newOne} to immutably add another prop to the original and store as a new object.

Switch android x86 screen resolution

I'd like to clarify one small gotcha here. You must use CustomVideoMode1 before CustomVideoMode2, etc. VirtualBox recognizes these modes in order starting from 1 and if you skip a number, it will not recognize anything at or beyond the number you skipped. This caught me by surprise.

Check if a user has scrolled to the bottom

This is my two cents:

$('#container_element').scroll( function(){
        console.log($(this).scrollTop()+' + '+ $(this).height()+' = '+ ($(this).scrollTop() + $(this).height())   +' _ '+ $(this)[0].scrollHeight  );
        if($(this).scrollTop() + $(this).height() == $(this)[0].scrollHeight){
            console.log('bottom found');
        }
    });

Formula to convert date to number

If you change the format of the cells to General then this will show the date value of a cell as behind the scenes Excel saves a date as the number of days since 01/01/1900

Screenprint 1

Screenprint 2

If your date is text and you need to convert it then DATEVALUE will do this:

Datevalue function

Maven: The packaging for this project did not assign a file to the build artifact

This worked for me when I got the same error message...

mvn install deploy

Selecting multiple columns in a Pandas dataframe

You can use Pandas.

I create the DataFrame:

import pandas as pd
df = pd.DataFrame([[1, 2,5], [5,4, 5], [7,7, 8], [7,6,9]],
                  index=['Jane', 'Peter','Alex','Ann'],
                  columns=['Test_1', 'Test_2', 'Test_3'])

The DataFrame:

       Test_1  Test_2  Test_3
Jane        1       2       5
Peter       5       4       5
Alex        7       7       8
Ann         7       6       9

To select one or more columns by name:

df[['Test_1', 'Test_3']]

       Test_1  Test_3
Jane        1       5
Peter       5       5
Alex        7       8
Ann         7       9

You can also use:

df.Test_2

And you get column Test_2:

Jane     2
Peter    4
Alex     7
Ann      6

You can also select columns and rows from these rows using .loc(). This is called "slicing". Notice that I take from column Test_1 to Test_3:

df.loc[:, 'Test_1':'Test_3']

The "Slice" is:

       Test_1  Test_2  Test_3
Jane        1       2       5
Peter       5       4       5
Alex        7       7       8
Ann         7       6       9

And if you just want Peter and Ann from columns Test_1 and Test_3:

df.loc[['Peter', 'Ann'], ['Test_1', 'Test_3']]

You get:

       Test_1  Test_3
Peter       5       5
Ann         7       9

How can I add items to an empty set in python

D = {} is a dictionary not set.

>>> d = {}
>>> type(d)
<type 'dict'>

Use D = set():

>>> d = set()
>>> type(d)
<type 'set'>
>>> d.update({1})
>>> d.add(2)
>>> d.update([3,3,3])
>>> d
set([1, 2, 3])

How to make html table vertically scrollable

Try this one.. It is working... Here JSBIN

table tbody { height:300px; overflow-y:scroll; display:block; }
table thead { display:block; }

Add CSS or JavaScript files to layout head from views or partial views

I wrote an easy wrapper that allows you to register styles and scrips in every partial view dynamically into the head tag.

It is based on the DynamicHeader jsakamoto put up, but it has some performance improvements & tweaks.

It is very easy to use, and versatile.

The usage:

@{
    DynamicHeader.AddStyleSheet("/Content/Css/footer.css", ResourceType.Layout);    
    DynamicHeader.AddStyleSheet("/Content/Css/controls.css", ResourceType.Infrastructure);
    DynamicHeader.AddScript("/Content/Js/Controls.js", ResourceType.Infrastructure);
    DynamicHeader.AddStyleSheet("/Content/Css/homepage.css");    
}

You can find the full code, explanations and examples inside: Add Styles & Scripts Dynamically to Head Tag

count number of lines in terminal output

Piping to 'wc' could be better IF the last line ends with a newline (I know that in this case, it will)
However, if the last line does not end with a newline 'wc -l' gives back a false result.

For example:

$ echo "asd" | wc -l

Will return 1 and

$ echo -n "asd" | wc -l

Will return 0


So what I often use is grep <anything> -c

$ echo "asd" | grep "^.*$" -c
1

$ echo -n "asd" | grep "^.*$" -c
1

This is closer to reality than what wc -l will return.

HTML/Javascript change div content

$('#content').html('whatever');

pyplot axes labels for subplots

Here is a solution where you set the ylabel of one of the plots and adjust the position of it so it is centered vertically. This way you avoid problems mentioned by KYC.

import numpy as np
import matplotlib.pyplot as plt

def set_shared_ylabel(a, ylabel, labelpad = 0.01):
    """Set a y label shared by multiple axes
    Parameters
    ----------
    a: list of axes
    ylabel: string
    labelpad: float
        Sets the padding between ticklabels and axis label"""

    f = a[0].get_figure()
    f.canvas.draw() #sets f.canvas.renderer needed below

    # get the center position for all plots
    top = a[0].get_position().y1
    bottom = a[-1].get_position().y0

    # get the coordinates of the left side of the tick labels 
    x0 = 1
    for at in a:
        at.set_ylabel('') # just to make sure we don't and up with multiple labels
        bboxes, _ = at.yaxis.get_ticklabel_extents(f.canvas.renderer)
        bboxes = bboxes.inverse_transformed(f.transFigure)
        xt = bboxes.x0
        if xt < x0:
            x0 = xt
    tick_label_left = x0

    # set position of label
    a[-1].set_ylabel(ylabel)
    a[-1].yaxis.set_label_coords(tick_label_left - labelpad,(bottom + top)/2, transform=f.transFigure)

length = 100
x = np.linspace(0,100, length)
y1 = np.random.random(length) * 1000
y2 = np.random.random(length)

f,a = plt.subplots(2, sharex=True, gridspec_kw={'hspace':0})
a[0].plot(x, y1)
a[1].plot(x, y2)
set_shared_ylabel(a, 'shared y label (a. u.)')

enter image description here

Shell script to check if file exists

Wildcards aren't expanded inside quoted strings. And when wildcard is expanded, it's returned unchanged if there are no matches, it doesn't expand into an empty string. Try:

output="$(ls home/edward/bank1/fiche/Test* 2>/dev/null)"
if [ -n "$output" ]
then echo "Found one"
else echo "Found none"
fi

If the wildcard expanded to filenames, ls will list them on stdout; otherwise it will print an error on stderr, and nothing on stdout. The contents of stdout are assigned to output.

if [ -n "$output" ] tests whether $output contains anything.

Another way to write this would be:

if [ $(ls home/edward/bank1/fiche/Test* 2>/dev/null | wc -l) -gt 0 ]

How to convert WebResponse.GetResponseStream return into a string?

As @Heinzi mentioned the character set of the response should be used.

var encoding = response.CharacterSet == ""
    ? Encoding.UTF8
    : Encoding.GetEncoding(response.CharacterSet);

using (var stream = response.GetResponseStream())
{
    var reader = new StreamReader(stream, encoding);
    var responseString = reader.ReadToEnd();
}

What's the algorithm to calculate aspect ratio?

I think this does what you are asking for:

webdeveloper.com - decimal to fraction

Width/height gets you a decimal, converted to a fraction with ":" in place of '/' gives you a "ratio".

jQuery scroll() detect when user stops scrolling

Ok this is something that I've used before. Basically you look a hold a ref to the last scrollTop(). Once your timeout clears, you check the current scrollTop() and if they are the same, you are done scrolling.

$(window).scroll((e) ->
  clearTimeout(scrollTimer)
  $('header').addClass('hidden')

  scrollTimer = setTimeout((() ->
    if $(this).scrollTop() is currentScrollTop
      $('header').removeClass('hidden') 
  ), animationDuration)

  currentScrollTop = $(this).scrollTop()
)

What is the (best) way to manage permissions for Docker shared volumes?

This is arguably not the best way for most circumstances, but it's not been mentioned yet so perhaps it will help someone.

  1. Bind mount host volume

    Host folder FOOBAR is mounted in container /volume/FOOBAR

  2. Modify your container's startup script to find GID of the volume you're interested in

    $ TARGET_GID=$(stat -c "%g" /volume/FOOBAR)

  3. Ensure your user belongs to a group with this GID (you may have to create a new group). For this example I'll pretend my software runs as the nobody user when inside the container, so I want to ensure nobody belongs to a group with a group id equal to TARGET_GID

  EXISTS=$(cat /etc/group | grep $TARGET_GID | wc -l)

  # Create new group using target GID and add nobody user
  if [ $EXISTS == "0" ]; then
    groupadd -g $TARGET_GID tempgroup
    usermod -a -G tempgroup nobody
  else
    # GID exists, find group name and add
    GROUP=$(getent group $TARGET_GID | cut -d: -f1)
    usermod -a -G $GROUP nobody
  fi

I like this because I can easily modify group permissions on my host volumes and know that those updated permissions apply inside the docker container. This happens without any permission or ownership modifications to my host folders/files, which makes me happy.

I don't like this because it assumes there's no danger in adding yourself to an arbitrary groups inside the container that happen to be using a GID you want. It cannot be used with a USER clause in a Dockerfile (unless that user has root privileges I suppose). Also, it screams hack job ;-)

If you want to be hardcore you can obviously extend this in many ways - e.g. search for all groups on any subfiles, multiple volumes, etc.

Hibernate problem - "Use of @OneToMany or @ManyToMany targeting an unmapped class"

Your entity may not listed in hibernate configuration file.

Disabling browser print options (headers, footers, margins) from page?

I have a similar request from a client who wants to have the header, page numbers, and html footer removed. In this case, the client is presenting an HTML page that can double as a formal certificate. The added URL, page, and, header, are irrelevant and lead to a less-than-pleasing final product. In some ways, it just looks cheap.

Media=Print has not been able to disable these browser defaults. The only workaround is to tell the user to click the "Gear" button and toggle those items on/off. Seriously, I had no idea I could do that for 20 years (and we think the typical user will have a clue to click the toggle button?).

If CSS supports Media=Print, it should support the ability to control the entire end-user print experience. I appreciate that the browsers provide the added fields, but, why not allow CSS to control the overall print experience-if that is what's desired. A 90% solution could be 100% with three more fields! A simple:

#BrowserPrintDefaults{display:none} 

would suffice.

Again, it's not a matter whether or not the end-user wants to print it out or not (maybe your client is very private and doesn't want printed URLs floating around. Or maybe a executive team uses a private collaboration sites?). Glad to defend the end-user, but if somebody is seeking an answer, don't respond saying it's the right of the end-user to show or hide. Sometimes it's the right of the client paying the bills.

Select subset of columns in data.table R

Option using dplyr

require(dplyr)
dt<-as.data.frame(matrix(runif(10*10),10,10))
dt <- select(dt, -V1, -V2, -V3, -V4)
cor(dt)

node.js + mysql connection pooling

You will find this wrapper usefull :)

var pool = mysql.createPool(config.db);

exports.connection = {
    query: function () {
        var queryArgs = Array.prototype.slice.call(arguments),
            events = [],
            eventNameIndex = {};

        pool.getConnection(function (err, conn) {
            if (err) {
                if (eventNameIndex.error) {
                    eventNameIndex.error();
                }
            }
            if (conn) { 
                var q = conn.query.apply(conn, queryArgs);
                q.on('end', function () {
                    conn.release();
                });

                events.forEach(function (args) {
                    q.on.apply(q, args);
                });
            }
        });

        return {
            on: function (eventName, callback) {
                events.push(Array.prototype.slice.call(arguments));
                eventNameIndex[eventName] = callback;
                return this;
            }
        };
    }
};

Require it, use it like this:

db.connection.query("SELECT * FROM `table` WHERE `id` = ? ", row_id)
          .on('result', function (row) {
            setData(row);
          })
          .on('error', function (err) {
            callback({error: true, err: err});
          });

How do you convert a DataTable into a generic list?

// this is better suited for expensive object creation/initialization
IEnumerable<Employee> ParseEmployeeTable(DataTable dtEmployees)
{
    var employees = new ConcurrentBag<Employee>();

    Parallel.ForEach(dtEmployees.AsEnumerable(), (dr) =>
    {
        employees.Add(new Employee() 
        {
            _FirstName = dr["FirstName"].ToString(),
            _LastName = dr["Last_Name"].ToString()
        });
    });

    return employees;
}

html div onclick event

when click on div alert key

   $(document).delegate(".searchbtn", "click", function() {
        var key=$.trim($('#txtkey').val());
        alert(key);
        });

How to detect the physical connected state of a network cable/connector?

Use 'ip monitor' to get REAL TIME link state changes.

SpringMVC RequestMapping for GET parameters

You can add @RequestMapping like so:

@RequestMapping("/userGrid")
public @ResponseBody GridModel getUsersForGrid(
   @RequestParam("_search") String search,
   @RequestParam String nd,
   @RequestParam int rows,
   @RequestParam int page,
   @RequestParam String sidx) 
   @RequestParam String sord) {

Append date to filename in linux

I use this script in bash:

#!/bin/bash

now=$(date +"%b%d-%Y-%H%M%S")
FILE="$1"
name="${FILE%.*}"
ext="${FILE##*.}"

cp -v $FILE $name-$now.$ext

This script copies filename.ext to filename-date.ext, there is another that moves filename.ext to filename-date.ext, you can download them from here. Hope you find them useful!!

Update span tag value with JQuery

Tag ids must be unique. You are updating the span with ID 'ItemCostSpan' of which there are two. Give the span a class and get it using find.

    $("legend").each(function() {
        var SoftwareItem = $(this).text();
        itemCost = GetItemCost(SoftwareItem);
        $("input:checked").each(function() {               
            var Component = $(this).next("label").text();
            itemCost += GetItemCost(Component);
        });            
        $(this).find(".ItemCostSpan").text("Item Cost = $ " + itemCost);
    });

How are Anonymous inner classes used in Java?

Anonymous inner classes are effectively closures, so they can be used to emulate lambda expressions or "delegates". For example, take this interface:

public interface F<A, B> {
   B f(A a);
}

You can use this anonymously to create a first-class function in Java. Let's say you have the following method that returns the first number larger than i in the given list, or i if no number is larger:

public static int larger(final List<Integer> ns, final int i) {
  for (Integer n : ns)
     if (n > i)
        return n;
  return i;
}

And then you have another method that returns the first number smaller than i in the given list, or i if no number is smaller:

public static int smaller(final List<Integer> ns, final int i) {
   for (Integer n : ns)
      if (n < i)
         return n;
   return i;
}

These methods are almost identical. Using the first-class function type F, we can rewrite these into one method as follows:

public static <T> T firstMatch(final List<T> ts, final F<T, Boolean> f, T z) {
   for (T t : ts)
      if (f.f(t))
         return t;
   return z;
}

You can use an anonymous class to use the firstMatch method:

F<Integer, Boolean> greaterThanTen = new F<Integer, Boolean> {
   Boolean f(final Integer n) {
      return n > 10;
   }
};
int moreThanMyFingersCanCount = firstMatch(xs, greaterThanTen, x);

This is a really contrived example, but its easy to see that being able to pass functions around as if they were values is a pretty useful feature. See "Can Your Programming Language Do This" by Joel himself.

A nice library for programming Java in this style: Functional Java.

Could not insert new outlet connection: Could not find any information for the class named

I solved this problem by programmatically creating the Labels and Textfields, and then Command-Dragged from the little empty circles on the left of the code to the components on the Storyboard. To illustrate my point: I wrote @IBOutlet weak var HelloLabel: UILabel!, and then pressed Command and dragged the code into the component on the storyboard.

How to convert an ASCII character into an int in C

Use the ASCII to Integer atoi() function which accepts a string and converts it into an integer:

#include <stdlib.h>

int num = atoi("23"); // 23

If the string contains a decimal, the number will be truncated:

int num = atoi("23.21"); // 23

Get Context in a Service

As Service is already a Context itself

you can even get it through:

Context mContext = this;

OR

Context mContext = [class name].this;  //[] only specify the class name
// mContext = JobServiceSchedule.this; 

Tools to search for strings inside files without indexing

There is also a Windows built-in program called findstr.exe with which you can search within files.

>findstr /s "provider=sqloledb" *.cs

How do I convert a dictionary to a JSON String in C#?

It seems a lot of different libraries and what not have seem to come and go over the previous years. However as of April 2016, this solution worked well for me. Strings easily replaced by ints.

TL/DR; Copy this if that's what you came here for:

    //outputfilename will be something like: "C:/MyFolder/MyFile.txt"
    void WriteDictionaryAsJson(Dictionary<string, List<string>> myDict, string outputfilename)
    {
        DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Dictionary<string, List<string>>));
        MemoryStream ms = new MemoryStream();
        js.WriteObject(ms, myDict); //Does the serialization.

        StreamWriter streamwriter = new StreamWriter(outputfilename);
        streamwriter.AutoFlush = true; // Without this, I've run into issues with the stream being "full"...this solves that problem.

        ms.Position = 0; //ms contains our data in json format, so let's start from the beginning
        StreamReader sr = new StreamReader(ms); //Read all of our memory
        streamwriter.WriteLine(sr.ReadToEnd()); // and write it out.

        ms.Close(); //Shutdown everything since we're done.
        streamwriter.Close();
        sr.Close();
    }

Two import points. First, be sure to add System.Runtime.Serliazation as a reference in your project inside Visual Studio's Solution Explorer. Second, add this line,

using System.Runtime.Serialization.Json;

at the top of the file with the rest of your usings, so the DataContractJsonSerializer class can be found. This blog post has more information on this method of serialization.

Data Format (Input / Output)

My data is a dictionary with 3 strings, each pointing to a list of strings. The lists of strings have lengths 3, 4, and 1. The data looks like this:

StringKeyofDictionary1 => ["abc","def","ghi"]
StringKeyofDictionary2 => ["String01","String02","String03","String04"]
Stringkey3 => ["someString"]

The output written to file will be on one line, here is the formatted output:

 [{
     "Key": "StringKeyofDictionary1",
     "Value": ["abc",
     "def",
     "ghi"]
 },
 {
     "Key": "StringKeyofDictionary2",
     "Value": ["String01",
     "String02",
     "String03",
     "String04",
 ]
 },
 {
     "Key": "Stringkey3",
     "Value": ["SomeString"]
 }]

What is key=lambda

Lambda can be any function. So if you had a function

def compare_person(a):
         return a.age

You could sort a list of Person (each of which having an age attribute) like this:

sorted(personArray, key=compare_person)

This way, the list would be sorted by age in ascending order.

The parameter is called lambda because python has a nifty lambda keywords for defining such functions on the fly. Instead of defining a function compare_person and passing that to sorted, you can also write:

sorted(personArray, key=lambda a: a.age)

which does the same thing.

How to reload current page?

Here is the simple one

if (this.router && this.router.url === '/') { or your current page url e.g '/home' 
    window.location.reload();
  } else {
    this.router.navigate([url]);
  }

Django model "doesn't declare an explicit app_label"

Most probably you have dependent imports.

In my case I used a serializer class as a parameter in my model, and the serializer class was using this model: serializer_class = AccountSerializer

from ..api.serializers import AccountSerializer

class Account(AbstractBaseUser):
    serializer_class = AccountSerializer
    ...

And in the "serializers" file:

from ..models import Account

class AccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = Account
        fields = (
            'id', 'email', 'date_created', 'date_modified',
            'firstname', 'lastname', 'password', 'confirm_password')
    ...

Best way to include CSS? Why use @import?

Quoted from http://webdesign.about.com/od/beginningcss/f/css_import_link.htm

The main purpose of @import method is to use multiple style sheets on a page, but only one link in your < head >. For example, a corporation might have a global style sheet for every page on the site, with sub-sections having additional styles that only apply to that sub-section. By linking to the sub-section style sheet and importing the global styles at the top of that style sheet, you don't have to maintain a gigantic style sheet with all the styles for the site and every sub-section. The only requirement is that any @import rules need to come before the rest of your style rules. And remember that inheritance can still be a problem.

Remove all special characters with RegExp

str.replace(/\s|[0-9_]|\W|[#$%^&*()]/g, "") I did sth like this. But there is some people who did it much easier like str.replace(/\W_/g,"");

Update a column in MySQL

If you want to update data you should use UPDATE command instead of INSERT

python: order a list of numbers without built-in sort, min, max function

def bubble_sort(seq):
    """Inefficiently sort the mutable sequence (list) in place.
       seq MUST BE A MUTABLE SEQUENCE.

       As with list.sort() and random.shuffle this does NOT return 
    """
    changed = True
    while changed:
        changed = False
        for i in xrange(len(seq) - 1):
            if seq[i] > seq[i+1]:
                seq[i], seq[i+1] = seq[i+1], seq[i]
                changed = True
    return None

if __name__ == "__main__":
   """Sample usage and simple test suite"""

   from random import shuffle

   testset = range(100)
   testcase = testset[:] # make a copy
   shuffle(testcase)
   assert testcase != testset  # we've shuffled it
   bubble_sort(testcase)
   assert testcase == testset  # we've unshuffled it back into a copy

From : http://rosettacode.org/wiki/Bubble_Sort#Python

What does 'stale file handle' in Linux mean?

When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).

Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle message because you asked for some nonexistent data.

When you perform a cd operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.

Using Python Requests: Sessions, Cookies, and POST

I don't know how stubhub's api works, but generally it should look like this:

s = requests.Session()
data = {"login":"my_login", "password":"my_password"}
url = "http://example.net/login"
r = s.post(url, data=data)

Now your session contains cookies provided by login form. To access cookies of this session simply use

s.cookies

Any further actions like another requests will have this cookie

jquery/javascript convert date string to date

If you only need it once, it's overkill to load a plugin.

For a date "dd/mm/yyyy", this works for me:

new Date(d.date.substring(6, 10),d.date.substring(3, 5)-1,d.date.substring(0, 2));

Just invert month and day for mm/dd/yyyy, the syntax is new Date(y,m,d)

Apply jQuery datepicker to multiple instances

I had a similar problem with dynamically adding datepicker classes. The solution I found was to comment out line 46 of datepicker.js

// this.element.on('click', $.proxy(this.show, this));

How to start color picker on Mac OS?

You can turn the color picker into an application by following the guide here:

http://hints.macworld.com/article.php?story=20060408050920158

From the guide:

Simply fire up AppleScript (Applications -> AppleScript Editor) and enter this text:

choose color

Now, save it as an application (File -> Save As, and set the File Format pop-up to Application), and you're done

How to skip over an element in .map()?

You can use after of you method map(). The method filter() for example in your case:

var sources = images.map(function (img) {
  if(img.src.split('.').pop() === "json"){ // if extension is .json
    return null; // skip
  }
  else {
    return img.src;
  }
});

The method filter:

const sourceFiltered = sources.filter(item => item)

Then, only the existing items are in the new array sourceFiltered.

Generate .pem file used to set up Apple Push Notifications

To enable Push Notification for your iOS app, you will need to create and upload the Apple Push Notification Certificate (.pem file) to us so we will be able to connect to Apple Push Server on your behalf.

(Updated version with updated screen shots Here)

Step 1: Login to iOS Provisioning Portal, click "Certificates" on the left navigation bar. Then, click "+" button.

enter image description here

Step 2: Select Apple Push Notification service SSL (Production) option under Distribution section, then click "Continue" button.

enter image description here

Step 3: Select the App ID you want to use for your BYO app (How to Create An App ID), then click "Continue" to go to next step.

enter image description here

Step 4: Follow the steps "About Creating a Certificate Signing Request (CSR)" to create a Certificate Signing Request.

enter image description here

To supplement the instruction provided by Apple. Here are some of the additional screenshots to assist you to complete the required steps:

Step 4 Supplementary Screenshot 1: Navigate to Certificate Assistant of Keychain Access on your Mac.

enter image description here

Step 4 Supplementary Screenshot 2: Fill in the Certificate Information. Click Continue.

enter image description here

Step 5: Upload the ".certSigningRequest" file which is generated in Step 4, then click "Generate" button.

enter image description here

Step 6: Click "Done" to finish the registration, the iOS Provisioning Portal Page will be refreshed that looks like the following screen:

enter image description here

Then Click "Download" button to download the certificate (.cer file) you've created just now. - Double click the downloaded file to install the certificate into Keychain Access on your Mac.

Step 7: On your Mac, go to "Keychain", look for the certificate you have just installed. If unsure which certificate is the correct one, it should start with "Apple Production IOS Push Services:" followed by your app's bundle ID.

enter image description here

Step 8: Expand the certificate, you should see the private key with either your name or your company name. Select both items by using the "Select" key on your keyboard, right click (or cmd-click if you use a single button mouse), choose "Export 2 items", like Below:

enter image description here

Then save the p12 file with name "pushcert.p12" to your Desktop - now you will be prompted to enter a password to protect it, you can either click Enter to skip the password or enter a password you desire.

Step 9: Now the most difficult part - open "Terminal" on your Mac, and run the following commands:

cd
cd Desktop
openssl pkcs12 -in pushcert.p12 -out pushcert.pem -nodes -clcerts

Step 10: Remove pushcert.p12 from Desktop to avoid mis-uploading it to Build Your Own area. Open "Terminal" on your Mac, and run the following commands:

cd
cd Desktop
rm pushcert.p12

Step 11 - NEW AWS UPDATE: Create new pushcert.p12 to submit to AWS SNS. Double click on the new pushcert.pem, then export the one highlighed on the green only.

enter image description here Credit: AWS new update

Now you have successfully created an Apple Push Notification Certificate (.p12 file)! You will need to upload this file to our Build Your Own area later on. :)

I'm getting an error "invalid use of incomplete type 'class map'

I am just providing another case where you can get this error message. The solution will be the same as Adam has mentioned above. This is from a real code and I renamed the class name.

class FooReader {
  public:
     /** Constructor */
     FooReader() : d(new FooReaderPrivate(this)) { }  // will not compile here
     .......
  private:
     FooReaderPrivate* d;
};

====== In a separate file =====
class FooReaderPrivate {
  public:
     FooReaderPrivate(FooReader*) : parent(p) { }
  private:
     FooReader* parent;
};

The above will no pass the compiler and get error: invalid use of incomplete type FooReaderPrivate. You basically have to put the inline portion into the *.cpp implementation file. This is OK. What I am trying to say here is that you may have a design issue. Cross reference of two classes may be necessary some cases, but I would say it is better to avoid them at the start of the design. I would be wrong, but please comment then I will update my posting.

Wait for all promises to resolve

You can use "await" in an "async function".

app.controller('MainCtrl', async function($scope, $q, $timeout) {
  ...
  var all = await $q.all([one.promise, two.promise, three.promise]); 
  ...
}

NOTE: I'm not 100% sure you can call an async function from a non-async function and have the right results.

That said this wouldn't ever be used on a website. But for load-testing/integration test...maybe.

Example code:

_x000D_
_x000D_
async function waitForIt(printMe) {_x000D_
  console.log(printMe);_x000D_
  console.log("..."+await req());_x000D_
  console.log("Legendary!")_x000D_
}_x000D_
_x000D_
function req() {_x000D_
  _x000D_
  var promise = new Promise(resolve => {_x000D_
    setTimeout(() => {_x000D_
      resolve("DARY!");_x000D_
    }, 2000);_x000D_
    _x000D_
  });_x000D_
_x000D_
    return promise;_x000D_
}_x000D_
_x000D_
waitForIt("Legen-Wait For It");
_x000D_
_x000D_
_x000D_

How to Edit a row in the datatable

Try the SetField method:

By passing column object :

table.Rows[rowIndex].SetField(column, value);

By Passing column index :

table.Rows[rowIndex].SetField(0 /*column index*/, value);

By Passing column name as string :

table.Rows[rowIndex].SetField("product_name" /*columnName*/, value);

Anaconda Navigator won't launch (windows 10)

I was working on my Windows 10 machine and I'm not sure which package "broke" Spyder and Anaconda Navigator, but could have been either, or, or both Kivy-1.10.1 and moviepy-0.2.3.5 which gave me problems. I installed with either pip or conda. So of course I looked on this site to see what to do to fix. I found how pyqt was probably the issue. I uninstalled pyqt, kivy, and moviepy by using "pip uninstall ". I found where/or how they were installed by "pip list" and "conda list". After they were uninstalled I used "conda install - c anaconda pyqt" to reinstall pyqt. After installing pyqt I launched Spyder with no problems.

Is there a mechanism to loop x times in ES6 (ECMAScript 6) without mutable variables?

I think it is pretty simple:

[...Array(3).keys()]

or

Array(3).fill()

React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function

        import React, { useState } from "react"

    const inputTextValue = ({ initialValue }) => {
        const [value, setValue] = useState(initialValue);
        return {
            value,
            onChange: (e) => { setValue(e.target.value) }
        };
    };

    export default () => {
        const textValue = inputTextValue("");
        return (<>
            <input {...textValue} />
        </>
        );
    }

/*"Solution I Tired Changed Name of Funtion in Captial "*/

    import React, { useState } from "react"

const InputTextValue = ({ initialValue }) => {
    const [value, setValue] = useState(initialValue);
    return {
        value,
        onChange: (e) => { setValue(e.target.value) }
    };
};

export default () => {
    const textValue = InputTextValue("");
    return (<>
        <input {...textValue} />
    </>
    );
}

Spark Kill Running Application

  • copy past the application Id from the spark scheduler, for instance application_1428487296152_25597
  • connect to the server that have launch the job
  • yarn application -kill application_1428487296152_25597

Open a Web Page in a Windows Batch FIle

hh.exe (help pages renderer) is capable of opening some simple webpages:

hh http://www.nissan.com

This will work even if browsing is blocked through:

HKEY_CURRENT_USER\Software\Policies\Microsoft\Internet Explorer

Static vs class functions/variables in Swift classes?

I got this confusion in one of my project as well and found this post, very helpful. Tried the same in my playground and here is the summary. Hope this helps someone with stored properties and functions of type static, final,class, overriding class vars etc.

class Simple {

    init() {print("init method called in base")}

    class func one() {print("class - one()")}

    class func two() {print("class - two()")}

    static func staticOne() {print("staticOne()")}

    static func staticTwo() {print("staticTwo()")}

    final func yesFinal() {print("yesFinal()")}

    static var myStaticVar = "static var in base"

    //Class stored properties not yet supported in classes; did you mean 'static'?
    class var myClassVar1 = "class var1"

    //This works fine
    class var myClassVar: String {
       return "class var in base"
    }
}

class SubSimple: Simple {
    //Successful override
    override class func one() {
        print("subClass - one()")
    }
    //Successful override
    override class func two () {
        print("subClass - two()")
    }

    //Error: Class method overrides a 'final' class method
    override static func staticOne() {

    }

    //error: Instance method overrides a 'final' instance method
    override final func yesFinal() {

    }

    //Works fine
    override class var myClassVar: String {
        return "class var in subclass"
    }
}

And here is the testing samples:

print(Simple.one())
print(Simple.two())
print(Simple.staticOne())
print(Simple.staticTwo())
print(Simple.yesFinal(Simple()))
print(SubSimple.one())
print(Simple.myStaticVar)
print(Simple.myClassVar)
print(SubSimple.myClassVar)

//Output
class - one()
class - two()
staticOne()
staticTwo()
init method called in base
(Function)
subClass - one()
static var in base
class var in base
class var in subclass

How to import existing *.sql files in PostgreSQL 8.4?

Always preferred using a connection service file (lookup/google 'psql connection service file')

Then simply:

psql service={yourservicename} < {myfile.sql}

Where yourservicename is a section name from the service file.

android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database

Another thing to note is Environment.getExternalStorageDirectory() has been deprecated in API 29, so change this if you're using this to get the database path:

https://developer.android.com/reference/android/os/Environment#getExternalStorageDirectory()

This method was deprecated in API level 29.

To improve user privacy, direct access to shared/external storage devices is deprecated. When an app targets Build.VERSION_CODES.Q, the path returned from this method is no longer directly accessible to apps. Apps can continue to access content stored on shared/external storage by migrating to alternatives such as Context#getExternalFilesDir(String), MediaStore, or Intent#ACTION_OPEN_DOCUMENT.

ERROR 1064 (42000) in MySQL

Finally got a solution.

First .sql file converts into the UTF8.

Then use this command

mysql -p -u root --default_character_set utf8 test </var/201535.sql

---root is the username

---test is the database name

or

mysql -p -u root test < /var/201535.sql 

---root is the username

---test is the database name

Purpose of installing Twitter Bootstrap through npm?

If you NPM those modules you can serve them using static redirect.

First install the packages:

npm install jquery
npm install bootstrap

Then on the server.js:

var express = require('express');
var app = express();

// prepare server
app.use('/api', api); // redirect API calls
app.use('/', express.static(__dirname + '/www')); // redirect root
app.use('/js', express.static(__dirname + '/node_modules/bootstrap/dist/js')); // redirect bootstrap JS
app.use('/js', express.static(__dirname + '/node_modules/jquery/dist')); // redirect JS jQuery
app.use('/css', express.static(__dirname + '/node_modules/bootstrap/dist/css')); // redirect CSS bootstrap

Then, finally, at the .html:

<link rel="stylesheet" href="/css/bootstrap.min.css">
<script src="/js/jquery.min.js"></script>
<script src="/js/bootstrap.min.js"></script>

I would not serve pages directly from the folder where your server.js file is (which is usually the same as node_modules) as proposed by timetowonder, that way people can access your server.js file.

Of course you can simply download and copy & paste on your folder, but with NPM you can simply update when needed... easier, I think.

How can I hide/show a div when a button is clicked?

Use JQuery. You need to set-up a click event on your button which will toggle the visibility of your wizard div.

$('#btn').click(function() {
    $('#wizard').toggle();
});

Refer to the JQuery website for more information.

This can also be done without JQuery. Using only standard JavaScript:

<script type="text/javascript">
   function toggle_visibility(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = 'block';
   }
</script>

Then add onclick="toggle_visibility('id_of_element_to_toggle');" to the button that is used to show and hide the div.

Get type name without full namespace

best way to use:

typeof(T).Name

How to negate the whole regex?

Apply this if you use laravel.

Laravel has a not_regex where field under validation must not match the given regular expression; uses the PHP preg_match function internally.

'email' => 'not_regex:/^.+$/i'

java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory

I copied the contents of the "C:\Program Files\Apache Software Foundation\Tomcat 6.0\conf" directory to the "workspace\Servers\Tomcat v6.0 Server at localhost-config" directory for Eclipse. I refreshed the "Servers\Tomcat v6.0 Server at localhost-config" folder in the Eclipse Project Explorer and then everything was good.

Swift - Integer conversion to Hours/Minutes/Seconds

Swift 5:

extension Int {

    func secondsToTime() -> String {

        let (h,m,s) = (self / 3600, (self % 3600) / 60, (self % 3600) % 60)

        let h_string = h < 10 ? "0\(h)" : "\(h)"
        let m_string =  m < 10 ? "0\(m)" : "\(m)"
        let s_string =  s < 10 ? "0\(s)" : "\(s)"

        return "\(h_string):\(m_string):\(s_string)"
    }
}

Usage:

let seconds : Int = 119
print(seconds.secondsToTime()) // Result = "00:01:59"

Binary search (bisection) in Python

This is right from the manual:

http://docs.python.org/2/library/bisect.html

8.5.1. Searching Sorted Lists

The above bisect() functions are useful for finding insertion points but can be tricky or awkward to use for common searching tasks. The following five functions show how to transform them into the standard lookups for sorted lists:

def index(a, x):
    'Locate the leftmost value exactly equal to x'
    i = bisect_left(a, x)
    if i != len(a) and a[i] == x:
        return i
    raise ValueError

So with the slight modification your code should be:

def index(a, x):
    'Locate the leftmost value exactly equal to x'
    i = bisect_left(a, x)
    if i != len(a) and a[i] == x:
        return i
    return -1

Git blame -- prior commits?

Build on stangls's answer, I put this script in my PATH (even on Windows) as git-bh:

That allows me to look for all commits where a word was involved:

git bh path/to/myfile myWord

Script:

#!/bin/bash
f=$1
shift
csha=""
{ git log --pretty=format:%H -- "$f"; echo; } | {
  while read hash; do
    res=$(git blame -L"/$1/",+1 $hash -- "$f" 2>/dev/null | sed 's/^/  /')
    sha=${res%% (*}
    if [[ "${res}" != "" && "${csha}" != "${sha}" ]]; then
      echo "--- ${hash}"
      echo "${res}"
      csha="${sha}"
    fi
  done
}

How to backup MySQL database in PHP?

using PHP function:

EXPORT_DATABASE("localhost", "user", "pass", "db_name" );

updated function code at github.

Excel plot time series frequency with continuous xaxis

You can get good Time Series graphs in Excel, the way you want, but you have to work with a few quirks.

  1. Be sure to select "Scatter Graph" (with a line option). This is needed if you have non-uniform time stamps, and will scale the X-axis accordingly.

  2. In your data, you need to add a column with the mid-point. Here's what I did with your sample data. (This trick ensures that the data gets plotted at the mid-point, like you desire.) enter image description here

  3. You can format the x-axis options with this menu. (Chart->Design->Layout) enter image description here

  4. Select "Axes" and go to Primary Horizontal Axis, and then select "More Primary Horizontal Axis Options"

  5. Set up the options you wish. (Fix the starting and ending points.) enter image description here

  6. And you will get a graph such as the one below. enter image description here

You can then tweak many of the options, label the axes better etc, but this should get you started.

Hope this helps you move forward.

JPA CascadeType.ALL does not delete orphans

Just @OneToMany(cascade = CascadeType.ALL, mappedBy = "xxx", fetch = FetchType.LAZY, orphanRemoval = true).

Remove targetEntity = MyClass.class, it works great.

Converting String Array to an Integer Array

Stream.of().mapToInt().toArray() seems to be the best options.

int[] arr = Stream.of(new String[]{"1", "2", "3"})
                  .mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(arr));

git push vs git push origin <branchname>

The first push should be a:

git push -u origin branchname

That would make sure:

Any future git push will, with that default policy, only push the current branch, and only if that branch has an upstream branch with the same name.
that avoid pushing all matching branches (previous default policy), where tons of test branches were pushed even though they aren't ready to be visible on the upstream repo.

bash shell nested for loop

One one line (semi-colons necessary):

for i in 0 1 2 3 4 5 6 7 8 9; do for j in 0 1 2 3 4 5 6 7 8 9; do echo "$i$j"; done; done

Formatted for legibility (no semi-colons needed):

for i in 0 1 2 3 4 5 6 7 8 9
do
    for j in 0 1 2 3 4 5 6 7 8 9
    do 
        echo "$i$j"
    done
done

There are different views on how the shell code should be laid out over multiple lines; that's about what I normally use, unless I put the next operation on the same line as the do (saving two lines here).

Arrays in type script

You can also do this as well (shorter cut) instead of having to do instance declaration. You do this in JSON instead.

class Book {
    public BookId: number;
    public Title: string;
    public Author: string;
    public Price: number;
    public Description: string;
}

var bks: Book[] = [];

 bks.push({BookId: 1, Title:"foo", Author:"foo", Price: 5, Description: "foo"});   //This is all done in JSON.

Received an invalid column length from the bcp client for colid 6

I got this error message with a much more recent ssis version (vs 2015 enterprise, i think it's ssis 2016). I will comment here because this is the first reference that comes up when you google this error message. I think it happens mostly with character columns when the source character size is larger than the target character size. I got this message when I was using an ado.net input to ms sql from a teradata database. Funny because the prior oledb writes to ms sql handled all the character conversion perfectly with no coding overrides. The colid number and the a corresponding Destination Input column # you sometimes get with the colid message are worthless. It's not the column when you count down from the top of the mapping or anything like that. If I were microsoft, I'd be embarrased to give an error message that looks like it's pointing at the problem column when it isn't. I found the problem colid by making an educated guess and then changing the input to the mapping to "Ignore" and then rerun and see if the message went away. In my case and in my environment I fixed it by substr( 'ing the Teradata input to the character size of the ms sql declaration for the output column. Check and make sure your input substr propagates through all you data conversions and mappings. In my case it didn't and I had to delete all my Data Conversion's and Mappings and start over again. Again funny that OLEDB just handled it and ADO.net threw the error and had to have all this intervention to make it work. In general you should use OLEDB when your target is MS Sql.

how to sort pandas dataframe from one column

Just adding some more operations on data. Suppose we have a dataframe df, we can do several operations to get desired outputs

ID         cost      tax    label
1       216590      1600    test      
2       523213      1800    test 
3          250      1500    experiment

(df['label'].value_counts().to_frame().reset_index()).sort_values('label', ascending=False)

will give sorted output of labels as a dataframe

    index   label
0   test        2
1   experiment  1

How to configure Spring Security to allow Swagger URL to be accessed without authentication

Considering all of your API requests located with a url pattern of /api/.. you can tell spring to secure only this url pattern by using below configuration. Which means that you are telling spring what to secure instead of what to ignore.

@Override
protected void configure(HttpSecurity http) throws Exception {
  http
    .csrf().disable()
     .authorizeRequests()
      .antMatchers("/api/**").authenticated()
      .anyRequest().permitAll()
      .and()
    .httpBasic().and()
    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

Document Root PHP

Yes, on the server side $_SERVER['DOCUMENT_ROOT'] is equivalent to / on the client side.

For example: the value of "{$_SERVER['DOCUMENT_ROOT']}/images/thumbnail.png" will be the string /var/www/html/images/thumbnail.png on a server where it's local file at that path can be reached from the client side at the url http://example.com/images/thumbnail.png

No, in other words the value of $_SERVER['DOCUMENT_ROOT'] is not / rather it is the server's local path to what the server shows the client at example.com/

note: $_SERVER['DOCUMENT_ROOT'] does not include a trailing /

Python in Xcode 4+?

Another way, which I've been using for awhile in XCode3:

See steps 1-15 above.

  1. Choose /bin/bash as your executable
  2. For the "Debugger" field, select "None".
  3. In the "Arguments" tab, click the "Base Expansions On" field and select the target you created earlier.
  4. Click the "+" icon under "Arguments Passed On Launch". You may have to expand that section by clicking on the triangle pointing to the right.
  5. Type in "-l". This will tell bash to use your login environment (PYTHONPATH, etc..)
  6. Do step #19 again.
  7. Type in "-c '$(SOURCE_ROOT)/.py'"
  8. Click "OK".
  9. Start coding.

The nice thing about this way is it will use the same environment to develop in that you would use to run in outside of XCode (as setup from your bash .profile).

It's also generic enough to let you develop/run any type of file, not just python.

Switch: Multiple values in one case?

There's no way to evaluate multiple values in one 'case'. You could either use an if statement (as others have suggested) or call a method which evaluates the range that the integer belongs to and returns a value which represents that range (such as "minor", "adult", etc.), then evaluate this returned value in the switch statement. Of course, you'd probably still be using an if statement in the custom method.

How to launch PowerShell (not a script) from the command line

The color and window sizing are defined by the shortcut LNK file. I think I found a way that will do what you need, try this:

explorer.exe "Windows PowerShell.lnk"

The LNK file is in the all user start menu which is located in different places depending whether your on XP or Windows 7. In 7 the LNK file is here:

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories\Windows PowerShell

JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors

I think you've missed the point of access control.

A quick recap on why CORS exists: Since JS code from a website can execute XHR, that site could potentially send requests to other sites, masquerading as you and exploiting the trust those sites have in you(e.g. if you have logged in, a malicious site could attempt to extract information or execute actions you never wanted) - this is called a CSRF attack. To prevent that, web browsers have very stringent limitations on what XHR you can send - you are generally limited to just your domain, and so on.

Now, sometimes it's useful for a site to allow other sites to contact it - sites that provide APIs or services, like the one you're trying to access, would be prime candidates. CORS was developed to allow site A(e.g. paste.ee) to say "I trust site B, so you can send XHR from it to me". This is specified by site A sending "Access-Control-Allow-Origin" headers in its responses.

In your specific case, it seems that paste.ee doesn't bother to use CORS. Your best bet is to contact the site owner and find out why, if you want to use paste.ee with a browser script. Alternatively, you could try using an extension(those should have higher XHR privileges).

Why can't overriding methods throw exceptions broader than the overridden method?

In my opinion, it is a fail in the Java syntax design. Polymorphism shouldn't limit the usage of exception handling. In fact, other computer languages don't do it (C#).

Moreover, a method is overriden in a more specialiced subclass so that it is more complex and, for this reason, more probable to throwing new exceptions.

Iterate through DataSet

foreach (DataTable table in dataSet.Tables)
{
    foreach (DataRow row in table.Rows)
    {
        foreach (object item in row.ItemArray)
        {
            // read item
        }
    }
}

Or, if you need the column info:

foreach (DataTable table in dataSet.Tables)
{
    foreach (DataRow row in table.Rows)
    {
        foreach (DataColumn column in table.Columns)
        {
            object item = row[column];
            // read column and item
        }
    }
}

python xlrd unsupported format, or corrupt file.

Try to open it with pandas:

import pandas as pd
data = pd.read_html('filename.xls')

Or try any other html python parser.

That's not a proper excel file, but an html readable with excel.

Determine if an element has a CSS class with jQuery

Use the hasClass method:

jQueryCollection.hasClass(className);

or

$(selector).hasClass(className);

The argument is (obviously) a string representing the class you are checking, and it returns a boolean (so it doesn't support chaining like most jQuery methods).

Note: If you pass a className argument that contains whitespace, it will be matched literally against the collection's elements' className string. So if, for instance, you have an element,

<span class="foo bar" />

then this will return true:

$('span').hasClass('foo bar')

and these will return false:

$('span').hasClass('bar foo')
$('span').hasClass('foo  bar')

Can't accept license agreement Android SDK Platform 24

The simplest way to solve this issue is to accept the licenses using the following command:

Windows OS:

C:\Users\{your-username}\AppData\Local\Android\sdk\tools\bin\sdkmanager --licenses

You will be presented with disclaimers. In order to continue your development efforts, you need to answer 'y' to all disclaimers.

javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake during web service communicaiton

With base at TLSv1.2 ALERT: fatal, handshake_failure I obtained after debug with this thread previos answer

-Djavax.net.debug=all

I went to https://www.ssllabs.com/and observed that the web server required a SSLv3 connection deprecate at june 2015, and deprecated at JDKu31 Release notes

ssllabs results

I edited the ${java_home}/jre/lib/security/java.security at the line

jdk.tls.disabledAlgorithms=SSLv3, RC4, DES, MD5withRSA, DH keySize < 1024,
EC keySize < 224, 3DES_EDE_CBC, anon, NULL

to

jdk.tls.disabledAlgorithms= RC4, DES, MD5withRSA, DH keySize < 1024,
EC keySize < 224, 3DES_EDE_CBC, anon, NULL

As a final step I got this error

sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target [javax.net.ssl.SSLHandshakeException]

I fixed this intalling the cert with the java keytool, following this answer PKIX path building failed” and “unable to find valid certification path to requested target”

What is the exact meaning of Git Bash?

At its core, Git is a set of command line utility programs that are designed to execute on a Unix style command-line environment. Modern operating systems like Linux and macOS both include built-in Unix command line terminals. This makes Linux and macOS complementary operating systems when working with Git. Microsoft Windows instead uses Windows command prompt, a non-Unix terminal environment.

What is Git Bash?

Git Bash is an application for Microsoft Windows environments which provides an emulation layer for a Git command line experience. Bash is an acronym for Bourne Again Shell. A shell is a terminal application used to interface with an operating system through written commands. Bash is a popular default shell on Linux and macOS. Git Bash is a package that installs Bash, some common bash utilities, and Git on a Windows operating system.

source : https://www.atlassian.com/git/tutorials/git-bash

How to compare two colors for similarity/difference

See Wikipedia's article on Color Difference for the right leads. Basically, you want to compute a distance metric in some multidimensional colorspace.

But RGB is not "perceptually uniform", so your Euclidean RGB distance metric suggested by Vadim will not match the human-perceived distance between colors. For a start, L*a*b* is intended to be a perceptually uniform colorspace, and the deltaE metric is commonly used. But there are more refined colorspaces and more refined deltaE formulas that get closer to matching human perception.

You'll have to learn more about colorspaces and illuminants to do the conversions. But for a quick formula that is better than the Euclidean RGB metric, just do this:

  • Assume that your RGB values are in the sRGB colorspace
  • Find the sRGB to L*a*b* conversion formulas
  • Convert your sRGB colors to L*a*b*
  • Compute deltaE between your two L*a*b* values

It's not computationally expensive, it's just some nonlinear formulas and some multiplications and additions.

html tables & inline styles

Forget float, margin and html 3/5. The mail is very obsolete. You need do all with table. One line = one table. You need margin or padding ? Do another column.

Codepen

Example : i need one line with 1 One Picture of 40*40 2 One margin of 10 px 3 One text of 400px

I start my line :

<table style=" background-repeat:no-repeat; width:450px;margin:0;" cellpadding="0" cellspacing="0" border="0">
   <tr style="height:40px; width:450px; margin:0;">
     <td style="height:40px; width:40px; margin:0;">
        <img src="" style="width=40px;height40;margin:0;display:block"
     </td>
     <td style="height:40px; width:10px; margin:0;">        
     </td>
     <td style="height:40px; width:400px; margin:0;">
     <p style=" margin:0;"> my text   </p>
     </td>
   </tr>
</table>

Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2

For Windows, you can check the official Intel MKL optimization for TensorFlow wheels that are compiled with AVX2. This solution speeds up my inference ~x3.

conda install tensorflow-mkl

Fastest way to convert an iterator to a list

since python 3.5 you can use * iterable unpacking operator:

user_list = [*your_iterator]

but the pythonic way to do it is:

user_list  = list(your_iterator)

React-Router open Link in new tab

target="_blank" is enough to open in a new tab, when you are using react-router

eg: <Link to={/admin/posts/error-post-list/${this.props.errorDate}} target="_blank"> View Details </Link>

When do I use the PHP constant "PHP_EOL"?

On some system may be useful to use this constant because if, for example, you are sending an email, you can use PHP_EOL to have a cross-system script working on more systems... but even if it's useful sometime you can find this constant undefined, modern hosting with latest php engine do not have this problem but I think that a good thing is write a bit code that saves this situation:

<?php
  if (!defined('PHP_EOL')) {
    if (strtoupper(substr(PHP_OS,0,3) == 'WIN')) {
      define('PHP_EOL',"\r\n");
    } elseif (strtoupper(substr(PHP_OS,0,3) == 'MAC')) {
      define('PHP_EOL',"\r");
    } elseif (strtoupper(substr(PHP_OS,0,3) == 'DAR')) {
      define('PHP_EOL',"\n");
    } else {
      define('PHP_EOL',"\n");
    }
  }
?>

So you can use PHP_EOL without problems... obvious that PHP_EOL should be used on script that should work on more systems at once otherwise you can use \n or \r or \r\n...

Note: PHP_EOL can be

1) on Unix    LN    == \n
2) on Mac     CR    == \r
3) on Windows CR+LN == \r\n

Hope this answer help.

Getting first value from map in C++

You can use the iterator that is returned by the begin() method of the map template:

std::map<K,V> myMap;
std::pair<K,V> firstEntry = *myMap.begin()

But remember that the std::map container stores its content in an ordered way. So the first entry is not always the first entry that has been added.

Tab key == 4 spaces and auto-indent after curly braces in Vim

The auto-indent is based on the current syntax mode. I know that if you are editing Foo.java, then entering a { and hitting Enter indents the following line.

As for tabs, there are two settings. Within Vim, type a colon and then "set tabstop=4" which will set the tabs to display as four spaces. Hit colon again and type "set expandtab" which will insert spaces for tabs.

You can put these settings in a .vimrc (or _vimrc on Windows) in your home directory, so you only have to type them once.

What is the meaning of <> in mysql query?

<> means not equal to, != also means not equal to.

Documentation

Sum across multiple columns with dplyr

Using reduce() from purrr is slightly faster than rowSums and definately faster than apply, since you avoid iterating over all the rows and just take advantage of the vectorized operations:

library(purrr)
library(dplyr)
iris %>% mutate(Petal = reduce(select(., starts_with("Petal")), `+`))

See this for timings

jQuery click function doesn't work after ajax call?

When you use $('.deletelanguage').click() to register an event handler it adds the handler to only those elements which exists in the dom when the code was executed

you need to use delegation based event handlers here

$(document).on('click', '.deletelanguage', function(){
    alert("success");
});

Read lines from a file into a Bash array

The readarray command (also spelled mapfile) was introduced in bash 4.0.

readarray -t a < /path/to/filename

What is the equivalent of Java static methods in Kotlin?

The exact conversion of the java static method to kotlin equivalent would be like this. e.g. Here the util class has one static method which would be equivalent in both java and kotlin. The use of @JvmStatic is important.

Java code:

    class Util{
         public static String capitalize(String text){
         return text.toUpperCase();}
       }

Kotlin code:

    class Util {
        companion object {
            @JvmStatic
            fun capitalize(text:String): String {
                return text.toUpperCase()
            }
        }
    }

Filling a List with all enum values in Java

try

enum E {
    E1, E2, E3
}

public static void main(String[] args) throws Exception {
    List<E> list = Arrays.asList(E.values());
    System.out.println(list);
}

Convert int to ASCII and back in Python

What about BASE58 encoding the URL? Like for example flickr does.

# note the missing lowercase L and the zero etc.
BASE58 = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ' 
url = ''
while node_id >= 58:
    div, mod = divmod(node_id, 58)
    url = BASE58[mod] + url
    node_id = int(div)

return 'http://short.com/%s' % BASE58[node_id] + url

Turning that back into a number isn't a big deal either.

Add a space (" ") after an element using :after

There can be a problem with "\00a0" in pseudo-elements because it takes the text-decoration of its defining element, so that, for example, if the defining element is underlined, then the white space of the pseudo-element is also underlined.

The easiest way to deal with this is to define the opacity of the pseudo-element to be zero, eg:

element:before{
  content: "_";
  opacity: 0;
}

How to set a Postgresql default value datestamp like 'YYYYMM'?

It's a common misconception that you can denormalise like this for performance. Use date_trunc('month', date) for your queries and add an index expression for this if you find it running slow.

Is it possible to decompile a compiled .pyc file into a .py file?

You may try Easy Python Decompiler. It's based on Decompyle++ and Uncompyle2. It's supports decompiling python versions 1.0-3.3

Note: I am the author of the above tool.

How to Determine the Screen Height and Width in Flutter

Using the following method we can get the device's physical height. Ex. 1080X1920

WidgetsBinding.instance.window.physicalSize.height
WidgetsBinding.instance.window.physicalSize.width

How to show data in a table by using psql command line interface?

On windows use the name of the table in quotes: TABLE "user"; or SELECT * FROM "user";

Mysql database sync between two databases

Have a look at Schema and Data Comparison tools in dbForge Studio for MySQL. These tool will help you to compare, to see the differences, generate a synchronization script and synchronize two databases.

mongodb group values by multiple fields

Using aggregate function like below :

[
{$group: {_id : {book : '$book',address:'$addr'}, total:{$sum :1}}},
{$project : {book : '$_id.book', address : '$_id.address', total : '$total', _id : 0}}
]

it will give you result like following :

        {
            "total" : 1,
            "book" : "book33",
            "address" : "address90"
        }, 
        {
            "total" : 1,
            "book" : "book5",
            "address" : "address1"
        }, 
        {
            "total" : 1,
            "book" : "book99",
            "address" : "address9"
        }, 
        {
            "total" : 1,
            "book" : "book1",
            "address" : "address5"
        }, 
        {
            "total" : 1,
            "book" : "book5",
            "address" : "address2"
        }, 
        {
            "total" : 1,
            "book" : "book3",
            "address" : "address4"
        }, 
        {
            "total" : 1,
            "book" : "book11",
            "address" : "address77"
        }, 
        {
            "total" : 1,
            "book" : "book9",
            "address" : "address3"
        }, 
        {
            "total" : 1,
            "book" : "book1",
            "address" : "address15"
        }, 
        {
            "total" : 2,
            "book" : "book1",
            "address" : "address2"
        }, 
        {
            "total" : 3,
            "book" : "book1",
            "address" : "address1"
        }

I didn't quite get your expected result format, so feel free to modify this to one you need.

Android: how to parse URL String with spaces to URI object?

To handle spaces, @, and other unsafe characters in arbitrary locations in the url path, Use Uri.Builder in combination with a local instance of URL as I have described here:

private Uri.Builder builder;
public Uri getUriFromUrl(String thisUrl) {
    URL url = new URL(thisUrl);
    builder =  new Uri.Builder()
                            .scheme(url.getProtocol())
                            .authority(url.getAuthority())
                            .appendPath(url.getPath());
    return builder.build();
}

How to determine previous page URL in Angular?

You can use Location as mentioned here.

Here's my code if the link opened on new tab

navBack() {
    let cur_path = this.location.path();
    this.location.back();
    if (cur_path === this.location.path())
     this.router.navigate(['/default-route']);    
  }

Required imports

import { Router } from '@angular/router';
import { Location } from '@angular/common';

filtering a list using LINQ

var filtered = projects;
foreach (var tag in filteredTags) {
  filtered = filtered.Where(p => p.Tags.Contains(tag))
}

The nice thing with this approach is that you can refine search results incrementally.

cannot redeclare block scoped variable (typescript)

In my case (using IntelliJ) File - Invalidate Caches / Restart... did the trick.

The property 'Id' is part of the object's key information and cannot be modified

Just hoping this helps someone else, after struggling for hours with this because i knew i wasnt updating the PK and i definitely had a PK. I had the PK value databound to a menu bar to show the current PK value and this was causing the issue.

Naming conventions for Java methods that return boolean

I want to point a different view on this general naming convention, e.g.:

see java.util.Set: boolean add?(E e)

where the rationale is:

do some processing then report whether it succeeded or not.

While the return is indeed a boolean the method's name should point the processing to complete instead of the result type (boolean for this example).

Your createFreshSnapshot example seems for me more related to this point of view because seems to mean this: create a fresh-snapshot then report whether the create-operation succeeded. Considering this reasoning the name createFreshSnapshot seems to be the best one for your situation.

What is the purpose of global.asax in asp.net

MSDN has an outline of the purpose of the global.asax file.

Effectively, global.asax allows you to write code that runs in response to "system level" events, such as the application starting, a session ending, an application error occuring, without having to try and shoe-horn that code into each and every page of your site.

You can use it by by choosing Add > New Item > Global Application Class in Visual Studio. Once you've added the file, you can add code under any of the events that are listed (and created by default, at least in Visual Studio 2008):

  • Application_Start
  • Application_End
  • Session_Start
  • Session_End
  • Application_BeginRequest
  • Application_AuthenticateRequest
  • Application_Error

There are other events that you can also hook into, such as "LogRequest".

TypeError: 'in <string>' requires string as left operand, not int

You simply need to make cab a string:

cab = '6176'

As the error message states, you cannot do <int> in <string>:

>>> 1 in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not int
>>> 

because integers and strings are two totally different things and Python does not embrace implicit type conversion ("Explicit is better than implicit.").

In fact, Python only allows you to use the in operator with a right operand of type string if the left operand is also of type string:

>>> '1' in '123'  # Works!
True
>>>
>>> [] in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not list
>>>
>>> 1.0 in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not float
>>>
>>> {} in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not dict
>>>

How to get $HOME directory of different user in bash script?

Quick and dirty, and store it in a variable:

USER=somebody
USER_HOME="$(echo -n $(bash -c "cd ~${USER} && pwd"))"

How to update data in one table from corresponding data in another table in SQL Server 2005

use test1

insert into employee(deptid) select deptid from test2.dbo.employee

Navigation drawer: How do I set the selected item at startup?

API 23 provides the following method:

navigationView.setCheckedItem(R.id.nav_item_id);

However, for some reason this function did not cause the code behind the navigation item to run. The method certainly highlights the item in the navigation drawer, or 'checks' it, but it does not seem to call the OnNavigationItemSelectedListener resulting in a blank screen on start-up if your start-up screen depends on navigation drawer selections. It is possible to manually call the listener, but it seems hacky:

if (savedInstanceState == null) this.onNavigationItemSelected(navigationView.getMenu().getItem(0));

The above code assumes:

  1. You have implemented NavigationView.OnNavigationItemSelectedListener in your activity
  2. You have already called:
    navigationView.setNavigationItemSelectedListener(this);
  3. The item you wish to select is located in position 0

Using StringWriter for XML Serialization

public static T DeserializeFromXml<T>(string xml)
{
    T result;
    XmlSerializerFactory serializerFactory = new XmlSerializerFactory();
    XmlSerializer serializer =serializerFactory.CreateSerializer(typeof(T));

    using (StringReader sr3 = new StringReader(xml))
    {
        XmlReaderSettings settings = new XmlReaderSettings()
        {
            CheckCharacters = false // default value is true;
        };

        using (XmlReader xr3 = XmlTextReader.Create(sr3, settings))
        {
            result = (T)serializer.Deserialize(xr3);
        }
    }

    return result;
}

Interface vs Base class

Prefer interfaces over abstract classes

Rationale, the main points to consider [two already mentioned here] are :

  • Interfaces are more flexible, because a class can implement multiple interfaces. Since Java does not have multiple inheritance, using abstract classes prevents your users from using any other class hierarchy. In general, prefer interfaces when there are no default implementations or state. Java collections offer good examples of this (Map, Set, etc.).
  • Abstract classes have the advantage of allowing better forward compatibility. Once clients use an interface, you cannot change it; if they use an abstract class, you can still add behavior without breaking existing code. If compatibility is a concern, consider using abstract classes.
  • Even if you do have default implementations or internal state, consider offering an interface and an abstract implementation of it. This will assist clients, but still allow them greater freedom if desired [1].
    Of course, the subject has been discussed at length elsewhere [2,3].

[1] It adds more code, of course, but if brevity is your primary concern, you probably should have avoided Java in the first place!

[2] Joshua Bloch, Effective Java, items 16-18.

[3] http://www.codeproject.com/KB/ar...

Changing CSS for last <li>

:last-child is really the only way to do it without modifying the HTML - but assuming you can do that, the main option is just to give it a class="last-item", then do:

li.last-item { /* ... */ }

Obviously, you can automate this in the dynamic page generation language of your choice. Also, there is a lastChild JavaScript property in the W3C DOM.

Here's an example of doing what you want in Prototype:

$$("ul").each(function(x) { $(x.lastChild).addClassName("last-item"); });

Or even more simply:

$$("ul li:last-child").each(function(x) { x.addClassName("last-item"); });

In jQuery, you can write it even more compactly:

$("ul li:last-child").addClass("last-item");

Also note that this should work without using the actual last-child CSS selector - rather, a JavaScript implementation of it is used - so it should be less buggy and more reliable across browsers.

Giving my function access to outside variable

By default, when you are inside a function, you do not have access to the outer variables.


If you want your function to have access to an outer variable, you have to declare it as global, inside the function :

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

For more informations, see Variable scope.

But note that using global variables is not a good practice : with this, your function is not independant anymore.


A better idea would be to make your function return the result :

function someFuntion(){
    $myArr = array();       // At first, you have an empty array
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;      // Put that $myVal into the array
    return $myArr;
}

And call the function like this :

$result = someFunction();


Your function could also take parameters, and even work on a parameter passed by reference :

function someFuntion(array & $myArr){
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;      // Put that $myVal into the array
}

Then, call the function like this :

$myArr = array( ... );
someFunction($myArr);  // The function will receive $myArr, and modify it

With this :

  • Your function received the external array as a parameter
  • And can modify it, as it's passed by reference.
  • And it's better practice than using a global variable : your function is a unit, independant of any external code.


For more informations about that, you should read the Functions section of the PHP manual, and,, especially, the following sub-sections :

Test if a string contains any of the strings from an array

If you are seraching for whole words you can do this that works case insensitive.

private boolean containsKeyword(String line, String[] keywords)
{
    String[] inputWords = line.split(" ");

    for (String inputWord : inputWords)
    {
        for (String keyword : keywords)
        {
            if (inputWord.equalsIgnoreCase(keyword))
            {
                return true;
            }
        }
    }

    return false;
}

Do you have to include <link rel="icon" href="favicon.ico" type="image/x-icon" />?

If you don't call the favicon, favicon.ico, you can use that tag to specify the actual path (incase you have it in an images/ directory). The browser/webpage looks for favicon.ico in the root directory by default.

How do I update all my CPAN modules to their latest versions?

Try perl -MCPAN -e "upgrade /(.\*)/". It works fine for me.

How to set a binding in Code?

Replace:

myBinding.Source = ViewModel.SomeString;

with:

myBinding.Source = ViewModel;

Example:

Binding myBinding = new Binding();
myBinding.Source = ViewModel;
myBinding.Path = new PropertyPath("SomeString");
myBinding.Mode = BindingMode.TwoWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
BindingOperations.SetBinding(txtText, TextBox.TextProperty, myBinding);

Your source should be just ViewModel, the .SomeString part is evaluated from the Path (the Path can be set by the constructor or by the Path property).

Split large string in n-size chunks in JavaScript

I would use a regex...

var chunkStr = function(str, chunkLength) {
    return str.match(new RegExp('[\\s\\S]{1,' + +chunkLength + '}', 'g'));
}

Prevent nginx 504 Gateway timeout using PHP set_time_limit()

You need to add extra nginx directive (for ngx_http_proxy_module) in nginx.conf, e.g.:

proxy_read_timeout 300;

Basically the nginx proxy_read_timeout directive changes the proxy timeout, the FcgidIOTimeout is for scripts that are quiet too long, and FcgidBusyTimeout is for scripts that take too long to execute.

Also if you're using FastCGI application, increase these options as well:

FcgidBusyTimeout 300
FcgidIOTimeout 250

Then reload nginx and PHP5-FPM.

Plesk

In Plesk, you can add it in Web Server Settings under Additional nginx directives.

For FastCGI check in Web Server Settings under Additional directives for HTTP.

See: How to fix FastCGI timeout issues in Plesk?

GetType used in PowerShell, difference between variables

Select-Object creates a new psobject and copies the properties you requested to it. You can verify this with GetType():

PS > $a.GetType().fullname
System.DayOfWeek

PS > $b.GetType().fullname
System.Management.Automation.PSCustomObject

Installing Google Protocol Buffers on mac

It's a new year and there's a new mismatch between the version of protobuf in Homebrew and the cutting edge release. As of February 2016, brew install protobuf will give you version 2.6.1.

If you want the 3.0 beta release instead, you can install it with:

brew install --devel protobuf

How to get primary key column in Oracle?

Try This Code Here I created a table for get primary key column in oracle which is called test and then query

create table test
(
id int,
name varchar2(20),
city varchar2(20),
phone int,
constraint pk_id_name_city primary key (id,name,city)
);

SELECT cols.table_name, cols.column_name, cols.position, cons.status, cons.owner FROM all_constraints cons, all_cons_columns cols WHERE cols.table_name = 'TEST' AND cons.constraint_type = 'P' AND cons.constraint_name = cols.constraint_name AND cons.owner = cols.owner  ORDER BY cols.table_name, cols.position;

How to change column datatype from character to numeric in PostgreSQL 8.4

You can try using USING:

The optional USING clause specifies how to compute the new column value from the old; if omitted, the default conversion is the same as an assignment cast from old data type to new. A USING clause must be provided if there is no implicit or assignment cast from old to new type.

So this might work (depending on your data):

alter table presales alter column code type numeric(10,0) using code::numeric;
-- Or if you prefer standard casting...
alter table presales alter column code type numeric(10,0) using cast(code as numeric);

This will fail if you have anything in code that cannot be cast to numeric; if the USING fails, you'll have to clean up the non-numeric data by hand before changing the column type.

How to get a particular date format ('dd-MMM-yyyy') in SELECT query SQL Server 2008 R2

It doesn't look like DD-MMM-YYYY is supported by default (at least, with dash as separator). However, using the AS clause, you should be able to do something like:

SELECT CONVERT(VARCHAR(11), SYSDATETIME(), 106) AS [DD-MON-YYYY]

See here: http://www.sql-server-helper.com/sql-server-2008/sql-server-2008-date-format.aspx

How to clear radio button in Javascript?

if the id of the radio buttons are 'male' and 'female', value reset can be done by using jquery

$('input[id=male]').attr('checked',false);
$('input[id=female]').attr('checked',false);

Download files from server php

If the folder is accessible from the browser (not outside the document root of your web server), then you just need to output links to the locations of those files. If they are outside the document root, you will need to have links, buttons, whatever, that point to a PHP script that handles getting the files from their location and streaming to the response.

Loop timer in JavaScript

You should try something like this:

 function update(){
    i++;
    document.getElementById('tekst').innerHTML = i;
    setInterval(update(),1000);
    }

This means that you have to create a function in which you do the stuff you need to do, and make sure it will call itself with an interval you like. In your body onload call the function for the first time like this:

<body onload="update()">

Converting Columns into rows with their respective data in sql server

DECLARE @TABLE TABLE 
  (RowNo INT,ScripName  VARCHAR(10),ScripCode  VARCHAR(10)
  ,Price  VARCHAR(10))      
INSERT INTO @TABLE VALUES
  (1,'20 MICRONS ','533022','39')
SELECT ColumnName,ColumnValue from @Table
 Unpivot(ColumnValue For ColumnName IN (ScripName,ScripCode,Price)) AS H

converting multiple columns from character to numeric format in r

You can use index of columns: data_set[,1:9] <- sapply(dataset[,1:9],as.character)

NLTK and Stopwords Fail #lookuperror

You don't seem to have the stopwords corpus on your computer.

You need to start the NLTK Downloader and download all the data you need.

Open a Python console and do the following:

>>> import nltk
>>> nltk.download()
showing info http://nltk.github.com/nltk_data/

In the GUI window that opens simply press the 'Download' button to download all corpora or go to the 'Corpora' tab and only download the ones you need/want.

MySQL DROP all tables, ignoring foreign keys

From this answer,

execute:

  use `dbName`; --your db name here
  SET FOREIGN_KEY_CHECKS = 0; 
  SET @tables = NULL;
  SET GROUP_CONCAT_MAX_LEN=32768;

  SELECT GROUP_CONCAT('`', table_schema, '`.`', table_name, '`') INTO @tables
  FROM   information_schema.tables 
  WHERE  table_schema = (SELECT DATABASE());
  SELECT IFNULL(@tables, '') INTO @tables;

  SET        @tables = CONCAT('DROP TABLE IF EXISTS ', @tables);
  PREPARE    stmt FROM @tables;
  EXECUTE    stmt;
  DEALLOCATE PREPARE stmt;
  SET        FOREIGN_KEY_CHECKS = 1;

This drops tables from the database currently in use. You can set current database using use.


Or otherwise, Dion's accepted answer is simpler, except you need to execute it twice, first to get the query, and second to execute the query. I provided some silly back-ticks to escape special characters in db and table names.

  SELECT CONCAT('DROP TABLE IF EXISTS `', table_schema, '`.`', table_name, '`;')
  FROM   information_schema.tables
  WHERE  table_schema = 'dbName'; --your db name here

linux find regex

Regular expressions with character classes (e.g. [[:digit:]]) are not supported in the default regular expression syntax used by find. You need to specify a different regex type such as posix-extended in order to use them.

Take a look at GNU Find's Regular Expression documentation which shows you all the regex types and what they support.

how to enable sqlite3 for php?

Only use:

sudo apt-get install php5-sqlite

and later

sudo service apache2 restart

Set value to currency in <input type="number" />

Add step="0.01" to the <input type="number" /> parameters:

<input type="number" min="0.01" step="0.01" max="2500" value="25.67" />

Demo: http://jsfiddle.net/uzbjve2u/

But the Dollar sign must stay outside the textbox... every non-numeric or separator charachter will be cropped automatically.

Otherwise you could use a classic textbox, like described here.

font size in html code

just write the css attributes in a proper manner i.e:

font-size:35px;

Converting an int to std::string

Non-standard function, but its implemented on most common compilers:

int input = MY_VALUE;
char buffer[100] = {0};
int number_base = 10;
std::string output = itoa(input, buffer, number_base);

Update

C++11 introduced several std::to_string overloads (note that it defaults to base-10).

Is SMTP based on TCP or UDP?

In theory SMTP can be handled by either TCP, UDP, or some 3rd party protocol.

As defined in RFC 821, RFC 2821, and RFC 5321:

SMTP is independent of the particular transmission subsystem and requires only a reliable ordered data stream channel.

In addition, the Internet Assigned Numbers Authority has allocated port 25 for both TCP and UDP for use by SMTP.

In practice however, most if not all organizations and applications only choose to implement the TCP protocol. For example, in Microsoft's port listing port 25 is only listed for TCP and not UDP.


The big difference between TCP and UDP that makes TCP ideal here is that TCP checks to make sure that every packet is received and re-sends them if they are not whereas UDP will simply send packets and not check for receipt. This makes UDP ideal for things like streaming video where every single packet isn't as important as keeping a continuous flow of packets from the server to the client.

Considering SMTP, it makes more sense to use TCP over UDP. SMTP is a mail transport protocol, and in mail every single packet is important. If you lose several packets in the middle of the message the recipient might not even receive the message and if they do they might be missing key information. This makes TCP more appropriate because it ensures that every packet is delivered.

Groovy / grails how to determine a data type?

To determine the class of an object simply call:

someObject.getClass()

You can abbreviate this to someObject.class in most cases. However, if you use this on a Map it will try to retrieve the value with key 'class'. Because of this, I always use getClass() even though it's a little longer.

If you want to check if an object implements a particular interface or extends a particular class (e.g. Date) use:

(somObject instanceof Date)

or to check if the class of an object is exactly a particular class (not a subclass of it), use:

(somObject.getClass() == Date)

Create iOS Home Screen Shortcuts on Chrome for iOS

Can't change the default browser, but try this (found online a while ago). Add a bookmark in Safari called "Open in Chrome" with the following.

javascript:location.href=%22googlechrome%22+location.href.substring(4);

Will open the current page in Chrome. Not as convenient, but maybe someone will find it useful.

Source

Works for me.

How to Allow Remote Access to PostgreSQL database

If using PostgreSql 9.5.1, please follow the below configuration:

  1. Open hg_hba.conf in pgAdmin pgAdmin
  2. Select your path, and open it, then add a setting pg_hba.conf
  3. Restart postgresql service

ASP.Net MVC: How to display a byte array image from model

If you want to present the image, add a method as a helper class or to the model itself and allow the method to convert the byte array image to a image format like PNG or JPG then convert to Base64 string. Once you have that, bind the base64 value on your view in the format

"data:image/[image file type extension];base64,[your base64 string goes here]"

The above is assigned to the img tag's src attribute.

The only issue I have with this is the base64 string being too long. So, I would not recommend it for multiple models being shown in a view.

Android: how to convert whole ImageView to Bitmap?

Just thinking out loud here (with admittedly little expertise working with graphics in Java) maybe something like this would work?:

ImageView iv = (ImageView)findViewById(R.id.imageview);
Bitmap bitmap = Bitmap.createBitmap(iv.getWidth(), iv.getHeight(), Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
iv.draw(canvas);

Out of curiosity, what are you trying to accomplish? There may be a better way to achieve your goal than what you have in mind.

Using '<%# Eval("item") %>'; Handling Null Value and showing 0 against

It should work as well

Eval("item") == null?"0": Eval("item");

How many spaces will Java String.trim() remove?

It will remove all spaces on both the sides.

Link to "pin it" on pinterest without generating a button

You can create a custom link as described here using a small jQuery script

$('.linkPinIt').click(function(){
    var url = $(this).attr('href');
    var media = $(this).attr('data-image');
    var desc = $(this).attr('data-desc');
    window.open("//www.pinterest.com/pin/create/button/"+
    "?url="+url+
    "&media="+media+
    "&description="+desc,"_blank","top=0,right=0,width=750,height=320");
    return false; 
});

this will work for all links with class linkPinItwhich have the image and the description stored in the HTML 5 data attributes data-image and data-desc

<a href="https%3A%2F%2Fwww.flickr.com%2Fphotos%2Fkentbrew%2F6851755809%2F" 
   data-image="https%3A%2F%2Fc4.staticflickr.com%2F8%2F7027%2F6851755809_df5b2051c9_b.jpg" 
   data-desc="Title for Pinterest Photo" class="linkPinIt">
    Pin it!
</a> 

see this jfiddle example

How do I PHP-unserialize a jQuery-serialized form?

// jQuery Post

var arraydata = $('.selector').serialize();

// jquery.post serialized var - TO - PHP Array format

parse_str($_POST[arraydata], $searcharray);
print_r($searcharray); // Only for print array

// You get any same of that

 Array (
 [A] => 1
 [B] => 2
 [C] => 3
 [D] => 4
 [E] => 5
 [F] => 6
 [G] => 7
 [H] => 8
 )

What static analysis tools are available for C#?

  • Gendarme is an open source rules based static analyzer (similar to FXCop, but finds a lot of different problems).
  • Clone Detective is a nice plug-in for Visual Studio that finds duplicate code.
  • Also speaking of Mono, I find the act of compiling with the Mono compiler (if your code is platform independent enough to do that, a goal you might want to strive for anyway) finds tons of unreferenced variables and other Warnings that Visual Studio completely misses (even with the warning level set to 4).

How do you share code between projects/solutions in Visual Studio?

There is a very good case for using "adding existing file links" when reusing code across projects, and that is when you need to reference and support different versions of dependent libraries.

Making multiple assemblies with references to different external assemblies isn't easy to do otherwise without duplicating your code, or utilizing tricks with source code control.

I believe that it's easiest to maintain one project for development and unit test, then to create 'build' projects using existing file links when you need to create the assemblies which reference different versions of those external assemblies.

Count all occurrences of a string in lots of files with grep

If you want number of occurrences per file (example for string "tcp"):

grep -RIci "tcp" . | awk -v FS=":" -v OFS="\t" '$2>0 { print $2, $1 }' | sort -hr

Example output:

53  ./HTTPClient/src/HTTPClient.cpp
21  ./WiFi/src/WiFiSTA.cpp
19  ./WiFi/src/ETH.cpp
13  ./WiFi/src/WiFiAP.cpp
4   ./WiFi/src/WiFiClient.cpp
4   ./HTTPClient/src/HTTPClient.h
3   ./WiFi/src/WiFiGeneric.cpp
2   ./WiFi/examples/WiFiClientBasic/WiFiClientBasic.ino
2   ./WiFiClientSecure/src/ssl_client.cpp
1   ./WiFi/src/WiFiServer.cpp

Explanation:

  • grep -RIci NEEDLE . - looks for string NEEDLE recursively from current directory (following symlinks), ignoring binaries, counting number of occurrences, ignoring case
  • awk ... - this command ignores files with zero occurrences and formats lines
  • sort -hr - sorts lines in reverse order by numbers in first column

Of course, it works with other grep commands with option -c (count) as well. For example:

grep -c "tcp" *.txt | awk -v FS=":" -v OFS="\t" '$2>0 { print $2, $1 }' | sort -hr