Programs & Examples On #Import libraries

Keyboard shortcuts are not active in Visual Studio with Resharper installed

Without resetting Visual Studio settings :

I found simply

  • ReSharper > Options > Keyboards
  • Apply Scheme button
  • Save button

Brought back my lost ReSharper keyboard commands without messing with my VS settings.

(Visual Studio Community 2017 + ReSharper Ultimate)

Tesseract running error

The simpliest way is to install the needed package:

sudo apt-get install tesseract-ocr-eng  #for english
sudo apt-get install tesseract-ocr-tam  #for tamil
sudo apt-get install tesseract-ocr-deu  #for deutsch (German)

As you can notice, it opens the road to others languages (i.e. tesseract-ocr-fra).

Swift alert view with OK and Cancel: which button tapped?

You can easily do this by using UIAlertController

let alertController = UIAlertController(
       title: "Your title", message: "Your message", preferredStyle: .alert)
let defaultAction = UIAlertAction(
       title: "Close Alert", style: .default, handler: nil)
//you can add custom actions as well 
alertController.addAction(defaultAction)

present(alertController, animated: true, completion: nil)

.

Reference: iOS Show Alert

Simple way to unzip a .zip file using zlib

Minizip does have an example programs to demonstrate its usage - the files are called minizip.c and miniunz.c.

Update: I had a few minutes so I whipped up this quick, bare bones example for you. It's very smelly C, and I wouldn't use it without major improvements. Hopefully it's enough to get you going for now.

// uzip.c - Simple example of using the minizip API.
// Do not use this code as is! It is educational only, and probably
// riddled with errors and leaks!
#include <stdio.h>
#include <string.h>

#include "unzip.h"

#define dir_delimter '/'
#define MAX_FILENAME 512
#define READ_SIZE 8192

int main( int argc, char **argv )
{
    if ( argc < 2 )
    {
        printf( "usage:\n%s {file to unzip}\n", argv[ 0 ] );
        return -1;
    }

    // Open the zip file
    unzFile *zipfile = unzOpen( argv[ 1 ] );
    if ( zipfile == NULL )
    {
        printf( "%s: not found\n" );
        return -1;
    }

    // Get info about the zip file
    unz_global_info global_info;
    if ( unzGetGlobalInfo( zipfile, &global_info ) != UNZ_OK )
    {
        printf( "could not read file global info\n" );
        unzClose( zipfile );
        return -1;
    }

    // Buffer to hold data read from the zip file.
    char read_buffer[ READ_SIZE ];

    // Loop to extract all files
    uLong i;
    for ( i = 0; i < global_info.number_entry; ++i )
    {
        // Get info about current file.
        unz_file_info file_info;
        char filename[ MAX_FILENAME ];
        if ( unzGetCurrentFileInfo(
            zipfile,
            &file_info,
            filename,
            MAX_FILENAME,
            NULL, 0, NULL, 0 ) != UNZ_OK )
        {
            printf( "could not read file info\n" );
            unzClose( zipfile );
            return -1;
        }

        // Check if this entry is a directory or file.
        const size_t filename_length = strlen( filename );
        if ( filename[ filename_length-1 ] == dir_delimter )
        {
            // Entry is a directory, so create it.
            printf( "dir:%s\n", filename );
            mkdir( filename );
        }
        else
        {
            // Entry is a file, so extract it.
            printf( "file:%s\n", filename );
            if ( unzOpenCurrentFile( zipfile ) != UNZ_OK )
            {
                printf( "could not open file\n" );
                unzClose( zipfile );
                return -1;
            }

            // Open a file to write out the data.
            FILE *out = fopen( filename, "wb" );
            if ( out == NULL )
            {
                printf( "could not open destination file\n" );
                unzCloseCurrentFile( zipfile );
                unzClose( zipfile );
                return -1;
            }

            int error = UNZ_OK;
            do    
            {
                error = unzReadCurrentFile( zipfile, read_buffer, READ_SIZE );
                if ( error < 0 )
                {
                    printf( "error %d\n", error );
                    unzCloseCurrentFile( zipfile );
                    unzClose( zipfile );
                    return -1;
                }

                // Write data to file.
                if ( error > 0 )
                {
                    fwrite( read_buffer, error, 1, out ); // You should check return of fwrite...
                }
            } while ( error > 0 );

            fclose( out );
        }

        unzCloseCurrentFile( zipfile );

        // Go the the next entry listed in the zip file.
        if ( ( i+1 ) < global_info.number_entry )
        {
            if ( unzGoToNextFile( zipfile ) != UNZ_OK )
            {
                printf( "cound not read next file\n" );
                unzClose( zipfile );
                return -1;
            }
        }
    }

    unzClose( zipfile );

    return 0;
}

I built and tested it with MinGW/MSYS on Windows like this:

contrib/minizip/$ gcc -I../.. -o unzip uzip.c unzip.c ioapi.c ../../libz.a
contrib/minizip/$ ./unzip.exe /j/zlib-125.zip

How to keep :active css style after clicking an element

I FIGURED IT OUT. SIMPLE, EFFECTIVE NO jQUERY

We're going to to be using a hidden checkbox.
This example includes one "on click - off click 'hover / active' state"

--

To make content itself clickable:

_x000D_
_x000D_
#activate-div{display:none}

.my-div{background-color:#FFF}

#activate-div:checked ~ label
.my-div{background-color:#000}
_x000D_
<input type="checkbox" id="activate-div">
<label for="activate-div">
  <div class="my-div">
    //MY DIV CONTENT
  </div>
</label>
_x000D_
_x000D_
_x000D_

To make button change content:

_x000D_
_x000D_
#activate-div{display:none}

.my-div{background-color:#FFF}

#activate-div:checked +
.my-div{background-color:#000}
_x000D_
<input type="checkbox" id="activate-div">
<div class="my-div">
  //MY DIV CONTENT
</div>

<label for="activate-div">
  //MY BUTTON STUFF
</label>
_x000D_
_x000D_
_x000D_

Hope it helps!!

Oracle SqlPlus - saving output in a file but don't show on screen

Try This:

sqlplus -s ${ORA_CONN_STR} <<EOF >/dev/null

How to correctly link php-fpm and Nginx Docker containers?

I think we also need to give the fpm container the volume, dont we? So =>

fpm:
    image: php:fpm
    volumes:
        - ./:/var/www/test/

If i dont do this, i run into this exception when firing a request, as fpm cannot find requested file:

[error] 6#6: *4 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream, client: 172.17.42.1, server: localhost, request: "GET / HTTP/1.1", upstream: "fastcgi://172.17.0.81:9000", host: "localhost"

MySQL timezone change?

This works fine

<?php
      $con=mysqli_connect("localhost","my_user","my_password","my_db");
      $con->query("SET GLOBAL time_zone = 'Asia/Calcutta'");
      $con->query("SET time_zone = '+05:30'");
      $con->query("SET @@session.time_zone = '+05:30'");
?>

D3.js: How to get the computed width and height for an arbitrary element?

Once I faced with the issue when I did not know which the element currently stored in my variable (svg or html) but I needed to get it width and height. I created this function and want to share it:

function computeDimensions(selection) {
  var dimensions = null;
  var node = selection.node();

  if (node instanceof SVGGraphicsElement) { // check if node is svg element
    dimensions = node.getBBox();
  } else { // else is html element
    dimensions = node.getBoundingClientRect();
  }
  console.log(dimensions);
  return dimensions;
}

Little demo in the hidden snippet below. We handle click on the blue div and on the red svg circle with the same function.

_x000D_
_x000D_
var svg = d3.select('svg')
  .attr('width', 50)
  .attr('height', 50);

function computeDimensions(selection) {
    var dimensions = null;
  var node = selection.node();

  if (node instanceof SVGElement) {
    dimensions = node.getBBox();
  } else {
    dimensions = node.getBoundingClientRect();
  }
  console.clear();
  console.log(dimensions);
  return dimensions;
}

var circle = svg
    .append("circle")
    .attr("r", 20)
    .attr("cx", 30)
    .attr("cy", 30)
    .attr("fill", "red")
    .on("click", function() { computeDimensions(circle); });
    
var div = d3.selectAll("div").on("click", function() { computeDimensions(div) });
_x000D_
* {
  margin: 0;
  padding: 0;
  border: 0;
}

body {
  background: #ffd;
}

.div {
  display: inline-block;
  background-color: blue;
  margin-right: 30px;
  width: 30px;
  height: 30px;
}
_x000D_
<h3>
  Click on blue div block or svg circle
</h3>
<svg></svg>
<div class="div"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.11.0/d3.min.js"></script>
_x000D_
_x000D_
_x000D_

Setting up FTP on Amazon Cloud Server

Don't forget to update your iptables firewall if you have one to allow the 20-21 and 1024-1048 ranges in.

Do this from /etc/sysconfig/iptables

Adding lines like this:

-A INPUT -m state --state NEW -m tcp -p tcp --dport 20:21 -j ACCEPT

-A INPUT -m state --state NEW -m tcp -p tcp --dport 1024:1048 -j ACCEPT

And restart iptables with the command:

sudo service iptables restart

Submit form with Enter key without submit button?

Change #form to your form's ID

$('#form input').keydown(function(e) {
    if (e.keyCode == 13) {
        $('#form').submit();
    }
});

Or alternatively

$('input').keydown(function(e) {
    if (e.keyCode == 13) {
        $(this).closest('form').submit();
    }
});

How to detect browser using angularjs?

I modified the above technique which was close to what I wanted for angular and turned it into a service :-). I included ie9 because I was having some issues in my angularjs app, but could be something I'm doing, so feel free to take it out.

angular.module('myModule').service('browserDetectionService', function() {

 return {
isCompatible: function () {

  var browserInfo = navigator.userAgent;
  var browserFlags =  {};

  browserFlags.ISFF = browserInfo.indexOf('Firefox') != -1;
  browserFlags.ISOPERA = browserInfo.indexOf('Opera') != -1;
  browserFlags.ISCHROME = browserInfo.indexOf('Chrome') != -1;
  browserFlags.ISSAFARI = browserInfo.indexOf('Safari') != -1 && !browserFlags.ISCHROME;
  browserFlags.ISWEBKIT = browserInfo.indexOf('WebKit') != -1;

  browserFlags.ISIE = browserInfo.indexOf('Trident') > 0 || navigator.userAgent.indexOf('MSIE') > 0;
  browserFlags.ISIE6 = browserInfo.indexOf('MSIE 6') > 0;
  browserFlags.ISIE7 = browserInfo.indexOf('MSIE 7') > 0;
  browserFlags.ISIE8 = browserInfo.indexOf('MSIE 8') > 0;
  browserFlags.ISIE9 = browserInfo.indexOf('MSIE 9') > 0;
  browserFlags.ISIE10 = browserInfo.indexOf('MSIE 10') > 0;
  browserFlags.ISOLD = browserFlags.ISIE6 || browserFlags.ISIE7 || browserFlags.ISIE8 || browserFlags.ISIE9; // MUST be here

  browserFlags.ISIE11UP = browserInfo.indexOf('MSIE') == -1 && browserInfo.indexOf('Trident') > 0;
  browserFlags.ISIE10UP = browserFlags.ISIE10 || browserFlags.ISIE11UP;
  browserFlags.ISIE9UP = browserFlags.ISIE9 || browserFlags.ISIE10UP;

  return !browserFlags.ISOLD;
  }
};

});

MySQL Data - Best way to implement paging?

This tutorial shows a great way to do pagination. Efficient Pagination Using MySQL

In short, avoid to use OFFSET or large LIMIT

Better way to convert an int to a boolean

Joking aside, if you're only expecting your input integer to be a zero or a one, you should really be checking that this is the case.

int yourInteger = whatever;
bool yourBool;
switch (yourInteger)
{
    case 0: yourBool = false; break;
    case 1: yourBool = true;  break;
    default:
        throw new InvalidOperationException("Integer value is not valid");
}

The out-of-the-box Convert won't check this; nor will yourInteger (==|!=) (0|1).

How to set auto increment primary key in PostgreSQL?

Try this command:

ALTER TABLE your_table ADD COLUMN key_column BIGSERIAL PRIMARY KEY;

Try it with the same DB-user as the one you have created the table.

PHP, How to get current date in certain format

date("Y-m-d H:i:s"); // This should do it.

React js change child component's state from parent component

You can send a prop from the parent and use it in child component so you will base child's state changes on the sent prop changes and you can handle this by using getDerivedStateFromProps in the child component.

Fastest way of finding differences between two files in unix?

This will work fast:

Case 1 - File2 = File1 + extra text appended.

grep -Fxvf File2.txt File1.txt >> File3.txt

File 1: 80 Lines File 2: 100 Lines File 3: 20 Lines

Getting request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

In case of Request to a REST Service:

You need to allow the CORS (cross origin sharing of resources) on the endpoint of your REST Service with Spring annotation:

@CrossOrigin(origins = "http://localhost:8080")

Very good tutorial: https://spring.io/guides/gs/rest-service-cors/

What is SELF JOIN and when would you use it?

A self join is simply when you join a table with itself. There is no SELF JOIN keyword, you just write an ordinary join where both tables involved in the join are the same table. One thing to notice is that when you are self joining it is necessary to use an alias for the table otherwise the table name would be ambiguous.

It is useful when you want to correlate pairs of rows from the same table, for example a parent - child relationship. The following query returns the names of all immediate subcategories of the category 'Kitchen'.

SELECT T2.name
FROM category T1
JOIN category T2
ON T2.parent = T1.id
WHERE T1.name = 'Kitchen'

.NET String.Format() to add commas in thousands place for a number

Note that the value that you're formatting should be numeric. It doesn't look like it will take a string representation of a number and format is with commas.

How to solve "java.io.IOException: error=12, Cannot allocate memory" calling Runtime#exec()?

I solved this using JNA: https://github.com/twall/jna

import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;

public class prova {

    private interface CLibrary extends Library {
        CLibrary INSTANCE = (CLibrary) Native.loadLibrary((Platform.isWindows() ? "msvcrt" : "c"), CLibrary.class);
        int system(String cmd);
    }

    private static int exec(String command) {
        return CLibrary.INSTANCE.system(command);
    }

    public static void main(String[] args) {
        exec("ls");
    }
}

Python "TypeError: unhashable type: 'slice'" for encoding categorical data

Your x and y values ??are not running so first of all youre begin to write this point

 import numpy as np
 import pandas as pd
 import matplotlib as plt

 dataframe=pd.read_csv(".\datasets\Position_Salaries.csv")

 x=dataframe.iloc[:,1:2].values 
 y=dataframe.iloc[:,2].values    
 x1=dataframe.iloc[:,:-1].values 

point of value have publish

yii2 hidden input value

You can use this code line in view(form)

 <?= $form->field($model, 'hidden1')->hiddenInput(['value'=>'your_value'])->label(false) ?>

Please refere this as example

If your need to pass currant date and time as hidden input : Model attribute is 'created_on' and its value is retrieve from date('Y-m-d H:i:s') , just like:"2020-03-10 09:00:00"

  <?= $form->field($model, 'created_on')->hiddenInput(['value'=>date('Y-m-d H:i:s')])->label(false) ?>

How to get multiple counts with one SQL query?

One way which works for sure

SELECT a.distributor_id,
    (SELECT COUNT(*) FROM myTable WHERE level='personal' and distributor_id = a.distributor_id) as PersonalCount,
    (SELECT COUNT(*) FROM myTable WHERE level='exec' and distributor_id = a.distributor_id) as ExecCount,
    (SELECT COUNT(*) FROM myTable WHERE distributor_id = a.distributor_id) as TotalCount
FROM (SELECT DISTINCT distributor_id FROM myTable) a ;

EDIT:
See @KevinBalmforth's break down of performance for why you likely don't want to use this method and instead should opt for @Taryn?'s answer. I'm leaving this so people can understand their options.

Mailto: Body formatting

From the first result on Google:

mailto:[email protected]_t?subject=Header&body=This%20is...%20the%20first%20line%0D%0AThis%20is%20the%20second

"X does not name a type" error in C++

When the compiler compiles the class User and gets to the MyMessageBox line, MyMessageBox has not yet been defined. The compiler has no idea MyMessageBox exists, so cannot understand the meaning of your class member.

You need to make sure MyMessageBox is defined before you use it as a member. This is solved by reversing the definition order. However, you have a cyclic dependency: if you move MyMessageBox above User, then in the definition of MyMessageBox the name User won't be defined!

What you can do is forward declare User; that is, declare it but don't define it. During compilation, a type that is declared but not defined is called an incomplete type. Consider the simpler example:

struct foo; // foo is *declared* to be a struct, but that struct is not yet defined

struct bar
{
    // this is okay, it's just a pointer;
    // we can point to something without knowing how that something is defined
    foo* fp; 

    // likewise, we can form a reference to it
    void some_func(foo& fr);

    // but this would be an error, as before, because it requires a definition
    /* foo fooMember; */
};

struct foo // okay, now define foo!
{
    int fooInt;
    double fooDouble;
};

void bar::some_func(foo& fr)
{
    // now that foo is defined, we can read that reference:
    fr.fooInt = 111605;
    fr.foDouble = 123.456;
}

By forward declaring User, MyMessageBox can still form a pointer or reference to it:

class User; // let the compiler know such a class will be defined

class MyMessageBox
{
public:
    // this is ok, no definitions needed yet for User (or Message)
    void sendMessage(Message *msg, User *recvr); 

    Message receiveMessage();
    vector<Message>* dataMessageList;
};

class User
{
public:
    // also ok, since it's now defined
    MyMessageBox dataMsgBox;
};

You cannot do this the other way around: as mentioned, a class member needs to have a definition. (The reason is that the compiler needs to know how much memory User takes up, and to know that it needs to know the size of its members.) If you were to say:

class MyMessageBox;

class User
{
public:
    // size not available! it's an incomplete type
    MyMessageBox dataMsgBox;
};

It wouldn't work, since it doesn't know the size yet.


On a side note, this function:

 void sendMessage(Message *msg, User *recvr);

Probably shouldn't take either of those by pointer. You can't send a message without a message, nor can you send a message without a user to send it to. And both of those situations are expressible by passing null as an argument to either parameter (null is a perfectly valid pointer value!)

Rather, use a reference (possibly const):

 void sendMessage(const Message& msg, User& recvr);

How can I convert string date to NSDate?

 func convertDateFormatter(date: String) -> String
 {

    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"//this your string date format
    dateFormatter.timeZone = NSTimeZone(name: "UTC")
    let date = dateFormatter.dateFromString(date)


    dateFormatter.dateFormat = "yyyy MMM EEEE HH:mm"///this is what you want to convert format
    dateFormatter.timeZone = NSTimeZone(name: "UTC")
    let timeStamp = dateFormatter.stringFromDate(date!)


    return timeStamp
}

Updated for Swift 3.

func convertDateFormatter(date: String) -> String
{

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"//this your string date format
    dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
    let date = dateFormatter.date(from: date)


    dateFormatter.dateFormat = "yyyy MMM EEEE HH:mm"///this is what you want to convert format
    dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
    let timeStamp = dateFormatter.string(from: date!)


    return timeStamp
}

Resource leak: 'in' is never closed

private static Scanner in;

I fixed it by declaring in as a private static Scanner class variable. Not sure why that fixed it but that is what eclipse recommended I do.

How do I send a cross-domain POST request via JavaScript?

One more important thing to note!!! In example above it's described how to use

$.ajax({
    type     : 'POST',
    dataType : 'json', 
    url      : 'another-remote-server',
    ...
});

JQuery 1.6 and lower has a bug with cross-domain XHR. According to Firebug no requests except OPTIONS were sent. No POST. At all.

Spent 5 hours testing/tuning my code. Adding a lot of headers on the remote server (script). Without any effect. But later, I've updated JQuery lib to 1.6.4, and everything works like a charm.

Remove multiple items from a Python list in just one statement

But what if I don't know the indices of the items I want to remove?

I do not exactly understand why you do not like .remove but to get the first index corresponding to a value use .index(value):

ind=item_list.index('item')

then remove the corresponding value:

del item_list.pop[ind]

.index(value) gets the first occurrence of value, and .remove(value) removes the first occurrence of value

Best way to access a control on another form in Windows Forms?

public void Enable_Usercontrol1()
{
    UserControl1 usercontrol1 = new UserControl1();
    usercontrol1.Enabled = true;
} 
/*
    Put this Anywhere in your Form and Call it by Enable_Usercontrol1();
    Also, Make sure the Usercontrol1 Modifiers is Set to Protected Internal
*/

Counting array elements in Perl

Edit: Hash versus Array

As cincodenada correctly pointed out in the comment, ysth gave a better answer: I should have answered your question with another question: "Do you really want to use a Perl array? A hash may be more appropriate."

An array allocates memory for all possible indices up to the largest used so-far. In your example, you allocate 24 cells (but use only 3). By contrast, a hash only allocates space for those fields that are actually used.

Array solution: scalar grep

Here are two possible solutions (see below for explanation):

print scalar(grep {defined $_} @a), "\n";  # prints 3
print scalar(grep $_, @a), "\n";            # prints 3

Explanation: After adding $a[23], your array really contains 24 elements --- but most of them are undefined (which also evaluates as false). You can count the number of defined elements (as done in the first solution) or the number of true elements (second solution).

What is the difference? If you set $a[10]=0, then the first solution will count it, but the second solution won't (because 0 is false but defined). If you set $a[3]=undef, none of the solutions will count it.

Hash solution (by yst)

As suggested by another solution, you can work with a hash and avoid all the problems:

$a{0}  = 1;
$a{5}  = 2;
$a{23} = 3;
print scalar(keys %a), "\n";  # prints 3

This solution counts zeros and undef values.

jQuery selector regular expressions

James Padolsey created a wonderful filter that allows regex to be used for selection.

Say you have the following div:

<div class="asdf">

Padolsey's :regex filter can select it like so:

$("div:regex(class, .*sd.*)")

Also, check the official documentation on selectors.

UPDATE: : syntax Deprecation JQuery 3.0

Since jQuery.expr[':'] used in Padolsey's implementation is already deprecated and will render a syntax error in the latest version of jQuery, here is his code adapted to jQuery 3+ syntax:

jQuery.expr.pseudos.regex = jQuery.expr.createPseudo(function (expression) {
    return function (elem) {
        var matchParams = expression.split(','),
            validLabels = /^(data|css):/,
            attr = {
                method: matchParams[0].match(validLabels) ?
                    matchParams[0].split(':')[0] : 'attr',
                property: matchParams.shift().replace(validLabels, '')
            },
            regexFlags = 'ig',
            regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g, ''), regexFlags);
        return regex.test(jQuery(elem)[attr.method](attr.property));
    }
});

Ruby: How to turn a hash into HTTP parameters?

I know this is an old question, but I just wanted to post this bit of code as I could not find a simple gem to do just this task for me.

module QueryParams

  def self.encode(value, key = nil)
    case value
    when Hash  then value.map { |k,v| encode(v, append_key(key,k)) }.join('&')
    when Array then value.map { |v| encode(v, "#{key}[]") }.join('&')
    when nil   then ''
    else            
      "#{key}=#{CGI.escape(value.to_s)}" 
    end
  end

  private

  def self.append_key(root_key, key)
    root_key.nil? ? key : "#{root_key}[#{key.to_s}]"
  end
end

Rolled up as gem here: https://github.com/simen/queryparams

Adding a regression line on a ggplot

In general, to provide your own formula you should use arguments x and y that will correspond to values you provided in ggplot() - in this case x will be interpreted as x.plot and y as y.plot. You can find more information about smoothing methods and formula via the help page of function stat_smooth() as it is the default stat used by geom_smooth().

ggplot(data,aes(x.plot, y.plot)) +
  stat_summary(fun.data=mean_cl_normal) + 
  geom_smooth(method='lm', formula= y~x)

If you are using the same x and y values that you supplied in the ggplot() call and need to plot the linear regression line then you don't need to use the formula inside geom_smooth(), just supply the method="lm".

ggplot(data,aes(x.plot, y.plot)) +
  stat_summary(fun.data= mean_cl_normal) + 
  geom_smooth(method='lm')

How to insert element into arrays at specific position?

You can insert elements during a foreach loop, since this loop works on a copy of the original array, but you have to keep track of the number of inserted lines (I call this "bloat" in this code):

$bloat=0;
foreach ($Lines as $n=>$Line)
    {
    if (MustInsertLineHere($Line))
        {
        array_splice($Lines,$n+$bloat,0,"string to insert");
        ++$bloat;
        }
    }

Obviously, you can generalize this "bloat" idea to handle arbitrary insertions and deletions during the foreach loop.

Reset IntelliJ UI to Default

All above answers are correct, but you loose configuration settings.

But if your IDE's only themes or fonts are changed or some UI related issues and you want to restore to default theme, then just delete

${user.home}/.IntelliJIdea13/config/options/options.xml

file while IDE is not running, then after next restart IDE's theme will gets reset to default.

remove all variables except functions

Here's a one-liner that removes all objects except for functions:

rm(list = setdiff(ls(), lsf.str()))

It uses setdiff to find the subset of objects in the global environment (as returned by ls()) that don't have mode function (as returned by lsf.str())

Cannot read configuration file due to insufficient permissions

Make sure your web.config file is not marked Read-only

E: Unable to locate package npm

Download the the repository key with:

curl -s https://deb.nodesource.com/gpgkey/nodesource.gpg.key | apt-key add -

Then setup the repository:

sudo sh -c "echo deb https://deb.nodesource.com/node_8.x cosmic main \
                 > /etc/apt/sources.list.d/nodesource.list"
sudo apt-get update
sudo apt-get install nodejs

JComboBox Selection Change Listener?

Here is creating a ComboBox adding a listener for item selection change:

JComboBox comboBox = new JComboBox();

comboBox.setBounds(84, 45, 150, 20);
contentPane.add(comboBox);

JComboBox comboBox_1 = new JComboBox();
comboBox_1.setBounds(84, 97, 150, 20);
contentPane.add(comboBox_1);
comboBox.addItemListener(new ItemListener() {
    public void itemStateChanged(ItemEvent arg0) {
        //Do Something
    }
});

alter the size of column in table containing data

Case 1 : Yes, this works fine.

Case 2 : This will fail with the error ORA-01441 : cannot decrease column length because some value is too big.

Share and enjoy.

Question mark and colon in statement. What does it mean?

This is also known as the "inline if", or as above the ternary operator. https://en.wikipedia.org/wiki/%3F:

It's used to reduce code, though it's not recommended to use a lot of these on a single line as it may make maintaining code quite difficult. Imagine:

a = b?c:(d?e:(f?g:h));

and you could go on a while.

It ends up basically the same as writing:

if(b)
  a = c;
else if(d)
  a = e;
else if(f)
  a = g;
else
  a = h;

In your case, "string requestUri = _apiURL + "?e=" + OperationURL[0] + ((OperationURL[1] == "GET") ? GetRequestSignature() : "");"

Can also be written as: (omitting the else, since it's an empty string)

string requestUri = _apiURL + "?e=" + OperationURL[0];
if((OperationURL[1] == "GET")
    requestUri = requestUri + GetRequestSignature();

or like this:

string requestUri;
if((OperationURL[1] == "GET")
    requestUri = _apiURL + "?e=" + OperationURL[0] + GetRequestSignature();
else
    requestUri = _apiURL + "?e=" + OperationURL[0];

Depending on your preference / the code style your boss tells you to use.

Java - sending HTTP parameters via POST method easily

Appears that you also have to callconnection.getOutputStream() "at least once" (as well as setDoOutput(true)) for it to treat it as a POST.

So the minimum required code is:

    URL url = new URL(urlString);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    //connection.setRequestMethod("POST"); this doesn't seem to do anything at all..so not useful
    connection.setDoOutput(true); // set it to POST...not enough by itself however, also need the getOutputStream call...
    connection.connect();
    connection.getOutputStream().close(); 

You can even use "GET" style parameters in the urlString, surprisingly. Though that might confuse things.

You can also use NameValuePair apparently.

convert datetime to date format dd/mm/yyyy

this is you need and all people

   string date  = textBox1.Text;

        DateTime date2 = Convert.ToDateTime(date);
        var date3 = date2.Date;
        var D = date3.Day;
      var M =  date3.Month;         
      var y = date3.Year;
      string monthStr = M.ToString("00");
      string date4 = D.ToString() + "/" + monthStr.ToString() + "/" + y.ToString();


      textBox1.Text = date4;

How to find EOF through fscanf?

while (fscanf(input,"%s",arr) != EOF && count!=7) {
  len=strlen(arr); 
  count++; 
}

how to use the Box-Cox power transformation in R

According to the Box-cox transformation formula in the paper Box,George E. P.; Cox,D.R.(1964). "An analysis of transformations", I think mlegge's post might need to be slightly edited.The transformed y should be (y^(lambda)-1)/lambda instead of y^(lambda). (Actually, y^(lambda) is called Tukey transformation, which is another distinct transformation formula.)
So, the code should be:

(trans <- bc$x[which.max(bc$y)])
[1] 0.4242424
# re-run with transformation
mnew <- lm(((y^trans-1)/trans) ~ x) # Instead of mnew <- lm(y^trans ~ x) 

More information

Please correct me if I misunderstood it.

Text to speech(TTS)-Android

A minimalistic example to quickly test the TTS system:

private TextToSpeech textToSpeechSystem;

@Override
protected void onStart() {
  super.onStart();
  textToSpeechSystem = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            if (status == TextToSpeech.SUCCESS) {
                String textToSay = "Hello world, this is a test message!";
                textToSpeechSystem.speak(textToSay, TextToSpeech.QUEUE_ADD, null);
            }
        }
   });
}

If you don't use localized messages textToSpeechSystem.setLanguage(..) is important as well, since your users probably don't all have English set as their default language so the pronunciation of the words will be wrong. But for testing TTS in general this snippet is enough

Related links: https://developer.android.com/reference/android/speech/tts/TextToSpeech

How to convert CSV to JSON in Node.js

Here is a solution that does not require a separate module. However, it is very crude, and does not implement much error handling. It could also use more tests, but it will get you going. If you are parsing very large files, you may want to seek an alternative. Also, see this solution from Ben Nadel.

Node Module Code, csv2json.js:

/*
 * Convert a CSV String to JSON
 */
exports.convert = function(csvString) {
    var json = [];
    var csvArray = csvString.split("\n");

    // Remove the column names from csvArray into csvColumns.
    // Also replace single quote with double quote (JSON needs double).
    var csvColumns = JSON
            .parse("[" + csvArray.shift().replace(/'/g, '"') + "]");

    csvArray.forEach(function(csvRowString) {

        var csvRow = csvRowString.split(",");

        // Here we work on a single row.
        // Create an object with all of the csvColumns as keys.
        jsonRow = new Object();
        for ( var colNum = 0; colNum < csvRow.length; colNum++) {
            // Remove beginning and ending quotes since stringify will add them.
            var colData = csvRow[colNum].replace(/^['"]|['"]$/g, "");
            jsonRow[csvColumns[colNum]] = colData;
        }
        json.push(jsonRow);
    });

    return JSON.stringify(json);
};

Jasmine Test, csv2jsonSpec.js:

var csv2json = require('csv2json.js');

var CSV_STRING = "'col1','col2','col3'\n'1','2','3'\n'4','5','6'";
var JSON_STRING = '[{"col1":"1","col2":"2","col3":"3"},{"col1":"4","col2":"5","col3":"6"}]';

/* jasmine specs for csv2json */
describe('csv2json', function() {

    it('should convert a csv string to a json string.', function() {
        expect(csv2json.convert(CSV_STRING)).toEqual(
                JSON_STRING);
    });
});

Converting double to string

This code compiles and works for me. It converts a double to a string using the calls you tried.

public class TestDouble {

    public static void main(String[] args) {
        double total = 44;
        String total2 = Double.toString(total);

        System.out.println("Double is " + total2);
    }
}

I am puzzled by your seeing the NumberFormatException. Look at the stack trace. I'm guessing you have other code that you are not showing in your example that is causing that exception to be thrown.

django admin - add custom form fields that are not part of the model

Django 2.1.1 The primary answer got me halfway to answering my question. It did not help me save the result to a field in my actual model. In my case I wanted a textfield that a user could enter data into, then when a save occurred the data would be processed and the result put into a field in the model and saved. While the original answer showed how to get the value from the extra field, it did not show how to save it back to the model at least in Django 2.1.1

This takes the value from an unbound custom field, processes, and saves it into my real description field:

class WidgetForm(forms.ModelForm):
    extra_field = forms.CharField(required=False)

    def processData(self, input):
        # example of error handling
        if False:
            raise forms.ValidationError('Processing failed!')

        return input + " has been processed"

    def save(self, commit=True):
        extra_field = self.cleaned_data.get('extra_field', None)

        # self.description = "my result" note that this does not work

        # Get the form instance so I can write to its fields
        instance = super(WidgetForm, self).save(commit=commit)

        # this writes the processed data to the description field
        instance.description = self.processData(extra_field)

        if commit:
            instance.save()

        return instance

    class Meta:
        model = Widget
        fields = "__all__"

Web API optional parameters

I figured it out. I was using a bad example I found in the past of how to map query string to the method parameters.

In case anyone else needs it, in order to have optional parameters in a query string such as:

  • ~/api/products/filter?apc=AA&xpc=BB
  • ~/api/products/filter?sku=7199123

you would use:

[Route("products/filter/{apc?}/{xpc?}/{sku?}")]
public IHttpActionResult Get(string apc = null, string xpc = null, int? sku = null)
{ ... }

It seems odd to have to define default values for the method parameters when these types already have a default.

Reading in from System.in - Java

You probably looking for something like this.

FileInputStream in = new FileInputStream("inputFile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));

Initializing a struct to 0

See §6.7.9 Initialization:

21 If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

So, yes both of them work. Note that in C99 a new way of initialization, called designated initialization can be used too:

myStruct _m1 = {.c2 = 0, .c1 = 1};

rails 3.1.0 ActionView::Template::Error (application.css isn't precompiled)

Here's the quick fix:

If you're using capistrano do this add this to your deploy.rb:

after 'deploy:update_code' do
  run "cd #{release_path}; RAILS_ENV=production rake assets:precompile"
end

cap deploy

Regular expression to find URLs within a string

All of the above answers are not match for Unicode characters in URL, for example: http://google.com?query=d?c+filan+dã+search

For the solution, this one should work:

(ftp:\/\/|www\.|https?:\/\/){1}[a-zA-Z0-9u00a1-\uffff0-]{2,}\.[a-zA-Z0-9u00a1-\uffff0-]{2,}(\S*)

5.7.57 SMTP - Client was not authenticated to send anonymous mail during MAIL FROM error

Main two reasons only as mentioned in above comments

  1. NetworkCredentials you set should be correct. Verify with try actually signing into the account.
  2. You need to set UseDefaultCredentials to false first and then set Credentials Or Put smtp.UseDefaultCredentials = false; above the smtp.Credentials assignment.

Webpack "OTS parsing error" loading fonts

I just had the same issue with Font Awesome. Turned out this was caused by a problem with FTP. The file was uploaded as text (ASCII) instead of binary, which corrupted the file. I simply changed my FTP software to binary, re-uploaded the font files, and then it all worked.

https://css-tricks.com/forums/topic/custom-fonts-returns-failed-to-decode-downloaded-font/ this helped me in the end I had the same issue with FTP transferring files as text

How do I make a redirect in PHP?

Summary of existing answers plus my own two cents:

1. Basic answer

You can use the header() function to send a new HTTP header, but this must be sent to the browser before any HTML or text (so before the <!DOCTYPE ...> declaration, for example).

header('Location: '.$newURL);

2. Important details

die() or exit()

header("Location: http://example.com/myOtherPage.php");
die();

Why you should use die() or exit(): The Daily WTF

Absolute or relative URL

Since June 2014 both absolute and relative URLs can be used. See RFC 7231 which had replaced the old RFC 2616, where only absolute URLs were allowed.

Status Codes

PHP's "Location"-header still uses the HTTP 302-redirect code, this is a "temporary" redirect and may not be the one you should use. You should consider either 301 (permanent redirect) or 303 (other).

Note: W3C mentions that the 303-header is incompatible with "many pre-HTTP/1.1 user agents. Currently used browsers are all HTTP/1.1 user agents. This is not true for many other user agents like spiders and robots.

3. Documentation

HTTP Headers and the header() function in PHP

4. Alternatives

You may use the alternative method of http_redirect($url); which needs the PECL package pecl to be installed.

5. Helper Functions

This function doesn't incorporate the 303 status code:

function Redirect($url, $permanent = false)
{
    header('Location: ' . $url, true, $permanent ? 301 : 302);

    exit();
}

Redirect('http://example.com/', false);

This is more flexible:

function redirect($url, $statusCode = 303)
{
   header('Location: ' . $url, true, $statusCode);
   die();
}

6. Workaround

As mentioned header() redirects only work before anything is written out. They usually fail if invoked inmidst HTML output. Then you might use a HTML header workaround (not very professional!) like:

 <meta http-equiv="refresh" content="0;url=finalpage.html">

Or a JavaScript redirect even.

window.location.replace("http://example.com/");

C#: easiest way to populate a ListBox from a List

You can also use the AddRange method

listBox1.Items.AddRange(myList.ToArray());

Check the current number of connections to MongoDb

Connect to MongoDB using mongo-shell and run following command.

db.serverStatus().connections

e.g:

mongo> db.serverStatus().connections
{ "current" : 3, "available" : 816, "totalCreated" : NumberLong(1270) }

How to get the last day of the month?

Here is another answer. No extra packages required.

datetime.date(year + int(month/12), month%12+1, 1)-datetime.timedelta(days=1)

Get the first day of the next month and subtract a day from it.

Which ChromeDriver version is compatible with which Chrome Browser version?

At the time of writing this I have discovered that chromedriver 2.46 or 2.36 works well with Chrome 75.0.3770.100

Documentation here: http://chromedriver.chromium.org/downloads states align driver and browser alike but I found I had issues even with the most up-to-date driver when using Chrome 75

I am running Selenium 2 on Windows 10 Machine.

Flatten List in LINQ

Try SelectMany()

var result = iList.SelectMany( i => i );

Why use pip over easy_install?

UPDATE: setuptools has absorbed distribute as opposed to the other way around, as some thought. setuptools is up-to-date with the latest distutils changes and the wheel format. Hence, easy_install and pip are more or less on equal footing now.

Source: http://pythonhosted.org/setuptools/merge-faq.html#why-setuptools-and-not-distribute-or-another-name

'Operation is not valid due to the current state of the object' error during postback

For ASP.NET 1.1, this is still due to someone posting more than 1000 form fields, but the setting must be changed in the registry rather than a config file. It should be added as a DWORD named MaxHttpCollectionKeys in the registry under

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ASP.NET\1.1.4322.0

for 32-bit editions of Windows, and

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\ASP.NET\1.1.4322.0

for 64-bit editions of Windows.

What's a good way to extend Error in JavaScript?

In short:

  • If you are using ES6 without transpilers:

    class CustomError extends Error { /* ... */}
    
  • If you are using Babel transpiler:

Option 1: use babel-plugin-transform-builtin-extend

Option 2: do it yourself (inspired from that same library)

    function CustomError(...args) {
      const instance = Reflect.construct(Error, args);
      Reflect.setPrototypeOf(instance, Reflect.getPrototypeOf(this));
      return instance;
    }
    CustomError.prototype = Object.create(Error.prototype, {
      constructor: {
        value: Error,
        enumerable: false,
        writable: true,
        configurable: true
      }
    });
    Reflect.setPrototypeOf(CustomError, Error);
  • If you are using pure ES5:

    function CustomError(message, fileName, lineNumber) {
      var instance = new Error(message, fileName, lineNumber);
      Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
      return instance;
    }
    CustomError.prototype = Object.create(Error.prototype, {
      constructor: {
        value: Error,
        enumerable: false,
        writable: true,
        configurable: true
      }
    });
    if (Object.setPrototypeOf){
        Object.setPrototypeOf(CustomError, Error);
    } else {
        CustomError.__proto__ = Error;
    }
    
  • Alternative: use Classtrophobic framework

Explanation:

Why extending the Error class using ES6 and Babel is a problem?

Because an instance of CustomError is not anymore recognized as such.

class CustomError extends Error {}
console.log(new CustomError('test') instanceof Error);// true
console.log(new CustomError('test') instanceof CustomError);// false

In fact, from the official documentation of Babel, you cannot extend any built-in JavaScript classes such as Date, Array, DOM or Error.

The issue is described here:

What about the other SO answers?

All the given answers fix the instanceof issue but you lose the regular error console.log:

console.log(new CustomError('test'));
// output:
// CustomError {name: "MyError", message: "test", stack: "Error?    at CustomError (<anonymous>:4:19)?    at <anonymous>:1:5"}

Whereas using the method mentioned above, not only you fix the instanceof issue but you also keep the regular error console.log:

console.log(new CustomError('test'));
// output:
// Error: test
//     at CustomError (<anonymous>:2:32)
//     at <anonymous>:1:5

SQL select statements with multiple tables

You need to join the two tables:

select p.id, p.first, p.middle, p.last, p.age,
       a.id as address_id, a.street, a.city, a.state, a.zip
from Person p inner join Address a on p.id = a.person_id
where a.zip = '97229';

This will select all of the columns from both tables. You could of course limit that by choosing different columns in the select clause.

Button Center CSS

Consider adding this to your CSS to resolve the problem:

.btn {
  width: 20%;
  margin-left: 40%;
  margin-right: 30%;
}

Decoding and verifying JWT token using System.IdentityModel.Tokens.Jwt

I am just wondering why to use some libraries for JWT token decoding and verification at all.

Encoded JWT token can be created using following pseudocode

var headers = base64URLencode(myHeaders);
var claims = base64URLencode(myClaims);
var payload = header + "." + claims;

var signature = base64URLencode(HMACSHA256(payload, secret));

var encodedJWT = payload + "." + signature;

It is very easy to do without any specific library. Using following code:

using System;
using System.Text;
using System.Security.Cryptography;

public class Program
{   
    // More info: https://stormpath.com/blog/jwt-the-right-way/
    public static void Main()
    {           
        var header = "{\"typ\":\"JWT\",\"alg\":\"HS256\"}";
        var claims = "{\"sub\":\"1047986\",\"email\":\"[email protected]\",\"given_name\":\"John\",\"family_name\":\"Doe\",\"primarysid\":\"b521a2af99bfdc65e04010ac1d046ff5\",\"iss\":\"http://example.com\",\"aud\":\"myapp\",\"exp\":1460555281,\"nbf\":1457963281}";

        var b64header = Convert.ToBase64String(Encoding.UTF8.GetBytes(header))
            .Replace('+', '-')
            .Replace('/', '_')
            .Replace("=", "");
        var b64claims = Convert.ToBase64String(Encoding.UTF8.GetBytes(claims))
            .Replace('+', '-')
            .Replace('/', '_')
            .Replace("=", "");

        var payload = b64header + "." + b64claims;
        Console.WriteLine("JWT without sig:    " + payload);

        byte[] key = Convert.FromBase64String("mPorwQB8kMDNQeeYO35KOrMMFn6rFVmbIohBphJPnp4=");
        byte[] message = Encoding.UTF8.GetBytes(payload);

        string sig = Convert.ToBase64String(HashHMAC(key, message))
            .Replace('+', '-')
            .Replace('/', '_')
            .Replace("=", "");

        Console.WriteLine("JWT with signature: " + payload + "." + sig);        
    }

    private static byte[] HashHMAC(byte[] key, byte[] message)
    {
        var hash = new HMACSHA256(key);
        return hash.ComputeHash(message);
    }
}

The token decoding is reversed version of the code above.To verify the signature you will need to the same and compare signature part with calculated signature.

UPDATE: For those how are struggling how to do base64 urlsafe encoding/decoding please see another SO question, and also wiki and RFCs

What is the point of "Initial Catalog" in a SQL Server connection string?

If the user name that is in the connection string has access to more then one database you have to specify the database you want the connection string to connect to. If your user has only one database available then you are correct that it doesn't matter. But it is good practice to put this in your connection string.

When do you use map vs flatMap in RxJava?

Flatmap maps observables to observables. Map maps items to items.

Flatmap is more flexible but Map is more lightweight and direct, so it kind of depends on your usecase.

If you are doing ANYTHING async (including switching threads), you should be using Flatmap, as Map will not check if the consumer is disposed (part of the lightweight-ness)

Using Excel as front end to Access database (with VBA)

Unless there is a strong advantage to running your user form in Excel then I would go with a 100% Access solution that would export the reports and data to Excel on an ad-hoc basis.

From what you describe, Access seems the stronger contender as it is built for working with data:
you would have a lot more tools at your disposal to solve any data problems than have to go around the limitations of Excel and shoehorn it into becoming Access...

As for your questions:

  1. Very easy. There have been some other questions on SO on that subject.
    See for instance this one and that one.

  2. Don't know, but I would guess that there could be a small penalty.
    The biggest difficulty I see is trying to get all the functionalities that Access gives you and re-creating some of these in Excel.

  3. Yes, you can have multiple Excel users and a single Access database.
    Here again, using Access as a front-end and keeping the data in a linked Access database on your network would make more sense and it's easy as pie, there's even a wizard in Access to help you do that: it's just 1 click away.

Really, as most other people have said, take a tiny bit of time to get acquainted with Access, it will save you a lot of time and trouble.
You may know Excel better but if you've gone 80% of the way already if you know VBA and are familiar with the Office object model.

Other advantages of doing it in Access: the Access 2007 runtime is free, meaning that if you were to deploy to app to 1 or 30 PC it would cost you the same: nothing.
You only need one full version of Access for your development work (the Runtime doesn't have the designers).

Get a DataTable Columns DataType

You could always use typeof in the if statement. It is better than working with string values like the answer of Natarajan.

if (dt.Columns[0].DataType == typeof(DateTime))
{
}

Commenting in a Bash script inside a multiline command

In addition to the examples by DigitalRoss, here's another form that you can use if you prefer $() instead of backticks `

echo abc $(: comment) \
     def $(: comment) \
     xyz

Of course, you can use the colon syntax with backticks as well:

echo abc `: comment` \
     def `: comment` \
     xyz

Additional Notes

The reason $(#comment) doesn't work is because once it sees the #, it treats the rest of the line as comments, including the closing parentheses: comment). So the parentheses is never closed.

Backticks parse differently and will detect the closing backtick even after a #.

How to download a file using a Java REST service and a data stream

See example here: Input and Output binary streams using JERSEY?

Pseudo code would be something like this (there are a few other similar options in above mentioned post):

@Path("file/")
@GET
@Produces({"application/pdf"})
public StreamingOutput getFileContent() throws Exception {
     public void write(OutputStream output) throws IOException, WebApplicationException {
        try {
          //
          // 1. Get Stream to file from first server
          //
          while(<read stream from first server>) {
              output.write(<bytes read from first server>)
          }
        } catch (Exception e) {
            throw new WebApplicationException(e);
        } finally {
              // close input stream
        }
    }
}

Why does sed not replace all occurrences?

You have to put a g at the end, it stands for "global":

echo dog dog dos | sed -r 's:dog:log:g'
                                     ^

What is the easiest way to remove the first character from a string?

class String
  def bye_felicia()
    felicia = self.strip[0] #first char, not first space.
    self.sub(felicia, '')
  end
end

How to set variable from a SQL query?

To ASSIGN variables using a SQL select the best practice is as shown below

->DECLARE co_id INT ;
->DECLARE sname VARCHAR(10) ;

->SELECT course_id INTO co_id FROM course_details ;
->SELECT student_name INTO sname FROM course_details;

IF you have to assign more than one variable in a single line you can use this same SELECT INTO

->DECLARE val1 int;
->DECLARE val2 int;

->SELECT student__id,student_name INTO val1,val2 FROM student_details;

--HAPPY CODING-- 

jQuery get text as number

Always use parseInt with a radix (base) as the second parameter, or you will get unexpected results:

var number = parseInt($(this).find('.number').text(), 10);

A popular variation however is to use + as a unitary operator. This will always convert with base 10 and never throw an error, just return zero NaN which can be tested with the function isNaN() if it's an invalid number:

var number = +($(this).find('.number').text());

How to get datas from List<Object> (Java)?

System.out.println("Element "+i+list.get(0));}

Should be

System.out.println("Element "+i+list.get(i));}

To use the JSF tags, you give the dataList value attribute a reference to your list of elements, and the var attribute is a local name for each element of that list in turn. Inside the dataList, you use properties of the object (getters) to output the information about that individual object:

<t:dataList id="myDataList" value="#{houseControlList}" var="element" rows="3" >
...
<t:outputText id="houseId" value="#{element.houseId}"/>
...
</t:dataList>

Powershell script to check if service is started, if not then start it

The below is a compact script that will check if "running" and attempt start service until the service returns as running.

$Service = 'ServiceName'
If ((Get-Service $Service).Status -ne 'Running') {
   do {
       Start-Service $Service -ErrorAction SilentlyContinue
       Start-Sleep 10
   } until ((Get-Service $Service).Status -eq 'Running')
} Return "$($Service) has STARTED"

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined

By reading your exception , It's sure that you forgot to autowire customerService

You should autowire your customerservice .

make following changes in your controller class

@Controller
public class CustomerController{

    @Autowired
    private Customerservice customerservice;
......other code......

}

Again your service implementation class

write

@Service
public class CustomerServiceImpl implements CustomerService {
    @Autowired
    private CustomerDAO customerDAO;
......other code......

.....add transactional methods
}

If you are using hibernate make necessary changes in your applicationcontext xml file(configuration of session factory is needed).

you should autowire sessionFactory set method in your DAO mplementation

please find samle application context :

<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:annotation-config />
    <context:component-scan base-package="com.sparkle" />
    <!-- Configures the @Controller programming model -->
    <mvc:annotation-driven />

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
            p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" p:order="0" />

    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>
    <!-- <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
        p:location="/WEB-INF/jdbc.properties" /> -->

     <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">         
        <list>
            <value>/WEB-INF/jdbc.properties</value>          

        </list>    
    </property>     
    </bean>




    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource"
        p:driverClassName="${jdbc.driverClassName}"
        p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
        p:password="${jdbc.password}" />


    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${jdbc.dialect}</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <tx:annotation-driven />


   <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
          p:sessionFactory-ref="sessionFactory"/>


</beans>

note that i am using jdbc.properties file for jdbc url and driver specification

Unfinished Stubbing Detected in Mockito

org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:
E.g. thenReturn() may be missing.

For mocking of void methods try out below:

//Kotlin Syntax

 Mockito.`when`(voidMethodCall())
           .then {
                Unit //Do Nothing
            }

MySQL CREATE TABLE IF NOT EXISTS in PHPmyadmin import

On the CREATE TABLE,

The AUTO_INCREMENT of abuse_id is set to 2. MySQL now thinks 1 already exists.

With the INSERT statement you are trying to insert abuse_id with record 1. Please set AUTO_INCREMENT on CREATE_TABLE to 1 and try again.

Otherwise set the abuse_id in the INSERT statement to 'NULL'.

How can i resolve this?

Node.js server that accepts POST requests

The following code shows how to read values from an HTML form. As @pimvdb said you need to use the request.on('data'...) to capture the contents of the body.

const http = require('http')

const server = http.createServer(function(request, response) {
  console.dir(request.param)

  if (request.method == 'POST') {
    console.log('POST')
    var body = ''
    request.on('data', function(data) {
      body += data
      console.log('Partial body: ' + body)
    })
    request.on('end', function() {
      console.log('Body: ' + body)
      response.writeHead(200, {'Content-Type': 'text/html'})
      response.end('post received')
    })
  } else {
    console.log('GET')
    var html = `
            <html>
                <body>
                    <form method="post" action="http://localhost:3000">Name: 
                        <input type="text" name="name" />
                        <input type="submit" value="Submit" />
                    </form>
                </body>
            </html>`
    response.writeHead(200, {'Content-Type': 'text/html'})
    response.end(html)
  }
})

const port = 3000
const host = '127.0.0.1'
server.listen(port, host)
console.log(`Listening at http://${host}:${port}`)


If you use something like Express.js and Bodyparser then it would look like this since Express will handle the request.body concatenation

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

app.use(express.bodyParser())

app.get('/', function(request, response) {
  console.log('GET /')
  var html = `
    <html>
        <body>
            <form method="post" action="http://localhost:3000">Name: 
                <input type="text" name="name" />
                <input type="submit" value="Submit" />
            </form>
        </body>
    </html>`
  response.writeHead(200, {'Content-Type': 'text/html'})
  response.end(html)
})

app.post('/', function(request, response) {
  console.log('POST /')
  console.dir(request.body)
  response.writeHead(200, {'Content-Type': 'text/html'})
  response.end('thanks')
})

port = 3000
app.listen(port)
console.log(`Listening at http://localhost:${port}`)

PostgreSQL create table if not exists

I created a generic solution out of the existing answers which can be reused for any table:

CREATE OR REPLACE FUNCTION create_if_not_exists (table_name text, create_stmt text)
RETURNS text AS
$_$
BEGIN

IF EXISTS (
    SELECT *
    FROM   pg_catalog.pg_tables 
    WHERE    tablename  = table_name
    ) THEN
   RETURN 'TABLE ' || '''' || table_name || '''' || ' ALREADY EXISTS';
ELSE
   EXECUTE create_stmt;
   RETURN 'CREATED';
END IF;

END;
$_$ LANGUAGE plpgsql;

Usage:

select create_if_not_exists('my_table', 'CREATE TABLE my_table (id integer NOT NULL);');

It could be simplified further to take just one parameter if one would extract the table name out of the query parameter. Also I left out the schemas.

Can I force pip to reinstall the current version?

pip install --upgrade --force-reinstall <package>

When upgrading, reinstall all packages even if they are already up-to-date.

pip install -I <package>
pip install --ignore-installed <package>

Ignore the installed packages (reinstalling instead).

Checking if an object is a number in C#

Rather than rolling your own, the most reliable way to tell if an in-built type is numeric is probably to reference Microsoft.VisualBasic and call Information.IsNumeric(object value). The implementation handles a number of subtle cases such as char[] and HEX and OCT strings.

Auto height div with overflow and scroll when needed

Quick Answer with Main Points

Pretty much the same answer as the best chosen answer from @Joum, to quicken your quest of trying to achieve the answer to the posted question and save time from deciphering whats going on in the syntax --

Answer

Set position attribute to fixed, set the top and bottom attributes to your liking for the element or div that you want to have an "auto" size of in comparison to its parent element and then set overflow to hidden.

.YourClass && || #YourId{
   position:fixed;
   top:10px;
   bottom:10px;
   width:100%; //Do not forget width
   overflow-y:auto;
}

Wallah! This is all you need for your special element that you want to have a dynamic height according to screen size and or dynamic incoming content while maintaining the opportunity to scroll.

How to redirect the output of the time command to a file in Linux?

If you are using csh you can use:

/usr/bin/time --output=outfile -p $SHELL  -c 'your command'

For example:

/usr/bin/time --output=outtime.txt -p csh -c 'cat file'

Spring Boot @autowired does not work, classes in different package

In my case @component was not working because I initialized that class instance by using new <classname>().

If we initialize instance by conventional Java way anywhere in code, then spring won't add that component in IOC container.

Why use static_cast<int>(x) instead of (int)x?

One pragmatic tip: you can search easily for the static_cast keyword in your source code if you plan to tidy up the project.

Where is the web server root directory in WAMP?

Everything suggested by user "mins" is correct, and excellent information.

WAMP 2.5 provides a default Server Configuration display when you enter localhost into your browser. This maps to c:\wamp\www, as described in previous posts. Creating subdirectories under www will cause Projects to appear on this display. A click and you're in your project.

I have various projects under different directory structures, sometimes on shared drives which makes this centralized location of files inconvenient. Luckily, there is a second feature of WAMP 2.5, an Alias, which makes specifying the location of one (or more) disparate web directories quite easy. No editing of configuration files. Using the WAMP menu, choose Apache > Alias directories > Add an Alias.

WAMP has evolved nicely to provide support for a variety of developer preferences.

Windows recursive grep command-line

Recursive search for import word inside src folder:

> findstr /s import .\src\*

How to check the function's return value if true or false

Wrong syntax. You can't compare a Boolean to a string like "false" or "true". In your case, just test it's inverse:

if(!ValidateForm()) { ...

You could test against the constant false, but it's rather ugly and generally frowned upon:

if(ValidateForm() == false) { ...

git push: permission denied (public key)

In order to deploy to your friend's repo you need to add your public key to the repository's deploy keys.

Go to the repository, go to deploy keys, and add the id_rsa.pub (or whatever yours is named) to "deploy keys".

I believe adding the key to your own account only lets you write to repositories that your account created. If it was created by an organization you need to add the key to the repo's deploy keys.

https://developer.github.com/v3/guides/managing-deploy-keys/

Removing character in list of strings

lst = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")...]

msg = filter(lambda x : x != "8", lst)

print msg

EDIT: For anyone who came across this post, just for understanding the above removes any elements from the list which are equal to 8.

Supposing we use the above example the first element ("aaaaa8") would not be equal to 8 and so it would be dropped.

To make this (kinda work?) with how the intent of the question was we could perform something similar to this

msg = filter(lambda x: x != "8", map(lambda y: list(y), lst))
  • I am not in an interpreter at the moment so of course mileage may vary, we may have to index so we do list(y[0]) would be the only modification to the above for this explanation purposes.

What this does is split each element of list up into an array of characters so ("aaaa8") would become ["a", "a", "a", "a", "8"].

This would result in a data type that looks like this

msg = [["a", "a", "a", "a"], ["b", "b"]...]

So finally to wrap that up we would have to map it to bring them all back into the same type roughly

msg = list(map(lambda q: ''.join(q), filter(lambda x: x != "8", map(lambda y: list(y[0]), lst))))

I would absolutely not recommend it, but if you were really wanting to play with map and filter, that would be how I think you could do it with a single line.

Can I scale a div's height proportionally to its width using CSS?

You can use View Width for the "width" and again half of the View Width for the "height". In this way you're guaranteed the correct ratio regardless of the viewport size.

<div class="ss"></div>

.ss
{
    width: 30vw;
    height: 15vw;
}

Fiddle

Git Pull While Ignoring Local Changes?

For me the following worked:

(1) First fetch all changes:

$ git fetch --all

(2) Then reset the master:

$ git reset --hard origin/master

(3) Pull/update:

$ git pull

Algorithm to generate all possible permutations of a list?

Basically, for each item from left to right, all the permutations of the remaining items are generated (and each one is added with the current elements). This can be done recursively (or iteratively if you like pain) until the last item is reached at which point there is only one possible order.

So with the list [1,2,3,4] all the permutations that start with 1 are generated, then all the permutations that start with 2, then 3 then 4.

This effectively reduces the problem from one of finding permutations of a list of four items to a list of three items. After reducing to 2 and then 1 item lists, all of them will be found.
Example showing process permutations using 3 coloured balls:
Red, green and blue coloured balls ordered permutations image (from https://en.wikipedia.org/wiki/Permutation#/media/File:Permutations_RGB.svg - https://commons.wikimedia.org/wiki/File:Permutations_RGB.svg)

Groovy - Convert object to JSON string

I couldn't get the other answers to work within the evaluate console in Intellij so...

groovy.json.JsonOutput.toJson(myObject)

This works quite well, but unfortunately

groovy.json.JsonOutput.prettyString(myObject)

didn't work for me.

To get it pretty printed I had to do this...

groovy.json.JsonOutput.prettyPrint(groovy.json.JsonOutput.toJson(myObject))

Removing cordova plugins from the project

You could use: cordova plugins list | awk '{print $1}' | xargs cordova plugins rm

and use cordova plugins list to verify if plugins are all removed.

How do I trim a file extension from a String in Java?

String fileName="foo.bar";
int dotIndex=fileName.lastIndexOf('.');
if(dotIndex>=0) { // to prevent exception if there is no dot
  fileName=fileName.substring(0,dotIndex);
}

Is this a trick question? :p

I can't think of a faster way atm.

String.Replace ignoring case

below is the alternative to replace string ignoring character case

String thisString = "hello world"; 
String replaceString = "World";

//thisString.Replace("World", "csharp"); 
//below is the alternative to replace string ignoring character case

int start = StringUtils.indexOfIgnoreCase(thisString,replaceString);
String searchKey = thisString.substring(start, start+replaceString.length());
thisString= thisString.replaceAll(searchKey ,replaceString );
System.out.println(thisString);

//prints hello World

SQL Server - stop or break execution of a SQL script

Thx for the answer!

raiserror() works fine but you shouldn't forget the return statement otherwise the script continues without error! (hense the raiserror isn't a "throwerror" ;-)) and of course doing a rollback if necessary!

raiserror() is nice to tell the person who executes the script that something went wrong.

How to convert JSON to XML or XML to JSON?

I'm not sure there is point in such conversion (yes, many do it, but mostly to force a square peg through round hole) -- there is structural impedance mismatch, and conversion is lossy. So I would recommend against such format-to-format transformations.

But if you do it, first convert from json to object, then from object to xml (and vice versa for reverse direction). Doing direct transformation leads to ugly output, loss of information, or possibly both.

Disable a textbox using CSS

Going further on Pekka's answer, I had a style "style1" on some of my textboxes. You can create a "style1[disabled]" so you style only the disabled textboxes using "style1" style:

.style1[disabled] { ... }

Worked ok on IE8.

How to center canvas in html5

You can give your canvas the ff CSS properties:

#myCanvas
{
    display: block;
    margin: 0 auto;
}

Can I have an onclick effect in CSS?

you can use :target

or to filter by class name, use .classname:target

or filter by id name using #idname:target

_x000D_
_x000D_
#id01:target {      
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.msg {
    display:none;
}

.close {        
    color:white;        
    width: 2rem;
    height: 2rem;
    background-color: black;
    text-align:center;
    margin:20px;
}
_x000D_
  
<a href="#id01">Open</a>

<div id="id01" class="msg">    
    <a href="" class="close">&times;</a>
    <p>Some text. Some text. Some text.</p>
    <p>Some text. Some text. Some text.</p>
</div>
_x000D_
_x000D_
_x000D_

Struct memory layout in C

In C, the compiler is allowed to dictate some alignment for every primitive type. Typically the alignment is the size of the type. But it's entirely implementation-specific.

Padding bytes are introduced so every object is properly aligned. Reordering is not allowed.

Possibly every remotely modern compiler implements #pragma pack which allows control over padding and leaves it to the programmer to comply with the ABI. (It is strictly nonstandard, though.)

From C99 §6.7.2.1:

12 Each non-bit-field member of a structure or union object is aligned in an implementation- defined manner appropriate to its type.

13 Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.

gradlew: Permission Denied

I got the same error trying to execute flutter run on a mac. Apparently, in your flutter project, there is a file android/gradlew that is expected to be executable (and it wasn't). So in my case,

chmod a+rx android/gradlew

i used this command and execute the project

Getting attributes of Enum's value

If your enum contains a value like Equals you might bump into a few bugs using some extensions in a lot of answers here. This is because it is normally assumed that typeof(YourEnum).GetMember(YourEnum.Value) would return only one value, which is the MemberInfo of your enum. Here's a slightly safer version Adam Crawford's answer.

public static class AttributeExtensions
{
    #region Methods

    public static T GetAttribute<T>(this Enum enumValue) where T : Attribute
    {
        var type = enumValue.GetType();
        var memberInfo = type.GetMember(enumValue.ToString());
        var member = memberInfo.FirstOrDefault(m => m.DeclaringType == type);
        var attribute = Attribute.GetCustomAttribute(member, typeof(T), false);
        return attribute is T ? (T)attribute : null;
    }

    #endregion
}

Sending string via socket (python)

This piece of code is incorrect.

while 1:
    (clientsocket, address) = serversocket.accept()
    print ("connection found!")
    data = clientsocket.recv(1024).decode()
    print (data)
    r='REceieve'
    clientsocket.send(r.encode())

The call on accept() on the serversocket blocks until there's a client connection. When you first connect to the server from the client, it accepts the connection and receives data. However, when it enters the loop again, it is waiting for another connection and thus blocks as there are no other clients that are trying to connect.

That's the reason the recv works correct only the first time. What you should do is find out how you can handle the communication with a client that has been accepted - maybe by creating a new Thread to handle communication with that client and continue accepting new clients in the loop, handling them in the same way.

Tip: If you want to work on creating your own chat application, you should look at a networking engine like Twisted. It will help you understand the whole concept better too.

What are some reasons for jquery .focus() not working?

I found that focus does not work when trying to get a focus on a text element (such as a notice div), but does work when focusing on input fields.

Undefined or null for AngularJS

You can always add it exactly for your application

angular.isUndefinedOrNull = function(val) {
    return angular.isUndefined(val) || val === null 
}

How to get the file ID so I can perform a download of a file from Google Drive API on Android?

This script logs all the file names and ids in the drive:

// Log the name and id of every file in the user's Drive
function listFiles() {
  var files = DriveApp.getFiles();
  while ( files.hasNext() ) {
    var file = files.next();
    Logger.log( file.getName() + ' ' + file.getId() );
  }
}  

Also, the "Files: list" page has a form at the end that lists the metadata of all the files in the drive, that can be used in case you need but a few ids.

CSS display:table-row does not expand when width is set to 100%

give on .view-type class float:left; or delete the float:right; of .view-name

edit: Wrap your div <div class="view-row"> with another div for example <div class="table">

and set the following css :

.table {
    display:table;
    width:100%;}

You have to use the table structure for correct results.

Why can't radio buttons be "readonly"?

This is the trick you can go with.

<input type="radio" name="name" onclick="this.checked = false;" />

Determine which element the mouse pointer is on top of in JavaScript

DEMO

There's a really cool function called document.elementFromPoint which does what it sounds like.

What we need is to find the x and y coords of the mouse and then call it using those values:

var x = event.clientX, y = event.clientY,
    elementMouseIsOver = document.elementFromPoint(x, y);

document.elementFromPoint

jQuery event object

Updating user data - ASP.NET Identity

I also had problems using UpdateAsync when developing a version of SimpleSecurity that uses ASP.NET Identity. For example, I added a feature to do a password reset that needed to add a password reset token to the user information. At first I tried using UpdateAsync and it got the same results as you did. I ended up wrapping the user entity in a repository pattern and got it to work. You can look at the SimpleSecurity project for an example. After working with ASP.NET Identity more (documentation is still non-existent) I think that UpdateAsync just commits the update to the context, you still need to save the context for it to commit to the database.

Objective-C Static Class Level variables

u can rename the class as classA.mm and add C++ features in it.

Occurrences of substring in a string

Try this one. It replaces all the matches with a -.

String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int numberOfMatches = 0;
while (str.contains(findStr)){
    str = str.replaceFirst(findStr, "-");
    numberOfMatches++;
}

And if you don't want to destroy your str you can create a new string with the same content:

String str = "helloslkhellodjladfjhello";
String strDestroy = str;
String findStr = "hello";
int numberOfMatches = 0;
while (strDestroy.contains(findStr)){
    strDestroy = strDestroy.replaceFirst(findStr, "-");
    numberOfMatches++;
}

After executing this block these will be your values:

str = "helloslkhellodjladfjhello"
strDestroy = "-slk-djladfj-"
findStr = "hello"
numberOfMatches = 3

How to define Typescript Map of key value pair. where key is a number and value is an array of objects

First thing, define a type or interface for your object, it will make things much more readable:

type Product = { productId: number; price: number; discount: number };

You used a tuple of size one instead of array, it should look like this:

let myarray: Product[];
let priceListMap : Map<number, Product[]> = new Map<number, Product[]>();

So now this works fine:

myarray.push({productId : 1 , price : 100 , discount : 10});
myarray.push({productId : 2 , price : 200 , discount : 20});
myarray.push({productId : 3 , price : 300 , discount : 30});
priceListMap.set(1 , this.myarray);
myarray = null;

(code in playground)

check android application is in foreground or not?

I don't understand what you want, but You can detect currently foreground/background application with ActivityManager.getRunningAppProcesses() call.

Something like,

class ForegroundCheckTask extends AsyncTask<Context, Void, Boolean> {

  @Override
  protected Boolean doInBackground(Context... params) {
    final Context context = params[0].getApplicationContext();
    return isAppOnForeground(context);
  }

  private boolean isAppOnForeground(Context context) {
    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
    if (appProcesses == null) {
      return false;
    }
    final String packageName = context.getPackageName();
    for (RunningAppProcessInfo appProcess : appProcesses) {
      if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
        return true;
      }
    }
    return false;
  }
}

// Use like this:
boolean foregroud = new ForegroundCheckTask().execute(context).get();

Also let me know if I misunderstand..

UPDATE: Look at this SO question Determining the current foreground application from a background task or service fore more information..

Thanks..

What is POCO in Entity Framework?

POCOs(Plain old CLR objects) are simply entities of your Domain. Normally when we use entity framework the entities are generated automatically for you. This is great but unfortunately these entities are interspersed with database access functionality which is clearly against the SOC (Separation of concern). POCOs are simple entities without any data access functionality but still gives the capabilities all EntityObject functionalities like

  • Lazy loading
  • Change tracking

Here is a good start for this

POCO Entity framework

You can also generate POCOs so easily from your existing Entity framework project using Code generators.

EF 5.X DbContext code generator

For div to extend full height

In case also setting the height of the html and the body to 100% makes everything messier for you as it did for me, the following worked for me:

height: calc(100vh - 33rem)

The - 33rem is the height of the elements coming after the one we want to take full height, i.e., 100vh. By subtracting the height, we will make sure there is no overflow and it will always be responsive (assuming we are working with rem instead of px).

Postgres: clear entire database before re-creating / re-populating from bash script

I'd just drop the database and then re-create it. On a UNIX or Linux system, that should do it:

$ dropdb development_db_name
$ createdb developmnent_db_name

That's how I do it, actually.

get value from DataTable

It looks like you have accidentally declared DataType as an array rather than as a string.

Change line 3 to:

Dim DataType As String = myTableData.Rows(i).Item(1)

That should work.

How to get form values in Symfony2 controller

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

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

or you can get all data sent

$data = $form->getData();

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

How can I pause setInterval() functions?

While @Jonas Giuro is right when saying that:

You cannot PAUSE the setInterval function, you can either STOP it (clearInterval), or let it run

On the other hand this behavior can be simulated with approach @VitaliyG suggested:

You shouldn't measure time in interval function. Instead just save time when timer was started and measure difference when timer was stopped/paused. Use setInterval only to update displayed value.

_x000D_
_x000D_
var output = $('h1');_x000D_
var isPaused = false;_x000D_
var time = new Date();_x000D_
var offset = 0;_x000D_
var t = window.setInterval(function() {_x000D_
  if(!isPaused) {_x000D_
    var milisec = offset + (new Date()).getTime() - time.getTime();_x000D_
    output.text(parseInt(milisec / 1000) + "s " + (milisec % 1000));_x000D_
  }_x000D_
}, 10);_x000D_
_x000D_
//with jquery_x000D_
$('.toggle').on('click', function(e) {_x000D_
  e.preventDefault();_x000D_
  isPaused = !isPaused;_x000D_
  if (isPaused) {_x000D_
    offset += (new Date()).getTime() - time.getTime();_x000D_
  } else {_x000D_
    time = new Date();_x000D_
  }_x000D_
_x000D_
});
_x000D_
h1 {_x000D_
    font-family: Helvetica, Verdana, sans-serif;_x000D_
    font-size: 12px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<h1>Seconds: 0</h1>_x000D_
<button class="toggle">Toggle</button>
_x000D_
_x000D_
_x000D_

php refresh current page?

$_SERVER['REQUEST_URI'] should work.

How to view the SQL queries issued by JPA?

If you use hibernate and logback as your logger you could use the following (shows only the bindings and not the results):

<appender
    name="STDOUT"
    class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
        <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} -
            %msg%n</pattern>
    </encoder>
    <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
        <evaluator>
            <expression>return message.toLowerCase().contains("org.hibernate.type") &amp;&amp;
                logger.startsWith("returning");</expression>
        </evaluator>
        <OnMismatch>NEUTRAL</OnMismatch>
        <OnMatch>DENY</OnMatch>
    </filter>
</appender>

org.hibernate.SQL=DEBUG prints the Query

<logger name="org.hibernate.SQL">
    <level value="DEBUG" />
</logger>

org.hibernate.type=TRACE prints the bindings and normally the results, which will be suppressed thru the custom filter

<logger name="org.hibernate.type">
    <level value="TRACE" />
</logger>

You need the janino dependency (http://logback.qos.ch/manual/filters.html#JaninoEventEvaluator):

<dependency>
    <groupId>org.codehaus.janino</groupId>
    <artifactId>janino</artifactId>
    <version>2.6.1</version>
</dependency>

Responsive timeline UI with Bootstrap3

_x000D_
_x000D_
.timeline {_x000D_
  list-style: none;_x000D_
  padding: 20px 0 20px;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.timeline:before {_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  position: absolute;_x000D_
  content: " ";_x000D_
  width: 3px;_x000D_
  background-color: #eeeeee;_x000D_
  left: 50%;_x000D_
  margin-left: -1.5px;_x000D_
}_x000D_
_x000D_
.timeline > li {_x000D_
  margin-bottom: 20px;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.timeline > li:before,_x000D_
.timeline > li:after {_x000D_
  content: " ";_x000D_
  display: table;_x000D_
}_x000D_
_x000D_
.timeline > li:after {_x000D_
  clear: both;_x000D_
}_x000D_
_x000D_
.timeline > li:before,_x000D_
.timeline > li:after {_x000D_
  content: " ";_x000D_
  display: table;_x000D_
}_x000D_
_x000D_
.timeline > li:after {_x000D_
  clear: both;_x000D_
}_x000D_
_x000D_
.timeline > li > .timeline-panel {_x000D_
  width: 46%;_x000D_
  float: left;_x000D_
  border: 1px solid #d4d4d4;_x000D_
  border-radius: 2px;_x000D_
  padding: 20px;_x000D_
  position: relative;_x000D_
  -webkit-box-shadow: 0 1px 6px rgba(0, 0, 0, 0.175);_x000D_
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.175);_x000D_
}_x000D_
_x000D_
.timeline > li > .timeline-panel:before {_x000D_
  position: absolute;_x000D_
  top: 26px;_x000D_
  right: -15px;_x000D_
  display: inline-block;_x000D_
  border-top: 15px solid transparent;_x000D_
  border-left: 15px solid #ccc;_x000D_
  border-right: 0 solid #ccc;_x000D_
  border-bottom: 15px solid transparent;_x000D_
  content: " ";_x000D_
}_x000D_
_x000D_
.timeline > li > .timeline-panel:after {_x000D_
  position: absolute;_x000D_
  top: 27px;_x000D_
  right: -14px;_x000D_
  display: inline-block;_x000D_
  border-top: 14px solid transparent;_x000D_
  border-left: 14px solid #fff;_x000D_
  border-right: 0 solid #fff;_x000D_
  border-bottom: 14px solid transparent;_x000D_
  content: " ";_x000D_
}_x000D_
_x000D_
.timeline > li > .timeline-badge {_x000D_
  color: #fff;_x000D_
  width: 50px;_x000D_
  height: 50px;_x000D_
  line-height: 50px;_x000D_
  font-size: 1.4em;_x000D_
  text-align: center;_x000D_
  position: absolute;_x000D_
  top: 16px;_x000D_
  left: 50%;_x000D_
  margin-left: -25px;_x000D_
  background-color: #999999;_x000D_
  z-index: 100;_x000D_
  border-top-right-radius: 50%;_x000D_
  border-top-left-radius: 50%;_x000D_
  border-bottom-right-radius: 50%;_x000D_
  border-bottom-left-radius: 50%;_x000D_
}_x000D_
_x000D_
.timeline > li.timeline-inverted > .timeline-panel {_x000D_
  float: right;_x000D_
}_x000D_
_x000D_
.timeline > li.timeline-inverted > .timeline-panel:before {_x000D_
  border-left-width: 0;_x000D_
  border-right-width: 15px;_x000D_
  left: -15px;_x000D_
  right: auto;_x000D_
}_x000D_
_x000D_
.timeline > li.timeline-inverted > .timeline-panel:after {_x000D_
  border-left-width: 0;_x000D_
  border-right-width: 14px;_x000D_
  left: -14px;_x000D_
  right: auto;_x000D_
}_x000D_
_x000D_
.timeline-badge.primary {_x000D_
  background-color: #2e6da4 !important;_x000D_
}_x000D_
_x000D_
.timeline-badge.success {_x000D_
  background-color: #3f903f !important;_x000D_
}_x000D_
_x000D_
.timeline-badge.warning {_x000D_
  background-color: #f0ad4e !important;_x000D_
}_x000D_
_x000D_
.timeline-badge.danger {_x000D_
  background-color: #d9534f !important;_x000D_
}_x000D_
_x000D_
.timeline-badge.info {_x000D_
  background-color: #5bc0de !important;_x000D_
}_x000D_
_x000D_
.timeline-title {_x000D_
  margin-top: 0;_x000D_
  color: inherit;_x000D_
}_x000D_
_x000D_
.timeline-body > p,_x000D_
.timeline-body > ul {_x000D_
  margin-bottom: 0;_x000D_
}_x000D_
_x000D_
.timeline-body > p + p {_x000D_
  margin-top: 5px;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="page-header">_x000D_
    <h1 id="timeline">Timeline</h1>_x000D_
  </div>_x000D_
  <ul class="timeline">_x000D_
    <li>_x000D_
      <div class="timeline-badge"><i class="glyphicon glyphicon-check"></i></div>_x000D_
      <div class="timeline-panel">_x000D_
         <p><small class="text-muted"><i class="glyphicon glyphicon-time"></i> 11 hours ago via Twitter</small></p>_x000D_
        <div class="timeline-heading">_x000D_
          <h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
          <p><small class="text-muted"><i class="glyphicon glyphicon-time"></i> 11 hours ago via Twitter</small></p>_x000D_
        </div>_x000D_
        <div class="timeline-body">_x000D_
          <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
            Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
        </div>_x000D_
      </div>_x000D_
    </li>_x000D_
    <li class="timeline-inverted">_x000D_
      <div class="timeline-badge warning"><i class="glyphicon glyphicon-credit-card"></i></div>_x000D_
      <div class="timeline-panel">_x000D_
        <div class="timeline-heading">_x000D_
          <h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
        </div>_x000D_
        <div class="timeline-body">_x000D_
          <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
            Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
          <p>Suco de cevadiss, é um leite divinis, qui tem lupuliz, matis, aguis e fermentis. Interagi no mé, cursus quis, vehicula ac nisi. Aenean vel dui dui. Nullam leo erat, aliquet quis tempus a, posuere ut mi. Ut scelerisque neque et turpis posuere_x000D_
            pulvinar pellentesque nibh ullamcorper. Pharetra in mattis molestie, volutpat elementum justo. Aenean ut ante turpis. Pellentesque laoreet mé vel lectus scelerisque interdum cursus velit auctor. Lorem ipsum dolor sit amet, consectetur adipiscing_x000D_
            elit. Etiam ac mauris lectus, non scelerisque augue. Aenean justo massa.</p>_x000D_
        </div>_x000D_
      </div>_x000D_
    </li>_x000D_
    <li>_x000D_
      <div class="timeline-badge danger"><i class="glyphicon glyphicon-credit-card"></i></div>_x000D_
      <div class="timeline-panel">_x000D_
        <div class="timeline-heading">_x000D_
          <h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
        </div>_x000D_
        <div class="timeline-body">_x000D_
          <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
            Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
        </div>_x000D_
      </div>_x000D_
    </li>_x000D_
    <li class="timeline-inverted">_x000D_
      <div class="timeline-panel">_x000D_
        <div class="timeline-heading">_x000D_
          <h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
        </div>_x000D_
        <div class="timeline-body">_x000D_
          <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
            Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
        </div>_x000D_
      </div>_x000D_
    </li>_x000D_
    <li>_x000D_
      <div class="timeline-badge info"><i class="glyphicon glyphicon-floppy-disk"></i></div>_x000D_
      <div class="timeline-panel">_x000D_
        <div class="timeline-heading">_x000D_
          <h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
        </div>_x000D_
        <div class="timeline-body">_x000D_
          <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
            Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
          <hr>_x000D_
          <div class="btn-group">_x000D_
            <button type="button" class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown">_x000D_
              <i class="glyphicon glyphicon-cog"></i> <span class="caret"></span>_x000D_
            </button>_x000D_
            <ul class="dropdown-menu" role="menu">_x000D_
              <li><a href="#">Action</a></li>_x000D_
              <li><a href="#">Another action</a></li>_x000D_
              <li><a href="#">Something else here</a></li>_x000D_
              <li class="divider"></li>_x000D_
              <li><a href="#">Separated link</a></li>_x000D_
            </ul>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </li>_x000D_
    <li>_x000D_
      <div class="timeline-panel">_x000D_
        <div class="timeline-heading">_x000D_
          <h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
        </div>_x000D_
        <div class="timeline-body">_x000D_
          <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
            Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
        </div>_x000D_
      </div>_x000D_
    </li>_x000D_
    <li class="timeline-inverted">_x000D_
      <div class="timeline-badge success"><i class="glyphicon glyphicon-thumbs-up"></i></div>_x000D_
      <div class="timeline-panel">_x000D_
        <div class="timeline-heading">_x000D_
          <h4 class="timeline-title">Mussum ipsum cacilds</h4>_x000D_
        </div>_x000D_
        <div class="timeline-body">_x000D_
          <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo._x000D_
            Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>_x000D_
        </div>_x000D_
      </div>_x000D_
    </li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://codepen.io/bsngr/pen/Ifvbi/

When to use RDLC over RDL reports?

From my experience there are few things to think about both things:

I. RDL reports are HOSTED reports generally. This means you need to implement SSRS Server. They are a built in extension of Visual Studio from SQL Server for the reporting language. When you install SSRS you should have an add on called 'Business Intelligence Development Studio' which is much easier to work with the reports than without it.

R eport

D efinition

L angauge

Benefits of RDL reports:

  1. You can host the reports in an environment that has services running for you on them.
  2. You can configure security on an item or inheriting level to handle security as a standalone concept
  3. You can configure the service to send out emails(provided you have an SMTP server you have access to) and save files on schedules
  4. You have a database generally called 'ReportServer' you can query for info on the reports once published.
  5. You can access these reports still through 'ReportViewer' in a client application written in ASP.NET, WPF (with a winform control bleh!), or Winforms in .NET using 'ProcessingMode.Remote'.
  6. You can set parameters a user can see and use to gain more flexibility.
  7. You can configure parts of a report to be used for connection strings as 'Data Sources' as well as a sql query, xml, or other datasets as a 'Dataset'. These parts and others can be stored and configured to cache data on a regular basis.
  8. You can write .NET proxy classes of the services http:// /ReportServer/ReportingService2010 or /ReportExecution2005. You can then make up your OWN methods in .NET for emailing, saving, or manipulating SSRS data from the service directly of a Server hosting SSRS reports in code. Programmatically Export SSRS report from sharepoint using ReportService2010.asmx

Downsides:

  1. SSRS is kind of wonkey compared to other things on getting it up fast. Most people get confused by the security policy and designing reports as an 'add on' to VS. SQL 2005 = VS BIDS 2005 , SQL 2008 = VS BIDS 2008, SQL 2012 = VS BIDS 2010(LOL).
  2. Continuing on 1 the policy for security settings IMHO are idiotically overcomplex. There is server security, database security and roles, two security settings on the page hosted for the service. Most people only set up an admin than can't get in and wonder why other users cannot. Most common complaint or question on SSRS is related to getting in generally from my experience.
  3. You can use 'expressions' that will supposeduly 'enhance' your report. Often times you do more than a few and your report goes to a crawl in performance.
  4. You have a set amount of things you can do and export to. SSRS has no hover over reporting I know of without a javascript hack.
  5. Speed and performance can take a hit as the stupid SSRS config recycles the system and a first report can take a while at times just loading the site. You can get around this by altering it but I have found making a keep alive service for it works better.

II. RDLC reports are CLIENT CONTAINED reports that are NOT HOSTED ANYWHERE. The extra c in the name means 'Client'. Generally this is an extension of the RDL language meant for use only in Visual Studio Client Applications. It exists in Visual Studio when you add a 'reporting' item.

Benefits of RDLC reports:

  1. You can hookup a wcf service much much much more easier to the dataset.
  2. You have more control over the dataset and can use POCO classes filled with Entity framework objects or ADO.NET directly as well as tables themselves. You can monkey with the data for optimization it before binding it to the report.
  3. You can customize the look more with add on's directly in code behind.

Downsides:

  1. You need to handle parameters on your own and while you can implement wrapper methods to help the legwork is a little more than expected and unfortunate.
  2. The user cannot SEE the parameters in a 'ReportViewer' control unless it is in remote mode and accessing an RLD report. Thus you need to make textboxes, dropdowns, radio buttons on your own outside the control to pass to it. Some people like this added control, I do not personally.
  3. Anything you want to do with servicing the reports for distribution you need to build yourself. Emailing, subscriptions, saving. Sorry you need to build that in .NET or else implement a proxy that already does that from above you could just be getting using hosted reports.

Honestly I like both for different purposes. If I want something to go out to analysts that they use all the time and tweak for graphs, charts, drill downs and exports to Excel I use RDL and just have SSRS's site do all the legwork of handling the email distributions. If I want an application that has a report section and I know that application is it's own module with rules and governance I use an RDLC and having the parameters be smaller and be driven by the decisions the user made before getting to the report part of what client they are on and site and then they usually just choose a time frame or type and nothing more. So generally a complex report I would use RDL and for something simple I would use RDLC IMHO.

I hope that helps.

Check if a string contains a string in C++

Actually, you can try to use boost library,I think std::string doesn't supply enough method to do all the common string operation.In boost,you can just use the boost::algorithm::contains:

#include <string>
#include <boost/algorithm/string.hpp>

int main() {
    std::string s("gengjiawen");
    std::string t("geng");
    bool b = boost::algorithm::contains(s, t);
    std::cout << b << std::endl;
    return 0;
}

Center a DIV horizontally and vertically

You want to set style

margin: auto;

And remove the positioning styles (top, left, position)

I know this will center horrizontaly but I'm not sure about vertical!

How to render string with html tags in Angular 4+?

Use one way flow syntax property binding:

<div [innerHTML]="comment"></div>

From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script> tag but keeps safe content such as the <b> element."

shuffling/permutating a DataFrame in pandas

This might be more useful when you want your index shuffled.

def shuffle(df):
    index = list(df.index)
    random.shuffle(index)
    df = df.ix[index]
    df.reset_index()
    return df

It selects new df using new index, then reset them.

How to show a running progress bar while page is loading

In this sample, I created a JavaScript progress bar (with percentage display), you can control it and hide it with JavaScript.

In this sample, the progress bar advances every 100ms. You can see it in JSFiddle

var elapsedTime = 0;
var interval = setInterval(function() {
  timer()
}, 100);

function progressbar(percent) {
  document.getElementById("prgsbarcolor").style.width = percent + '%';
  document.getElementById("prgsbartext").innerHTML = percent + '%';
}

function timer() {
  if (elapsedTime > 100) {
    document.getElementById("prgsbartext").style.color = "#FFF";
    document.getElementById("prgsbartext").innerHTML = "Completed.";
    if (elapsedTime >= 107) {
      clearInterval(interval);
      history.go(-1);
    }
  } else {
    progressbar(elapsedTime);
  }
  elapsedTime++;
}

Why is null an object and what's the difference between null and undefined?

For example window.someWeirdProperty is undefined, so

"window.someWeirdProperty === null" evaluates to false while

"window.someWeirdProperty === undefined" evaluates to true.

Moreover checkif if (!o) is not the same as checking if (o == null) for o being false.

How do I delete unpushed git commits?

If you want to move that commit to another branch, get the SHA of the commit in question

git rev-parse HEAD

Then switch the current branch

git checkout other-branch

And cherry-pick the commit to other-branch

git cherry-pick <sha-of-the-commit>

What is JSON and why would I use it?

In short, it is a scripting notation for passing data about. In some ways an alternative to XML, natively supporting basic data types, arrays and associative arrays (name-value pairs, called Objects because that is what they represent).

The syntax is that used in JavaScript and JSON itself stands for "JavaScript Object Notation". However it has become portable and is used in other languages too.

A useful link for detail is here:

http://secretgeek.net/json_3mins.asp

Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 4 (Year)

In my case, I was dealing with a file that was generated by hadoop on a linux box. When I tried to import to sql I had this issue. The fix wound up being to use the hex value for 'line feed' 0x0a. It also worked for bulk insert

bulk insert table from 'file' 
WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '0x0a')

Using CookieContainer with WebClient class

 WebClient wb = new WebClient();
 wb.Headers.Add(HttpRequestHeader.Cookie, "somecookie");

From Comments

How do you format the name and value of the cookie in place of "somecookie" ?

wb.Headers.Add(HttpRequestHeader.Cookie, "cookiename=cookievalue"); 

For multiple cookies:

wb.Headers.Add(HttpRequestHeader.Cookie, 
              "cookiename1=cookievalue1;" +
              "cookiename2=cookievalue2");

jQuery get the name of a select option

Using name on a select option is not valid.

Other have suggested the data- attribute, an alternative is a lookup table

Here the "this" refers to the select so no need to "find" the option

_x000D_
_x000D_
var names = ["", "acoustic", "jazz", "acoustic_jazz", "party", "acoustic_party", "jazz_party", "acoustic_jazz_party"];_x000D_
_x000D_
$(function() {_x000D_
  $('#band_type_choices').on('change', function() {_x000D_
    $('.checkboxlist').hide();_x000D_
    var idx = this.selectedIndex;_x000D_
    if (idx > 0) $('#checkboxlist_' + names[idx]).show();_x000D_
  });_x000D_
});
_x000D_
.checkboxlist { display:none }
_x000D_
Choose acoustic to see the corresponding div_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select id="band_type_choices">_x000D_
  <option vlaue="0"></option>_x000D_
  <option value="100" name="acoustic">Acoustic</option>_x000D_
  <option value="0" name="jazz">Jazz/Easy Listening</option>_x000D_
  <option value="0" name="acoustic_jazz">Acoustic + Jazz/Easy Listening</option>_x000D_
  <option value="0" name="party">Party</option>_x000D_
  <option value="0" name="acoustic_party">Acoustic + Party</option>_x000D_
  <option value="0" name="jazz_party">Jazz/Easy Listening + Party</option>_x000D_
  <option value="0" name="acoustic_jazz_party">Acoustic + Jazz/Easy Listening + Party</option>_x000D_
</select>_x000D_
<div class="checkboxlist" id="checkboxlist_acoustic">_x000D_
  <input type="checkbox" class="checkbox keys" name="keys" value="100" />Keys<br>_x000D_
  <input type="checkbox" class="checkbox acou_guit" name="acou_guit" value="100" />Acoustic Guitar<br>_x000D_
  <input type="checkbox" class="checkbox drums" name="drums" value="100" />Drums<br>_x000D_
  <input type="checkbox" class="checkbox alt_sax" name="alt_sax" value="100" />Alto Sax<br>_x000D_
  <input type="checkbox" class="checkbox ten_sax" name="ten_sax" value="100" />Tenor Sax<br>_x000D_
  <input type="checkbox" class="checkbox clarinet" name="clarinet" value="100" />Clarinet<br>_x000D_
  <input type="checkbox" class="checkbox trombone" name="trombone" value="100" />Trombone<br>_x000D_
  <input type="checkbox" class="checkbox trumpet" name="trumpet" value="100" />Trumpet<br>_x000D_
  <input type="checkbox" class="checkbox flute" name="flute" value="100" />Flute<br>_x000D_
  <input type="checkbox" class="checkbox cello" name="cello" value="100" />Cello<br>_x000D_
  <input type="checkbox" class="checkbox violin" name="violin" value="100" />Violin<br>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to write :hover using inline style?

Not gonna happen with CSS only

Inline javascript

<a href='index.html' 
    onmouseover='this.style.textDecoration="none"' 
    onmouseout='this.style.textDecoration="underline"'>
    Click Me
</a>

In a working draft of the CSS2 spec it was declared that you could use pseudo-classes inline like this:

<a href="http://www.w3.org/Style/CSS"
   style="{color: blue; background: white}  /* a+=0 b+=0 c+=0 */
      :visited {color: green}           /* a+=0 b+=1 c+=0 */
      :hover {background: yellow}       /* a+=0 b+=1 c+=0 */
      :visited:hover {color: purple}    /* a+=0 b+=2 c+=0 */
     ">
</a>

but it was never implemented in the release of the spec as far as I know.

http://www.w3.org/TR/2002/WD-css-style-attr-20020515#pseudo-rules

How to ensure that there is a delay before a service is started in systemd?

The systemd way to do this is to have the process "talk back" when it's setup somehow, like by opening a socket or sending a notification (or a parent script exiting). Which is of course not always straight-forward especially with third party stuff :|

You might be able to do something inline like

ExecStart=/bin/bash -c '/bin/start_cassandra &; do_bash_loop_waiting_for_it_to_come_up_here'

or a script that does the same. Or put do_bash_loop_waiting_for_it_to_come_up_here in an ExecStartPost

Or create a helper .service that waits for it to come up, so the helper service depends on cassandra, and waits for it to come up, then your other process can depend on the helper service.

(May want to increase TimeoutStartSec from the default 90s as well)

Fixing npm path in Windows 8 and 10

change the path for nodejs in environment varibale.

setting environment variable

select records from postgres where timestamp is in certain range

Search till the seconds for the timestamp column in postgress

select * from "TableName" e
    where timestamp >= '2020-08-08T13:00:00' and timestamp < '2020-08-08T17:00:00';

How to delete a row from GridView?

Please try this code.....

DataRow dr = dtPrf_Mstr.NewRow();
dtPrf_Mstr.Rows.Add(dr);
GVGLCode.DataSource = dtPrf_Mstr;
GVGLCode.DataBind();
int iCount = GVGLCode.Rows.Count;
for (int i = 0; i < iCount; i++)
{
   GVGLCode.Rows.Remove(GVGLCode.Rows[i]);
}
GVGLCode.DataBind();

Android, ListView IllegalStateException: "The content of the adapter has changed but ListView did not receive a notification"

Please try one of these solutions :

  1. Sometimes, if you add new object to data list in a thread (or doInBackground method), this error will occur. The solution is : create a temporary list and do adding data to this list in thread(or doInBackground), then do copying all data from temporary list to the list of adapter in UI thread (or onPostExcute)

  2. Make sure all UI updates are called in UI thread.

How to uncheck a checkbox in pure JavaScript?

There is another way to do this:

//elem - get the checkbox element and then
elem.setAttribute('checked', 'checked'); //check
elem.removeAttribute('checked'); //uncheck

How do I insert a drop-down menu for a simple Windows Forms app in Visual Studio 2008?

You can use ComboBox, then point your mouse to the upper arrow facing right, it will unfold a box called ComboBox Tasks and in there you can go ahead and edit your items or fill in the items / strings one per line. This should be the easiest.

How to implement swipe gestures for mobile devices?

I like your solution and implemented it on my site - however, with some little improvements. Just wanted to share my code:

function detectSwipe(id, f) {
    var detect = {
        startX: 0,
        startY: 0,
        endX: 0,
        endY: 0,
        minX: 30,   // min X swipe for horizontal swipe
        maxX: 30,   // max X difference for vertical swipe
        minY: 50,   // min Y swipe for vertial swipe
        maxY: 60    // max Y difference for horizontal swipe
    },
        direction = null,
        element = document.getElementById(id);

    element.addEventListener('touchstart', function (event) {
        var touch = event.touches[0];
        detect.startX = touch.screenX;
        detect.startY = touch.screenY;
    });

    element.addEventListener('touchmove', function (event) {
        event.preventDefault();
        var touch = event.touches[0];
        detect.endX = touch.screenX;
        detect.endY = touch.screenY;
    });

    element.addEventListener('touchend', function (event) {
        if (
            // Horizontal move.
            (Math.abs(detect.endX - detect.startX) > detect.minX)
                && (Math.abs(detect.endY - detect.startY) < detect.maxY)
        ) {
            direction = (detect.endX > detect.startX) ? 'right' : 'left';
        } else if (
            // Vertical move.
            (Math.abs(detect.endY - detect.startY) > detect.minY)
                && (Math.abs(detect.endX - detect.startX) < detect.maxX)
        ) {
            direction = (detect.endY > detect.startY) ? 'down' : 'up';
        }

        if ((direction !== null) && (typeof f === 'function')) {
            f(element, direction);
        }
    });
}

Use it like:

detectSwipe('an_element_id', myfunction);

Or

detectSwipe('another_element_id', my_other_function);

If a swipe is detected the function myfunction is called with parameter element-id and 'left', 'right', 'up' oder 'down'.

"Javac" doesn't work correctly on Windows 10

Kind of beating a dead horse now but, I want to clarify one thing that may not be quite so obvious. Yes indeed you need to edit the PATH environment variable as already stated many times. The key for me was to edit the PATH under SYSTEM variables. I had inadvertently edited the PATH under USER variables. Why did this matter? On my machine I have to log in as an Administrator to edit environment variables. So editing the User variables was not helping because I run the command prompt under my login (non-admin) account. Grrr!

Also, I found that closing the command prompt window, and re-opening it after the PATH variable update was required. Changing the order of the values, adding semi-colons, etc. didn't make a difference for me.

Cheers

How to convert text column to datetime in SQL

Use convert with style 101.

select convert(datetime, Remarks, 101)

If your column is really text you need to convert to varchar before converting to datetime

select convert(datetime, convert(varchar(30), Remarks), 101)

How to read/process command line arguments?

Yet another option is argh. It builds on argparse, and lets you write things like:

import argh

# declaring:

def echo(text):
    "Returns given word as is."
    return text

def greet(name, greeting='Hello'):
    "Greets the user with given name. The greeting is customizable."
    return greeting + ', ' + name

# assembling:

parser = argh.ArghParser()
parser.add_commands([echo, greet])

# dispatching:

if __name__ == '__main__':
    parser.dispatch()

It will automatically generate help and so on, and you can use decorators to provide extra guidance on how the arg-parsing should work.

Using Linq to get the last N elements of a collection?

I am surprised that no one has mentioned it, but SkipWhile does have a method that uses the element's index.

public static IEnumerable<T> TakeLastN<T>(this IEnumerable<T> source, int n)
{
    if (source == null)
        throw new ArgumentNullException("Source cannot be null");

    int goldenIndex = source.Count() - n;
    return source.SkipWhile((val, index) => index < goldenIndex);
}

//Or if you like them one-liners (in the spirit of the current accepted answer);
//However, this is most likely impractical due to the repeated calculations
collection.SkipWhile((val, index) => index < collection.Count() - N)

The only perceivable benefit that this solution presents over others is that you can have the option to add in a predicate to make a more powerful and efficient LINQ query, instead of having two separate operations that traverse the IEnumerable twice.

public static IEnumerable<T> FilterLastN<T>(this IEnumerable<T> source, int n, Predicate<T> pred)
{
    int goldenIndex = source.Count() - n;
    return source.SkipWhile((val, index) => index < goldenIndex && pred(val));
}

How to know a Pod's own IP address from inside a container in the Pod?

In some cases, instead of relying on downward API, programmatically reading the local IP address (from network interfaces) from inside of the container also works.

For example, in golang: https://stackoverflow.com/a/31551220/6247478

Query to convert from datetime to date mysql

Use the DATE function:

SELECT DATE(orders.date_purchased) AS date

Python reading from a file and saving to utf-8

Process text to and from Unicode at the I/O boundaries of your program using open with the encoding parameter. Make sure to use the (hopefully documented) encoding of the file being read. The default encoding varies by OS (specifically, locale.getpreferredencoding(False) is the encoding used), so I recommend always explicitly using the encoding parameter for portability and clarity (Python 3 syntax below):

with open(filename, 'r', encoding='utf8') as f:
    text = f.read()

# process Unicode text

with open(filename, 'w', encoding='utf8') as f:
    f.write(text)

If still using Python 2 or for Python 2/3 compatibility, the io module implements open with the same semantics as Python 3's open and exists in both versions:

import io
with io.open(filename, 'r', encoding='utf8') as f:
    text = f.read()

# process Unicode text

with io.open(filename, 'w', encoding='utf8') as f:
    f.write(text)

How to enable C# 6.0 feature in Visual Studio 2013?

Information for obsoleted prerelease software:

According to this it's just a install and go for Visual Studio 2013:

In fact, installing the C# 6.0 compiler from this release involves little more than installing a Visual Studio 2013 extension, which in turn updates the MSBuild target files.

So just get the files from https://github.com/dotnet/roslyn and you are ready to go.

You do have to know it is an outdated version of the specs implemented there, since they no longer update the package for Visual Studio 2013:

You can also try April's End User Preview, which installs on top of Visual Studio 2013. (note: this VS 2013 preview is quite out of date, and is no longer updated)

So if you do want to use the latest version, you have to download the Visual Studio 2015.

Adding new files to a subversion repository

To add a new file in SVN

svn add file_name
svn commit -m "text about changes..."

To add a new file in a directory in SVN

svn add directory_name/file_name
svn commit -m "text about changes"

To add all new files in a directory with some targets (files) are already versioned (added):

svn add directory_name/*
svn commit -m "text about changes"

Draw a line in a div

Answered this just to emphasize @rblarsen comment on question :

You don't need the style tags in the CSS-file

If you remove the style tag from your css file it will work.

Windows 7 - Add Path

I think you are editing something in the windows registry but that has no effect on the path.

Try this:

How to Add, Remove or Edit Environment variables in Windows 7

the variable of interest is the PATH

also you can type on the command line:

Set PATH=%PATH%;(your new path);

Importing larger sql files into MySQL

I really like the BigDump to do it. It's a very simple PHP file that you edit and send with your huge file through SSH or FTP. Run and wait! It's very easy to configure character encoding, comes UTF-8 by default.

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

Here is something that i have been trying.(Insertion sort- not the best way to sort but does the work)

def sort(list):
    for index in range(1,len(list)):
        value = list[index]
        i = index-1
        while i>=0:
            if value < list[i]:
                list[i+1] = list[i]
                list[i] = value
                i -= 1
            else:
                break

printf() formatting for hex

The %#08X conversion must precede the value with 0X; that is required by the standard. There's no evidence in the standard that the # should alter the behaviour of the 08 part of the specification except that the 0X prefix is counted as part of the length (so you might want/need to use %#010X. If, like me, you like your hex presented as 0x1234CDEF, then you have to use 0x%08X to achieve the desired result. You could use %#.8X and that should also insert the leading zeroes.

Try variations on the following code:

#include <stdio.h>

int main(void)
{
    int j = 0;
    printf("0x%.8X = %#08X = %#.8X = %#010x\n", j, j, j, j);
    for (int i = 0; i < 8; i++)
    {
        j = (j << 4) | (i + 6);
        printf("0x%.8X = %#08X = %#.8X = %#010x\n", j, j, j, j);
    }
    return(0);
}

On an RHEL 5 machine, and also on Mac OS X (10.7.5), the output was:

0x00000000 = 00000000 = 00000000 = 0000000000
0x00000006 = 0X000006 = 0X00000006 = 0x00000006
0x00000067 = 0X000067 = 0X00000067 = 0x00000067
0x00000678 = 0X000678 = 0X00000678 = 0x00000678
0x00006789 = 0X006789 = 0X00006789 = 0x00006789
0x0006789A = 0X06789A = 0X0006789A = 0x0006789a
0x006789AB = 0X6789AB = 0X006789AB = 0x006789ab
0x06789ABC = 0X6789ABC = 0X06789ABC = 0x06789abc
0x6789ABCD = 0X6789ABCD = 0X6789ABCD = 0x6789abcd

I'm a little surprised at the treatment of 0; I'm not clear why the 0X prefix is omitted, but with two separate systems doing it, it must be standard. It confirms my prejudices against the # option.


The treatment of zero is according to the standard.

ISO/IEC 9899:2011 §7.21.6.1 The fprintf function

¶6 The flag characters and their meanings are:
...
# The result is converted to an "alternative form". ... For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to it. ...

(Emphasis added.)


Note that using %#X will use upper-case letters for the hex digits and 0X as the prefix; using %#x will use lower-case letters for the hex digits and 0x as the prefix. If you prefer 0x as the prefix and upper-case letters, you have to code the 0x separately: 0x%X. Other format modifiers can be added as needed, of course.

For printing addresses, use the <inttypes.h> header and the uintptr_t type and the PRIXPTR format macro:

#include <inttypes.h>
#include <stdio.h>

int main(void)
{
    void *address = &address;  // &address has type void ** but it converts to void *
    printf("Address 0x%.12" PRIXPTR "\n", (uintptr_t)address);
    return 0;
}

Example output:

Address 0x7FFEE5B29428

Choose your poison on the length — I find that a precision of 12 works well for addresses on a Mac running macOS. Combined with the . to specify the minimum precision (digits), it formats addresses reliably. If you set the precision to 16, the extra 4 digits are always 0 in my experience on the Mac, but there's certainly a case to be made for using 16 instead of 12 in portable 64-bit code (but you'd use 8 for 32-bit code).

Barcode scanner for mobile phone for Website in form

You can use the Android app Barcode Scanner Terminal (DISCLAIMER! I'm the developer). It can scan the barcode and send it to the PC and in your case enter it on the web form. More details here.

How to validate numeric values which may contain dots or commas?

In order to represent a single digit in the form of a regular expression you can use either:

[0-9] or \d

In order to specify how many times the number appears you would add

[0-9]*: the star means there are zero or more digits

[0-9]{2}: {N} means N digits

[0-9]{0,2}: {N,M} N digits or M digits

[0-9]{0-9}: {N-M} N digits to M digits. Note: M can be left blank for an infinite representation

Lets say I want to represent a number between 1 and 99 I would express it as such:

[0-9]{1-2} or [0-9]{1,2} or \d{1-2} or \d{1,2}

Or lets say we were working with binary display, displaying a byte size, we would want our digits to be between 0 and 1 and length of a byte size, 8, so we would represent it as follows:

[0-1]{8} representation of a binary byte

Then if you want to add a , or a . symbol you would use:

\, or \. or you can use [.] or [,]

You can also state a selection between possible values as such

[.,] means either a dot or a comma symbol

And you just need to concatenate the pieces together, so in the case where you want to represent a 1 or 2 digit number followed by either a comma or a period and followed by two more digits you would express it as follows: >

[0-9]{1,2}[.,]\d{1-2}

Also note that regular expression strings inside C++ strings must be double-back-slashed so every \ becomes \\

Gather multiple sets of columns

It's not at all related to "tidyr" and "dplyr", but here's another option to consider: merged.stack from my "splitstackshape" package, V1.4.0 and above.

library(splitstackshape)
merged.stack(df, id.vars = c("id", "time"), 
             var.stubs = c("Q3.2.", "Q3.3."),
             sep = "var.stubs")
#     id       time .time_1       Q3.2.       Q3.3.
#  1:  1 2009-01-01      1. -0.62645381  1.35867955
#  2:  1 2009-01-01      2.  1.51178117 -0.16452360
#  3:  1 2009-01-01      3.  0.91897737  0.39810588
#  4:  2 2009-01-02      1.  0.18364332 -0.10278773
#  5:  2 2009-01-02      2.  0.38984324 -0.25336168
#  6:  2 2009-01-02      3.  0.78213630 -0.61202639
#  7:  3 2009-01-03      1. -0.83562861  0.38767161
# <<:::SNIP:::>>
# 24:  8 2009-01-08      3. -1.47075238 -1.04413463
# 25:  9 2009-01-09      1.  0.57578135  1.10002537
# 26:  9 2009-01-09      2.  0.82122120 -0.11234621
# 27:  9 2009-01-09      3. -0.47815006  0.56971963
# 28: 10 2009-01-10      1. -0.30538839  0.76317575
# 29: 10 2009-01-10      2.  0.59390132  0.88110773
# 30: 10 2009-01-10      3.  0.41794156 -0.13505460
#     id       time .time_1       Q3.2.       Q3.3.

How to handle change of checkbox using jQuery?

Hope, this would be of some help.

$('input[type=checkbox]').change(function () {
    if ($(this).prop("checked")) {
        //do the stuff that you would do when 'checked'

        return;
    }
    //Here do the stuff you want to do when 'unchecked'
});

Excel formula to reference 'CELL TO THE LEFT'

Even simpler:

=indirect(address(row(), column() - 1))

OFFSET returns a reference relative to the current reference, so if indirect returns the correct reference, you don't need it.

Bower: ENOGIT Git is not installed or not in the PATH

Run the following command at your node.js command prompt where "<git path>" is the path to your git bin folder:

set PATH=%PATH%;<git path>;

So, like this:

set PATH=%PATH%;C:\Program Files\Git\bin;

Or this: (Notice the (x86) )

set PATH=%PATH%;C:\Program Files (x86)\Git\bin;

This will add git to your path variables. Be sure you type it correctly or you could possibly delete your path vars which would be bad.

Javascript - object key->value

var o = { cat : "meow", dog : "woof"};
var x = Object.keys(o);

for (i=0; i<x.length; i++) {
  console.log(o[x[i]]);
}

IAB

How can I check if a URL exists via PHP?

Other way to check if a URL is valid or not can be:

<?php

  if (isValidURL("http://www.gimepix.com")) {
      echo "URL is valid...";
  } else {
      echo "URL is not valid...";
  }

  function isValidURL($url) {
      $file_headers = @get_headers($url);
      if (strpos($file_headers[0], "200 OK") > 0) {
         return true;
      } else {
        return false;
      }
  }
?>

The static keyword and its various uses in C++

Static Object: We can define class members static using static keyword. When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member.

A static member is shared by all objects of the class. All static data is initialized to zero when the first object is created, if no other initialization is present. We can't put it in the class definition but it can be initialized outside the class as done in the following example by redeclaring the static variable, using the scope resolution operator :: to identify which class it belongs to.

Let us try the following example to understand the concept of static data members:

#include <iostream>

using namespace std;

class Box
{
   public:
      static int objectCount;
      // Constructor definition
      Box(double l=2.0, double b=2.0, double h=2.0)
      {
         cout <<"Constructor called." << endl;
         length = l;
         breadth = b;
         height = h;
         // Increase every time object is created
         objectCount++;
      }
      double Volume()
      {
         return length * breadth * height;
      }
   private:
      double length;     // Length of a box
      double breadth;    // Breadth of a box
      double height;     // Height of a box
};

// Initialize static member of class Box
int Box::objectCount = 0;

int main(void)
{
   Box Box1(3.3, 1.2, 1.5);    // Declare box1
   Box Box2(8.5, 6.0, 2.0);    // Declare box2

   // Print total number of objects.
   cout << "Total objects: " << Box::objectCount << endl;

   return 0;
}

When the above code is compiled and executed, it produces the following result:

Constructor called.
Constructor called.
Total objects: 2

Static Function Members: By declaring a function member as static, you make it independent of any particular object of the class. A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator ::.

A static member function can only access static data member, other static member functions and any other functions from outside the class.

Static member functions have a class scope and they do not have access to the this pointer of the class. You could use a static member function to determine whether some objects of the class have been created or not.

Let us try the following example to understand the concept of static function members:

#include <iostream>

using namespace std;

class Box
{
   public:
      static int objectCount;
      // Constructor definition
      Box(double l=2.0, double b=2.0, double h=2.0)
      {
         cout <<"Constructor called." << endl;
         length = l;
         breadth = b;
         height = h;
         // Increase every time object is created
         objectCount++;
      }
      double Volume()
      {
         return length * breadth * height;
      }
      static int getCount()
      {
         return objectCount;
      }
   private:
      double length;     // Length of a box
      double breadth;    // Breadth of a box
      double height;     // Height of a box
};

// Initialize static member of class Box
int Box::objectCount = 0;

int main(void)
{

   // Print total number of objects before creating object.
   cout << "Inital Stage Count: " << Box::getCount() << endl;

   Box Box1(3.3, 1.2, 1.5);    // Declare box1
   Box Box2(8.5, 6.0, 2.0);    // Declare box2

   // Print total number of objects after creating object.
   cout << "Final Stage Count: " << Box::getCount() << endl;

   return 0;
}

When the above code is compiled and executed, it produces the following result:

Inital Stage Count: 0
Constructor called.
Constructor called.
Final Stage Count: 2

How to make type="number" to positive numbers only

_x000D_
_x000D_
<input type="number" min="1" step="1">
_x000D_
_x000D_
_x000D_

How to give a time delay of less than one second in excel vba?

I have try this and it works for me:

Private Sub DelayMs(ms As Long)
    Debug.Print TimeValue(Now)
    Application.Wait (Now + (ms * 0.00000001))
    Debug.Print TimeValue(Now)
End Sub

Private Sub test()
    Call DelayMs (2000)  'test code with delay of 2 seconds, see debug window
End Sub

WP -- Get posts by category?

Check here : http://codex.wordpress.org/Template_Tags/get_posts

Note: The category parameter needs to be the ID of the category, and not the category name.

RestSharp simple complete example

I managed to find a blog post on the subject, which links off to an open source project that implements RestSharp. Hopefully of some help to you.

http://dkdevelopment.net/2010/05/18/dropbox-api-and-restsharp-for-a-c-developer/ The blog post is a 2 parter, and the project is here: https://github.com/dkarzon/DropNet

It might help if you had a full example of what wasn't working. It's difficult to get context on how the client was set up if you don't provide the code.

How to know if a Fragment is Visible?

you can try this way:

Fragment currentFragment = getFragmentManager().findFragmentById(R.id.fragment_container);

or

Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container);

In this if, you check if currentFragment is instance of YourFragment

if (currentFragment instanceof YourFragment) {
     Log.v(TAG, "your Fragment is Visible");
}

Spring Boot application as a Service

The following works for springboot 1.3 and above:

As init.d service

The executable jar has the usual start, stop, restart, and status commands. It will also set up a PID file in the usual /var/run directory and logging in the usual /var/log directory by default.

You just need to symlink your jar into /etc/init.d like so

sudo link -s /var/myapp/myapp.jar /etc/init.d/myapp

OR

sudo ln -s ~/myproject/build/libs/myapp-1.0.jar /etc/init.d/myapp_servicename

After that you can do the usual

/etc/init.d/myapp start

Then setup a link in whichever runlevel you want the app to start/stop in on boot if so desired.


As a systemd service

To run a Spring Boot application installed in var/myapp you can add the following script in /etc/systemd/system/myapp.service:

[Unit]
Description=myapp
After=syslog.target

[Service]
ExecStart=/var/myapp/myapp.jar

[Install]
WantedBy=multi-user.target

NB: in case you are using this method, do not forget to make the jar file itself executable (with chmod +x) otherwise it will fail with error "Permission denied".

Reference

http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/html/deployment-install.html#deployment-service

Detect if device is iOS

It's probably worth answering that iPads running iOS 13 will have navigator.platform set to MacIntel, which means you'll need to find another way to detect iPadOS devices.

Rails 4 - passing variable to partial

Don't use locals in Rails 4.2+

In Rails 4.2 I had to remove the locals part and just use size: 30 instead. Otherwise, it wouldn't pass the local variable correctly.

For example, use this:

<%= render @users, size: 30 %>

Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null

i solved the problem i exlained...for example in the file we render the other component,other component name is same with me method of current component such as:

const Login = () => {

}

render(
  <Login/>
)

..for solve this we must change the method name

Error Code: 1062. Duplicate entry '1' for key 'PRIMARY'

I just encountered the same issue but here it seemed to come from the fact that I declared the ID-column to be UNsigned and that in combination with an ID-value of '0' (zero) caused the import to fail...

So by changing the value of every ID (PK-column) that I'd declared '0' and every corresponding FK to the new value, my issue was solved.

How to reload the current state?

Everything failed for me. Only thing that worked...is adding cache-view="false" into the view which I want to reload when going to it.

from this issue https://github.com/angular-ui/ui-router/issues/582

SQL - using alias in Group By

Beware of using aliases when grouping the results from a view in SQLite. You will get unexpected results if the alias name is the same as the column name of any underlying tables (to the views.)

How do I find an array item with TypeScript? (a modern, easier way)

You could just use underscore library.

Install it:

   npm install underscore --save
   npm install @types/underscore --save-dev

Import it

   import _ = require('underscore');

Use it

    var x = _.filter(
      [{ "id": 1 }, { "id": -2 }, { "id": 3 }],
      myObj => myObj.id < 0)
    );

Xml Parsing in C#

First add an Enrty and Category class:

public class Entry {     public string Id { get; set; }     public string Title { get; set; }     public string Updated { get; set; }     public string Summary { get; set; }     public string GPoint { get; set; }     public string GElev { get; set; }     public List<string> Categories { get; set; } }  public class Category {     public string Label { get; set; }     public string Term { get; set; } } 

Then use LINQ to XML

XDocument xDoc = XDocument.Load("path");          List<Entry> entries = (from x in xDoc.Descendants("entry")             select new Entry()             {                 Id = (string) x.Element("id"),                 Title = (string)x.Element("title"),                 Updated = (string)x.Element("updated"),                 Summary = (string)x.Element("summary"),                 GPoint = (string)x.Element("georss:point"),                 GElev = (string)x.Element("georss:elev"),                 Categories = (from c in x.Elements("category")                                   select new Category                                   {                                       Label = (string)c.Attribute("label"),                                       Term = (string)c.Attribute("term")                                   }).ToList();             }).ToList(); 

How can I convert an image into a Base64 string?

This code runs perfect in my project:

profile_image.buildDrawingCache();
Bitmap bmap = profile_image.getDrawingCache();
String encodedImageData = getEncoded64ImageStringFromBitmap(bmap);


public String getEncoded64ImageStringFromBitmap(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.JPEG, 70, stream);
    byte[] byteFormat = stream.toByteArray();

    // Get the Base64 string
    String imgString = Base64.encodeToString(byteFormat, Base64.NO_WRAP);

    return imgString;
}